MucOptions.java

  1package eu.siacs.conversations.entities;
  2
  3import android.annotation.SuppressLint;
  4
  5import java.util.ArrayList;
  6import java.util.HashSet;
  7import java.util.List;
  8import java.util.Set;
  9
 10import eu.siacs.conversations.Config;
 11import eu.siacs.conversations.R;
 12import eu.siacs.conversations.utils.JidHelper;
 13import eu.siacs.conversations.utils.UIHelper;
 14import eu.siacs.conversations.xml.Namespace;
 15import eu.siacs.conversations.xmpp.chatstate.ChatState;
 16import eu.siacs.conversations.xmpp.forms.Data;
 17import eu.siacs.conversations.xmpp.forms.Field;
 18import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 19import eu.siacs.conversations.xmpp.jid.Jid;
 20import eu.siacs.conversations.xmpp.pep.Avatar;
 21
 22@SuppressLint("DefaultLocale")
 23public class MucOptions {
 24
 25	private boolean mAutoPushConfiguration = true;
 26
 27	public Account getAccount() {
 28		return this.conversation.getAccount();
 29	}
 30
 31	public void setSelf(User user) {
 32		this.self = user;
 33	}
 34
 35	public void changeAffiliation(Jid jid, Affiliation affiliation) {
 36		User user = findUserByRealJid(jid);
 37		synchronized (users) {
 38			if (user != null && user.getRole() == Role.NONE) {
 39				users.remove(user);
 40				if (affiliation.ranks(Affiliation.MEMBER)) {
 41					user.affiliation = affiliation;
 42					users.add(user);
 43				}
 44			}
 45		}
 46	}
 47
 48	public void flagNoAutoPushConfiguration() {
 49		mAutoPushConfiguration = false;
 50	}
 51
 52	public boolean autoPushConfiguration() {
 53		return mAutoPushConfiguration;
 54	}
 55
 56	public boolean isSelf(Jid counterpart) {
 57		return counterpart.getResourcepart().equals(getActualNick());
 58	}
 59
 60	public void resetChatState() {
 61		synchronized (users) {
 62			for(User user : users) {
 63				user.chatState = Config.DEFAULT_CHATSTATE;
 64			}
 65		}
 66	}
 67
 68	public enum Affiliation {
 69		OWNER("owner", 4, R.string.owner),
 70		ADMIN("admin", 3, R.string.admin),
 71		MEMBER("member", 2, R.string.member),
 72		OUTCAST("outcast", 0, R.string.outcast),
 73		NONE("none", 1, R.string.no_affiliation);
 74
 75		Affiliation(String string, int rank, int resId) {
 76			this.string = string;
 77			this.resId = resId;
 78			this.rank = rank;
 79		}
 80
 81		private String string;
 82		private int resId;
 83		private int rank;
 84
 85		public int getResId() {
 86			return resId;
 87		}
 88
 89		@Override
 90		public String toString() {
 91			return this.string;
 92		}
 93
 94		public boolean outranks(Affiliation affiliation) {
 95			return rank > affiliation.rank;
 96		}
 97
 98		public boolean ranks(Affiliation affiliation) {
 99			return rank >= affiliation.rank;
100		}
101	}
102
103	public enum Role {
104		MODERATOR("moderator", R.string.moderator,3),
105		VISITOR("visitor", R.string.visitor,1),
106		PARTICIPANT("participant", R.string.participant,2),
107		NONE("none", R.string.no_role,0);
108
109		Role(String string, int resId, int rank) {
110			this.string = string;
111			this.resId = resId;
112			this.rank = rank;
113		}
114
115		private String string;
116		private int resId;
117		private int rank;
118
119		public int getResId() {
120			return resId;
121		}
122
123		@Override
124		public String toString() {
125			return this.string;
126		}
127
128		public boolean ranks(Role role) {
129			return rank >= role.rank;
130		}
131	}
132
133	public enum Error {
134		NO_RESPONSE,
135		SERVER_NOT_FOUND,
136		NONE,
137		NICK_IN_USE,
138		PASSWORD_REQUIRED,
139		BANNED,
140		MEMBERS_ONLY,
141		KICKED,
142		SHUTDOWN,
143		INVALID_NICK,
144		UNKNOWN
145	}
146
147	public static final String STATUS_CODE_SELF_PRESENCE = "110";
148	public static final String STATUS_CODE_ROOM_CREATED = "201";
149	public static final String STATUS_CODE_BANNED = "301";
150	public static final String STATUS_CODE_CHANGED_NICK = "303";
151	public static final String STATUS_CODE_KICKED = "307";
152	public static final String STATUS_CODE_AFFILIATION_CHANGE = "321";
153	public static final String STATUS_CODE_LOST_MEMBERSHIP = "322";
154	public static final String STATUS_CODE_SHUTDOWN = "332";
155
156	private interface OnEventListener {
157		void onSuccess();
158
159		void onFailure();
160	}
161
162	public interface OnRenameListener extends OnEventListener {
163
164	}
165
166	public static class User implements Comparable<User> {
167		private Role role = Role.NONE;
168		private Affiliation affiliation = Affiliation.NONE;
169		private Jid realJid;
170		private Jid fullJid;
171		private long pgpKeyId = 0;
172		private Avatar avatar;
173		private MucOptions options;
174		private ChatState chatState = Config.DEFAULT_CHATSTATE;
175
176		public User(MucOptions options, Jid from) {
177			this.options = options;
178			this.fullJid = from;
179		}
180
181		public String getName() {
182			return fullJid == null ? null : fullJid.getResourcepart();
183		}
184
185		public void setRealJid(Jid jid) {
186			this.realJid = jid != null ? jid.toBareJid() : null;
187		}
188
189		public Role getRole() {
190			return this.role;
191		}
192
193		public void setRole(String role) {
194			if (role == null) {
195				this.role = Role.NONE;
196				return;
197			}
198			role = role.toLowerCase();
199			switch (role) {
200				case "moderator":
201					this.role = Role.MODERATOR;
202					break;
203				case "participant":
204					this.role = Role.PARTICIPANT;
205					break;
206				case "visitor":
207					this.role = Role.VISITOR;
208					break;
209				default:
210					this.role = Role.NONE;
211					break;
212			}
213		}
214
215		public Affiliation getAffiliation() {
216			return this.affiliation;
217		}
218
219		public void setAffiliation(String affiliation) {
220			if (affiliation == null) {
221				this.affiliation = Affiliation.NONE;
222				return;
223			}
224			affiliation = affiliation.toLowerCase();
225			switch (affiliation) {
226				case "admin":
227					this.affiliation = Affiliation.ADMIN;
228					break;
229				case "owner":
230					this.affiliation = Affiliation.OWNER;
231					break;
232				case "member":
233					this.affiliation = Affiliation.MEMBER;
234					break;
235				case "outcast":
236					this.affiliation = Affiliation.OUTCAST;
237					break;
238				default:
239					this.affiliation = Affiliation.NONE;
240			}
241		}
242
243		public void setPgpKeyId(long id) {
244			this.pgpKeyId = id;
245		}
246
247		public long getPgpKeyId() {
248			if (this.pgpKeyId != 0) {
249				return this.pgpKeyId;
250			} else if (realJid != null) {
251				return getAccount().getRoster().getContact(realJid).getPgpKeyId();
252			} else {
253				return 0;
254			}
255		}
256
257		public Contact getContact() {
258			if (fullJid != null) {
259				return getAccount().getRoster().getContactFromRoster(realJid);
260			} else if (realJid != null){
261				return getAccount().getRoster().getContact(realJid);
262			} else {
263				return null;
264			}
265		}
266
267		public boolean setAvatar(Avatar avatar) {
268			if (this.avatar != null && this.avatar.equals(avatar)) {
269				return false;
270			} else {
271				this.avatar = avatar;
272				return true;
273			}
274		}
275
276		public String getAvatar() {
277			return avatar == null ? null : avatar.getFilename();
278		}
279
280		public Account getAccount() {
281			return options.getAccount();
282		}
283
284		public Conversation getConversation() {
285			return options.getConversation();
286		}
287
288		public Jid getFullJid() {
289			return fullJid;
290		}
291
292		@Override
293		public boolean equals(Object o) {
294			if (this == o) return true;
295			if (o == null || getClass() != o.getClass()) return false;
296
297			User user = (User) o;
298
299			if (role != user.role) return false;
300			if (affiliation != user.affiliation) return false;
301			if (realJid != null ? !realJid.equals(user.realJid) : user.realJid != null)
302				return false;
303			return fullJid != null ? fullJid.equals(user.fullJid) : user.fullJid == null;
304
305		}
306
307		@Override
308		public int hashCode() {
309			int result = role != null ? role.hashCode() : 0;
310			result = 31 * result + (affiliation != null ? affiliation.hashCode() : 0);
311			result = 31 * result + (realJid != null ? realJid.hashCode() : 0);
312			result = 31 * result + (fullJid != null ? fullJid.hashCode() : 0);
313			return result;
314		}
315
316		@Override
317		public String toString() {
318			return "[fulljid:"+String.valueOf(fullJid)+",realjid:"+String.valueOf(realJid)+",affiliation"+affiliation.toString()+"]";
319		}
320
321		public boolean realJidMatchesAccount() {
322			return realJid != null && realJid.equals(options.account.getJid().toBareJid());
323		}
324
325		@Override
326		public int compareTo(User another) {
327			if (another.getAffiliation().outranks(getAffiliation())) {
328				return 1;
329			} else if (getAffiliation().outranks(another.getAffiliation())) {
330				return -1;
331			} else {
332				return getComparableName().compareToIgnoreCase(another.getComparableName());
333			}
334		}
335
336
337		private String getComparableName() {
338			Contact contact = getContact();
339			if (contact != null) {
340				return contact.getDisplayName();
341			} else {
342				String name = getName();
343				return name == null ? "" : name;
344			}
345		}
346
347		public Jid getRealJid() {
348			return realJid;
349		}
350
351		public boolean setChatState(ChatState chatState) {
352			if (this.chatState == chatState) {
353				return false;
354			}
355			this.chatState = chatState;
356			return true;
357		}
358	}
359
360	private Account account;
361	private final Set<User> users = new HashSet<>();
362	private final List<String> features = new ArrayList<>();
363	private Data form = new Data();
364	private final Conversation conversation;
365	private boolean isOnline = false;
366	private Error error = Error.NONE;
367	public OnRenameListener onRenameListener = null;
368	private User self;
369	private String password = null;
370
371	public MucOptions(Conversation conversation) {
372		this.account = conversation.getAccount();
373		this.conversation = conversation;
374		this.self = new User(this,createJoinJid(getProposedNick()));
375	}
376
377	public void updateFeatures(ArrayList<String> features) {
378		this.features.clear();
379		this.features.addAll(features);
380	}
381
382	public void updateFormData(Data form) {
383		this.form = form;
384	}
385
386	public boolean hasFeature(String feature) {
387		return this.features.contains(feature);
388	}
389
390	public boolean canInvite() {
391		Field field = this.form.getFieldByName("muc#roomconfig_allowinvites");
392		return !membersOnly() || self.getRole().ranks(Role.MODERATOR) || (field != null && "1".equals(field.getValue()));
393	}
394
395	public boolean canChangeSubject() {
396		Field field = this.form.getFieldByName("muc#roomconfig_changesubject");
397		return self.getRole().ranks(Role.MODERATOR) || (field != null && "1".equals(field.getValue()));
398	}
399
400	public boolean participating() {
401		return !online()
402				|| self.getRole().ranks(Role.PARTICIPANT)
403				|| hasFeature("muc_unmoderated");
404	}
405
406	public boolean membersOnly() {
407		return hasFeature("muc_membersonly");
408	}
409
410	public boolean mamSupport() {
411		return hasFeature(Namespace.MAM) || hasFeature(Namespace.MAM_LEGACY);
412	}
413
414	public boolean mamLegacy() {
415		return hasFeature(Namespace.MAM_LEGACY) && !hasFeature(Namespace.MAM);
416	}
417
418	public boolean nonanonymous() {
419		return hasFeature("muc_nonanonymous");
420	}
421
422	public boolean persistent() {
423		return hasFeature("muc_persistent");
424	}
425
426	public boolean moderated() {
427		return hasFeature("muc_moderated");
428	}
429
430	public User deleteUser(Jid jid) {
431		User user = findUserByFullJid(jid);
432		if (user != null) {
433			synchronized (users) {
434				users.remove(user);
435				boolean realJidInMuc = false;
436				for (User u : users) {
437					if (user.realJid != null && user.realJid.equals(u.realJid)) {
438						realJidInMuc = true;
439						break;
440					}
441				}
442				boolean self = user.realJid != null && user.realJid.equals(account.getJid().toBareJid());
443				if (membersOnly()
444						&& nonanonymous()
445						&& user.affiliation.ranks(Affiliation.MEMBER)
446						&& user.realJid != null
447						&& !realJidInMuc
448						&& !self) {
449					user.role = Role.NONE;
450					user.avatar = null;
451					user.fullJid = null;
452					users.add(user);
453				}
454			}
455		}
456		return user;
457	}
458
459	//returns true if real jid was new;
460	public boolean updateUser(User user) {
461		User old;
462		boolean realJidFound = false;
463		if (user.fullJid == null && user.realJid != null) {
464			old = findUserByRealJid(user.realJid);
465			realJidFound = old != null;
466			if (old != null) {
467				if (old.fullJid != null) {
468					return false; //don't add. user already exists
469				} else {
470					synchronized (users) {
471						users.remove(old);
472					}
473				}
474			}
475		} else if (user.realJid != null) {
476			old = findUserByRealJid(user.realJid);
477			realJidFound = old != null;
478			synchronized (users) {
479				if (old != null && old.fullJid == null) {
480					users.remove(old);
481				}
482			}
483		}
484		old = findUserByFullJid(user.getFullJid());
485		synchronized (this.users) {
486			if (old != null) {
487				users.remove(old);
488			}
489			boolean fullJidIsSelf = isOnline && user.getFullJid() != null && user.getFullJid().equals(self.getFullJid());
490			if ((!membersOnly() || user.getAffiliation().ranks(Affiliation.MEMBER))
491					&& user.getAffiliation().outranks(Affiliation.OUTCAST)
492					&& !fullJidIsSelf){
493				this.users.add(user);
494				return !realJidFound && user.realJid != null;
495			}
496		}
497		return false;
498	}
499
500	public User findUserByFullJid(Jid jid) {
501		if (jid == null) {
502			return null;
503		}
504		synchronized (users) {
505			for (User user : users) {
506				if (jid.equals(user.getFullJid())) {
507					return user;
508				}
509			}
510		}
511		return null;
512	}
513
514	public User findUserByRealJid(Jid jid) {
515		if (jid == null) {
516			return null;
517		}
518		synchronized (users) {
519			for (User user : users) {
520				if (jid.equals(user.realJid)) {
521					return user;
522				}
523			}
524		}
525		return null;
526	}
527
528	public User findUser(ReadByMarker readByMarker) {
529		if (readByMarker.getRealJid() != null) {
530			User user = findUserByRealJid(readByMarker.getRealJid().toBareJid());
531			if (user == null) {
532				user = new User(this,readByMarker.getFullJid());
533				user.setRealJid(readByMarker.getRealJid());
534			}
535			return user;
536		} else if (readByMarker.getFullJid() != null) {
537			return findUserByFullJid(readByMarker.getFullJid());
538		} else {
539			return null;
540		}
541	}
542
543	public boolean isContactInRoom(Contact contact) {
544		return findUserByRealJid(contact.getJid().toBareJid()) != null;
545	}
546
547	public boolean isUserInRoom(Jid jid) {
548		return findUserByFullJid(jid) != null;
549	}
550
551	public void setError(Error error) {
552		this.isOnline = isOnline && error == Error.NONE;
553		this.error = error;
554	}
555
556	public boolean setOnline() {
557		boolean before = this.isOnline;
558		this.isOnline = true;
559		return !before;
560	}
561
562	public ArrayList<User> getUsers() {
563		return getUsers(true);
564	}
565
566	public ArrayList<User> getUsers(boolean includeOffline) {
567		synchronized (users) {
568			if (includeOffline) {
569				return new ArrayList<>(users);
570			} else {
571				ArrayList<User> onlineUsers = new ArrayList<>();
572				for (User user : users) {
573					if (user.getRole().ranks(Role.PARTICIPANT)) {
574						onlineUsers.add(user);
575					}
576				}
577				return onlineUsers;
578			}
579		}
580	}
581
582	public ArrayList<User> getUsersWithChatState(ChatState state, int max) {
583		synchronized (users) {
584			ArrayList<User> list = new ArrayList<>();
585			for(User user : users) {
586				if (user.chatState == state) {
587					list.add(user);
588					if (list.size() >= max) {
589						break;
590					}
591				}
592			}
593			return list;
594		}
595	}
596
597	public List<User> getUsers(int max) {
598		ArrayList<User> subset = new ArrayList<>();
599		HashSet<Jid> jids = new HashSet<>();
600		jids.add(account.getJid().toBareJid());
601		synchronized (users) {
602			for(User user : users) {
603				if (user.getRealJid() == null || jids.add(user.getRealJid())) {
604					subset.add(user);
605				}
606				if (subset.size() >= max) {
607					break;
608				}
609			}
610		}
611		return subset;
612	}
613
614	public int getUserCount() {
615		synchronized (users) {
616			return users.size();
617		}
618	}
619
620	private String getProposedNick() {
621		if (conversation.getBookmark() != null
622				&& conversation.getBookmark().getNick() != null
623				&& !conversation.getBookmark().getNick().trim().isEmpty()) {
624			return conversation.getBookmark().getNick().trim();
625		} else if (!conversation.getJid().isBareJid()) {
626			return conversation.getJid().getResourcepart();
627		} else {
628			return JidHelper.localPartOrFallback(account.getJid());
629		}
630	}
631
632	public String getActualNick() {
633		if (this.self.getName() != null) {
634			return this.self.getName();
635		} else {
636			return this.getProposedNick();
637		}
638	}
639
640	public boolean online() {
641		return this.isOnline;
642	}
643
644	public Error getError() {
645		return this.error;
646	}
647
648	public void setOnRenameListener(OnRenameListener listener) {
649		this.onRenameListener = listener;
650	}
651
652	public void setOffline() {
653		synchronized (users) {
654			this.users.clear();
655		}
656		this.error = Error.NO_RESPONSE;
657		this.isOnline = false;
658	}
659
660	public User getSelf() {
661		return self;
662	}
663
664	public boolean setSubject(String subject) {
665		return this.conversation.setAttribute("subject",subject);
666	}
667
668	public String getSubject() {
669		return this.conversation.getAttribute("subject");
670	}
671
672	public List<User> getFallbackUsersFromCryptoTargets() {
673		List<User> users = new ArrayList<>();
674		for(Jid jid : conversation.getAcceptedCryptoTargets()) {
675			User user = new User(this,null);
676			user.setRealJid(jid);
677			users.add(user);
678		}
679		return users;
680	}
681
682	public List<User> getUsersRelevantForNameAndAvatar() {
683		final List<User> users;
684		if (isOnline) {
685			users = getUsers(5);
686		} else {
687			users = getFallbackUsersFromCryptoTargets();
688		}
689		return users;
690	}
691
692	public String createNameFromParticipants() {
693		List<User> users = getUsersRelevantForNameAndAvatar();
694		if (users.size() >= 2) {
695			StringBuilder builder = new StringBuilder();
696			for (User user : users) {
697				if (builder.length() != 0) {
698					builder.append(", ");
699				}
700				String name = UIHelper.getDisplayName(user);
701				if (name != null) {
702					builder.append(name.split("\\s+")[0]);
703				}
704			}
705			return builder.toString();
706		} else {
707			return null;
708		}
709	}
710
711	public long[] getPgpKeyIds() {
712		List<Long> ids = new ArrayList<>();
713		for (User user : this.users) {
714			if (user.getPgpKeyId() != 0) {
715				ids.add(user.getPgpKeyId());
716			}
717		}
718		ids.add(account.getPgpId());
719		long[] primitiveLongArray = new long[ids.size()];
720		for (int i = 0; i < ids.size(); ++i) {
721			primitiveLongArray[i] = ids.get(i);
722		}
723		return primitiveLongArray;
724	}
725
726	public boolean pgpKeysInUse() {
727		synchronized (users) {
728			for (User user : users) {
729				if (user.getPgpKeyId() != 0) {
730					return true;
731				}
732			}
733		}
734		return false;
735	}
736
737	public boolean everybodyHasKeys() {
738		synchronized (users) {
739			for (User user : users) {
740				if (user.getPgpKeyId() == 0) {
741					return false;
742				}
743			}
744		}
745		return true;
746	}
747
748	public Jid createJoinJid(String nick) {
749		try {
750			return Jid.fromString(this.conversation.getJid().toBareJid().toString() + "/" + nick);
751		} catch (final InvalidJidException e) {
752			return null;
753		}
754	}
755
756	public Jid getTrueCounterpart(Jid jid) {
757		if (jid.equals(getSelf().getFullJid())) {
758			return account.getJid().toBareJid();
759		}
760		User user = findUserByFullJid(jid);
761		return user == null ? null : user.realJid;
762	}
763
764	public String getPassword() {
765		this.password = conversation.getAttribute(Conversation.ATTRIBUTE_MUC_PASSWORD);
766		if (this.password == null && conversation.getBookmark() != null
767				&& conversation.getBookmark().getPassword() != null) {
768			return conversation.getBookmark().getPassword();
769		} else {
770			return this.password;
771		}
772	}
773
774	public void setPassword(String password) {
775		if (conversation.getBookmark() != null) {
776			conversation.getBookmark().setPassword(password);
777		} else {
778			this.password = password;
779		}
780		conversation.setAttribute(Conversation.ATTRIBUTE_MUC_PASSWORD, password);
781	}
782
783	public Conversation getConversation() {
784		return this.conversation;
785	}
786
787	public List<Jid> getMembers() {
788		ArrayList<Jid> members = new ArrayList<>();
789		synchronized (users) {
790			for (User user : users) {
791				if (user.affiliation.ranks(Affiliation.MEMBER) && user.realJid != null) {
792					members.add(user.realJid);
793				}
794			}
795		}
796		return members;
797	}
798}