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.getAvatarFilename() != null) {
73 avatar = mXmppConnectionService.getFileBackend().getAvatar(contact.getAvatarFilename(), 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.mipmap.new_launcher_round, 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.getAvatarFilename() != 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 MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.getJid().asBareJid());
169 if (user != null) {
170 clear(user);
171 }
172 clear(conversation);
173 }
174 }
175
176 private String key(Contact contact, int size) {
177 synchronized (this.sizes) {
178 if (!this.sizes.contains(size)) {
179 this.sizes.add(size);
180 }
181 }
182 return PREFIX_CONTACT +
183 '\0' +
184 contact.getAccount().getJid().asBareJid() +
185 '\0' +
186 emptyOnNull(contact.getJid()) +
187 '\0' +
188 size;
189 }
190
191 private String key(MucOptions.User user, int size) {
192 synchronized (this.sizes) {
193 if (!this.sizes.contains(size)) {
194 this.sizes.add(size);
195 }
196 }
197 return PREFIX_CONTACT +
198 '\0' +
199 user.getAccount().getJid().asBareJid() +
200 '\0' +
201 emptyOnNull(user.getFullJid()) +
202 '\0' +
203 emptyOnNull(user.getRealJid()) +
204 '\0' +
205 size;
206 }
207
208 public Bitmap get(ListItem item, int size) {
209 return get(item, size, false);
210 }
211
212 public Bitmap get(ListItem item, int size, boolean cachedOnly) {
213 if (item instanceof Contact) {
214 return get((Contact) item, size, cachedOnly);
215 } else if (item instanceof Bookmark) {
216 Bookmark bookmark = (Bookmark) item;
217 if (bookmark.getConversation() != null) {
218 return get(bookmark.getConversation(), size, cachedOnly);
219 } else {
220 Jid jid = bookmark.getJid();
221 Account account = bookmark.getAccount();
222 Contact contact = jid == null ? null : account.getRoster().getContact(jid);
223 if (contact != null && contact.getAvatarFilename() != null) {
224 return get(contact, size, cachedOnly);
225 }
226 String seed = jid != null ? jid.asBareJid().toString() : null;
227 return get(bookmark.getDisplayName(), seed, size, cachedOnly);
228 }
229 } else {
230 String seed = item.getJid() != null ? item.getJid().asBareJid().toString() : null;
231 return get(item.getDisplayName(), seed, size, cachedOnly);
232 }
233 }
234
235 public Bitmap get(Conversation conversation, int size) {
236 return get(conversation, size, false);
237 }
238
239 public Bitmap get(Conversation conversation, int size, boolean cachedOnly) {
240 if (conversation.getMode() == Conversation.MODE_SINGLE) {
241 return get(conversation.getContact(), size, cachedOnly);
242 } else {
243 return get(conversation.getMucOptions(), size, cachedOnly);
244 }
245 }
246
247 public void clear(Conversation conversation) {
248 if (conversation.getMode() == Conversation.MODE_SINGLE) {
249 clear(conversation.getContact());
250 } else {
251 clear(conversation.getMucOptions());
252 synchronized (this.conversationDependentKeys) {
253 Set<String> keys = this.conversationDependentKeys.get(conversation.getUuid());
254 if (keys == null) {
255 return;
256 }
257 LruCache<String, Bitmap> cache = this.mXmppConnectionService.getBitmapCache();
258 for (String key : keys) {
259 cache.remove(key);
260 }
261 keys.clear();
262 }
263 }
264 }
265
266 private Bitmap get(MucOptions mucOptions, int size, boolean cachedOnly) {
267 final String KEY = key(mucOptions, size);
268 Bitmap bitmap = this.mXmppConnectionService.getBitmapCache().get(KEY);
269 if (bitmap != null || cachedOnly) {
270 return bitmap;
271 }
272
273 bitmap = mXmppConnectionService.getFileBackend().getAvatar(mucOptions.getAvatar(), size);
274
275 if (bitmap == null) {
276 final List<MucOptions.User> users = mucOptions.getUsersRelevantForNameAndAvatar();
277 if (users.size() == 0) {
278 Conversation c = mucOptions.getConversation();
279 bitmap = getImpl(c.getName().toString(), c.getJid().asBareJid().toString(), size);
280 } else {
281 bitmap = getImpl(users, size);
282 }
283 }
284
285 this.mXmppConnectionService.getBitmapCache().put(KEY, bitmap);
286
287 return bitmap;
288 }
289
290 private Bitmap get(List<MucOptions.User> users, int size, boolean cachedOnly) {
291 final String KEY = key(users, size);
292 Bitmap bitmap = this.mXmppConnectionService.getBitmapCache().get(KEY);
293 if (bitmap != null || cachedOnly) {
294 return bitmap;
295 }
296 bitmap = getImpl(users, size);
297 this.mXmppConnectionService.getBitmapCache().put(KEY, bitmap);
298 return bitmap;
299 }
300
301 private Bitmap getImpl(List<MucOptions.User> users, int size) {
302 int count = users.size();
303 Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
304 Canvas canvas = new Canvas(bitmap);
305 bitmap.eraseColor(TRANSPARENT);
306 if (count == 0) {
307 throw new AssertionError("Unable to draw tiles for 0 users");
308 } else if (count == 1) {
309 drawTile(canvas, users.get(0), 0, 0, size / 2 - 1, size);
310 drawTile(canvas, users.get(0).getAccount(), size / 2 + 1, 0, size, size);
311 } else if (count == 2) {
312 drawTile(canvas, users.get(0), 0, 0, size / 2 - 1, size);
313 drawTile(canvas, users.get(1), size / 2 + 1, 0, size, size);
314 } else if (count == 3) {
315 drawTile(canvas, users.get(0), 0, 0, size / 2 - 1, size);
316 drawTile(canvas, users.get(1), size / 2 + 1, 0, size, size / 2 - 1);
317 drawTile(canvas, users.get(2), size / 2 + 1, size / 2 + 1, size,
318 size);
319 } else if (count == 4) {
320 drawTile(canvas, users.get(0), 0, 0, size / 2 - 1, size / 2 - 1);
321 drawTile(canvas, users.get(1), 0, size / 2 + 1, size / 2 - 1, size);
322 drawTile(canvas, users.get(2), size / 2 + 1, 0, size, size / 2 - 1);
323 drawTile(canvas, users.get(3), size / 2 + 1, size / 2 + 1, size,
324 size);
325 } else {
326 drawTile(canvas, users.get(0), 0, 0, size / 2 - 1, size / 2 - 1);
327 drawTile(canvas, users.get(1), 0, size / 2 + 1, size / 2 - 1, size);
328 drawTile(canvas, users.get(2), size / 2 + 1, 0, size, size / 2 - 1);
329 drawTile(canvas, "\u2026", PLACEHOLDER_COLOR, size / 2 + 1, size / 2 + 1,
330 size, size);
331 }
332 return bitmap;
333 }
334
335 public void clear(final MucOptions options) {
336 if (options == null) {
337 return;
338 }
339 synchronized (this.sizes) {
340 for (Integer size : sizes) {
341 this.mXmppConnectionService.getBitmapCache().remove(key(options, size));
342 }
343 }
344 }
345
346 private String key(final MucOptions options, int size) {
347 synchronized (this.sizes) {
348 if (!this.sizes.contains(size)) {
349 this.sizes.add(size);
350 }
351 }
352 return PREFIX_CONVERSATION + "_" + options.getConversation().getUuid()
353 + "_" + String.valueOf(size);
354 }
355
356 private String key(List<MucOptions.User> users, int size) {
357 final Conversation conversation = users.get(0).getConversation();
358 StringBuilder builder = new StringBuilder("TILE_");
359 builder.append(conversation.getUuid());
360
361 for (MucOptions.User user : users) {
362 builder.append("\0");
363 builder.append(emptyOnNull(user.getRealJid()));
364 builder.append("\0");
365 builder.append(emptyOnNull(user.getFullJid()));
366 }
367 builder.append('\0');
368 builder.append(size);
369 final String key = builder.toString();
370 synchronized (this.conversationDependentKeys) {
371 Set<String> keys;
372 if (this.conversationDependentKeys.containsKey(conversation.getUuid())) {
373 keys = this.conversationDependentKeys.get(conversation.getUuid());
374 } else {
375 keys = new HashSet<>();
376 this.conversationDependentKeys.put(conversation.getUuid(), keys);
377 }
378 keys.add(key);
379 }
380 return key;
381 }
382
383 public Bitmap get(Account account, int size) {
384 return get(account, size, false);
385 }
386
387 public Bitmap get(Account account, int size, boolean cachedOnly) {
388 final String KEY = key(account, size);
389 Bitmap avatar = mXmppConnectionService.getBitmapCache().get(KEY);
390 if (avatar != null || cachedOnly) {
391 return avatar;
392 }
393 avatar = mXmppConnectionService.getFileBackend().getAvatar(account.getAvatar(), size);
394 if (avatar == null) {
395 avatar = get(account.getJid().asBareJid().toString(), null, size, false);
396 }
397 mXmppConnectionService.getBitmapCache().put(KEY, avatar);
398 return avatar;
399 }
400
401 public Bitmap get(Message message, int size, boolean cachedOnly) {
402 final Conversational conversation = message.getConversation();
403 if (message.getType() == Message.TYPE_STATUS && message.getCounterparts() != null && message.getCounterparts().size() > 1) {
404 return get(message.getCounterparts(), size, cachedOnly);
405 } else if (message.getStatus() == Message.STATUS_RECEIVED) {
406 Contact c = message.getContact();
407 if (c != null && (c.getProfilePhoto() != null || c.getAvatarFilename() != null)) {
408 return get(c, size, cachedOnly);
409 } else if (conversation instanceof Conversation && message.getConversation().getMode() == Conversation.MODE_MULTI) {
410 final Jid trueCounterpart = message.getTrueCounterpart();
411 final MucOptions mucOptions = ((Conversation) conversation).getMucOptions();
412 MucOptions.User user;
413 if (trueCounterpart != null) {
414 user = mucOptions.findOrCreateUserByRealJid(trueCounterpart, message.getCounterpart());
415 } else {
416 user = mucOptions.findUserByFullJid(message.getCounterpart());
417 }
418 if (user != null) {
419 return getImpl(user, size, cachedOnly);
420 }
421 } else if (c != null) {
422 return get(c, size, cachedOnly);
423 }
424 Jid tcp = message.getTrueCounterpart();
425 String seed = tcp != null ? tcp.asBareJid().toString() : null;
426 return get(UIHelper.getMessageDisplayName(message), seed, size, cachedOnly);
427 } else {
428 return get(conversation.getAccount(), size, cachedOnly);
429 }
430 }
431
432 public void clear(Account account) {
433 synchronized (this.sizes) {
434 for (Integer size : sizes) {
435 this.mXmppConnectionService.getBitmapCache().remove(key(account, size));
436 }
437 }
438 }
439
440 public void clear(MucOptions.User user) {
441 synchronized (this.sizes) {
442 for (Integer size : sizes) {
443 this.mXmppConnectionService.getBitmapCache().remove(key(user, size));
444 }
445 }
446 }
447
448 private String key(Account account, int size) {
449 synchronized (this.sizes) {
450 if (!this.sizes.contains(size)) {
451 this.sizes.add(size);
452 }
453 }
454 return PREFIX_ACCOUNT + "_" + account.getUuid() + "_"
455 + String.valueOf(size);
456 }
457
458 /*public Bitmap get(String name, int size) {
459 return get(name,null, size,false);
460 }*/
461
462 public Bitmap get(final String name, String seed, final int size, boolean cachedOnly) {
463 final String KEY = key(seed == null ? name : seed, size);
464 Bitmap bitmap = mXmppConnectionService.getBitmapCache().get(KEY);
465 if (bitmap != null || cachedOnly) {
466 return bitmap;
467 }
468 bitmap = getImpl(name, seed, size);
469 mXmppConnectionService.getBitmapCache().put(KEY, bitmap);
470 return bitmap;
471 }
472
473 private Bitmap getImpl(final String name, final String seed, final int size) {
474 Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
475 Canvas canvas = new Canvas(bitmap);
476 final String trimmedName = name == null ? "" : name.trim();
477 drawTile(canvas, trimmedName, seed, 0, 0, size, size);
478 return bitmap;
479 }
480
481 private String key(String name, int size) {
482 synchronized (this.sizes) {
483 if (!this.sizes.contains(size)) {
484 this.sizes.add(size);
485 }
486 }
487 return PREFIX_GENERIC + "_" + name + "_" + String.valueOf(size);
488 }
489
490 private boolean drawTile(Canvas canvas, String letter, int tileColor, int left, int top, int right, int bottom) {
491 letter = letter.toUpperCase(Locale.getDefault());
492 Paint tilePaint = new Paint(), textPaint = new Paint();
493 tilePaint.setColor(tileColor);
494 textPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
495 textPaint.setColor(FG_COLOR);
496 textPaint.setTypeface(Typeface.create("sans-serif-light",
497 Typeface.NORMAL));
498 textPaint.setTextSize((float) ((right - left) * 0.8));
499 Rect rect = new Rect();
500
501 canvas.drawRect(new Rect(left, top, right, bottom), tilePaint);
502 textPaint.getTextBounds(letter, 0, 1, rect);
503 float width = textPaint.measureText(letter);
504 canvas.drawText(letter, (right + left) / 2 - width / 2, (top + bottom)
505 / 2 + rect.height() / 2, textPaint);
506 return true;
507 }
508
509 private boolean drawTile(Canvas canvas, MucOptions.User user, int left, int top, int right, int bottom) {
510 Contact contact = user.getContact();
511 if (contact != null) {
512 Uri uri = null;
513 if (contact.getProfilePhoto() != null) {
514 uri = Uri.parse(contact.getProfilePhoto());
515 } else if (contact.getAvatarFilename() != null) {
516 uri = mXmppConnectionService.getFileBackend().getAvatarUri(
517 contact.getAvatarFilename());
518 }
519 if (drawTile(canvas, uri, left, top, right, bottom)) {
520 return true;
521 }
522 } else if (user.getAvatar() != null) {
523 Uri uri = mXmppConnectionService.getFileBackend().getAvatarUri(user.getAvatar());
524 if (drawTile(canvas, uri, left, top, right, bottom)) {
525 return true;
526 }
527 }
528 if (contact != null) {
529 String seed = contact.getJid().asBareJid().toString();
530 drawTile(canvas, contact.getDisplayName(), seed, left, top, right, bottom);
531 } else {
532 String seed = user.getRealJid() == null ? null : user.getRealJid().asBareJid().toString();
533 drawTile(canvas, user.getName(), seed, left, top, right, bottom);
534 }
535 return true;
536 }
537
538 private boolean drawTile(Canvas canvas, Account account, int left, int top, int right, int bottom) {
539 String avatar = account.getAvatar();
540 if (avatar != null) {
541 Uri uri = mXmppConnectionService.getFileBackend().getAvatarUri(avatar);
542 if (uri != null) {
543 if (drawTile(canvas, uri, left, top, right, bottom)) {
544 return true;
545 }
546 }
547 }
548 String name = account.getJid().asBareJid().toString();
549 return drawTile(canvas, name, name, left, top, right, bottom);
550 }
551
552 private boolean drawTile(Canvas canvas, String name, String seed, int left, int top, int right, int bottom) {
553 if (name != null) {
554 final String letter = getFirstLetter(name);
555 final int color = UIHelper.getColorForName(seed == null ? name : seed);
556 drawTile(canvas, letter, color, left, top, right, bottom);
557 return true;
558 }
559 return false;
560 }
561
562 private static String getFirstLetter(String name) {
563 for (Character c : name.toCharArray()) {
564 if (Character.isLetterOrDigit(c)) {
565 return c.toString();
566 }
567 }
568 return "X";
569 }
570
571 private boolean drawTile(Canvas canvas, Uri uri, int left, int top, int right, int bottom) {
572 if (uri != null) {
573 Bitmap bitmap = mXmppConnectionService.getFileBackend()
574 .cropCenter(uri, bottom - top, right - left);
575 if (bitmap != null) {
576 drawTile(canvas, bitmap, left, top, right, bottom);
577 return true;
578 }
579 }
580 return false;
581 }
582
583 private boolean drawTile(Canvas canvas, Bitmap bm, int dstleft, int dsttop, int dstright, int dstbottom) {
584 Rect dst = new Rect(dstleft, dsttop, dstright, dstbottom);
585 canvas.drawBitmap(bm, null, dst, null);
586 return true;
587 }
588
589 @Override
590 public void onAdvancedStreamFeaturesAvailable(Account account) {
591 XmppConnection.Features features = account.getXmppConnection().getFeatures();
592 if (features.pep() && !features.pepPersistent()) {
593 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": has pep but is not persistent");
594 if (account.getAvatar() != null) {
595 mXmppConnectionService.republishAvatarIfNeeded(account);
596 }
597 }
598 }
599
600 private static String emptyOnNull(@Nullable Jid value) {
601 return value == null ? "" : value.toString();
602 }
603}