Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Matrix Notice Message Types #460

Merged
merged 1 commit into from
Oct 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 40 additions & 4 deletions apprise/plugins/NotifyMatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,21 @@
r'(?P<home_server>[a-z0-9.-]+))?\s*$', re.I)


class MatrixMessageType(object):
"""
The Matrix Message types
"""
TEXT = "text"
NOTICE = "notice"


# matrix message types are placed into this list for validation purposes
MATRIX_MESSAGE_TYPES = (
MatrixMessageType.TEXT,
MatrixMessageType.NOTICE,
)


class MatrixWebhookMode(object):
# Webhook Mode is disabled
DISABLED = "off"
Expand All @@ -81,7 +96,7 @@ class MatrixWebhookMode(object):
T2BOT = "t2bot"


# webhook modes are placed ito this list for validation purposes
# webhook modes are placed into this list for validation purposes
MATRIX_WEBHOOK_MODES = (
MatrixWebhookMode.DISABLED,
MatrixWebhookMode.MATRIX,
Expand Down Expand Up @@ -206,6 +221,12 @@ class NotifyMatrix(NotifyBase):
'values': MATRIX_WEBHOOK_MODES,
'default': MatrixWebhookMode.DISABLED,
},
'msgtype': {
'name': _('Message Type'),
'type': 'choice:string',
'values': MATRIX_MESSAGE_TYPES,
'default': MatrixMessageType.TEXT,
},
'to': {
'alias_of': 'targets',
},
Expand All @@ -214,7 +235,8 @@ class NotifyMatrix(NotifyBase):
},
})

def __init__(self, targets=None, mode=None, include_image=False, **kwargs):
def __init__(self, targets=None, mode=None, msgtype=None,
include_image=False, **kwargs):
"""
Initialize Matrix Object
"""
Expand All @@ -240,13 +262,21 @@ def __init__(self, targets=None, mode=None, include_image=False, **kwargs):
self._room_cache = {}

# Setup our mode
self.mode = MatrixWebhookMode.DISABLED \
self.mode = self.template_args['mode']['default'] \
if not isinstance(mode, six.string_types) else mode.lower()
if self.mode and self.mode not in MATRIX_WEBHOOK_MODES:
msg = 'The mode specified ({}) is invalid.'.format(mode)
self.logger.warning(msg)
raise TypeError(msg)

# Setup our message type
self.msgtype = self.template_args['msgtype']['default'] \
if not isinstance(msgtype, six.string_types) else msgtype.lower()
if self.msgtype and self.msgtype not in MATRIX_MESSAGE_TYPES:
caronc marked this conversation as resolved.
Show resolved Hide resolved
msg = 'The msgtype specified ({}) is invalid.'.format(msgtype)
self.logger.warning(msg)
raise TypeError(msg)

if self.mode == MatrixWebhookMode.T2BOT:
# t2bot configuration requires that a webhook id is specified
self.access_token = validate_regex(
Expand Down Expand Up @@ -534,7 +564,7 @@ def _send_server_notification(self, body, title='',

# Define our payload
payload = {
'msgtype': 'm.text',
'msgtype': 'm.{}'.format(self.msgtype),
'body': '{title}{body}'.format(
title='' if not title else '{}\r\n'.format(title),
body=body),
Expand Down Expand Up @@ -1109,6 +1139,7 @@ def url(self, privacy=False, *args, **kwargs):
params = {
'image': 'yes' if self.include_image else 'no',
'mode': self.mode,
'msgtype': self.msgtype,
}

# Extend our parameters
Expand Down Expand Up @@ -1189,6 +1220,11 @@ def parse_url(url):
# unquote our hostname and pass it in as the password/token
results['password'] = NotifyMatrix.unquote(results['host'])

# Support the message type keyword
if 'msgtype' in results['qsd'] and len(results['qsd']['msgtype']):
results['msgtype'] = \
NotifyMatrix.unquote(results['qsd']['msgtype'])

# Support the use of the token= keyword
if 'token' in results['qsd'] and len(results['qsd']['token']):
results['password'] = NotifyMatrix.unquote(results['qsd']['token'])
Expand Down
16 changes: 16 additions & 0 deletions test/test_matrix_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import six
import mock
import requests
import pytest
from apprise import plugins
from apprise import AppriseAsset
from json import dumps
Expand Down Expand Up @@ -110,6 +111,21 @@ def test_notify_matrix_plugin_general(mock_post, mock_get):
obj.send(body="test") is True
obj.send(title="title", body="test") is True

# Test notice type notifications
kwargs = plugins.NotifyMatrix.parse_url(
'matrix://user:passwd@hostname/#abcd?msgtype=notice')
obj = plugins.NotifyMatrix(**kwargs)
assert isinstance(obj.url(), six.string_types) is True
assert isinstance(obj, plugins.NotifyMatrix) is True
obj.send(body="test") is True
obj.send(title="title", body="test") is True

with pytest.raises(TypeError):
# invalid message type specified
kwargs = plugins.NotifyMatrix.parse_url(
'matrix://user:passwd@hostname/#abcd?msgtype=invalid')
obj = plugins.NotifyMatrix(**kwargs)

# Force a failed login
ro = response_obj.copy()
del ro['access_token']
Expand Down