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	protected long getTimestamp(Element packet) {
24		long now = System.currentTimeMillis();
25		Element delay = packet.findChild("delay");
26		if (delay == null) {
27			return now;
28		}
29		String stamp = delay.getAttribute("stamp");
30		if (stamp == null) {
31			return now;
32		}
33		try {
34			long time = parseTimestamp(stamp).getTime();
35			return now < time ? now : time;
36		} catch (ParseException e) {
37			return now;
38		}
39	}
40
41	public static Date parseTimestamp(String timestamp) throws ParseException {
42		timestamp = timestamp.replace("Z", "+0000");
43		SimpleDateFormat dateFormat;
44		timestamp = timestamp.substring(0,19)+timestamp.substring(timestamp.length() -5,timestamp.length());
45		dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ",Locale.US);
46		return dateFormat.parse(timestamp);
47	}
48
49	protected void updateLastseen(final Element packet, final Account account,
50			final boolean presenceOverwrite) {
51		final Jid from = packet.getAttributeAsJid("from");
52		updateLastseen(packet, account, from, presenceOverwrite);
53	}
54
55	protected void updateLastseen(final Element packet, final Account account, final Jid from,
56								  final boolean presenceOverwrite) {
57		final String presence = from == null || from.isBareJid() ? "" : from.getResourcepart();
58		final Contact contact = account.getRoster().getContact(from);
59		final 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}