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