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