package de.thedevstack.conversationsplus.xmpp.avatar; import de.thedevstack.conversationsplus.xmpp.pep.Avatar; import de.thedevstack.conversationsplus.xmpp.pubsub.PubSubPacketParser; import de.thedevstack.conversationsplus.xml.Element; import de.thedevstack.conversationsplus.xmpp.stanzas.IqPacket; /** * Parses the IQ Packets for handling Avatars * as defined in XEP-0084. * @see {@link http://xmpp.org/extensions/xep-0084.html} */ public class AvatarPacketParser { /** * Extracts the base64 encoded avatar data from an IqPacket. * @param packet the IqPacket to be parsed. * @return base64 encoded avatar data */ public static String parseAvatarData(IqPacket packet) { Element items = PubSubPacketParser.findItems(packet); String base64Avatar = null; if (null != items) { Element item = items.findChild("item"); if (null != item) { base64Avatar = item.findChildContent("data", AvatarPacketGenerator.NAMESPACE_AVATAR_DATA); } } return base64Avatar; } public static Avatar parseMetadata(Element items) { if (null != items) { Element item = items.findChild("item"); if (item == null) { return null; } Element metadata = item.findChild("metadata"); if (metadata == null) { return null; } String primaryId = item.getAttribute("id"); if (primaryId == null) { return null; } for (Element child : metadata.getChildren()) { if (child.getName().equals("info") && primaryId.equals(child.getAttribute("id"))) { Avatar avatar = new Avatar(); String height = child.getAttribute("height"); String width = child.getAttribute("width"); String size = child.getAttribute("bytes"); try { if (height != null) { avatar.height = Integer.parseInt(height); } if (width != null) { avatar.width = Integer.parseInt(width); } if (size != null) { avatar.size = Long.parseLong(size); } } catch (NumberFormatException e) { return null; } avatar.type = child.getAttribute("type"); String hash = child.getAttribute("id"); if (!Avatar.isValidSHA1(hash)) { return null; } avatar.sha1sum = hash; avatar.origin = Avatar.Origin.PEP; return avatar; } } } return null; } public static Avatar parseMetadata(IqPacket packet) { return parseMetadata(PubSubPacketParser.findItems(packet)); } }