AvatarService.java

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