gajim.org
Sign In
Sign Up
Sign In
Sign Up
Manage this list
×
Keyboard Shortcuts
Thread View
j
: Next unread message
k
: Previous unread message
j a
: Jump to all threads
j l
: Jump to MailingList overview
2026
October
September
August
July
June
May
April
March
February
January
2025
December
November
October
September
August
July
June
May
April
March
February
January
2024
December
November
October
September
August
July
June
May
April
March
February
January
2023
December
November
October
September
August
July
June
May
April
March
February
January
2022
December
November
October
September
August
July
June
May
April
March
February
January
2021
December
November
October
September
August
July
June
May
April
March
February
January
2020
December
November
October
September
August
July
June
May
April
March
February
January
2019
December
November
October
September
August
July
June
May
April
March
February
January
2018
December
November
October
September
August
July
June
May
April
March
February
January
2017
December
November
October
September
August
July
June
May
April
March
February
January
2016
December
November
October
September
August
July
June
May
April
March
February
January
2015
December
November
October
September
August
July
June
May
April
March
February
January
2014
December
November
October
September
August
July
June
May
April
March
February
January
2013
December
November
October
September
August
July
June
May
April
March
February
January
2012
December
November
October
September
August
July
June
May
April
March
February
January
2011
December
November
October
September
August
July
June
May
April
March
February
January
2010
December
November
October
September
August
July
June
May
April
March
February
January
2009
December
November
October
September
August
July
June
May
April
March
February
January
2008
December
November
October
September
August
July
June
May
April
March
February
January
2007
December
November
October
September
August
July
June
May
April
March
February
January
2006
December
November
October
September
August
July
June
May
April
List overview
Download
Commits
----- 2026 -----
October 2026
September 2026
August 2026
July 2026
June 2026
May 2026
April 2026
March 2026
February 2026
January 2026
----- 2025 -----
December 2025
November 2025
October 2025
September 2025
August 2025
July 2025
June 2025
May 2025
April 2025
March 2025
February 2025
January 2025
----- 2024 -----
December 2024
November 2024
October 2024
September 2024
August 2024
July 2024
June 2024
May 2024
April 2024
March 2024
February 2024
January 2024
----- 2023 -----
December 2023
November 2023
October 2023
September 2023
August 2023
July 2023
June 2023
May 2023
April 2023
March 2023
February 2023
January 2023
----- 2022 -----
December 2022
November 2022
October 2022
September 2022
August 2022
July 2022
June 2022
May 2022
April 2022
March 2022
February 2022
January 2022
----- 2021 -----
December 2021
November 2021
October 2021
September 2021
August 2021
July 2021
June 2021
May 2021
April 2021
March 2021
February 2021
January 2021
----- 2020 -----
December 2020
November 2020
October 2020
September 2020
August 2020
July 2020
June 2020
May 2020
April 2020
March 2020
February 2020
January 2020
----- 2019 -----
December 2019
November 2019
October 2019
September 2019
August 2019
July 2019
June 2019
May 2019
April 2019
March 2019
February 2019
January 2019
----- 2018 -----
December 2018
November 2018
October 2018
September 2018
August 2018
July 2018
June 2018
May 2018
April 2018
March 2018
February 2018
January 2018
----- 2017 -----
December 2017
November 2017
October 2017
September 2017
August 2017
July 2017
June 2017
May 2017
April 2017
March 2017
February 2017
January 2017
----- 2016 -----
December 2016
November 2016
October 2016
September 2016
August 2016
July 2016
June 2016
May 2016
April 2016
March 2016
February 2016
January 2016
----- 2015 -----
December 2015
November 2015
October 2015
September 2015
August 2015
July 2015
June 2015
May 2015
April 2015
March 2015
February 2015
January 2015
----- 2014 -----
December 2014
November 2014
October 2014
September 2014
August 2014
July 2014
June 2014
May 2014
April 2014
March 2014
February 2014
January 2014
----- 2013 -----
December 2013
November 2013
October 2013
September 2013
August 2013
July 2013
June 2013
May 2013
April 2013
March 2013
February 2013
January 2013
----- 2012 -----
December 2012
November 2012
October 2012
September 2012
August 2012
July 2012
June 2012
May 2012
April 2012
March 2012
February 2012
January 2012
----- 2011 -----
December 2011
November 2011
October 2011
September 2011
August 2011
July 2011
June 2011
May 2011
April 2011
March 2011
February 2011
January 2011
----- 2010 -----
December 2010
November 2010
October 2010
September 2010
August 2010
July 2010
June 2010
May 2010
April 2010
March 2010
February 2010
January 2010
----- 2009 -----
December 2009
November 2009
October 2009
September 2009
August 2009
July 2009
June 2009
May 2009
April 2009
March 2009
February 2009
January 2009
----- 2008 -----
December 2008
November 2008
October 2008
September 2008
August 2008
July 2008
June 2008
May 2008
April 2008
March 2008
February 2008
January 2008
----- 2007 -----
December 2007
November 2007
October 2007
September 2007
August 2007
July 2007
June 2007
May 2007
April 2007
March 2007
February 2007
January 2007
----- 2006 -----
December 2006
November 2006
October 2006
September 2006
August 2006
July 2006
June 2006
May 2006
April 2006
commits@gajim.org
17632 discussions
Start a n
N
ew thread
[Git][gajim/python-nbxmpp][master] 1.91.0
by Philipp Hörist
25 Sep '20
25 Sep '20
Philipp Hörist pushed to branch master at gajim / python-nbxmpp Commits: 29212faa by lovetox at 2020-09-25T17:02:52+02:00 1.91.0 - - - - - 2 changed files: - nbxmpp/__init__.py - setup.cfg Changes: ===================================== nbxmpp/__init__.py ===================================== @@ -4,4 +4,4 @@ from .protocol import * gi.require_version('Soup', '2.4') -__version__ = "1.0.2" +__version__ = "1.91.0" ===================================== setup.cfg ===================================== @@ -1,6 +1,6 @@ [metadata] name = nbxmpp -version = 1.0.2 +version = 1.91.0 description = XMPP Library author = Yann Leboulanger, Philipp Hoerist author_email = gajim-devel(a)gajim.org View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/commit/29212faaaa0472960770553b…
-- View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/commit/29212faaaa0472960770553b…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/python-nbxmpp] Deleted branch tasks
by Philipp Hörist
25 Sep '20
25 Sep '20
Philipp Hörist deleted branch tasks at gajim / python-nbxmpp -- You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/python-nbxmpp][master] 2 commits: Discovery: Use tasks
by Philipp Hörist
25 Sep '20
25 Sep '20
Philipp Hörist pushed to branch master at gajim / python-nbxmpp Commits: bcb25603 by lovetox at 2020-09-24T14:31:39+02:00 Discovery: Use tasks - - - - - aa662a44 by lovetox at 2020-09-25T16:46:41+02:00 MUC: Add request_info() This method returns the disco info and vcard of a MUC - - - - - 3 changed files: - nbxmpp/modules/discovery.py - nbxmpp/modules/muc.py - nbxmpp/modules/util.py Changes: ===================================== nbxmpp/modules/discovery.py ===================================== @@ -20,7 +20,6 @@ import logging from nbxmpp.protocol import Iq from nbxmpp.namespaces import Namespace -from nbxmpp.protocol import isResultNode from nbxmpp.protocol import ErrorNode from nbxmpp.protocol import ERR_ITEM_NOT_FOUND from nbxmpp.protocol import NodeProcessed @@ -31,9 +30,9 @@ from nbxmpp.structs import DiscoInfo from nbxmpp.structs import DiscoItems from nbxmpp.structs import DiscoItem from nbxmpp.structs import StanzaHandler -from nbxmpp.util import call_on_response -from nbxmpp.util import callback from nbxmpp.util import raise_error +from nbxmpp.task import iq_request_task +from nbxmpp.errors import StanzaError log = logging.getLogger('nbxmpp.m.discovery') @@ -59,27 +58,28 @@ class Discovery(BaseModule): client.send_stanza(iq) raise NodeProcessed - @call_on_response('_disco_info_received') + @iq_request_task def disco_info(self, jid, node=None): + _task = yield + self._log.info('Disco info: %s, node: %s', jid, node) - return get_disco_request(Namespace.DISCO_INFO, jid, node) - @callback - def _disco_info_received(self, stanza): - if not isResultNode(stanza): - return raise_error(self._log.info, stanza) - return parse_disco_info(stanza) + response = yield get_disco_request(Namespace.DISCO_INFO, jid, node) + if response.isError(): + raise StanzaError(response) + yield parse_disco_info(response) - @call_on_response('_disco_items_received') + @iq_request_task def disco_items(self, jid, node=None): + _task = yield + self._log.info('Disco items: %s, node: %s', jid, node) - return get_disco_request(Namespace.DISCO_ITEMS, jid, node) - @callback - def _disco_items_received(self, stanza): - if not isResultNode(stanza): - return raise_error(self._log.info, stanza) - return parse_disco_items(stanza) + response = yield get_disco_request(Namespace.DISCO_ITEMS, jid, node) + if response.isError(): + raise StanzaError(response) + yield parse_disco_items(response) + def parse_disco_info(stanza, timestamp=None): ===================================== nbxmpp/modules/muc.py ===================================== @@ -15,6 +15,8 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <
http://www.gnu.org/licenses/
>. +from dataclasses import dataclass + from nbxmpp.namespaces import Namespace from nbxmpp.protocol import ERR_NOT_ACCEPTABLE from nbxmpp.protocol import JID @@ -41,14 +43,24 @@ from nbxmpp.structs import CommonResult from nbxmpp.structs import MucConfigResult from nbxmpp.structs import MucUserData from nbxmpp.structs import MucDestroyed +from nbxmpp.task import iq_request_task from nbxmpp.util import call_on_response from nbxmpp.util import callback from nbxmpp.util import raise_error +from nbxmpp.errors import is_error +from nbxmpp.modules.util import raise_if_error +from nbxmpp.modules.util import parse_xmpp_uri from nbxmpp.modules.dataforms import extend_form from nbxmpp.modules.base import BaseModule class MUC(BaseModule): + + _depends = { + 'disco_info': 'Discovery', + 'request_vcard': 'VCardTemp', + } + def __init__(self, client): BaseModule.__init__(self, client) @@ -380,6 +392,42 @@ class MUC(BaseModule): room_jid, reason, jid) return iq + @iq_request_task + def request_info(self, jid, request_vcard=True, allow_redirect=False): + _task = yield + + redirected = False + + disco_info = yield self.disco_info(jid) + if is_error(disco_info): + error_response = disco_info + + if not allow_redirect: + raise error_response + + if error_response.condition != 'gone': + raise error_response + + try: + jid = parse_xmpp_uri(error_response.condition_data)[0] + except Exception: + raise error_response + + redirected = True + disco_info = yield self.disco_info(jid) + raise_if_error(disco_info) + + if not request_vcard or not disco_info.supports(Namespace.VCARD): + yield MucInfoResult(info=disco_info, redirected=redirected) + + vcard = yield self.request_vcard(jid) + if is_error(vcard): + yield MucInfoResult(info=disco_info, redirected=redirected) + + yield MucInfoResult(info=disco_info, + vcard=vcard, + redirected=redirected) + @call_on_response('_default_response') def set_config(self, room_jid, form): iq = Iq(typ='set', to=room_jid, queryNS=Namespace.MUC_OWNER) @@ -577,3 +625,10 @@ class MUC(BaseModule): role=role, actor=item.getTagAttr('actor', 'nick'), reason=item.getTagData('reason')) + + +@dataclass +class MucInfoResult: + info: object + vcard: object = None + redirected: bool = False ===================================== nbxmpp/modules/util.py ===================================== @@ -15,6 +15,9 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <
http://www.gnu.org/licenses/
>. +from urllib.parse import urlparse +from urllib.parse import unquote + from nbxmpp.structs import CommonResult from nbxmpp.errors import StanzaError from nbxmpp.errors import is_error @@ -39,3 +42,22 @@ def finalize(task, result): if isinstance(result, Node): return task.set_result(result) return result + + +def parse_xmpp_uri(uri): + url = urlparse(uri) + if url.scheme != 'xmpp': + raise ValueError('not a xmpp uri') + + if not ';' in url.query: + return (url.path, url.query, {}) + + action, query = url.query.split(';', 1) + key_value_pairs = query.split(';') + + dict_ = {} + for key_value in key_value_pairs: + key, value = key_value.split('=') + dict_[key] = unquote(value) + + return (url.path, action, dict_) View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/compare/4d55d9a2fdfba62b71a0497…
-- View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/compare/4d55d9a2fdfba62b71a0497…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/python-nbxmpp] Pushed new branch tasks
by Philipp Hörist
25 Sep '20
25 Sep '20
Philipp Hörist pushed new branch tasks at gajim / python-nbxmpp -- View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/tree/tasks
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/gajim] Deleted branch avatars
by Philipp Hörist
24 Sep '20
24 Sep '20
Philipp Hörist deleted branch avatars at gajim / gajim -- You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/gajim][master] 3 commits: Add task decoractor
by Philipp Hörist
24 Sep '20
24 Sep '20
Philipp Hörist pushed to branch master at gajim / gajim Commits: f903a0a4 by lovetox at 2020-09-24T09:43:26+02:00 Add task decoractor - - - - - a0ed4fb7 by lovetox at 2020-09-24T09:43:26+02:00 Refactor VCard and VCardAvatars code - Move XEP-0153 code from VCard into VCardAvatars - Rely on new nbxmpp module VCardTemp - Don’t advertise avatar with XEP-0153 - - - - - a0d8b200 by lovetox at 2020-09-24T09:43:26+02:00 Refactor UserAvatar module - Adapt to nbxmpp changes - - - - - 16 changed files: - gajim/common/app.py - gajim/common/client.py - gajim/common/connection.py - gajim/common/const.py - gajim/common/helpers.py - gajim/common/modules/discovery.py - gajim/common/modules/presence.py - gajim/common/modules/user_avatar.py - gajim/common/modules/util.py - gajim/common/modules/vcard_avatars.py - gajim/common/modules/vcard_temp.py - gajim/dialog_messages.py - gajim/groupchat_control.py - gajim/gtk/profile.py - gajim/gtk/server_info.py - gajim/vcard.py Changes: ===================================== gajim/common/app.py ===================================== @@ -36,6 +36,7 @@ import logging import uuid from pathlib import Path from collections import namedtuple +from collections import defaultdict import nbxmpp from gi.repository import Gdk @@ -151,6 +152,7 @@ _dependencies = { 'IDLE': False, } +_tasks = defaultdict(list) def print_version(): log('gajim').info('Gajim Version: %s', gajim.__version__) @@ -661,3 +663,27 @@ def get_groupchat_control(account, jid): return app.interface.minimized_controls[account][jid] except Exception: return None + + +def register_task(self, task): + _tasks[id(self)].append(task) + + +def remove_task(task, id_): + try: + _tasks[id_].remove(task) + except Exception: + pass + else: + if not _tasks[id_]: + del _tasks[id_] + + +def cancel_tasks(obj): + id_ = id(obj) + if id_ not in _tasks: + return + + task_list = _tasks[id_] + for task in task_list: + task.cancel() ===================================== gajim/common/client.py ===================================== @@ -57,7 +57,6 @@ class Client(ConnectionHandlers): self._priority = 0 self._connect_machine_calls = 0 - self.avatar_conversion = False self.addressing_supported = False self.is_zeroconf = False @@ -451,10 +450,6 @@ class Client(ConnectionHandlers): # We did not resume the stream, so we are not joined any MUCs self.update_presence(include_muc=False) - if not self.avatar_conversion: - # ask our VCard - self.get_module('VCardTemp').request_vcard() - self.get_module('Bookmarks').request_bookmarks() self.get_module('SoftwareVersion').set_enabled(True) self.get_module('Annotations').request_annotations() ===================================== gajim/common/connection.py ===================================== @@ -71,7 +71,6 @@ class CommonConnection: self.pep = {} self.roster_supported = True - self.avatar_conversion = False self._stun_servers = [] # STUN servers of our jabber server ===================================== gajim/common/const.py ===================================== @@ -128,13 +128,6 @@ class IdleState(Enum): AWAKE = 'online' -@unique -class RequestAvatar(IntEnum): - SELF = 0 - ROOM = 1 - USER = 2 - - @unique class PEPEventType(IntEnum): ABSTRACT = 0 ===================================== gajim/common/helpers.py ===================================== @@ -824,13 +824,7 @@ def get_subscription_request_msg(account=None): s = _('I would like to add you to my contact list.') if account: s = _('Hello, I am $name.') + ' ' + s - name = app.connections[account].get_module('VCardTemp').get_vard_name() - nick = app.nicks[account] - if name and nick: - name += ' (%s)' % nick - elif nick: - name = nick - s = Template(s).safe_substitute({'name': name}) + s = Template(s).safe_substitute({'name': app.nicks[account]}) return s def get_user_proxy(account): ===================================== gajim/common/modules/discovery.py ===================================== @@ -112,9 +112,7 @@ class Discovery(BaseModule): self._con.get_module('PEP').pass_disco(result) self._con.get_module('PubSub').pass_disco(result) self._con.get_module('Bookmarks').pass_disco(result) - - if 'urn:xmpp:pep-vcard-conversion:0' in result.features: - self._con.avatar_conversion = True + self._con.get_module('VCardAvatars').pass_disco(result) self._con.get_module('Caps').update_caps() ===================================== gajim/common/modules/presence.py ===================================== @@ -362,11 +362,6 @@ class Presence(BaseModule): nick_tag = presence.setTag('nick', namespace=Namespace.NICK) nick_tag.setData(nick) - if not self._con.avatar_conversion: - # XEP-0398 not supported by server so - # we add the avatar sha to our presence - self._con.get_module('VCardAvatars').add_update_node(presence) - if (idle_time and app.is_installed('IDLE') and app.settings.get('autoaway')): ===================================== gajim/common/modules/user_avatar.py ===================================== @@ -15,18 +15,19 @@ # XEP-0084: User Avatar from nbxmpp.namespaces import Namespace -from nbxmpp.util import is_error_result +from nbxmpp.modules.util import is_error from gajim.common import app from gajim.common.modules.base import BaseModule from gajim.common.modules.util import event_node - +from gajim.common.modules.util import task class UserAvatar(BaseModule): _nbxmpp_extends = 'UserAvatar' _nbxmpp_methods = [ - 'request_avatar' + 'request_avatar', + 'set_avatar', ] def __init__(self, con): @@ -38,12 +39,11 @@ class UserAvatar(BaseModule): if properties.pubsub_event.retracted: return - data = properties.pubsub_event.data + metadata = properties.pubsub_event.data jid = str(properties.jid) - if data is None: - # Remove avatar - self._log.info('Remove: %s', jid) + if metadata is None or not metadata.infos: + self._log.info('No avatar published: %s', jid) app.contacts.set_avatar(self._account, jid, None) self._con.get_module('Roster').set_avatar_sha(jid, None) app.interface.update_avatar(self._account, jid) @@ -54,32 +54,39 @@ class UserAvatar(BaseModule): else: sha = app.contacts.get_avatar_sha(self._account, jid) - if sha == data.id: - self._log.info('Avatar already known: %s %s', jid, data.id) + if sha in metadata.avatar_shas: + self._log.info('Avatar already known: %s %s', jid, sha) return - self._log.info('Request: %s %s', jid, data.id) - self._nbxmpp('UserAvatar').request_avatar( - jid, data.id, callback=self._avatar_received) + avatar_info = metadata.infos[0] + self._log.info('Request: %s %s', jid, avatar_info.id) + self._request_avatar(jid, avatar_info) + + @task + def _request_avatar(self, jid, avatar_info): + _task = yield + + avatar = yield self._nbxmpp('UserAvatar').request_avatar( + avatar_info, jid=jid) - def _avatar_received(self, result): - if is_error_result(result): - self._log.info(result) + if is_error(avatar): + self._log.warning(avatar) return - self._log.info('Received Avatar: %s %s', result.jid, result.sha) - app.interface.save_avatar(result.data) + self._log.info('Received Avatar: %s %s', jid, avatar.sha) + app.interface.save_avatar(avatar.data) - if self._con.get_own_jid().bare_match(result.jid): - app.settings.set_account_setting(self._account, - 'avatar_sha', - result.sha) + if self._con.get_own_jid().bare_match(jid): + app.config.set_per('accounts', + self._account, + 'avatar_sha', + avatar.sha) else: - self._con.get_module('Roster').set_avatar_sha(str(result.jid), - result.sha) + self._con.get_module('Roster').set_avatar_sha( + str(jid), avatar.sha) - app.contacts.set_avatar(self._account, str(result.jid), result.sha) - app.interface.update_avatar(self._account, str(result.jid)) + app.contacts.set_avatar(self._account, str(jid), avatar.sha) + app.interface.update_avatar(self._account, str(jid)) def get_instance(*args, **kwargs): ===================================== gajim/common/modules/util.py ===================================== @@ -20,6 +20,8 @@ from logging import LoggerAdapter from functools import wraps from functools import partial +from nbxmpp.task import Task + from gajim.common import app from gajim.common.const import EME_MESSAGES @@ -88,3 +90,17 @@ def get_eme_message(eme_data): class LogAdapter(LoggerAdapter): def process(self, msg, kwargs): return '(%s) %s' % (self.extra['account'], msg), kwargs + + +def task(func): + @wraps(func) + def func_wrapper(self, *args, callback=None, user_data=None, **kwargs): + task_ = Task(func(self, *args, **kwargs)) + app.register_task(self, task_) + task_.set_finalize_func(app.remove_task, id(self)) + task_.set_user_data(user_data) + if callback is not None: + task_.add_done_callback(callback) + task_.start() + return task_ + return func_wrapper ===================================== gajim/common/modules/vcard_avatars.py ===================================== @@ -14,16 +14,14 @@ # XEP-0153: vCard-Based Avatars -from pathlib import Path - from nbxmpp.namespaces import Namespace from nbxmpp.structs import StanzaHandler from nbxmpp.const import AvatarState +from nbxmpp.modules.util import is_error from gajim.common import app -from gajim.common import configpaths -from gajim.common.const import RequestAvatar from gajim.common.modules.base import BaseModule +from gajim.common.modules.util import task class VCardAvatars(BaseModule): @@ -38,17 +36,55 @@ class VCardAvatars(BaseModule): priority=51), ] - self.avatar_advertised = False - self._find_own_avatar() + self.avatar_conversion_available = False + + def pass_disco(self, info): + is_available = Namespace.VCARD_CONVERSION in info.features + self.avatar_conversion_available = is_available + self._log.info('Discovered Avatar Conversion') + + @task + def _request_vcard(self, jid, expected_sha, type_): + _task = yield + + vcard = yield self._con.get_module('VCardTemp').request_vcard(jid=jid) + + if is_error(vcard): + self._log.warning(vcard) + return + + avatar, avatar_sha = vcard.get_avatar() + if avatar is None: + self._log.warning('Avatar missing: %s %s', jid, expected_sha) + return - def _find_own_avatar(self): - sha = app.settings.get_account_setting(self._account, 'avatar_sha') - if not sha: + if expected_sha != avatar_sha: + self._log.warning('Avatar mismatch: %s %s != %s', + jid, + expected_sha, + avatar_sha) return - path = Path(configpaths.get('AVATAR')) / sha - if not path.exists(): - self._log.info('Missing own avatar, reset sha') - app.settings.set_account_setting(self._account, 'avatar_sha', '') + + self._log.info('Received: %s %s', jid, avatar_sha) + app.interface.save_avatar(avatar) + + if type_ == 'contact': + self._con.get_module('Roster').set_avatar_sha(jid, avatar_sha) + app.contacts.set_avatar(self._account, jid, avatar_sha) + app.interface.update_avatar(self._account, jid) + + elif type_ == 'muc': + app.storage.cache.set_muc_avatar_sha(jid, avatar_sha) + app.contacts.set_avatar(self._account, jid, avatar_sha) + app.interface.update_avatar(self._account, jid, room_avatar=True) + + elif type_ == 'muc-user': + contact = app.contacts.get_gc_contact(self._account, + jid.bare, + jid.resource) + if contact is not None: + contact.avatar_sha = avatar_sha + app.interface.update_avatar(contact=contact) def _presence_received(self, _con, _stanza, properties): if not properties.type.is_available: @@ -59,15 +95,6 @@ class VCardAvatars(BaseModule): return if self._con.get_own_jid().bare_match(properties.jid): - if self._con.get_own_jid() == properties.jid: - # Initial presence reflection - if self._con.avatar_conversion: - # XEP-0398: Tells us the current avatar sha on the - # initial presence reflection - self._self_update_received(properties) - else: - # Presence from another resource of ours - self._self_update_received(properties) return if properties.from_muc: @@ -78,38 +105,6 @@ class VCardAvatars(BaseModule): str(properties.jid)) self._update_received(properties, room=contact is not None) - def _self_update_received(self, properties): - jid = properties.jid.bare - if properties.avatar_state == AvatarState.EMPTY: - # Empty <photo/> tag, means no avatar is advertised - self._log.info('%s has no avatar published', properties.jid) - app.settings.set_account_setting(self._account, 'avatar_sha', '') - app.contacts.set_avatar(self._account, jid, None) - app.interface.update_avatar(self._account, jid) - return - - self._log.info('Update: %s %s', jid, properties.avatar_sha) - current_sha = app.settings.get_account_setting(self._account, - 'avatar_sha') - - if properties.avatar_sha != current_sha: - path = Path(configpaths.get('AVATAR')) / properties.avatar_sha - if path.exists(): - app.settings.set_account_setting(self._account, - 'avatar_sha', - properties.avatar_sha) - app.contacts.set_avatar(self._account, - jid, - properties.avatar_sha) - app.interface.update_avatar(self._account, jid) - else: - self._log.info('Request : %s', jid) - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.SELF) - else: - self._log.info('Avatar already known: %s %s', - jid, properties.avatar_sha) - def muc_disco_info_update(self, disco_info): if not disco_info.supports(Namespace.VCARD): return @@ -135,9 +130,6 @@ class VCardAvatars(BaseModule): if state == AvatarState.EMPTY: # Empty <photo/> tag, means no avatar is advertised self._log.info('%s has no avatar published', jid) - - # Remove avatar - self._log.debug('Remove: %s', jid) app.contacts.set_avatar(self._account, jid, None) if room: @@ -169,11 +161,9 @@ class VCardAvatars(BaseModule): if avatar_sha not in self._requested_shas: self._requested_shas.append(avatar_sha) if room: - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.ROOM, jid, sha=avatar_sha) + self._request_vcard(jid, avatar_sha, 'muc') else: - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.USER, jid, sha=avatar_sha) + self._request_vcard(jid, avatar_sha, 'contact') def _gc_update_received(self, properties): nick = properties.jid.resource @@ -186,9 +176,8 @@ class VCardAvatars(BaseModule): return if properties.avatar_state == AvatarState.EMPTY: - # Empty <photo/> tag, means no avatar is advertised, remove avatar + # Empty <photo/> tag, means no avatar is advertised self._log.info('%s has no avatar published', nick) - self._log.debug('Remove: %s', nick) gc_contact.avatar_sha = None app.interface.update_avatar(contact=gc_contact) else: @@ -197,9 +186,9 @@ class VCardAvatars(BaseModule): if properties.avatar_sha not in self._requested_shas: app.log('avatar').info('Request: %s', nick) self._requested_shas.append(properties.avatar_sha) - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.USER, str(properties.jid), - room=True, sha=properties.avatar_sha) + self._request_vcard(properties.jid, + properties.avatar_sha, + 'muc-user') return if gc_contact.avatar_sha != properties.avatar_sha: @@ -210,29 +199,6 @@ class VCardAvatars(BaseModule): else: self._log.info('Avatar already known: %s', nick) - def send_avatar_presence(self, force=False, after_publish=False): - if self._con.avatar_conversion: - if not after_publish: - # XEP-0398: We only resend presence after we publish a - # new avatar - return - else: - if self.avatar_advertised and not force: - self._log.debug('Avatar already advertised') - return - - self._con.update_presence() - self.avatar_advertised = True - - def add_update_node(self, node): - update = node.setTag('x', namespace=Namespace.VCARD_UPDATE) - if self._con.get_module('VCardTemp').own_vcard_received: - sha = app.settings.get_account_setting(self._account, 'avatar_sha') - own_jid = self._con.get_own_jid() - self._log.info('Send avatar presence to: %s %s', - node.getTo() or own_jid, sha or 'no sha advertised') - update.setTagData('photo', sha) - def get_instance(*args, **kwargs): return VCardAvatars(*args, **kwargs), 'VCardAvatars' ===================================== gajim/common/modules/vcard_temp.py ===================================== @@ -14,27 +14,25 @@ # XEP-0054: vcard-temp -import hashlib -import binascii -import base64 - -import nbxmpp from nbxmpp.namespaces import Namespace from gajim.common import app -from gajim.common.const import RequestAvatar from gajim.common.nec import NetworkEvent from gajim.common.modules.base import BaseModule -from gajim.common.connection_handlers_events import InformationEvent class VCardTemp(BaseModule): + + _nbxmpp_extends = 'VCardTemp' + _nbxmpp_methods = [ + 'request_vcard', + 'set_vcard', + ] + def __init__(self, con): BaseModule.__init__(self, con) self._own_vcard = None - self.own_vcard_received = False - self.room_jids = [] self.supported = False def pass_disco(self, info): @@ -48,267 +46,6 @@ class VCardTemp(BaseModule): account=self._account, feature=Namespace.VCARD)) - @staticmethod - def _node_to_dict(node): - dict_ = {} - for info in node.getChildren(): - name = info.getName() - if name in ('ADR', 'TEL', 'EMAIL'): # we can have several - dict_.setdefault(name, []) - entry = {} - for child in info.getChildren(): - entry[child.getName()] = child.getData() - dict_[name].append(entry) - elif info.getChildren() == []: - dict_[name] = info.getData() - else: - dict_[name] = {} - for child in info.getChildren(): - dict_[name][child.getName()] = child.getData() - return dict_ - - def request_vcard(self, callback=RequestAvatar.SELF, jid=None, - room=False, sha=None): - if not app.account_is_available(self._account): - return - - if isinstance(callback, RequestAvatar): - if callback == RequestAvatar.SELF: - if not self.supported: - return - callback = self._on_own_avatar_received - elif callback == RequestAvatar.ROOM: - callback = self._on_room_avatar_received - elif callback == RequestAvatar.USER: - callback = self._on_avatar_received - - if room: - room_jid = app.get_room_from_fjid(jid) - if room_jid not in self.room_jids: - self.room_jids.append(room_jid) - - iq = nbxmpp.Iq(typ='get') - if jid: - iq.setTo(jid) - iq.setQuery('vCard').setNamespace(Namespace.VCARD) - - own_jid = self._con.get_own_jid().bare - self._log.info('Request: %s, expected sha: %s', jid or own_jid, sha) - - self._con.connection.SendAndCallForResponse( - iq, self._parse_vcard, {'callback': callback, 'expected_sha': sha}) - - def send_vcard(self, vcard, sha): - if not app.account_is_available(self._account): - return - - iq = nbxmpp.Iq(typ='set') - iq2 = iq.setTag(Namespace.VCARD + ' vCard') - for i in vcard: - if i == 'jid': - continue - if isinstance(vcard[i], dict): - iq3 = iq2.addChild(i) - for j in vcard[i]: - iq3.addChild(j).setData(vcard[i][j]) - elif isinstance(vcard[i], list): - for j in vcard[i]: - iq3 = iq2.addChild(i) - for k in j: - iq3.addChild(k).setData(j[k]) - else: - iq2.addChild(i).setData(vcard[i]) - - self._log.info('Upload avatar: %s %s', self._account, sha) - - self._con.connection.SendAndCallForResponse( - iq, self._avatar_publish_result, {'sha': sha}) - - def upload_room_avatar(self, room_jid, data): - iq = nbxmpp.Iq(typ='set', to=room_jid) - vcard = iq.addChild('vCard', namespace=Namespace.VCARD) - photo = vcard.addChild('PHOTO') - photo.addChild('TYPE', payload='image/png') - photo.addChild('BINVAL', payload=data) - - self._log.info('Upload avatar: %s', room_jid) - self._con.connection.SendAndCallForResponse( - iq, self._upload_room_avatar_result) - - @staticmethod - def _upload_room_avatar_result(_nbxmpp_client, stanza): - if not nbxmpp.isResultNode(stanza): - reason = stanza.getErrorMsg() or stanza.getError() - app.nec.push_incoming_event(InformationEvent( - None, dialog_name='avatar-upload-error', args=reason)) - - def _avatar_publish_result(self, _nbxmpp_client, stanza, sha): - if stanza.getType() == 'result': - current_sha = app.settings.get_account_setting(self._account, - 'avatar_sha') - if current_sha != sha: - if not app.account_is_connected(self._account): - return - app.settings.set_account_setting( - self._account, 'avatar_sha', sha or '') - own_jid = self._con.get_own_jid().bare - app.contacts.set_avatar(self._account, own_jid, sha) - app.interface.update_avatar( - self._account, self._con.get_own_jid().bare) - self._con.get_module('VCardAvatars').send_avatar_presence( - after_publish=True) - self._log.info('%s: Published: %s', self._account, sha) - self._con.get_module('MUC').update_presence() - app.nec.push_incoming_event( - NetworkEvent('vcard-published', account=self._account)) - - elif stanza.getType() == 'error': - app.nec.push_incoming_event( - NetworkEvent('vcard-not-published', account=self._account)) - - def _get_vcard_photo(self, vcard, jid): - try: - photo = vcard['PHOTO']['BINVAL'] - except (KeyError, AttributeError, TypeError): - avatar_sha = None - photo_decoded = None - else: - if photo == '': - avatar_sha = None - photo_decoded = None - else: - try: - photo_decoded = base64.b64decode(photo.encode('utf-8')) - except binascii.Error as error: - self._log.warning('Invalid avatar for %s: %s', jid, error) - return None, None - avatar_sha = hashlib.sha1(photo_decoded).hexdigest() - - return avatar_sha, photo_decoded - - def _parse_vcard(self, _nbxmpp_client, stanza, callback, expected_sha): - frm_jid = stanza.getFrom() - room = False - if frm_jid is None: - frm_jid = self._con.get_own_jid() - elif frm_jid.bare in self.room_jids: - room = True - - resource = frm_jid.resource - jid = frm_jid.bare - - stanza_error = stanza.getError() - if stanza_error in ('service-unavailable', 'item-not-found', - 'not-allowed'): - self._log.info('vCard not available: %s %s', frm_jid, stanza_error) - callback(jid, resource, room, {}, expected_sha) - return - - vcard_node = stanza.getTag('vCard', namespace=Namespace.VCARD) - if vcard_node is None: - self._log.info('vCard not available: %s', frm_jid) - self._log.debug(stanza) - return - vcard = self._node_to_dict(vcard_node) - - if self._con.get_own_jid().bare_match(jid): - if 'NICKNAME' in vcard: - app.nicks[self._account] = vcard['NICKNAME'] - elif 'FN' in vcard: - app.nicks[self._account] = vcard['FN'] - - app.nec.push_incoming_event(NetworkEvent('vcard-received', - account=self._account, - jid=jid, - vcard_dict=vcard)) - - callback(jid, resource, room, vcard, expected_sha) - - def _on_own_avatar_received(self, jid, _resource, _room, vcard, *args): - avatar_sha, photo_decoded = self._get_vcard_photo(vcard, jid) - - self._log.info('Received own vcard, avatar sha is: %s', avatar_sha) - - self._own_vcard = vcard - self.own_vcard_received = True - - if avatar_sha is None: - # No avatar found in vcard - self._log.info('No avatar found') - app.settings.set_account_setting(self._account, 'avatar_sha', '') - app.contacts.set_avatar(self._account, jid, avatar_sha) - self._con.get_module('VCardAvatars').send_avatar_presence( - force=True) - return - - # Avatar found in vcard - current_sha = app.settings.get_account_setting(self._account, - 'avatar_sha') - if current_sha == avatar_sha: - self._con.get_module('VCardAvatars').send_avatar_presence() - else: - app.interface.save_avatar(photo_decoded) - app.contacts.set_avatar(self._account, jid, avatar_sha) - app.settings.set_account_setting( - self._account, 'avatar_sha', avatar_sha) - self._con.get_module('VCardAvatars').send_avatar_presence( - force=True) - - app.interface.update_avatar(self._account, jid) - - def _on_room_avatar_received(self, jid, _resource, _room, vcard, - expected_sha): - avatar_sha, photo_decoded = self._get_vcard_photo(vcard, jid) - if expected_sha != avatar_sha: - self._log.warning('Avatar mismatch: %s %s', jid, avatar_sha) - return - - app.interface.save_avatar(photo_decoded) - - self._log.info('Received: %s %s', jid, avatar_sha) - app.storage.cache.set_muc_avatar_sha(jid, avatar_sha) - app.contacts.set_avatar(self._account, jid, avatar_sha) - app.interface.update_avatar(self._account, jid, room_avatar=True) - - def _on_avatar_received(self, jid, resource, room, vcard, expected_sha): - request_jid = jid - if room: - request_jid = '%s/%s' % (jid, resource) - - avatar_sha, photo_decoded = self._get_vcard_photo(vcard, request_jid) - if expected_sha != avatar_sha: - self._log.warning('Received: avatar mismatch: %s %s', - request_jid, avatar_sha) - return - - app.interface.save_avatar(photo_decoded) - - # Received vCard from a contact - if room: - self._log.info('Received: %s %s', resource, avatar_sha) - contact = app.contacts.get_gc_contact(self._account, jid, resource) - if contact is not None: - contact.avatar_sha = avatar_sha - app.interface.update_avatar(contact=contact) - else: - self._log.info('Received: %s %s', jid, avatar_sha) - self._con.get_module('Roster').set_avatar_sha(jid, avatar_sha) - app.contacts.set_avatar(self._account, jid, avatar_sha) - app.interface.update_avatar(self._account, jid) - - def get_vard_name(self): - name = '' - vcard = self._own_vcard - if not vcard: - return name - - if 'N' in vcard: - if 'GIVEN' in vcard['N'] and 'FAMILY' in vcard['N']: - name = vcard['N']['GIVEN'] + ' ' + vcard['N']['FAMILY'] - if not name and 'FN' in vcard: - name = vcard['FN'] - return name - def get_instance(*args, **kwargs): return VCardTemp(*args, **kwargs), 'VCardTemp' ===================================== gajim/dialog_messages.py ===================================== @@ -133,10 +133,6 @@ messages = { 'for the chosen encryption.'), ErrorDialog), - 'avatar-upload-error': Message( - _('Avatar Upload Failed'), - '%s', - ErrorDialog), } ===================================== gajim/groupchat_control.py ===================================== @@ -35,6 +35,7 @@ from nbxmpp.const import StatusCode from nbxmpp.const import Affiliation from nbxmpp.const import PresenceType from nbxmpp.util import is_error_result +from nbxmpp.modules.vcard_temp import VCard from gi.repository import Gtk from gi.repository import Gdk @@ -43,7 +44,7 @@ from gi.repository import Gio from gajim import gtkgui_helpers from gajim import gui_menu_builder -from gajim import vcard +from gajim.vcard import VcardWindow from gajim.common import events from gajim.common import app @@ -65,7 +66,6 @@ from gajim.command_system.implementation.hosts import GroupChatCommands from gajim.gtk.dialogs import DialogButton from gajim.gtk.dialogs import ConfirmationCheckDialog -from gajim.gtk.dialogs import ErrorDialog from gajim.gtk.dialogs import ConfirmationDialog from gajim.gtk.filechoosers import AvatarChooserDialog from gajim.gtk.groupchat_config import GroupchatConfig @@ -573,20 +573,32 @@ class GroupchatControl(ChatControlBase): data, sha = app.interface.avatar_storage.prepare_for_publish( filename) if sha is None: - ErrorDialog( - _('Could not load image'), - transient_for=self.parent_win.window) + self.add_info_message(_('Loading avatar failed')) return avatar = base64.b64encode(data).decode('utf-8') + vcard = VCard() + vcard.set_avatar(avatar, 'image/png') + con = app.connections[self.account] - con.get_module('VCardTemp').upload_room_avatar( - self.room_jid, avatar) + con.get_module('VCardTemp').set_vcard( + vcard, + jid=self.room_jid, + callback=self._on_upload_avatar_result) AvatarChooserDialog(_on_accept, transient_for=self.parent_win.window, modal=True) + def _on_upload_avatar_result(self, task): + try: + task.finish() + except Exception as error: + self.add_info_message(_(f'Avatar upload failed: {error}')) + + else: + self.add_info_message(_('Avatar upload successful')) + def _on_contact_information(self, _action, param): nick = param.get_string() gc_contact = app.contacts.get_gc_contact(self.account, @@ -598,7 +610,7 @@ class GroupchatControl(ChatControlBase): window.present() else: app.interface.instances[self.account]['infos'][contact.jid] = \ - vcard.VcardWindow(contact, self.account, gc_contact) + VcardWindow(contact, self.account, gc_contact) def _on_kick(self, _action, param): nick = param.get_string() ===================================== gajim/gtk/profile.py ===================================== @@ -16,37 +16,35 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <
http://www.gnu.org/licenses/
>. -import base64 import time import logging -import hashlib from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GLib +from nbxmpp.errors import is_error +from nbxmpp.modules.vcard_temp import VCard + from gajim.common import app -from gajim.common import ged from gajim.common.i18n import _ from gajim.common.const import AvatarSize -from gajim.common.helpers import event_filter +from gajim.common.modules.util import task from gajim import gtkgui_helpers from gajim.gtk.dialogs import ErrorDialog from gajim.gtk.dialogs import InformationDialog from gajim.gtk.util import get_builder -from gajim.gtk.util import EventHelper from gajim.gtk.filechoosers import AvatarChooserDialog log = logging.getLogger('gajim.profile') -class ProfileWindow(Gtk.ApplicationWindow, EventHelper): +class ProfileWindow(Gtk.ApplicationWindow): def __init__(self, account): Gtk.ApplicationWindow.__init__(self) - EventHelper.__init__(self) self.set_application(app.app) self.set_position(Gtk.WindowPosition.CENTER) self.set_show_menubar(False) @@ -69,8 +67,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.dialog = None self.avatar_mime_type = None - self.avatar_encoded = None - self.avatar_sha = None + self._avatar_bytes = None self.message_id = self.statusbar.push(self.context_id, _('Retrieving profile…')) self.update_progressbar_timeout_id = GLib.timeout_add( @@ -78,15 +75,10 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.remove_statusbar_timeout_id = None self.xml.connect_signals(self) - self.register_events([ - ('vcard-published', ged.GUI1, self._nec_vcard_published), - ('vcard-not-published', ged.GUI1, self._nec_vcard_not_published), - ]) self.show_all() self.xml.get_object('ok_button').grab_focus() - app.connections[account].get_module('VCardTemp').request_vcard( - self._nec_vcard_received, self.jid) + self._request_vcard() def on_information_notebook_switch_page(self, widget, page, page_num): GLib.idle_add(self.xml.get_object('ok_button').grab_focus) @@ -100,6 +92,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.remove_statusbar_timeout_id = None def on_profile_window_destroy(self, widget): + app.cancel_tasks(self) if self.update_progressbar_timeout_id is not None: GLib.source_remove(self.update_progressbar_timeout_id) if self.remove_statusbar_timeout_id is not None: @@ -120,8 +113,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): button.hide() text_button = self.xml.get_object('NOPHOTO_button') text_button.show() - self.avatar_encoded = None - self.avatar_sha = None + self._avatar_bytes = None self.avatar_mime_type = None def _on_set_avatar_clicked(self, _button): @@ -144,8 +136,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): text_button = self.xml.get_object('NOPHOTO_button') text_button.hide() - self.avatar_sha = sha - self.avatar_encoded = base64.b64encode(data).decode('utf-8') + self._avatar_bytes = data self.avatar_mime_type = 'image/png' AvatarChooserDialog(on_ok, transient_for=self) @@ -176,37 +167,43 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): except AttributeError: pass - def set_values(self, vcard_): + def _set_avatar(self, vcard): + avatar, _ = vcard.get_avatar() + button = self.xml.get_object('PHOTO_button') image = self.xml.get_object('PHOTO_image') text_button = self.xml.get_object('NOPHOTO_button') - if 'PHOTO' not in vcard_: - # set default image + + if avatar is None: + image.set_from_pixbuf(None) + button.hide() + text_button.show() + return + + try: + surface = self._get_surface_from_data(avatar) + except Exception: + log.exception('Error while loading avatar') image.set_from_pixbuf(None) button.hide() text_button.show() + return + + self._avatar_bytes = avatar + self.avatar_mime_type = vcard.data['PHOTO']['TYPE'] + + image.set_from_surface(surface) + button.show() + text_button.hide() + + def _get_surface_from_data(self, data): + scale = self.get_scale_factor() + pixbuf = gtkgui_helpers.scale_pixbuf_from_data(data, AvatarSize.VCARD) + return Gdk.cairo_surface_create_from_pixbuf(pixbuf, scale) + + def set_values(self, vcard_): for i in vcard_.keys(): if i == 'PHOTO': - photo_encoded = vcard_[i]['BINVAL'] - if photo_encoded == '': - continue - self.avatar_encoded = photo_encoded - photo_decoded = base64.b64decode(photo_encoded.encode('utf-8')) - self.avatar_sha = hashlib.sha1(photo_decoded).hexdigest() - if 'TYPE' in vcard_[i]: - self.avatar_mime_type = vcard_[i]['TYPE'] - - scale = self.get_scale_factor() - surface = app.interface.avatar_storage.surface_from_filename( - self.avatar_sha, AvatarSize.VCARD, scale) - if surface is None: - pixbuf = gtkgui_helpers.scale_pixbuf_from_data( - photo_decoded, AvatarSize.VCARD) - surface = Gdk.cairo_surface_create_from_pixbuf(pixbuf, - scale) - image.set_from_surface(surface) - button.show() - text_button.hide() continue if i in ('ADR', 'TEL', 'EMAIL'): for entry in vcard_[i]: @@ -236,9 +233,6 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.progressbar.set_fraction(0) self.update_progressbar_timeout_id = None - def _nec_vcard_received(self, jid, resource, room, vcard_, *args): - self.set_values(vcard_) - def add_to_vcard(self, vcard_, entry, txt): """ Add an information to the vCard dictionary @@ -291,11 +285,10 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): vcard_['DESC'] = txt # Avatar - if self.avatar_encoded: - vcard_['PHOTO'] = {'BINVAL': self.avatar_encoded} - if self.avatar_mime_type: - vcard_['PHOTO']['TYPE'] = self.avatar_mime_type - return vcard_, self.avatar_sha + vcard = VCard(vcard_) + if self._avatar_bytes: + vcard.set_avatar(self._avatar_bytes, self.avatar_mime_type) + return vcard def on_ok_button_clicked(self, widget): if self.update_progressbar_timeout_id: @@ -308,43 +301,69 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): 'information.'), transient_for=self) return - vcard_, sha = self.make_vcard() - nick = vcard_.get('NICKNAME') or None - app.connections[self.account].get_module('UserNickname').set_nickname(nick) - if not nick: - nick = app.settings.get_account_setting(self.account, 'name') - app.nicks[self.account] = nick - app.connections[self.account].get_module('VCardTemp').send_vcard( - vcard_, sha) + + vcard_ = self.make_vcard() + + client = app.get_client(self.account) + client.get_module('VCardTemp').set_vcard( + vcard_, callback=self._on_set_vcard_result) + self._set_nickname(vcard_) + self.message_id = self.statusbar.push( self.context_id, _('Sending profile…')) self.progressbar.show() self.update_progressbar_timeout_id = GLib.timeout_add( 100, self.update_progressbar) - @event_filter(['account']) - def _nec_vcard_published(self, _event): - if self.update_progressbar_timeout_id is not None: - GLib.source_remove(self.update_progressbar_timeout_id) - self.update_progressbar_timeout_id = None - self.destroy() + @task + def _request_vcard(self): + _task = yield - @event_filter(['account']) - def _nec_vcard_not_published(self, _event): - if self.message_id: - self.statusbar.remove(self.context_id, self.message_id) - self.message_id = self.statusbar.push( - self.context_id, _('Information NOT published')) - self.remove_statusbar_timeout_id = GLib.timeout_add_seconds( - 3, self.remove_statusbar, self.message_id) - if self.update_progressbar_timeout_id is not None: - GLib.source_remove(self.update_progressbar_timeout_id) - self.progressbar.set_fraction(0) - self.update_progressbar_timeout_id = None - InformationDialog( - _('vCard publication failed'), - _('There was an error while publishing your personal information, ' - 'try again later.'), transient_for=self) + client = app.get_client(self.account) + vcard = yield client.get_module('VCardTemp').request_vcard() + + if is_error(vcard): + return + + self._set_avatar(vcard) + self.set_values(vcard.data) + + def _on_set_vcard_result(self, task_): + try: + task_.finish() + except Exception as error: + log.warning(error) + + if self.message_id: + self.statusbar.remove(self.context_id, self.message_id) + self.message_id = self.statusbar.push( + self.context_id, _('Information NOT published')) + self.remove_statusbar_timeout_id = GLib.timeout_add_seconds( + 3, self.remove_statusbar, self.message_id) + if self.update_progressbar_timeout_id is not None: + GLib.source_remove(self.update_progressbar_timeout_id) + self.progressbar.set_fraction(0) + self.update_progressbar_timeout_id = None + InformationDialog( + _('vCard publication failed'), + _('There was an error while publishing your personal information, ' + 'try again later.'), transient_for=self) + + else: + if self.update_progressbar_timeout_id is not None: + GLib.source_remove(self.update_progressbar_timeout_id) + self.update_progressbar_timeout_id = None + self.destroy() + + def _set_nickname(self, vcard): + nick = vcard.data.get('NICKNAME') or None + + client = app.get_client(self.account) + client.get_module('UserNickname').set_nickname(nick) + + if not nick: + nick = app.config.get_per('accounts', self.account, 'name') + app.nicks[self.account] = nick def on_cancel_button_clicked(self, widget): self.destroy() ===================================== gajim/gtk/server_info.py ===================================== @@ -299,7 +299,7 @@ class ServerInfo(Gtk.ApplicationWindow, EventHelper): con.get_module('HTTPUpload').available, http_upload_info), Feature('XEP-0398: Avatar Conversion', - con.avatar_conversion), + con.get_module('VCardAvatars').avatar_conversion_available), Feature('XEP-0411: Bookmarks Conversion', con.get_module('Bookmarks').conversion) ] ===================================== gajim/vcard.py ===================================== @@ -26,8 +26,7 @@ # along with Gajim. If not, see <
http://www.gnu.org/licenses/
>. import os -import base64 -import binascii +import logging from gi.repository import Gtk from gi.repository import GLib @@ -35,6 +34,7 @@ from gi.repository import Gdk from nbxmpp.structs import AnnotationNote from nbxmpp.util import is_error_result from nbxmpp.protocol import JID +from nbxmpp.errors import is_error from gajim import gtkgui_helpers from gajim.common import helpers @@ -45,10 +45,12 @@ from gajim.common.i18n import Q_ from gajim.common.i18n import _ from gajim.common.const import AvatarSize from gajim.common.nec import EventHelper +from gajim.common.modules.util import task from gajim.gtk.util import get_builder -# log = logging.getLogger('gajim.vcard') + +log = logging.getLogger('gajim.vcard') class VcardWindow(EventHelper): @@ -151,6 +153,7 @@ class VcardWindow(EventHelper): new_note = AnnotationNote(jid=self.contact.jid, data=new_annotation) con.get_module('Annotations').set_note(new_note) self.unregister_events() + app.cancel_tasks(self) def on_vcard_information_window_key_press_event(self, widget, event): if event.keyval == Gdk.KEY_Escape: @@ -181,31 +184,7 @@ class VcardWindow(EventHelper): def _set_values(self, vcard, jid): for i in vcard.keys(): - if i == 'PHOTO' and self.xml.get_object('information_notebook').\ - get_n_pages() > 4: - if 'BINVAL' not in vcard[i]: - continue - photo_encoded = vcard[i]['BINVAL'] - if photo_encoded == '': - continue - try: - photo_decoded = base64.b64decode( - photo_encoded.encode('utf-8')) - except binascii.Error as error: - app.log('avatar').warning('Invalid avatar for %s: %s', jid, error) - continue - - pixbuf = gtkgui_helpers.get_pixbuf_from_data(photo_decoded) - if pixbuf is None: - continue - self.avatar = pixbuf - pixbuf = gtkgui_helpers.scale_pixbuf(pixbuf, AvatarSize.VCARD) - surface = Gdk.cairo_surface_create_from_pixbuf( - pixbuf, self.window.get_scale_factor()) - image = self.xml.get_object('PHOTO_image') - image.set_from_surface(surface) - image.show() - self.xml.get_object('user_avatar_label').show() + if i == 'PHOTO': continue if i in ('ADR', 'TEL', 'EMAIL'): for entry in vcard[i]: @@ -225,6 +204,32 @@ class VcardWindow(EventHelper): self.set_value(i + '_label', vcard[i]) self.vcard_arrived = True + def _load_avatar(self, vcard): + if not self.xml.get_object('information_notebook').get_n_pages() > 4: + # TODO: why? + return + + try: + avatar, _ = vcard.get_avatar() + except Exception as error: + log.warning('Failed to load avatar: %s', error) + return + + if avatar is None: + return + + pixbuf = gtkgui_helpers.get_pixbuf_from_data(avatar) + pixbuf = gtkgui_helpers.scale_pixbuf(pixbuf, AvatarSize.VCARD) + + surface = Gdk.cairo_surface_create_from_pixbuf( + pixbuf, self.window.get_scale_factor()) + image = self.xml.get_object('PHOTO_image') + image.set_from_surface(surface) + image.show() + + self.avatar = pixbuf + self.xml.get_object('user_avatar_label').show() + def clear_values(self): for l in ('FN', 'NICKNAME', 'N_FAMILY', 'N_GIVEN', 'N_MIDDLE', 'N_PREFIX', 'N_SUFFIX', 'EMAIL_HOME_USERID', 'TEL_HOME_NUMBER', 'BDAY', @@ -242,9 +247,19 @@ class VcardWindow(EventHelper): widget.set_text('') self.xml.get_object('DESC_textview').get_buffer().set_text('') - def _nec_vcard_received(self, jid, resource, room, vcard, *args): + @task + def _request_vcard(self, jid): + _task = yield + + con = app.connections[self.account] + vcard = yield con.get_module('VCardTemp').request_vcard(jid=jid) + + if is_error(vcard): + return + self.clear_values() - self._set_values(vcard, jid) + self._set_values(vcard.data, str(jid)) + self._load_avatar(vcard) def set_os_info(self, result, jid): if self.xml.get_object('information_notebook').get_n_pages() < 5: @@ -448,14 +463,11 @@ class VcardWindow(EventHelper): self.fill_status_label() + jid = self.contact.jid if self.gc_contact: - con.get_module('VCardTemp').request_vcard( - self._nec_vcard_received, - self.gc_contact.get_full_jid(), - room=True) - else: - con.get_module('VCardTemp').request_vcard( - self._nec_vcard_received, self.contact.jid) + jid = self.gc_contact.get_full_jid() + + self._request_vcard(jid) def on_close_button_clicked(self, widget): self.window.destroy() View it on GitLab:
https://dev.gajim.org/gajim/gajim/-/compare/84137fcdd10260ff905bc87efdd9a5b…
-- View it on GitLab:
https://dev.gajim.org/gajim/gajim/-/compare/84137fcdd10260ff905bc87efdd9a5b…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/gajim][avatars] 4 commits: DOAP: Add doap-style.xsl
by Philipp Hörist
24 Sep '20
24 Sep '20
Philipp Hörist pushed to branch avatars at gajim / gajim Commits: 84137fcd by wurstsalat at 2020-09-23T22:57:51+02:00 DOAP: Add doap-style.xsl - - - - - f903a0a4 by lovetox at 2020-09-24T09:43:26+02:00 Add task decoractor - - - - - a0ed4fb7 by lovetox at 2020-09-24T09:43:26+02:00 Refactor VCard and VCardAvatars code - Move XEP-0153 code from VCard into VCardAvatars - Rely on new nbxmpp module VCardTemp - Don’t advertise avatar with XEP-0153 - - - - - a0d8b200 by lovetox at 2020-09-24T09:43:26+02:00 Refactor UserAvatar module - Adapt to nbxmpp changes - - - - - 17 changed files: - data/gajim.doap - gajim/common/app.py - gajim/common/client.py - gajim/common/connection.py - gajim/common/const.py - gajim/common/helpers.py - gajim/common/modules/discovery.py - gajim/common/modules/presence.py - gajim/common/modules/user_avatar.py - gajim/common/modules/util.py - gajim/common/modules/vcard_avatars.py - gajim/common/modules/vcard_temp.py - gajim/dialog_messages.py - gajim/groupchat_control.py - gajim/gtk/profile.py - gajim/gtk/server_info.py - gajim/vcard.py Changes: ===================================== data/gajim.doap ===================================== @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> +<?xml-stylesheet href="
https://gajim.org/files/doap-style.xsl
" type="text/xsl"?> <rdf:RDF xmlns="
http://usefulinc.com/ns/doap#
" xmlns:rdf="
http://www.w3.org/1999/02/22-rdf-syntax-ns#
" xmlns:xmpp="
https://linkmauve.fr/ns/xmpp-doap#
" ===================================== gajim/common/app.py ===================================== @@ -36,6 +36,7 @@ import logging import uuid from pathlib import Path from collections import namedtuple +from collections import defaultdict import nbxmpp from gi.repository import Gdk @@ -151,6 +152,7 @@ _dependencies = { 'IDLE': False, } +_tasks = defaultdict(list) def print_version(): log('gajim').info('Gajim Version: %s', gajim.__version__) @@ -661,3 +663,27 @@ def get_groupchat_control(account, jid): return app.interface.minimized_controls[account][jid] except Exception: return None + + +def register_task(self, task): + _tasks[id(self)].append(task) + + +def remove_task(task, id_): + try: + _tasks[id_].remove(task) + except Exception: + pass + else: + if not _tasks[id_]: + del _tasks[id_] + + +def cancel_tasks(obj): + id_ = id(obj) + if id_ not in _tasks: + return + + task_list = _tasks[id_] + for task in task_list: + task.cancel() ===================================== gajim/common/client.py ===================================== @@ -57,7 +57,6 @@ class Client(ConnectionHandlers): self._priority = 0 self._connect_machine_calls = 0 - self.avatar_conversion = False self.addressing_supported = False self.is_zeroconf = False @@ -451,10 +450,6 @@ class Client(ConnectionHandlers): # We did not resume the stream, so we are not joined any MUCs self.update_presence(include_muc=False) - if not self.avatar_conversion: - # ask our VCard - self.get_module('VCardTemp').request_vcard() - self.get_module('Bookmarks').request_bookmarks() self.get_module('SoftwareVersion').set_enabled(True) self.get_module('Annotations').request_annotations() ===================================== gajim/common/connection.py ===================================== @@ -71,7 +71,6 @@ class CommonConnection: self.pep = {} self.roster_supported = True - self.avatar_conversion = False self._stun_servers = [] # STUN servers of our jabber server ===================================== gajim/common/const.py ===================================== @@ -128,13 +128,6 @@ class IdleState(Enum): AWAKE = 'online' -@unique -class RequestAvatar(IntEnum): - SELF = 0 - ROOM = 1 - USER = 2 - - @unique class PEPEventType(IntEnum): ABSTRACT = 0 ===================================== gajim/common/helpers.py ===================================== @@ -824,13 +824,7 @@ def get_subscription_request_msg(account=None): s = _('I would like to add you to my contact list.') if account: s = _('Hello, I am $name.') + ' ' + s - name = app.connections[account].get_module('VCardTemp').get_vard_name() - nick = app.nicks[account] - if name and nick: - name += ' (%s)' % nick - elif nick: - name = nick - s = Template(s).safe_substitute({'name': name}) + s = Template(s).safe_substitute({'name': app.nicks[account]}) return s def get_user_proxy(account): ===================================== gajim/common/modules/discovery.py ===================================== @@ -112,9 +112,7 @@ class Discovery(BaseModule): self._con.get_module('PEP').pass_disco(result) self._con.get_module('PubSub').pass_disco(result) self._con.get_module('Bookmarks').pass_disco(result) - - if 'urn:xmpp:pep-vcard-conversion:0' in result.features: - self._con.avatar_conversion = True + self._con.get_module('VCardAvatars').pass_disco(result) self._con.get_module('Caps').update_caps() ===================================== gajim/common/modules/presence.py ===================================== @@ -362,11 +362,6 @@ class Presence(BaseModule): nick_tag = presence.setTag('nick', namespace=Namespace.NICK) nick_tag.setData(nick) - if not self._con.avatar_conversion: - # XEP-0398 not supported by server so - # we add the avatar sha to our presence - self._con.get_module('VCardAvatars').add_update_node(presence) - if (idle_time and app.is_installed('IDLE') and app.settings.get('autoaway')): ===================================== gajim/common/modules/user_avatar.py ===================================== @@ -15,18 +15,19 @@ # XEP-0084: User Avatar from nbxmpp.namespaces import Namespace -from nbxmpp.util import is_error_result +from nbxmpp.modules.util import is_error from gajim.common import app from gajim.common.modules.base import BaseModule from gajim.common.modules.util import event_node - +from gajim.common.modules.util import task class UserAvatar(BaseModule): _nbxmpp_extends = 'UserAvatar' _nbxmpp_methods = [ - 'request_avatar' + 'request_avatar', + 'set_avatar', ] def __init__(self, con): @@ -38,12 +39,11 @@ class UserAvatar(BaseModule): if properties.pubsub_event.retracted: return - data = properties.pubsub_event.data + metadata = properties.pubsub_event.data jid = str(properties.jid) - if data is None: - # Remove avatar - self._log.info('Remove: %s', jid) + if metadata is None or not metadata.infos: + self._log.info('No avatar published: %s', jid) app.contacts.set_avatar(self._account, jid, None) self._con.get_module('Roster').set_avatar_sha(jid, None) app.interface.update_avatar(self._account, jid) @@ -54,32 +54,39 @@ class UserAvatar(BaseModule): else: sha = app.contacts.get_avatar_sha(self._account, jid) - if sha == data.id: - self._log.info('Avatar already known: %s %s', jid, data.id) + if sha in metadata.avatar_shas: + self._log.info('Avatar already known: %s %s', jid, sha) return - self._log.info('Request: %s %s', jid, data.id) - self._nbxmpp('UserAvatar').request_avatar( - jid, data.id, callback=self._avatar_received) + avatar_info = metadata.infos[0] + self._log.info('Request: %s %s', jid, avatar_info.id) + self._request_avatar(jid, avatar_info) + + @task + def _request_avatar(self, jid, avatar_info): + _task = yield + + avatar = yield self._nbxmpp('UserAvatar').request_avatar( + avatar_info, jid=jid) - def _avatar_received(self, result): - if is_error_result(result): - self._log.info(result) + if is_error(avatar): + self._log.warning(avatar) return - self._log.info('Received Avatar: %s %s', result.jid, result.sha) - app.interface.save_avatar(result.data) + self._log.info('Received Avatar: %s %s', jid, avatar.sha) + app.interface.save_avatar(avatar.data) - if self._con.get_own_jid().bare_match(result.jid): - app.settings.set_account_setting(self._account, - 'avatar_sha', - result.sha) + if self._con.get_own_jid().bare_match(jid): + app.config.set_per('accounts', + self._account, + 'avatar_sha', + avatar.sha) else: - self._con.get_module('Roster').set_avatar_sha(str(result.jid), - result.sha) + self._con.get_module('Roster').set_avatar_sha( + str(jid), avatar.sha) - app.contacts.set_avatar(self._account, str(result.jid), result.sha) - app.interface.update_avatar(self._account, str(result.jid)) + app.contacts.set_avatar(self._account, str(jid), avatar.sha) + app.interface.update_avatar(self._account, str(jid)) def get_instance(*args, **kwargs): ===================================== gajim/common/modules/util.py ===================================== @@ -20,6 +20,8 @@ from logging import LoggerAdapter from functools import wraps from functools import partial +from nbxmpp.task import Task + from gajim.common import app from gajim.common.const import EME_MESSAGES @@ -88,3 +90,17 @@ def get_eme_message(eme_data): class LogAdapter(LoggerAdapter): def process(self, msg, kwargs): return '(%s) %s' % (self.extra['account'], msg), kwargs + + +def task(func): + @wraps(func) + def func_wrapper(self, *args, callback=None, user_data=None, **kwargs): + task_ = Task(func(self, *args, **kwargs)) + app.register_task(self, task_) + task_.set_finalize_func(app.remove_task, id(self)) + task_.set_user_data(user_data) + if callback is not None: + task_.add_done_callback(callback) + task_.start() + return task_ + return func_wrapper ===================================== gajim/common/modules/vcard_avatars.py ===================================== @@ -14,16 +14,14 @@ # XEP-0153: vCard-Based Avatars -from pathlib import Path - from nbxmpp.namespaces import Namespace from nbxmpp.structs import StanzaHandler from nbxmpp.const import AvatarState +from nbxmpp.modules.util import is_error from gajim.common import app -from gajim.common import configpaths -from gajim.common.const import RequestAvatar from gajim.common.modules.base import BaseModule +from gajim.common.modules.util import task class VCardAvatars(BaseModule): @@ -38,17 +36,55 @@ class VCardAvatars(BaseModule): priority=51), ] - self.avatar_advertised = False - self._find_own_avatar() + self.avatar_conversion_available = False + + def pass_disco(self, info): + is_available = Namespace.VCARD_CONVERSION in info.features + self.avatar_conversion_available = is_available + self._log.info('Discovered Avatar Conversion') + + @task + def _request_vcard(self, jid, expected_sha, type_): + _task = yield + + vcard = yield self._con.get_module('VCardTemp').request_vcard(jid=jid) + + if is_error(vcard): + self._log.warning(vcard) + return + + avatar, avatar_sha = vcard.get_avatar() + if avatar is None: + self._log.warning('Avatar missing: %s %s', jid, expected_sha) + return - def _find_own_avatar(self): - sha = app.settings.get_account_setting(self._account, 'avatar_sha') - if not sha: + if expected_sha != avatar_sha: + self._log.warning('Avatar mismatch: %s %s != %s', + jid, + expected_sha, + avatar_sha) return - path = Path(configpaths.get('AVATAR')) / sha - if not path.exists(): - self._log.info('Missing own avatar, reset sha') - app.settings.set_account_setting(self._account, 'avatar_sha', '') + + self._log.info('Received: %s %s', jid, avatar_sha) + app.interface.save_avatar(avatar) + + if type_ == 'contact': + self._con.get_module('Roster').set_avatar_sha(jid, avatar_sha) + app.contacts.set_avatar(self._account, jid, avatar_sha) + app.interface.update_avatar(self._account, jid) + + elif type_ == 'muc': + app.storage.cache.set_muc_avatar_sha(jid, avatar_sha) + app.contacts.set_avatar(self._account, jid, avatar_sha) + app.interface.update_avatar(self._account, jid, room_avatar=True) + + elif type_ == 'muc-user': + contact = app.contacts.get_gc_contact(self._account, + jid.bare, + jid.resource) + if contact is not None: + contact.avatar_sha = avatar_sha + app.interface.update_avatar(contact=contact) def _presence_received(self, _con, _stanza, properties): if not properties.type.is_available: @@ -59,15 +95,6 @@ class VCardAvatars(BaseModule): return if self._con.get_own_jid().bare_match(properties.jid): - if self._con.get_own_jid() == properties.jid: - # Initial presence reflection - if self._con.avatar_conversion: - # XEP-0398: Tells us the current avatar sha on the - # initial presence reflection - self._self_update_received(properties) - else: - # Presence from another resource of ours - self._self_update_received(properties) return if properties.from_muc: @@ -78,38 +105,6 @@ class VCardAvatars(BaseModule): str(properties.jid)) self._update_received(properties, room=contact is not None) - def _self_update_received(self, properties): - jid = properties.jid.bare - if properties.avatar_state == AvatarState.EMPTY: - # Empty <photo/> tag, means no avatar is advertised - self._log.info('%s has no avatar published', properties.jid) - app.settings.set_account_setting(self._account, 'avatar_sha', '') - app.contacts.set_avatar(self._account, jid, None) - app.interface.update_avatar(self._account, jid) - return - - self._log.info('Update: %s %s', jid, properties.avatar_sha) - current_sha = app.settings.get_account_setting(self._account, - 'avatar_sha') - - if properties.avatar_sha != current_sha: - path = Path(configpaths.get('AVATAR')) / properties.avatar_sha - if path.exists(): - app.settings.set_account_setting(self._account, - 'avatar_sha', - properties.avatar_sha) - app.contacts.set_avatar(self._account, - jid, - properties.avatar_sha) - app.interface.update_avatar(self._account, jid) - else: - self._log.info('Request : %s', jid) - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.SELF) - else: - self._log.info('Avatar already known: %s %s', - jid, properties.avatar_sha) - def muc_disco_info_update(self, disco_info): if not disco_info.supports(Namespace.VCARD): return @@ -135,9 +130,6 @@ class VCardAvatars(BaseModule): if state == AvatarState.EMPTY: # Empty <photo/> tag, means no avatar is advertised self._log.info('%s has no avatar published', jid) - - # Remove avatar - self._log.debug('Remove: %s', jid) app.contacts.set_avatar(self._account, jid, None) if room: @@ -169,11 +161,9 @@ class VCardAvatars(BaseModule): if avatar_sha not in self._requested_shas: self._requested_shas.append(avatar_sha) if room: - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.ROOM, jid, sha=avatar_sha) + self._request_vcard(jid, avatar_sha, 'muc') else: - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.USER, jid, sha=avatar_sha) + self._request_vcard(jid, avatar_sha, 'contact') def _gc_update_received(self, properties): nick = properties.jid.resource @@ -186,9 +176,8 @@ class VCardAvatars(BaseModule): return if properties.avatar_state == AvatarState.EMPTY: - # Empty <photo/> tag, means no avatar is advertised, remove avatar + # Empty <photo/> tag, means no avatar is advertised self._log.info('%s has no avatar published', nick) - self._log.debug('Remove: %s', nick) gc_contact.avatar_sha = None app.interface.update_avatar(contact=gc_contact) else: @@ -197,9 +186,9 @@ class VCardAvatars(BaseModule): if properties.avatar_sha not in self._requested_shas: app.log('avatar').info('Request: %s', nick) self._requested_shas.append(properties.avatar_sha) - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.USER, str(properties.jid), - room=True, sha=properties.avatar_sha) + self._request_vcard(properties.jid, + properties.avatar_sha, + 'muc-user') return if gc_contact.avatar_sha != properties.avatar_sha: @@ -210,29 +199,6 @@ class VCardAvatars(BaseModule): else: self._log.info('Avatar already known: %s', nick) - def send_avatar_presence(self, force=False, after_publish=False): - if self._con.avatar_conversion: - if not after_publish: - # XEP-0398: We only resend presence after we publish a - # new avatar - return - else: - if self.avatar_advertised and not force: - self._log.debug('Avatar already advertised') - return - - self._con.update_presence() - self.avatar_advertised = True - - def add_update_node(self, node): - update = node.setTag('x', namespace=Namespace.VCARD_UPDATE) - if self._con.get_module('VCardTemp').own_vcard_received: - sha = app.settings.get_account_setting(self._account, 'avatar_sha') - own_jid = self._con.get_own_jid() - self._log.info('Send avatar presence to: %s %s', - node.getTo() or own_jid, sha or 'no sha advertised') - update.setTagData('photo', sha) - def get_instance(*args, **kwargs): return VCardAvatars(*args, **kwargs), 'VCardAvatars' ===================================== gajim/common/modules/vcard_temp.py ===================================== @@ -14,27 +14,25 @@ # XEP-0054: vcard-temp -import hashlib -import binascii -import base64 - -import nbxmpp from nbxmpp.namespaces import Namespace from gajim.common import app -from gajim.common.const import RequestAvatar from gajim.common.nec import NetworkEvent from gajim.common.modules.base import BaseModule -from gajim.common.connection_handlers_events import InformationEvent class VCardTemp(BaseModule): + + _nbxmpp_extends = 'VCardTemp' + _nbxmpp_methods = [ + 'request_vcard', + 'set_vcard', + ] + def __init__(self, con): BaseModule.__init__(self, con) self._own_vcard = None - self.own_vcard_received = False - self.room_jids = [] self.supported = False def pass_disco(self, info): @@ -48,267 +46,6 @@ class VCardTemp(BaseModule): account=self._account, feature=Namespace.VCARD)) - @staticmethod - def _node_to_dict(node): - dict_ = {} - for info in node.getChildren(): - name = info.getName() - if name in ('ADR', 'TEL', 'EMAIL'): # we can have several - dict_.setdefault(name, []) - entry = {} - for child in info.getChildren(): - entry[child.getName()] = child.getData() - dict_[name].append(entry) - elif info.getChildren() == []: - dict_[name] = info.getData() - else: - dict_[name] = {} - for child in info.getChildren(): - dict_[name][child.getName()] = child.getData() - return dict_ - - def request_vcard(self, callback=RequestAvatar.SELF, jid=None, - room=False, sha=None): - if not app.account_is_available(self._account): - return - - if isinstance(callback, RequestAvatar): - if callback == RequestAvatar.SELF: - if not self.supported: - return - callback = self._on_own_avatar_received - elif callback == RequestAvatar.ROOM: - callback = self._on_room_avatar_received - elif callback == RequestAvatar.USER: - callback = self._on_avatar_received - - if room: - room_jid = app.get_room_from_fjid(jid) - if room_jid not in self.room_jids: - self.room_jids.append(room_jid) - - iq = nbxmpp.Iq(typ='get') - if jid: - iq.setTo(jid) - iq.setQuery('vCard').setNamespace(Namespace.VCARD) - - own_jid = self._con.get_own_jid().bare - self._log.info('Request: %s, expected sha: %s', jid or own_jid, sha) - - self._con.connection.SendAndCallForResponse( - iq, self._parse_vcard, {'callback': callback, 'expected_sha': sha}) - - def send_vcard(self, vcard, sha): - if not app.account_is_available(self._account): - return - - iq = nbxmpp.Iq(typ='set') - iq2 = iq.setTag(Namespace.VCARD + ' vCard') - for i in vcard: - if i == 'jid': - continue - if isinstance(vcard[i], dict): - iq3 = iq2.addChild(i) - for j in vcard[i]: - iq3.addChild(j).setData(vcard[i][j]) - elif isinstance(vcard[i], list): - for j in vcard[i]: - iq3 = iq2.addChild(i) - for k in j: - iq3.addChild(k).setData(j[k]) - else: - iq2.addChild(i).setData(vcard[i]) - - self._log.info('Upload avatar: %s %s', self._account, sha) - - self._con.connection.SendAndCallForResponse( - iq, self._avatar_publish_result, {'sha': sha}) - - def upload_room_avatar(self, room_jid, data): - iq = nbxmpp.Iq(typ='set', to=room_jid) - vcard = iq.addChild('vCard', namespace=Namespace.VCARD) - photo = vcard.addChild('PHOTO') - photo.addChild('TYPE', payload='image/png') - photo.addChild('BINVAL', payload=data) - - self._log.info('Upload avatar: %s', room_jid) - self._con.connection.SendAndCallForResponse( - iq, self._upload_room_avatar_result) - - @staticmethod - def _upload_room_avatar_result(_nbxmpp_client, stanza): - if not nbxmpp.isResultNode(stanza): - reason = stanza.getErrorMsg() or stanza.getError() - app.nec.push_incoming_event(InformationEvent( - None, dialog_name='avatar-upload-error', args=reason)) - - def _avatar_publish_result(self, _nbxmpp_client, stanza, sha): - if stanza.getType() == 'result': - current_sha = app.settings.get_account_setting(self._account, - 'avatar_sha') - if current_sha != sha: - if not app.account_is_connected(self._account): - return - app.settings.set_account_setting( - self._account, 'avatar_sha', sha or '') - own_jid = self._con.get_own_jid().bare - app.contacts.set_avatar(self._account, own_jid, sha) - app.interface.update_avatar( - self._account, self._con.get_own_jid().bare) - self._con.get_module('VCardAvatars').send_avatar_presence( - after_publish=True) - self._log.info('%s: Published: %s', self._account, sha) - self._con.get_module('MUC').update_presence() - app.nec.push_incoming_event( - NetworkEvent('vcard-published', account=self._account)) - - elif stanza.getType() == 'error': - app.nec.push_incoming_event( - NetworkEvent('vcard-not-published', account=self._account)) - - def _get_vcard_photo(self, vcard, jid): - try: - photo = vcard['PHOTO']['BINVAL'] - except (KeyError, AttributeError, TypeError): - avatar_sha = None - photo_decoded = None - else: - if photo == '': - avatar_sha = None - photo_decoded = None - else: - try: - photo_decoded = base64.b64decode(photo.encode('utf-8')) - except binascii.Error as error: - self._log.warning('Invalid avatar for %s: %s', jid, error) - return None, None - avatar_sha = hashlib.sha1(photo_decoded).hexdigest() - - return avatar_sha, photo_decoded - - def _parse_vcard(self, _nbxmpp_client, stanza, callback, expected_sha): - frm_jid = stanza.getFrom() - room = False - if frm_jid is None: - frm_jid = self._con.get_own_jid() - elif frm_jid.bare in self.room_jids: - room = True - - resource = frm_jid.resource - jid = frm_jid.bare - - stanza_error = stanza.getError() - if stanza_error in ('service-unavailable', 'item-not-found', - 'not-allowed'): - self._log.info('vCard not available: %s %s', frm_jid, stanza_error) - callback(jid, resource, room, {}, expected_sha) - return - - vcard_node = stanza.getTag('vCard', namespace=Namespace.VCARD) - if vcard_node is None: - self._log.info('vCard not available: %s', frm_jid) - self._log.debug(stanza) - return - vcard = self._node_to_dict(vcard_node) - - if self._con.get_own_jid().bare_match(jid): - if 'NICKNAME' in vcard: - app.nicks[self._account] = vcard['NICKNAME'] - elif 'FN' in vcard: - app.nicks[self._account] = vcard['FN'] - - app.nec.push_incoming_event(NetworkEvent('vcard-received', - account=self._account, - jid=jid, - vcard_dict=vcard)) - - callback(jid, resource, room, vcard, expected_sha) - - def _on_own_avatar_received(self, jid, _resource, _room, vcard, *args): - avatar_sha, photo_decoded = self._get_vcard_photo(vcard, jid) - - self._log.info('Received own vcard, avatar sha is: %s', avatar_sha) - - self._own_vcard = vcard - self.own_vcard_received = True - - if avatar_sha is None: - # No avatar found in vcard - self._log.info('No avatar found') - app.settings.set_account_setting(self._account, 'avatar_sha', '') - app.contacts.set_avatar(self._account, jid, avatar_sha) - self._con.get_module('VCardAvatars').send_avatar_presence( - force=True) - return - - # Avatar found in vcard - current_sha = app.settings.get_account_setting(self._account, - 'avatar_sha') - if current_sha == avatar_sha: - self._con.get_module('VCardAvatars').send_avatar_presence() - else: - app.interface.save_avatar(photo_decoded) - app.contacts.set_avatar(self._account, jid, avatar_sha) - app.settings.set_account_setting( - self._account, 'avatar_sha', avatar_sha) - self._con.get_module('VCardAvatars').send_avatar_presence( - force=True) - - app.interface.update_avatar(self._account, jid) - - def _on_room_avatar_received(self, jid, _resource, _room, vcard, - expected_sha): - avatar_sha, photo_decoded = self._get_vcard_photo(vcard, jid) - if expected_sha != avatar_sha: - self._log.warning('Avatar mismatch: %s %s', jid, avatar_sha) - return - - app.interface.save_avatar(photo_decoded) - - self._log.info('Received: %s %s', jid, avatar_sha) - app.storage.cache.set_muc_avatar_sha(jid, avatar_sha) - app.contacts.set_avatar(self._account, jid, avatar_sha) - app.interface.update_avatar(self._account, jid, room_avatar=True) - - def _on_avatar_received(self, jid, resource, room, vcard, expected_sha): - request_jid = jid - if room: - request_jid = '%s/%s' % (jid, resource) - - avatar_sha, photo_decoded = self._get_vcard_photo(vcard, request_jid) - if expected_sha != avatar_sha: - self._log.warning('Received: avatar mismatch: %s %s', - request_jid, avatar_sha) - return - - app.interface.save_avatar(photo_decoded) - - # Received vCard from a contact - if room: - self._log.info('Received: %s %s', resource, avatar_sha) - contact = app.contacts.get_gc_contact(self._account, jid, resource) - if contact is not None: - contact.avatar_sha = avatar_sha - app.interface.update_avatar(contact=contact) - else: - self._log.info('Received: %s %s', jid, avatar_sha) - self._con.get_module('Roster').set_avatar_sha(jid, avatar_sha) - app.contacts.set_avatar(self._account, jid, avatar_sha) - app.interface.update_avatar(self._account, jid) - - def get_vard_name(self): - name = '' - vcard = self._own_vcard - if not vcard: - return name - - if 'N' in vcard: - if 'GIVEN' in vcard['N'] and 'FAMILY' in vcard['N']: - name = vcard['N']['GIVEN'] + ' ' + vcard['N']['FAMILY'] - if not name and 'FN' in vcard: - name = vcard['FN'] - return name - def get_instance(*args, **kwargs): return VCardTemp(*args, **kwargs), 'VCardTemp' ===================================== gajim/dialog_messages.py ===================================== @@ -133,10 +133,6 @@ messages = { 'for the chosen encryption.'), ErrorDialog), - 'avatar-upload-error': Message( - _('Avatar Upload Failed'), - '%s', - ErrorDialog), } ===================================== gajim/groupchat_control.py ===================================== @@ -35,6 +35,7 @@ from nbxmpp.const import StatusCode from nbxmpp.const import Affiliation from nbxmpp.const import PresenceType from nbxmpp.util import is_error_result +from nbxmpp.modules.vcard_temp import VCard from gi.repository import Gtk from gi.repository import Gdk @@ -43,7 +44,7 @@ from gi.repository import Gio from gajim import gtkgui_helpers from gajim import gui_menu_builder -from gajim import vcard +from gajim.vcard import VcardWindow from gajim.common import events from gajim.common import app @@ -65,7 +66,6 @@ from gajim.command_system.implementation.hosts import GroupChatCommands from gajim.gtk.dialogs import DialogButton from gajim.gtk.dialogs import ConfirmationCheckDialog -from gajim.gtk.dialogs import ErrorDialog from gajim.gtk.dialogs import ConfirmationDialog from gajim.gtk.filechoosers import AvatarChooserDialog from gajim.gtk.groupchat_config import GroupchatConfig @@ -573,20 +573,32 @@ class GroupchatControl(ChatControlBase): data, sha = app.interface.avatar_storage.prepare_for_publish( filename) if sha is None: - ErrorDialog( - _('Could not load image'), - transient_for=self.parent_win.window) + self.add_info_message(_('Loading avatar failed')) return avatar = base64.b64encode(data).decode('utf-8') + vcard = VCard() + vcard.set_avatar(avatar, 'image/png') + con = app.connections[self.account] - con.get_module('VCardTemp').upload_room_avatar( - self.room_jid, avatar) + con.get_module('VCardTemp').set_vcard( + vcard, + jid=self.room_jid, + callback=self._on_upload_avatar_result) AvatarChooserDialog(_on_accept, transient_for=self.parent_win.window, modal=True) + def _on_upload_avatar_result(self, task): + try: + task.finish() + except Exception as error: + self.add_info_message(_(f'Avatar upload failed: {error}')) + + else: + self.add_info_message(_('Avatar upload successful')) + def _on_contact_information(self, _action, param): nick = param.get_string() gc_contact = app.contacts.get_gc_contact(self.account, @@ -598,7 +610,7 @@ class GroupchatControl(ChatControlBase): window.present() else: app.interface.instances[self.account]['infos'][contact.jid] = \ - vcard.VcardWindow(contact, self.account, gc_contact) + VcardWindow(contact, self.account, gc_contact) def _on_kick(self, _action, param): nick = param.get_string() ===================================== gajim/gtk/profile.py ===================================== @@ -16,37 +16,35 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <
http://www.gnu.org/licenses/
>. -import base64 import time import logging -import hashlib from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GLib +from nbxmpp.errors import is_error +from nbxmpp.modules.vcard_temp import VCard + from gajim.common import app -from gajim.common import ged from gajim.common.i18n import _ from gajim.common.const import AvatarSize -from gajim.common.helpers import event_filter +from gajim.common.modules.util import task from gajim import gtkgui_helpers from gajim.gtk.dialogs import ErrorDialog from gajim.gtk.dialogs import InformationDialog from gajim.gtk.util import get_builder -from gajim.gtk.util import EventHelper from gajim.gtk.filechoosers import AvatarChooserDialog log = logging.getLogger('gajim.profile') -class ProfileWindow(Gtk.ApplicationWindow, EventHelper): +class ProfileWindow(Gtk.ApplicationWindow): def __init__(self, account): Gtk.ApplicationWindow.__init__(self) - EventHelper.__init__(self) self.set_application(app.app) self.set_position(Gtk.WindowPosition.CENTER) self.set_show_menubar(False) @@ -69,8 +67,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.dialog = None self.avatar_mime_type = None - self.avatar_encoded = None - self.avatar_sha = None + self._avatar_bytes = None self.message_id = self.statusbar.push(self.context_id, _('Retrieving profile…')) self.update_progressbar_timeout_id = GLib.timeout_add( @@ -78,15 +75,10 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.remove_statusbar_timeout_id = None self.xml.connect_signals(self) - self.register_events([ - ('vcard-published', ged.GUI1, self._nec_vcard_published), - ('vcard-not-published', ged.GUI1, self._nec_vcard_not_published), - ]) self.show_all() self.xml.get_object('ok_button').grab_focus() - app.connections[account].get_module('VCardTemp').request_vcard( - self._nec_vcard_received, self.jid) + self._request_vcard() def on_information_notebook_switch_page(self, widget, page, page_num): GLib.idle_add(self.xml.get_object('ok_button').grab_focus) @@ -100,6 +92,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.remove_statusbar_timeout_id = None def on_profile_window_destroy(self, widget): + app.cancel_tasks(self) if self.update_progressbar_timeout_id is not None: GLib.source_remove(self.update_progressbar_timeout_id) if self.remove_statusbar_timeout_id is not None: @@ -120,8 +113,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): button.hide() text_button = self.xml.get_object('NOPHOTO_button') text_button.show() - self.avatar_encoded = None - self.avatar_sha = None + self._avatar_bytes = None self.avatar_mime_type = None def _on_set_avatar_clicked(self, _button): @@ -144,8 +136,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): text_button = self.xml.get_object('NOPHOTO_button') text_button.hide() - self.avatar_sha = sha - self.avatar_encoded = base64.b64encode(data).decode('utf-8') + self._avatar_bytes = data self.avatar_mime_type = 'image/png' AvatarChooserDialog(on_ok, transient_for=self) @@ -176,37 +167,43 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): except AttributeError: pass - def set_values(self, vcard_): + def _set_avatar(self, vcard): + avatar, _ = vcard.get_avatar() + button = self.xml.get_object('PHOTO_button') image = self.xml.get_object('PHOTO_image') text_button = self.xml.get_object('NOPHOTO_button') - if 'PHOTO' not in vcard_: - # set default image + + if avatar is None: + image.set_from_pixbuf(None) + button.hide() + text_button.show() + return + + try: + surface = self._get_surface_from_data(avatar) + except Exception: + log.exception('Error while loading avatar') image.set_from_pixbuf(None) button.hide() text_button.show() + return + + self._avatar_bytes = avatar + self.avatar_mime_type = vcard.data['PHOTO']['TYPE'] + + image.set_from_surface(surface) + button.show() + text_button.hide() + + def _get_surface_from_data(self, data): + scale = self.get_scale_factor() + pixbuf = gtkgui_helpers.scale_pixbuf_from_data(data, AvatarSize.VCARD) + return Gdk.cairo_surface_create_from_pixbuf(pixbuf, scale) + + def set_values(self, vcard_): for i in vcard_.keys(): if i == 'PHOTO': - photo_encoded = vcard_[i]['BINVAL'] - if photo_encoded == '': - continue - self.avatar_encoded = photo_encoded - photo_decoded = base64.b64decode(photo_encoded.encode('utf-8')) - self.avatar_sha = hashlib.sha1(photo_decoded).hexdigest() - if 'TYPE' in vcard_[i]: - self.avatar_mime_type = vcard_[i]['TYPE'] - - scale = self.get_scale_factor() - surface = app.interface.avatar_storage.surface_from_filename( - self.avatar_sha, AvatarSize.VCARD, scale) - if surface is None: - pixbuf = gtkgui_helpers.scale_pixbuf_from_data( - photo_decoded, AvatarSize.VCARD) - surface = Gdk.cairo_surface_create_from_pixbuf(pixbuf, - scale) - image.set_from_surface(surface) - button.show() - text_button.hide() continue if i in ('ADR', 'TEL', 'EMAIL'): for entry in vcard_[i]: @@ -236,9 +233,6 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.progressbar.set_fraction(0) self.update_progressbar_timeout_id = None - def _nec_vcard_received(self, jid, resource, room, vcard_, *args): - self.set_values(vcard_) - def add_to_vcard(self, vcard_, entry, txt): """ Add an information to the vCard dictionary @@ -291,11 +285,10 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): vcard_['DESC'] = txt # Avatar - if self.avatar_encoded: - vcard_['PHOTO'] = {'BINVAL': self.avatar_encoded} - if self.avatar_mime_type: - vcard_['PHOTO']['TYPE'] = self.avatar_mime_type - return vcard_, self.avatar_sha + vcard = VCard(vcard_) + if self._avatar_bytes: + vcard.set_avatar(self._avatar_bytes, self.avatar_mime_type) + return vcard def on_ok_button_clicked(self, widget): if self.update_progressbar_timeout_id: @@ -308,43 +301,69 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): 'information.'), transient_for=self) return - vcard_, sha = self.make_vcard() - nick = vcard_.get('NICKNAME') or None - app.connections[self.account].get_module('UserNickname').set_nickname(nick) - if not nick: - nick = app.settings.get_account_setting(self.account, 'name') - app.nicks[self.account] = nick - app.connections[self.account].get_module('VCardTemp').send_vcard( - vcard_, sha) + + vcard_ = self.make_vcard() + + client = app.get_client(self.account) + client.get_module('VCardTemp').set_vcard( + vcard_, callback=self._on_set_vcard_result) + self._set_nickname(vcard_) + self.message_id = self.statusbar.push( self.context_id, _('Sending profile…')) self.progressbar.show() self.update_progressbar_timeout_id = GLib.timeout_add( 100, self.update_progressbar) - @event_filter(['account']) - def _nec_vcard_published(self, _event): - if self.update_progressbar_timeout_id is not None: - GLib.source_remove(self.update_progressbar_timeout_id) - self.update_progressbar_timeout_id = None - self.destroy() + @task + def _request_vcard(self): + _task = yield - @event_filter(['account']) - def _nec_vcard_not_published(self, _event): - if self.message_id: - self.statusbar.remove(self.context_id, self.message_id) - self.message_id = self.statusbar.push( - self.context_id, _('Information NOT published')) - self.remove_statusbar_timeout_id = GLib.timeout_add_seconds( - 3, self.remove_statusbar, self.message_id) - if self.update_progressbar_timeout_id is not None: - GLib.source_remove(self.update_progressbar_timeout_id) - self.progressbar.set_fraction(0) - self.update_progressbar_timeout_id = None - InformationDialog( - _('vCard publication failed'), - _('There was an error while publishing your personal information, ' - 'try again later.'), transient_for=self) + client = app.get_client(self.account) + vcard = yield client.get_module('VCardTemp').request_vcard() + + if is_error(vcard): + return + + self._set_avatar(vcard) + self.set_values(vcard.data) + + def _on_set_vcard_result(self, task_): + try: + task_.finish() + except Exception as error: + log.warning(error) + + if self.message_id: + self.statusbar.remove(self.context_id, self.message_id) + self.message_id = self.statusbar.push( + self.context_id, _('Information NOT published')) + self.remove_statusbar_timeout_id = GLib.timeout_add_seconds( + 3, self.remove_statusbar, self.message_id) + if self.update_progressbar_timeout_id is not None: + GLib.source_remove(self.update_progressbar_timeout_id) + self.progressbar.set_fraction(0) + self.update_progressbar_timeout_id = None + InformationDialog( + _('vCard publication failed'), + _('There was an error while publishing your personal information, ' + 'try again later.'), transient_for=self) + + else: + if self.update_progressbar_timeout_id is not None: + GLib.source_remove(self.update_progressbar_timeout_id) + self.update_progressbar_timeout_id = None + self.destroy() + + def _set_nickname(self, vcard): + nick = vcard.data.get('NICKNAME') or None + + client = app.get_client(self.account) + client.get_module('UserNickname').set_nickname(nick) + + if not nick: + nick = app.config.get_per('accounts', self.account, 'name') + app.nicks[self.account] = nick def on_cancel_button_clicked(self, widget): self.destroy() ===================================== gajim/gtk/server_info.py ===================================== @@ -299,7 +299,7 @@ class ServerInfo(Gtk.ApplicationWindow, EventHelper): con.get_module('HTTPUpload').available, http_upload_info), Feature('XEP-0398: Avatar Conversion', - con.avatar_conversion), + con.get_module('VCardAvatars').avatar_conversion_available), Feature('XEP-0411: Bookmarks Conversion', con.get_module('Bookmarks').conversion) ] ===================================== gajim/vcard.py ===================================== @@ -26,8 +26,7 @@ # along with Gajim. If not, see <
http://www.gnu.org/licenses/
>. import os -import base64 -import binascii +import logging from gi.repository import Gtk from gi.repository import GLib @@ -35,6 +34,7 @@ from gi.repository import Gdk from nbxmpp.structs import AnnotationNote from nbxmpp.util import is_error_result from nbxmpp.protocol import JID +from nbxmpp.errors import is_error from gajim import gtkgui_helpers from gajim.common import helpers @@ -45,10 +45,12 @@ from gajim.common.i18n import Q_ from gajim.common.i18n import _ from gajim.common.const import AvatarSize from gajim.common.nec import EventHelper +from gajim.common.modules.util import task from gajim.gtk.util import get_builder -# log = logging.getLogger('gajim.vcard') + +log = logging.getLogger('gajim.vcard') class VcardWindow(EventHelper): @@ -151,6 +153,7 @@ class VcardWindow(EventHelper): new_note = AnnotationNote(jid=self.contact.jid, data=new_annotation) con.get_module('Annotations').set_note(new_note) self.unregister_events() + app.cancel_tasks(self) def on_vcard_information_window_key_press_event(self, widget, event): if event.keyval == Gdk.KEY_Escape: @@ -181,31 +184,7 @@ class VcardWindow(EventHelper): def _set_values(self, vcard, jid): for i in vcard.keys(): - if i == 'PHOTO' and self.xml.get_object('information_notebook').\ - get_n_pages() > 4: - if 'BINVAL' not in vcard[i]: - continue - photo_encoded = vcard[i]['BINVAL'] - if photo_encoded == '': - continue - try: - photo_decoded = base64.b64decode( - photo_encoded.encode('utf-8')) - except binascii.Error as error: - app.log('avatar').warning('Invalid avatar for %s: %s', jid, error) - continue - - pixbuf = gtkgui_helpers.get_pixbuf_from_data(photo_decoded) - if pixbuf is None: - continue - self.avatar = pixbuf - pixbuf = gtkgui_helpers.scale_pixbuf(pixbuf, AvatarSize.VCARD) - surface = Gdk.cairo_surface_create_from_pixbuf( - pixbuf, self.window.get_scale_factor()) - image = self.xml.get_object('PHOTO_image') - image.set_from_surface(surface) - image.show() - self.xml.get_object('user_avatar_label').show() + if i == 'PHOTO': continue if i in ('ADR', 'TEL', 'EMAIL'): for entry in vcard[i]: @@ -225,6 +204,32 @@ class VcardWindow(EventHelper): self.set_value(i + '_label', vcard[i]) self.vcard_arrived = True + def _load_avatar(self, vcard): + if not self.xml.get_object('information_notebook').get_n_pages() > 4: + # TODO: why? + return + + try: + avatar, _ = vcard.get_avatar() + except Exception as error: + log.warning('Failed to load avatar: %s', error) + return + + if avatar is None: + return + + pixbuf = gtkgui_helpers.get_pixbuf_from_data(avatar) + pixbuf = gtkgui_helpers.scale_pixbuf(pixbuf, AvatarSize.VCARD) + + surface = Gdk.cairo_surface_create_from_pixbuf( + pixbuf, self.window.get_scale_factor()) + image = self.xml.get_object('PHOTO_image') + image.set_from_surface(surface) + image.show() + + self.avatar = pixbuf + self.xml.get_object('user_avatar_label').show() + def clear_values(self): for l in ('FN', 'NICKNAME', 'N_FAMILY', 'N_GIVEN', 'N_MIDDLE', 'N_PREFIX', 'N_SUFFIX', 'EMAIL_HOME_USERID', 'TEL_HOME_NUMBER', 'BDAY', @@ -242,9 +247,19 @@ class VcardWindow(EventHelper): widget.set_text('') self.xml.get_object('DESC_textview').get_buffer().set_text('') - def _nec_vcard_received(self, jid, resource, room, vcard, *args): + @task + def _request_vcard(self, jid): + _task = yield + + con = app.connections[self.account] + vcard = yield con.get_module('VCardTemp').request_vcard(jid=jid) + + if is_error(vcard): + return + self.clear_values() - self._set_values(vcard, jid) + self._set_values(vcard.data, str(jid)) + self._load_avatar(vcard) def set_os_info(self, result, jid): if self.xml.get_object('information_notebook').get_n_pages() < 5: @@ -448,14 +463,11 @@ class VcardWindow(EventHelper): self.fill_status_label() + jid = self.contact.jid if self.gc_contact: - con.get_module('VCardTemp').request_vcard( - self._nec_vcard_received, - self.gc_contact.get_full_jid(), - room=True) - else: - con.get_module('VCardTemp').request_vcard( - self._nec_vcard_received, self.contact.jid) + jid = self.gc_contact.get_full_jid() + + self._request_vcard(jid) def on_close_button_clicked(self, widget): self.window.destroy() View it on GitLab:
https://dev.gajim.org/gajim/gajim/-/compare/66ffec3179ec15d17a88633211498ac…
-- View it on GitLab:
https://dev.gajim.org/gajim/gajim/-/compare/66ffec3179ec15d17a88633211498ac…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/python-nbxmpp][master] 9 commits: Add error module
by Philipp Hörist
24 Sep '20
24 Sep '20
Philipp Hörist pushed to branch master at gajim / python-nbxmpp Commits: 190ce1ec by lovetox at 2020-09-22T23:21:15+02:00 Add error module - - - - - 8bd67f6f by lovetox at 2020-09-22T23:21:15+02:00 Add task module Module provides a decorator which wraps a generator in a Task The Task iterates the generator until it ends and processes the yielded values. Example: ``` @iq_request_task request_something(self, jid): task = yield response = yield get_request_iq() result = process(response) if is_error_result(result): raise StanzaError(result) yield result ``` - - - - - 192e8093 by lovetox at 2020-09-22T23:21:15+02:00 Add util module - - - - - ddb5134f by lovetox at 2020-09-22T23:21:15+02:00 Protocol: Add isError() and isResult() methods - - - - - 397d7c5a by lovetox at 2020-09-22T23:21:15+02:00 Add Namespace - - - - - 1b5bfca9 by lovetox at 2020-09-22T23:28:00+02:00 Add VCard Temp (XEP-0054) support - - - - - b1cb21dd by lovetox at 2020-09-22T23:36:19+02:00 PubSub: Rewrite and use Tasks - - - - - 13022658 by lovetox at 2020-09-22T23:37:05+02:00 Rewrite UserAvatar module - Add set_avatar() - - - - - 4d55d9a2 by lovetox at 2020-09-23T13:15:40+02:00 Connection: Add necessary methods to implement - - - - - 22 changed files: - nbxmpp/client.py - nbxmpp/connection.py - nbxmpp/dispatcher.py - + nbxmpp/errors.py - nbxmpp/modules/activity.py - nbxmpp/modules/base.py - nbxmpp/modules/bookmarks.py - nbxmpp/modules/location.py - nbxmpp/modules/mood.py - nbxmpp/modules/nickname.py - nbxmpp/modules/omemo.py - nbxmpp/modules/openpgp.py - nbxmpp/modules/pubsub.py - nbxmpp/modules/tune.py - nbxmpp/modules/user_avatar.py - + nbxmpp/modules/util.py - + nbxmpp/modules/vcard_temp.py - nbxmpp/namespaces.py - nbxmpp/protocol.py - nbxmpp/structs.py - + nbxmpp/task.py - test/unit/test_avatar.py Changes: ===================================== nbxmpp/client.py ===================================== @@ -119,6 +119,7 @@ class Client(Observable): self._mode = Mode.CLIENT self._ping_source_id = None + self._tasks = [] self._dispatcher = StanzaDispatcher(self) self._dispatcher.subscribe('before-dispatch', self._on_before_dispatch) @@ -130,6 +131,15 @@ class Client(Observable): self._state = StreamState.DISCONNECTED + def add_task(self, task): + self._tasks.append(task) + + def remove_task(self, task, _context): + try: + self._tasks.remove(task) + except Exception: + pass + @property def log_context(self): return self._log_context @@ -447,6 +457,8 @@ class Client(Observable): def _on_disconnected(self, _connection, _signal_name): self.state = StreamState.DISCONNECTED + for task in self._tasks: + task.cancel() self._remove_ping_timer() self._dispatcher.remove_ping_callback(self._ping_id) self._reset_stream() @@ -833,6 +845,8 @@ class Client(Observable): self._dispatcher.unregister_handler(*args, **kwargs) def destroy(self): + for task in self._tasks: + task.cancel() self._remove_ping_timer() self._smacks = None self._sasl = None ===================================== nbxmpp/connection.py ===================================== @@ -134,6 +134,12 @@ class Connection(Observable): def start_tls_negotiation(self): raise NotImplementedError + def shutdown_output(self): + raise NotImplementedError + + def shutdown_input(self): + raise NotImplementedError + def destroy(self): self.remove_subscriptions() self._peer_certificate = None ===================================== nbxmpp/dispatcher.py ===================================== @@ -75,6 +75,7 @@ from nbxmpp.modules.chatstates import Chatstates from nbxmpp.modules.register import Register from nbxmpp.modules.http_upload import HTTPUpload from nbxmpp.modules.mam import MAM +from nbxmpp.modules.vcard_temp import VCardTemp from nbxmpp.modules.misc import unwrap_carbon from nbxmpp.modules.misc import unwrap_mam from nbxmpp.structs import StanzaTimeoutError @@ -180,6 +181,7 @@ class StanzaDispatcher(Observable): self._modules['Register'] = Register(self._client) self._modules['HTTPUpload'] = HTTPUpload(self._client) self._modules['MAM'] = MAM(self._client) + self._modules['VCardTemp'] = VCardTemp(self._client) for instance in self._modules.values(): for handler in instance.handlers: ===================================== nbxmpp/errors.py ===================================== @@ -0,0 +1,115 @@ +# Copyright (C) 2020 Philipp Hörist <philipp AT
hoerist.com
> +# +# This file is part of nbxmpp. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 3 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; If not, see <
http://www.gnu.org/licenses/
>. + +from nbxmpp.namespaces import Namespace + + +def is_error(error): + return isinstance(error, BaseError) + + +class BaseError(Exception): + def __init__(self, is_fatal=False): + self.is_fatal = is_fatal + + +class StanzaError(BaseError): + + log_level = 'info' + app_namespace = None + + def __init__(self, stanza): + BaseError.__init__(self) + self.stanza = stanza + self._stanza_name = stanza.getName() + self._error_node = stanza.getTag('error') + self.condition = stanza.getError() + self.condition_data = self._error_node.getTagData(self.condition) + self.app_condition = self._get_app_condition() + self.type = stanza.getErrorType() + self.jid = stanza.getFrom() + self.id = stanza.getID() + self._text = {} + + text_elements = self._error_node.getTags('text', + namespace=Namespace.STANZAS) + for element in text_elements: + lang = element.getXmlLang() + text = element.getData() + self._text[lang] = text + + def _get_app_condition(self): + if self.app_namespace is None: + return None + + for node in self._error_node.getChildren(): + if node.getNamespace() == self.app_namespace: + return node.getName() + return None + + def get_text(self, pref_lang=None): + if pref_lang is not None: + text = self._text.get(pref_lang) + if text is not None: + return text + + if self._text: + text = self._text.get('en') + if text is not None: + return text + + text = self._text.get(None) + if text is not None: + return text + return self._text.popitem()[1] + return '' + + def set_text(self, lang, text): + self._text[lang] = text + + def __str__(self): + condition = self.condition + if self.app_condition is not None: + condition = '%s (%s)' % (self.condition, self.app_condition) + text = self.get_text('en') or '' + if text: + text = ' - %s' % text + return 'Error from %s: %s%s' % (self.jid, condition, text) + + +class PubSubStanzaError(StanzaError): + + app_namespace = Namespace.PUBSUB_ERROR + + +class MalformedStanzaError(BaseError): + + log_level = 'warning' + + def __init__(self, text, stanza, is_fatal=True): + BaseError.__init__(self, is_fatal=is_fatal) + self.stanza = stanza + self.text = str(text) + + +class CancelledError(BaseError): + + log_level = 'info' + + def __init__(self): + BaseError.__init__(self, is_fatal=True) + self.text = 'Task has been cancelled' ===================================== nbxmpp/modules/activity.py ===================================== @@ -25,6 +25,11 @@ from nbxmpp.modules.base import BaseModule class Activity(BaseModule): + + _depends = { + 'publish': 'PubSub' + } + def __init__(self, client): BaseModule.__init__(self, client) @@ -91,6 +96,4 @@ class Activity(BaseModule): if data.text: item.addChild('text', payload=data.text) - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').publish( - jid, Namespace.ACTIVITY, item, id_='current') + self.publish(Namespace.ACTIVITY, item, id_='current') ===================================== nbxmpp/modules/base.py ===================================== @@ -21,7 +21,17 @@ from nbxmpp.util import LogAdapter class BaseModule: + + _depends = {} + def __init__(self, client): logger_name = 'nbxmpp.m.%s' % self.__class__.__name__.lower() self._log = LogAdapter(logging.getLogger(logger_name), {'context': client.log_context}) + + def __getattr__(self, name): + if name not in self._depends: + raise AttributeError + + module = self._client.get_module(self._depends[name]) + return getattr(module, name) ===================================== nbxmpp/modules/bookmarks.py ===================================== @@ -30,11 +30,9 @@ from nbxmpp.util import to_xs_boolean from nbxmpp.util import call_on_response from nbxmpp.util import callback from nbxmpp.util import raise_error -from nbxmpp.util import is_error_result from nbxmpp.modules.pubsub import get_pubsub_item from nbxmpp.modules.pubsub import get_pubsub_items from nbxmpp.modules.pubsub import get_pubsub_request -from nbxmpp.modules.pubsub import get_publish_options from nbxmpp.modules.base import BaseModule @@ -47,13 +45,19 @@ BOOKMARK_2_OPTIONS = { 'pubsub#notify_delete': 'true', 'pubsub#notify_retract': 'true', 'pubsub#persist_items': 'true', - 'pubsub#max_items': '128', + 'pubsub#max_items': 'max', 'pubsub#access_model': 'whitelist', 'pubsub#send_last_published_item': 'never', } class Bookmarks(BaseModule): + + _depends = { + 'retract': 'PubSub', + 'publish': 'PubSub', + } + def __init__(self, client): BaseModule.__init__(self, client) @@ -71,8 +75,6 @@ class Bookmarks(BaseModule): self._bookmark_2_queue = {} self._bookmark_1_queue = [] - self._node_configuration_in_progress = False - self._node_configuration_not_possible = False def _process_pubsub_bookmarks(self, _client, stanza, properties): if not properties.is_pubsub_event: @@ -315,115 +317,44 @@ class Bookmarks(BaseModule): def retract_bookmark(self, bookmark_jid): self._log.info('Retract Bookmark: %s', bookmark_jid) - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').retract(jid, - Namespace.BOOKMARKS_2, - str(bookmark_jid)) + + self.retract(Namespace.BOOKMARKS_2, str(bookmark_jid)) def _store_bookmark_1(self, bookmarks): self._log.info('Store Bookmarks 1 (PubSub)') - jid = self._client.get_bound_jid().bare + self._bookmark_1_queue = bookmarks item = self._build_storage_node(bookmarks) - options = get_publish_options(BOOKMARK_1_OPTIONS) - self._client.get_module('PubSub').publish( - jid, - Namespace.BOOKMARKS, - item, - id_='current', - options=options, - callback=self._on_store_bookmark_result, - user_data=Namespace.BOOKMARKS) + self.publish(Namespace.BOOKMARKS, + item, + id_='current', + options=BOOKMARK_1_OPTIONS, + force_node_options=True, + callback=self._on_store_bookmark_result, + user_data=Namespace.BOOKMARKS) def _store_bookmark_2(self, bookmarks): - if self._node_configuration_not_possible: - self._log.warning('Node configuration not possible') - return - self._log.info('Store Bookmarks 2 (PubSub)') - jid = self._client.get_bound_jid().bare + for bookmark in bookmarks: self._bookmark_2_queue[bookmark.jid] = bookmark item = self._build_conference_node(bookmark) - options = get_publish_options(BOOKMARK_2_OPTIONS) - self._client.get_module('PubSub').publish( - jid, - Namespace.BOOKMARKS_2, - item, - id_=str(bookmark.jid), - options=options, - callback=self._on_store_bookmark_result, - user_data=Namespace.BOOKMARKS_2) - - def _on_store_bookmark_result(self, result, node): - if not is_error_result(result): - self._bookmark_1_queue = [] - self._bookmark_2_queue.pop(result.id, None) - return - - if (result.condition == 'conflict' and - result.app_condition == 'precondition-not-met'): - if self._node_configuration_in_progress: - return - - self._node_configuration_in_progress = True - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').get_node_configuration( - jid, - node, - callback=self._on_node_configuration_received) - - else: - self._bookmark_1_queue = [] - self._bookmark_2_queue.pop(result.id, None) - self._log.warning(result) - - def _on_node_configuration_received(self, result): - if is_error_result(result): - self._log.warning(result) - self._bookmark_1_queue = [] - self._bookmark_2_queue.clear() - return - - if result.node == Namespace.BOOKMARKS: - config = BOOKMARK_1_OPTIONS - else: - config = BOOKMARK_2_OPTIONS - self._apply_config(result.form, config) - self._client.get_module('PubSub').set_node_configuration( - result.jid, - result.node, - result.form, - callback=self._on_node_configuration_finished) - - def _on_node_configuration_finished(self, result): - self._node_configuration_in_progress = False - if is_error_result(result): - self._log.warning(result) - self._bookmark_2_queue.clear() - self._bookmark_1_queue = [] - self._node_configuration_not_possible = True - return - - self._log.info('Republish bookmarks') - if self._bookmark_2_queue: - bookmarks = self._bookmark_2_queue.copy() - self._bookmark_2_queue.clear() - self._store_bookmark_2(bookmarks.values()) - else: - bookmarks = self._bookmark_1_queue.copy() - self._bookmark_1_queue.clear() - self._store_bookmark_1(bookmarks) + self.publish(Namespace.BOOKMARKS_2, + item, + id_=str(bookmark.jid), + options=BOOKMARK_2_OPTIONS, + force_node_options=True, + callback=self._on_store_bookmark_result, + user_data=Namespace.BOOKMARKS_2) + + def _on_store_bookmark_result(self, task): + try: + result = task.finish() + except Exception as error: + self._log.warning(error) - @staticmethod - def _apply_config(form, config): - for var, value in config.items(): - try: - field = form[var] - except KeyError: - pass - else: - field.value = value + self._bookmark_1_queue = [] + self._bookmark_2_queue.pop(result.id, None) @call_on_response('_on_private_store_result') def _store_with_private(self, bookmarks): ===================================== nbxmpp/modules/location.py ===================================== @@ -24,6 +24,11 @@ from nbxmpp.modules.base import BaseModule class Location(BaseModule): + + _depends = { + 'publish': 'PubSub' + } + def __init__(self, client): BaseModule.__init__(self, client) @@ -70,6 +75,4 @@ class Location(BaseModule): if value is not None: item.addChild(tag, payload=value) - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').publish( - jid, Namespace.LOCATION, item, id_='current') + self.publish(Namespace.LOCATION, item, id_='current') ===================================== nbxmpp/modules/mood.py ===================================== @@ -25,6 +25,11 @@ from nbxmpp.modules.base import BaseModule class Mood(BaseModule): + + _depends = { + 'publish': 'PubSub' + } + def __init__(self, client): BaseModule.__init__(self, client) @@ -80,6 +85,4 @@ class Mood(BaseModule): if data.text: item.addChild('text', payload=data.text) - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').publish( - jid, Namespace.MOOD, item, id_='current') + self.publish(Namespace.MOOD, item, id_='current') ===================================== nbxmpp/modules/nickname.py ===================================== @@ -23,6 +23,11 @@ from nbxmpp.modules.base import BaseModule class Nickname(BaseModule): + + _depends = { + 'publish': 'PubSub' + } + def __init__(self, client): BaseModule.__init__(self, client) @@ -87,6 +92,5 @@ class Nickname(BaseModule): item = Node('nick', {'xmlns': Namespace.NICK}) if nickname is not None: item.addData(nickname) - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').publish( - jid, Namespace.NICK, item, id_='current') + + self.publish(Namespace.NICK, item, id_='current') ===================================== nbxmpp/modules/omemo.py ===================================== @@ -35,6 +35,11 @@ from nbxmpp.modules.base import BaseModule class OMEMO(BaseModule): + + _depends = { + 'publish': 'PubSub' + } + def __init__(self, client): BaseModule.__init__(self, client) @@ -192,9 +197,8 @@ class OMEMO(BaseModule): item.addChild('device').setAttr('id', device) self._log.info('Set devicelist: %s', devicelist) - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').publish( - jid, Namespace.OMEMO_TEMP_DL, item, id_='current') + + self.publish(Namespace.OMEMO_TEMP_DL, item, id_='current') @call_on_response('_devicelist_received') def request_devicelist(self, jid=None): @@ -225,9 +229,8 @@ class OMEMO(BaseModule): self._log.info('Set bundle') node = '%s:%s' % (Namespace.OMEMO_TEMP_BUNDLE, device_id) - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').publish( - jid, node, item, id_='current') + + self.publish(node, item, id_='current') @staticmethod def _create_bundle(bundle): ===================================== nbxmpp/modules/openpgp.py ===================================== @@ -38,6 +38,11 @@ from nbxmpp.modules.base import BaseModule class OpenPGP(BaseModule): + + _depends = { + 'publish': 'PubSub' + } + def __init__(self, client): BaseModule.__init__(self, client) @@ -154,9 +159,8 @@ class OpenPGP(BaseModule): item.addChild('pubkey-metadata', attrs=attrs) self._log.info('Set keylist: %s', keylist) - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').publish( - jid, Namespace.OPENPGP_PK, item, id_='current') + + self.publish(Namespace.OPENPGP_PK, item, id_='current') def set_public_key(self, key, fingerprint, date): date = time.strftime( @@ -168,9 +172,8 @@ class OpenPGP(BaseModule): node = '%s:%s' % (Namespace.OPENPGP_PK, fingerprint) self._log.info('Set public key') - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').publish( - jid, node, item, id_='current') + + self.publish(node, item, id_='current') @call_on_response('_public_key_received') def request_public_key(self, jid, fingerprint): @@ -274,9 +277,8 @@ class OpenPGP(BaseModule): item.setData(b64encode(secret_key)) self._log.info('Set secret key') - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').publish( - jid, Namespace.OPENPGP_SK, item, id_='current') + + self.publish(Namespace.OPENPGP_SK, item, id_='current') def parse_signcrypt(stanza): ===================================== nbxmpp/modules/pubsub.py ===================================== @@ -1,4 +1,4 @@ -# Copyright (C) 2018 Philipp Hörist <philipp AT
hoerist.com
> +# Copyright (C) 2020 Philipp Hörist <philipp AT
hoerist.com
> # # This file is part of nbxmpp. # @@ -15,20 +15,20 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <
http://www.gnu.org/licenses/
>. -from nbxmpp.namespaces import Namespace -from nbxmpp.protocol import Node -from nbxmpp.protocol import Iq -from nbxmpp.protocol import isResultNode +from collections import namedtuple + +from nbxmpp.task import iq_request_task +from nbxmpp.errors import is_error +from nbxmpp.errors import PubSubStanzaError +from nbxmpp.errors import MalformedStanzaError from nbxmpp.structs import StanzaHandler from nbxmpp.structs import PubSubEventData -from nbxmpp.structs import CommonResult -from nbxmpp.structs import PubSubConfigResult -from nbxmpp.structs import PubSubPublishResult -from nbxmpp.modules.dataforms import extend_form -from nbxmpp.util import call_on_response -from nbxmpp.util import callback -from nbxmpp.util import raise_error +from nbxmpp.protocol import Iq +from nbxmpp.protocol import Node +from nbxmpp.namespaces import Namespace from nbxmpp.modules.base import BaseModule +from nbxmpp.modules.util import process_response +from nbxmpp.modules.dataforms import extend_form class PubSub(BaseModule): @@ -84,107 +84,101 @@ class PubSub(BaseModule): id_ = item.getAttr('id') properties.pubsub_event = PubSubEventData(node, id_, item) - @call_on_response('_publish_result_received') - def publish(self, jid, node, item, id_=None, options=None): - query = Iq('set', to=jid) - pubsub = query.addChild('pubsub', namespace=Namespace.PUBSUB) - publish = pubsub.addChild('publish', {'node': node}) - attrs = {} - if id_ is not None: - attrs = {'id': id_} - publish.addChild('item', attrs, [item]) - if options: - publish = pubsub.addChild('publish-options') - publish.addChild(node=options) - return query - - @callback - def _publish_result_received(self, stanza): - if not isResultNode(stanza): - return raise_error(self._log.warning, stanza) - - jid = stanza.getFrom() - pubsub = stanza.getTag('pubsub', namespace=Namespace.PUBSUB) - if pubsub is None: - # XEP-0060: IQ payload is not mandatory on result - return PubSubPublishResult(jid, None, None) - - publish = pubsub.getTag('publish') - if publish is None: - return raise_error(self._log.warning, stanza, 'stanza-malformed') - - node = publish.getAttr('node') - item = publish.getTag('item') - if item is None: - return raise_error(self._log.warning, stanza, 'stanza-malformed') - - id_ = item.getAttr('id') - return PubSubPublishResult(jid, node, id_) - - @call_on_response('_default_response') - def retract(self, jid, node, id_, notify=True): - query = Iq('set', to=jid) - pubsub = query.addChild('pubsub', namespace=Namespace.PUBSUB) - attrs = {'node': node} - if notify: - attrs['notify'] = 'true' - retract = pubsub.addChild('retract', attrs=attrs) - retract.addChild('item', {'id': id_}) - return query - - @call_on_response('_default_response') - def set_node_configuration(self, jid, node, form): - self._log.info('Set configuration for %s %s', node, jid) - query = Iq('set', to=jid) - pubsub = query.addChild('pubsub', namespace=Namespace.PUBSUB_OWNER) - configure = pubsub.addChild('configure', {'node': node}) - form.setAttr('type', 'submit') - configure.addChild(node=form) - return query - - @call_on_response('_node_configuration_received') - def get_node_configuration(self, jid, node): - self._log.info('Request node configuration') - query = Iq('get', to=jid) - pubsub = query.addChild('pubsub', namespace=Namespace.PUBSUB_OWNER) - pubsub.addChild('configure', {'node': node}) - return query - - @callback - def _node_configuration_received(self, stanza): - if not isResultNode(stanza): - return raise_error(self._log.warning, stanza) - - jid = stanza.getFrom() - pubsub = stanza.getTag('pubsub', namespace=Namespace.PUBSUB_OWNER) - if pubsub is None: - return raise_error(self._log.warning, stanza, 'stanza-malformed', - 'No pubsub node found') - - configure = pubsub.getTag('configure') - if configure is None: - return raise_error(self._log.warning, stanza, 'stanza-malformed', - 'No configure node found') - - node = configure.getAttr('node') - - forms = configure.getTags('x', namespace=Namespace.DATA) - for form in forms: - dataform = extend_form(node=form) - form_type = dataform.vars.get('FORM_TYPE') - if form_type is None or form_type.value != Namespace.PUBSUB_CONFIG: - continue - self._log.info('Node configuration received from: %s', jid) - return PubSubConfigResult(jid=jid, node=node, form=dataform) - - return raise_error(self._log.warning, stanza, 'stanza-malformed', - 'No valid form type found') - - @callback - def _default_response(self, stanza): - if not isResultNode(stanza): - return raise_error(self._log.info, stanza) - return CommonResult(jid=stanza.getFrom()) + @iq_request_task + def request_item(self, node, id_, jid=None): + task = yield + + response = yield _make_pubsub_request(node, id_=id_, jid=jid) + + if response.isError(): + raise PubSubStanzaError(response) + + item = _get_pubsub_item(response, node, id_) + yield task.set_result(item) + + @iq_request_task + def request_items(self, node, max_items=None, jid=None): + _task = yield + + response = yield _make_pubsub_request(node, + max_items=max_items, + jid=jid) + + if response.isError(): + raise PubSubStanzaError(response) + + yield _get_pubsub_items(response, node) + + @iq_request_task + def publish(self, + node, + item, + id_=None, + options=None, + jid=None, + force_node_options=False): + + _task = yield + + request = _make_publish_request(node, item, id_, options, jid) + response = yield request + + if response.isError(): + error = PubSubStanzaError(response) + if (not force_node_options or + error.app_condition != 'precondition-not-met'): + raise error + + result = yield self.reconfigure_node(node, options, jid) + if is_error(result): + raise result + + response = yield request + if response.isError(): + raise PubSubStanzaError(response) + + jid = response.getFrom() + item_id = _get_published_item_id(response, node, id_) + yield PubSubPublishResult(jid, node, item_id) + + @iq_request_task + def retract(self, node, id_, jid=None, notify=True): + _task = yield + + response = yield _make_retract_request(node, id_, jid, notify) + yield process_response(response) + + @iq_request_task + def reconfigure_node(self, node, options, jid=None): + _task = yield + + result = yield self.get_node_configuration(node, jid) + if is_error(result): + raise result + + _apply_options(result.form, options) + result = yield self.set_node_configuration(node, result.form, jid) + yield result + + @iq_request_task + def set_node_configuration(self, node, form, jid=None): + _task = yield + + response = yield _make_node_configuration(node, form, jid) + yield process_response(response) + + @iq_request_task + def get_node_configuration(self, node, jid=None): + _task = yield + + response = yield _make_node_configuration_request(node, jid) + + if response.isError(): + raise PubSubStanzaError(response) + + jid = response.getFrom() + form = _get_configure_form(response, node) + yield PubSubNodeConfigurationResult(jid=jid, node=node, form=form) def get_pubsub_request(jid, node, id_=None, max_items=None): @@ -225,3 +219,171 @@ def get_publish_options(config): field = options.addChild('field', attrs={'var': var}) field.setTagData('value', value) return options + + +def _get_pubsub_items(response, node): + pubsub_node = response.getTag('pubsub', namespace=Namespace.PUBSUB) + if pubsub_node is None: + raise MalformedStanzaError('pubsub node missing', response) + + items_node = pubsub_node.getTag('items') + if items_node is None: + raise MalformedStanzaError('items node missing', response) + + if items_node.getAttr('node') != node: + raise MalformedStanzaError('invalid node attr', response) + + return items_node.getTags('item') + + +def _get_pubsub_item(response, node, id_): + items = _get_pubsub_items(response, node) + + if len(items) > 1: + raise MalformedStanzaError('multiple items found', response) + + if not items: + return None + + item = items[0] + if item.getAttr('id') != id_: + raise MalformedStanzaError('invalid item id', response) + + return item + + +def _make_pubsub_request(node, id_=None, max_items=None, jid=None): + query = Iq('get', to=jid) + pubsub = query.addChild('pubsub', namespace=Namespace.PUBSUB) + items = pubsub.addChild('items', {'node': node}) + if max_items is not None: + items.setAttr('max_items', max_items) + if id_ is not None: + items.addChild('item', {'id': id_}) + return query + + +def _get_configure_form(response, node): + pubsub = response.getTag('pubsub', namespace=Namespace.PUBSUB_OWNER) + if pubsub is None: + raise MalformedStanzaError('pubsub node missing', response) + + configure = pubsub.getTag('configure') + if configure is None: + raise MalformedStanzaError('configure node missing', response) + + if node != configure.getAttr('node'): + raise MalformedStanzaError('invalid node attribute', response) + + forms = configure.getTags('x', namespace=Namespace.DATA) + for form in forms: + dataform = extend_form(node=form) + form_type = dataform.vars.get('FORM_TYPE') + if form_type is None or form_type.value != Namespace.PUBSUB_CONFIG: + continue + + return dataform + + raise MalformedStanzaError('no valid form type found', response) + + +def _get_published_item_id(response, node, id_): + pubsub = response.getTag('pubsub', namespace=Namespace.PUBSUB) + if pubsub is None: + #
https://xmpp.org/extensions/xep-0060.html#publisher-publish-success
+ # If the publish request did not include an ItemID, + # the IQ-result SHOULD include an empty <item/> element + # that specifies the ItemID of the published item. + # + # If the server did not add a payload we assume the item was + # published with the id we requested + return id_ + + publish = pubsub.getTag('publish') + if publish is None: + raise MalformedStanzaError('publish node missing', response) + + if node != publish.getAttr('node'): + raise MalformedStanzaError('invalid node attribute', response) + + item = publish.getTag('item') + if item is None: + raise MalformedStanzaError('item node missing', response) + + item_id = item.getAttr('id') + if id_ is not None and item_id != id_: + raise MalformedStanzaError('invalid item id', response) + + return item_id + + +def _make_publish_request(node, item, id_, options, jid): + query = Iq('set', to=jid) + pubsub = query.addChild('pubsub', namespace=Namespace.PUBSUB) + publish = pubsub.addChild('publish', {'node': node}) + attrs = {} + if id_ is not None: + attrs = {'id': id_} + publish.addChild('item', attrs, [item]) + if options: + publish = pubsub.addChild('publish-options') + publish.addChild(node=_make_publish_options(options)) + return query + + +def _make_publish_options(options): + data = Node(Namespace.DATA + ' x', attrs={'type': 'submit'}) + field = data.addChild('field', attrs={'var': 'FORM_TYPE', 'type': 'hidden'}) + field.setTagData('value', Namespace.PUBSUB_PUBLISH_OPTIONS) + + for var, value in options.items(): + field = data.addChild('field', attrs={'var': var}) + field.setTagData('value', value) + return data + + +def _make_retract_request(node, id_, jid, notify): + query = Iq('set', to=jid) + pubsub = query.addChild('pubsub', namespace=Namespace.PUBSUB) + attrs = {'node': node} + if notify: + attrs['notify'] = 'true' + retract = pubsub.addChild('retract', attrs=attrs) + retract.addChild('item', {'id': id_}) + return query + + +def _make_node_configuration(node, form, jid): + query = Iq('set', to=jid) + pubsub = query.addChild('pubsub', namespace=Namespace.PUBSUB_OWNER) + configure = pubsub.addChild('configure', {'node': node}) + form.setAttr('type', 'submit') + configure.addChild(node=form) + return query + + +def _make_node_configuration_request(node, jid): + query = Iq('get', to=jid) + pubsub = query.addChild('pubsub', namespace=Namespace.PUBSUB_OWNER) + pubsub.addChild('configure', {'node': node}) + return query + + +def _apply_options(form, options): + for var, value in options.items(): + try: + field = form[var] + except KeyError: + pass + else: + field.value = value + + +PubSubNodeConfigurationResult = namedtuple('PubSubConfigResult', + 'jid node form') + +PubSubConfigResult = namedtuple('PubSubConfigResult', + 'jid node form') + +PubSubPublishResult = namedtuple('PubSubPublishResult', + 'jid node id') ===================================== nbxmpp/modules/tune.py ===================================== @@ -24,6 +24,11 @@ from nbxmpp.modules.base import BaseModule class Tune(BaseModule): + + _depends = { + 'publish': 'PubSub' + } + def __init__(self, client): BaseModule.__init__(self, client) @@ -70,6 +75,4 @@ class Tune(BaseModule): if value is not None: item.addChild(tag, payload=value) - jid = self._client.get_bound_jid().bare - self._client.get_module('PubSub').publish( - jid, Namespace.TUNE, item, id_='current') + self.publish(Namespace.TUNE, item, id_='current') ===================================== nbxmpp/modules/user_avatar.py ===================================== @@ -15,22 +15,37 @@ # You should have received a copy of the GNU General Public License # along with this program; If not, see <
http://www.gnu.org/licenses/
>. -import base64 +from typing import List +from typing import Dict + +import hashlib +from dataclasses import dataclass +from dataclasses import asdict +from dataclasses import field from nbxmpp.namespaces import Namespace from nbxmpp.protocol import NodeProcessed -from nbxmpp.protocol import isResultNode +from nbxmpp.protocol import Node from nbxmpp.structs import StanzaHandler -from nbxmpp.structs import AvatarMetaData -from nbxmpp.structs import AvatarData -from nbxmpp.util import call_on_response -from nbxmpp.util import callback -from nbxmpp.util import raise_error -from nbxmpp.modules.pubsub import get_pubsub_request +from nbxmpp.structs import CommonResult +from nbxmpp.util import b64encode +from nbxmpp.util import b64decode +from nbxmpp.errors import MalformedStanzaError +from nbxmpp.task import iq_request_task from nbxmpp.modules.base import BaseModule +from nbxmpp.modules.util import raise_if_error +from nbxmpp.modules.util import finalize class UserAvatar(BaseModule): + + _depends = { + 'get_node_configuration': 'PubSub', + 'set_node_configuration': 'PubSub', + 'publish': 'PubSub', + 'request_item': 'PubSub', + } + def __init__(self, client): BaseModule.__init__(self, client) @@ -65,11 +80,10 @@ class UserAvatar(BaseModule): properties.jid) return - info = metadata.getTags('info', one=True) try: - data = AvatarMetaData(**info.getAttrs()) - except Exception: - self._log.warning('Malformed user avatar data') + data = AvatarMetaData.from_node(metadata) + except Exception as error: + self._log.warning('Malformed user avatar data: %s', error) self._log.warning(stanza) raise NodeProcessed @@ -79,42 +93,255 @@ class UserAvatar(BaseModule): properties.pubsub_event = pubsub_event - @call_on_response('_avatar_data_received') - def request_avatar(self, jid, id_): - return get_pubsub_request(jid, Namespace.AVATAR_DATA, id_=id_) + @iq_request_task + def request_avatar(self, avatar_info, jid=None): + task = yield - @callback - def _avatar_data_received(self, stanza): - jid = stanza.getFrom() - if jid is None: - jid = self._client.get_bound_jid().bare + item = yield self.request_item(Namespace.AVATAR_DATA, + id_=avatar_info.id, + jid=jid) - if not isResultNode(stanza): - return raise_error(self._log.warning, stanza) + raise_if_error(item) - pubsub_node = stanza.getTag('pubsub') - items_node = pubsub_node.getTag('items') - item = items_node.getTag('item') if item is None: - return raise_error(self._log.warning, stanza, 'stanza-malformed', - 'No item in node found') + yield task.set_result(None) + + yield _get_avatar_data(item, avatar_info.id) + + @iq_request_task + def set_avatar(self, avatar, public=False): + + task = yield + + if avatar is None: + result = yield self._publish_avatar_metadata(None) + yield finalize(task, result) + + access_model = 'open' if public else 'presence' + + result = yield self._publish_avatar(avatar, access_model) + + yield finalize(task, result) + + @iq_request_task + def _publish_avatar(self, avatar, access_model): + task = yield + + options = { + 'pubsub#persist_items': 'true', + 'pubsub#access_model': access_model, + } + + for info, data in avatar.pubsub_avatar_info(): + item = _make_avatar_data_node(data) + self._log.info('Publish avatar data: %s, %s', info, access_model) + + result = yield self.publish(Namespace.AVATAR_DATA, + item, + id_=info.id, + options=options, + force_node_options=True) + + raise_if_error(result) + + result = yield self._publish_avatar_metadata(avatar.metadata) - sha = item.getAttr('id') - data_node = item.getTag('data', namespace=Namespace.AVATAR_DATA) - if data_node is None: - return raise_error(self._log.warning, stanza, 'stanza-malformed', - 'No data node found') + yield finalize(task, result) - data = data_node.getData() - if data is None: - return raise_error(self._log.warning, stanza, 'stanza-malformed', - 'Data node empty') + @iq_request_task + def _publish_avatar_metadata(self, metadata): + task = yield + + self._log.info('Publish avatar meta data: %s', metadata) + + result = yield self.publish(Namespace.AVATAR_METADATA, + metadata.to_node(), + id_='current') + + yield finalize(task, result) + + @iq_request_task + def get_access_model(self): + _task = yield + + self._log.info('Request access model') + + result = yield self.get_node_configuration(Namespace.AVATAR_DATA) + + raise_if_error(result) + + yield result.form['pubsub#access_model'].value + + @iq_request_task + def set_access_model(self, model): + task = yield + + if model not in ('open', 'presence'): + raise ValueError('Invalid access model') + + result = yield self.get_node_configuration(Namespace.AVATAR_DATA) + + raise_if_error(result) try: - data = base64.b64decode(data.encode('utf-8')) - except Exception as error: - return raise_error(self._log.warning, stanza, - 'stanza-malformed', str(error)) + access_model = result.form['pubsub#access_model'].value + except Exception: + yield task.set_error('warning', + condition='access-model-not-supported') + + if access_model == model: + jid = self._client.get_bound_jid().new_as_bare() + yield CommonResult(jid=jid) + + result.form['pubsub#access_model'].value = model + + self._log.info('Set access model %s', model) + + result = yield self.set_node_configuration(Namespace.AVATAR_DATA, + result.form) + + yield finalize(task, result) + + +def _get_avatar_data(item, id_): + data_node = item.getTag('data', namespace=Namespace.AVATAR_DATA) + if data_node is None: + raise MalformedStanzaError('data node missing', item) + + data = data_node.getData() + if not data: + raise MalformedStanzaError('data node empty', item) + + try: + avatar = b64decode(data, return_type=bytes) + except Exception as error: + raise MalformedStanzaError(f'decoding error: {error}', item) + + avatar_sha = hashlib.sha1(avatar).hexdigest() + if avatar_sha != id_: + raise MalformedStanzaError(f'avatar does not match sha', item) + + return AvatarData(data=avatar, sha=avatar_sha) + + +def _make_metadata_node(infos): + item = Node('metadata', attrs={'xmlns': Namespace.AVATAR_METADATA}) + for info in infos: + item.addChild('info', attrs=info.to_dict()) + return item + + +def _make_avatar_data_node(avatar): + item = Node('data', attrs={'xmlns': Namespace.AVATAR_DATA}) + item.setData(b64encode(avatar.data)) + return item + + +def _get_info_attrs(avatar, avatar_sha, height, width): + info_attrs = { + 'id': avatar_sha, + 'bytes': len(avatar), + 'type': 'image/png', + } + + if height is not None: + info_attrs['height'] = height + + if width is not None: + info_attrs['width'] = width + + return info_attrs + + +@dataclass +class AvatarInfo: + bytes: int + id: str + type: str + url: str = None + height: int = None + width: int = None + + def __post_init__(self): + if self.bytes is None: + raise ValueError + if self.id is None: + raise ValueError + if self.type is None: + raise ValueError + + self.bytes = int(self.bytes) + + if self.height is not None: + self.height = int(self.height) + if self.width is not None: + self.width = int(self.width) + + def to_dict(self): + info_dict = asdict(self) + if self.height is None: + info_dict.pop('height') + if self.width is None: + info_dict.pop('width') + if self.url is None: + info_dict.pop('url') + return info_dict + + +@dataclass +class AvatarData: + data: bytes + sha: str + + +@dataclass +class AvatarMetaData: + infos: List[AvatarInfo] = field(default_factory=list) + + @classmethod + def from_node(cls, node): + infos = [] + info_nodes = node.getTags('info') + for info in info_nodes: + infos.append(AvatarInfo( + bytes=info.getAttr('bytes'), + id=info.getAttr('id'), + type=info.getAttr('type'), + url=info.getAttr('url'), + height=info.getAttr('height'), + width=info.getAttr('width') + )) + return cls(infos=infos) + + def add_avatar_info(self, avatar_info): + self.infos.append(avatar_info) + + def to_node(self): + return _make_metadata_node(self.infos) + + @property + def avatar_shas(self): + return [info.id for info in self.infos] + + +@dataclass +class Avatar: + metadata: AvatarMetaData = field(default_factory=AvatarMetaData) + data: Dict[AvatarInfo, bytes] = field(init=False, default_factory=dict) + + def add_image_source(self, data, type_, height, width, url=None): + sha = hashlib.sha1(data).hexdigest() + info = AvatarInfo(bytes=len(data), + id=sha, + type=type_, + height=height, + width=width, + url=url) + self.metadata.add_avatar_info(info) + self.data[info] = AvatarData(data=data, sha=sha) - self._log.info('Received avatar data: %s %s', jid, sha) - return AvatarData(jid, sha, data) + def pubsub_avatar_info(self): + for info, data in self.data.items(): + if info.url is not None: + continue + yield info, data ===================================== nbxmpp/modules/util.py ===================================== @@ -0,0 +1,41 @@ +# Copyright (C) 2020 Philipp Hörist <philipp AT
hoerist.com
> +# +# This file is part of nbxmpp. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 3 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; If not, see <
http://www.gnu.org/licenses/
>. + +from nbxmpp.structs import CommonResult +from nbxmpp.errors import StanzaError +from nbxmpp.errors import is_error +from nbxmpp.simplexml import Node + + +def process_response(response): + if response.isError(): + raise StanzaError(response) + + return CommonResult(jid=response.getFrom()) + + +def raise_if_error(result): + if is_error(result): + raise result + + +def finalize(task, result): + if is_error(result): + raise result + if isinstance(result, Node): + return task.set_result(result) + return result ===================================== nbxmpp/modules/vcard_temp.py ===================================== @@ -0,0 +1,143 @@ +# Copyright (C) 2020 Philipp Hörist <philipp AT
hoerist.com
> +# +# This file is part of nbxmpp. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 3 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; If not, see <
http://www.gnu.org/licenses/
>. + +import hashlib +from dataclasses import dataclass +from dataclasses import field + +from nbxmpp.task import iq_request_task +from nbxmpp.util import b64decode +from nbxmpp.util import b64encode +from nbxmpp.errors import StanzaError +from nbxmpp.errors import MalformedStanzaError +from nbxmpp.protocol import Iq +from nbxmpp.simplexml import Node +from nbxmpp.namespaces import Namespace +from nbxmpp.modules.base import BaseModule +from nbxmpp.modules.util import process_response + + +class VCardTemp(BaseModule): + def __init__(self, client): + BaseModule.__init__(self, client) + + self._client = client + self.handlers = [] + + @iq_request_task + def request_vcard(self, jid=None): + _task = yield + + response = yield _make_vcard_request(jid) + + if response.isError(): + raise StanzaError(response) + + vcard_node = _get_vcard_node(response) + yield VCard.from_node(vcard_node) + + @iq_request_task + def set_vcard(self, vcard, jid=None): + _task = yield + + response = yield _make_vcard_publish(jid, vcard) + yield process_response(response) + + +def _make_vcard_request(jid): + iq = Iq(typ='get', to=jid) + iq.addChild('vCard', namespace=Namespace.VCARD) + return iq + + +def _get_vcard_node(response): + vcard_node = response.getTag('vCard', namespace=Namespace.VCARD) + if vcard_node is None: + raise MalformedStanzaError('vCard node missing', response) + return vcard_node + + +def _make_vcard_publish(jid, vcard): + iq = Iq(typ='set', to=jid) + iq.addChild(node=vcard.to_node()) + return iq + + +@dataclass +class VCard: + data: dict = field(default_factory=dict) + + @classmethod + def from_node(cls, node): + dict_ = {} + for info in node.getChildren(): + name = info.getName() + if name in ('ADR', 'TEL', 'EMAIL'): + dict_.setdefault(name, []) + entry = {} + for child in info.getChildren(): + entry[child.getName()] = child.getData() + dict_[name].append(entry) + elif info.getChildren() == []: + dict_[name] = info.getData() + else: + dict_[name] = {} + for child in info.getChildren(): + dict_[name][child.getName()] = child.getData() + + return cls(data=dict_) + + def to_node(self): + vcard = Node(tag='vCard', attrs={'xmlns': Namespace.VCARD}) + for i in self.data: + if i == 'jid': + continue + if isinstance(self.data[i], dict): + child = vcard.addChild(i) + for j in self.data[i]: + child.addChild(j).setData(self.data[i][j]) + elif isinstance(self.data[i], list): + for j in self.data[i]: + child = vcard.addChild(i) + for k in j: + child.addChild(k).setData(j[k]) + else: + vcard.addChild(i).setData(self.data[i]) + return vcard + + def set_avatar(self, avatar, type_=None): + avatar = b64encode(avatar) + if 'PHOTO' not in self.data: + self.data['PHOTO'] = {} + + self.data['PHOTO']['BINVAL'] = avatar + + if type_ is not None: + self.data['PHOTO']['TYPE'] = type_ + + def get_avatar(self): + try: + avatar = self.data['PHOTO']['BINVAL'] + except Exception: + return None, None + + if not avatar: + return None, None + + avatar = b64decode(avatar, return_type=bytes) + avatar_sha = hashlib.sha1(avatar).hexdigest() + return avatar, avatar_sha ===================================== nbxmpp/namespaces.py ===================================== @@ -121,6 +121,7 @@ class _Namespaces: PUBKEY_PUBKEY: str = 'urn:xmpp:pubkey:2' PUBKEY_REVOKE: str = 'urn:xmpp:revoke:2' PUBSUB: str = '
http://jabber.org/protocol/pubsub
' + PUBSUB_ERROR: str = '
http://jabber.org/protocol/pubsub#errors
' PUBSUB_CONFIG: str = '
http://jabber.org/protocol/pubsub#node_config
' PUBSUB_EVENT: str = '
http://jabber.org/protocol/pubsub#event
' PUBSUB_OWNER: str = '
http://jabber.org/protocol/pubsub#owner
' ===================================== nbxmpp/protocol.py ===================================== @@ -1072,6 +1072,12 @@ class Protocol(Node): if timestamp is not None: self.setTimestamp(timestamp) + def isError(self): + return self.getAttr('type') == 'error' + + def isResult(self): + return self.getAttr('type') == 'result' + def getTo(self): """ Return value of the 'to' attribute ===================================== nbxmpp/structs.py ===================================== @@ -73,10 +73,6 @@ StanzaIDData.__new__.__defaults__ = (None, None) PubSubEventData = namedtuple('PubSubEventData', 'node id item data deleted retracted purged') PubSubEventData.__new__.__defaults__ = (None, None, None, False, False, False) -PubSubConfigResult = namedtuple('PubSubConfigResult', 'jid node form') - -PubSubPublishResult = namedtuple('PubSubPublishResult', 'jid node id') - MoodData = namedtuple('MoodData', 'mood text') ActivityData = namedtuple('ActivityData', 'activity subactivity text') @@ -84,12 +80,6 @@ ActivityData = namedtuple('ActivityData', 'activity subactivity text') LocationData = namedtuple('LocationData', LOCATION_DATA) LocationData.__new__.__defaults__ = (None,) * len(LocationData._fields) -AvatarMetaData = namedtuple('AvatarMetaData', 'bytes height width id type url') -AvatarMetaData.__new__.__defaults__ = (None,) * len(AvatarMetaData._fields) - -AvatarData = namedtuple('AvatarData', 'jid sha data') -AvatarData.__new__.__defaults__ = (None,) * len(AvatarData._fields) - BookmarkData = namedtuple('BookmarkData', 'jid name nick autojoin password') BookmarkData.__new__.__defaults__ = (None, None, None, None) ===================================== nbxmpp/task.py ===================================== @@ -0,0 +1,283 @@ +# Copyright (C) 2020 Philipp Hörist <philipp AT
hoerist.com
> +# +# This file is part of nbxmpp. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 3 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; If not, see <
http://www.gnu.org/licenses/
>. + +import weakref +import inspect +import logging +from enum import IntEnum +from functools import wraps + +from nbxmpp.errors import is_error +from nbxmpp.errors import CancelledError +from nbxmpp.simplexml import Node + + +log = logging.getLogger('nbxmpp.task') + + +class _ResultSet: + pass + +ResultSet = _ResultSet() + + +class NoType: + pass + + +class TaskState(IntEnum): + INIT = 0 + RUNNING = 1 + FINISHED = 2 + CANCELLED = 3 + + @property + def is_init(self): + return self == TaskState.INIT + + @property + def is_running(self): + return self == TaskState.RUNNING + + @property + def is_finished(self): + return self == TaskState.FINISHED + + @property + def is_cancelled(self): + return self == TaskState.CANCELLED + + +def iq_request_task(func): + @wraps(func) + def func_wrapper(self, *args, + callback=None, user_data=None, **kwargs): + task = IqRequestTask(func(self, *args, **kwargs), + self._log, + self._client) + self._client.add_task(task) + task.set_finalize_func(self._client.remove_task) + task.set_user_data(user_data) + if callback is not None: + task.add_done_callback(callback) + task.start() + return task + return func_wrapper + + +def is_fatal_error(error): + if is_error(error): + return error.is_fatal + return isinstance(error, Exception) + + +class Task: + + ''' + Base class for wrapping a generator method. + + It runs the generator depending on what the generator yields. If the + generator yields another generator a sub task is created. If it yields + a type defined in _process_types, _run_async() is called which needs to + be implemented by classes. + + the implementation of _run_async() must be really async, means it should + not call _async_finished() in the same mainloop cycle. Otherwise sub tasks + may break. _async_finished() needs to call _next_step(result). + ''' + + _process_types = (NoType,) + + def __init__(self, gen, logger=log): + self._logger = logger + self._gen = gen + self._done_callbacks = [] + self._sub_task = None + self._result = None + self._error = None + self._user_data = None + self._finalize_func = None + self._finalize_context = None + self._state = TaskState.INIT + + @property + def state(self): + return self._state + + def add_done_callback(self, callback, weak=True): + if self._state in (TaskState.FINISHED, TaskState.CANCELLED): + raise RuntimeError('Task is finished') + + if weak: + if inspect.ismethod(callback): + callback = weakref.WeakMethod(callback) + elif inspect.isfunction(callback): + callback = weakref.ref(callback) + else: + ValueError('Unknown callback object') + + self._done_callbacks.append(callback) + + def start(self): + if not self._state.is_init: + raise RuntimeError('Task already started') + + self._state = TaskState.RUNNING + next(self._gen) + self._next_step(self) + + def _run_async(self, data): + raise NotImplementedError + + def _async_finished(self, *args, **kwargs): + raise NotImplementedError + + def _sub_task_completed(self, task): + self._sub_task = None + if self._state.is_cancelled: + return + + result = task.get_result() + if is_fatal_error(result): + self._error = result + self._set_finished() + else: + self._next_step(result) + + def _next_step(self, result): + try: + res = self._gen.send(result) + except StopIteration: + self._set_finished() + return + + except Exception as error: + self._log_if_fatal(error) + self._error = error + self._set_finished() + return + + if isinstance(res, self._process_types): + self._run_async(res) + + elif isinstance(res, Task): + if self._sub_task is not None: + RuntimeError('Only one sub task can be active') + + self._sub_task = res + self._sub_task.add_done_callback(self._sub_task_completed, + weak=False) + + else: + if res is not ResultSet: + self._result = res + self._set_finished() + + def _set_finished(self): + self._state = TaskState.FINISHED + self._invoke_callbacks() + self._finalize() + + def _log_if_fatal(self, error): + if is_error(error): + if error.is_fatal: + self._logger.log(error.log_level, error) + + elif isinstance(error, Exception): + self._logger.exception('Fatal Exception') + + def _invoke_callbacks(self): + for callback in self._done_callbacks: + if isinstance(callback, weakref.WeakMethod): + callback = callback() + if callback is None: + return + + callback(self) + + def set_result(self, result): + self._result = result + return ResultSet + + def get_result(self): + # if self._error is None, there was no error + # but None is a valid value for self._result + if self._error is not None: + return self._error + return self._result + + def finish(self): + if self._error is not None: + raise self._error # pylint: disable=raising-bad-type + return self._result + + def set_user_data(self, user_data): + self._user_data = user_data + + def get_user_data(self): + return self._user_data + + def set_finalize_func(self, func, context=None): + self._finalize_func = func + self._finalize_context = context + + def cancel(self): + if self._state.is_cancelled: + return + + self._state = TaskState.CANCELLED + if self._sub_task is not None: + self._sub_task.cancel() + + self._error = CancelledError() + self._invoke_callbacks() + self._finalize() + + def _finalize(self): + self._done_callbacks.clear() + self._sub_task = None + self._error = None + self._result = None + self._user_data = None + self._gen.close() + if self._finalize_func is not None: + self._finalize_func(self, self._finalize_context) + + +class IqRequestTask(Task): + + ''' + A Task for running IQ requests + + ''' + + _process_types = (Node,) + + def __init__(self, gen, logger, client): + super().__init__(gen, logger) + self._client = client + + def _run_async(self, stanza): + self._client.send_stanza(stanza, callback=self._async_finished) + + def _async_finished(self, _client, result, *args, **kwargs): + if self._state != TaskState.CANCELLED: + self._next_step(result) + + def _finalize(self): + self._client = None + super()._finalize() ===================================== test/unit/test_avatar.py ===================================== @@ -2,27 +2,27 @@ from test.lib.util import StanzaHandlerTest from nbxmpp.namespaces import Namespace from nbxmpp.structs import StanzaHandler -from nbxmpp.structs import AvatarMetaData from nbxmpp.structs import PubSubEventData - +from nbxmpp.modules.user_avatar import AvatarMetaData +from nbxmpp.modules.user_avatar import AvatarInfo class AvatarTest(StanzaHandlerTest): def test_avatar_parsing(self): def _on_message(_con, _stanza, properties): - - data = AvatarMetaData(bytes='12345', - height='64', - width='64', - id='111f4b3c50d7b0df729d299bc6f8e9ef9066971f', - type='image/png', - url='
http://avatars.example.org/happy.gif
') - + info = AvatarInfo(bytes='12345', + height='64', + width='64', + id='111f4b3c50d7b0df729d299bc6f8e9ef9066971f', + type='image/png', + url='
http://avatars.example.org/happy.gif
') + + metadata = AvatarMetaData(infos=[info]) pubsub_event = PubSubEventData( node='urn:xmpp:avatar:metadata', id='111f4b3c50d7b0df729d299bc6f8e9ef9066971f', item=None, - data=data, + data=metadata, deleted=False, retracted=False, purged=False) View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/compare/36aef2b65f653ed657e2706…
-- View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/compare/36aef2b65f653ed657e2706…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/python-nbxmpp] Deleted branch tasks
by Philipp Hörist
24 Sep '20
24 Sep '20
Philipp Hörist deleted branch tasks at gajim / python-nbxmpp -- You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/gajim][avatars] 2 commits: Refactor VCard and VCardAvatars code
by Philipp Hörist
24 Sep '20
24 Sep '20
Philipp Hörist pushed to branch avatars at gajim / gajim Commits: 11ebbaad by lovetox at 2020-09-24T09:31:59+02:00 Refactor VCard and VCardAvatars code - Move XEP-0153 code from VCard into VCardAvatars - Rely on new nbxmpp module VCardTemp - Don’t advertise avatar with XEP-0153 - - - - - 66ffec31 by lovetox at 2020-09-24T09:32:07+02:00 Refactor UserAvatar module - Adapt to nbxmpp changes - - - - - 14 changed files: - gajim/common/client.py - gajim/common/connection.py - gajim/common/const.py - gajim/common/helpers.py - gajim/common/modules/discovery.py - gajim/common/modules/presence.py - gajim/common/modules/user_avatar.py - gajim/common/modules/vcard_avatars.py - gajim/common/modules/vcard_temp.py - gajim/dialog_messages.py - gajim/groupchat_control.py - gajim/gtk/profile.py - gajim/gtk/server_info.py - gajim/vcard.py Changes: ===================================== gajim/common/client.py ===================================== @@ -57,7 +57,6 @@ class Client(ConnectionHandlers): self._priority = 0 self._connect_machine_calls = 0 - self.avatar_conversion = False self.addressing_supported = False self.is_zeroconf = False @@ -451,10 +450,6 @@ class Client(ConnectionHandlers): # We did not resume the stream, so we are not joined any MUCs self.update_presence(include_muc=False) - if not self.avatar_conversion: - # ask our VCard - self.get_module('VCardTemp').request_vcard() - self.get_module('Bookmarks').request_bookmarks() self.get_module('SoftwareVersion').set_enabled(True) self.get_module('Annotations').request_annotations() ===================================== gajim/common/connection.py ===================================== @@ -71,7 +71,6 @@ class CommonConnection: self.pep = {} self.roster_supported = True - self.avatar_conversion = False self._stun_servers = [] # STUN servers of our jabber server ===================================== gajim/common/const.py ===================================== @@ -128,13 +128,6 @@ class IdleState(Enum): AWAKE = 'online' -@unique -class RequestAvatar(IntEnum): - SELF = 0 - ROOM = 1 - USER = 2 - - @unique class PEPEventType(IntEnum): ABSTRACT = 0 ===================================== gajim/common/helpers.py ===================================== @@ -824,13 +824,7 @@ def get_subscription_request_msg(account=None): s = _('I would like to add you to my contact list.') if account: s = _('Hello, I am $name.') + ' ' + s - name = app.connections[account].get_module('VCardTemp').get_vard_name() - nick = app.nicks[account] - if name and nick: - name += ' (%s)' % nick - elif nick: - name = nick - s = Template(s).safe_substitute({'name': name}) + s = Template(s).safe_substitute({'name': app.nicks[account]}) return s def get_user_proxy(account): ===================================== gajim/common/modules/discovery.py ===================================== @@ -112,9 +112,7 @@ class Discovery(BaseModule): self._con.get_module('PEP').pass_disco(result) self._con.get_module('PubSub').pass_disco(result) self._con.get_module('Bookmarks').pass_disco(result) - - if 'urn:xmpp:pep-vcard-conversion:0' in result.features: - self._con.avatar_conversion = True + self._con.get_module('VCardAvatars').pass_disco(result) self._con.get_module('Caps').update_caps() ===================================== gajim/common/modules/presence.py ===================================== @@ -362,11 +362,6 @@ class Presence(BaseModule): nick_tag = presence.setTag('nick', namespace=Namespace.NICK) nick_tag.setData(nick) - if not self._con.avatar_conversion: - # XEP-0398 not supported by server so - # we add the avatar sha to our presence - self._con.get_module('VCardAvatars').add_update_node(presence) - if (idle_time and app.is_installed('IDLE') and app.settings.get('autoaway')): ===================================== gajim/common/modules/user_avatar.py ===================================== @@ -15,18 +15,19 @@ # XEP-0084: User Avatar from nbxmpp.namespaces import Namespace -from nbxmpp.util import is_error_result +from nbxmpp.modules.util import is_error from gajim.common import app from gajim.common.modules.base import BaseModule from gajim.common.modules.util import event_node - +from gajim.common.modules.util import task class UserAvatar(BaseModule): _nbxmpp_extends = 'UserAvatar' _nbxmpp_methods = [ - 'request_avatar' + 'request_avatar', + 'set_avatar', ] def __init__(self, con): @@ -38,12 +39,11 @@ class UserAvatar(BaseModule): if properties.pubsub_event.retracted: return - data = properties.pubsub_event.data + metadata = properties.pubsub_event.data jid = str(properties.jid) - if data is None: - # Remove avatar - self._log.info('Remove: %s', jid) + if metadata is None or not metadata.infos: + self._log.info('No avatar published: %s', jid) app.contacts.set_avatar(self._account, jid, None) self._con.get_module('Roster').set_avatar_sha(jid, None) app.interface.update_avatar(self._account, jid) @@ -54,32 +54,39 @@ class UserAvatar(BaseModule): else: sha = app.contacts.get_avatar_sha(self._account, jid) - if sha == data.id: - self._log.info('Avatar already known: %s %s', jid, data.id) + if sha in metadata.avatar_shas: + self._log.info('Avatar already known: %s %s', jid, sha) return - self._log.info('Request: %s %s', jid, data.id) - self._nbxmpp('UserAvatar').request_avatar( - jid, data.id, callback=self._avatar_received) + avatar_info = metadata.infos[0] + self._log.info('Request: %s %s', jid, avatar_info.id) + self._request_avatar(jid, avatar_info) + + @task + def _request_avatar(self, jid, avatar_info): + _task = yield + + avatar = yield self._nbxmpp('UserAvatar').request_avatar( + avatar_info, jid=jid) - def _avatar_received(self, result): - if is_error_result(result): - self._log.info(result) + if is_error(avatar): + self._log.warning(avatar) return - self._log.info('Received Avatar: %s %s', result.jid, result.sha) - app.interface.save_avatar(result.data) + self._log.info('Received Avatar: %s %s', jid, avatar.sha) + app.interface.save_avatar(avatar.data) - if self._con.get_own_jid().bare_match(result.jid): - app.settings.set_account_setting(self._account, - 'avatar_sha', - result.sha) + if self._con.get_own_jid().bare_match(jid): + app.config.set_per('accounts', + self._account, + 'avatar_sha', + avatar.sha) else: - self._con.get_module('Roster').set_avatar_sha(str(result.jid), - result.sha) + self._con.get_module('Roster').set_avatar_sha( + str(jid), avatar.sha) - app.contacts.set_avatar(self._account, str(result.jid), result.sha) - app.interface.update_avatar(self._account, str(result.jid)) + app.contacts.set_avatar(self._account, str(jid), avatar.sha) + app.interface.update_avatar(self._account, str(jid)) def get_instance(*args, **kwargs): ===================================== gajim/common/modules/vcard_avatars.py ===================================== @@ -14,16 +14,14 @@ # XEP-0153: vCard-Based Avatars -from pathlib import Path - from nbxmpp.namespaces import Namespace from nbxmpp.structs import StanzaHandler from nbxmpp.const import AvatarState +from nbxmpp.modules.util import is_error from gajim.common import app -from gajim.common import configpaths -from gajim.common.const import RequestAvatar from gajim.common.modules.base import BaseModule +from gajim.common.modules.util import task class VCardAvatars(BaseModule): @@ -38,17 +36,55 @@ class VCardAvatars(BaseModule): priority=51), ] - self.avatar_advertised = False - self._find_own_avatar() + self.avatar_conversion_available = False + + def pass_disco(self, info): + is_available = Namespace.VCARD_CONVERSION in info.features + self.avatar_conversion_available = is_available + self._log.info('Discovered Avatar Conversion') + + @task + def _request_vcard(self, jid, expected_sha, type_): + _task = yield + + vcard = yield self._con.get_module('VCardTemp').request_vcard(jid=jid) + + if is_error(vcard): + self._log.warning(vcard) + return + + avatar, avatar_sha = vcard.get_avatar() + if avatar is None: + self._log.warning('Avatar missing: %s %s', jid, expected_sha) + return - def _find_own_avatar(self): - sha = app.settings.get_account_setting(self._account, 'avatar_sha') - if not sha: + if expected_sha != avatar_sha: + self._log.warning('Avatar mismatch: %s %s != %s', + jid, + expected_sha, + avatar_sha) return - path = Path(configpaths.get('AVATAR')) / sha - if not path.exists(): - self._log.info('Missing own avatar, reset sha') - app.settings.set_account_setting(self._account, 'avatar_sha', '') + + self._log.info('Received: %s %s', jid, avatar_sha) + app.interface.save_avatar(avatar) + + if type_ == 'contact': + self._con.get_module('Roster').set_avatar_sha(jid, avatar_sha) + app.contacts.set_avatar(self._account, jid, avatar_sha) + app.interface.update_avatar(self._account, jid) + + elif type_ == 'muc': + app.storage.cache.set_muc_avatar_sha(jid, avatar_sha) + app.contacts.set_avatar(self._account, jid, avatar_sha) + app.interface.update_avatar(self._account, jid, room_avatar=True) + + elif type_ == 'muc-user': + contact = app.contacts.get_gc_contact(self._account, + jid.bare, + jid.resource) + if contact is not None: + contact.avatar_sha = avatar_sha + app.interface.update_avatar(contact=contact) def _presence_received(self, _con, _stanza, properties): if not properties.type.is_available: @@ -59,15 +95,6 @@ class VCardAvatars(BaseModule): return if self._con.get_own_jid().bare_match(properties.jid): - if self._con.get_own_jid() == properties.jid: - # Initial presence reflection - if self._con.avatar_conversion: - # XEP-0398: Tells us the current avatar sha on the - # initial presence reflection - self._self_update_received(properties) - else: - # Presence from another resource of ours - self._self_update_received(properties) return if properties.from_muc: @@ -78,38 +105,6 @@ class VCardAvatars(BaseModule): str(properties.jid)) self._update_received(properties, room=contact is not None) - def _self_update_received(self, properties): - jid = properties.jid.bare - if properties.avatar_state == AvatarState.EMPTY: - # Empty <photo/> tag, means no avatar is advertised - self._log.info('%s has no avatar published', properties.jid) - app.settings.set_account_setting(self._account, 'avatar_sha', '') - app.contacts.set_avatar(self._account, jid, None) - app.interface.update_avatar(self._account, jid) - return - - self._log.info('Update: %s %s', jid, properties.avatar_sha) - current_sha = app.settings.get_account_setting(self._account, - 'avatar_sha') - - if properties.avatar_sha != current_sha: - path = Path(configpaths.get('AVATAR')) / properties.avatar_sha - if path.exists(): - app.settings.set_account_setting(self._account, - 'avatar_sha', - properties.avatar_sha) - app.contacts.set_avatar(self._account, - jid, - properties.avatar_sha) - app.interface.update_avatar(self._account, jid) - else: - self._log.info('Request : %s', jid) - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.SELF) - else: - self._log.info('Avatar already known: %s %s', - jid, properties.avatar_sha) - def muc_disco_info_update(self, disco_info): if not disco_info.supports(Namespace.VCARD): return @@ -135,9 +130,6 @@ class VCardAvatars(BaseModule): if state == AvatarState.EMPTY: # Empty <photo/> tag, means no avatar is advertised self._log.info('%s has no avatar published', jid) - - # Remove avatar - self._log.debug('Remove: %s', jid) app.contacts.set_avatar(self._account, jid, None) if room: @@ -169,11 +161,9 @@ class VCardAvatars(BaseModule): if avatar_sha not in self._requested_shas: self._requested_shas.append(avatar_sha) if room: - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.ROOM, jid, sha=avatar_sha) + self._request_vcard(jid, avatar_sha, 'muc') else: - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.USER, jid, sha=avatar_sha) + self._request_vcard(jid, avatar_sha, 'contact') def _gc_update_received(self, properties): nick = properties.jid.resource @@ -186,9 +176,8 @@ class VCardAvatars(BaseModule): return if properties.avatar_state == AvatarState.EMPTY: - # Empty <photo/> tag, means no avatar is advertised, remove avatar + # Empty <photo/> tag, means no avatar is advertised self._log.info('%s has no avatar published', nick) - self._log.debug('Remove: %s', nick) gc_contact.avatar_sha = None app.interface.update_avatar(contact=gc_contact) else: @@ -197,9 +186,9 @@ class VCardAvatars(BaseModule): if properties.avatar_sha not in self._requested_shas: app.log('avatar').info('Request: %s', nick) self._requested_shas.append(properties.avatar_sha) - self._con.get_module('VCardTemp').request_vcard( - RequestAvatar.USER, str(properties.jid), - room=True, sha=properties.avatar_sha) + self._request_vcard(properties.jid, + properties.avatar_sha, + 'muc-user') return if gc_contact.avatar_sha != properties.avatar_sha: @@ -210,29 +199,6 @@ class VCardAvatars(BaseModule): else: self._log.info('Avatar already known: %s', nick) - def send_avatar_presence(self, force=False, after_publish=False): - if self._con.avatar_conversion: - if not after_publish: - # XEP-0398: We only resend presence after we publish a - # new avatar - return - else: - if self.avatar_advertised and not force: - self._log.debug('Avatar already advertised') - return - - self._con.update_presence() - self.avatar_advertised = True - - def add_update_node(self, node): - update = node.setTag('x', namespace=Namespace.VCARD_UPDATE) - if self._con.get_module('VCardTemp').own_vcard_received: - sha = app.settings.get_account_setting(self._account, 'avatar_sha') - own_jid = self._con.get_own_jid() - self._log.info('Send avatar presence to: %s %s', - node.getTo() or own_jid, sha or 'no sha advertised') - update.setTagData('photo', sha) - def get_instance(*args, **kwargs): return VCardAvatars(*args, **kwargs), 'VCardAvatars' ===================================== gajim/common/modules/vcard_temp.py ===================================== @@ -14,27 +14,25 @@ # XEP-0054: vcard-temp -import hashlib -import binascii -import base64 - -import nbxmpp from nbxmpp.namespaces import Namespace from gajim.common import app -from gajim.common.const import RequestAvatar from gajim.common.nec import NetworkEvent from gajim.common.modules.base import BaseModule -from gajim.common.connection_handlers_events import InformationEvent class VCardTemp(BaseModule): + + _nbxmpp_extends = 'VCardTemp' + _nbxmpp_methods = [ + 'request_vcard', + 'set_vcard', + ] + def __init__(self, con): BaseModule.__init__(self, con) self._own_vcard = None - self.own_vcard_received = False - self.room_jids = [] self.supported = False def pass_disco(self, info): @@ -48,267 +46,6 @@ class VCardTemp(BaseModule): account=self._account, feature=Namespace.VCARD)) - @staticmethod - def _node_to_dict(node): - dict_ = {} - for info in node.getChildren(): - name = info.getName() - if name in ('ADR', 'TEL', 'EMAIL'): # we can have several - dict_.setdefault(name, []) - entry = {} - for child in info.getChildren(): - entry[child.getName()] = child.getData() - dict_[name].append(entry) - elif info.getChildren() == []: - dict_[name] = info.getData() - else: - dict_[name] = {} - for child in info.getChildren(): - dict_[name][child.getName()] = child.getData() - return dict_ - - def request_vcard(self, callback=RequestAvatar.SELF, jid=None, - room=False, sha=None): - if not app.account_is_available(self._account): - return - - if isinstance(callback, RequestAvatar): - if callback == RequestAvatar.SELF: - if not self.supported: - return - callback = self._on_own_avatar_received - elif callback == RequestAvatar.ROOM: - callback = self._on_room_avatar_received - elif callback == RequestAvatar.USER: - callback = self._on_avatar_received - - if room: - room_jid = app.get_room_from_fjid(jid) - if room_jid not in self.room_jids: - self.room_jids.append(room_jid) - - iq = nbxmpp.Iq(typ='get') - if jid: - iq.setTo(jid) - iq.setQuery('vCard').setNamespace(Namespace.VCARD) - - own_jid = self._con.get_own_jid().bare - self._log.info('Request: %s, expected sha: %s', jid or own_jid, sha) - - self._con.connection.SendAndCallForResponse( - iq, self._parse_vcard, {'callback': callback, 'expected_sha': sha}) - - def send_vcard(self, vcard, sha): - if not app.account_is_available(self._account): - return - - iq = nbxmpp.Iq(typ='set') - iq2 = iq.setTag(Namespace.VCARD + ' vCard') - for i in vcard: - if i == 'jid': - continue - if isinstance(vcard[i], dict): - iq3 = iq2.addChild(i) - for j in vcard[i]: - iq3.addChild(j).setData(vcard[i][j]) - elif isinstance(vcard[i], list): - for j in vcard[i]: - iq3 = iq2.addChild(i) - for k in j: - iq3.addChild(k).setData(j[k]) - else: - iq2.addChild(i).setData(vcard[i]) - - self._log.info('Upload avatar: %s %s', self._account, sha) - - self._con.connection.SendAndCallForResponse( - iq, self._avatar_publish_result, {'sha': sha}) - - def upload_room_avatar(self, room_jid, data): - iq = nbxmpp.Iq(typ='set', to=room_jid) - vcard = iq.addChild('vCard', namespace=Namespace.VCARD) - photo = vcard.addChild('PHOTO') - photo.addChild('TYPE', payload='image/png') - photo.addChild('BINVAL', payload=data) - - self._log.info('Upload avatar: %s', room_jid) - self._con.connection.SendAndCallForResponse( - iq, self._upload_room_avatar_result) - - @staticmethod - def _upload_room_avatar_result(_nbxmpp_client, stanza): - if not nbxmpp.isResultNode(stanza): - reason = stanza.getErrorMsg() or stanza.getError() - app.nec.push_incoming_event(InformationEvent( - None, dialog_name='avatar-upload-error', args=reason)) - - def _avatar_publish_result(self, _nbxmpp_client, stanza, sha): - if stanza.getType() == 'result': - current_sha = app.settings.get_account_setting(self._account, - 'avatar_sha') - if current_sha != sha: - if not app.account_is_connected(self._account): - return - app.settings.set_account_setting( - self._account, 'avatar_sha', sha or '') - own_jid = self._con.get_own_jid().bare - app.contacts.set_avatar(self._account, own_jid, sha) - app.interface.update_avatar( - self._account, self._con.get_own_jid().bare) - self._con.get_module('VCardAvatars').send_avatar_presence( - after_publish=True) - self._log.info('%s: Published: %s', self._account, sha) - self._con.get_module('MUC').update_presence() - app.nec.push_incoming_event( - NetworkEvent('vcard-published', account=self._account)) - - elif stanza.getType() == 'error': - app.nec.push_incoming_event( - NetworkEvent('vcard-not-published', account=self._account)) - - def _get_vcard_photo(self, vcard, jid): - try: - photo = vcard['PHOTO']['BINVAL'] - except (KeyError, AttributeError, TypeError): - avatar_sha = None - photo_decoded = None - else: - if photo == '': - avatar_sha = None - photo_decoded = None - else: - try: - photo_decoded = base64.b64decode(photo.encode('utf-8')) - except binascii.Error as error: - self._log.warning('Invalid avatar for %s: %s', jid, error) - return None, None - avatar_sha = hashlib.sha1(photo_decoded).hexdigest() - - return avatar_sha, photo_decoded - - def _parse_vcard(self, _nbxmpp_client, stanza, callback, expected_sha): - frm_jid = stanza.getFrom() - room = False - if frm_jid is None: - frm_jid = self._con.get_own_jid() - elif frm_jid.bare in self.room_jids: - room = True - - resource = frm_jid.resource - jid = frm_jid.bare - - stanza_error = stanza.getError() - if stanza_error in ('service-unavailable', 'item-not-found', - 'not-allowed'): - self._log.info('vCard not available: %s %s', frm_jid, stanza_error) - callback(jid, resource, room, {}, expected_sha) - return - - vcard_node = stanza.getTag('vCard', namespace=Namespace.VCARD) - if vcard_node is None: - self._log.info('vCard not available: %s', frm_jid) - self._log.debug(stanza) - return - vcard = self._node_to_dict(vcard_node) - - if self._con.get_own_jid().bare_match(jid): - if 'NICKNAME' in vcard: - app.nicks[self._account] = vcard['NICKNAME'] - elif 'FN' in vcard: - app.nicks[self._account] = vcard['FN'] - - app.nec.push_incoming_event(NetworkEvent('vcard-received', - account=self._account, - jid=jid, - vcard_dict=vcard)) - - callback(jid, resource, room, vcard, expected_sha) - - def _on_own_avatar_received(self, jid, _resource, _room, vcard, *args): - avatar_sha, photo_decoded = self._get_vcard_photo(vcard, jid) - - self._log.info('Received own vcard, avatar sha is: %s', avatar_sha) - - self._own_vcard = vcard - self.own_vcard_received = True - - if avatar_sha is None: - # No avatar found in vcard - self._log.info('No avatar found') - app.settings.set_account_setting(self._account, 'avatar_sha', '') - app.contacts.set_avatar(self._account, jid, avatar_sha) - self._con.get_module('VCardAvatars').send_avatar_presence( - force=True) - return - - # Avatar found in vcard - current_sha = app.settings.get_account_setting(self._account, - 'avatar_sha') - if current_sha == avatar_sha: - self._con.get_module('VCardAvatars').send_avatar_presence() - else: - app.interface.save_avatar(photo_decoded) - app.contacts.set_avatar(self._account, jid, avatar_sha) - app.settings.set_account_setting( - self._account, 'avatar_sha', avatar_sha) - self._con.get_module('VCardAvatars').send_avatar_presence( - force=True) - - app.interface.update_avatar(self._account, jid) - - def _on_room_avatar_received(self, jid, _resource, _room, vcard, - expected_sha): - avatar_sha, photo_decoded = self._get_vcard_photo(vcard, jid) - if expected_sha != avatar_sha: - self._log.warning('Avatar mismatch: %s %s', jid, avatar_sha) - return - - app.interface.save_avatar(photo_decoded) - - self._log.info('Received: %s %s', jid, avatar_sha) - app.storage.cache.set_muc_avatar_sha(jid, avatar_sha) - app.contacts.set_avatar(self._account, jid, avatar_sha) - app.interface.update_avatar(self._account, jid, room_avatar=True) - - def _on_avatar_received(self, jid, resource, room, vcard, expected_sha): - request_jid = jid - if room: - request_jid = '%s/%s' % (jid, resource) - - avatar_sha, photo_decoded = self._get_vcard_photo(vcard, request_jid) - if expected_sha != avatar_sha: - self._log.warning('Received: avatar mismatch: %s %s', - request_jid, avatar_sha) - return - - app.interface.save_avatar(photo_decoded) - - # Received vCard from a contact - if room: - self._log.info('Received: %s %s', resource, avatar_sha) - contact = app.contacts.get_gc_contact(self._account, jid, resource) - if contact is not None: - contact.avatar_sha = avatar_sha - app.interface.update_avatar(contact=contact) - else: - self._log.info('Received: %s %s', jid, avatar_sha) - self._con.get_module('Roster').set_avatar_sha(jid, avatar_sha) - app.contacts.set_avatar(self._account, jid, avatar_sha) - app.interface.update_avatar(self._account, jid) - - def get_vard_name(self): - name = '' - vcard = self._own_vcard - if not vcard: - return name - - if 'N' in vcard: - if 'GIVEN' in vcard['N'] and 'FAMILY' in vcard['N']: - name = vcard['N']['GIVEN'] + ' ' + vcard['N']['FAMILY'] - if not name and 'FN' in vcard: - name = vcard['FN'] - return name - def get_instance(*args, **kwargs): return VCardTemp(*args, **kwargs), 'VCardTemp' ===================================== gajim/dialog_messages.py ===================================== @@ -133,10 +133,6 @@ messages = { 'for the chosen encryption.'), ErrorDialog), - 'avatar-upload-error': Message( - _('Avatar Upload Failed'), - '%s', - ErrorDialog), } ===================================== gajim/groupchat_control.py ===================================== @@ -35,6 +35,7 @@ from nbxmpp.const import StatusCode from nbxmpp.const import Affiliation from nbxmpp.const import PresenceType from nbxmpp.util import is_error_result +from nbxmpp.modules.vcard_temp import VCard from gi.repository import Gtk from gi.repository import Gdk @@ -43,7 +44,7 @@ from gi.repository import Gio from gajim import gtkgui_helpers from gajim import gui_menu_builder -from gajim import vcard +from gajim.vcard import VcardWindow from gajim.common import events from gajim.common import app @@ -65,7 +66,6 @@ from gajim.command_system.implementation.hosts import GroupChatCommands from gajim.gtk.dialogs import DialogButton from gajim.gtk.dialogs import ConfirmationCheckDialog -from gajim.gtk.dialogs import ErrorDialog from gajim.gtk.dialogs import ConfirmationDialog from gajim.gtk.filechoosers import AvatarChooserDialog from gajim.gtk.groupchat_config import GroupchatConfig @@ -573,20 +573,32 @@ class GroupchatControl(ChatControlBase): data, sha = app.interface.avatar_storage.prepare_for_publish( filename) if sha is None: - ErrorDialog( - _('Could not load image'), - transient_for=self.parent_win.window) + self.add_info_message(_('Loading avatar failed')) return avatar = base64.b64encode(data).decode('utf-8') + vcard = VCard() + vcard.set_avatar(avatar, 'image/png') + con = app.connections[self.account] - con.get_module('VCardTemp').upload_room_avatar( - self.room_jid, avatar) + con.get_module('VCardTemp').set_vcard( + vcard, + jid=self.room_jid, + callback=self._on_upload_avatar_result) AvatarChooserDialog(_on_accept, transient_for=self.parent_win.window, modal=True) + def _on_upload_avatar_result(self, task): + try: + task.finish() + except Exception as error: + self.add_info_message(_(f'Avatar upload failed: {error}')) + + else: + self.add_info_message(_('Avatar upload successful')) + def _on_contact_information(self, _action, param): nick = param.get_string() gc_contact = app.contacts.get_gc_contact(self.account, @@ -598,7 +610,7 @@ class GroupchatControl(ChatControlBase): window.present() else: app.interface.instances[self.account]['infos'][contact.jid] = \ - vcard.VcardWindow(contact, self.account, gc_contact) + VcardWindow(contact, self.account, gc_contact) def _on_kick(self, _action, param): nick = param.get_string() ===================================== gajim/gtk/profile.py ===================================== @@ -16,37 +16,35 @@ # You should have received a copy of the GNU General Public License # along with Gajim. If not, see <
http://www.gnu.org/licenses/
>. -import base64 import time import logging -import hashlib from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GLib +from nbxmpp.errors import is_error +from nbxmpp.modules.vcard_temp import VCard + from gajim.common import app -from gajim.common import ged from gajim.common.i18n import _ from gajim.common.const import AvatarSize -from gajim.common.helpers import event_filter +from gajim.common.modules.util import task from gajim import gtkgui_helpers from gajim.gtk.dialogs import ErrorDialog from gajim.gtk.dialogs import InformationDialog from gajim.gtk.util import get_builder -from gajim.gtk.util import EventHelper from gajim.gtk.filechoosers import AvatarChooserDialog log = logging.getLogger('gajim.profile') -class ProfileWindow(Gtk.ApplicationWindow, EventHelper): +class ProfileWindow(Gtk.ApplicationWindow): def __init__(self, account): Gtk.ApplicationWindow.__init__(self) - EventHelper.__init__(self) self.set_application(app.app) self.set_position(Gtk.WindowPosition.CENTER) self.set_show_menubar(False) @@ -69,8 +67,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.dialog = None self.avatar_mime_type = None - self.avatar_encoded = None - self.avatar_sha = None + self._avatar_bytes = None self.message_id = self.statusbar.push(self.context_id, _('Retrieving profile…')) self.update_progressbar_timeout_id = GLib.timeout_add( @@ -78,15 +75,10 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.remove_statusbar_timeout_id = None self.xml.connect_signals(self) - self.register_events([ - ('vcard-published', ged.GUI1, self._nec_vcard_published), - ('vcard-not-published', ged.GUI1, self._nec_vcard_not_published), - ]) self.show_all() self.xml.get_object('ok_button').grab_focus() - app.connections[account].get_module('VCardTemp').request_vcard( - self._nec_vcard_received, self.jid) + self._request_vcard() def on_information_notebook_switch_page(self, widget, page, page_num): GLib.idle_add(self.xml.get_object('ok_button').grab_focus) @@ -100,6 +92,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.remove_statusbar_timeout_id = None def on_profile_window_destroy(self, widget): + app.cancel_tasks(self) if self.update_progressbar_timeout_id is not None: GLib.source_remove(self.update_progressbar_timeout_id) if self.remove_statusbar_timeout_id is not None: @@ -120,8 +113,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): button.hide() text_button = self.xml.get_object('NOPHOTO_button') text_button.show() - self.avatar_encoded = None - self.avatar_sha = None + self._avatar_bytes = None self.avatar_mime_type = None def _on_set_avatar_clicked(self, _button): @@ -144,8 +136,7 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): text_button = self.xml.get_object('NOPHOTO_button') text_button.hide() - self.avatar_sha = sha - self.avatar_encoded = base64.b64encode(data).decode('utf-8') + self._avatar_bytes = data self.avatar_mime_type = 'image/png' AvatarChooserDialog(on_ok, transient_for=self) @@ -176,37 +167,43 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): except AttributeError: pass - def set_values(self, vcard_): + def _set_avatar(self, vcard): + avatar, _ = vcard.get_avatar() + button = self.xml.get_object('PHOTO_button') image = self.xml.get_object('PHOTO_image') text_button = self.xml.get_object('NOPHOTO_button') - if 'PHOTO' not in vcard_: - # set default image + + if avatar is None: + image.set_from_pixbuf(None) + button.hide() + text_button.show() + return + + try: + surface = self._get_surface_from_data(avatar) + except Exception: + log.exception('Error while loading avatar') image.set_from_pixbuf(None) button.hide() text_button.show() + return + + self._avatar_bytes = avatar + self.avatar_mime_type = vcard.data['PHOTO']['TYPE'] + + image.set_from_surface(surface) + button.show() + text_button.hide() + + def _get_surface_from_data(self, data): + scale = self.get_scale_factor() + pixbuf = gtkgui_helpers.scale_pixbuf_from_data(data, AvatarSize.VCARD) + return Gdk.cairo_surface_create_from_pixbuf(pixbuf, scale) + + def set_values(self, vcard_): for i in vcard_.keys(): if i == 'PHOTO': - photo_encoded = vcard_[i]['BINVAL'] - if photo_encoded == '': - continue - self.avatar_encoded = photo_encoded - photo_decoded = base64.b64decode(photo_encoded.encode('utf-8')) - self.avatar_sha = hashlib.sha1(photo_decoded).hexdigest() - if 'TYPE' in vcard_[i]: - self.avatar_mime_type = vcard_[i]['TYPE'] - - scale = self.get_scale_factor() - surface = app.interface.avatar_storage.surface_from_filename( - self.avatar_sha, AvatarSize.VCARD, scale) - if surface is None: - pixbuf = gtkgui_helpers.scale_pixbuf_from_data( - photo_decoded, AvatarSize.VCARD) - surface = Gdk.cairo_surface_create_from_pixbuf(pixbuf, - scale) - image.set_from_surface(surface) - button.show() - text_button.hide() continue if i in ('ADR', 'TEL', 'EMAIL'): for entry in vcard_[i]: @@ -236,9 +233,6 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): self.progressbar.set_fraction(0) self.update_progressbar_timeout_id = None - def _nec_vcard_received(self, jid, resource, room, vcard_, *args): - self.set_values(vcard_) - def add_to_vcard(self, vcard_, entry, txt): """ Add an information to the vCard dictionary @@ -291,11 +285,10 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): vcard_['DESC'] = txt # Avatar - if self.avatar_encoded: - vcard_['PHOTO'] = {'BINVAL': self.avatar_encoded} - if self.avatar_mime_type: - vcard_['PHOTO']['TYPE'] = self.avatar_mime_type - return vcard_, self.avatar_sha + vcard = VCard(vcard_) + if self._avatar_bytes: + vcard.set_avatar(self._avatar_bytes, self.avatar_mime_type) + return vcard def on_ok_button_clicked(self, widget): if self.update_progressbar_timeout_id: @@ -308,43 +301,69 @@ class ProfileWindow(Gtk.ApplicationWindow, EventHelper): 'information.'), transient_for=self) return - vcard_, sha = self.make_vcard() - nick = vcard_.get('NICKNAME') or None - app.connections[self.account].get_module('UserNickname').set_nickname(nick) - if not nick: - nick = app.settings.get_account_setting(self.account, 'name') - app.nicks[self.account] = nick - app.connections[self.account].get_module('VCardTemp').send_vcard( - vcard_, sha) + + vcard_ = self.make_vcard() + + client = app.get_client(self.account) + client.get_module('VCardTemp').set_vcard( + vcard_, callback=self._on_set_vcard_result) + self._set_nickname(vcard_) + self.message_id = self.statusbar.push( self.context_id, _('Sending profile…')) self.progressbar.show() self.update_progressbar_timeout_id = GLib.timeout_add( 100, self.update_progressbar) - @event_filter(['account']) - def _nec_vcard_published(self, _event): - if self.update_progressbar_timeout_id is not None: - GLib.source_remove(self.update_progressbar_timeout_id) - self.update_progressbar_timeout_id = None - self.destroy() + @task + def _request_vcard(self): + _task = yield - @event_filter(['account']) - def _nec_vcard_not_published(self, _event): - if self.message_id: - self.statusbar.remove(self.context_id, self.message_id) - self.message_id = self.statusbar.push( - self.context_id, _('Information NOT published')) - self.remove_statusbar_timeout_id = GLib.timeout_add_seconds( - 3, self.remove_statusbar, self.message_id) - if self.update_progressbar_timeout_id is not None: - GLib.source_remove(self.update_progressbar_timeout_id) - self.progressbar.set_fraction(0) - self.update_progressbar_timeout_id = None - InformationDialog( - _('vCard publication failed'), - _('There was an error while publishing your personal information, ' - 'try again later.'), transient_for=self) + client = app.get_client(self.account) + vcard = yield client.get_module('VCardTemp').request_vcard() + + if is_error(vcard): + return + + self._set_avatar(vcard) + self.set_values(vcard.data) + + def _on_set_vcard_result(self, task_): + try: + task_.finish() + except Exception as error: + log.warning(error) + + if self.message_id: + self.statusbar.remove(self.context_id, self.message_id) + self.message_id = self.statusbar.push( + self.context_id, _('Information NOT published')) + self.remove_statusbar_timeout_id = GLib.timeout_add_seconds( + 3, self.remove_statusbar, self.message_id) + if self.update_progressbar_timeout_id is not None: + GLib.source_remove(self.update_progressbar_timeout_id) + self.progressbar.set_fraction(0) + self.update_progressbar_timeout_id = None + InformationDialog( + _('vCard publication failed'), + _('There was an error while publishing your personal information, ' + 'try again later.'), transient_for=self) + + else: + if self.update_progressbar_timeout_id is not None: + GLib.source_remove(self.update_progressbar_timeout_id) + self.update_progressbar_timeout_id = None + self.destroy() + + def _set_nickname(self, vcard): + nick = vcard.data.get('NICKNAME') or None + + client = app.get_client(self.account) + client.get_module('UserNickname').set_nickname(nick) + + if not nick: + nick = app.config.get_per('accounts', self.account, 'name') + app.nicks[self.account] = nick def on_cancel_button_clicked(self, widget): self.destroy() ===================================== gajim/gtk/server_info.py ===================================== @@ -299,7 +299,7 @@ class ServerInfo(Gtk.ApplicationWindow, EventHelper): con.get_module('HTTPUpload').available, http_upload_info), Feature('XEP-0398: Avatar Conversion', - con.avatar_conversion), + con.get_module('VCardAvatars').avatar_conversion_available), Feature('XEP-0411: Bookmarks Conversion', con.get_module('Bookmarks').conversion) ] ===================================== gajim/vcard.py ===================================== @@ -26,8 +26,7 @@ # along with Gajim. If not, see <
http://www.gnu.org/licenses/
>. import os -import base64 -import binascii +import logging from gi.repository import Gtk from gi.repository import GLib @@ -35,6 +34,7 @@ from gi.repository import Gdk from nbxmpp.structs import AnnotationNote from nbxmpp.util import is_error_result from nbxmpp.protocol import JID +from nbxmpp.errors import is_error from gajim import gtkgui_helpers from gajim.common import helpers @@ -45,10 +45,12 @@ from gajim.common.i18n import Q_ from gajim.common.i18n import _ from gajim.common.const import AvatarSize from gajim.common.nec import EventHelper +from gajim.common.modules.util import task from gajim.gtk.util import get_builder -# log = logging.getLogger('gajim.vcard') + +log = logging.getLogger('gajim.vcard') class VcardWindow(EventHelper): @@ -151,6 +153,7 @@ class VcardWindow(EventHelper): new_note = AnnotationNote(jid=self.contact.jid, data=new_annotation) con.get_module('Annotations').set_note(new_note) self.unregister_events() + app.cancel_tasks(self) def on_vcard_information_window_key_press_event(self, widget, event): if event.keyval == Gdk.KEY_Escape: @@ -181,31 +184,7 @@ class VcardWindow(EventHelper): def _set_values(self, vcard, jid): for i in vcard.keys(): - if i == 'PHOTO' and self.xml.get_object('information_notebook').\ - get_n_pages() > 4: - if 'BINVAL' not in vcard[i]: - continue - photo_encoded = vcard[i]['BINVAL'] - if photo_encoded == '': - continue - try: - photo_decoded = base64.b64decode( - photo_encoded.encode('utf-8')) - except binascii.Error as error: - app.log('avatar').warning('Invalid avatar for %s: %s', jid, error) - continue - - pixbuf = gtkgui_helpers.get_pixbuf_from_data(photo_decoded) - if pixbuf is None: - continue - self.avatar = pixbuf - pixbuf = gtkgui_helpers.scale_pixbuf(pixbuf, AvatarSize.VCARD) - surface = Gdk.cairo_surface_create_from_pixbuf( - pixbuf, self.window.get_scale_factor()) - image = self.xml.get_object('PHOTO_image') - image.set_from_surface(surface) - image.show() - self.xml.get_object('user_avatar_label').show() + if i == 'PHOTO': continue if i in ('ADR', 'TEL', 'EMAIL'): for entry in vcard[i]: @@ -225,6 +204,32 @@ class VcardWindow(EventHelper): self.set_value(i + '_label', vcard[i]) self.vcard_arrived = True + def _load_avatar(self, vcard): + if not self.xml.get_object('information_notebook').get_n_pages() > 4: + # TODO: why? + return + + try: + avatar, _ = vcard.get_avatar() + except Exception as error: + log.warning('Failed to load avatar: %s', error) + return + + if avatar is None: + return + + pixbuf = gtkgui_helpers.get_pixbuf_from_data(avatar) + pixbuf = gtkgui_helpers.scale_pixbuf(pixbuf, AvatarSize.VCARD) + + surface = Gdk.cairo_surface_create_from_pixbuf( + pixbuf, self.window.get_scale_factor()) + image = self.xml.get_object('PHOTO_image') + image.set_from_surface(surface) + image.show() + + self.avatar = pixbuf + self.xml.get_object('user_avatar_label').show() + def clear_values(self): for l in ('FN', 'NICKNAME', 'N_FAMILY', 'N_GIVEN', 'N_MIDDLE', 'N_PREFIX', 'N_SUFFIX', 'EMAIL_HOME_USERID', 'TEL_HOME_NUMBER', 'BDAY', @@ -242,9 +247,19 @@ class VcardWindow(EventHelper): widget.set_text('') self.xml.get_object('DESC_textview').get_buffer().set_text('') - def _nec_vcard_received(self, jid, resource, room, vcard, *args): + @task + def _request_vcard(self, jid): + _task = yield + + con = app.connections[self.account] + vcard = yield con.get_module('VCardTemp').request_vcard(jid=jid) + + if is_error(vcard): + return + self.clear_values() - self._set_values(vcard, jid) + self._set_values(vcard.data, str(jid)) + self._load_avatar(vcard) def set_os_info(self, result, jid): if self.xml.get_object('information_notebook').get_n_pages() < 5: @@ -448,14 +463,11 @@ class VcardWindow(EventHelper): self.fill_status_label() + jid = self.contact.jid if self.gc_contact: - con.get_module('VCardTemp').request_vcard( - self._nec_vcard_received, - self.gc_contact.get_full_jid(), - room=True) - else: - con.get_module('VCardTemp').request_vcard( - self._nec_vcard_received, self.contact.jid) + jid = self.gc_contact.get_full_jid() + + self._request_vcard(jid) def on_close_button_clicked(self, widget): self.window.destroy() View it on GitLab:
https://dev.gajim.org/gajim/gajim/-/compare/f0c45711954c1a3299412943700d80e…
-- View it on GitLab:
https://dev.gajim.org/gajim/gajim/-/compare/f0c45711954c1a3299412943700d80e…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
← Newer
1
...
321
322
323
324
325
326
327
...
1764
Older →
Jump to page:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
Results per page:
10
25
50
100
200