AbstractParser.java

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