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