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									final Contact c = conversation.getAccount().getRoster().getContact(user.getRealJid());
122									c.setAvatar(avatar);
123									mXmppConnectionService.syncRoster(conversation.getAccount());
124									mXmppConnectionService.getAvatarService().clear(c);
125									mXmppConnectionService.updateRosterUi();
126								}
127							} else if (mXmppConnectionService.isDataSaverDisabled()) {
128								mXmppConnectionService.fetchAvatar(mucOptions.getAccount(), avatar);
129							}
130						}
131					}
132				}
133			} else if (type.equals("unavailable")) {
134				final boolean fullJidMatches = from.equals(mucOptions.getSelf().getFullJid());
135				if (x.hasChild("destroy") && fullJidMatches) {
136					Element destroy = x.findChild("destroy");
137					final Jid alternate = destroy == null ? null : InvalidJid.getNullForInvalid(destroy.getAttributeAsJid("jid"));
138					mucOptions.setError(MucOptions.Error.DESTROYED);
139					if (alternate != null) {
140						Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": muc destroyed. alternate location " + alternate);
141					}
142				} else if (codes.contains(MucOptions.STATUS_CODE_SHUTDOWN) && fullJidMatches) {
143					mucOptions.setError(MucOptions.Error.SHUTDOWN);
144				} else if (codes.contains(MucOptions.STATUS_CODE_SELF_PRESENCE)) {
145					if (codes.contains(MucOptions.STATUS_CODE_KICKED)) {
146						mucOptions.setError(MucOptions.Error.KICKED);
147					} else if (codes.contains(MucOptions.STATUS_CODE_BANNED)) {
148						mucOptions.setError(MucOptions.Error.BANNED);
149					} else if (codes.contains(MucOptions.STATUS_CODE_LOST_MEMBERSHIP)) {
150						mucOptions.setError(MucOptions.Error.MEMBERS_ONLY);
151					} else if (codes.contains(MucOptions.STATUS_CODE_AFFILIATION_CHANGE)) {
152						mucOptions.setError(MucOptions.Error.MEMBERS_ONLY);
153					} else if (codes.contains(MucOptions.STATUS_CODE_SHUTDOWN)) {
154						mucOptions.setError(MucOptions.Error.SHUTDOWN);
155					} else if (!codes.contains(MucOptions.STATUS_CODE_CHANGED_NICK)) {
156						mucOptions.setError(MucOptions.Error.UNKNOWN);
157						Log.d(Config.LOGTAG, "unknown error in conference: " + packet);
158					}
159				} else if (!from.isBareJid()){
160					Element item = x.findChild("item");
161					if (item != null) {
162						mucOptions.updateUser(parseItem(conversation, item, from));
163					}
164					MucOptions.User user = mucOptions.deleteUser(from);
165					if (user != null) {
166						mXmppConnectionService.getAvatarService().clear(user);
167					}
168				}
169			} else if (type.equals("error")) {
170				final Element error = packet.findChild("error");
171				if (error == null) {
172					return;
173				}
174				if (error.hasChild("conflict")) {
175					if (mucOptions.online()) {
176						invokeRenameListener(mucOptions, false);
177					} else {
178						mucOptions.setError(MucOptions.Error.NICK_IN_USE);
179					}
180				} else if (error.hasChild("not-authorized")) {
181					mucOptions.setError(MucOptions.Error.PASSWORD_REQUIRED);
182				} else if (error.hasChild("forbidden")) {
183					mucOptions.setError(MucOptions.Error.BANNED);
184				} else if (error.hasChild("registration-required")) {
185					mucOptions.setError(MucOptions.Error.MEMBERS_ONLY);
186				} else if (error.hasChild("resource-constraint")) {
187					mucOptions.setError(MucOptions.Error.RESOURCE_CONSTRAINT);
188				} else if (error.hasChild("remote-server-timeout")) {
189					mucOptions.setError(MucOptions.Error.REMOTE_SERVER_TIMEOUT);
190				} else if (error.hasChild("gone")) {
191					final String gone = error.findChildContent("gone");
192					final Jid alternate;
193					if (gone != null) {
194						final XmppUri xmppUri = new XmppUri(gone);
195						if (xmppUri.isValidJid()) {
196							alternate = xmppUri.getJid();
197						} else {
198							alternate = null;
199						}
200					} else {
201						alternate = null;
202					}
203					mucOptions.setError(MucOptions.Error.DESTROYED);
204					if (alternate != null) {
205						Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": muc destroyed. alternate location " + alternate);
206					}
207				} else {
208					final String text = error.findChildContent("text");
209					if (text != null && text.contains("attribute 'to'")) {
210						if (mucOptions.online()) {
211							invokeRenameListener(mucOptions, false);
212						} else {
213							mucOptions.setError(MucOptions.Error.INVALID_NICK);
214						}
215					} else {
216						mucOptions.setError(MucOptions.Error.UNKNOWN);
217						Log.d(Config.LOGTAG, "unknown error in conference: " + packet);
218					}
219				}
220			}
221		}
222	}
223
224	private static void invokeRenameListener(final MucOptions options, boolean success) {
225		if (options.onRenameListener != null) {
226			if (success) {
227				options.onRenameListener.onSuccess();
228			} else {
229				options.onRenameListener.onFailure();
230			}
231			options.onRenameListener = null;
232		}
233	}
234
235	private static List<String> getStatusCodes(Element x) {
236		List<String> codes = new ArrayList<>();
237		if (x != null) {
238			for (Element child : x.getChildren()) {
239				if (child.getName().equals("status")) {
240					String code = child.getAttribute("code");
241					if (code != null) {
242						codes.add(code);
243					}
244				}
245			}
246		}
247		return codes;
248	}
249
250	private void parseContactPresence(final PresencePacket packet, final Account account) {
251		final PresenceGenerator mPresenceGenerator = mXmppConnectionService.getPresenceGenerator();
252		final Jid from = packet.getFrom();
253		if (from == null || from.equals(account.getJid())) {
254			return;
255		}
256		final String type = packet.getAttribute("type");
257		final Contact contact = account.getRoster().getContact(from);
258		if (type == null) {
259			final String resource = from.isBareJid() ? "" : from.getResource();
260			Avatar avatar = Avatar.parsePresence(packet.findChild("x", "vcard-temp:x:update"));
261			if (avatar != null && (!contact.isSelf() || account.getAvatar() == null)) {
262				avatar.owner = from.asBareJid();
263				if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
264					if (avatar.owner.equals(account.getJid().asBareJid())) {
265						account.setAvatar(avatar.getFilename());
266						mXmppConnectionService.databaseBackend.updateAccount(account);
267						mXmppConnectionService.getAvatarService().clear(account);
268						mXmppConnectionService.updateConversationUi();
269						mXmppConnectionService.updateAccountUi();
270					} else {
271						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}