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] Pushed new tag 3.2.0
by Philipp Hörist (ï¼ lovetox)
28 Aug '22
28 Aug '22
Philipp Hörist pushed new tag 3.2.0 at gajim / python-nbxmpp -- View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/tree/3.2.0
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/python-nbxmpp][master] release: 3.2.0
by Philipp Hörist (ï¼ lovetox)
28 Aug '22
28 Aug '22
Philipp Hörist pushed to branch master at gajim / python-nbxmpp Commits: 4597ea9c by lovetox at 2022-08-28T20:59:12+02:00 release: 3.2.0 - - - - - 3 changed files: - ChangeLog - nbxmpp/__init__.py - setup.cfg Changes: ===================================== ChangeLog ===================================== @@ -1,3 +1,13 @@ +nbxmpp 3.2.0 (28 Aug 2022) + + New + + * Add support for Extensible SASL Profile (XEP-0388) + + Bug Fixes + + * Set timeout for host-meta http query (#130) + nbxmpp 3.1.1 (27 Jul 2022) Improvements ===================================== nbxmpp/__init__.py ===================================== @@ -4,4 +4,4 @@ from .protocol import * gi.require_version('Soup', '2.4') -__version__: str = '3.1.1' +__version__: str = '3.2.0' ===================================== setup.cfg ===================================== @@ -1,6 +1,6 @@ [metadata] name = nbxmpp -version = 3.1.1 +version = 3.2.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/4597ea9c2bfc0dc60f2cf75a…
-- View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/commit/4597ea9c2bfc0dc60f2cf75a…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/python-nbxmpp] Deleted branch sasl2
by Philipp Hörist (ï¼ lovetox)
28 Aug '22
28 Aug '22
Philipp Hörist deleted branch sasl2 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: feat: Add support for Extensible SASL Profile (XEP-0388)
by Philipp Hörist (ï¼ lovetox)
28 Aug '22
28 Aug '22
Philipp Hörist pushed to branch master at gajim / python-nbxmpp Commits: f1305fc9 by lovetox at 2022-08-28T20:21:28+02:00 feat: Add support for Extensible SASL Profile (XEP-0388) - - - - - b1d80691 by lovetox at 2022-08-28T20:23:52+02:00 chore: Update doap - - - - - 5 changed files: - nbxmpp/client.py - nbxmpp/namespaces.py - nbxmpp/protocol.py - nbxmpp/sasl.py - python-nbxmpp.doap Changes: ===================================== nbxmpp/client.py ===================================== @@ -692,7 +692,10 @@ class Client(Observable): elif self.state == StreamState.AUTH_SUCCESSFUL: self._stream_authenticated = True - self._start_stream() + if self._sasl.is_sasl2(): + self.state = StreamState.WAIT_FOR_FEATURES + else: + self._start_stream() elif self.state == StreamState.AUTH_FAILED: self._disconnect_with_error(StreamError.SASL, @@ -786,7 +789,7 @@ class Client(Observable): self.state = StreamState.WAIT_FOR_TLS_PROCEED def _start_auth(self, features): - if not features.has_sasl(): + if not features.has_sasl() and not features.has_sasl_2(): self._log.error('Server does not support SASL') self._disconnect_with_error(StreamError.SASL, 'sasl-not-supported') ===================================== nbxmpp/namespaces.py ===================================== @@ -143,6 +143,7 @@ class _Namespaces: ROSTER_VER: str = 'urn:xmpp:features:rosterver' RSM: str = '
http://jabber.org/protocol/rsm
' SASL: str = 'urn:ietf:params:xml:ns:xmpp-sasl' + SASL2: str = 'urn:xmpp:sasl:1' SEARCH: str = 'jabber:iq:search' SECLABEL: str = 'urn:xmpp:sec-label:0' SECLABEL_CATALOG: str = 'urn:xmpp:sec-label:catalog:2' ===================================== nbxmpp/protocol.py ===================================== @@ -1709,10 +1709,15 @@ class Features(Node): def has_sasl(self): return self.getTag('mechanisms', namespace=Namespace.SASL) is not None + def has_sasl_2(self): + return self.getTag('mechanisms', namespace=Namespace.SASL2) is not None + def get_mechs(self) -> set[str]: - mechanisms = self.getTag('mechanisms', namespace=Namespace.SASL) + mechanisms = self.getTag('mechanisms', namespace=Namespace.SASL2) if mechanisms is None: - return set() + mechanisms = self.getTag('mechanisms', namespace=Namespace.SASL) + if mechanisms is None: + return set() mechanisms = mechanisms.getTags('mechanism') return set(mech.getData() for mech in mechanisms) ===================================== nbxmpp/sasl.py ===================================== @@ -15,13 +15,15 @@ # 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 typing import Any +from typing import Optional + import os import hmac import binascii import logging import hashlib from hashlib import pbkdf2_hmac -from typing import Optional from nbxmpp.namespaces import Namespace from nbxmpp.protocol import Node @@ -66,6 +68,8 @@ class SASL: self._allowed_mechs = None self._enabled_mechs = None + self._sasl_ns = None + self._mechanism = None self._error = None self._log = LogAdapter(log, {'context': client.log_context}) @@ -74,6 +78,10 @@ class SASL: def error(self): return self._error + def is_sasl2(self) -> bool: + assert self._sasl_ns is not None + return self._sasl_ns == Namespace.SASL2 + def set_password(self, password): self._password = password @@ -82,8 +90,9 @@ class SASL: return self._password def delegate(self, stanza): - if stanza.getNamespace() != Namespace.SASL: + if stanza.getNamespace() != self._sasl_ns: return + if stanza.getName() == 'challenge': self._on_challenge(stanza) elif stanza.getName() == 'failure': @@ -95,6 +104,11 @@ class SASL: self._allowed_mechs = self._client.mechs self._enabled_mechs = self._allowed_mechs self._mechanism = None + + self._sasl_ns = Namespace.SASL + if features.has_sasl_2(): + self._sasl_ns = Namespace.SASL2 + self._error = None # -PLUS variants need TLS channel binding data @@ -153,15 +167,13 @@ class SASL: return def _send_initiate(self) -> None: + assert self._mechanism is not None data = self._mechanism.get_initiate_data() - node = Node('auth', - attrs={'xmlns': Namespace.SASL, - 'mechanism': self._mechanism.name}) - if data is not None: - node.setData(data) - self._client.send_nonza(node) + nonza = get_initiate_nonza(self._sasl_ns, self._mechanism.name, data) + self._client.send_nonza(nonza) def _on_challenge(self, stanza) -> None: + assert self._mechanism is not None try: data = self._mechanism.get_response_data(stanza.getData()) except AttributeError: @@ -174,22 +186,21 @@ class SASL: self._abort_auth() return - node = Node('response', - attrs={'xmlns': Namespace.SASL}, - payload=[data]) - self._client.send_nonza(node) + nonza = get_response_nonza(self._sasl_ns, data) + self._client.send_nonza(nonza) def _on_success(self, stanza): self._log.info('Successfully authenticated with remote server') + data = get_success_data(stanza, self._sasl_ns) try: - self._mechanism.get_success_data(stanza.getData()) - except AttributeError: - pass - except AuthFail as error: - self._log.error(error) + self._mechanism.validate_success_data(data) + except Exception as error: + self._log.error('Unable to validate success data: %s', error) self._abort_auth() return + self._log.info('Validated success data') + self._on_sasl_finished(True, None, None) def _on_failure(self, stanza): @@ -208,7 +219,7 @@ class SASL: self._abort_auth(reason, text) def _abort_auth(self, reason='malformed-request', text=None): - node = Node('abort', attrs={'xmlns': Namespace.SASL}) + node = Node('abort', attrs={'xmlns': self._sasl_ns}) self._client.send_nonza(node) self._on_sasl_finished(False, reason, text) @@ -220,6 +231,33 @@ class SASL: self._client.set_state(StreamState.AUTH_SUCCESSFUL) +def get_initiate_nonza(ns: str, + mechanism: str, + data: Optional[str]) -> Any: + + if ns == Namespace.SASL: + node = Node('auth', attrs={'xmlns': ns, 'mechanism': mechanism}) + if data is not None: + node.setData(data) + + else: + node = Node('authenticate', attrs={'xmlns': ns, 'mechanism': mechanism}) + if data is not None: + node.setTagData('initial-response', data) + + return node + + +def get_response_nonza(ns: str, data: str) -> Any: + return Node('response', attrs={'xmlns': ns}, payload=[data]) + + +def get_success_data(stanza: Any, ns: str) -> Optional[str]: + if ns == Namespace.SASL2: + return stanza.getTagData('additional-data') + return stanza.getData() + + class BaseMechanism: name: str @@ -235,8 +273,8 @@ class BaseMechanism: def get_response_data(self, data: str) -> str: raise NotImplementedError - def validate_success_data(self, data: str) -> None: - raise NotImplementedError + def validate_success_data(self, _data: str) -> None: + return None class PLAIN(BaseMechanism): ===================================== python-nbxmpp.doap ===================================== @@ -379,6 +379,14 @@ <xmpp:version>0.1</xmpp:version> </xmpp:SupportedXep> </implements> + <implements> + <xmpp:SupportedXep> + <xmpp:xep rdf:resource="
https://xmpp.org/extensions/xep-0388.html
"/> + <xmpp:status>partial</xmpp:status> + <xmpp:version>0.3.0</xmpp:version> + <xmpp:note>No support for 'continue' flows</xmpp:note> + </xmpp:SupportedXep> + </implements> <implements> <xmpp:SupportedXep> <xmpp:xep rdf:resource="
https://xmpp.org/extensions/xep-0392.html
"/> View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/compare/18c408c07afc6df5dbd5de4…
-- View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/compare/18c408c07afc6df5dbd5de4…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/python-nbxmpp][sasl2] chore: Update doap
by Philipp Hörist (ï¼ lovetox)
28 Aug '22
28 Aug '22
Philipp Hörist pushed to branch sasl2 at gajim / python-nbxmpp Commits: b1d80691 by lovetox at 2022-08-28T20:23:52+02:00 chore: Update doap - - - - - 1 changed file: - python-nbxmpp.doap Changes: ===================================== python-nbxmpp.doap ===================================== @@ -379,6 +379,14 @@ <xmpp:version>0.1</xmpp:version> </xmpp:SupportedXep> </implements> + <implements> + <xmpp:SupportedXep> + <xmpp:xep rdf:resource="
https://xmpp.org/extensions/xep-0388.html
"/> + <xmpp:status>partial</xmpp:status> + <xmpp:version>0.3.0</xmpp:version> + <xmpp:note>No support for 'continue' flows</xmpp:note> + </xmpp:SupportedXep> + </implements> <implements> <xmpp:SupportedXep> <xmpp:xep rdf:resource="
https://xmpp.org/extensions/xep-0392.html
"/> View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/commit/b1d80691c531b2fe7bd4c8ba…
-- View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/commit/b1d80691c531b2fe7bd4c8ba…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/python-nbxmpp][sasl2] feat: Add support for Extensible SASL Profile (XEP-0388)
by Philipp Hörist (ï¼ lovetox)
28 Aug '22
28 Aug '22
Philipp Hörist pushed to branch sasl2 at gajim / python-nbxmpp Commits: f1305fc9 by lovetox at 2022-08-28T20:21:28+02:00 feat: Add support for Extensible SASL Profile (XEP-0388) - - - - - 4 changed files: - nbxmpp/client.py - nbxmpp/namespaces.py - nbxmpp/protocol.py - nbxmpp/sasl.py Changes: ===================================== nbxmpp/client.py ===================================== @@ -692,7 +692,10 @@ class Client(Observable): elif self.state == StreamState.AUTH_SUCCESSFUL: self._stream_authenticated = True - self._start_stream() + if self._sasl.is_sasl2(): + self.state = StreamState.WAIT_FOR_FEATURES + else: + self._start_stream() elif self.state == StreamState.AUTH_FAILED: self._disconnect_with_error(StreamError.SASL, @@ -786,7 +789,7 @@ class Client(Observable): self.state = StreamState.WAIT_FOR_TLS_PROCEED def _start_auth(self, features): - if not features.has_sasl(): + if not features.has_sasl() and not features.has_sasl_2(): self._log.error('Server does not support SASL') self._disconnect_with_error(StreamError.SASL, 'sasl-not-supported') ===================================== nbxmpp/namespaces.py ===================================== @@ -143,6 +143,7 @@ class _Namespaces: ROSTER_VER: str = 'urn:xmpp:features:rosterver' RSM: str = '
http://jabber.org/protocol/rsm
' SASL: str = 'urn:ietf:params:xml:ns:xmpp-sasl' + SASL2: str = 'urn:xmpp:sasl:1' SEARCH: str = 'jabber:iq:search' SECLABEL: str = 'urn:xmpp:sec-label:0' SECLABEL_CATALOG: str = 'urn:xmpp:sec-label:catalog:2' ===================================== nbxmpp/protocol.py ===================================== @@ -1709,10 +1709,15 @@ class Features(Node): def has_sasl(self): return self.getTag('mechanisms', namespace=Namespace.SASL) is not None + def has_sasl_2(self): + return self.getTag('mechanisms', namespace=Namespace.SASL2) is not None + def get_mechs(self) -> set[str]: - mechanisms = self.getTag('mechanisms', namespace=Namespace.SASL) + mechanisms = self.getTag('mechanisms', namespace=Namespace.SASL2) if mechanisms is None: - return set() + mechanisms = self.getTag('mechanisms', namespace=Namespace.SASL) + if mechanisms is None: + return set() mechanisms = mechanisms.getTags('mechanism') return set(mech.getData() for mech in mechanisms) ===================================== nbxmpp/sasl.py ===================================== @@ -15,13 +15,15 @@ # 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 typing import Any +from typing import Optional + import os import hmac import binascii import logging import hashlib from hashlib import pbkdf2_hmac -from typing import Optional from nbxmpp.namespaces import Namespace from nbxmpp.protocol import Node @@ -66,6 +68,8 @@ class SASL: self._allowed_mechs = None self._enabled_mechs = None + self._sasl_ns = None + self._mechanism = None self._error = None self._log = LogAdapter(log, {'context': client.log_context}) @@ -74,6 +78,10 @@ class SASL: def error(self): return self._error + def is_sasl2(self) -> bool: + assert self._sasl_ns is not None + return self._sasl_ns == Namespace.SASL2 + def set_password(self, password): self._password = password @@ -82,8 +90,9 @@ class SASL: return self._password def delegate(self, stanza): - if stanza.getNamespace() != Namespace.SASL: + if stanza.getNamespace() != self._sasl_ns: return + if stanza.getName() == 'challenge': self._on_challenge(stanza) elif stanza.getName() == 'failure': @@ -95,6 +104,11 @@ class SASL: self._allowed_mechs = self._client.mechs self._enabled_mechs = self._allowed_mechs self._mechanism = None + + self._sasl_ns = Namespace.SASL + if features.has_sasl_2(): + self._sasl_ns = Namespace.SASL2 + self._error = None # -PLUS variants need TLS channel binding data @@ -153,15 +167,13 @@ class SASL: return def _send_initiate(self) -> None: + assert self._mechanism is not None data = self._mechanism.get_initiate_data() - node = Node('auth', - attrs={'xmlns': Namespace.SASL, - 'mechanism': self._mechanism.name}) - if data is not None: - node.setData(data) - self._client.send_nonza(node) + nonza = get_initiate_nonza(self._sasl_ns, self._mechanism.name, data) + self._client.send_nonza(nonza) def _on_challenge(self, stanza) -> None: + assert self._mechanism is not None try: data = self._mechanism.get_response_data(stanza.getData()) except AttributeError: @@ -174,22 +186,21 @@ class SASL: self._abort_auth() return - node = Node('response', - attrs={'xmlns': Namespace.SASL}, - payload=[data]) - self._client.send_nonza(node) + nonza = get_response_nonza(self._sasl_ns, data) + self._client.send_nonza(nonza) def _on_success(self, stanza): self._log.info('Successfully authenticated with remote server') + data = get_success_data(stanza, self._sasl_ns) try: - self._mechanism.get_success_data(stanza.getData()) - except AttributeError: - pass - except AuthFail as error: - self._log.error(error) + self._mechanism.validate_success_data(data) + except Exception as error: + self._log.error('Unable to validate success data: %s', error) self._abort_auth() return + self._log.info('Validated success data') + self._on_sasl_finished(True, None, None) def _on_failure(self, stanza): @@ -208,7 +219,7 @@ class SASL: self._abort_auth(reason, text) def _abort_auth(self, reason='malformed-request', text=None): - node = Node('abort', attrs={'xmlns': Namespace.SASL}) + node = Node('abort', attrs={'xmlns': self._sasl_ns}) self._client.send_nonza(node) self._on_sasl_finished(False, reason, text) @@ -220,6 +231,33 @@ class SASL: self._client.set_state(StreamState.AUTH_SUCCESSFUL) +def get_initiate_nonza(ns: str, + mechanism: str, + data: Optional[str]) -> Any: + + if ns == Namespace.SASL: + node = Node('auth', attrs={'xmlns': ns, 'mechanism': mechanism}) + if data is not None: + node.setData(data) + + else: + node = Node('authenticate', attrs={'xmlns': ns, 'mechanism': mechanism}) + if data is not None: + node.setTagData('initial-response', data) + + return node + + +def get_response_nonza(ns: str, data: str) -> Any: + return Node('response', attrs={'xmlns': ns}, payload=[data]) + + +def get_success_data(stanza: Any, ns: str) -> Optional[str]: + if ns == Namespace.SASL2: + return stanza.getTagData('additional-data') + return stanza.getData() + + class BaseMechanism: name: str @@ -235,8 +273,8 @@ class BaseMechanism: def get_response_data(self, data: str) -> str: raise NotImplementedError - def validate_success_data(self, data: str) -> None: - raise NotImplementedError + def validate_success_data(self, _data: str) -> None: + return None class PLAIN(BaseMechanism): View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/commit/f1305fc956c90cbf2b20d7e5…
-- View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/commit/f1305fc956c90cbf2b20d7e5…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/gajim][archive_cache] 10 commits: chore: Update DOAP file
by Daniel Brötzmann (ï¼ wurstsalat)
28 Aug '22
28 Aug '22
Daniel Brötzmann pushed to branch archive_cache at gajim / gajim Commits: 0e17e748 by wurstsalat at 2022-08-24T20:23:34+02:00 chore: Update DOAP file - - - - - 8a6b117a by wurstsalat at 2022-08-24T20:48:16+02:00 imprv: MessageActionsBox: Disable encryption button if MUC is public Fixes #10959 - - - - - f9a3eaad by wurstsalat at 2022-08-26T17:38:27+02:00 fix: Chatstates: Don’t sent chatstate delayed to ourself - - - - - 63c362f5 by wurstsalat at 2022-08-26T23:29:54+02:00 imprv: ChatList: Always show when switching workspace Fixes #11108 - - - - - 2cf04a23 by Daniel Brötzmann at 2022-08-27T11:09:45+00:00 feat: Add drag and drop support for pinned chats - - - - - 5125e2c0 by wurstsalat at 2022-08-27T14:06:16+02:00 chore: Control: Remove obsolete code - - - - - 8431f218 by wurstsalat at 2022-08-27T14:08:08+02:00 fix: Preview: Sanitize filename from disallowed chars Fixes #11105, #10752 - - - - - ae53799c by lovetox at 2022-08-28T17:45:14+02:00 new: Add event storage - - - - - 88f324b5 by wurstsalat at 2022-08-28T17:45:14+02:00 Add more events - - - - - 3f3f2484 by wurstsalat at 2022-08-28T17:45:34+02:00 Add more events 2 - - - - - 26 changed files: - data/gajim.doap - gajim/common/app.py - gajim/common/application.py - gajim/common/events.py - gajim/common/helpers.py - gajim/common/modules/chatstates.py - gajim/common/modules/contacts.py - gajim/common/modules/muc.py - gajim/common/preview_helpers.py - gajim/common/setting_values.py - gajim/common/settings.py - gajim/common/storage/base.py - + gajim/common/storage/events.py - gajim/data/gui/message_actions_box.ui - gajim/gtk/chat_banner.py - gajim/gtk/chat_list.py - gajim/gtk/chat_list_stack.py - gajim/gtk/chat_page.py - gajim/gtk/chat_stack.py - gajim/gtk/control.py - gajim/gtk/conversation/view.py - gajim/gtk/groupchat_nick_completion.py - gajim/gtk/groupchat_roster.py - gajim/gtk/main.py - gajim/gtk/message_actions_box.py - + test/no_gui/test_sanitize_filename.py Changes: ===================================== data/gajim.doap ===================================== @@ -170,8 +170,9 @@ <implements> <xmpp:SupportedXep> <xmpp:xep rdf:resource="
https://xmpp.org/extensions/xep-0071.html
"/> - <xmpp:status>complete</xmpp:status> + <xmpp:status>removed</xmpp:status> <xmpp:version>1.4</xmpp:version> + <xmpp:since>1.4.0</xmpp:since> </xmpp:SupportedXep> </implements> <implements> @@ -343,8 +344,9 @@ <implements> <xmpp:SupportedXep> <xmpp:xep rdf:resource="
https://xmpp.org/extensions/xep-0174.html
"/> - <xmpp:status>complete</xmpp:status> + <xmpp:status>removed</xmpp:status> <xmpp:version>2.0</xmpp:version> + <xmpp:since>1.4.0</xmpp:since> </xmpp:SupportedXep> </implements> <implements> @@ -673,7 +675,7 @@ <xmpp:SupportedXep> <xmpp:xep rdf:resource="
https://xmpp.org/extensions/xep-0441.html
"/> <xmpp:status>complete</xmpp:status> - <xmpp:version>0.2</xmpp:version> + <xmpp:version>0.2.0</xmpp:version> </xmpp:SupportedXep> </implements> <implements> ===================================== gajim/common/app.py ===================================== @@ -59,6 +59,7 @@ from gajim.gui.application import GajimApplication from gajim.common.storage.cache import CacheStorage from gajim.common.storage.archive import MessageArchiveStorage + from gajim.common.storage.events import EventStorage from gajim.common.cert_store import CertificateStore from gajim.common.call_manager import CallManager from gajim.common.preview import PreviewManager @@ -88,6 +89,7 @@ class Storage: def __init__(self): self.cache: CacheStorage = None self.archive: MessageArchiveStorage = None + self.events: EventStorage = None storage = Storage() ===================================== gajim/common/application.py ===================================== @@ -44,6 +44,7 @@ from gajim.common.events import GajimUpdateAvailable from gajim.common.client import Client from gajim.common.helpers import make_http_request +from gajim.common.storage.events import EventStorage from gajim.common.task_manager import TaskManager from gajim.common.settings import Settings from gajim.common.settings import LegacyConfig @@ -74,6 +75,9 @@ def _init_core(self) -> None: app.storage.cache = CacheStorage() app.storage.cache.init() + app.storage.events = EventStorage() + app.storage.events.init() + app.storage.archive = MessageArchiveStorage() app.storage.archive.init() ===================================== gajim/common/events.py ===================================== @@ -32,7 +32,10 @@ from nbxmpp.structs import LocationData from nbxmpp.structs import RosterItem from nbxmpp.structs import TuneData +from nbxmpp.const import Affiliation from nbxmpp.const import InviteType +from nbxmpp.const import Role +from nbxmpp.const import StatusCode from gajim.common.file_props import FileProp from gajim.common.const import JingleState @@ -676,3 +679,100 @@ class AllowGajimUpdateCheck(ApplicationEvent): class GajimUpdateAvailable(ApplicationEvent): name: str = field(init=False, default='gajim-update-available') version: str + + +@dataclass +class MUCNicknameChanged(ApplicationEvent): + name: str = field(init=False, default='muc-nickname-changed') + is_self: bool + new_name: str + old_name: str + timestamp: float + + +@dataclass +class MUCRoomConfigChanged(ApplicationEvent): + name: str = field(init=False, default='muc-room-config-changed') + timestamp: float + status_codes: set[StatusCode] + + +@dataclass +class MUCRoomConfigFinished(ApplicationEvent): + name: str = field(init=False, default='muc-room-config-finished') + timestamp: float + + +@dataclass +class MUCRoomPresenceError(ApplicationEvent): + name: str = field(init=False, default='muc-room-presence-error') + timestamp: float + error: Any + + +@dataclass +class MUCRoomKicked(ApplicationEvent): + name: str = field(init=False, default='muc-room-kicked') + timestamp: float + status_codes: Optional[set[StatusCode]] + reason: Optional[str] + actor: Optional[str] + + +@dataclass +class MUCRoomDestroyed(ApplicationEvent): + name: str = field(init=False, default='muc-room-destroyed') + timestamp: float + reason: Optional[str] + alternate: Optional[JID] + + +@dataclass +class MUCUserJoined(ApplicationEvent): + name: str = field(init=False, default='muc-user-joined') + timestamp: float + is_self: bool + nick: str + status_codes: Optional[set[StatusCode]] + + +@dataclass +class MUCUserLeft(ApplicationEvent): + name: str = field(init=False, default='muc-user-left') + timestamp: float + nick: str + status_codes: Optional[set[StatusCode]] + reason: Optional[str] + actor: Optional[str] + + +@dataclass +class MUCUserRoleChanged(ApplicationEvent): + name: str = field(init=False, default='muc-user-role-changed') + timestamp: float + is_self: bool + nick: str + role: Role + reason: Optional[str] + actor: Optional[str] + + +@dataclass +class MUCUserAffiliationChanged(ApplicationEvent): + name: str = field(init=False, default='muc-user-affiliation-changed') + timestamp: float + is_self: bool + nick: str + affiliation: Affiliation + reason: Optional[str] + actor: Optional[str] + + +@dataclass +class MUCUserStatusShowChanged(ApplicationEvent): + name: str = field(init=False, default='muc-user-status-show-changed') + timestamp: float + is_self: bool + nick: str + status: str + show_value: str ===================================== gajim/common/helpers.py ===================================== @@ -37,7 +37,6 @@ import re import os import subprocess -import base64 import hashlib import shlex import socket @@ -58,10 +57,10 @@ from datetime import timedelta from urllib.parse import unquote from urllib.parse import urlparse -from encodings.punycode import punycode_encode from functools import wraps from pathlib import Path from packaging.version import Version as V +import unicodedata from nbxmpp.namespaces import Namespace from nbxmpp.const import Role @@ -358,28 +357,40 @@ def get_file_path_from_dnd_dropped_uri(uri: str) -> str: def sanitize_filename(filename: str) -> str: ''' - Make sure the filename we will write does contain only acceptable and latin - characters, and is not too long (in that case hash it) + Sanitize filename of elements not allowed on Windows +
https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
+ Limit filename length to 50 chars on all systems ''' - # 48 is the limit - if len(filename) > 48: - hash_ = hashlib.md5(filename.encode('utf-8')) - filename = base64.b64encode(hash_.digest()).decode('utf-8') - - # make it latin chars only - filename = punycode_encode(filename).decode('utf-8') - filename = filename.replace('/', '_') - if os.name == 'nt': - filename = filename.replace('?', '_')\ - .replace(':', '_')\ - .replace('\\', '_')\ - .replace('"', "'")\ - .replace('|', '_')\ - .replace('*', '_')\ - .replace('<', '_')\ - .replace('>', '_') - - return filename + if sys.platform == 'win32': + blacklist = ['\\', '/', ':', '*', '?', '"', '<', '>', '|', '\0'] + reserved_filenames = [ + 'CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', + 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2', 'LPT3', 'LPT4', + 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9', + ] + filename = ''.join(char for char in filename if char not in blacklist) + + filename = ''.join(char for char in filename if 31 < ord(char)) + + filename = unicodedata.normalize('NFKD', filename) + filename = filename.rstrip('. ') + filename = filename.strip() + + if all(char == '.' for char in filename): + filename = f'__{filename}' + if filename.upper() in reserved_filenames: + filename = f'__{filename}' + if len(filename) == 0: + filename = '__' + + extension = Path(filename).suffix[:10] + filename = Path(filename).stem + final_length = 50 - len(extension) + + # Many Filesystems have a limit on filename length: keep it short + filename = filename[:final_length] + + return f'{filename}{extension}' def get_contact_dict_for_account(account: str) -> dict[str, types.BareContact]: ===================================== gajim/common/modules/chatstates.py ===================================== @@ -253,6 +253,11 @@ def set_chatstate_delayed(self, # Used when we go from Composing -> Active after deleting all text # from the Textview. We delay the Active state because maybe the # User starts writing again. + + # Don’t send chatstates to ourself + if self._con.get_own_jid().bare_match(contact.jid): + return + self.remove_delay_timeout(contact) self._delay_timeout_ids[contact.jid] = GLib.timeout_add_seconds( 2, self.set_chatstate, contact, state) ===================================== gajim/common/modules/contacts.py ===================================== @@ -15,11 +15,14 @@ from __future__ import annotations from typing import Any +from typing import cast from typing import Iterator from typing import Optional from typing import Union from typing import overload +import time + import cairo from nbxmpp.const import Affiliation from nbxmpp.const import Chatstate @@ -29,9 +32,12 @@ from nbxmpp.structs import DiscoInfo from nbxmpp.structs import LocationData from nbxmpp.structs import TuneData +from nbxmpp.structs import MessageProperties from nbxmpp.structs import MucSubject +from nbxmpp.structs import PresenceProperties from gajim.common import app +from gajim.common import events from gajim.common import types from gajim.common.const import PresenceShowExt from gajim.common.const import SimpleClientState @@ -671,6 +677,15 @@ def is_irc(self) -> bool: return False return disco_info.is_irc + @property + def encryption_available(self) -> bool: + disco_info = self.get_disco() + if disco_info is None: + return True + + return (disco_info.muc_is_members_only and + disco_info.muc_is_nonanonymous) + def get_config_value(self, field_name: str) -> Any: disco_info = self.get_disco() assert disco_info is not None @@ -933,12 +948,31 @@ def update_presence(self, if not self._presence.available and presence.available: self._presence = presence - self.notify('user-joined', *args) + + properties = cast(MessageProperties, args[0]) + event = events.MUCUserJoined( + timestamp=time.time(), + is_self=properties.is_muc_self_presence, + nick=self.name, + status_codes=properties.muc_status_codes) + + app.storage.events.store(self, event) + self.notify('user-joined', event) return if not presence.available: self._presence = presence - self.notify('user-left', *args) + + properties = cast(MessageProperties, args[0]) + event = events.MUCUserLeft( + timestamp=time.time(), + nick=self.name, + status_codes=properties.muc_status_codes, + reason=properties.muc_user.reason, + actor=properties.muc_user.actor) + + app.storage.events.store(self, event) + self.notify('user-left', event) return signals: list[str] = [] @@ -953,8 +987,39 @@ def update_presence(self, signals.append('user-status-show-changed') self._presence = presence + for signal in signals: - self.notify(signal, *args) + if signal == 'user-affiliation-changed': + properties = cast(PresenceProperties, args[0]) + event = events.MUCUserAffiliationChanged( + timestamp=time.time(), + is_self=properties.is_muc_self_presence, + nick=self.name, + affiliation=self.affiliation, + reason=properties.muc_user.reason, + actor=properties.muc_user.actor) + + if signal == 'user-role-changed': + properties = cast(PresenceProperties, args[0]) + event = events.MUCUserRoleChanged( + timestamp=time.time(), + is_self=properties.is_muc_self_presence, + nick=self.name, + role=self.role, + reason=properties.muc_user.reason, + actor=properties.muc_user.actor) + + if signal == 'user-status-show-changed': + properties = cast(PresenceProperties, args[0]) + event = events.MUCUserStatusShowChanged( + timestamp=time.time(), + is_self=properties.is_muc_self_presence, + nick=self.name, + status=properties.status, + show_value=properties.show.value) + + app.storage.events.store(self, event) + self.notify(signal, event) def update_avatar(self, *args: Any) -> None: app.app.avatar_storage.invalidate_cache(self._jid) ===================================== gajim/common/modules/muc.py ===================================== @@ -44,6 +44,7 @@ from gi.repository import GLib from gajim.common import app +from gajim.common import events from gajim.common import helpers from gajim.common import types from gajim.common.const import ClientState, KindConstant @@ -456,7 +457,11 @@ def _on_disco_result_after_config(self, task: Task) -> None: self._log.info('Configuration finished: %s', jid) room = self._get_contact(jid.bare) - room.notify('room-config-finished') + event = events.MUCRoomConfigFinished(timestamp=time.time()) + + assert isinstance(room, GroupchatContact) + app.storage.events.store(room, event) + room.notify('room-config-finished', event) def update_presence(self) -> None: mucs = self._get_mucs_with_state([MUCJoinedState.JOINED, @@ -536,6 +541,11 @@ def _on_error_presence(self, self._set_muc_state(room_jid, MUCJoinedState.NOT_JOINED) else: + event = events.MUCRoomPresenceError( + timestamp=time.time(), + error=properties.error) + assert isinstance(room, GroupchatContact) + app.storage.events.store(room, event) room.notify('room-presence-error', properties) def _on_muc_user_presence(self, @@ -560,7 +570,15 @@ def _on_muc_user_presence(self, self._set_muc_state(room_jid, MUCJoinedState.NOT_JOINED) self._con.get_module('Bookmarks').remove(room_jid) room.set_not_joined() - room.notify('room-destroyed', properties) + + event = events.MUCRoomDestroyed( + timestamp=time.time(), + reason=properties.muc_destroyed.reason, + alternate=properties.muc_destroyed.alternate) + assert isinstance(room, GroupchatContact) + app.storage.events.store(room, event) + + room.notify('room-destroyed', event) return if properties.is_nickname_changed: @@ -586,10 +604,16 @@ def _on_muc_user_presence(self, presence = self._process_user_presence(properties) occupant.update_presence(presence, properties) - room.notify('user-nickname-changed', - occupant, - new_occupant, - properties) + event = events.MUCNicknameChanged( + is_self=properties.is_self_presence, + new_name=new_occupant.name, + old_name=occupant.name, + timestamp=time.time()) + + assert isinstance(room, GroupchatContact) + app.storage.events.store(room, event) + + room.notify('user-nickname-changed', event, occupant, new_occupant) return is_joined = self._is_user_joined(properties.jid) @@ -616,7 +640,16 @@ def _on_muc_user_presence(self, if properties.is_muc_self_presence and properties.is_kicked: self._set_muc_state(room_jid, MUCJoinedState.NOT_JOINED) room.set_not_joined() - room.notify('room-kicked', properties) + + event = events.MUCRoomKicked( + timestamp=time.time(), + status_codes=properties.muc_status_codes, + reason=properties.muc_user.reason, + actor=properties.muc_user.actor) + assert isinstance(room, GroupchatContact) + app.storage.events.store(room, event) + room.notify('room-kicked', event) + status_codes = properties.muc_status_codes or [] if StatusCode.REMOVED_SERVICE_SHUTDOWN in status_codes: self._start_rejoin_timeout(room_jid) @@ -889,12 +922,21 @@ def _on_config_change(self, if not properties.is_muc_config_change: return - room_jid = str(properties.muc_jid) self._log.info('Received config change: %s %s', - room_jid, properties.muc_status_codes) + properties.muc_jid, properties.muc_status_codes) - room = self._get_contact(room_jid) - room.notify('room-config-changed', properties) + assert properties.muc_status_codes is not None + event = events.MUCRoomConfigChanged( + timestamp=time.time(), + status_codes=properties.muc_status_codes) + + assert properties.muc_jid is not None + room = self._get_contact(properties.muc_jid) + + assert isinstance(room, GroupchatContact) + app.storage.events.store(room, event) + + room.notify('room-config-changed', event) raise nbxmpp.NodeProcessed ===================================== gajim/common/preview_helpers.py ===================================== @@ -45,6 +45,7 @@ from cryptography.hazmat.primitives.ciphers import algorithms from cryptography.hazmat.primitives.ciphers.modes import GCM +from gajim.common.helpers import sanitize_filename from gajim.common.i18n import _ log = logging.getLogger('gajim.c.preview_helpers') @@ -308,12 +309,7 @@ def get_image_paths(uri: str, web_stem = path.stem extension = path.suffix - if len(web_stem) > 90: - # Many Filesystems have a limit on filename length - # Most have 255, some encrypted ones only 143 - # We add around 50 chars for the hash, - # so the filename should not exceed 90 - web_stem = web_stem[:90] + web_stem = sanitize_filename(web_stem) name_hash = hashlib.sha1(str(uri).encode()).hexdigest() ===================================== gajim/common/setting_values.py ===================================== @@ -506,24 +506,33 @@ class _ACCOUNT_DEFAULT: 'name', ] -AllWorkspaceSettings = Literal[StringWorkspaceSettings, 'open_chats'] +AllWorkspaceSettings = Literal[StringWorkspaceSettings, 'chats'] -OpenChatSettingT = list[tuple[str, JID, str, bool]] -AllWorkspaceSettingsT = Union[str, OpenChatSettingT] + +class OpenChatSettingDetails(TypedDict): + account: str + jid: JID + type: str + pinned: bool + position: int + + +OpenChatsSettingT = list[OpenChatSettingDetails] +AllWorkspaceSettingsT = Union[str, OpenChatsSettingT] class WorkspaceSettings(TypedDict): name: str color: str avatar_sha: str - open_chats: OpenChatSettingT + chats: OpenChatsSettingT WORKSPACE_SETTINGS: WorkspaceSettings = { 'name': _('My Workspace'), 'color': '', 'avatar_sha': '', - 'open_chats': [], + 'chats': [], } ===================================== gajim/common/settings.py ===================================== @@ -56,7 +56,7 @@ from gajim.common.setting_values import StringGroupChatSettings from gajim.common.setting_values import AllWorkspaceSettings from gajim.common.setting_values import AllWorkspaceSettingsT -from gajim.common.setting_values import OpenChatSettingT +from gajim.common.setting_values import OpenChatsSettingT from gajim.common.setting_values import StringWorkspaceSettings from gajim.common.setting_values import ACCOUNT_SETTINGS from gajim.common.setting_values import PROXY_SETTINGS @@ -82,6 +82,8 @@ log = logging.getLogger('gajim.c.settings') +CURRENT_USER_VERSION = 2 + CREATE_SQL = ''' CREATE TABLE settings ( name TEXT UNIQUE, @@ -100,10 +102,11 @@ INSERT INTO settings(name, settings) VALUES ('plugins', '{}'); INSERT INTO settings(name, settings) VALUES ('workspaces', '%s'); - PRAGMA user_version=1; + PRAGMA user_version=%s; ''' % (json.dumps(STATUS_PRESET_EXAMPLES), json.dumps(PROXY_EXAMPLES), - json.dumps(INITAL_WORKSPACE)) + json.dumps(INITAL_WORKSPACE), + CURRENT_USER_VERSION) _SignalCallable = Callable[[Any, str, Optional[str], Optional[JID]], Any] @@ -217,6 +220,7 @@ def init(self) -> None: self._commit() self._migrate_database() self._load_app_overrides() + self._commit() @staticmethod def _setup_installation_defaults() -> None: @@ -320,6 +324,23 @@ def _migrate(self) -> None: self._settings['workspaces'] = INITAL_WORKSPACE self._set_user_version(1) + if version < 2: + # Migrate open chats to new key and format + for workspace in self._settings['workspaces'].values(): + open_chats = [] + for open_chat in workspace.get('open_chats', []): + account, jid, type_, pinned = open_chat + open_chats.append({'account': account, + 'jid': jid, + 'type': type_, + 'pinned': pinned, + 'position': -1}) + + workspace['chats'] = open_chats + workspace.pop('open_chats', None) + + self._set_user_version(2) + def _migrate_old_config(self) -> None: config_file = configpaths.get('CONFIG_FILE') if not config_file.exists(): @@ -1180,8 +1201,8 @@ def set_workspace_setting(self, @overload def set_workspace_setting(self, workspace_id: str, - setting: Literal['open_chats'], - value: list[tuple[str, JID, str, bool]] + setting: Literal['chats'], + value: OpenChatsSettingT ) -> None: ... @@ -1207,8 +1228,8 @@ def set_workspace_setting(self, @overload def get_workspace_setting(self, workspace_id: str, - setting: Literal['open_chats'] - ) -> OpenChatSettingT: + setting: Literal['chats'] + ) -> OpenChatsSettingT: ... @overload ===================================== gajim/common/storage/base.py ===================================== @@ -98,6 +98,13 @@ def _adapt_disco_info(disco_info: DiscoInfo) -> str: sqlite3.register_adapter(DiscoInfo, _adapt_disco_info) +def _convert_json(json_string: bytes) -> dict[str, Any]: + return json.loads(json_string) + + +sqlite3.register_converter('JSON', _convert_json) + + class Encoder(json.JSONEncoder): def default(self, o: Any) -> Any: if isinstance(o, set): ===================================== gajim/common/storage/events.py ===================================== @@ -0,0 +1,131 @@ +# This file is part of Gajim. +# +# Gajim 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; version 3 only. +# +# Gajim 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 Gajim. If not, see <
http://www.gnu.org/licenses/
>. + +from __future__ import annotations +import dataclasses + +from typing import Any +from typing import NamedTuple + +import json +import sqlite3 +import logging +from collections import namedtuple + +from nbxmpp.protocol import JID + +from gajim.common import events +from gajim.common.storage.base import SqliteStorage +from gajim.common.types import ChatContactT + + +EVENTS_SQL_STATEMENT = ''' + CREATE TABLE events ( + account TEXT, + jid TEXT, + event TEXT, + timestamp REAL, + data TEXT); + + CREATE INDEX idx_account_jid ON events(account, jid); + + PRAGMA user_version=1; + ''' + +EVENT_CLASSES: dict[str, Any] = { + 'muc-nickname-changed': events.MUCNicknameChanged, + 'muc-room-config-changed': events.MUCRoomConfigChanged, + 'muc-room-config-finished': events.MUCRoomConfigFinished, + 'muc-room-presence-error': events.MUCRoomPresenceError, + 'muc-room-kicked': events.MUCRoomKicked, + 'muc-room-destroyed': events.MUCRoomDestroyed, + 'muc-user-joined': events.MUCUserJoined, + 'muc-user-left': events.MUCUserLeft, + 'muc-user-role-changed': events.MUCUserRoleChanged, + 'muc-user-affiliation-changed': events.MUCUserAffiliationChanged, + 'muc-user-status-show-changed': events.MUCUserStatusShowChanged, +} + +log = logging.getLogger('gajim.c.storage.events') + + +class EventRow(NamedTuple): + account: str + jid: JID + event: str + timestamp: float + data: dict[str, Any] + + +class EventStorage(SqliteStorage): + def __init__(self): + SqliteStorage.__init__(self, + log, + None, + EVENTS_SQL_STATEMENT) + + def init(self, **kwargs: Any) -> None: + SqliteStorage.init(self, + detect_types=sqlite3.PARSE_COLNAMES) + self._con.row_factory = self._namedtuple_factory + + @staticmethod + def _namedtuple_factory(cursor: sqlite3.Cursor, + row: tuple[Any, ...]) -> NamedTuple: + + assert cursor.description is not None + fields = [col[0] for col in cursor.description] + Row = namedtuple('Row', fields) # type: ignore + return Row(*row) + + def _migrate(self) -> None: + pass + + def store(self, + contact: ChatContactT, + event: Any + ) -> None: + + event_dict = dataclasses.asdict(event) + name = event_dict.pop('name') + timestamp = event_dict.pop('timestamp') + + insert_sql = ''' + INSERT INTO events(account, jid, event, timestamp, data) + VALUES(?, ?, ?, ?, ?)''' + + self._con.execute(insert_sql, (contact.account, + contact.jid, + name, + timestamp, + json.dumps(event_dict))) + + def load(self, + contact: ChatContactT, + before: bool, + timestamp: float + ) -> list[EventRow]: + + time_operator = '<' if before else '>' + + insert_sql = ''' + SELECT account, jid, event, timestamp, data as "data [JSON]" + FROM events WHERE account=? AND jid=? AND timestamp %s ? + ''' % time_operator + + for row in self._con.execute(insert_sql, (contact.account, + contact.jid, + timestamp)).fetchall(): + event_class = EVENT_CLASSES[row.event] + yield event_class(**row.data, timestamp=row.timestamp) ===================================== gajim/data/gui/message_actions_box.ui ===================================== @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<!-- Generated with glade 3.38.2 --> +<!-- Generated with glade 3.40.0 --> <interface> <requires lib="gtk+" version="3.24"/> <object class="GtkBox" id="box"> @@ -91,7 +91,6 @@ <property name="visible">True</property> <property name="can-focus">True</property> <property name="receives-default">True</property> - <property name="tooltip-text" translatable="yes">Choose encryption</property> <property name="relief">none</property> <child> <object class="GtkImage" id="encryption_image"> ===================================== gajim/gtk/chat_banner.py ===================================== @@ -21,8 +21,6 @@ import cairo -from nbxmpp.structs import PresenceProperties - from gajim.common import app from gajim.common import ged from gajim.common import types @@ -184,13 +182,7 @@ def _on_muc_state_changed(self, if contact.is_joined: self._update_content() - def _on_user_role_changed(self, - _contact: GroupchatContact, - _signal_name: str, - user_contact: GroupchatParticipant, - properties: PresenceProperties - ) -> None: - + def _on_user_role_changed(self, *args: Any) -> None: self._update_content() def _on_user_state_changed(self, *args: Any) -> None: ===================================== gajim/gtk/chat_list.py ===================================== @@ -26,6 +26,7 @@ from gi.repository import Gio from gi.repository import Gdk from gi.repository import GLib +from gi.repository import GObject from gi.repository import Gtk import cairo @@ -47,6 +48,7 @@ from gajim.common.helpers import AdditionalDataDict from gajim.common.preview_helpers import filename_from_uri from gajim.common.preview_helpers import guess_simple_file_type +from gajim.common.setting_values import OpenChatsSettingT from gajim.common.types import ChatContactT from gajim.common.types import OneOnOneContactT from gajim.common.modules.contacts import BareContact @@ -65,6 +67,13 @@ class ChatList(Gtk.ListBox, EventHelper): + + __gsignals__ = { + 'chat-order-changed': (GObject.SignalFlags.RUN_LAST, + None, + ()), + } + def __init__(self, workspace_id: str) -> None: Gtk.ListBox.__init__(self) EventHelper.__init__(self) @@ -94,12 +103,16 @@ def __init__(self, workspace_id: str) -> None: entries, Gdk.DragAction.MOVE) + self._drag_row: Optional[ChatRow] = None + self._chat_order: list[ChatRow] = [] + self.register_events([ ('account-enabled', ged.GUI2, self._on_account_changed), ('account-disabled', ged.GUI2, self._on_account_changed), ('bookmarks-received', ged.GUI1, self._on_bookmarks_received), ]) + self.connect('drag-data-received', self._on_drag_data_received) self.connect('destroy', self._on_destroy) self._timer_id = GLib.timeout_add_seconds(60, self._update_timer) @@ -146,6 +159,94 @@ def emit_unread_changed(self) -> None: self._workspace_id, count) + def _get_row_before(self, row: ChatRow) -> Optional[ChatRow]: + row_before = self.get_row_at_index(row.get_index() - 1) + if row_before is None: + return + return cast(ChatRow, row_before) + + def _get_row_after(self, row: ChatRow) -> Optional[ChatRow]: + row_after = self.get_row_at_index(row.get_index() + 1) + if row_after is None: + return + return cast(ChatRow, row_after) + + def _get_last_row(self) -> ChatRow: + index = len(self.get_children()) - 1 + last_row = self.get_row_at_index(index) + assert last_row is not None + return cast(ChatRow, last_row) + + def set_drag_row(self, row: ChatRow) -> None: + self._drag_row = row + + def _on_drag_data_received(self, + _widget: Gtk.Widget, + _drag_context: Gdk.DragContext, + _x_coord: int, + y_coord: int, + selection_data: Gtk.SelectionData, + _info: int, + _time: int + ) -> None: + + item_type = selection_data.get_data_type().name() + if item_type != 'CHAT_LIST_ITEM': + log.debug('Unknown item type dropped') + return + + assert self._drag_row is not None + + if not self._drag_row.is_pinned: + log.debug('Dropped row is not pinned') + return + + row = cast(ChatRow, self.get_row_at_y(y_coord)) + if row is not None: + alloc = row.get_allocation() + hover_row_y = alloc.y + hover_row_height = alloc.height + + if y_coord < hover_row_y + hover_row_height / 2: + row_before = self._get_row_before(row) + row_after = row + else: + row_before = row + row_after = self._get_row_after(row) + else: + row_before = self._get_last_row() + row_after = None + + if self._drag_row in (row_before, row_after): + log.debug('Dropped row on self') + return + + if row_before is not None and not row_before.is_pinned: + log.debug('Dropped under not pinned row') + return + + self._change_pinned_order(row_before) + + def _change_pinned_order(self, row_before: Optional[ChatRow]) -> None: + assert self._drag_row is not None + + self._chat_order.remove(self._drag_row) + + if row_before is None: + self._chat_order.insert(0, self._drag_row) + else: + offset = 0 + if row_before.position < self._drag_row.position: + offset = 1 + self._chat_order.insert( + row_before.position + offset, self._drag_row) + + for row in self._chat_order: + row.position = self._chat_order.index(row) + + self.emit('chat-order-changed') + self.invalidate_sort() + def _on_destroy(self, _widget: Gtk.Widget) -> None: GLib.source_remove(self._timer_id) @@ -198,9 +299,11 @@ def _sort_func(self, row1: ChatRow, row2: ChatRow) -> int: log.debug('Mouseover active, don’t sort rows') return 0 - # Don’t sort pinned rows themselves + # Sort pinned rows according to stored order if row1.is_pinned and row2.is_pinned: - return 0 + if row1.position > row2.position: + return 1 + return -1 # Sort pinned rows to top if row1.is_pinned > row2.is_pinned: @@ -250,14 +353,30 @@ def get_chat_type(self, account: str, jid: JID) -> Optional[str]: return row.type return None - def add_chat(self, account: str, jid: JID, type_: str, - pinned: bool = False) -> None: - if self._chats.get((account, jid)) is not None: + def add_chat(self, + account: str, + jid: JID, + type_: str, + pinned: bool, + position: int + ) -> None: + + key = (account, jid) + if self._chats.get(key) is not None: # Chat is already in the List return - row = ChatRow(self._workspace_id, account, jid, type_, pinned) - self._chats[(account, jid)] = row + row = ChatRow(self._workspace_id, + account, + jid, + type_, + pinned, + position) + + self._chats[key] = row + if pinned: + self._chat_order.insert(position, row) + self.add(row) def select_chat(self, account: str, jid: JID) -> None: @@ -332,12 +451,26 @@ def select_chat_number(self, number: int) -> None: def toggle_chat_pinned(self, account: str, jid: JID) -> None: row = self._chats[(account, jid)] + + if row.is_pinned: + self._chat_order.remove(row) + row.position = -1 + else: + self._chat_order.append(row) + row.position = self._chat_order.index(row) + row.toggle_pinned() self.invalidate_sort() - def remove_chat(self, account: str, jid: JID, - emit_unread: bool = True) -> None: + def remove_chat(self, + account: str, + jid: JID, + emit_unread: bool = True + ) -> None: + row = self._chats.pop((account, jid)) + if row.is_pinned: + self._chat_order.remove(row) self.remove(row) row.destroy() if emit_unread: @@ -359,10 +492,15 @@ def get_selected_chat(self) -> Optional[ChatRow]: def contains_chat(self, account: str, jid: JID) -> bool: return self._chats.get((account, jid)) is not None - def get_open_chats(self) -> list[tuple[str, JID, str, bool]]: - open_chats: list[tuple[str, JID, str, bool]] = [] - for key, value in self._chats.items(): - open_chats.append(key + (value.type, value.is_pinned)) + def get_open_chats(self) -> OpenChatsSettingT: + open_chats: OpenChatsSettingT = [] + for key, row in self._chats.items(): + account, jid = key + open_chats.append({'account': account, + 'jid': jid, + 'type': row.type, + 'pinned': row.is_pinned, + 'position': row.position}) return open_chats def update_time(self) -> None: @@ -536,14 +674,22 @@ def _on_bookmarks_received(self, _event: events.BookmarksReceived) -> None: class ChatRow(Gtk.ListBoxRow): - def __init__(self, workspace_id: str, account: str, jid: JID, type_: str, - pinned: bool) -> None: + def __init__(self, + workspace_id: str, + account: str, + jid: JID, + type_: str, + pinned: bool, + position: int + ) -> None: + Gtk.ListBoxRow.__init__(self) self.account = account self.jid = jid self.workspace_id = workspace_id self.type = type_ + self.position = position self.active_label = ActiveHeader() self.conversations_label = ConversationsHeader() @@ -735,6 +881,10 @@ def _on_drag_begin(self, widget: Gtk.Widget, drag_context: Gdk.DragContext ) -> None: + + chat_list = cast(ChatList, self.get_parent()) + chat_list.set_drag_row(self) + # Use rendered ChatListRow as drag icon alloc = self.get_allocation() surface = cairo.ImageSurface( ===================================== gajim/gtk/chat_list_stack.py ===================================== @@ -14,7 +14,6 @@ from __future__ import annotations -from typing import Dict from typing import Optional from typing import cast @@ -66,7 +65,7 @@ def __init__(self, self.set_vexpand(True) self.set_vhomogeneous(False) - self._chat_lists: Dict[str, ChatList] = {} + self._chat_lists: dict[str, ChatList] = {} self._last_visible_child_name: str = 'default' @@ -153,6 +152,7 @@ def _on_search_changed(self, search_entry: Gtk.SearchEntry) -> None: def add_chat_list(self, workspace_id: str) -> ChatList: chat_list = ChatList(workspace_id) chat_list.connect('row-selected', self._on_row_selected) + chat_list.connect('chat-order-changed', self._on_chat_order_changed) self._chat_lists[workspace_id] = chat_list self.add_named(chat_list, workspace_id) @@ -161,8 +161,10 @@ def add_chat_list(self, workspace_id: str) -> ChatList: def remove_chat_list(self, workspace_id: str) -> None: chat_list = self._chat_lists[workspace_id] self.remove(chat_list) - for account, jid, _type, _pinned in chat_list.get_open_chats(): - self.remove_chat(workspace_id, account, jid) + for open_chat in chat_list.get_open_chats(): + self.remove_chat(workspace_id, + open_chat['account'], + open_chat['jid']) self._chat_lists.pop(workspace_id) chat_list.destroy() @@ -177,6 +179,12 @@ def _on_row_selected(self, self.emit('chat-selected', row.workspace_id, row.account, row.jid) + def _on_chat_order_changed(self, + chat_list: ChatList + ) -> None: + + self.store_open_chats(chat_list.workspace_id) + def show_chat_list(self, workspace_id: str) -> None: cur_workspace_id = self.get_visible_child_name() if cur_workspace_id == workspace_id: @@ -187,12 +195,19 @@ def show_chat_list(self, workspace_id: str) -> None: self.set_visible_child_name(workspace_id) - def add_chat(self, workspace_id: str, account: str, jid: JID, type_: str, - pinned: bool = False) -> None: + def add_chat(self, + workspace_id: str, + account: str, + jid: JID, + type_: str, + pinned: bool, + position: int + ) -> None: + chat_list = self._chat_lists.get(workspace_id) if chat_list is None: chat_list = self.add_chat_list(workspace_id) - chat_list.add_chat(account, jid, type_, pinned) + chat_list.add_chat(account, jid, type_, pinned, position) def select_chat(self, account: str, jid: JID) -> None: chat_list = self.find_chat(account, jid) @@ -206,7 +221,7 @@ def store_open_chats(self, workspace_id: str) -> None: chat_list = self._chat_lists[workspace_id] open_chats = chat_list.get_open_chats() app.settings.set_workspace_setting( - workspace_id, 'open_chats', open_chats) + workspace_id, 'chats', open_chats) @structs.actionmethod def _toggle_chat_pinned(self, @@ -235,7 +250,8 @@ def _move_chat_to_workspace(self, current_chatlist.remove_chat(params.account, params.jid) new_chatlist = self.get_chatlist(workspace_id) - new_chatlist.add_chat(params.account, params.jid, type_) + new_chatlist.add_chat(params.account, params.jid, type_, False, -1) + self.store_open_chats(current_chatlist.workspace_id) self.store_open_chats(workspace_id) ===================================== gajim/gtk/chat_page.py ===================================== @@ -221,6 +221,7 @@ def add_chat_for_workspace(self, jid: JID, type_: str, pinned: bool = False, + position: int = -1, select: bool = False) -> None: client = app.get_client(account) @@ -240,7 +241,7 @@ def add_chat_for_workspace(self, return self._chat_list_stack.add_chat(workspace_id, account, jid, type_, - pinned) + pinned, position) if self._startup_finished: if select: @@ -249,18 +250,20 @@ def add_chat_for_workspace(self, def load_workspace_chats(self, workspace_id: str) -> None: open_chats = app.settings.get_workspace_setting(workspace_id, - 'open_chats') + 'chats') active_accounts = app.settings.get_active_accounts() - for account, jid, type_, pinned in open_chats: + for open_chat in open_chats: + account = open_chat['account'] if account not in active_accounts: continue self.add_chat_for_workspace(workspace_id, account, - jid, - type_, - pinned=pinned) + open_chat['jid'], + open_chat['type'], + pinned=open_chat['pinned'], + position=open_chat['position']) def is_chat_active(self, account: str, jid: JID) -> bool: return self._chat_list_stack.is_chat_active(account, jid) ===================================== gajim/gtk/chat_stack.py ===================================== @@ -28,7 +28,6 @@ from nbxmpp.errors import StanzaError from nbxmpp.protocol import JID from nbxmpp.structs import MessageProperties -from nbxmpp.structs import PresenceProperties from gajim.common import app from gajim.common import events @@ -297,23 +296,25 @@ def _on_user_joined(self, contact: GroupchatContact, _signal_name: str, _user_contact: GroupchatParticipant, - _properties: PresenceProperties + _event: events.MUCUserJoined ) -> None: + self._update_group_chat_actions(contact) def _on_user_role_changed(self, contact: GroupchatContact, _signal_name: str, _user_contact: GroupchatParticipant, - _properties: PresenceProperties + _event: events.MUCUserRoleChanged ) -> None: + self._update_group_chat_actions(contact) def _on_user_affiliation_changed(self, contact: GroupchatContact, _signal_name: str, _user_contact: GroupchatParticipant, - _properties: PresenceProperties + _event: events.MUCUserAffiliationChanged ) -> None: self._update_group_chat_actions(contact) ===================================== gajim/gtk/control.py ===================================== @@ -19,9 +19,6 @@ from typing import Union from typing import cast -from collections import defaultdict -from collections import deque -from functools import partial import os import logging import time @@ -105,12 +102,6 @@ def __init__(self) -> None: self._muc_subjects: dict[ types.ChatContactT, tuple[float, MucSubject]] = {} - # Store 100 info messages per contact on a FIFO basis - self._info_messages: dict[ - types.ChatContactT, - deque[tuple[float, str]]] = defaultdict( - partial(deque, maxlen=100)) # pyright: ignore - self.widget = cast(Gtk.Box, self._ui.get_object('control_box')) self.widget.show_all() @@ -212,9 +203,6 @@ def switch_contact(self, contact: Union[BareContact, for transfer in transfers: self.add_file_transfer(transfer) - for timestamp, message in self._info_messages[contact]: - self.add_info_message(message, timestamp) - if isinstance(contact, GroupchatContact): if (app.settings.get('show_subject_on_join') or not contact.is_joining): @@ -515,10 +503,6 @@ def add_info_message(self, timestamp: Optional[float] = None ) -> None: - if timestamp is None: - assert self._contact is not None - self._info_messages[self._contact].append((time.time(), text)) - self.conversation_view.add_info_message(text, timestamp) def add_file_transfer(self, transfer: HTTPFileTransfer) -> None: @@ -639,6 +623,40 @@ def _fetch_n_lines_history(self, # if self.conversation_view.reduce_message_count(before): # self._scrolled_view.set_history_complete(before, False) + for event in app.storage.events.load(self._contact, before, timestamp): + if isinstance(event, events.MUCUserJoined): + self._process_muc_user_joined(event) + + if isinstance(event, events.MUCUserLeft): + self._process_muc_user_left(event) + + if isinstance(event, events.MUCNicknameChanged): + self._process_muc_nickname_changed(event) + + if isinstance(event, events.MUCRoomKicked): + self._process_muc_room_kicked(event) + + if isinstance(event, events.MUCUserAffiliationChanged): + self._process_muc_user_affiliation_changed(event) + + if isinstance(event, events.MUCUserRoleChanged): + self._process_muc_user_role_changed(event) + + if isinstance(event, events.MUCUserStatusShowChanged): + self._process_muc_user_status_show_changed(event) + + if isinstance(event, events.MUCRoomConfigChanged): + self._process_muc_room_config_changed(event) + + if isinstance(event, events.MUCRoomConfigFinished): + self._process_muc_room_config_finished(event) + + if isinstance(event, events.MUCRoomPresenceError): + self._process_muc_room_presence_error(event) + + if isinstance(event, events.MUCRoomDestroyed): + self._process_muc_room_destroyed(event) + self._scrolled_view.block_signals(False) def add_messages(self, messages: list[ConversationRow]): @@ -725,150 +743,212 @@ def add_message(self, def _on_user_nickname_changed(self, contact: types.GroupchatContact, _signal_name: str, - old_contact: types.GroupchatParticipant, - new_contact: types.GroupchatParticipant, - properties: PresenceProperties + _old_contact: types.GroupchatParticipant, + _new_contact: types.GroupchatParticipant, + event: events.MUCNicknameChanged ) -> None: - if properties.is_muc_self_presence: - message = _('You are now known as %s') % new_contact.name + self._process_muc_nickname_changed(event) + + def _process_muc_nickname_changed(self, + event: events.MUCNicknameChanged + ) -> None: + + if event.is_self: + message = _('You are now known as %s') % event.new_name else: message = _('{nick} is now known ' - 'as {new_nick}').format(nick=old_contact.name, - new_nick=new_contact.name) + 'as {new_nick}').format(nick=event.old_name, + new_nick=event.new_name) + self.add_info_message(message, event.timestamp) - self.add_info_message(message) + def _on_room_kicked(self, + _contact: GroupchatContact, + _signal_name: str, + event: events.MUCRoomKicked + ) -> None: - def _on_muc_user_status_show_changed(self, - contact: GroupchatContact, - _signal_name: str, - user_contact: GroupchatParticipant, - properties: PresenceProperties - ) -> None: + self._process_muc_room_kicked(event) - if not contact.settings.get('print_status'): + def _process_muc_room_kicked(self, event: events.MUCRoomKicked) -> None: + status_codes = event.status_codes or [] + + reason = event.reason + reason = '' if reason is None else f': {reason}' + + actor = event.actor + # Group Chat: You have been kicked by Alice + actor = '' if actor is None else _(' by {actor}').format( + actor=actor) + + # Group Chat: We have been removed from the room by Alice: reason + message = _('You have been removed from the ' + 'group chat{actor}{reason}') + + if StatusCode.REMOVED_ERROR in status_codes: + # Handle 333 before 307, some MUCs add both + # Group Chat: Server kicked us because of an server error + message = _('You have left due ' + 'to an error{reason}').format(reason=reason) + + elif StatusCode.REMOVED_KICKED in status_codes: + # Group Chat: We have been kicked by Alice: reason + message = _('You have been ' + 'kicked{actor}{reason}').format(actor=actor, + reason=reason) + + elif StatusCode.REMOVED_BANNED in status_codes: + # Group Chat: We have been banned by Alice: reason + message = _('You have been ' + 'banned{actor}{reason}').format(actor=actor, + reason=reason) + + elif StatusCode.REMOVED_AFFILIATION_CHANGE in status_codes: + # Group Chat: We were removed because of an affiliation change + reason = _(': Affiliation changed') + message = message.format(actor=actor, reason=reason) + + elif StatusCode.REMOVED_NONMEMBER_IN_MEMBERS_ONLY in status_codes: + # Group Chat: Room configuration changed + reason = _(': Group chat configuration changed to members-only') + message = message.format(actor=actor, reason=reason) + + elif StatusCode.REMOVED_SERVICE_SHUTDOWN in status_codes: + # Group Chat: Kicked because of server shutdown + reason = ': System shutdown' + message = message.format(actor=actor, reason=reason) + + else: + # No formatted message available return - self.conversation_view.add_user_status(user_contact.name, - user_contact.show.value, - user_contact.status) + self.add_info_message(message, event.timestamp) - def _on_user_status_show_changed(self, - _user_contact: GroupchatParticipant, + def _on_user_affiliation_changed(self, + _contact: GroupchatContact, _signal_name: str, - properties: PresenceProperties + user_contact: GroupchatParticipant, + event: events.MUCUserAffiliationChanged ) -> None: - nick = properties.muc_nickname - status = properties.status - status = '' if not status else f' - {status}' - assert properties.show is not None - show = helpers.get_uf_show(properties.show.value) + self._process_muc_user_affiliation_changed(event) - assert isinstance(self.contact, GroupchatParticipant) - if not self.contact.room.settings.get('print_status'): - return + def _process_muc_user_affiliation_changed(self, + event: events.MUCUserAffiliationChanged + ) -> None: - if properties.is_muc_self_presence: - message = _('You are now {show}{status}').format(show=show, - status=status) + affiliation = helpers.get_uf_affiliation(event.affiliation) + nick = event.name + + reason = event.reason + reason = '' if reason is None else f': {reason}' + actor = event.actor + # Group Chat: You have been kicked by Alice + actor = '' if actor is None else _(' by {actor}').format( + actor=actor) + + if event.is_self: + message = _('** Your Affiliation has been set to ' + '{affiliation}{actor}{reason}').format( + affiliation=affiliation, + actor=actor, + reason=reason) else: - message = _('{nick} is now {show}{status}').format(nick=nick, - show=show, - status=status) - self.add_info_message(message) - - def invite(self, invited_jid: JID) -> None: - # TODO: Remove, used by command system - self.client.get_module('MUC').invite( - self.contact.jid, invited_jid) - invited_contact = self.client.get_module('Contacts').get_contact( - invited_jid) - self.add_info_message( - _('%s has been invited to this group chat') % invited_contact.name) + message = _('** Affiliation of {nick} has been set to ' + '{affiliation}{actor}{reason}').format( + nick=nick, + affiliation=affiliation, + actor=actor, + reason=reason) - def _on_room_voice_request(self, - _contact: GroupchatContact, - _signal_name: str, - properties: MessageProperties - ) -> None: - voice_request = properties.voice_request - assert voice_request is not None + self.add_info_message(message, event.timestamp) - def on_approve() -> None: - self.client.get_module('MUC').approve_voice_request( - self.contact.jid, voice_request) + def _on_user_role_changed(self, + _contact: GroupchatContact, + _signal_name: str, + user_contact: GroupchatParticipant, + event: events.MUCUserRoleChanged + ) -> None: - ConfirmationDialog( - _('Voice Request'), - _('Voice Request'), - _('<b>%(nick)s</b> from <b>%(room_name)s</b> requests voice') % { - 'nick': voice_request.nick, 'room_name': self.contact.name}, - [DialogButton.make('Cancel'), - DialogButton.make('Accept', - text=_('_Approve'), - callback=on_approve)], - modal=False).show() + self._process_muc_user_role_changed(event) - def add_muc_message(self, - text: str, - tim: float, - contact: str = '', - displaymarking: Optional[Displaymarking] = None, - message_id: Optional[str] = None, - stanza_id: Optional[str] = None, - additional_data: Optional[AdditionalDataDict] = None, - ) -> None: + def _process_muc_user_role_changed(self, + event: events.MUCUserRoleChanged + ) -> None: - assert isinstance(self._contact, GroupchatContact) + role = helpers.get_uf_role(event.role) + nick = event.nick - if contact == self._contact.nickname: - kind = 'outgoing' + reason = event.reason + reason = '' if reason is None else f': {reason}' + + actor = event.actor + # Group Chat: You have been kicked by Alice + actor = '' if actor is None else _(' by {actor}').format(actor=actor) + + if event.is_self: + message = _('** Your Role has been set to ' + '{role}{actor}{reason}').format(role=role, + actor=actor, + reason=reason) else: - kind = 'incoming' - # muc-specific chatstate + message = _('** Role of {nick} has been set to ' + '{role}{actor}{reason}').format(nick=nick, + role=role, + actor=actor, + reason=reason) + self.add_info_message(message, event.timestamp) - self._add_message(text, - kind, - contact, - tim, - displaymarking=displaymarking, - message_id=message_id, - stanza_id=stanza_id, - additional_data=additional_data) + def _on_user_status_show_changed(self, + _user_contact: GroupchatParticipant, + _signal_name: str, + event: events.MUCUserStatusShowChanged + ) -> None: - def _on_room_subject(self, - contact: GroupchatContact, - _signal_name: str, - subject: Optional[MucSubject] - ) -> None: + self._process_muc_user_status_show_changed(event) - if subject is None: - return + def _process_muc_user_status_show_changed(self, + event: events.MUCUserStatusShowChanged + ) -> None: - _timestamp, old_subject = self._muc_subjects.get(contact, (None, None)) - if old_subject is not None and old_subject.text == subject.text: - # Probably a rejoin, we already showed that subject + nick = event.nick + status = event.status + status = '' if not status else f' - {status}' + show = helpers.get_uf_show(event.show_value) + + assert isinstance(self.contact, GroupchatParticipant) + if not self.contact.room.settings.get('print_status'): return - self._muc_subjects[contact] = (time.time(), subject) + if event.is_self: + message = _('You are now {show}{status}').format(show=show, + status=status) - if (app.settings.get('show_subject_on_join') or - not contact.is_joining): - self.conversation_view.add_muc_subject(subject) + else: + message = _('{nick} is now {show}{status}').format( + nick=nick, + show=show, + status=status) + + self.add_info_message(message, event.timestamp) def _on_room_config_changed(self, _contact: GroupchatContact, _signal_name: str, - properties: MessageProperties + event: events.MUCRoomConfigChanged ) -> None: - #
http://www.xmpp.org/extensions/xep-0045.html#roomconfig-notify
- status_codes = properties.muc_status_codes - assert status_codes is not None + self._process_muc_room_config_changed(event) + def _process_muc_room_config_changed(self, + event: events.MUCRoomConfigChanged + ) -> None: + + #
http://www.xmpp.org/extensions/xep-0045.html#roomconfig-notify
+ status_codes = event.status_codes changes: list[str] = [] + if StatusCode.SHOWING_UNAVAILABLE in status_codes: changes.append(_('Group chat now shows unavailable members')) @@ -882,7 +962,8 @@ def _on_room_config_changed(self, self.client.get_module('Discovery').disco_muc(self.contact.jid) if StatusCode.CONFIG_ROOM_LOGGING in status_codes: - # Can be a presence (see chg_contact_status in groupchat_control.py) + # Can be a presence + # (see chg_contact_status in groupchat_control.py) changes.append(_('Conversations are stored on the server')) if StatusCode.CONFIG_NO_ROOM_LOGGING in status_codes: @@ -897,194 +978,127 @@ def _on_room_config_changed(self, if StatusCode.CONFIG_FULL_ANONYMOUS in status_codes: changes.append(_('Group chat is now fully anonymous')) - for change in changes: - self.add_info_message(change) - - def rejoin(self) -> None: - self.client.get_module('MUC').join(self.contact.jid) - - def _on_user_joined(self, - contact: GroupchatContact, - _signal_name: str, - user_contact: GroupchatParticipant, - properties: PresenceProperties - ) -> None: - - nick = user_contact.name - if not properties.is_muc_self_presence: - if contact.is_joined: - self.conversation_view.add_muc_user_joined(nick) - return - - status_codes = properties.muc_status_codes or [] - - if not contact.is_joined: - # We just joined the room - self.add_info_message(_('You (%s) joined the group chat') % nick) - - if StatusCode.NON_ANONYMOUS in status_codes: - self.add_info_message( - _('Any participant is allowed to see your full XMPP Address')) - - if StatusCode.CONFIG_ROOM_LOGGING in status_codes: - self.add_info_message(_('Conversations are stored on the server')) - - if StatusCode.NICKNAME_MODIFIED in status_codes: - self.add_info_message( - _('The server has assigned or modified your nickname in this ' - 'group chat')) + for message in changes: + self.add_info_message(message, event.timestamp) def _on_room_config_finished(self, _contact: GroupchatContact, - _signal_name: str + _signal_name: str, + event: events.MUCRoomConfigFinished ) -> None: + self._process_muc_room_config_finished(event) + + def _process_muc_room_config_finished(self, + event: events.MUCRoomConfigFinished + ) -> None: + self.add_info_message(_('A new group chat has been created')) - def _on_user_affiliation_changed(self, - _contact: GroupchatContact, - _signal_name: str, - user_contact: GroupchatParticipant, - properties: PresenceProperties - ) -> None: - affiliation = helpers.get_uf_affiliation(user_contact.affiliation) - nick = user_contact.name + def _on_room_presence_error(self, + _contact: GroupchatContact, + _signal_name: str, + event: events.MUCRoomPresenceError + ) -> None: - assert properties.muc_user is not None - reason = properties.muc_user.reason - reason = '' if reason is None else f': {reason}' + self._process_muc_room_presence_error(event) - actor = properties.muc_user.actor - # Group Chat: You have been kicked by Alice - actor = '' if actor is None else _(' by {actor}').format(actor=actor) + def _process_muc_room_presence_error(self, + event: events.MUCRoomPresenceError + ) -> None: - if properties.is_muc_self_presence: - message = _('** Your Affiliation has been set to ' - '{affiliation}{actor}{reason}').format( - affiliation=affiliation, - actor=actor, - reason=reason) - else: - message = _('** Affiliation of {nick} has been set to ' - '{affiliation}{actor}{reason}').format( - nick=nick, - affiliation=affiliation, - actor=actor, - reason=reason) + error_message = to_user_string(event.error) + self.add_info_message(_('Error: %s') % error_message) - self.add_info_message(message) + def _on_room_destroyed(self, + _contact: GroupchatContact, + _signal_name: str, + event: events.MUCRoomDestroyed + ) -> None: - def _on_user_role_changed(self, - _contact: GroupchatContact, - _signal_name: str, - user_contact: GroupchatParticipant, - properties: PresenceProperties - ) -> None: - role = helpers.get_uf_role(user_contact.role) - nick = user_contact.name + self._process_muc_room_destroyed(event) - assert properties.muc_user is not None - reason = properties.muc_user.reason + def _process_muc_room_destroyed(self, + event: events.MUCRoomDestroyed + ) -> None: + + reason = event.reason reason = '' if reason is None else f': {reason}' - actor = properties.muc_user.actor - # Group Chat: You have been kicked by Alice - actor = '' if actor is None else _(' by {actor}').format(actor=actor) + message = _('Group chat has been destroyed') - if properties.is_muc_self_presence: - message = _('** Your Role has been set to ' - '{role}{actor}{reason}').format(role=role, - actor=actor, - reason=reason) - else: - message = _('** Role of {nick} has been set to ' - '{role}{actor}{reason}').format(nick=nick, - role=role, - actor=actor, - reason=reason) + if event.alternate is not None: + message += '\n' + _('You can join this group chat instead: ' + 'xmpp:%s?join') % str(event.alternate) - self.add_info_message(message) + self.add_info_message(message, event.timestamp) - def _on_room_kicked(self, + def _on_user_joined(self, _contact: GroupchatContact, _signal_name: str, - properties: MessageProperties + _user_contact: GroupchatParticipant, + event: events.MUCUserJoined ) -> None: - status_codes = properties.muc_status_codes or [] - assert properties.muc_user is not None - reason = properties.muc_user.reason - reason = '' if reason is None else f': {reason}' + self._process_muc_user_joined(event) - actor = properties.muc_user.actor - # Group Chat: You have been kicked by Alice - actor = '' if actor is None else _(' by {actor}').format(actor=actor) + def _process_muc_user_joined(self, event: events.MUCUserJoined) -> None: + assert isinstance(self.contact, GroupchatContact) - # Group Chat: We have been removed from the room by Alice: reason - message = _('You have been removed from the group chat{actor}{reason}') + if not event.is_self: + if self.contact.is_joined: + self.conversation_view.add_muc_user_joined(event.nick) + return - if StatusCode.REMOVED_ERROR in status_codes: - # Handle 333 before 307, some MUCs add both - # Group Chat: Server kicked us because of an server error - message = _('You have left due ' - 'to an error{reason}').format(reason=reason) - self.add_info_message(message) + status_codes = event.status_codes or [] - elif StatusCode.REMOVED_KICKED in status_codes: - # Group Chat: We have been kicked by Alice: reason - message = _('You have been ' - 'kicked{actor}{reason}').format(actor=actor, - reason=reason) - self.add_info_message(message) + message = None + if not self.contact.is_joined: + # We just joined the room + message = _('You (%s) joined the group chat') % event.nick - elif StatusCode.REMOVED_BANNED in status_codes: - # Group Chat: We have been banned by Alice: reason - message = _('You have been ' - 'banned{actor}{reason}').format(actor=actor, - reason=reason) - self.add_info_message(message) + if StatusCode.NON_ANONYMOUS in status_codes: + message = _('Any participant is allowed to see your full ' + 'XMPP Address') - elif StatusCode.REMOVED_AFFILIATION_CHANGE in status_codes: - # Group Chat: We were removed because of an affiliation change - reason = _(': Affiliation changed') - message = message.format(actor=actor, reason=reason) - self.add_info_message(message) + if StatusCode.CONFIG_ROOM_LOGGING in status_codes: + message = _('Conversations are stored on the server') - elif StatusCode.REMOVED_NONMEMBER_IN_MEMBERS_ONLY in status_codes: - # Group Chat: Room configuration changed - reason = _(': Group chat configuration changed to members-only') - message = message.format(actor=actor, reason=reason) - self.add_info_message(message) + if StatusCode.NICKNAME_MODIFIED in status_codes: + message = _('The server has assigned or modified your ' + 'nickname in this group chat') - elif StatusCode.REMOVED_SERVICE_SHUTDOWN in status_codes: - # Group Chat: Kicked because of server shutdown - reason = ': System shutdown' - message = message.format(actor=actor, reason=reason) - self.add_info_message(message) + if message is not None: + self.add_info_message(message, event.timestamp) def _on_user_left(self, _contact: GroupchatContact, _signal_name: str, - user_contact: GroupchatParticipant, - properties: MessageProperties + _user_contact: GroupchatParticipant, + event: events.MUCUserLeft ) -> None: - status_codes = properties.muc_status_codes or [] - nick = user_contact.name - assert properties.muc_user is not None - reason = properties.muc_user.reason + self._process_muc_user_left(event) + + def _process_muc_user_left(self, event: events.MUCUserLeft) -> None: + status_codes = event.status_codes or [] + nick = event.nick + + reason = event.reason reason = '' if reason is None else f': {reason}' - actor = properties.muc_user.actor + actor = event.actor # Group Chat: You have been kicked by Alice - actor = '' if actor is None else _(' by {actor}').format(actor=actor) + actor = '' if actor is None else _(' by {actor}').format( + actor=actor) # Group Chat: We have been removed from the room - message = _('{nick} has been removed from the group chat{by}{reason}') + message = _('{nick} has been removed from the group ' + 'chat{by}{reason}') if StatusCode.REMOVED_ERROR in status_codes: # Handle 333 before 307, some MUCs add both self.conversation_view.add_muc_user_left( - nick, properties.muc_user.reason, error=True) + nick, event.reason, error=True) elif StatusCode.REMOVED_KICKED in status_codes: # Group Chat: User was kicked by Alice: reason @@ -1092,7 +1106,6 @@ def _on_user_left(self, 'kicked{actor}{reason}').format(nick=nick, actor=actor, reason=reason) - self.add_info_message(message) elif StatusCode.REMOVED_BANNED in status_codes: # Group Chat: User was banned by Alice: reason @@ -1100,49 +1113,104 @@ def _on_user_left(self, 'banned{actor}{reason}').format(nick=nick, actor=actor, reason=reason) - self.add_info_message(message) elif StatusCode.REMOVED_AFFILIATION_CHANGE in status_codes: reason = _(': Affiliation changed') message = message.format(nick=nick, by=actor, reason=reason) - self.add_info_message(message) elif StatusCode.REMOVED_NONMEMBER_IN_MEMBERS_ONLY in status_codes: reason = _(': Group chat configuration changed to members-only') message = message.format(nick=nick, by=actor, reason=reason) - self.add_info_message(message) else: - self.conversation_view.add_muc_user_left( - nick, properties.muc_user.reason) + self.conversation_view.add_muc_user_left(nick, event.reason) + return - def _on_room_presence_error(self, - _contact: GroupchatContact, - _signal_name: str, - properties: PresenceProperties - ) -> None: + self.add_info_message(message, event.timestamp) - assert properties.error is not None - error_message = to_user_string(properties.error) - self.add_info_message(_('Error: %s') % error_message) + def _on_muc_user_status_show_changed(self, + contact: GroupchatContact, + _signal_name: str, + user_contact: GroupchatParticipant, + properties: PresenceProperties + ) -> None: - def _on_room_destroyed(self, - _contact: GroupchatContact, - _signal_name: str, - properties: PresenceProperties - ) -> None: + if not contact.settings.get('print_status'): + return - destroyed = properties.muc_destroyed - assert destroyed is not None + self.conversation_view.add_user_status(user_contact.name, + user_contact.show.value, + user_contact.status) - reason = destroyed.reason - reason = '' if reason is None else f': {reason}' + def _on_room_voice_request(self, + _contact: GroupchatContact, + _signal_name: str, + properties: MessageProperties + ) -> None: + voice_request = properties.voice_request + assert voice_request is not None - message = _('Group chat has been destroyed') - self.add_info_message(message) + def on_approve() -> None: + self.client.get_module('MUC').approve_voice_request( + self.contact.jid, voice_request) + + ConfirmationDialog( + _('Voice Request'), + _('Voice Request'), + _('<b>%(nick)s</b> from <b>%(room_name)s</b> requests voice') % { + 'nick': voice_request.nick, 'room_name': self.contact.name}, + [DialogButton.make('Cancel'), + DialogButton.make('Accept', + text=_('_Approve'), + callback=on_approve)], + modal=False).show() - alternate = destroyed.alternate - if alternate is not None: - join_message = _('You can join this group chat ' - 'instead: xmpp:%s?join') % str(alternate) - self.add_info_message(join_message) + def add_muc_message(self, + text: str, + tim: float, + contact: str = '', + displaymarking: Optional[Displaymarking] = None, + message_id: Optional[str] = None, + stanza_id: Optional[str] = None, + additional_data: Optional[AdditionalDataDict] = None, + ) -> None: + + assert isinstance(self._contact, GroupchatContact) + + if contact == self._contact.nickname: + kind = 'outgoing' + else: + kind = 'incoming' + # muc-specific chatstate + + self._add_message(text, + kind, + contact, + tim, + displaymarking=displaymarking, + message_id=message_id, + stanza_id=stanza_id, + additional_data=additional_data) + + def _on_room_subject(self, + contact: GroupchatContact, + _signal_name: str, + subject: Optional[MucSubject] + ) -> None: + + if subject is None: + return + + _timestamp, old_subject = self._muc_subjects.get(contact, (None, None)) + if old_subject is not None and old_subject.text == subject.text: + # Probably a rejoin, we already showed that subject + return + + self._muc_subjects[contact] = (time.time(), subject) + + if (app.settings.get('show_subject_on_join') or + not contact.is_joining): + self.conversation_view.add_muc_subject(subject) + + def rejoin(self) -> None: + self.client.get_module('MUC').join(self.contact.jid) ===================================== gajim/gtk/conversation/view.py ===================================== @@ -176,7 +176,7 @@ def add_muc_subject(self, def add_muc_user_left(self, nick: str, - reason: str, + reason: Optional[str], error: bool = False) -> None: assert isinstance(self._contact, GroupchatContact) if not self._contact.settings.get('print_join_left'): ===================================== gajim/gtk/groupchat_nick_completion.py ===================================== @@ -18,7 +18,6 @@ import logging -from nbxmpp.structs import PresenceProperties from gi.repository import Gtk from gi.repository import Gdk @@ -27,6 +26,7 @@ from gajim.common import ged from gajim.common import types from gajim.common.events import GcMessageReceived +from gajim.common.events import MUCNicknameChanged from gajim.common.ged import EventHelper from gajim.common.helpers import jid_is_blocked from gajim.common.helpers import message_needs_highlight @@ -76,12 +76,12 @@ def switch_contact(self, contact: types.GroupchatContactT) -> None: def _on_user_nickname_changed(self, _contact: types.GroupchatContact, _signal_name: str, + event: MUCNicknameChanged, old_contact: types.GroupchatParticipant, - new_contact: types.GroupchatParticipant, - properties: PresenceProperties + new_contact: types.GroupchatParticipant ) -> None: - if properties.is_muc_self_presence: + if event.is_self: return old_name = old_contact.name ===================================== gajim/gtk/groupchat_roster.py ===================================== @@ -25,7 +25,6 @@ from gi.repository import Gtk from gi.repository import GLib from nbxmpp.const import Affiliation -from nbxmpp.structs import PresenceProperties from gajim.common import app from gajim.common import ged @@ -36,6 +35,7 @@ from gajim.common.const import AvatarSize from gajim.common.const import StyleAttr from gajim.common.events import ApplicationEvent +from gajim.common.events import MUCNicknameChanged from gajim.common.modules.contacts import GroupchatContact from .menus import get_groupchat_roster_menu @@ -283,9 +283,9 @@ def _update_contact(self, def _on_user_nickname_changed(self, contact: types.GroupchatContact, _signal_name: str, + _event: MUCNicknameChanged, old_contact: types.GroupchatParticipant, - new_contact: types.GroupchatParticipant, - properties: PresenceProperties + new_contact: types.GroupchatParticipant ) -> None: self._remove_contact(old_contact) ===================================== gajim/gtk/main.py ===================================== @@ -653,6 +653,13 @@ def activate_workspace(self, workspace_id: str) -> None: self._main_stack.show_chats(workspace_id) self._workspace_side_bar.activate_workspace(workspace_id) + # Show chatlist if it is hidden + chat_list_stack = self._chat_page.get_chat_list_stack() + chat_list = chat_list_stack.get_current_chat_list() + if chat_list is not None: + if not chat_list.is_visible(): + self._toggle_chat_list() + def update_workspace(self, workspace_id: str) -> None: self._chat_page.update_workspace(workspace_id) self._workspace_side_bar.update_avatar(workspace_id) ===================================== gajim/gtk/message_actions_box.py ===================================== @@ -219,9 +219,8 @@ def switch_contact(self, contact: ChatContactT) -> None: self._set_settings_menu(contact) - encryption = self._contact.settings.get('encryption') - self._set_encryption_state(encryption) - self._set_encryption_details(encryption) + self._update_encryption_button() + self._update_encryption_details_button() self._set_chatstate(True) @@ -286,18 +285,6 @@ def _set_chatstate(self, state: bool) -> None: self._client.get_module('Chatstate').set_chatstate( self._contact, Chatstate.INACTIVE) - def _set_encryption_state(self, state: str) -> None: - action = app.window.get_action('set-encryption') - action.set_state(GLib.Variant('s', state)) - - if state in ('OMEMO', 'OpenPGP', 'PGP'): - icon_name = 'channel-secure-symbolic' - else: - icon_name = 'channel-insecure-symbolic' - - self._ui.encryption_image.set_from_icon_name(icon_name, - Gtk.IconSize.MENU) - def _change_encryption(self, action: Gio.SimpleAction, param: GLib.Variant @@ -319,13 +306,43 @@ def _change_encryption(self, if not plugin.activate_encryption(app.window.get_control()): return - self._set_encryption_state(new_state) contact = self.get_current_contact() contact.settings.set('encryption', new_state) - self._set_encryption_details(new_state) + self._update_encryption_button() + self._update_encryption_details_button() + + def _update_encryption_button(self) -> None: + contact = self.get_current_contact() + state = contact.settings.get('encryption') + + action = app.window.get_action('set-encryption') + action.set_state(GLib.Variant('s', state)) + + sensitive = True + tooltip = _('Choose encryption') + + if state in ('OMEMO', 'OpenPGP', 'PGP'): + icon_name = 'channel-secure-symbolic' + else: + icon_name = 'channel-insecure-symbolic' + + if isinstance(self._contact, GroupchatContact): + if not self._contact.encryption_available: + sensitive = False + tooltip = _('This is a public group chat. ' + 'Encryption is not available.') + icon_name = 'channel-insecure-symbolic' + + self._ui.encryption_menu_button.set_sensitive(sensitive) + self._ui.encryption_menu_button.set_tooltip_text(tooltip) + self._ui.encryption_image.set_from_icon_name( + icon_name, Gtk.IconSize.MENU) + + def _update_encryption_details_button(self) -> None: + contact = self.get_current_contact() + state = contact.settings.get('encryption') - def _set_encryption_details(self, state: str) -> None: encryption_state = {'visible': bool(state), 'enc_type': state, 'authenticated': False} @@ -341,19 +358,22 @@ def _set_encryption_details(self, state: str) -> None: if authenticated: authenticated_string = _('and authenticated') - self._ui.encryption_details_image.set_from_icon_name( - 'security-high-symbolic', Gtk.IconSize.MENU) + icon_name = 'security-high-symbolic' else: authenticated_string = _('and NOT authenticated') - self._ui.encryption_details_image.set_from_icon_name( - 'security-low-symbolic', Gtk.IconSize.MENU) + icon_name = 'security-low-symbolic' tooltip = _('%(type)s encryption is active %(authenticated)s.') % { - 'type': enc_type, 'authenticated': authenticated_string} + 'type': enc_type, + 'authenticated': authenticated_string} + + if isinstance(self._contact, GroupchatContact) and visible: + visible = self._contact.encryption_available - self._ui.encryption_details_button.set_tooltip_text(tooltip) self._ui.encryption_details_button.set_visible(visible) - self._ui.encryption_details_image.set_sensitive(visible) + self._ui.encryption_details_button.set_tooltip_text(tooltip) + self._ui.encryption_details_image.set_from_icon_name( + icon_name, Gtk.IconSize.MENU) def _on_encryption_details_clicked(self, _button: Gtk.Button) -> None: contact = self.get_current_contact() ===================================== test/no_gui/test_sanitize_filename.py ===================================== @@ -0,0 +1,61 @@ + +import sys +import unittest +from unittest.mock import patch +from gajim.common.helpers import sanitize_filename + + +class SanitizeTest(unittest.TestCase): + '''Tests for the sanitize_filename function.''' + + @patch.object(sys, 'platform', 'win32') + def test_invalid_chars(self): + '''Make sure invalid characters are removed in filenames''' + self.assertEqual(sanitize_filename('A/B/C'), 'ABC') + self.assertEqual(sanitize_filename('A*C.d'), 'AC.d') + self.assertEqual(sanitize_filename('A?C.d'), 'AC.d') + + @patch.object(sys, 'platform', 'win32') + def test_invalid_suffix(self): + '''Dots are not allowed at the end''' + self.assertEqual(sanitize_filename('def.'), 'def') + self.assertEqual(sanitize_filename('def.ghi'), 'def.ghi') + self.assertTrue(sanitize_filename('X' * 1000 + '.').endswith('X')) + + @patch.object(sys, 'platform', 'win32') + def test_reserved_words(self): + '''Make sure reserved Windows words are prefixed''' + self.assertEqual(sanitize_filename('NUL'), '__NUL') + self.assertEqual(sanitize_filename('..'), '__') + + @patch.object(sys, 'platform', 'win32') + def test_long_names(self): + '''Make sure long names are truncated''' + self.assertEqual(len(sanitize_filename('X' * 300)), 50) + self.assertEqual(len(sanitize_filename( + '.'.join(['X' * 100, 'X' * 100, 'X' * 100]))), 50) + self.assertEqual(len(sanitize_filename( + '.'.join(['X' * 300, 'X' * 300, 'X' * 300]))), 50) + self.assertEqual(len(sanitize_filename('.' * 300 + '.txt')), 50) + + @patch.object(sys, 'platform', 'win32') + def test_unicode_normalization(self): + '''Names should be NFKD normalized''' + self.assertEqual(sanitize_filename('Ñž'), chr(1091) + chr(774)) + + @patch.object(sys, 'platform', 'win32') + def test_extensions(self): + '''Filename extensions should be preserved when possible.''' + really_long_name = 'X' * 1000 + '.pdf' + self.assertTrue(sanitize_filename(really_long_name).endswith('.pdf')) + self.assertTrue(sanitize_filename('X' * 1000).endswith('X')) + self.assertTrue(sanitize_filename( + 'X' * 100 + '.' + 'X' * 100 + '.pdf').endswith('.pdf')) + self.assertTrue(sanitize_filename( + 'X' * 100 + '.' + 'X' * 400).endswith('X')) + self.assertTrue(sanitize_filename( + 'X' * 100 + '.' + 'X' * 400 + '.pdf').endswith('.pdf')) + + +if __name__ == '__main__': + unittest.main() View it on GitLab:
https://dev.gajim.org/gajim/gajim/-/compare/8af47b1b53332370dba67902d88575c…
-- View it on GitLab:
https://dev.gajim.org/gajim/gajim/-/compare/8af47b1b53332370dba67902d88575c…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/gajim][move-workspace-chats-on-remove] imprv: Workspaces: Move chats when removing workspace
by Daniel Brötzmann (ï¼ wurstsalat)
28 Aug '22
28 Aug '22
Daniel Brötzmann pushed to branch move-workspace-chats-on-remove at gajim / gajim Commits: 6a2a3eca by wurstsalat at 2022-08-28T12:16:08+02:00 imprv: Workspaces: Move chats when removing workspace Closes #11098 - - - - - 6 changed files: - gajim/gtk/chat_list_stack.py - gajim/gtk/main.py - gajim/gtk/menus.py - gajim/gtk/structs.py - gajim/gtk/workspace_dialog.py - gajim/gtk/workspace_side_bar.py Changes: ===================================== gajim/gtk/chat_list_stack.py ===================================== @@ -243,16 +243,21 @@ def _move_chat_to_workspace(self, if not workspace_id: workspace_id = app.window.add_workspace(switch=False) - current_chatlist = cast(ChatList, self.get_visible_child()) - type_ = current_chatlist.get_chat_type(params.account, params.jid) + if params.source_workspace_id: + source_chatlist = self.get_chatlist(params.source_workspace_id) + else: + source_chatlist = cast(ChatList, self.get_visible_child()) + + type_ = source_chatlist.get_chat_type(params.account, params.jid) if type_ is None: return - current_chatlist.remove_chat(params.account, params.jid) + + source_chatlist.remove_chat(params.account, params.jid) new_chatlist = self.get_chatlist(workspace_id) new_chatlist.add_chat(params.account, params.jid, type_, False, -1) - self.store_open_chats(current_chatlist.workspace_id) + self.store_open_chats(source_chatlist.workspace_id) self.store_open_chats(workspace_id) @structs.actionmethod ===================================== gajim/gtk/main.py ===================================== @@ -62,6 +62,7 @@ from .structs import AccountJidParam from .structs import AddChatActionParams from .structs import actionmethod +from .structs import ChatListEntryParam if TYPE_CHECKING: from .control import ChatControl @@ -626,18 +627,52 @@ def _remove_workspace(self, self.remove_workspace(workspace_id) def remove_workspace(self, workspace_id: str) -> None: + if len(app.settings.get_workspaces()) == 1: + log.warning('Tried to remove the only workspace') + return + was_active = self.get_active_workspace() == workspace_id + chat_list = self.get_chat_list(workspace_id) + open_chats = chat_list.get_open_chats() + + def _continue_removing_workspace(): + new_workspace_id = self._workspace_side_bar.get_other_workspace( + workspace_id) + if new_workspace_id is None: + log.warning('No other workspaces found') + return - success = self._workspace_side_bar.remove_workspace(workspace_id) - if not success: + for open_chat in open_chats: + params = ChatListEntryParam( + workspace_id=new_workspace_id, + source_workspace_id=workspace_id, + account=open_chat['account'], + jid=open_chat['jid']) + self.activate_action('move-chat-to-workspace', + params.to_variant()) + + if was_active: + self.activate_workspace(new_workspace_id) + + self._workspace_side_bar.remove_workspace(workspace_id) + self._chat_page.remove_chat_list(workspace_id) + app.settings.remove_workspace(workspace_id) + + if open_chats: + ConfirmationDialog( + _('Remove Workspace'), + _('Remove Workspace'), + _('This workspace contains chats. All chats will be moved to ' + 'the next workspace. Remove anyway?'), + [DialogButton.make('Cancel', + text=_('_No')), + DialogButton.make('Remove', + callback=_continue_removing_workspace)] + ).show() return - if was_active: - new_active_id = self._workspace_side_bar.get_first_workspace() - self.activate_workspace(new_active_id) - - self._chat_page.remove_chat_list(workspace_id) - app.settings.remove_workspace(workspace_id) + # No chats in chat list, it is save to remove this workspace + _continue_removing_workspace() def _activate_workspace(self, _action: Gio.SimpleAction, ===================================== gajim/gtk/menus.py ===================================== @@ -410,6 +410,7 @@ def get_chat_list_row_menu(workspace_id: str, menu = GajimMenu() params = ChatListEntryParam(workspace_id=workspace_id, + source_workspace_id='', account=account, jid=jid) @@ -423,6 +424,7 @@ def get_chat_list_row_menu(workspace_id: str, submenu.add_item(name, 'win.move-chat-to-workspace', params) params = ChatListEntryParam(workspace_id='', + source_workspace_id='', account=account, jid=jid) @@ -450,6 +452,7 @@ def get_workspace_params(current_workspace_id: str, continue name = app.settings.get_workspace_setting(workspace_id, 'name') params = ChatListEntryParam(workspace_id=workspace_id, + source_workspace_id=current_workspace_id, account=account, jid=jid) yield name, params @@ -577,9 +580,12 @@ def get_format_menu() -> GajimMenu: def get_workspace_menu(workspace_id: str) -> GajimMenu: menuitems: MenuItemListT = [ (_('Edit…'), 'win.edit-workspace', f'"{workspace_id}"'), - (_('Remove'), 'win.remove-workspace', f'"{workspace_id}"'), ] + if len(app.settings.get_workspaces()) > 1: + menuitems.append( + (_('Remove'), 'win.remove-workspace', f'"{workspace_id}"')) + return GajimMenu.from_list(menuitems) ===================================== gajim/gtk/structs.py ===================================== @@ -55,6 +55,7 @@ class AddChatActionParams(VariantMixin): @dataclass class ChatListEntryParam(VariantMixin): workspace_id: str + source_workspace_id: str account: str jid: JID ===================================== gajim/gtk/workspace_dialog.py ===================================== @@ -24,8 +24,6 @@ from .avatar import make_workspace_avatar from .avatar_selector import AvatarSelector -from .dialogs import ConfirmationDialog -from .dialogs import DialogButton from .builder import get_builder from .util import rgba_to_float from .util import make_rgba @@ -93,25 +91,9 @@ def _on_key_press(self, _widget: Gtk.Widget, event: Gdk.EventKey) -> None: self.destroy() def _on_remove_workspace(self, _button: Gtk.Button) -> None: - def _on_remove(): - assert self._workspace_id is not None - app.window.remove_workspace(self._workspace_id) - self.destroy() assert self._workspace_id is not None - chat_list = app.window.get_chat_list(self._workspace_id) - open_chats = chat_list.get_open_chats() - if len(open_chats) > 0: - ConfirmationDialog( - _('Remove Workspace'), - _('Remove Workspace'), - _('This workspace contains chats. Remove anyway?'), - [DialogButton.make('Cancel', - text=_('_No')), - DialogButton.make('Remove', - callback=_on_remove)]).show() - return - # No chats in chat list, it is save to remove workspace - _on_remove() + app.window.remove_workspace(self._workspace_id) + self.destroy() def _on_cancel(self, _button: Gtk.Button) -> None: self.destroy() ===================================== gajim/gtk/workspace_side_bar.py ===================================== @@ -158,6 +158,7 @@ def _process_chat_list_drop(self, workspace_id = '' params = ChatListEntryParam(workspace_id=workspace_id, + source_workspace_id='', account=account, jid=jid) app.window.activate_action('move-chat-to-workspace', @@ -221,12 +222,18 @@ def store_workspace_order(self) -> None: order.remove('add') app.settings.set_app_setting('workspace_order', order) - def remove_workspace(self, workspace_id: str) -> bool: - if len(self._workspaces) == 1: - return False + def remove_workspace(self, workspace_id: str) -> None: row = self._workspaces.pop(workspace_id) self.remove(row) - return True + + def get_other_workspace(self, + exclude_workspace_id: str + ) -> Optional[str]: + + for workspace in self._workspaces.values(): + if workspace.workspace_id != exclude_workspace_id: + return workspace.workspace_id + return None def activate_workspace(self, workspace_id: str) -> None: row = cast(CommonWorkspace, self.get_selected_row()) View it on GitLab:
https://dev.gajim.org/gajim/gajim/-/commit/6a2a3ecaa311ca489720a5376d189923…
-- View it on GitLab:
https://dev.gajim.org/gajim/gajim/-/commit/6a2a3ecaa311ca489720a5376d189923…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/gajim] Pushed new branch move-workspace-chats-on-remove
by Daniel Brötzmann (ï¼ wurstsalat)
28 Aug '22
28 Aug '22
Daniel Brötzmann pushed new branch move-workspace-chats-on-remove at gajim / gajim -- View it on GitLab:
https://dev.gajim.org/gajim/gajim/-/tree/move-workspace-chats-on-remove
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
[Git][gajim/python-nbxmpp][master] 2 commits: refactor: SASL: Prepare module for XEP-0388
by Philipp Hörist (ï¼ lovetox)
28 Aug '22
28 Aug '22
Philipp Hörist pushed to branch master at gajim / python-nbxmpp Commits: c9969f4f by lovetox at 2022-08-28T07:01:40+00:00 refactor: SASL: Prepare module for XEP-0388 - Move sending stanzas out of mechanism impl - Add missing SHA-512-PLUS method - Add type hints - - - - - 18c408c0 by lovetox at 2022-08-28T09:06:03+02:00 ci: Disable pylint check - - - - - 5 changed files: - .ci/pylint-test.py - nbxmpp/client.py - nbxmpp/protocol.py - nbxmpp/auth.py → nbxmpp/sasl.py - test/unit/test_sasl_scram.py Changes: ===================================== .ci/pylint-test.py ===================================== @@ -14,6 +14,7 @@ DISABLED_CHECKS = [ 'W0201', # attribute-defined-outside-init 'W0212', # protected-access 'W0221', # arguments-differ + 'W0223', # abstract-method 'W0231', # super-init-not-called 'W0233', # non-parent-init-called 'W0621', # redefined-outer-name ===================================== nbxmpp/client.py ===================================== @@ -39,7 +39,7 @@ from nbxmpp.addresses import NoMoreAddresses from nbxmpp.tcp import TCPConnection from nbxmpp.websocket import WebsocketConnection from nbxmpp.smacks import Smacks -from nbxmpp.auth import SASL +from nbxmpp.sasl import SASL from nbxmpp.const import StreamState from nbxmpp.const import StreamError from nbxmpp.const import ConnectionType ===================================== nbxmpp/protocol.py ===================================== @@ -44,6 +44,7 @@ def ascii_upper(s): return s.upper() SASL_AUTH_MECHS = [ + 'SCRAM-SHA-512-PLUS', 'SCRAM-SHA-512', 'SCRAM-SHA-256-PLUS', 'SCRAM-SHA-256', ===================================== nbxmpp/auth.py → nbxmpp/sasl.py ===================================== @@ -21,6 +21,7 @@ import binascii import logging import hashlib from hashlib import pbkdf2_hmac +from typing import Optional from nbxmpp.namespaces import Namespace from nbxmpp.protocol import Node @@ -32,7 +33,7 @@ from nbxmpp.util import LogAdapter from nbxmpp.const import StreamState -log = logging.getLogger('nbxmpp.auth') +log = logging.getLogger('nbxmpp.sasl') try: gssapi = __import__('gssapi') @@ -51,9 +52,20 @@ class SASL: self._password = None + self._mechanism_classes = { + 'PLAIN': PLAIN, + 'EXTERNAL': EXTERNAL, + 'GSSAPI': GSSAPI, + 'SCRAM-SHA-1': SCRAM_SHA_1, + 'SCRAM-SHA-1-PLUS': SCRAM_SHA_1_PLUS, + 'SCRAM-SHA-256': SCRAM_SHA_256, + 'SCRAM-SHA-256-PLUS': SCRAM_SHA_256_PLUS, + 'SCRAM-SHA-512': SCRAM_SHA_512, + 'SCRAM-SHA-512-PLUS': SCRAM_SHA_512_PLUS + } + self._allowed_mechs = None self._enabled_mechs = None - self._method = None self._error = None self._log = LogAdapter(log, {'context': client.log_context}) @@ -82,13 +94,14 @@ class SASL: def start_auth(self, features): self._allowed_mechs = self._client.mechs self._enabled_mechs = self._allowed_mechs - self._method = None + self._mechanism = None self._error = None # -PLUS variants need TLS channel binding data # This is currently not supported via GLib self._enabled_mechs.discard('SCRAM-SHA-1-PLUS') self._enabled_mechs.discard('SCRAM-SHA-256-PLUS') + self._enabled_mechs.discard('SCRAM-SHA-512-PLUS') # channel_binding_data = None if not GSSAPI_AVAILABLE: @@ -127,69 +140,49 @@ class SASL: self._on_sasl_finished(False, 'no-password') return - # if chosen_mechanism == 'SCRAM-SHA-256-PLUS': - # self._method = SCRAM_SHA_256_PLUS(self._client, - # channel_binding_data) - # self._method.initiate(self._client.username, self._password) - - # elif chosen_mechanism == 'SCRAM-SHA-1-PLUS': - # self._method = SCRAM_SHA_1_PLUS(self._client, - # channel_binding_data) - # self._method.initiate(self._client.username, self._password) - - if chosen_mechanism == 'SCRAM-SHA-512': - self._method = SCRAM_SHA_512(self._client, None) - self._method.initiate(self._client.username, self._password) - - elif chosen_mechanism == 'SCRAM-SHA-256': - self._method = SCRAM_SHA_256(self._client, None) - self._method.initiate(self._client.username, self._password) - - elif chosen_mechanism == 'SCRAM-SHA-1': - self._method = SCRAM_SHA_1(self._client, None) - self._method.initiate(self._client.username, self._password) + mech_class = self._mechanism_classes[chosen_mechanism] + self._mechanism = mech_class(self._client.username, + self._password, + domain_based_name or self._client.domain) - elif chosen_mechanism == 'PLAIN': - self._method = PLAIN(self._client) - self._method.initiate(self._client.username, self._password) - - elif chosen_mechanism == 'ANONYMOUS': - self._method = ANONYMOUS(self._client) - self._method.initiate() # pylint: disable=E1120 - - elif chosen_mechanism == 'EXTERNAL': - self._method = EXTERNAL(self._client) - self._method.initiate(self._client.username, self._client.Server) + try: + self._send_initiate() + except AuthFail as error: + self._log.error(error) + self._abort_auth() + return - elif chosen_mechanism == 'GSSAPI': - self._method = GSSAPI(self._client) - if domain_based_name: - hostname = domain_based_name - else: - hostname = self._client.domain - try: - self._method.initiate(hostname) # pylint: disable=E1120 - except AuthFail as error: - self._log.error(error) - self._abort_auth() - return - else: - self._log.error('Unknown auth mech') + def _send_initiate(self) -> None: + data = self._mechanism.get_initiate_data() + node = Node('auth', + attrs={'xmlns': Namespace.SASL, + 'mechanism': self._mechanism.name}) + if data is not None: + node.setData(data) + self._client.send_nonza(node) - def _on_challenge(self, stanza): + def _on_challenge(self, stanza) -> None: try: - self._method.response(stanza.getData()) + data = self._mechanism.get_response_data(stanza.getData()) except AttributeError: self._log.info('Mechanism has no response method') self._abort_auth() + return + except AuthFail as error: self._log.error(error) self._abort_auth() + return + + node = Node('response', + attrs={'xmlns': Namespace.SASL}, + payload=[data]) + self._client.send_nonza(node) def _on_success(self, stanza): self._log.info('Successfully authenticated with remote server') try: - self._method.success(stanza.getData()) + self._mechanism.get_success_data(stanza.getData()) except AttributeError: pass except AuthFail as error: @@ -227,61 +220,59 @@ class SASL: self._client.set_state(StreamState.AUTH_SUCCESSFUL) -class PLAIN: +class BaseMechanism: - _mechanism = 'PLAIN' + name: str - def __init__(self, client): - self._client = client + def __init__(self, username: str, password: str, domain: str): + self._username = username + self._password = password + self._domain = domain - def initiate(self, username, password): - payload = b64encode('\x00%s\x00%s' % (username, password)) - node = Node('auth', - attrs={'xmlns': Namespace.SASL, 'mechanism': 'PLAIN'}, - payload=[payload]) - self._client.send_nonza(node) + def get_initiate_data(self) -> Optional[str]: + raise NotImplementedError + def get_response_data(self, data: str) -> str: + raise NotImplementedError -class EXTERNAL: + def validate_success_data(self, data: str) -> None: + raise NotImplementedError - _mechanism = 'EXTERNAL' - def __init__(self, client): - self._client = client +class PLAIN(BaseMechanism): - def initiate(self, username, server): - payload = b64encode('%s@%s' % (username, server)) - node = Node('auth', - attrs={'xmlns': Namespace.SASL, 'mechanism': 'EXTERNAL'}, - payload=[payload]) - self._client.send_nonza(node) + name = 'PLAIN' + def get_initiate_data(self) -> str: + return b64encode('\x00%s\x00%s' % (self._username, self._password)) -class ANONYMOUS: - _mechanism = 'ANONYMOUS' +class EXTERNAL(BaseMechanism): - def __init__(self, client): - self._client = client + name = 'EXTERNAL' - def initiate(self): - node = Node('auth', attrs={'xmlns': Namespace.SASL, - 'mechanism': 'ANONYMOUS'}) - self._client.send_nonza(node) + def get_initiate_data(self) -> str: + return b64encode('%s@%s' % (self._username, self._domain)) -class GSSAPI: +class ANONYMOUS(BaseMechanism): - # See
https://tools.ietf.org/html/rfc4752#section-3.1
+ name = 'ANONYMOUS' - _mechanism = 'GSSAPI' + def get_initiate_data(self) -> None: + return None - def __init__(self, client): - self._client = client - def initiate(self, hostname): +class GSSAPI(BaseMechanism): + + # See
https://tools.ietf.org/html/rfc4752#section-3.1
+ + name = 'GSSAPI' + + def get_initiate_data(self) -> str: service = gssapi.Name( - 'xmpp@%s' % hostname, name_type=gssapi.NameType.hostbased_service) + 'xmpp@%s' % self._domain, + name_type=gssapi.NameType.hostbased_service) try: self.ctx = gssapi.SecurityContext( name=service, usage="initiate", @@ -289,75 +280,66 @@ class GSSAPI: token = self.ctx.step() except (gssapi.exceptions.GeneralError, gssapi.raw.misc.GSSError) as e: raise AuthFail(e) - node = Node('auth', - attrs={'xmlns': Namespace.SASL, 'mechanism': 'GSSAPI'}, - payload=b64encode(token)) - self._client.send_nonza(node) - def response(self, server_message, *args, **kwargs): - server_message = b64decode(server_message) + return b64encode(token) + + def get_response_data(self, data: str) -> str: + byte_data = b64decode(data) try: if not self.ctx.complete: - output_token = self.ctx.step(server_message) + output_token = self.ctx.step(byte_data) else: - _result = self.ctx.unwrap(server_message) + _result = self.ctx.unwrap(byte_data) # TODO(jelmer): Log result.message data = b'\x00\x00\x00\x00' + bytes(self.ctx.initiator_name) output_token = self.ctx.wrap(data, False).message except (gssapi.exceptions.GeneralError, gssapi.raw.misc.GSSError) as e: raise AuthFail(e) - response = b64encode(output_token) - node = Node('response', - attrs={'xmlns': Namespace.SASL}, - payload=response) - self._client.send_nonza(node) + + return b64encode(output_token) -class SCRAM: +class SCRAM(BaseMechanism): - _mechanism = '' + name = '' _channel_binding = '' _hash_method = '' - def __init__(self, client, channel_binding): - self._client = client - self._channel_binding_data = channel_binding + def __init__(self, *args, **kwargs) -> None: + BaseMechanism.__init__(self, *args, **kwargs) + self._channel_binding_data = None self._client_nonce = '%x' % int(binascii.hexlify(os.urandom(24)), 16) self._client_first_message_bare = None self._server_signature = None - self._password = None + + def set_channel_binding_data(self, data: bytes) -> None: + self._channel_binding_data = data @property - def nonce_length(self): + def nonce_length(self) -> int: return len(self._client_nonce) @property - def _b64_channel_binding_data(self): - if self._mechanism.endswith('PLUS'): + def _b64_channel_binding_data(self) -> str: + if self.name.endswith('PLUS'): return b64encode(b'%s%s' % (self._channel_binding.encode(), self._channel_binding_data)) return b64encode(self._channel_binding) @staticmethod - def _scram_parse(scram_data): + def _scram_parse(scram_data: str) -> dict[str, str]: return dict(s.split('=', 1) for s in scram_data.split(',')) - def initiate(self, username, password): - self._password = password - self._client_first_message_bare = 'n=%s,r=%s' % (username, + def get_initiate_data(self) -> str: + self._client_first_message_bare = 'n=%s,r=%s' % (self._username, self._client_nonce) client_first_message = '%s%s' % (self._channel_binding, self._client_first_message_bare) - payload = b64encode(client_first_message) - node = Node('auth', - attrs={'xmlns': Namespace.SASL, - 'mechanism': self._mechanism}, - payload=[payload]) - self._client.send_nonza(node) + return b64encode(client_first_message) - def response(self, server_first_message): - server_first_message = b64decode(server_first_message).decode() + def get_response_data(self, data) -> str: + server_first_message = b64decode(data).decode() challenge = self._scram_parse(server_first_message) client_nonce = challenge['r'][:self.nonce_length] @@ -397,64 +379,66 @@ class SCRAM: server_key = self._hmac(salted_password, 'Server Key') self._server_signature = self._hmac(server_key, auth_message) - payload = b64encode(client_finale_message) - node = Node('response', - attrs={'xmlns': Namespace.SASL}, - payload=[payload]) - self._client.send_nonza(node) + return b64encode(client_finale_message) - def success(self, server_last_message): - server_last_message = b64decode(server_last_message).decode() + def validate_success_data(self, data: str) -> None: + server_last_message = b64decode(data).decode() success = self._scram_parse(server_last_message) server_signature = b64decode(success['v']) if server_signature != self._server_signature: raise AuthFail('Invalid server signature') - def _hmac(self, key, message): + def _hmac(self, key: bytes, message: str) -> bytes: return hmac.new(key=key, msg=message.encode(), digestmod=self._hash_method).digest() @staticmethod - def _xor(x, y): + def _xor(x: bytes, y: bytes) -> bytes: return bytes([px ^ py for px, py in zip(x, y)]) - def _h(self, data): + def _h(self, data: bytes) -> bytes: return hashlib.new(self._hash_method, data).digest() class SCRAM_SHA_1(SCRAM): - _mechanism = 'SCRAM-SHA-1' + name = 'SCRAM-SHA-1' _channel_binding = 'n,,' _hash_method = 'sha1' class SCRAM_SHA_1_PLUS(SCRAM_SHA_1): - _mechanism = 'SCRAM-SHA-1-PLUS' + name = 'SCRAM-SHA-1-PLUS' _channel_binding = 'p=tls-unique,,' class SCRAM_SHA_256(SCRAM): - _mechanism = 'SCRAM-SHA-256' + name = 'SCRAM-SHA-256' _channel_binding = 'n,,' _hash_method = 'sha256' class SCRAM_SHA_256_PLUS(SCRAM_SHA_256): - _mechanism = 'SCRAM-SHA-256-PLUS' + name = 'SCRAM-SHA-256-PLUS' _channel_binding = 'p=tls-unique,,' class SCRAM_SHA_512(SCRAM): - _mechanism = 'SCRAM-SHA-512' + name = 'SCRAM-SHA-512' _channel_binding = 'n,,' _hash_method = 'sha512' +class SCRAM_SHA_512_PLUS(SCRAM_SHA_512): + + name = 'SCRAM-SHA-512-PLUS' + _channel_binding = 'p=tls-unique,,' + + class AuthFail(Exception): pass ===================================== test/unit/test_sasl_scram.py ===================================== @@ -1,33 +1,34 @@ import unittest from unittest.mock import Mock -from nbxmpp.auth import SCRAM_SHA_1 +from nbxmpp.sasl import SCRAM_SHA_1 from nbxmpp.util import b64encode # Test vector from
https://wiki.xmpp.org/web/SASL_and_SCRAM-SHA-1
+ class SCRAM(unittest.TestCase): def setUp(self): self.con = Mock() - self._method = SCRAM_SHA_1(self.con, None) - self._method._client_nonce = 'fyko+d2lbbFgONRv9qkxdawL' self.maxDiff = None self._username = 'user' self._password = 'pencil' - - self.auth = '<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="SCRAM-SHA-1">%s</auth>' % b64encode('n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL') - self.challenge = b64encode('r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=4096') - self.response = '<response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">%s</response>' % b64encode('c=biws,r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,p=v0X8v3Bz2T0CJGbJQyF0X+HI4Ts=') - self.success = b64encode('v=rmF9pqV8S7suAoZWja4dJRkFsKQ=') + self._mechanism = SCRAM_SHA_1(self._username, self._password, None) + self._mechanism._client_nonce = 'fyko+d2lbbFgONRv9qkxdawL' def test_auth(self): - self._method.initiate(self._username, self._password) - self.assertEqual(self.auth, str(self.con.send_nonza.call_args[0][0])) + initial = b64encode('n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL') + data = self._mechanism.get_initiate_data() + self.assertEqual(data, initial) + + challenge = b64encode('r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=4096') + data = self._mechanism.get_response_data(challenge) - self._method.response(self.challenge) - self.assertEqual(self.response, str(self.con.send_nonza.call_args[0][0])) + response = b64encode('c=biws,r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,p=v0X8v3Bz2T0CJGbJQyF0X+HI4Ts=') + self.assertEqual(data, response) - self._method.success(self.success) + success = b64encode('v=rmF9pqV8S7suAoZWja4dJRkFsKQ=') + self._mechanism.validate_success_data(success) if __name__ == '__main__': View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/compare/85120e7ccc04e835312b604…
-- View it on GitLab:
https://dev.gajim.org/gajim/python-nbxmpp/-/compare/85120e7ccc04e835312b604…
You're receiving this email because of your account on
dev.gajim.org
.
1
0
0
0
← Newer
1
...
108
109
110
111
112
113
114
...
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