AbstractParser.java

 1package eu.siacs.conversations.parser;
 2
 3
 4import java.text.ParseException;
 5import java.text.SimpleDateFormat;
 6import java.util.Date;
 7import java.util.Locale;
 8
 9import eu.siacs.conversations.entities.Account;
10import eu.siacs.conversations.entities.Contact;
11import eu.siacs.conversations.services.XmppConnectionService;
12import eu.siacs.conversations.xml.Element;
13import eu.siacs.conversations.xmpp.jid.Jid;
14
15public abstract class AbstractParser {
16
17	protected XmppConnectionService mXmppConnectionService;
18
19	protected AbstractParser(XmppConnectionService service) {
20		this.mXmppConnectionService = service;
21	}
22
23	public static Long getTimestamp(Element element, Long defaultValue) {
24		Element delay = element.findChild("delay","urn:xmpp:delay");
25		if (delay != null) {
26			String stamp = delay.getAttribute("stamp");
27			if (stamp != null) {
28				try {
29					return AbstractParser.parseTimestamp(delay.getAttribute("stamp")).getTime();
30				} catch (ParseException e) {
31					return defaultValue;
32				}
33			}
34		}
35		return defaultValue;
36	}
37
38	protected long getTimestamp(Element packet) {
39		return getTimestamp(packet,System.currentTimeMillis());
40	}
41
42	public static Date parseTimestamp(String timestamp) throws ParseException {
43		timestamp = timestamp.replace("Z", "+0000");
44		SimpleDateFormat dateFormat;
45		timestamp = timestamp.substring(0,19)+timestamp.substring(timestamp.length() -5,timestamp.length());
46		dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ",Locale.US);
47		return dateFormat.parse(timestamp);
48	}
49
50	protected void updateLastseen(final Element packet, final Account account, final boolean presenceOverwrite) {
51		updateLastseen(packet, account, packet.getAttributeAsJid("from"), presenceOverwrite);
52	}
53
54	protected void updateLastseen(final Element packet, final Account account, final Jid from, final boolean presenceOverwrite) {
55		final String presence = from == null || from.isBareJid() ? "" : from.getResourcepart();
56		final Contact contact = account.getRoster().getContact(from);
57		final long timestamp = getTimestamp(packet);
58		if (timestamp >= contact.lastseen.time) {
59			contact.lastseen.time = timestamp;
60			if (!presence.isEmpty() && presenceOverwrite) {
61				contact.lastseen.presence = presence;
62			}
63		}
64	}
65
66	protected String avatarData(Element items) {
67		Element item = items.findChild("item");
68		if (item == null) {
69			return null;
70		}
71		return item.findChildContent("data", "urn:xmpp:avatar:data");
72	}
73}