AbstractParser.java

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