1package eu.siacs.conversations.services;
2
3import android.content.res.Resources;
4import android.graphics.Bitmap;
5import android.graphics.BitmapFactory;
6import android.graphics.Canvas;
7import android.graphics.Paint;
8import android.graphics.PorterDuff;
9import android.graphics.PorterDuffXfermode;
10import android.graphics.Rect;
11import android.graphics.Typeface;
12import android.net.Uri;
13import android.support.annotation.Nullable;
14import android.util.DisplayMetrics;
15import android.util.Log;
16import android.util.LruCache;
17
18import java.util.ArrayList;
19import java.util.HashMap;
20import java.util.HashSet;
21import java.util.List;
22import java.util.Locale;
23import java.util.Set;
24
25import eu.siacs.conversations.Config;
26import eu.siacs.conversations.R;
27import eu.siacs.conversations.entities.Account;
28import eu.siacs.conversations.entities.Bookmark;
29import eu.siacs.conversations.entities.Contact;
30import eu.siacs.conversations.entities.Conversation;
31import eu.siacs.conversations.entities.ListItem;
32import eu.siacs.conversations.entities.Message;
33import eu.siacs.conversations.entities.MucOptions;
34import eu.siacs.conversations.utils.UIHelper;
35import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
36import eu.siacs.conversations.xmpp.XmppConnection;
37import rocks.xmpp.addr.Jid;
38
39public class AvatarService implements OnAdvancedStreamFeaturesLoaded {
40
41 private static final int FG_COLOR = 0xFFFAFAFA;
42 private static final int TRANSPARENT = 0x00000000;
43 private static final int PLACEHOLDER_COLOR = 0xFF202020;
44
45 private static final String PREFIX_CONTACT = "contact";
46 private static final String PREFIX_CONVERSATION = "conversation";
47 private static final String PREFIX_ACCOUNT = "account";
48 private static final String PREFIX_GENERIC = "generic";
49
50 final private ArrayList<Integer> sizes = new ArrayList<>();
51 final private HashMap<String, Set<String>> conversationDependentKeys = new HashMap<>();
52
53 protected XmppConnectionService mXmppConnectionService = null;
54
55 public AvatarService(XmppConnectionService service) {
56 this.mXmppConnectionService = service;
57 }
58
59 private Bitmap get(final Contact contact, final int size, boolean cachedOnly) {
60 if (contact.isSelf()) {
61 return get(contact.getAccount(), size, cachedOnly);
62 }
63 final String KEY = key(contact, size);
64 Bitmap avatar = this.mXmppConnectionService.getBitmapCache().get(KEY);
65 if (avatar != null || cachedOnly) {
66 return avatar;
67 }
68 if (contact.getProfilePhoto() != null) {
69 avatar = mXmppConnectionService.getFileBackend().cropCenterSquare(Uri.parse(contact.getProfilePhoto()), size);
70 }
71 if (avatar == null && contact.getAvatar() != null) {
72 avatar = mXmppConnectionService.getFileBackend().getAvatar(contact.getAvatar(), size);
73 }
74 if (avatar == null) {
75 avatar = get(contact.getDisplayName(), contact.getJid().asBareJid().toString(), size, cachedOnly);
76 }
77 this.mXmppConnectionService.getBitmapCache().put(KEY, avatar);
78 return avatar;
79 }
80
81 public Bitmap getRoundedShortcut(final Contact contact) {
82 return getRoundedShortcut(contact, false);
83 }
84
85 public Bitmap getRoundedShortcutWithIcon(final Contact contact) {
86 return getRoundedShortcut(contact, true);
87 }
88
89 private Bitmap getRoundedShortcut(final Contact contact, boolean withIcon) {
90 DisplayMetrics metrics = mXmppConnectionService.getResources().getDisplayMetrics();
91 int size = Math.round(metrics.density * 48);
92 Bitmap bitmap = get(contact, size);
93 Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
94 Canvas canvas = new Canvas(output);
95 final Paint paint = new Paint();
96
97 drawAvatar(bitmap, canvas, paint);
98 if (withIcon) {
99 drawIcon(canvas, paint);
100 }
101 return output;
102 }
103
104 private void drawAvatar(Bitmap bitmap, Canvas canvas, Paint paint) {
105 final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
106 paint.setAntiAlias(true);
107 canvas.drawARGB(0, 0, 0, 0);
108 canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);
109 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
110 canvas.drawBitmap(bitmap, rect, rect, paint);
111 }
112
113 private void drawIcon(Canvas canvas, Paint paint) {
114 BitmapFactory.Options opts = new BitmapFactory.Options();
115 opts.inSampleSize = 2;
116 Resources resources = mXmppConnectionService.getResources();
117 Bitmap icon = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher, opts);
118 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
119
120 int iconSize = Math.round(canvas.getHeight() / 2.6f);
121
122 int left = canvas.getWidth() - iconSize;
123 int top = canvas.getHeight() - iconSize;
124 final Rect rect = new Rect(left, top, left + iconSize, top + iconSize);
125 canvas.drawBitmap(icon, null, rect, paint);
126 }
127
128 public Bitmap get(final MucOptions.User user, final int size, boolean cachedOnly) {
129 Contact c = user.getContact();
130 if (c != null && (c.getProfilePhoto() != null || c.getAvatar() != null || user.getAvatar() == null)) {
131 return get(c, size, cachedOnly);
132 } else {
133 return getImpl(user, size, cachedOnly);
134 }
135 }
136
137 private Bitmap getImpl(final MucOptions.User user, final int size, boolean cachedOnly) {
138 final String KEY = key(user, size);
139 Bitmap avatar = this.mXmppConnectionService.getBitmapCache().get(KEY);
140 if (avatar != null || cachedOnly) {
141 return avatar;
142 }
143 if (user.getAvatar() != null) {
144 avatar = mXmppConnectionService.getFileBackend().getAvatar(user.getAvatar(), size);
145 }
146 if (avatar == null) {
147 Contact contact = user.getContact();
148 if (contact != null) {
149 avatar = get(contact, size, cachedOnly);
150 } else {
151 String seed = user.getRealJid() != null ? user.getRealJid().asBareJid().toString() : null;
152 avatar = get(user.getName(), seed, size, cachedOnly);
153 }
154 }
155 this.mXmppConnectionService.getBitmapCache().put(KEY, avatar);
156 return avatar;
157 }
158
159 public void clear(Contact contact) {
160 synchronized (this.sizes) {
161 for (Integer size : sizes) {
162 this.mXmppConnectionService.getBitmapCache().remove(
163 key(contact, size));
164 }
165 }
166 for (Conversation conversation : mXmppConnectionService.findAllConferencesWith(contact)) {
167 clear(conversation);
168 }
169 }
170
171 private String key(Contact contact, int size) {
172 synchronized (this.sizes) {
173 if (!this.sizes.contains(size)) {
174 this.sizes.add(size);
175 }
176 }
177 return PREFIX_CONTACT +
178 '\0' +
179 contact.getAccount().getJid().asBareJid() +
180 '\0' +
181 emptyOnNull(contact.getJid()) +
182 '\0' +
183 size;
184 }
185
186 private String key(MucOptions.User user, int size) {
187 synchronized (this.sizes) {
188 if (!this.sizes.contains(size)) {
189 this.sizes.add(size);
190 }
191 }
192 return PREFIX_CONTACT +
193 '\0' +
194 user.getAccount().getJid().asBareJid() +
195 '\0' +
196 emptyOnNull(user.getFullJid()) +
197 '\0' +
198 emptyOnNull(user.getRealJid()) +
199 '\0' +
200 size;
201 }
202
203 public Bitmap get(ListItem item, int size) {
204 return get(item, size, false);
205 }
206
207 public Bitmap get(ListItem item, int size, boolean cachedOnly) {
208 if (item instanceof Contact) {
209 return get((Contact) item, size, cachedOnly);
210 } else if (item instanceof Bookmark) {
211 Bookmark bookmark = (Bookmark) item;
212 if (bookmark.getConversation() != null) {
213 return get(bookmark.getConversation(), size, cachedOnly);
214 } else {
215 String seed = bookmark.getJid() != null ? bookmark.getJid().asBareJid().toString() : null;
216 return get(bookmark.getDisplayName(), seed, size, cachedOnly);
217 }
218 } else {
219 String seed = item.getJid() != null ? item.getJid().asBareJid().toString() : null;
220 return get(item.getDisplayName(), seed, size, cachedOnly);
221 }
222 }
223
224 public Bitmap get(Conversation conversation, int size) {
225 return get(conversation, size, false);
226 }
227
228 public Bitmap get(Conversation conversation, int size, boolean cachedOnly) {
229 if (conversation.getMode() == Conversation.MODE_SINGLE) {
230 return get(conversation.getContact(), size, cachedOnly);
231 } else {
232 return get(conversation.getMucOptions(), size, cachedOnly);
233 }
234 }
235
236 public void clear(Conversation conversation) {
237 if (conversation.getMode() == Conversation.MODE_SINGLE) {
238 clear(conversation.getContact());
239 } else {
240 clear(conversation.getMucOptions());
241 synchronized (this.conversationDependentKeys) {
242 Set<String> keys = this.conversationDependentKeys.get(conversation.getUuid());
243 if (keys == null) {
244 return;
245 }
246 LruCache<String, Bitmap> cache = this.mXmppConnectionService.getBitmapCache();
247 for (String key : keys) {
248 cache.remove(key);
249 }
250 keys.clear();
251 }
252 }
253 }
254
255 private Bitmap get(MucOptions mucOptions, int size, boolean cachedOnly) {
256 final String KEY = key(mucOptions, size);
257 Bitmap bitmap = this.mXmppConnectionService.getBitmapCache().get(KEY);
258 if (bitmap != null || cachedOnly) {
259 return bitmap;
260 }
261 final List<MucOptions.User> users = mucOptions.getUsersRelevantForNameAndAvatar();
262 if (users.size() == 0) {
263 Conversation c = mucOptions.getConversation();
264 bitmap = getImpl(c.getName().toString(), c.getJid().asBareJid().toString(), size);
265 } else {
266 bitmap = getImpl(users, size);
267 }
268 this.mXmppConnectionService.getBitmapCache().put(KEY, bitmap);
269 return bitmap;
270 }
271
272 private Bitmap get(List<MucOptions.User> users, int size, boolean cachedOnly) {
273 final String KEY = key(users, size);
274 Bitmap bitmap = this.mXmppConnectionService.getBitmapCache().get(KEY);
275 if (bitmap != null || cachedOnly) {
276 return bitmap;
277 }
278 bitmap = getImpl(users, size);
279 this.mXmppConnectionService.getBitmapCache().put(KEY, bitmap);
280 return bitmap;
281 }
282
283 private Bitmap getImpl(List<MucOptions.User> users, int size) {
284 int count = users.size();
285 Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
286 Canvas canvas = new Canvas(bitmap);
287 bitmap.eraseColor(TRANSPARENT);
288 if (count == 0) {
289 throw new AssertionError("Unable to draw tiles for 0 users");
290 } else if (count == 1) {
291 drawTile(canvas, users.get(0), 0, 0, size / 2 - 1, size);
292 drawTile(canvas, users.get(0).getAccount(), size / 2 + 1, 0, size, size);
293 } else if (count == 2) {
294 drawTile(canvas, users.get(0), 0, 0, size / 2 - 1, size);
295 drawTile(canvas, users.get(1), size / 2 + 1, 0, size, size);
296 } else if (count == 3) {
297 drawTile(canvas, users.get(0), 0, 0, size / 2 - 1, size);
298 drawTile(canvas, users.get(1), size / 2 + 1, 0, size, size / 2 - 1);
299 drawTile(canvas, users.get(2), size / 2 + 1, size / 2 + 1, size,
300 size);
301 } else if (count == 4) {
302 drawTile(canvas, users.get(0), 0, 0, size / 2 - 1, size / 2 - 1);
303 drawTile(canvas, users.get(1), 0, size / 2 + 1, size / 2 - 1, size);
304 drawTile(canvas, users.get(2), size / 2 + 1, 0, size, size / 2 - 1);
305 drawTile(canvas, users.get(3), size / 2 + 1, size / 2 + 1, size,
306 size);
307 } else {
308 drawTile(canvas, users.get(0), 0, 0, size / 2 - 1, size / 2 - 1);
309 drawTile(canvas, users.get(1), 0, size / 2 + 1, size / 2 - 1, size);
310 drawTile(canvas, users.get(2), size / 2 + 1, 0, size, size / 2 - 1);
311 drawTile(canvas, "\u2026", PLACEHOLDER_COLOR, size / 2 + 1, size / 2 + 1,
312 size, size);
313 }
314 return bitmap;
315 }
316
317 public void clear(MucOptions options) {
318 synchronized (this.sizes) {
319 for (Integer size : sizes) {
320 this.mXmppConnectionService.getBitmapCache().remove(key(options, size));
321 }
322 }
323 }
324
325 private String key(MucOptions options, int size) {
326 synchronized (this.sizes) {
327 if (!this.sizes.contains(size)) {
328 this.sizes.add(size);
329 }
330 }
331 return PREFIX_CONVERSATION + "_" + options.getConversation().getUuid()
332 + "_" + String.valueOf(size);
333 }
334
335 private String key(List<MucOptions.User> users, int size) {
336 final Conversation conversation = users.get(0).getConversation();
337 StringBuilder builder = new StringBuilder("TILE_");
338 builder.append(conversation.getUuid());
339
340 for (MucOptions.User user : users) {
341 builder.append("\0");
342 builder.append(emptyOnNull(user.getRealJid()));
343 builder.append("\0");
344 builder.append(emptyOnNull(user.getFullJid()));
345 }
346 builder.append('\0');
347 builder.append(size);
348 final String key = builder.toString();
349 synchronized (this.conversationDependentKeys) {
350 Set<String> keys;
351 if (this.conversationDependentKeys.containsKey(conversation.getUuid())) {
352 keys = this.conversationDependentKeys.get(conversation.getUuid());
353 } else {
354 keys = new HashSet<>();
355 this.conversationDependentKeys.put(conversation.getUuid(), keys);
356 }
357 keys.add(key);
358 }
359 return key;
360 }
361
362 public Bitmap get(Account account, int size) {
363 return get(account, size, false);
364 }
365
366 public Bitmap get(Account account, int size, boolean cachedOnly) {
367 final String KEY = key(account, size);
368 Bitmap avatar = mXmppConnectionService.getBitmapCache().get(KEY);
369 if (avatar != null || cachedOnly) {
370 return avatar;
371 }
372 avatar = mXmppConnectionService.getFileBackend().getAvatar(account.getAvatar(), size);
373 if (avatar == null) {
374 avatar = get(account.getJid().asBareJid().toString(), null, size, false);
375 }
376 mXmppConnectionService.getBitmapCache().put(KEY, avatar);
377 return avatar;
378 }
379
380 public Bitmap get(Message message, int size, boolean cachedOnly) {
381 final Conversation conversation = message.getConversation();
382 if (message.getType() == Message.TYPE_STATUS && message.getCounterparts() != null && message.getCounterparts().size() > 1) {
383 return get(message.getCounterparts(), size, cachedOnly);
384 } else if (message.getStatus() == Message.STATUS_RECEIVED) {
385 Contact c = message.getContact();
386 if (c != null && (c.getProfilePhoto() != null || c.getAvatar() != null)) {
387 return get(c, size, cachedOnly);
388 } else if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
389 final Jid trueCounterpart = message.getTrueCounterpart();
390 MucOptions.User user;
391 if (trueCounterpart != null) {
392 user = conversation.getMucOptions().findUserByRealJid(trueCounterpart);
393 } else {
394 user = conversation.getMucOptions().findUserByFullJid(message.getCounterpart());
395 }
396 if (user != null) {
397 return getImpl(user, size, cachedOnly);
398 }
399 } else if (c != null) {
400 return get(c, size, cachedOnly);
401 }
402 Jid tcp = message.getTrueCounterpart();
403 String seed = tcp != null ? tcp.asBareJid().toString() : null;
404 return get(UIHelper.getMessageDisplayName(message), seed, size, cachedOnly);
405 } else {
406 return get(conversation.getAccount(), size, cachedOnly);
407 }
408 }
409
410 public void clear(Account account) {
411 synchronized (this.sizes) {
412 for (Integer size : sizes) {
413 this.mXmppConnectionService.getBitmapCache().remove(key(account, size));
414 }
415 }
416 }
417
418 public void clear(MucOptions.User user) {
419 synchronized (this.sizes) {
420 for (Integer size : sizes) {
421 this.mXmppConnectionService.getBitmapCache().remove(key(user, size));
422 }
423 }
424 }
425
426 private String key(Account account, int size) {
427 synchronized (this.sizes) {
428 if (!this.sizes.contains(size)) {
429 this.sizes.add(size);
430 }
431 }
432 return PREFIX_ACCOUNT + "_" + account.getUuid() + "_"
433 + String.valueOf(size);
434 }
435
436 /*public Bitmap get(String name, int size) {
437 return get(name,null, size,false);
438 }*/
439
440 public Bitmap get(final String name, String seed, final int size, boolean cachedOnly) {
441 final String KEY = key(seed == null ? name : seed, size);
442 Bitmap bitmap = mXmppConnectionService.getBitmapCache().get(KEY);
443 if (bitmap != null || cachedOnly) {
444 return bitmap;
445 }
446 bitmap = getImpl(name, seed, size);
447 mXmppConnectionService.getBitmapCache().put(KEY, bitmap);
448 return bitmap;
449 }
450
451 private Bitmap getImpl(final String name, final String seed, final int size) {
452 Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
453 Canvas canvas = new Canvas(bitmap);
454 final String trimmedName = name == null ? "" : name.trim();
455 drawTile(canvas, trimmedName, seed, 0, 0, size, size);
456 return bitmap;
457 }
458
459 private String key(String name, int size) {
460 synchronized (this.sizes) {
461 if (!this.sizes.contains(size)) {
462 this.sizes.add(size);
463 }
464 }
465 return PREFIX_GENERIC + "_" + name + "_" + String.valueOf(size);
466 }
467
468 private boolean drawTile(Canvas canvas, String letter, int tileColor, int left, int top, int right, int bottom) {
469 letter = letter.toUpperCase(Locale.getDefault());
470 Paint tilePaint = new Paint(), textPaint = new Paint();
471 tilePaint.setColor(tileColor);
472 textPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
473 textPaint.setColor(FG_COLOR);
474 textPaint.setTypeface(Typeface.create("sans-serif-light",
475 Typeface.NORMAL));
476 textPaint.setTextSize((float) ((right - left) * 0.8));
477 Rect rect = new Rect();
478
479 canvas.drawRect(new Rect(left, top, right, bottom), tilePaint);
480 textPaint.getTextBounds(letter, 0, 1, rect);
481 float width = textPaint.measureText(letter);
482 canvas.drawText(letter, (right + left) / 2 - width / 2, (top + bottom)
483 / 2 + rect.height() / 2, textPaint);
484 return true;
485 }
486
487 private boolean drawTile(Canvas canvas, MucOptions.User user, int left, int top, int right, int bottom) {
488 Contact contact = user.getContact();
489 if (contact != null) {
490 Uri uri = null;
491 if (contact.getProfilePhoto() != null) {
492 uri = Uri.parse(contact.getProfilePhoto());
493 } else if (contact.getAvatar() != null) {
494 uri = mXmppConnectionService.getFileBackend().getAvatarUri(
495 contact.getAvatar());
496 }
497 if (drawTile(canvas, uri, left, top, right, bottom)) {
498 return true;
499 }
500 } else if (user.getAvatar() != null) {
501 Uri uri = mXmppConnectionService.getFileBackend().getAvatarUri(user.getAvatar());
502 if (drawTile(canvas, uri, left, top, right, bottom)) {
503 return true;
504 }
505 }
506 if (contact != null) {
507 String seed = contact.getJid().asBareJid().toString();
508 drawTile(canvas, contact.getDisplayName(), seed, left, top, right, bottom);
509 } else {
510 String seed = user.getRealJid() == null ? null : user.getRealJid().asBareJid().toString();
511 drawTile(canvas, user.getName(), seed, left, top, right, bottom);
512 }
513 return true;
514 }
515
516 private boolean drawTile(Canvas canvas, Account account, int left, int top, int right, int bottom) {
517 String avatar = account.getAvatar();
518 if (avatar != null) {
519 Uri uri = mXmppConnectionService.getFileBackend().getAvatarUri(avatar);
520 if (uri != null) {
521 if (drawTile(canvas, uri, left, top, right, bottom)) {
522 return true;
523 }
524 }
525 }
526 String name = account.getJid().asBareJid().toString();
527 return drawTile(canvas, name, name, left, top, right, bottom);
528 }
529
530 private boolean drawTile(Canvas canvas, String name, String seed, int left, int top, int right, int bottom) {
531 if (name != null) {
532 final String letter = getFirstLetter(name);
533 final int color = UIHelper.getColorForName(seed == null ? name : seed);
534 drawTile(canvas, letter, color, left, top, right, bottom);
535 return true;
536 }
537 return false;
538 }
539
540 private static String getFirstLetter(String name) {
541 for (Character c : name.toCharArray()) {
542 if (Character.isLetterOrDigit(c)) {
543 return c.toString();
544 }
545 }
546 return "X";
547 }
548
549 private boolean drawTile(Canvas canvas, Uri uri, int left, int top, int right, int bottom) {
550 if (uri != null) {
551 Bitmap bitmap = mXmppConnectionService.getFileBackend()
552 .cropCenter(uri, bottom - top, right - left);
553 if (bitmap != null) {
554 drawTile(canvas, bitmap, left, top, right, bottom);
555 return true;
556 }
557 }
558 return false;
559 }
560
561 private boolean drawTile(Canvas canvas, Bitmap bm, int dstleft, int dsttop, int dstright, int dstbottom) {
562 Rect dst = new Rect(dstleft, dsttop, dstright, dstbottom);
563 canvas.drawBitmap(bm, null, dst, null);
564 return true;
565 }
566
567 @Override
568 public void onAdvancedStreamFeaturesAvailable(Account account) {
569 XmppConnection.Features features = account.getXmppConnection().getFeatures();
570 if (features.pep() && !features.pepPersistent()) {
571 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": has pep but is not persistent");
572 if (account.getAvatar() != null) {
573 mXmppConnectionService.republishAvatarIfNeeded(account);
574 }
575 }
576 }
577
578 private static String emptyOnNull(@Nullable Jid value) {
579 return value == null ? "" : value.toString();
580 }
581}