AvatarService.java

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