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 retrieveMds() {
161        return retrieve(Namespace.MDS_DISPLAYED, null);
162    }
163
164    public IqPacket publishNick(String nick) {
165        final Element item = new Element("item");
166        item.setAttribute("id", "current");
167        item.addChild("nick", Namespace.NICK).setContent(nick);
168        return publish(Namespace.NICK, item);
169    }
170
171    public IqPacket deleteNode(final String node) {
172        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
173        final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB_OWNER);
174        pubsub.addChild("delete").setAttribute("node", node);
175        return packet;
176    }
177
178    public IqPacket deleteItem(final String node, final String id) {
179        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
180        final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB);
181        final Element retract = pubsub.addChild("retract");
182        retract.setAttribute("node", node);
183        retract.setAttribute("notify","true");
184        retract.addChild("item").setAttribute("id", id);
185        return packet;
186    }
187
188    public IqPacket publishAvatar(Avatar avatar, Bundle options) {
189        final Element item = new Element("item");
190        item.setAttribute("id", avatar.sha1sum);
191        final Element data = item.addChild("data", Namespace.AVATAR_DATA);
192        data.setContent(avatar.image);
193        return publish(Namespace.AVATAR_DATA, item, options);
194    }
195
196    public IqPacket publishElement(final String namespace, final Element element, String id, final Bundle options) {
197        final Element item = new Element("item");
198        item.setAttribute("id", id);
199        item.addChild(element);
200        return publish(namespace, item, options);
201    }
202
203    public IqPacket publishAvatarMetadata(final Avatar avatar, final Bundle options) {
204        final Element item = new Element("item");
205        item.setAttribute("id", avatar.sha1sum);
206        final Element metadata = item
207                .addChild("metadata", Namespace.AVATAR_METADATA);
208        final Element info = metadata.addChild("info");
209        info.setAttribute("bytes", avatar.size);
210        info.setAttribute("id", avatar.sha1sum);
211        info.setAttribute("height", avatar.height);
212        info.setAttribute("width", avatar.height);
213        info.setAttribute("type", avatar.type);
214        return publish(Namespace.AVATAR_METADATA, item, options);
215    }
216
217    public IqPacket retrievePepAvatar(final Avatar avatar) {
218        final Element item = new Element("item");
219        item.setAttribute("id", avatar.sha1sum);
220        final IqPacket packet = retrieve(Namespace.AVATAR_DATA, item);
221        packet.setTo(avatar.owner);
222        return packet;
223    }
224
225    public IqPacket retrieveVcardAvatar(final Avatar avatar) {
226        final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
227        packet.setTo(avatar.owner);
228        packet.addChild("vCard", "vcard-temp");
229        return packet;
230    }
231
232    public IqPacket retrieveVcardAvatar(final Jid to) {
233        final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
234        packet.setTo(to);
235        packet.addChild("vCard", "vcard-temp");
236        return packet;
237    }
238
239    public IqPacket retrieveAvatarMetaData(final Jid to) {
240        final IqPacket packet = retrieve("urn:xmpp:avatar:metadata", null);
241        if (to != null) {
242            packet.setTo(to);
243        }
244        return packet;
245    }
246
247    public IqPacket retrieveDeviceIds(final Jid to) {
248        final IqPacket packet = retrieve(AxolotlService.PEP_DEVICE_LIST, null);
249        if (to != null) {
250            packet.setTo(to);
251        }
252        return packet;
253    }
254
255    public IqPacket retrieveBundlesForDevice(final Jid to, final int deviceid) {
256        final IqPacket packet = retrieve(AxolotlService.PEP_BUNDLES + ":" + deviceid, null);
257        packet.setTo(to);
258        return packet;
259    }
260
261    public IqPacket retrieveVerificationForDevice(final Jid to, final int deviceid) {
262        final IqPacket packet = retrieve(AxolotlService.PEP_VERIFICATION + ":" + deviceid, null);
263        packet.setTo(to);
264        return packet;
265    }
266
267    public IqPacket publishDeviceIds(final Set<Integer> ids, final Bundle publishOptions) {
268        final Element item = new Element("item");
269        item.setAttribute("id", "current");
270        final Element list = item.addChild("list", AxolotlService.PEP_PREFIX);
271        for (Integer id : ids) {
272            final Element device = new Element("device");
273            device.setAttribute("id", id);
274            list.addChild(device);
275        }
276        return publish(AxolotlService.PEP_DEVICE_LIST, item, publishOptions);
277    }
278
279    public Element publishBookmarkItem(final Bookmark bookmark) {
280        final String name = bookmark.getBookmarkName();
281        final String nick = bookmark.getNick();
282        final String password = bookmark.getPassword();
283        final boolean autojoin = bookmark.autojoin();
284        final Element conference = new Element("conference", Namespace.BOOKMARKS2);
285        if (name != null) {
286            conference.setAttribute("name", name);
287        }
288        if (nick != null) {
289            conference.addChild("nick").setContent(nick);
290        }
291        if (password != null) {
292            conference.addChild("password").setContent(password);
293        }
294        conference.setAttribute("autojoin",String.valueOf(autojoin));
295        conference.addChild(bookmark.getExtensions());
296        return conference;
297    }
298
299    public Element mdsDisplayed(final String stanzaId, final Conversation conversation) {
300        final Jid by;
301        if (conversation.getMode() == Conversation.MODE_MULTI) {
302            by = conversation.getJid().asBareJid();
303        } else {
304            by = conversation.getAccount().getJid().asBareJid();
305        }
306        return mdsDisplayed(stanzaId, by);
307    }
308
309    private Element mdsDisplayed(final String stanzaId, final Jid by) {
310        final Element displayed = new Element("displayed", Namespace.MDS_DISPLAYED);
311        final Element stanzaIdElement = displayed.addChild("stanza-id", Namespace.STANZA_IDS);
312        stanzaIdElement.setAttribute("id", stanzaId);
313        stanzaIdElement.setAttribute("by", by);
314        return displayed;
315    }
316
317    public IqPacket publishBundles(final SignedPreKeyRecord signedPreKeyRecord, final IdentityKey identityKey,
318                                   final Set<PreKeyRecord> preKeyRecords, final int deviceId, Bundle publishOptions) {
319        final Element item = new Element("item");
320        item.setAttribute("id", "current");
321        final Element bundle = item.addChild("bundle", AxolotlService.PEP_PREFIX);
322        final Element signedPreKeyPublic = bundle.addChild("signedPreKeyPublic");
323        signedPreKeyPublic.setAttribute("signedPreKeyId", signedPreKeyRecord.getId());
324        ECPublicKey publicKey = signedPreKeyRecord.getKeyPair().getPublicKey();
325        signedPreKeyPublic.setContent(Base64.encodeToString(publicKey.serialize(), Base64.NO_WRAP));
326        final Element signedPreKeySignature = bundle.addChild("signedPreKeySignature");
327        signedPreKeySignature.setContent(Base64.encodeToString(signedPreKeyRecord.getSignature(), Base64.NO_WRAP));
328        final Element identityKeyElement = bundle.addChild("identityKey");
329        identityKeyElement.setContent(Base64.encodeToString(identityKey.serialize(), Base64.NO_WRAP));
330
331        final Element prekeys = bundle.addChild("prekeys", AxolotlService.PEP_PREFIX);
332        for (PreKeyRecord preKeyRecord : preKeyRecords) {
333            final Element prekey = prekeys.addChild("preKeyPublic");
334            prekey.setAttribute("preKeyId", preKeyRecord.getId());
335            prekey.setContent(Base64.encodeToString(preKeyRecord.getKeyPair().getPublicKey().serialize(), Base64.NO_WRAP));
336        }
337
338        return publish(AxolotlService.PEP_BUNDLES + ":" + deviceId, item, publishOptions);
339    }
340
341    public IqPacket publishVerification(byte[] signature, X509Certificate[] certificates, final int deviceId) {
342        final Element item = new Element("item");
343        item.setAttribute("id", "current");
344        final Element verification = item.addChild("verification", AxolotlService.PEP_PREFIX);
345        final Element chain = verification.addChild("chain");
346        for (int i = 0; i < certificates.length; ++i) {
347            try {
348                Element certificate = chain.addChild("certificate");
349                certificate.setContent(Base64.encodeToString(certificates[i].getEncoded(), Base64.NO_WRAP));
350                certificate.setAttribute("index", i);
351            } catch (CertificateEncodingException e) {
352                Log.d(Config.LOGTAG, "could not encode certificate");
353            }
354        }
355        verification.addChild("signature").setContent(Base64.encodeToString(signature, Base64.NO_WRAP));
356        return publish(AxolotlService.PEP_VERIFICATION + ":" + deviceId, item);
357    }
358
359    public IqPacket queryMessageArchiveManagement(final MessageArchiveService.Query mam) {
360        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
361        final Element query = packet.query(mam.version.namespace);
362        query.setAttribute("queryid", mam.getQueryId());
363        final Data data = new Data();
364        data.setFormType(mam.version.namespace);
365        if (mam.muc()) {
366            packet.setTo(mam.getWith());
367        } else if (mam.getWith() != null) {
368            data.put("with", mam.getWith().toEscapedString());
369        }
370        final long start = mam.getStart();
371        final long end = mam.getEnd();
372        if (start != 0) {
373            data.put("start", getTimestamp(start));
374        }
375        if (end != 0) {
376            data.put("end", getTimestamp(end));
377        }
378        data.submit();
379        query.addChild(data);
380        Element set = query.addChild("set", "http://jabber.org/protocol/rsm");
381        if (mam.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
382            set.addChild("before").setContent(mam.getReference());
383        } else if (mam.getReference() != null) {
384            set.addChild("after").setContent(mam.getReference());
385        }
386        set.addChild("max").setContent(String.valueOf(Config.PAGE_SIZE));
387        return packet;
388    }
389
390    public IqPacket generateGetBlockList() {
391        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
392        iq.addChild("blocklist", Namespace.BLOCKING);
393
394        return iq;
395    }
396
397    public IqPacket generateSetBlockRequest(final Jid jid, final boolean reportSpam, final String serverMsgId) {
398        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
399        final Element block = iq.addChild("block", Namespace.BLOCKING);
400        final Element item = block.addChild("item").setAttribute("jid", jid);
401        if (reportSpam) {
402            final Element report = item.addChild("report", Namespace.REPORTING);
403            report.setAttribute("reason", Namespace.REPORTING_REASON_SPAM);
404            if (serverMsgId != null) {
405                final Element stanzaId = report.addChild("stanza-id", Namespace.STANZA_IDS);
406                stanzaId.setAttribute("by", jid);
407                stanzaId.setAttribute("id", serverMsgId);
408            }
409        }
410        Log.d(Config.LOGTAG, iq.toString());
411        return iq;
412    }
413
414    public IqPacket generateSetUnblockRequest(final Jid jid) {
415        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
416        final Element block = iq.addChild("unblock", Namespace.BLOCKING);
417        block.addChild("item").setAttribute("jid", jid);
418        return iq;
419    }
420
421    public IqPacket generateSetPassword(final Account account, final String newPassword) {
422        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
423        packet.setTo(account.getDomain());
424        final Element query = packet.addChild("query", Namespace.REGISTER);
425        final Jid jid = account.getJid();
426        query.addChild("username").setContent(jid.getLocal());
427        query.addChild("password").setContent(newPassword);
428        return packet;
429    }
430
431    public IqPacket changeAffiliation(Conversation conference, Jid jid, String affiliation) {
432        List<Jid> jids = new ArrayList<>();
433        jids.add(jid);
434        return changeAffiliation(conference, jids, affiliation);
435    }
436
437    public IqPacket changeAffiliation(Conversation conference, List<Jid> jids, String affiliation) {
438        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
439        packet.setTo(conference.getJid().asBareJid());
440        packet.setFrom(conference.getAccount().getJid());
441        Element query = packet.query("http://jabber.org/protocol/muc#admin");
442        for (Jid jid : jids) {
443            Element item = query.addChild("item");
444            item.setAttribute("jid", jid);
445            item.setAttribute("affiliation", affiliation);
446        }
447        return packet;
448    }
449
450    public IqPacket changeRole(Conversation conference, String nick, String role) {
451        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
452        packet.setTo(conference.getJid().asBareJid());
453        packet.setFrom(conference.getAccount().getJid());
454        Element item = packet.query("http://jabber.org/protocol/muc#admin").addChild("item");
455        item.setAttribute("nick", nick);
456        item.setAttribute("role", role);
457        return packet;
458    }
459
460    public IqPacket moderateMessage(Account account, Message m, String reason) {
461        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
462        packet.setTo(m.getConversation().getJid().asBareJid());
463        packet.setFrom(account.getJid());
464        Element moderate =
465            packet.addChild("apply-to", "urn:xmpp:fasten:0")
466                  .setAttribute("id", m.getServerMsgId())
467                  .addChild("moderate", "urn:xmpp:message-moderate:0");
468        moderate.addChild("retract", "urn:xmpp:message-retract:0");
469        moderate.addChild("reason", "urn:xmpp:message-moderate:0").setContent(reason);
470        return packet;
471    }
472
473    public IqPacket requestHttpUploadSlot(Jid host, DownloadableFile file, String name, String mime) {
474        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
475        packet.setTo(host);
476        Element request = packet.addChild("request", Namespace.HTTP_UPLOAD);
477        request.setAttribute("filename", name == null ? convertFilename(file.getName()) : name);
478        request.setAttribute("size", file.getExpectedSize());
479        request.setAttribute("content-type", mime);
480        return packet;
481    }
482
483    public IqPacket requestHttpUploadLegacySlot(Jid host, DownloadableFile file, String mime) {
484        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
485        packet.setTo(host);
486        Element request = packet.addChild("request", Namespace.HTTP_UPLOAD_LEGACY);
487        request.addChild("filename").setContent(convertFilename(file.getName()));
488        request.addChild("size").setContent(String.valueOf(file.getExpectedSize()));
489        request.addChild("content-type").setContent(mime);
490        return packet;
491    }
492
493    private static String convertFilename(String name) {
494        int pos = name.indexOf('.');
495        if (pos != -1) {
496            try {
497                UUID uuid = UUID.fromString(name.substring(0, pos));
498                ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
499                bb.putLong(uuid.getMostSignificantBits());
500                bb.putLong(uuid.getLeastSignificantBits());
501                return Base64.encodeToString(bb.array(), Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP) + name.substring(pos);
502            } catch (Exception e) {
503                return name;
504            }
505        } else {
506            return name;
507        }
508    }
509
510    public IqPacket generateCreateAccountWithCaptcha(Account account, String id, Data data) {
511        final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
512        register.setFrom(account.getJid().asBareJid());
513        register.setTo(account.getDomain());
514        register.setId(id);
515        Element query = register.query(Namespace.REGISTER);
516        if (data != null) {
517            query.addChild(data);
518        }
519        return register;
520    }
521
522    public IqPacket pushTokenToAppServer(Jid appServer, String token, String deviceId) {
523        return pushTokenToAppServer(appServer, token, deviceId, null);
524    }
525
526    public IqPacket pushTokenToAppServer(Jid appServer, String token, String deviceId, Jid muc) {
527        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
528        packet.setTo(appServer);
529        final Element command = packet.addChild("command", Namespace.COMMANDS);
530        command.setAttribute("node", "register-push-fcm");
531        command.setAttribute("action", "execute");
532        final Data data = new Data();
533        data.put("token", token);
534        data.put("android-id", deviceId);
535        if (muc != null) {
536            data.put("muc", muc.toEscapedString());
537        }
538        data.submit();
539        command.addChild(data);
540        return packet;
541    }
542
543    public IqPacket unregisterChannelOnAppServer(Jid appServer, String deviceId, String channel) {
544        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
545        packet.setTo(appServer);
546        final Element command = packet.addChild("command", Namespace.COMMANDS);
547        command.setAttribute("node", "unregister-push-fcm");
548        command.setAttribute("action", "execute");
549        final Data data = new Data();
550        data.put("channel", channel);
551        data.put("android-id", deviceId);
552        data.submit();
553        command.addChild(data);
554        return packet;
555    }
556
557    public IqPacket enablePush(final Jid jid, final String node, final String secret) {
558        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
559        Element enable = packet.addChild("enable", Namespace.PUSH);
560        enable.setAttribute("jid", jid);
561        enable.setAttribute("node", node);
562        if (secret != null) {
563            Data data = new Data();
564            data.setFormType(Namespace.PUBSUB_PUBLISH_OPTIONS);
565            data.put("secret", secret);
566            data.submit();
567            enable.addChild(data);
568        }
569        return packet;
570    }
571
572    public IqPacket disablePush(final Jid jid, final String node) {
573        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
574        Element disable = packet.addChild("disable", Namespace.PUSH);
575        disable.setAttribute("jid", jid);
576        disable.setAttribute("node", node);
577        return packet;
578    }
579
580    public IqPacket queryAffiliation(Conversation conversation, String affiliation) {
581        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
582        packet.setTo(conversation.getJid().asBareJid());
583        packet.query("http://jabber.org/protocol/muc#admin").addChild("item").setAttribute("affiliation", affiliation);
584        return packet;
585    }
586
587    public static Bundle defaultGroupChatConfiguration() {
588        Bundle options = new Bundle();
589        options.putString("muc#roomconfig_persistentroom", "1");
590        options.putString("muc#roomconfig_membersonly", "1");
591        options.putString("muc#roomconfig_publicroom", "0");
592        options.putString("muc#roomconfig_whois", "anyone");
593        options.putString("muc#roomconfig_changesubject", "0");
594        options.putString("muc#roomconfig_allowinvites", "0");
595        options.putString("muc#roomconfig_enablearchiving", "1"); //prosody
596        options.putString("mam", "1"); //ejabberd community
597        options.putString("muc#roomconfig_mam", "1"); //ejabberd saas
598        return options;
599    }
600
601    public static Bundle defaultChannelConfiguration() {
602        Bundle options = new Bundle();
603        options.putString("muc#roomconfig_persistentroom", "1");
604        options.putString("muc#roomconfig_membersonly", "0");
605        options.putString("muc#roomconfig_publicroom", "1");
606        options.putString("muc#roomconfig_whois", "moderators");
607        options.putString("muc#roomconfig_changesubject", "0");
608        options.putString("muc#roomconfig_enablearchiving", "1"); //prosody
609        options.putString("mam", "1"); //ejabberd community
610        options.putString("muc#roomconfig_mam", "1"); //ejabberd saas
611        return options;
612    }
613
614    public IqPacket requestPubsubConfiguration(Jid jid, String node) {
615        return pubsubConfiguration(jid, node, null);
616    }
617
618    public IqPacket publishPubsubConfiguration(Jid jid, String node, Data data) {
619        return pubsubConfiguration(jid, node, data);
620    }
621
622    private IqPacket pubsubConfiguration(Jid jid, String node, Data data) {
623        IqPacket packet = new IqPacket(data == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
624        packet.setTo(jid);
625        Element pubsub = packet.addChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
626        Element configure = pubsub.addChild("configure").setAttribute("node", node);
627        if (data != null) {
628            configure.addChild(data);
629        }
630        return packet;
631    }
632
633    public IqPacket queryDiscoItems(Jid jid) {
634        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
635        packet.setTo(jid);
636        packet.query(Namespace.DISCO_ITEMS);
637        return packet;
638    }
639
640    public IqPacket queryDiscoItems(Jid jid, String node) {
641        IqPacket packet = queryDiscoItems(jid);
642        final Element query = packet.query(Namespace.DISCO_ITEMS);
643        query.setAttribute("node", node);
644        return packet;
645    }
646
647    public IqPacket queryDiscoInfo(Jid jid) {
648        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
649        packet.setTo(jid);
650        packet.addChild("query",Namespace.DISCO_INFO);
651        return packet;
652    }
653
654    public IqPacket bobResponse(IqPacket request) {
655        try {
656            String bobCid = request.findChild("data", "urn:xmpp:bob").getAttribute("cid");
657            Cid cid = BobTransfer.cid(bobCid);
658            DownloadableFile f = mXmppConnectionService.getFileForCid(cid);
659            if (f == null || !f.canRead()) {
660                throw new IOException("No such file");
661            } else if (f.getSize() > 129000) {
662                final IqPacket response = request.generateResponse(IqPacket.TYPE.ERROR);
663                final Element error = response.addChild("error");
664                error.setAttribute("type", "cancel");
665                error.addChild("policy-violation", "urn:ietf:params:xml:ns:xmpp-stanzas");
666                return response;
667            } else {
668                final IqPacket response = request.generateResponse(IqPacket.TYPE.RESULT);
669                final Element data = response.addChild("data", "urn:xmpp:bob");
670                data.setAttribute("cid", bobCid);
671                data.setAttribute("type", f.getMimeType());
672                ByteArrayOutputStream b64 = new ByteArrayOutputStream((int) f.getSize() * 2);
673                Base64OutputStream b64wrap = new Base64OutputStream(b64, Base64.NO_WRAP);
674                ByteStreams.copy(new FileInputStream(f), b64wrap);
675                b64wrap.flush();
676                b64wrap.close();
677                data.setContent(b64.toString("utf-8"));
678                return response;
679            }
680        } catch (final IOException | IllegalStateException e) {
681            final IqPacket response = request.generateResponse(IqPacket.TYPE.ERROR);
682            final Element error = response.addChild("error");
683            error.setAttribute("type", "cancel");
684            error.addChild("item-not-found", "urn:ietf:params:xml:ns:xmpp-stanzas");
685            return response;
686        }
687    }
688}