IqGenerator.java

  1package eu.siacs.conversations.generator;
  2
  3import android.os.Bundle;
  4import android.util.Base64;
  5import android.util.Base64OutputStream;
  6import android.util.Log;
  7
  8import com.cheogram.android.BobTransfer;
  9
 10import com.google.common.io.ByteStreams;
 11
 12import org.whispersystems.libsignal.IdentityKey;
 13import org.whispersystems.libsignal.ecc.ECPublicKey;
 14import org.whispersystems.libsignal.state.PreKeyRecord;
 15import org.whispersystems.libsignal.state.SignedPreKeyRecord;
 16
 17import java.io.ByteArrayOutputStream;
 18import java.io.FileInputStream;
 19import java.io.IOException;
 20import java.nio.ByteBuffer;
 21import java.security.cert.CertificateEncodingException;
 22import java.security.cert.X509Certificate;
 23import java.util.ArrayList;
 24import java.util.List;
 25import java.util.Locale;
 26import java.util.Set;
 27import java.util.TimeZone;
 28import java.util.UUID;
 29
 30import io.ipfs.cid.Cid;
 31
 32import eu.siacs.conversations.Config;
 33import eu.siacs.conversations.R;
 34import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 35import eu.siacs.conversations.entities.Account;
 36import eu.siacs.conversations.entities.Bookmark;
 37import eu.siacs.conversations.entities.Conversation;
 38import eu.siacs.conversations.entities.DownloadableFile;
 39import eu.siacs.conversations.entities.Message;
 40import eu.siacs.conversations.services.MessageArchiveService;
 41import eu.siacs.conversations.services.QuickConversationsService;
 42import eu.siacs.conversations.services.XmppConnectionService;
 43import eu.siacs.conversations.xml.Element;
 44import eu.siacs.conversations.xml.Namespace;
 45import eu.siacs.conversations.xmpp.Jid;
 46import eu.siacs.conversations.xmpp.forms.Data;
 47import eu.siacs.conversations.xmpp.pep.Avatar;
 48import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 49
 50public class IqGenerator extends AbstractGenerator {
 51
 52    public IqGenerator(final XmppConnectionService service) {
 53        super(service);
 54    }
 55
 56    public IqPacket discoResponse(final Account account, final IqPacket request) {
 57        final IqPacket packet = new IqPacket(IqPacket.TYPE.RESULT);
 58        packet.setId(request.getId());
 59        packet.setTo(request.getFrom());
 60        final Element query = packet.addChild("query", "http://jabber.org/protocol/disco#info");
 61        query.setAttribute("node", request.query().getAttribute("node"));
 62        final Element identity = query.addChild("identity");
 63        identity.setAttribute("category", "client");
 64        identity.setAttribute("type", getIdentityType());
 65        identity.setAttribute("name", getIdentityName());
 66        for (final String feature : getFeatures(account)) {
 67            query.addChild("feature").setAttribute("var", feature);
 68        }
 69        return packet;
 70    }
 71
 72    public IqPacket versionResponse(final IqPacket request) {
 73        final IqPacket packet = request.generateResponse(IqPacket.TYPE.RESULT);
 74        Element query = packet.query("jabber:iq:version");
 75        query.addChild("name").setContent(mXmppConnectionService.getString(R.string.app_name));
 76        query.addChild("version").setContent(getIdentityVersion());
 77        final StringBuilder os = new StringBuilder();
 78        if ("chromium".equals(android.os.Build.BRAND)) {
 79            os.append("Chrome OS");
 80        } else {
 81            os.append("Android");
 82        }
 83        os.append(" ");
 84        os.append(android.os.Build.VERSION.RELEASE);
 85        if (QuickConversationsService.isPlayStoreFlavor()) {
 86            os.append(" (");
 87            os.append(android.os.Build.BOARD);
 88            os.append(", ");
 89            os.append(android.os.Build.FINGERPRINT);
 90            os.append(")");
 91            query.addChild("os").setContent(os.toString());
 92        }
 93        return packet;
 94    }
 95
 96    public IqPacket entityTimeResponse(IqPacket request) {
 97        final IqPacket packet = request.generateResponse(IqPacket.TYPE.RESULT);
 98        Element time = packet.addChild("time", "urn:xmpp:time");
 99        final long now = System.currentTimeMillis();
100        time.addChild("utc").setContent(getTimestamp(now));
101        TimeZone ourTimezone = TimeZone.getDefault();
102        long offsetSeconds = ourTimezone.getOffset(now) / 1000;
103        long offsetMinutes = Math.abs((offsetSeconds % 3600) / 60);
104        long offsetHours = offsetSeconds / 3600;
105        String hours;
106        if (offsetHours < 0) {
107            hours = String.format(Locale.US, "%03d", offsetHours);
108        } else {
109            hours = String.format(Locale.US, "%02d", offsetHours);
110        }
111        String minutes = String.format(Locale.US, "%02d", offsetMinutes);
112        time.addChild("tzo").setContent(hours + ":" + minutes);
113        return packet;
114    }
115
116    public IqPacket purgeOfflineMessages() {
117        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
118        packet.addChild("offline", Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL).addChild("purge");
119        return packet;
120    }
121
122    protected IqPacket publish(final String node, final Element item, final Bundle options) {
123        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
124        final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB);
125        final Element publish = pubsub.addChild("publish");
126        publish.setAttribute("node", node);
127        publish.addChild(item);
128        if (options != null) {
129            final Element publishOptions = pubsub.addChild("publish-options");
130            publishOptions.addChild(Data.create(Namespace.PUBSUB_PUBLISH_OPTIONS, options));
131        }
132        return packet;
133    }
134
135    protected IqPacket publish(final String node, final Element item) {
136        return publish(node, item, null);
137    }
138
139    private IqPacket retrieve(String node, Element item) {
140        final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
141        final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB);
142        final Element items = pubsub.addChild("items");
143        items.setAttribute("node", node);
144        if (item != null) {
145            items.addChild(item);
146        }
147        return packet;
148    }
149
150    public IqPacket retrieveVcard4(final Jid jid) {
151        final IqPacket packet = retrieve("urn:xmpp:vcard4", null);
152        packet.setTo(jid);
153        return packet;
154    }
155
156    public IqPacket retrieveBookmarks() {
157        return retrieve(Namespace.BOOKMARKS2, null);
158    }
159
160    public IqPacket publishNick(String nick) {
161        final Element item = new Element("item");
162        item.setAttribute("id", "current");
163        item.addChild("nick", Namespace.NICK).setContent(nick);
164        return publish(Namespace.NICK, item);
165    }
166
167    public IqPacket deleteNode(final String node) {
168        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
169        final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB_OWNER);
170        pubsub.addChild("delete").setAttribute("node", node);
171        return packet;
172    }
173
174    public IqPacket deleteItem(final String node, final String id) {
175        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
176        final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB);
177        final Element retract = pubsub.addChild("retract");
178        retract.setAttribute("node", node);
179        retract.setAttribute("notify","true");
180        retract.addChild("item").setAttribute("id", id);
181        return packet;
182    }
183
184    public IqPacket publishAvatar(Avatar avatar, Bundle options) {
185        final Element item = new Element("item");
186        item.setAttribute("id", avatar.sha1sum);
187        final Element data = item.addChild("data", Namespace.AVATAR_DATA);
188        data.setContent(avatar.image);
189        return publish(Namespace.AVATAR_DATA, item, options);
190    }
191
192    public IqPacket publishElement(final String namespace, final Element element, String id, final Bundle options) {
193        final Element item = new Element("item");
194        item.setAttribute("id", id);
195        item.addChild(element);
196        return publish(namespace, item, options);
197    }
198
199    public IqPacket publishAvatarMetadata(final Avatar avatar, final Bundle options) {
200        final Element item = new Element("item");
201        item.setAttribute("id", avatar.sha1sum);
202        final Element metadata = item
203                .addChild("metadata", Namespace.AVATAR_METADATA);
204        final Element info = metadata.addChild("info");
205        info.setAttribute("bytes", avatar.size);
206        info.setAttribute("id", avatar.sha1sum);
207        info.setAttribute("height", avatar.height);
208        info.setAttribute("width", avatar.height);
209        info.setAttribute("type", avatar.type);
210        return publish(Namespace.AVATAR_METADATA, item, options);
211    }
212
213    public IqPacket retrievePepAvatar(final Avatar avatar) {
214        final Element item = new Element("item");
215        item.setAttribute("id", avatar.sha1sum);
216        final IqPacket packet = retrieve(Namespace.AVATAR_DATA, item);
217        packet.setTo(avatar.owner);
218        return packet;
219    }
220
221    public IqPacket retrieveVcardAvatar(final Avatar avatar) {
222        final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
223        packet.setTo(avatar.owner);
224        packet.addChild("vCard", "vcard-temp");
225        return packet;
226    }
227
228    public IqPacket retrieveVcardAvatar(final Jid to) {
229        final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
230        packet.setTo(to);
231        packet.addChild("vCard", "vcard-temp");
232        return packet;
233    }
234
235    public IqPacket retrieveAvatarMetaData(final Jid to) {
236        final IqPacket packet = retrieve("urn:xmpp:avatar:metadata", null);
237        if (to != null) {
238            packet.setTo(to);
239        }
240        return packet;
241    }
242
243    public IqPacket retrieveDeviceIds(final Jid to) {
244        final IqPacket packet = retrieve(AxolotlService.PEP_DEVICE_LIST, null);
245        if (to != null) {
246            packet.setTo(to);
247        }
248        return packet;
249    }
250
251    public IqPacket retrieveBundlesForDevice(final Jid to, final int deviceid) {
252        final IqPacket packet = retrieve(AxolotlService.PEP_BUNDLES + ":" + deviceid, null);
253        packet.setTo(to);
254        return packet;
255    }
256
257    public IqPacket retrieveVerificationForDevice(final Jid to, final int deviceid) {
258        final IqPacket packet = retrieve(AxolotlService.PEP_VERIFICATION + ":" + deviceid, null);
259        packet.setTo(to);
260        return packet;
261    }
262
263    public IqPacket publishDeviceIds(final Set<Integer> ids, final Bundle publishOptions) {
264        final Element item = new Element("item");
265        item.setAttribute("id", "current");
266        final Element list = item.addChild("list", AxolotlService.PEP_PREFIX);
267        for (Integer id : ids) {
268            final Element device = new Element("device");
269            device.setAttribute("id", id);
270            list.addChild(device);
271        }
272        return publish(AxolotlService.PEP_DEVICE_LIST, item, publishOptions);
273    }
274
275    public Element publishBookmarkItem(final Bookmark bookmark) {
276        final String name = bookmark.getBookmarkName();
277        final String nick = bookmark.getNick();
278        final String password = bookmark.getPassword();
279        final boolean autojoin = bookmark.autojoin();
280        final Element conference = new Element("conference", Namespace.BOOKMARKS2);
281        if (name != null) {
282            conference.setAttribute("name", name);
283        }
284        if (nick != null) {
285            conference.addChild("nick").setContent(nick);
286        }
287        if (password != null) {
288            conference.addChild("password").setContent(password);
289        }
290        conference.setAttribute("autojoin",String.valueOf(autojoin));
291        conference.addChild(bookmark.getExtensions());
292        return conference;
293    }
294
295    public IqPacket publishBundles(final SignedPreKeyRecord signedPreKeyRecord, final IdentityKey identityKey,
296                                   final Set<PreKeyRecord> preKeyRecords, final int deviceId, Bundle publishOptions) {
297        final Element item = new Element("item");
298        item.setAttribute("id", "current");
299        final Element bundle = item.addChild("bundle", AxolotlService.PEP_PREFIX);
300        final Element signedPreKeyPublic = bundle.addChild("signedPreKeyPublic");
301        signedPreKeyPublic.setAttribute("signedPreKeyId", signedPreKeyRecord.getId());
302        ECPublicKey publicKey = signedPreKeyRecord.getKeyPair().getPublicKey();
303        signedPreKeyPublic.setContent(Base64.encodeToString(publicKey.serialize(), Base64.NO_WRAP));
304        final Element signedPreKeySignature = bundle.addChild("signedPreKeySignature");
305        signedPreKeySignature.setContent(Base64.encodeToString(signedPreKeyRecord.getSignature(), Base64.NO_WRAP));
306        final Element identityKeyElement = bundle.addChild("identityKey");
307        identityKeyElement.setContent(Base64.encodeToString(identityKey.serialize(), Base64.NO_WRAP));
308
309        final Element prekeys = bundle.addChild("prekeys", AxolotlService.PEP_PREFIX);
310        for (PreKeyRecord preKeyRecord : preKeyRecords) {
311            final Element prekey = prekeys.addChild("preKeyPublic");
312            prekey.setAttribute("preKeyId", preKeyRecord.getId());
313            prekey.setContent(Base64.encodeToString(preKeyRecord.getKeyPair().getPublicKey().serialize(), Base64.NO_WRAP));
314        }
315
316        return publish(AxolotlService.PEP_BUNDLES + ":" + deviceId, item, publishOptions);
317    }
318
319    public IqPacket publishVerification(byte[] signature, X509Certificate[] certificates, final int deviceId) {
320        final Element item = new Element("item");
321        item.setAttribute("id", "current");
322        final Element verification = item.addChild("verification", AxolotlService.PEP_PREFIX);
323        final Element chain = verification.addChild("chain");
324        for (int i = 0; i < certificates.length; ++i) {
325            try {
326                Element certificate = chain.addChild("certificate");
327                certificate.setContent(Base64.encodeToString(certificates[i].getEncoded(), Base64.NO_WRAP));
328                certificate.setAttribute("index", i);
329            } catch (CertificateEncodingException e) {
330                Log.d(Config.LOGTAG, "could not encode certificate");
331            }
332        }
333        verification.addChild("signature").setContent(Base64.encodeToString(signature, Base64.NO_WRAP));
334        return publish(AxolotlService.PEP_VERIFICATION + ":" + deviceId, item);
335    }
336
337    public IqPacket queryMessageArchiveManagement(final MessageArchiveService.Query mam) {
338        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
339        final Element query = packet.query(mam.version.namespace);
340        query.setAttribute("queryid", mam.getQueryId());
341        final Data data = new Data();
342        data.setFormType(mam.version.namespace);
343        if (mam.muc()) {
344            packet.setTo(mam.getWith());
345        } else if (mam.getWith() != null) {
346            data.put("with", mam.getWith().toEscapedString());
347        }
348        final long start = mam.getStart();
349        final long end = mam.getEnd();
350        if (start != 0) {
351            data.put("start", getTimestamp(start));
352        }
353        if (end != 0) {
354            data.put("end", getTimestamp(end));
355        }
356        data.submit();
357        query.addChild(data);
358        Element set = query.addChild("set", "http://jabber.org/protocol/rsm");
359        if (mam.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
360            set.addChild("before").setContent(mam.getReference());
361        } else if (mam.getReference() != null) {
362            set.addChild("after").setContent(mam.getReference());
363        }
364        set.addChild("max").setContent(String.valueOf(Config.PAGE_SIZE));
365        return packet;
366    }
367
368    public IqPacket generateGetBlockList() {
369        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
370        iq.addChild("blocklist", Namespace.BLOCKING);
371
372        return iq;
373    }
374
375    public IqPacket generateSetBlockRequest(final Jid jid, final boolean reportSpam, final String serverMsgId) {
376        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
377        final Element block = iq.addChild("block", Namespace.BLOCKING);
378        final Element item = block.addChild("item").setAttribute("jid", jid);
379        if (reportSpam) {
380            final Element report = item.addChild("report", Namespace.REPORTING);
381            report.setAttribute("reason", Namespace.REPORTING_REASON_SPAM);
382            if (serverMsgId != null) {
383                final Element stanzaId = report.addChild("stanza-id", Namespace.STANZA_IDS);
384                stanzaId.setAttribute("by", jid);
385                stanzaId.setAttribute("id", serverMsgId);
386            }
387        }
388        Log.d(Config.LOGTAG, iq.toString());
389        return iq;
390    }
391
392    public IqPacket generateSetUnblockRequest(final Jid jid) {
393        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
394        final Element block = iq.addChild("unblock", Namespace.BLOCKING);
395        block.addChild("item").setAttribute("jid", jid);
396        return iq;
397    }
398
399    public IqPacket generateSetPassword(final Account account, final String newPassword) {
400        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
401        packet.setTo(account.getDomain());
402        final Element query = packet.addChild("query", Namespace.REGISTER);
403        final Jid jid = account.getJid();
404        query.addChild("username").setContent(jid.getLocal());
405        query.addChild("password").setContent(newPassword);
406        return packet;
407    }
408
409    public IqPacket changeAffiliation(Conversation conference, Jid jid, String affiliation) {
410        List<Jid> jids = new ArrayList<>();
411        jids.add(jid);
412        return changeAffiliation(conference, jids, affiliation);
413    }
414
415    public IqPacket changeAffiliation(Conversation conference, List<Jid> jids, String affiliation) {
416        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
417        packet.setTo(conference.getJid().asBareJid());
418        packet.setFrom(conference.getAccount().getJid());
419        Element query = packet.query("http://jabber.org/protocol/muc#admin");
420        for (Jid jid : jids) {
421            Element item = query.addChild("item");
422            item.setAttribute("jid", jid);
423            item.setAttribute("affiliation", affiliation);
424        }
425        return packet;
426    }
427
428    public IqPacket changeRole(Conversation conference, String nick, String role) {
429        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
430        packet.setTo(conference.getJid().asBareJid());
431        packet.setFrom(conference.getAccount().getJid());
432        Element item = packet.query("http://jabber.org/protocol/muc#admin").addChild("item");
433        item.setAttribute("nick", nick);
434        item.setAttribute("role", role);
435        return packet;
436    }
437
438    public IqPacket moderateMessage(Account account, Message m, String reason) {
439        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
440        packet.setTo(m.getConversation().getJid().asBareJid());
441        packet.setFrom(account.getJid());
442        Element moderate =
443            packet.addChild("apply-to", "urn:xmpp:fasten:0")
444                  .setAttribute("id", m.getServerMsgId())
445                  .addChild("moderate", "urn:xmpp:message-moderate:0");
446        moderate.addChild("retract", "urn:xmpp:message-retract:0");
447        moderate.addChild("reason", "urn:xmpp:message-moderate:0").setContent(reason);
448        return packet;
449    }
450
451    public IqPacket requestHttpUploadSlot(Jid host, DownloadableFile file, String name, String mime) {
452        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
453        packet.setTo(host);
454        Element request = packet.addChild("request", Namespace.HTTP_UPLOAD);
455        request.setAttribute("filename", name == null ? convertFilename(file.getName()) : name);
456        request.setAttribute("size", file.getExpectedSize());
457        request.setAttribute("content-type", mime);
458        return packet;
459    }
460
461    public IqPacket requestHttpUploadLegacySlot(Jid host, DownloadableFile file, String mime) {
462        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
463        packet.setTo(host);
464        Element request = packet.addChild("request", Namespace.HTTP_UPLOAD_LEGACY);
465        request.addChild("filename").setContent(convertFilename(file.getName()));
466        request.addChild("size").setContent(String.valueOf(file.getExpectedSize()));
467        request.addChild("content-type").setContent(mime);
468        return packet;
469    }
470
471    private static String convertFilename(String name) {
472        int pos = name.indexOf('.');
473        if (pos != -1) {
474            try {
475                UUID uuid = UUID.fromString(name.substring(0, pos));
476                ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
477                bb.putLong(uuid.getMostSignificantBits());
478                bb.putLong(uuid.getLeastSignificantBits());
479                return Base64.encodeToString(bb.array(), Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP) + name.substring(pos);
480            } catch (Exception e) {
481                return name;
482            }
483        } else {
484            return name;
485        }
486    }
487
488    public IqPacket generateCreateAccountWithCaptcha(Account account, String id, Data data) {
489        final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
490        register.setFrom(account.getJid().asBareJid());
491        register.setTo(account.getDomain());
492        register.setId(id);
493        Element query = register.query(Namespace.REGISTER);
494        if (data != null) {
495            query.addChild(data);
496        }
497        return register;
498    }
499
500    public IqPacket pushTokenToAppServer(Jid appServer, String token, String deviceId) {
501        return pushTokenToAppServer(appServer, token, deviceId, null);
502    }
503
504    public IqPacket pushTokenToAppServer(Jid appServer, String token, String deviceId, Jid muc) {
505        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
506        packet.setTo(appServer);
507        final Element command = packet.addChild("command", Namespace.COMMANDS);
508        command.setAttribute("node", "register-push-fcm");
509        command.setAttribute("action", "execute");
510        final Data data = new Data();
511        data.put("token", token);
512        data.put("android-id", deviceId);
513        if (muc != null) {
514            data.put("muc", muc.toEscapedString());
515        }
516        data.submit();
517        command.addChild(data);
518        return packet;
519    }
520
521    public IqPacket unregisterChannelOnAppServer(Jid appServer, String deviceId, String channel) {
522        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
523        packet.setTo(appServer);
524        final Element command = packet.addChild("command", Namespace.COMMANDS);
525        command.setAttribute("node", "unregister-push-fcm");
526        command.setAttribute("action", "execute");
527        final Data data = new Data();
528        data.put("channel", channel);
529        data.put("android-id", deviceId);
530        data.submit();
531        command.addChild(data);
532        return packet;
533    }
534
535    public IqPacket enablePush(final Jid jid, final String node, final String secret) {
536        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
537        Element enable = packet.addChild("enable", Namespace.PUSH);
538        enable.setAttribute("jid", jid);
539        enable.setAttribute("node", node);
540        if (secret != null) {
541            Data data = new Data();
542            data.setFormType(Namespace.PUBSUB_PUBLISH_OPTIONS);
543            data.put("secret", secret);
544            data.submit();
545            enable.addChild(data);
546        }
547        return packet;
548    }
549
550    public IqPacket disablePush(final Jid jid, final String node) {
551        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
552        Element disable = packet.addChild("disable", Namespace.PUSH);
553        disable.setAttribute("jid", jid);
554        disable.setAttribute("node", node);
555        return packet;
556    }
557
558    public IqPacket queryAffiliation(Conversation conversation, String affiliation) {
559        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
560        packet.setTo(conversation.getJid().asBareJid());
561        packet.query("http://jabber.org/protocol/muc#admin").addChild("item").setAttribute("affiliation", affiliation);
562        return packet;
563    }
564
565    public static Bundle defaultGroupChatConfiguration() {
566        Bundle options = new Bundle();
567        options.putString("muc#roomconfig_persistentroom", "1");
568        options.putString("muc#roomconfig_membersonly", "1");
569        options.putString("muc#roomconfig_publicroom", "0");
570        options.putString("muc#roomconfig_whois", "anyone");
571        options.putString("muc#roomconfig_changesubject", "0");
572        options.putString("muc#roomconfig_allowinvites", "0");
573        options.putString("muc#roomconfig_enablearchiving", "1"); //prosody
574        options.putString("mam", "1"); //ejabberd community
575        options.putString("muc#roomconfig_mam", "1"); //ejabberd saas
576        return options;
577    }
578
579    public static Bundle defaultChannelConfiguration() {
580        Bundle options = new Bundle();
581        options.putString("muc#roomconfig_persistentroom", "1");
582        options.putString("muc#roomconfig_membersonly", "0");
583        options.putString("muc#roomconfig_publicroom", "1");
584        options.putString("muc#roomconfig_whois", "moderators");
585        options.putString("muc#roomconfig_changesubject", "0");
586        options.putString("muc#roomconfig_enablearchiving", "1"); //prosody
587        options.putString("mam", "1"); //ejabberd community
588        options.putString("muc#roomconfig_mam", "1"); //ejabberd saas
589        return options;
590    }
591
592    public IqPacket requestPubsubConfiguration(Jid jid, String node) {
593        return pubsubConfiguration(jid, node, null);
594    }
595
596    public IqPacket publishPubsubConfiguration(Jid jid, String node, Data data) {
597        return pubsubConfiguration(jid, node, data);
598    }
599
600    private IqPacket pubsubConfiguration(Jid jid, String node, Data data) {
601        IqPacket packet = new IqPacket(data == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
602        packet.setTo(jid);
603        Element pubsub = packet.addChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
604        Element configure = pubsub.addChild("configure").setAttribute("node", node);
605        if (data != null) {
606            configure.addChild(data);
607        }
608        return packet;
609    }
610
611    public IqPacket queryDiscoItems(Jid jid) {
612        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
613        packet.setTo(jid);
614        packet.query(Namespace.DISCO_ITEMS);
615        return packet;
616    }
617
618    public IqPacket queryDiscoItems(Jid jid, String node) {
619        IqPacket packet = queryDiscoItems(jid);
620        final Element query = packet.query(Namespace.DISCO_ITEMS);
621        query.setAttribute("node", node);
622        return packet;
623    }
624
625    public IqPacket queryDiscoInfo(Jid jid) {
626        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
627        packet.setTo(jid);
628        packet.addChild("query",Namespace.DISCO_INFO);
629        return packet;
630    }
631
632    public IqPacket bobResponse(IqPacket request) {
633        try {
634            String bobCid = request.findChild("data", "urn:xmpp:bob").getAttribute("cid");
635            Cid cid = BobTransfer.cid(bobCid);
636            DownloadableFile f = mXmppConnectionService.getFileForCid(cid);
637            if (f == null || !f.canRead()) {
638                throw new IOException("No such file");
639            } else if (f.getSize() > 129000) {
640                final IqPacket response = request.generateResponse(IqPacket.TYPE.ERROR);
641                final Element error = response.addChild("error");
642                error.setAttribute("type", "cancel");
643                error.addChild("policy-violation", "urn:ietf:params:xml:ns:xmpp-stanzas");
644                return response;
645            } else {
646                final IqPacket response = request.generateResponse(IqPacket.TYPE.RESULT);
647                final Element data = response.addChild("data", "urn:xmpp:bob");
648                data.setAttribute("cid", bobCid);
649                data.setAttribute("type", f.getMimeType());
650                ByteArrayOutputStream b64 = new ByteArrayOutputStream((int) f.getSize() * 2);
651                Base64OutputStream b64wrap = new Base64OutputStream(b64, Base64.NO_WRAP);
652                ByteStreams.copy(new FileInputStream(f), b64wrap);
653                b64wrap.flush();
654                b64wrap.close();
655                data.setContent(b64.toString("utf-8"));
656                return response;
657            }
658        } catch (final IOException | IllegalStateException e) {
659            final IqPacket response = request.generateResponse(IqPacket.TYPE.ERROR);
660            final Element error = response.addChild("error");
661            error.setAttribute("type", "cancel");
662            error.addChild("item-not-found", "urn:ietf:params:xml:ns:xmpp-stanzas");
663            return response;
664        }
665    }
666}