MucOptions.java

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