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;
57        try {
58            from = Jid.fromString(packet.getAttribute("from")).toBareJid();
59        } catch (final InvalidJidException e) {
60			return;
61        }
62        String presence = from == null || from.isBareJid() ? "" : from.getResourcepart();
63		Contact contact = account.getRoster().getContact(from);
64		long timestamp = getTimestamp(packet);
65		if (timestamp >= contact.lastseen.time) {
66			contact.lastseen.time = timestamp;
67			if (!presence.isEmpty() && presenceOverwrite) {
68				contact.lastseen.presence = presence;
69			}
70		}
71	}
72
73	protected String avatarData(Element items) {
74		Element item = items.findChild("item");
75		if (item == null) {
76			return null;
77		}
78		Element data = item.findChild("data", "urn:xmpp:avatar:data");
79		if (data == null) {
80			return null;
81		}
82		return data.getContent();
83	}
84}