PresenceParser.java

  1package eu.siacs.conversations.parser;
  2
  3import android.util.Log;
  4
  5import java.util.ArrayList;
  6import java.util.List;
  7
  8
  9import eu.siacs.conversations.Config;
 10import eu.siacs.conversations.crypto.PgpEngine;
 11import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 12import eu.siacs.conversations.entities.Account;
 13import eu.siacs.conversations.entities.Contact;
 14import eu.siacs.conversations.entities.Conversation;
 15import eu.siacs.conversations.entities.Message;
 16import eu.siacs.conversations.entities.MucOptions;
 17import eu.siacs.conversations.entities.Presence;
 18import eu.siacs.conversations.generator.IqGenerator;
 19import eu.siacs.conversations.generator.PresenceGenerator;
 20import eu.siacs.conversations.services.XmppConnectionService;
 21import eu.siacs.conversations.utils.XmppUri;
 22import eu.siacs.conversations.xml.Element;
 23import eu.siacs.conversations.xml.Namespace;
 24import eu.siacs.conversations.xmpp.InvalidJid;
 25import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
 26import eu.siacs.conversations.xmpp.pep.Avatar;
 27import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
 28import eu.siacs.conversations.xmpp.Jid;
 29
 30public class PresenceParser extends AbstractParser implements
 31		OnPresencePacketReceived {
 32
 33	public PresenceParser(XmppConnectionService service) {
 34		super(service);
 35	}
 36
 37	public void parseConferencePresence(PresencePacket packet, Account account) {
 38		final Conversation conversation = packet.getFrom() == null ? null : mXmppConnectionService.find(account, packet.getFrom().asBareJid());
 39		if (conversation != null) {
 40			final MucOptions mucOptions = conversation.getMucOptions();
 41			boolean before = mucOptions.online();
 42			int count = mucOptions.getUserCount();
 43			final List<MucOptions.User> tileUserBefore = mucOptions.getUsers(5);
 44			processConferencePresence(packet, conversation);
 45			final List<MucOptions.User> tileUserAfter = mucOptions.getUsers(5);
 46			if (!tileUserAfter.equals(tileUserBefore)) {
 47				mXmppConnectionService.getAvatarService().clear(mucOptions);
 48			}
 49			if (before != mucOptions.online() || (mucOptions.online() && count != mucOptions.getUserCount())) {
 50				mXmppConnectionService.updateConversationUi();
 51			} else if (mucOptions.online()) {
 52				mXmppConnectionService.updateMucRosterUi();
 53			}
 54		}
 55	}
 56
 57	private void processConferencePresence(PresencePacket packet, Conversation conversation) {
 58		MucOptions mucOptions = conversation.getMucOptions();
 59		final Jid jid = conversation.getAccount().getJid();
 60		final Jid from = packet.getFrom();
 61		if (!from.isBareJid()) {
 62			final String type = packet.getAttribute("type");
 63			final Element x = packet.findChild("x", Namespace.MUC_USER);
 64			Avatar avatar = Avatar.parsePresence(packet.findChild("x", "vcard-temp:x:update"));
 65			final List<String> codes = getStatusCodes(x);
 66			if (type == null) {
 67				if (x != null) {
 68					Element item = x.findChild("item");
 69					if (item != null && !from.isBareJid()) {
 70						mucOptions.setError(MucOptions.Error.NONE);
 71						MucOptions.User user = parseItem(conversation, item, from);
 72						if (codes.contains(MucOptions.STATUS_CODE_SELF_PRESENCE) || (codes.contains(MucOptions.STATUS_CODE_ROOM_CREATED) && jid.equals(InvalidJid.getNullForInvalid(item.getAttributeAsJid("jid"))))) {
 73							if (mucOptions.setOnline()) {
 74								mXmppConnectionService.getAvatarService().clear(mucOptions);
 75							}
 76							if (mucOptions.setSelf(user)) {
 77								Log.d(Config.LOGTAG,"role or affiliation changed");
 78								mXmppConnectionService.databaseBackend.updateConversation(conversation);
 79							}
 80
 81							mXmppConnectionService.persistSelfNick(user);
 82							invokeRenameListener(mucOptions, true);
 83						}
 84						boolean isNew = mucOptions.updateUser(user);
 85						final AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
 86						Contact contact = user.getContact();
 87						if (isNew
 88								&& user.getRealJid() != null
 89								&& mucOptions.isPrivateAndNonAnonymous()
 90								&& (contact == null || !contact.mutualPresenceSubscription())
 91								&& axolotlService.hasEmptyDeviceList(user.getRealJid())) {
 92							axolotlService.fetchDeviceIds(user.getRealJid());
 93						}
 94						if (codes.contains(MucOptions.STATUS_CODE_ROOM_CREATED) && mucOptions.autoPushConfiguration()) {
 95							Log.d(Config.LOGTAG,mucOptions.getAccount().getJid().asBareJid()
 96									+": room '"
 97									+mucOptions.getConversation().getJid().asBareJid()
 98									+"' created. pushing default configuration");
 99							mXmppConnectionService.pushConferenceConfiguration(mucOptions.getConversation(),
100									IqGenerator.defaultChannelConfiguration(),
101									null);
102						}
103						if (mXmppConnectionService.getPgpEngine() != null) {
104							Element signed = packet.findChild("x", "jabber:x:signed");
105							if (signed != null) {
106								Element status = packet.findChild("status");
107								String msg = status == null ? "" : status.getContent();
108								long keyId = mXmppConnectionService.getPgpEngine().fetchKeyId(mucOptions.getAccount(), msg, signed.getContent());
109								if (keyId != 0) {
110									user.setPgpKeyId(keyId);
111								}
112							}
113						}
114						if (avatar != null) {
115							avatar.owner = from;
116							if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
117								if (user.setAvatar(avatar)) {
118									mXmppConnectionService.getAvatarService().clear(user);
119								}
120								if (user.getRealJid() != null) {
121									Contact c = conversation.getAccount().getRoster().getContact(user.getRealJid());
122									if (c.setAvatar(avatar)) {
123										mXmppConnectionService.syncRoster(conversation.getAccount());
124										mXmppConnectionService.getAvatarService().clear(c);
125										mXmppConnectionService.updateRosterUi();
126									}
127								}
128							} else if (mXmppConnectionService.isDataSaverDisabled()) {
129								mXmppConnectionService.fetchAvatar(mucOptions.getAccount(), avatar);
130							}
131						}
132					}
133				}
134			} else if (type.equals("unavailable")) {
135				final boolean fullJidMatches = from.equals(mucOptions.getSelf().getFullJid());
136				if (x.hasChild("destroy") && fullJidMatches) {
137					Element destroy = x.findChild("destroy");
138					final Jid alternate = destroy == null ? null : InvalidJid.getNullForInvalid(destroy.getAttributeAsJid("jid"));
139					mucOptions.setError(MucOptions.Error.DESTROYED);
140					if (alternate != null) {
141						Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": muc destroyed. alternate location " + alternate);
142					}
143				} else if (codes.contains(MucOptions.STATUS_CODE_SHUTDOWN) && fullJidMatches) {
144					mucOptions.setError(MucOptions.Error.SHUTDOWN);
145				} else if (codes.contains(MucOptions.STATUS_CODE_SELF_PRESENCE)) {
146					if (codes.contains(MucOptions.STATUS_CODE_KICKED)) {
147						mucOptions.setError(MucOptions.Error.KICKED);
148					} else if (codes.contains(MucOptions.STATUS_CODE_BANNED)) {
149						mucOptions.setError(MucOptions.Error.BANNED);
150					} else if (codes.contains(MucOptions.STATUS_CODE_LOST_MEMBERSHIP)) {
151						mucOptions.setError(MucOptions.Error.MEMBERS_ONLY);
152					} else if (codes.contains(MucOptions.STATUS_CODE_AFFILIATION_CHANGE)) {
153						mucOptions.setError(MucOptions.Error.MEMBERS_ONLY);
154					} else if (codes.contains(MucOptions.STATUS_CODE_SHUTDOWN)) {
155						mucOptions.setError(MucOptions.Error.SHUTDOWN);
156					} else if (!codes.contains(MucOptions.STATUS_CODE_CHANGED_NICK)) {
157						mucOptions.setError(MucOptions.Error.UNKNOWN);
158						Log.d(Config.LOGTAG, "unknown error in conference: " + packet);
159					}
160				} else if (!from.isBareJid()){
161					Element item = x.findChild("item");
162					if (item != null) {
163						mucOptions.updateUser(parseItem(conversation, item, from));
164					}
165					MucOptions.User user = mucOptions.deleteUser(from);
166					if (user != null) {
167						mXmppConnectionService.getAvatarService().clear(user);
168					}
169				}
170			} else if (type.equals("error")) {
171				final Element error = packet.findChild("error");
172				if (error == null) {
173					return;
174				}
175				if (error.hasChild("conflict")) {
176					if (mucOptions.online()) {
177						invokeRenameListener(mucOptions, false);
178					} else {
179						mucOptions.setError(MucOptions.Error.NICK_IN_USE);
180					}
181				} else if (error.hasChild("not-authorized")) {
182					mucOptions.setError(MucOptions.Error.PASSWORD_REQUIRED);
183				} else if (error.hasChild("forbidden")) {
184					mucOptions.setError(MucOptions.Error.BANNED);
185				} else if (error.hasChild("registration-required")) {
186					mucOptions.setError(MucOptions.Error.MEMBERS_ONLY);
187				} else if (error.hasChild("resource-constraint")) {
188					mucOptions.setError(MucOptions.Error.RESOURCE_CONSTRAINT);
189				} else if (error.hasChild("remote-server-timeout")) {
190					mucOptions.setError(MucOptions.Error.REMOTE_SERVER_TIMEOUT);
191				} else if (error.hasChild("gone")) {
192					final String gone = error.findChildContent("gone");
193					final Jid alternate;
194					if (gone != null) {
195						final XmppUri xmppUri = new XmppUri(gone);
196						if (xmppUri.isValidJid()) {
197							alternate = xmppUri.getJid();
198						} else {
199							alternate = null;
200						}
201					} else {
202						alternate = null;
203					}
204					mucOptions.setError(MucOptions.Error.DESTROYED);
205					if (alternate != null) {
206						Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": muc destroyed. alternate location " + alternate);
207					}
208				} else {
209					final String text = error.findChildContent("text");
210					if (text != null && text.contains("attribute 'to'")) {
211						if (mucOptions.online()) {
212							invokeRenameListener(mucOptions, false);
213						} else {
214							mucOptions.setError(MucOptions.Error.INVALID_NICK);
215						}
216					} else {
217						mucOptions.setError(MucOptions.Error.UNKNOWN);
218						Log.d(Config.LOGTAG, "unknown error in conference: " + packet);
219					}
220				}
221			}
222		}
223	}
224
225	private static void invokeRenameListener(final MucOptions options, boolean success) {
226		if (options.onRenameListener != null) {
227			if (success) {
228				options.onRenameListener.onSuccess();
229			} else {
230				options.onRenameListener.onFailure();
231			}
232			options.onRenameListener = null;
233		}
234	}
235
236	private static List<String> getStatusCodes(Element x) {
237		List<String> codes = new ArrayList<>();
238		if (x != null) {
239			for (Element child : x.getChildren()) {
240				if (child.getName().equals("status")) {
241					String code = child.getAttribute("code");
242					if (code != null) {
243						codes.add(code);
244					}
245				}
246			}
247		}
248		return codes;
249	}
250
251	private void parseContactPresence(final PresencePacket packet, final Account account) {
252		final PresenceGenerator mPresenceGenerator = mXmppConnectionService.getPresenceGenerator();
253		final Jid from = packet.getFrom();
254		if (from == null || from.equals(account.getJid())) {
255			return;
256		}
257		final String type = packet.getAttribute("type");
258		final Contact contact = account.getRoster().getContact(from);
259		if (type == null) {
260			final String resource = from.isBareJid() ? "" : from.getResource();
261			Avatar avatar = Avatar.parsePresence(packet.findChild("x", "vcard-temp:x:update"));
262			if (avatar != null && (!contact.isSelf() || account.getAvatar() == null)) {
263				avatar.owner = from.asBareJid();
264				if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
265					if (avatar.owner.equals(account.getJid().asBareJid())) {
266						account.setAvatar(avatar.getFilename());
267						mXmppConnectionService.databaseBackend.updateAccount(account);
268						mXmppConnectionService.getAvatarService().clear(account);
269						mXmppConnectionService.updateConversationUi();
270						mXmppConnectionService.updateAccountUi();
271					} else if (contact.setAvatar(avatar)) {
272						mXmppConnectionService.syncRoster(account);
273						mXmppConnectionService.getAvatarService().clear(contact);
274						mXmppConnectionService.updateConversationUi();
275						mXmppConnectionService.updateRosterUi();
276					}
277				} else if (mXmppConnectionService.isDataSaverDisabled()){
278					mXmppConnectionService.fetchAvatar(account, avatar);
279				}
280			}
281
282			if (mXmppConnectionService.isMuc(account, from)) {
283				return;
284			}
285
286			int sizeBefore = contact.getPresences().size();
287
288			final String show = packet.findChildContent("show");
289			final Element caps = packet.findChild("c", "http://jabber.org/protocol/caps");
290			final String message = packet.findChildContent("status");
291			final Presence presence = Presence.parse(show, caps, message);
292			contact.updatePresence(resource, presence);
293			if (presence.hasCaps()) {
294				mXmppConnectionService.fetchCaps(account, from, presence);
295			}
296
297			final Element idle = packet.findChild("idle", Namespace.IDLE);
298			if (idle != null) {
299				try {
300					final String since = idle.getAttribute("since");
301					contact.setLastseen(AbstractParser.parseTimestamp(since));
302					contact.flagInactive();
303				} catch (Throwable throwable) {
304					if (contact.setLastseen(AbstractParser.parseTimestamp(packet))) {
305						contact.flagActive();
306					}
307				}
308			} else {
309				if (contact.setLastseen(AbstractParser.parseTimestamp(packet))) {
310					contact.flagActive();
311				}
312			}
313
314			PgpEngine pgp = mXmppConnectionService.getPgpEngine();
315			Element x = packet.findChild("x", "jabber:x:signed");
316			if (pgp != null && x != null) {
317				Element status = packet.findChild("status");
318				String msg = status != null ? status.getContent() : "";
319				if (contact.setPgpKeyId(pgp.fetchKeyId(account, msg, x.getContent()))) {
320					mXmppConnectionService.syncRoster(account);
321				}
322			}
323			boolean online = sizeBefore < contact.getPresences().size();
324			mXmppConnectionService.onContactStatusChanged.onContactStatusChanged(contact, online);
325		} else if (type.equals("unavailable")) {
326			if (contact.setLastseen(AbstractParser.parseTimestamp(packet,0L,true))) {
327				contact.flagInactive();
328			}
329			if (from.isBareJid()) {
330				contact.clearPresences();
331			} else {
332				contact.removePresence(from.getResource());
333			}
334			if (contact.getShownStatus() == Presence.Status.OFFLINE) {
335				contact.flagInactive();
336			}
337			mXmppConnectionService.onContactStatusChanged.onContactStatusChanged(contact, false);
338		} else if (type.equals("subscribe")) {
339			if (contact.setPresenceName(packet.findChildContent("nick", Namespace.NICK))) {
340				mXmppConnectionService.syncRoster(account);
341				mXmppConnectionService.getAvatarService().clear(contact);
342			}
343			if (contact.getOption(Contact.Options.PREEMPTIVE_GRANT)) {
344				mXmppConnectionService.sendPresencePacket(account,
345						mPresenceGenerator.sendPresenceUpdatesTo(contact));
346			} else {
347				contact.setOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
348				final Conversation conversation = mXmppConnectionService.findOrCreateConversation(
349						account, contact.getJid().asBareJid(), false, false);
350				final String statusMessage = packet.findChildContent("status");
351				if (statusMessage != null
352						&& !statusMessage.isEmpty()
353						&& conversation.countMessages() == 0) {
354					conversation.add(new Message(
355							conversation,
356							statusMessage,
357							Message.ENCRYPTION_NONE,
358							Message.STATUS_RECEIVED
359					));
360				}
361			}
362		}
363		mXmppConnectionService.updateRosterUi();
364	}
365
366	@Override
367	public void onPresencePacketReceived(Account account, PresencePacket packet) {
368		if (packet.hasChild("x", Namespace.MUC_USER)) {
369			this.parseConferencePresence(packet, account);
370		} else if (packet.hasChild("x", "http://jabber.org/protocol/muc")) {
371			this.parseConferencePresence(packet, account);
372		} else if ("error".equals(packet.getAttribute("type")) && mXmppConnectionService.isMuc(account, packet.getFrom())) {
373			this.parseConferencePresence(packet, account);
374		} else {
375			this.parseContactPresence(packet, account);
376		}
377	}
378}