Avatar.java

  1package eu.siacs.conversations.xmpp.pep;
  2
  3import android.util.Base64;
  4
  5import eu.siacs.conversations.xml.Element;
  6import eu.siacs.conversations.xmpp.Jid;
  7
  8public class Avatar {
  9
 10	public enum Origin { PEP, VCARD }
 11
 12    public String type;
 13	public String sha1sum;
 14	public String image;
 15	public int height;
 16	public int width;
 17	public long size;
 18	public Jid owner;
 19	public Origin origin = Origin.PEP; //default to maintain compat
 20
 21	public byte[] getImageAsBytes() {
 22		return Base64.decode(image, Base64.DEFAULT);
 23	}
 24
 25	public String getFilename() {
 26		return sha1sum;
 27	}
 28
 29	public static Avatar parseMetadata(Element items) {
 30		Element item = items.findChild("item");
 31		if (item == null) {
 32			return null;
 33		}
 34		Element metadata = item.findChild("metadata");
 35		if (metadata == null) {
 36			return null;
 37		}
 38		String primaryId = item.getAttribute("id");
 39		if (primaryId == null) {
 40			return null;
 41		}
 42		for (Element child : metadata.getChildren()) {
 43			if (child.getName().equals("info")
 44					&& primaryId.equals(child.getAttribute("id"))) {
 45				Avatar avatar = new Avatar();
 46				String height = child.getAttribute("height");
 47				String width = child.getAttribute("width");
 48				String size = child.getAttribute("bytes");
 49				try {
 50					if (height != null) {
 51						avatar.height = Integer.parseInt(height);
 52					}
 53					if (width != null) {
 54						avatar.width = Integer.parseInt(width);
 55					}
 56					if (size != null) {
 57						avatar.size = Long.parseLong(size);
 58					}
 59				} catch (NumberFormatException e) {
 60					return null;
 61				}
 62				avatar.type = child.getAttribute("type");
 63				String hash = child.getAttribute("id");
 64				if (!isValidSHA1(hash)) {
 65					return null;
 66				}
 67				avatar.sha1sum = hash;
 68				avatar.origin = Origin.PEP;
 69				return avatar;
 70			}
 71		}
 72		return null;
 73	}
 74
 75	@Override
 76	public boolean equals(Object object) {
 77		if (object != null && object instanceof Avatar) {
 78			Avatar other = (Avatar) object;
 79			return other.getFilename().equals(this.getFilename());
 80		} else {
 81			return false;
 82		}
 83	}
 84
 85	public static Avatar parsePresence(Element x) {
 86		String hash = x == null ? null : x.findChildContent("photo");
 87		if (hash == null) {
 88			return null;
 89		}
 90		if (!isValidSHA1(hash)) {
 91			return null;
 92		}
 93		Avatar avatar = new Avatar();
 94		avatar.sha1sum = hash;
 95		avatar.origin = Origin.VCARD;
 96		return avatar;
 97	}
 98
 99	private static boolean isValidSHA1(String s) {
100		return s != null && s.matches("[a-fA-F0-9]{40}");
101	}
102}