MultiUserChatManager.java

   1package eu.siacs.conversations.xmpp.manager;
   2
   3import android.util.Log;
   4import androidx.annotation.NonNull;
   5import com.google.common.base.Strings;
   6import com.google.common.collect.Collections2;
   7import com.google.common.collect.ImmutableList;
   8import com.google.common.collect.ImmutableMap;
   9import com.google.common.collect.Iterables;
  10import com.google.common.util.concurrent.FutureCallback;
  11import com.google.common.util.concurrent.Futures;
  12import com.google.common.util.concurrent.ListenableFuture;
  13import com.google.common.util.concurrent.MoreExecutors;
  14import com.google.common.util.concurrent.SettableFuture;
  15import de.gultsch.common.FutureMerger;
  16import eu.siacs.conversations.Config;
  17import eu.siacs.conversations.entities.Account;
  18import eu.siacs.conversations.entities.Bookmark;
  19import eu.siacs.conversations.entities.Conversation;
  20import eu.siacs.conversations.entities.Conversational;
  21import eu.siacs.conversations.entities.MucOptions;
  22import eu.siacs.conversations.services.XmppConnectionService;
  23import eu.siacs.conversations.utils.CryptoHelper;
  24import eu.siacs.conversations.utils.StringUtils;
  25import eu.siacs.conversations.xml.Element;
  26import eu.siacs.conversations.xml.Namespace;
  27import eu.siacs.conversations.xmpp.Jid;
  28import eu.siacs.conversations.xmpp.XmppConnection;
  29import im.conversations.android.xmpp.Entity;
  30import im.conversations.android.xmpp.IqErrorException;
  31import im.conversations.android.xmpp.model.Extension;
  32import im.conversations.android.xmpp.model.conference.DirectInvite;
  33import im.conversations.android.xmpp.model.data.Data;
  34import im.conversations.android.xmpp.model.disco.info.InfoQuery;
  35import im.conversations.android.xmpp.model.error.Condition;
  36import im.conversations.android.xmpp.model.hints.NoCopy;
  37import im.conversations.android.xmpp.model.hints.NoStore;
  38import im.conversations.android.xmpp.model.jabber.Subject;
  39import im.conversations.android.xmpp.model.muc.Affiliation;
  40import im.conversations.android.xmpp.model.muc.History;
  41import im.conversations.android.xmpp.model.muc.MultiUserChat;
  42import im.conversations.android.xmpp.model.muc.Password;
  43import im.conversations.android.xmpp.model.muc.Role;
  44import im.conversations.android.xmpp.model.muc.admin.Item;
  45import im.conversations.android.xmpp.model.muc.admin.MucAdmin;
  46import im.conversations.android.xmpp.model.muc.owner.Destroy;
  47import im.conversations.android.xmpp.model.muc.owner.MucOwner;
  48import im.conversations.android.xmpp.model.muc.user.Invite;
  49import im.conversations.android.xmpp.model.muc.user.MucUser;
  50import im.conversations.android.xmpp.model.pgp.Signed;
  51import im.conversations.android.xmpp.model.stanza.Iq;
  52import im.conversations.android.xmpp.model.stanza.Message;
  53import im.conversations.android.xmpp.model.stanza.Presence;
  54import im.conversations.android.xmpp.model.vcard.update.VCardUpdate;
  55import java.util.Arrays;
  56import java.util.ArrayList;
  57import java.util.Collection;
  58import java.util.Collections;
  59import java.util.HashSet;
  60import java.util.TreeSet;
  61import java.util.List;
  62import java.util.Map;
  63import java.util.Set;
  64
  65public class MultiUserChatManager extends AbstractManager {
  66
  67    private final XmppConnectionService service;
  68
  69    private final Set<Conversation> inProgressConferenceJoins = new HashSet<>();
  70    private final Set<Conversation> inProgressConferencePings = new HashSet<>();
  71
  72    public MultiUserChatManager(final XmppConnectionService service, XmppConnection connection) {
  73        super(service, connection);
  74        this.service = service;
  75    }
  76
  77    public ListenableFuture<Void> join(final Conversation conversation) {
  78        return join(conversation, true);
  79    }
  80
  81    private ListenableFuture<Void> join(
  82            final Conversation conversation, final boolean autoPushConfiguration) {
  83        final var account = getAccount();
  84        synchronized (this.inProgressConferenceJoins) {
  85            this.inProgressConferenceJoins.add(conversation);
  86        }
  87        if (Config.MUC_LEAVE_BEFORE_JOIN) {
  88            unavailable(conversation);
  89        }
  90        conversation.resetMucOptions().setAutoPushConfiguration(autoPushConfiguration);
  91        conversation.setHasMessagesLeftOnServer(false);
  92        final var disco = fetchDiscoInfo(conversation);
  93
  94        final var caughtDisco =
  95                Futures.catchingAsync(
  96                        disco,
  97                        IqErrorException.class,
  98                        ex -> {
  99                            if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
 100                                return Futures.immediateFailedFuture(
 101                                        new IllegalStateException(
 102                                                "conversation got archived before disco returned"));
 103                            }
 104                            Log.d(Config.LOGTAG, "error fetching disco#info", ex);
 105                            final var iqError = ex.getError();
 106                            if (iqError != null
 107                                    && iqError.getCondition()
 108                                            instanceof Condition.RemoteServerNotFound) {
 109                                synchronized (this.inProgressConferenceJoins) {
 110                                    this.inProgressConferenceJoins.remove(conversation);
 111                                }
 112                                conversation
 113                                        .getMucOptions()
 114                                        .setError(MucOptions.Error.SERVER_NOT_FOUND);
 115                                service.updateConversationUi();
 116                                return Futures.immediateFailedFuture(ex);
 117                            } else {
 118                                return Futures.immediateFuture(new InfoQuery());
 119                            }
 120                        },
 121                        MoreExecutors.directExecutor());
 122
 123        return Futures.transform(
 124                caughtDisco,
 125                v -> {
 126                    checkConfigurationSendPresenceFetchHistory(conversation);
 127                    return null;
 128                },
 129                MoreExecutors.directExecutor());
 130    }
 131
 132    public ListenableFuture<Void> joinFollowingInvite(final Conversation conversation) {
 133        // TODO this special treatment is probably unnecessary; just always make sure the bookmark
 134        // exists
 135        return Futures.transform(
 136                join(conversation),
 137                v -> {
 138                    // we used to do this only for private groups
 139                    final Bookmark bookmark = conversation.getBookmark();
 140                    if (bookmark != null) {
 141                        if (bookmark.autojoin()) {
 142                            return null;
 143                        }
 144                        bookmark.setAutojoin(true);
 145                        getManager(BookmarkManager.class).create(bookmark);
 146                    } else {
 147                        getManager(BookmarkManager.class).save(conversation, null);
 148                    }
 149                    return null;
 150                },
 151                MoreExecutors.directExecutor());
 152    }
 153
 154    private void checkConfigurationSendPresenceFetchHistory(final Conversation conversation) {
 155
 156        Account account = conversation.getAccount();
 157        final MucOptions mucOptions = conversation.getMucOptions();
 158
 159        if (mucOptions.nonanonymous()
 160                && !mucOptions.membersOnly()
 161                && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
 162            synchronized (this.inProgressConferenceJoins) {
 163                this.inProgressConferenceJoins.remove(conversation);
 164            }
 165            mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
 166            service.updateConversationUi();
 167            return;
 168        }
 169
 170        final Jid joinJid = mucOptions.getSelf().getFullJid();
 171        Log.d(
 172                Config.LOGTAG,
 173                account.getJid().asBareJid().toString()
 174                        + ": joining conversation "
 175                        + joinJid.toString());
 176
 177        final var x = new MultiUserChat();
 178
 179        if (mucOptions.getPassword() != null) {
 180            x.addExtension(new Password(mucOptions.getPassword()));
 181        }
 182
 183        final var history = x.addExtension(new History());
 184
 185        if (mucOptions.mamSupport()) {
 186            // Use MAM instead of the limited muc history to get history
 187            history.setMaxStanzas(0);
 188        } else {
 189            // Fallback to muc history
 190            history.setSince(conversation.getLastMessageTransmitted().getTimestamp());
 191        }
 192        available(joinJid, mucOptions.nonanonymous(), x);
 193        if (!joinJid.equals(conversation.getJid())) {
 194            conversation.setContactJid(joinJid);
 195            getDatabase().updateConversation(conversation);
 196        }
 197
 198        if (mucOptions.mamSupport()) {
 199            this.service.getMessageArchiveService().catchupMUC(conversation);
 200        }
 201        fetchMembers(conversation);
 202        synchronized (this.inProgressConferenceJoins) {
 203            this.inProgressConferenceJoins.remove(conversation);
 204            this.service.sendUnsentMessages(conversation);
 205        }
 206    }
 207
 208    public ListenableFuture<Conversation> createPrivateGroupChat(
 209            final String name, final Collection<Jid> addresses) {
 210        final var service = getService();
 211        if (service == null) {
 212            return Futures.immediateFailedFuture(new IllegalStateException("No MUC service found"));
 213        }
 214        final var address = Jid.ofLocalAndDomain(CryptoHelper.pronounceable(), service);
 215        final var conversation =
 216                this.service.findOrCreateConversation(getAccount(), address, true, false, true);
 217        final var join = this.join(conversation, false);
 218        final var configured =
 219                Futures.transformAsync(
 220                        join,
 221                        v -> {
 222                            final var options =
 223                                    configWithName(defaultGroupChatConfiguration(), name);
 224                            return pushConfiguration(conversation, options);
 225                        },
 226                        MoreExecutors.directExecutor());
 227
 228        // TODO add catching to 'configured' to archive the chat again
 229
 230        return Futures.transform(
 231                configured,
 232                c -> {
 233                    for (var invitee : addresses) {
 234                        this.service.invite(conversation, invitee);
 235                    }
 236                    final var account = getAccount();
 237                    for (final var resource :
 238                            account.getSelfContact().getPresences().toResourceArray()) {
 239                        Jid other = getAccount().getJid().withResource(resource);
 240                        Log.d(
 241                                Config.LOGTAG,
 242                                account.getJid().asBareJid()
 243                                        + ": sending direct invite to "
 244                                        + other);
 245                        this.service.directInvite(conversation, other);
 246                    }
 247                    getManager(BookmarkManager.class).save(conversation, name);
 248                    return conversation;
 249                },
 250                MoreExecutors.directExecutor());
 251    }
 252
 253    public ListenableFuture<Conversation> createPublicChannel(
 254            final Jid address, final String name) {
 255
 256        final var conversation =
 257                this.service.findOrCreateConversation(getAccount(), address, true, false, true);
 258
 259        final var join = this.join(conversation, false);
 260        final var configuration =
 261                Futures.transformAsync(
 262                        join,
 263                        v -> {
 264                            final var options = configWithName(defaultChannelConfiguration(), name);
 265                            return pushConfiguration(conversation, options);
 266                        },
 267                        MoreExecutors.directExecutor());
 268
 269        // TODO mostly ignore configuration error
 270
 271        return Futures.transform(
 272                configuration,
 273                v -> {
 274                    getManager(BookmarkManager.class).save(conversation, name);
 275                    return conversation;
 276                },
 277                MoreExecutors.directExecutor());
 278    }
 279
 280    public void leave(final Conversation conversation) {
 281        final var mucOptions = conversation.getMucOptions();
 282        mucOptions.setOffline();
 283        getManager(DiscoManager.class).clear(conversation.getJid().asBareJid());
 284        unavailable(conversation);
 285    }
 286
 287    public void handlePresence(final Presence presence) {}
 288
 289    public void handleStatusMessage(final Message message) {
 290        final var from = Jid.Invalid.getNullForInvalid(message.getFrom());
 291        final var mucUser = message.getExtension(MucUser.class);
 292        if (from == null || from.isFullJid() || mucUser == null) {
 293            return;
 294        }
 295        final var conversation = this.service.find(getAccount(), from);
 296        if (conversation == null || conversation.getMode() != Conversation.MODE_MULTI) {
 297            return;
 298        }
 299        for (final var status : mucUser.getStatus()) {
 300            handleStatusCode(conversation, status);
 301        }
 302        final var item = mucUser.getItem();
 303        if (item == null) {
 304            return;
 305        }
 306        final var user = itemToUser(conversation, item, null, null, null, null);
 307        this.handleAffiliationChange(conversation, user);
 308    }
 309
 310    private void handleAffiliationChange(
 311            final Conversation conversation, final MucOptions.User user) {
 312        final var account = getAccount();
 313        Log.d(
 314                Config.LOGTAG,
 315                account.getJid()
 316                        + ": changing affiliation for "
 317                        + user.getRealJid()
 318                        + " to "
 319                        + user.getAffiliation()
 320                        + " in "
 321                        + conversation.getJid().asBareJid());
 322        if (user.realJidMatchesAccount()) {
 323            return;
 324        }
 325        final var mucOptions = conversation.getMucOptions();
 326        final boolean isNew = mucOptions.updateUser(user);
 327        final var avatarService = this.service.getAvatarService();
 328        if (Strings.isNullOrEmpty(mucOptions.getAvatar())) {
 329            avatarService.clear(mucOptions);
 330        }
 331        avatarService.clear(user);
 332        this.service.updateMucRosterUi();
 333        this.service.updateConversationUi();
 334        if (user.ranks(Affiliation.MEMBER)) {
 335            fetchDeviceIdsIfNeeded(isNew, user);
 336        } else {
 337            final var jid = user.getRealJid();
 338            final var cryptoTargets = conversation.getAcceptedCryptoTargets();
 339            if (cryptoTargets.remove(user.getRealJid())) {
 340                Log.d(
 341                        Config.LOGTAG,
 342                        account.getJid().asBareJid()
 343                                + ": removed "
 344                                + jid
 345                                + " from crypto targets of "
 346                                + conversation.getName());
 347                conversation.setAcceptedCryptoTargets(cryptoTargets);
 348                getDatabase().updateConversation(conversation);
 349            }
 350        }
 351    }
 352
 353    private void fetchDeviceIdsIfNeeded(final boolean isNew, final MucOptions.User user) {
 354        final var contact = user.getContact();
 355        final var mucOptions = user.getMucOptions();
 356        final var axolotlService = connection.getAxolotlService();
 357        if (isNew
 358                && user.getRealJid() != null
 359                && mucOptions.isPrivateAndNonAnonymous()
 360                && (contact == null || !contact.mutualPresenceSubscription())
 361                && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
 362            axolotlService.fetchDeviceIds(user.getRealJid());
 363        }
 364    }
 365
 366    private void handleStatusCode(final Conversation conversation, final int status) {
 367        if ((status >= 170 && status <= 174) || (status >= 102 && status <= 104)) {
 368            Log.d(
 369                    Config.LOGTAG,
 370                    getAccount().getJid().asBareJid()
 371                            + ": fetching disco#info on status code "
 372                            + status);
 373            getManager(MultiUserChatManager.class).fetchDiscoInfo(conversation);
 374        }
 375    }
 376
 377    public ListenableFuture<Void> fetchDiscoInfo(final Conversation conversation) {
 378        final var address = conversation.getJid().asBareJid();
 379        final var future =
 380                connection.getManager(DiscoManager.class).info(Entity.discoItem(address), null);
 381        return Futures.transform(
 382                future,
 383                infoQuery -> {
 384                    setDiscoInfo(conversation, infoQuery);
 385                    return null;
 386                },
 387                MoreExecutors.directExecutor());
 388    }
 389
 390    private void setDiscoInfo(final Conversation conversation, final InfoQuery result) {
 391        final var account = conversation.getAccount();
 392        final var address = conversation.getJid().asBareJid();
 393        final var avatarHash =
 394                result.getServiceDiscoveryExtension(
 395                        Namespace.MUC_ROOM_INFO, "muc#roominfo_avatarhash");
 396        if (VCardUpdate.isValidSHA1(avatarHash)) {
 397            connection.getManager(AvatarManager.class).handleVCardUpdate(address, avatarHash);
 398        }
 399        final MucOptions mucOptions = conversation.getMucOptions();
 400        final Bookmark bookmark = conversation.getBookmark();
 401        final boolean sameBefore =
 402                StringUtils.equals(
 403                        bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
 404
 405        final var hadOccupantId = mucOptions.occupantId();
 406        if (mucOptions.updateConfiguration(result)) {
 407            Log.d(
 408                    Config.LOGTAG,
 409                    account.getJid().asBareJid()
 410                            + ": muc configuration changed for "
 411                            + conversation.getJid().asBareJid());
 412            getDatabase().updateConversation(conversation);
 413        }
 414
 415        final var hasOccupantId = mucOptions.occupantId();
 416
 417        if (!hadOccupantId && hasOccupantId && mucOptions.online()) {
 418            final var me = mucOptions.getSelf().getFullJid();
 419            Log.d(
 420                    Config.LOGTAG,
 421                    account.getJid().asBareJid()
 422                            + ": gained support for occupant-id in "
 423                            + me
 424                            + ". resending presence");
 425            this.available(me, mucOptions.nonanonymous());
 426        }
 427
 428        if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
 429            if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
 430                getManager(BookmarkManager.class).create(bookmark);
 431            }
 432        }
 433        this.service.updateConversationUi();
 434    }
 435
 436    public void resendPresence(final Conversation conversation) {
 437        final MucOptions mucOptions = conversation.getMucOptions();
 438        if (mucOptions.online()) {
 439            available(mucOptions.getSelf().getFullJid(), mucOptions.nonanonymous());
 440        }
 441    }
 442
 443    private void available(
 444            final Jid address, final boolean nonAnonymous, final Extension... extensions) {
 445        final var presenceManager = getManager(PresenceManager.class);
 446        final var account = getAccount();
 447        final String pgpSignature = account.getPgpSignature();
 448        if (nonAnonymous && pgpSignature != null) {
 449            final String message = account.getPresenceStatusMessage();
 450            presenceManager.available(
 451                    address, message, combine(extensions, new Signed(pgpSignature)));
 452        } else {
 453            presenceManager.available(address, extensions);
 454        }
 455    }
 456
 457    public void unavailable(final Conversation conversation) {
 458        final var mucOptions = conversation.getMucOptions();
 459        getManager(PresenceManager.class).unavailable(mucOptions.getSelf().getFullJid());
 460    }
 461
 462    private static Extension[] combine(final Extension[] extensions, final Extension extension) {
 463        return new ImmutableList.Builder<Extension>()
 464                .addAll(Arrays.asList(extensions))
 465                .add(extension)
 466                .build()
 467                .toArray(new Extension[0]);
 468    }
 469
 470    public ListenableFuture<Void> pushConfiguration(
 471            final Conversation conversation, final Map<String, Object> input) {
 472        final var address = conversation.getJid().asBareJid();
 473        final var configuration = modifyBestInteroperability(input);
 474
 475        if (configuration.get("muc#roomconfig_whois") instanceof String whois
 476                && whois.equals("anyone")) {
 477            conversation.setAttribute("accept_non_anonymous", true);
 478            getDatabase().updateConversation(conversation);
 479        }
 480
 481        final var future = fetchConfigurationForm(address);
 482        return Futures.transformAsync(
 483                future,
 484                current -> {
 485                    final var modified = current.submit(configuration);
 486                    return submitConfigurationForm(address, modified);
 487                },
 488                MoreExecutors.directExecutor());
 489    }
 490
 491    public ListenableFuture<Data> fetchConfigurationForm(final Jid address) {
 492        final var iq = new Iq(Iq.Type.GET, new MucOwner());
 493        iq.setTo(address);
 494        Log.d(Config.LOGTAG, "fetching configuration form: " + iq);
 495        return Futures.transform(
 496                connection.sendIqPacket(iq),
 497                response -> {
 498                    final var mucOwner = response.getExtension(MucOwner.class);
 499                    if (mucOwner == null) {
 500                        throw new IllegalStateException("Missing MucOwner element in response");
 501                    }
 502                    return mucOwner.getConfiguration();
 503                },
 504                MoreExecutors.directExecutor());
 505    }
 506
 507    private ListenableFuture<Void> submitConfigurationForm(final Jid address, final Data data) {
 508        final var iq = new Iq(Iq.Type.SET);
 509        iq.setTo(address);
 510        final var mucOwner = iq.addExtension(new MucOwner());
 511        mucOwner.addExtension(data);
 512        Log.d(Config.LOGTAG, "pushing configuration form: " + iq);
 513        return Futures.transform(
 514                this.connection.sendIqPacket(iq), response -> null, MoreExecutors.directExecutor());
 515    }
 516
 517    public ListenableFuture<Void> fetchMembers(final Conversation conversation) {
 518        final var affiliations = new ArrayList<Affiliation>();
 519        affiliations.add(Affiliation.OUTCAST);
 520         if (conversation.getMucOptions().isPrivateAndNonAnonymous()) affiliations.addAll(List.of(Affiliation.OWNER, Affiliation.ADMIN, Affiliation.MEMBER));
 521        final var futures =
 522                Collections2.transform(
 523                        affiliations,
 524                        a -> fetchAffiliations(conversation, a));
 525        ListenableFuture<List<MucOptions.User>> future = FutureMerger.allAsList(futures);
 526        return Futures.transform(
 527                future,
 528                members -> {
 529                    setMembers(conversation, members);
 530                    return null;
 531                },
 532                MoreExecutors.directExecutor());
 533    }
 534
 535    private void setMembers(final Conversation conversation, final List<MucOptions.User> users) {
 536        for (final var user : users) {
 537            if (user.realJidMatchesAccount()) {
 538                continue;
 539            }
 540            boolean isNew = conversation.getMucOptions().updateUser(user);
 541            fetchDeviceIdsIfNeeded(isNew, user);
 542        }
 543        final var mucOptions = conversation.getMucOptions();
 544        final var members = mucOptions.getMembers(true);
 545        final var cryptoTargets = conversation.getAcceptedCryptoTargets();
 546        boolean changed = false;
 547        for (final var iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
 548            final var jid = iterator.next();
 549            if (!members.contains(jid) && !members.contains(jid.getDomain())) {
 550                iterator.remove();
 551                Log.d(
 552                        Config.LOGTAG,
 553                        getAccount().getJid().asBareJid()
 554                                + ": removed "
 555                                + jid
 556                                + " from crypto targets of "
 557                                + conversation.getName());
 558                changed = true;
 559            }
 560        }
 561        if (changed) {
 562            conversation.setAcceptedCryptoTargets(cryptoTargets);
 563            getDatabase().updateConversation(conversation);
 564        }
 565        // TODO only when room has no avatar
 566        this.service.getAvatarService().clear(mucOptions);
 567        this.service.updateMucRosterUi();
 568        this.service.updateConversationUi();
 569    }
 570
 571    private ListenableFuture<Collection<MucOptions.User>> fetchAffiliations(
 572            final Conversation conversation, final Affiliation affiliation) {
 573        final var iq = new Iq(Iq.Type.GET);
 574        iq.setTo(conversation.getJid().asBareJid());
 575        iq.addExtension(new MucAdmin()).addExtension(new Item()).setAffiliation(affiliation);
 576        return Futures.transform(
 577                this.connection.sendIqPacket(iq),
 578                response -> {
 579                    final var mucAdmin = response.getExtension(MucAdmin.class);
 580                    if (mucAdmin == null) {
 581                        throw new IllegalStateException("No query in response");
 582                    }
 583                    return Collections2.transform(
 584                            mucAdmin.getItems(), i -> itemToUser(conversation, i, null, null, null, null));
 585                },
 586                MoreExecutors.directExecutor());
 587    }
 588
 589    public ListenableFuture<Void> changeUsername(
 590            final Conversation conversation, final String username) {
 591
 592        // TODO when online send normal available presence
 593        // TODO when not online do a normal join
 594
 595        final Bookmark bookmark = conversation.getBookmark();
 596        final MucOptions options = conversation.getMucOptions();
 597        final Jid joinJid = options.createJoinJid(username);
 598        if (joinJid == null) {
 599            return Futures.immediateFailedFuture(new IllegalArgumentException());
 600        }
 601
 602        if (options.online()) {
 603            final SettableFuture<Void> renameFuture = SettableFuture.create();
 604            options.setOnRenameListener(
 605                    new MucOptions.OnRenameListener() {
 606
 607                        @Override
 608                        public void onSuccess() {
 609                            renameFuture.set(null);
 610                        }
 611
 612                        @Override
 613                        public void onFailure() {
 614                            renameFuture.setException(new IllegalStateException());
 615                        }
 616                    });
 617
 618            available(joinJid, options.nonanonymous());
 619
 620            if (username.equals(MucOptions.defaultNick(getAccount()))
 621                    && bookmark != null
 622                    && bookmark.getNick() != null) {
 623                Log.d(
 624                        Config.LOGTAG,
 625                        getAccount().getJid().asBareJid()
 626                                + ": removing nick from bookmark for "
 627                                + bookmark.getJid());
 628                bookmark.setNick(null);
 629                getManager(BookmarkManager.class).create(bookmark);
 630            }
 631            return renameFuture;
 632        } else {
 633            conversation.setContactJid(joinJid);
 634            getDatabase().updateConversation(conversation);
 635            if (bookmark != null) {
 636                bookmark.setNick(username);
 637                getManager(BookmarkManager.class).create(bookmark);
 638            }
 639            join(conversation);
 640            return Futures.immediateVoidFuture();
 641        }
 642    }
 643
 644    public void checkMucRequiresRename(final Conversation conversation) {
 645        final var options = conversation.getMucOptions();
 646        if (!options.online()) {
 647            return;
 648        }
 649        final String current = options.getActualNick();
 650        final String proposed = options.getProposedNickPure();
 651        if (current == null || current.equals(proposed)) {
 652            return;
 653        }
 654        final Jid joinJid = options.createJoinJid(proposed);
 655        Log.d(
 656                Config.LOGTAG,
 657                String.format(
 658                        "%s: muc rename required %s (was: %s)",
 659                        getAccount().getJid().asBareJid(), joinJid, current));
 660        available(joinJid, options.nonanonymous());
 661    }
 662
 663    public void setPassword(final Conversation conversation, final String password) {
 664        final var bookmark = conversation.getBookmark();
 665        conversation.getMucOptions().setPassword(password);
 666        if (bookmark != null) {
 667            bookmark.setAutojoin(true);
 668            getManager(BookmarkManager.class).create(bookmark);
 669        }
 670        getDatabase().updateConversation(conversation);
 671        this.join(conversation);
 672    }
 673
 674    public void pingAndRejoin(final Conversation conversation) {
 675        final Account account = getAccount();
 676        synchronized (this.inProgressConferenceJoins) {
 677            if (this.inProgressConferenceJoins.contains(conversation)) {
 678                Log.d(
 679                        Config.LOGTAG,
 680                        account.getJid().asBareJid()
 681                                + ": canceling muc self ping because join is already under way");
 682                return;
 683            }
 684        }
 685        synchronized (this.inProgressConferencePings) {
 686            if (!this.inProgressConferencePings.add(conversation)) {
 687                Log.d(
 688                        Config.LOGTAG,
 689                        account.getJid().asBareJid()
 690                                + ": canceling muc self ping because ping is already under way");
 691                return;
 692            }
 693        }
 694        final Jid self = conversation.getMucOptions().getSelf().getFullJid();
 695        final var future = getManager(PingManager.class).ping(self);
 696        Futures.addCallback(
 697                future,
 698                new FutureCallback<>() {
 699                    @Override
 700                    public void onSuccess(Iq result) {
 701                        Log.d(
 702                                Config.LOGTAG,
 703                                account.getJid().asBareJid()
 704                                        + ": ping to "
 705                                        + self
 706                                        + " came back fine");
 707                        synchronized (MultiUserChatManager.this.inProgressConferencePings) {
 708                            MultiUserChatManager.this.inProgressConferencePings.remove(
 709                                    conversation);
 710                        }
 711                    }
 712
 713                    @Override
 714                    public void onFailure(@NonNull Throwable throwable) {
 715                        synchronized (MultiUserChatManager.this.inProgressConferencePings) {
 716                            MultiUserChatManager.this.inProgressConferencePings.remove(
 717                                    conversation);
 718                        }
 719                        if (throwable instanceof IqErrorException iqErrorException) {
 720                            final var condition = iqErrorException.getErrorCondition();
 721                            if (condition instanceof Condition.ServiceUnavailable
 722                                    || condition instanceof Condition.FeatureNotImplemented
 723                                    || condition instanceof Condition.ItemNotFound) {
 724                                Log.d(
 725                                        Config.LOGTAG,
 726                                        account.getJid().asBareJid()
 727                                                + ": ping to "
 728                                                + self
 729                                                + " came back as ignorable error");
 730                            } else {
 731                                Log.d(
 732                                        Config.LOGTAG,
 733                                        account.getJid().asBareJid()
 734                                                + ": ping to "
 735                                                + self
 736                                                + " failed. attempting rejoin");
 737                                join(conversation);
 738                            }
 739                        }
 740                    }
 741                },
 742                MoreExecutors.directExecutor());
 743    }
 744
 745    public ListenableFuture<Void> destroy(final Jid address) {
 746        final var iq = new Iq(Iq.Type.SET);
 747        iq.setTo(address);
 748        final var mucOwner = iq.addExtension(new MucOwner());
 749        mucOwner.addExtension(new Destroy());
 750        return Futures.transform(
 751                connection.sendIqPacket(iq), result -> null, MoreExecutors.directExecutor());
 752    }
 753
 754    public ListenableFuture<Void> setAffiliation(
 755            final Conversation conversation, final Affiliation affiliation, Jid user) {
 756        return setAffiliation(conversation, affiliation, Collections.singleton(user));
 757    }
 758
 759    public ListenableFuture<Void> setAffiliation(
 760            final Conversation conversation,
 761            final Affiliation affiliation,
 762            final Collection<Jid> users) {
 763        final var address = conversation.getJid().asBareJid();
 764        final var iq = new Iq(Iq.Type.SET);
 765        iq.setTo(address);
 766        final var admin = iq.addExtension(new MucAdmin());
 767        for (final var user : users) {
 768            final var item = admin.addExtension(new Item());
 769            item.setJid(user);
 770            item.setAffiliation(affiliation);
 771        }
 772        return Futures.transform(
 773                this.connection.sendIqPacket(iq),
 774                response -> {
 775                    // TODO figure out what this was meant to do
 776                    // is this a work around for some servers not sending notifications when
 777                    // changing the affiliation of people not in the room? this would explain this
 778                    // firing only when getRole == None
 779                    final var mucOptions = conversation.getMucOptions();
 780                    for (final var user : users) {
 781                        mucOptions.changeAffiliation(user, affiliation);
 782                    }
 783                    service.getAvatarService().clear(mucOptions);
 784                    return null;
 785                },
 786                MoreExecutors.directExecutor());
 787    }
 788
 789    public ListenableFuture<Void> setRole(final Jid address, final Role role, final String user) {
 790        return setRole(address, role, Collections.singleton(user));
 791    }
 792
 793    public ListenableFuture<Void> setRole(
 794            final Jid address, final Role role, final Collection<String> users) {
 795        final var iq = new Iq(Iq.Type.SET);
 796        iq.setTo(address);
 797        final var admin = iq.addExtension(new MucAdmin());
 798        for (final var user : users) {
 799            final var item = admin.addExtension(new Item());
 800            item.setNick(user);
 801            item.setRole(role);
 802        }
 803        return Futures.transform(
 804                this.connection.sendIqPacket(iq), response -> null, MoreExecutors.directExecutor());
 805    }
 806
 807    public void setSubject(final Conversation conversation, final String subject) {
 808        final var message = new Message();
 809        message.setType(Message.Type.GROUPCHAT);
 810        message.setTo(conversation.getJid().asBareJid());
 811        message.addExtension(new Subject(subject));
 812        connection.sendMessagePacket(message);
 813    }
 814
 815    public void invite(final Conversation conversation, final Jid address) {
 816        Log.d(
 817                Config.LOGTAG,
 818                conversation.getAccount().getJid().asBareJid()
 819                        + ": inviting "
 820                        + address
 821                        + " to "
 822                        + conversation.getJid().asBareJid());
 823        final MucOptions.User user =
 824                conversation.getMucOptions().findUserByRealJid(address.asBareJid());
 825        if (user == null || user.getAffiliation() == Affiliation.OUTCAST) {
 826            this.setAffiliation(conversation, Affiliation.NONE, address);
 827        }
 828
 829        final var packet = new Message();
 830        packet.setTo(conversation.getJid().asBareJid());
 831        final var x = packet.addExtension(new MucUser());
 832        final var invite = x.addExtension(new Invite());
 833        invite.setTo(address.asBareJid());
 834        connection.sendMessagePacket(packet);
 835    }
 836
 837    public void directInvite(final Conversation conversation, final Jid address) {
 838        final var message = new Message();
 839        message.setTo(address);
 840        final var directInvite = message.addExtension(new DirectInvite());
 841        directInvite.setJid(conversation.getJid().asBareJid());
 842        final var password = conversation.getMucOptions().getPassword();
 843        if (password != null) {
 844            directInvite.setPassword(password);
 845        }
 846        if (address.isFullJid()) {
 847            message.addExtension(new NoStore());
 848            message.addExtension(new NoCopy());
 849        }
 850        this.connection.sendMessagePacket(message);
 851    }
 852
 853    public boolean isJoinInProgress(final Conversation conversation) {
 854        synchronized (this.inProgressConferenceJoins) {
 855            if (conversation.getMode() == Conversational.MODE_MULTI) {
 856                final boolean inProgress = this.inProgressConferenceJoins.contains(conversation);
 857                if (inProgress) {
 858                    Log.d(
 859                            Config.LOGTAG,
 860                            getAccount().getJid().asBareJid()
 861                                    + ": holding back message to group. join in progress");
 862                }
 863                return inProgress;
 864            } else {
 865                return false;
 866            }
 867        }
 868    }
 869
 870    public void clearInProgress() {
 871        synchronized (this.inProgressConferenceJoins) {
 872            this.inProgressConferenceJoins.clear();
 873        }
 874        synchronized (this.inProgressConferencePings) {
 875            this.inProgressConferencePings.clear();
 876        }
 877    }
 878
 879    public Jid getService() {
 880        return Iterables.getFirst(this.getServices(), null);
 881    }
 882
 883    public List<Jid> getServices() {
 884        final var builder = new ImmutableList.Builder<Jid>();
 885        for (final var entry : getManager(DiscoManager.class).getServerItems().entrySet()) {
 886            final var value = entry.getValue();
 887            if (value.getFeatureStrings().contains(Namespace.MUC)
 888                    && value.hasIdentityWithCategoryAndType("conference", "text")
 889                    && !value.getFeatureStrings().contains("jabber:iq:gateway")
 890                    && !value.hasIdentityWithCategoryAndType("conference", "irc")) {
 891                builder.add(entry.getKey());
 892            }
 893        }
 894        return builder.build();
 895    }
 896
 897    public static MucOptions.User itemToUser(
 898            final Conversation conference,
 899            im.conversations.android.xmpp.model.muc.Item item,
 900            final Jid from,
 901            final String occupantId,
 902            final String nicknameIn,
 903            final Element hatsEl) {
 904        final var affiliation = item.getAffiliation();
 905        final var role = item.getRole();
 906        var nick = item.getNick();
 907        try {
 908            if (nicknameIn != null && nick != null && !nick.equals(nicknameIn) && gnu.inet.encoding.Punycode.decode(nick).equals(nicknameIn)) {
 909                nick = nicknameIn;
 910            }
 911        } catch (final Exception e) { }
 912        Set<MucOptions.Hat> hats = new TreeSet<>();
 913        if (hatsEl != null) {
 914            for (final var hat : hatsEl.getChildren()) {
 915                if ("hat".equals(hat.getName()) && ("urn:xmpp:hats:0".equals(hat.getNamespace()) || "xmpp:prosody.im/protocol/hats:1".equals(hat.getNamespace()))) {
 916                    hats.add(new MucOptions.Hat(hat));
 917                }
 918            }
 919        }
 920        final Jid fullAddress;
 921        if (from != null && from.isFullJid()) {
 922            fullAddress = from;
 923        } else if (Strings.isNullOrEmpty(nick)) {
 924            fullAddress = null;
 925        } else {
 926            fullAddress = ofNick(conference, nick);
 927        }
 928        final Jid realJid = item.getAttributeAsJid("jid");
 929        MucOptions.User user = new MucOptions.User(conference.getMucOptions(), fullAddress, occupantId, nick, hats);
 930        if (Jid.Invalid.isValid(realJid)) {
 931            user.setRealJid(realJid);
 932        }
 933        user.setAffiliation(affiliation);
 934        user.setRole(role);
 935        return user;
 936    }
 937
 938    private static Jid ofNick(final Conversation conversation, final String nick) {
 939        try {
 940            return conversation.getJid().withResource(nick);
 941        } catch (final IllegalArgumentException e) {
 942            return null;
 943        }
 944    }
 945
 946    private static Map<String, Object> modifyBestInteroperability(
 947            final Map<String, Object> unmodified) {
 948        final var builder = new ImmutableMap.Builder<String, Object>();
 949        builder.putAll(unmodified);
 950
 951        if (unmodified.get("muc#roomconfig_moderatedroom") instanceof Boolean moderated) {
 952            builder.put("members_by_default", !moderated);
 953        }
 954        if (unmodified.get("muc#roomconfig_allowpm") instanceof String allowPm) {
 955            // ejabberd :-/
 956            final boolean allow = "anyone".equals(allowPm);
 957            builder.put("allow_private_messages", allow);
 958            builder.put("allow_private_messages_from_visitors", allow ? "anyone" : "nobody");
 959        }
 960
 961        if (unmodified.get("muc#roomconfig_allowinvites") instanceof Boolean allowInvites) {
 962            // TODO check that this actually does something useful?
 963            builder.put(
 964                    "{http://prosody.im/protocol/muc}roomconfig_allowmemberinvites", allowInvites);
 965        }
 966
 967        return builder.buildOrThrow();
 968    }
 969
 970    private static Map<String, Object> configWithName(
 971            final Map<String, Object> unmodified, final String name) {
 972        if (Strings.isNullOrEmpty(name)) {
 973            return unmodified;
 974        }
 975        return new ImmutableMap.Builder<String, Object>()
 976                .putAll(unmodified)
 977                .put("muc#roomconfig_roomname", name)
 978                .buildKeepingLast();
 979    }
 980
 981    public static Map<String, Object> defaultGroupChatConfiguration() {
 982        return new ImmutableMap.Builder<String, Object>()
 983                .put("muc#roomconfig_persistentroom", true)
 984                .put("muc#roomconfig_membersonly", true)
 985                .put("muc#roomconfig_publicroom", false)
 986                .put("muc#roomconfig_whois", "anyone")
 987                .put("muc#roomconfig_changesubject", false)
 988                .put("muc#roomconfig_allowinvites", false)
 989                .put("muc#roomconfig_enablearchiving", true) // prosody
 990                .put("mam", true) // ejabberd community
 991                .put("muc#roomconfig_mam", true) // ejabberd saas
 992                .buildOrThrow();
 993    }
 994
 995    public static Map<String, Object> defaultChannelConfiguration() {
 996        return new ImmutableMap.Builder<String, Object>()
 997                .put("muc#roomconfig_persistentroom", true)
 998                .put("muc#roomconfig_membersonly", false)
 999                .put("muc#roomconfig_publicroom", true)
1000                .put("muc#roomconfig_whois", "moderators")
1001                .put("muc#roomconfig_changesubject", false)
1002                .put("muc#roomconfig_enablearchiving", true) // prosody
1003                .put("mam", true) // ejabberd community
1004                .put("muc#roomconfig_mam", true) // ejabberd saas
1005                .buildOrThrow();
1006    }
1007}