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