view nickname.js @ 0:2a8d4e8600d0

Initial commit.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Fri, 21 Dec 2018 21:34:17 +0100
parents
children d6df73b466f6
line wrap: on
line source

'use strict';

function initNickname(connection) {
    const nick_input = document.getElementById('nick');
    const nick_change = document.getElementById('nick-change');

    const iq = $iq({type: 'get'})
        .c('pubsub', {xmlns: 'http://jabber.org/protocol/pubsub'})
            .c('items', {node: 'http://jabber.org/protocol/nick'});
    connection.sendIQ(iq, onNickname, onNicknameRetrievalError.bind(null, 'PubSub query failed.'));

    function nsResolver(prefix) {
        return {
            pubsub: 'http://jabber.org/protocol/pubsub',
            nickname: 'http://jabber.org/protocol/nick',
        }[prefix] || null;
    }

    function parseXPath(elem, xpath)
    {
        return elem.getRootNode().evaluate(xpath, elem, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    }

    function onNickname(result_iq)
    {
        const item = parseXPath(result_iq, './pubsub:pubsub/pubsub:items/pubsub:item');
        if (item == null)
            return onNicknameRetrievalError('no item found.');
        const id = item.getAttributeNS(null, 'id');
        const nick = parseXPath(item, './nickname:nick');
        nick_input.value = nick.textContent;
    }

    function onNicknameRetrievalError(string)
    {
        console.log('Failed to retrieve nickname: ' + string);
    }

    nick_change.addEventListener('click', function (evt) {
        const iq = $iq({type: 'set'})
            .c('pubsub', {xmlns: 'http://jabber.org/protocol/pubsub'})
                .c('publish', {node: 'http://jabber.org/protocol/nick'})
                    .c('item', {id: 'current'})
                        .c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
                            .t(nick_input.value);
        connection.sendIQ(iq, onNicknameChanged, onNicknameChangeError);
    });

    function onNicknameChanged(iq)
    {
        console.log("onNicknameChanged", iq);
    }

    function onNicknameChangeError(iq)
    {
        console.log("onNicknameChangeError", iq);
    }
}