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		ArrayList<String> stamps = new ArrayList<>();
28		for (Element child : packet.getChildren()) {
29			if (child.getName().equals("delay")) {
30				stamps.add(child.getAttribute("stamp").replace("Z", "+0000"));
31			}
32		}
33		Collections.sort(stamps);
34		if (stamps.size() >= 1) {
35			try {
36				String stamp = stamps.get(stamps.size() - 1);
37				if (stamp.contains(".")) {
38					Date date = new SimpleDateFormat(
39							"yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US)
40							.parse(stamp);
41					if (now < date.getTime()) {
42						return now;
43					} else {
44						return date.getTime();
45					}
46				} else {
47					Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ",
48							Locale.US).parse(stamp);
49					if (now < date.getTime()) {
50						return now;
51					} else {
52						return date.getTime();
53					}
54				}
55			} catch (ParseException e) {
56				return now;
57			}
58		} else {
59			return now;
60		}
61	}
62
63	protected void updateLastseen(final Element packet, final Account account,
64			final boolean presenceOverwrite) {
65        Jid from;
66        try {
67            from = Jid.fromString(packet.getAttribute("from")).toBareJid();
68        } catch (final InvalidJidException e) {
69            // TODO: Handle this?
70            from = null;
71        }
72        String presence = from == null || from.getResourcepart().isEmpty() ? "" : from.getResourcepart();
73		Contact contact = account.getRoster().getContact(from);
74		long timestamp = getTimestamp(packet);
75		if (timestamp >= contact.lastseen.time) {
76			contact.lastseen.time = timestamp;
77			if (!presence.isEmpty() && presenceOverwrite) {
78				contact.lastseen.presence = presence;
79			}
80		}
81	}
82
83	protected String avatarData(Element items) {
84		Element item = items.findChild("item");
85		if (item == null) {
86			return null;
87		}
88		Element data = item.findChild("data", "urn:xmpp:avatar:data");
89		if (data == null) {
90			return null;
91		}
92		return data.getContent();
93	}
94}