浏览代码

Set `jid` as id attribute for vcards, presence and roster contacts

This allows models to be retrieved from a dict instead of via array
traversal.
JC Brand 3 年之前
父节点
当前提交
230b72139a

+ 1 - 1
src/headless/plugins/bookmarks/collection.js

@@ -91,7 +91,7 @@ const Bookmarks = {
         api.alert(
             'error', __('Error'), [__("Sorry, something went wrong while trying to save your bookmark.")]
         );
-        this.findWhere({'jid': options.jid}).destroy();
+        this.get(options.jid)?.destroy();
     },
 
     fetchBookmarksFromServer (deferred) {

+ 1 - 1
src/headless/plugins/bookmarks/index.js

@@ -53,7 +53,7 @@ converse.plugins.add('converse-bookmarks', {
             getDisplayName () {
                 const { _converse } = this.__super__;
                 if (this.get('bookmarked') && _converse.bookmarks) {
-                    const bookmark = _converse.bookmarks.findWhere({'jid': this.get('jid')});
+                    const bookmark = _converse.bookmarks.get(this.get('jid'));
                     if (bookmark) {
                         return bookmark.get('name');
                     }

+ 4 - 4
src/headless/plugins/bookmarks/utils.js

@@ -28,14 +28,14 @@ export async function initBookmarks () {
 }
 
 /**
-  * Check if the user has a bookmark with a saved nickanme
-  * for this groupchat and return it.
-  */
+ * Check if the user has a bookmark with a saved nickanme
+ * for this groupchat and return it.
+ */
 export function getNicknameFromBookmark (jid) {
     if (!_converse.bookmarks || !api.settings.get('allow_bookmarks')) {
         return null;
     }
-    const bookmark = _converse.bookmarks.findWhere({'jid': jid});
+    const bookmark = _converse.bookmarks.get(jid);
     if (bookmark) {
         return bookmark.get('nick');
     }

+ 1 - 1
src/headless/plugins/chat/model.js

@@ -62,7 +62,7 @@ const ChatBox = ModelWithContact.extend({
         this.initMessages();
 
         if (this.get('type') === _converse.PRIVATE_CHAT_TYPE) {
-            this.presence = _converse.presences.findWhere({'jid': jid}) || _converse.presences.create({'jid': jid});
+            this.presence = _converse.presences.get(jid) || _converse.presences.create({ jid });
             await this.setRosterContact(jid);
             this.presence.on('change:show', item => this.onPresenceChanged(item));
         }

+ 1 - 1
src/headless/plugins/disco/entities.js

@@ -11,7 +11,7 @@ const DiscoEntities = Collection.extend({
             this.fetch({
                 add: true,
                 success: resolve,
-                error (m, e) {
+                error (_m, e) {
                     log.error(e);
                     reject (new Error("Could not fetch disco entities"));
                 }

+ 1 - 1
src/headless/plugins/disco/entity.js

@@ -19,7 +19,7 @@ const { Strophe } = converse.env;
 const DiscoEntity = Model.extend({
     idAttribute: 'jid',
 
-    initialize (attrs, options) {
+    initialize (_, options) {
         this.waitUntilFeaturesDiscovered = getOpenPromise();
 
         this.dataforms = new Collection();

+ 0 - 2
src/headless/plugins/muc/occupant.js

@@ -1,6 +1,4 @@
-import u from '../../utils/form';
 import { Model } from '@converse/skeletor/src/model.js';
-import { _converse, api } from '../../core.js';
 
 /**
  * Represents a participant in a MUC

+ 10 - 8
src/headless/plugins/roster/contact.js

@@ -10,6 +10,8 @@ const { Strophe, $iq, $pres } = converse.env;
  * @namespace RosterContact
  */
 const RosterContact = Model.extend({
+    idAttribute: 'jid',
+
     defaults: {
         'chat_state': undefined,
         'groups': [],
@@ -23,13 +25,13 @@ const RosterContact = Model.extend({
         this.initialized = getOpenPromise();
         this.setPresence();
         const { jid } = attributes;
-        const bare_jid = Strophe.getBareJidFromJid(jid).toLowerCase();
-        attributes.jid = bare_jid;
-        this.set(Object.assign({
-            'id': bare_jid,
-            'jid': bare_jid,
-            'user_id': Strophe.getNodeFromJid(jid)
-        }, attributes));
+        this.set({
+            ...attributes,
+            ...{
+                'jid': Strophe.getBareJidFromJid(jid).toLowerCase(),
+                'user_id': Strophe.getNodeFromJid(jid)
+            }
+        });
         /**
          * When a contact's presence status has changed.
          * The presence status is either `online`, `offline`, `dnd`, `away` or `xa`.
@@ -50,7 +52,7 @@ const RosterContact = Model.extend({
 
     setPresence () {
         const jid = this.get('jid');
-        this.presence = _converse.presences.findWhere({'jid': jid}) || _converse.presences.create({'jid': jid});
+        this.presence = _converse.presences.findWhere(jid) || _converse.presences.create({ jid });
     },
 
     openChat () {

+ 18 - 16
src/headless/plugins/roster/presence.js

@@ -11,6 +11,8 @@ export const Resources = Collection.extend({'model': Resource});
 
 
 export const Presence = Model.extend({
+    idAttribute: 'jid',
+
     defaults: {
         'show': 'offline'
     },
@@ -33,21 +35,21 @@ export const Presence = Model.extend({
     },
 
     /**
-        * Return the resource with the highest priority.
-        * If multiple resources have the same priority, take the latest one.
-        * @private
-        */
+     * Return the resource with the highest priority.
+     * If multiple resources have the same priority, take the latest one.
+     * @private
+     */
     getHighestPriorityResource () {
         return this.resources.sortBy(r => `${r.get('priority')}-${r.get('timestamp')}`).reverse()[0];
     },
 
     /**
-        * Adds a new resource and it's associated attributes as taken
-        * from the passed in presence stanza.
-        * Also updates the presence if the resource has higher priority (and is newer).
-        * @private
-        * @param { XMLElement } presence: The presence stanza
-        */
+     * Adds a new resource and it's associated attributes as taken
+     * from the passed in presence stanza.
+     * Also updates the presence if the resource has higher priority (and is newer).
+     * @private
+     * @param { XMLElement } presence: The presence stanza
+     */
     addResource (presence) {
         const jid = presence.getAttribute('from'),
                 name = Strophe.getResourceFromJid(jid),
@@ -68,12 +70,12 @@ export const Presence = Model.extend({
     },
 
     /**
-        * Remove the passed in resource from the resources map.
-        * Also redetermines the presence given that there's one less
-        * resource.
-        * @private
-        * @param { string } name: The resource name
-        */
+     * Remove the passed in resource from the resources map.
+     * Also redetermines the presence given that there's one less
+     * resource.
+     * @private
+     * @param { string } name: The resource name
+     */
     removeResource (name) {
         const resource = this.resources.get(name);
         if (resource) {

+ 1 - 1
src/headless/plugins/roster/utils.js

@@ -55,7 +55,7 @@ async function populateRoster (ignore_cache=false) {
 
 
 function updateUnreadCounter (chatbox) {
-    const contact = _converse.roster?.findWhere({'jid': chatbox.get('jid')});
+    const contact = _converse.roster?.get(chatbox.get('jid'));
     contact?.save({'num_unread': chatbox.get('num_unread')});
 }
 

+ 1 - 1
src/plugins/bookmark-views/form.js

@@ -14,7 +14,7 @@ class MUCBookmarkForm extends CustomElement {
     connectedCallback () {
         super.connectedCallback();
         this.model = _converse.chatboxes.get(this.jid);
-        this.bookmark  = _converse.bookmarks.findWhere({ 'jid': this.model.get('jid') });
+        this.bookmark  = _converse.bookmarks.get(this.model.get('jid'));
     }
 
     render () {

+ 2 - 2
src/plugins/bookmark-views/tests/bookmarks.js

@@ -488,8 +488,8 @@ describe("Bookmarks", function () {
         await u.waitUntil(() => _converse.bookmarks.onBookmarksReceived.calls.count());
         await _converse.api.waitUntil('bookmarksInitialized');
         expect(_converse.bookmarks.models.length).toBe(2);
-        expect(_converse.bookmarks.findWhere({'jid': 'theplay@conference.shakespeare.lit'}).get('autojoin')).toBe(true);
-        expect(_converse.bookmarks.findWhere({'jid': 'another@conference.shakespeare.lit'}).get('autojoin')).toBe(false);
+        expect(_converse.bookmarks.get('theplay@conference.shakespeare.lit').get('autojoin')).toBe(true);
+        expect(_converse.bookmarks.get('another@conference.shakespeare.lit').get('autojoin')).toBe(false);
     }));
 
     describe("The bookmarks list", function () {

+ 3 - 3
src/plugins/omemo/devicelist.js

@@ -53,7 +53,7 @@ const DeviceList = Model.extend({
             this._devices_promise = new Promise(resolve => {
                 this.devices.fetch({
                     'success': c => resolve(this.onDevicesFound(c)),
-                    'error': (m, e) => {
+                    'error': (_, e) => {
                         log.error(e);
                         resolve();
                     }
@@ -65,7 +65,7 @@ const DeviceList = Model.extend({
 
     async getOwnDeviceId () {
         let device_id = _converse.omemo_store.get('device_id');
-        if (!this.devices.findWhere({ 'id': device_id })) {
+        if (!this.devices.get(device_id)) {
             // Generate a new bundle if we cannot find our device
             await _converse.omemo_store.generateBundle();
             device_id = _converse.omemo_store.get('device_id');
@@ -124,7 +124,7 @@ const DeviceList = Model.extend({
         await Promise.all(device_ids.map(id => this.devices.get(id)).map(d =>
             new Promise(resolve => d.destroy({
                 'success': resolve,
-                'error': (m, e) => { log.error(e); resolve(); }
+                'error': (_, e) => { log.error(e); resolve(); }
             }))
         ));
         return this.publishDevices();

+ 1 - 1
src/plugins/rosterview/utils.js

@@ -2,7 +2,7 @@ import { _converse, api } from "@converse/headless/core";
 
 
 export function highlightRosterItem (chatbox) {
-    _converse.roster?.findWhere({'jid': chatbox.get('jid')})?.trigger('highlight');
+    _converse.roster?.get(chatbox.get('jid'))?.trigger('highlight');
 }