Added Synology Chat support (#944)

This commit is contained in:
Chris Caron 2023-11-19 12:07:27 -05:00 committed by GitHub
parent ccb97bc92e
commit a25ff00b9d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 517 additions and 3 deletions

View File

@ -85,6 +85,7 @@ SparkPost
Spontit Spontit
Streamlabs Streamlabs
Stride Stride
Synology Chat
Syslog Syslog
Techulus Techulus
Telegram Telegram

View File

@ -120,6 +120,7 @@ The table below identifies the services this tool supports and some example serv
| [Streamlabs](https://github.com/caronc/apprise/wiki/Notify_streamlabs) | strmlabs:// | (TCP) 443 | strmlabs://AccessToken/<br/>strmlabs://AccessToken/?name=name&identifier=identifier&amount=0&currency=USD | [Streamlabs](https://github.com/caronc/apprise/wiki/Notify_streamlabs) | strmlabs:// | (TCP) 443 | strmlabs://AccessToken/<br/>strmlabs://AccessToken/?name=name&identifier=identifier&amount=0&currency=USD
| [SparkPost](https://github.com/caronc/apprise/wiki/Notify_sparkpost) | sparkpost:// | (TCP) 443 | sparkpost://user@hostname/apikey<br />sparkpost://user@hostname/apikey/email<br />sparkpost://user@hostname/apikey/email1/email2/emailN<br />sparkpost://user@hostname/apikey/?name="From%20User" | [SparkPost](https://github.com/caronc/apprise/wiki/Notify_sparkpost) | sparkpost:// | (TCP) 443 | sparkpost://user@hostname/apikey<br />sparkpost://user@hostname/apikey/email<br />sparkpost://user@hostname/apikey/email1/email2/emailN<br />sparkpost://user@hostname/apikey/?name="From%20User"
| [Spontit](https://github.com/caronc/apprise/wiki/Notify_spontit) | spontit:// | (TCP) 443 | spontit://UserID@APIKey/<br />spontit://UserID@APIKey/Channel<br />spontit://UserID@APIKey/Channel1/Channel2/ChannelN | [Spontit](https://github.com/caronc/apprise/wiki/Notify_spontit) | spontit:// | (TCP) 443 | spontit://UserID@APIKey/<br />spontit://UserID@APIKey/Channel<br />spontit://UserID@APIKey/Channel1/Channel2/ChannelN
| [Synology Chat](https://github.com/caronc/apprise/wiki/Notify_synology_chat) | synology:// or synologys:// | (TCP) 80 or 443 | synology://hostname/token<br />synology://hostname:port/token
| [Syslog](https://github.com/caronc/apprise/wiki/Notify_syslog) | syslog:// | n/a | syslog://<br />syslog://Facility | [Syslog](https://github.com/caronc/apprise/wiki/Notify_syslog) | syslog:// | n/a | syslog://<br />syslog://Facility
| [Telegram](https://github.com/caronc/apprise/wiki/Notify_telegram) | tgram:// | (TCP) 443 | tgram://bottoken/ChatID<br />tgram://bottoken/ChatID1/ChatID2/ChatIDN | [Telegram](https://github.com/caronc/apprise/wiki/Notify_telegram) | tgram:// | (TCP) 443 | tgram://bottoken/ChatID<br />tgram://bottoken/ChatID1/ChatID2/ChatIDN
| [Twitter](https://github.com/caronc/apprise/wiki/Notify_twitter) | twitter:// | (TCP) 443 | twitter://CKey/CSecret/AKey/ASecret<br/>twitter://user@CKey/CSecret/AKey/ASecret<br/>twitter://CKey/CSecret/AKey/ASecret/User1/User2/User2<br/>twitter://CKey/CSecret/AKey/ASecret?mode=tweet | [Twitter](https://github.com/caronc/apprise/wiki/Notify_twitter) | twitter:// | (TCP) 443 | twitter://CKey/CSecret/AKey/ASecret<br/>twitter://user@CKey/CSecret/AKey/ASecret<br/>twitter://CKey/CSecret/AKey/ASecret/User1/User2/User2<br/>twitter://CKey/CSecret/AKey/ASecret?mode=tweet

View File

@ -0,0 +1,338 @@
# -*- coding: utf-8 -*-
# BSD 2-Clause License
#
# Apprise - Push Notification Library.
# Copyright (c) 2023, Chris Caron <lead2gold@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import requests
from json import dumps
from .NotifyBase import NotifyBase
from ..URLBase import PrivacyMode
from ..common import NotifyType
from ..AppriseLocale import gettext_lazy as _
# For API Details see:
# https://kb.synology.com/en-au/DSM/help/Chat/chat_integration
class NotifySynology(NotifyBase):
"""
A wrapper for Synology Chat Notifications
"""
# The default descriptive name associated with the Notification
service_name = 'Synology Chat'
# The services URL
service_url = 'https://www.synology.com/'
# The default protocol
protocol = 'synology'
# The default secure protocol
secure_protocol = 'synologys'
# A URL that takes you to the setup/help of the specific protocol
setup_url = 'https://github.com/caronc/apprise/wiki/Notify_synology_chat'
# Title is to be part of body
title_maxlen = 0
# Disable throttle rate for Synology requests since they are normally
# local anyway
request_rate_per_sec = 0
# Define object templates
templates = (
'{schema}://{host}/{token}',
'{schema}://{host}:{port}/{token}',
'{schema}://{user}@{host}/{token}',
'{schema}://{user}@{host}:{port}/{token}',
'{schema}://{user}:{password}@{host}/{token}',
'{schema}://{user}:{password}@{host}:{port}/{token}',
)
# Define our tokens; these are the minimum tokens required required to
# be passed into this function (as arguments). The syntax appends any
# previously defined in the base package and builds onto them
template_tokens = dict(NotifyBase.template_tokens, **{
'host': {
'name': _('Hostname'),
'type': 'string',
'required': True,
},
'port': {
'name': _('Port'),
'type': 'int',
'min': 1,
'max': 65535,
},
'user': {
'name': _('Username'),
'type': 'string',
},
'password': {
'name': _('Password'),
'type': 'string',
'private': True,
},
'token': {
'name': _('Token'),
'type': 'string',
'required': True,
'private': True,
},
})
# Define our template arguments
template_args = dict(NotifyBase.template_args, **{
'file_url': {
'name': _('Upload'),
'type': 'string',
},
'token': {
'alias_of': 'token',
},
})
# Define any kwargs we're using
template_kwargs = {
'headers': {
'name': _('HTTP Header'),
'prefix': '+',
},
}
def __init__(self, token=None, headers=None, file_url=None, **kwargs):
"""
Initialize Synology Chat Object
headers can be a dictionary of key/value pairs that you want to
additionally include as part of the server headers to post with
"""
super().__init__(**kwargs)
self.token = token
if not self.token:
msg = 'An invalid Synology Token ' \
'({}) was specified.'.format(token)
self.logger.warning(msg)
raise TypeError(msg)
self.fullpath = kwargs.get('fullpath')
# A URL to an attachment you want to upload (must be less then 32MB
# Acording to API details (at the time of writing plugin)
self.file_url = file_url
self.headers = {}
if headers:
# Store our extra headers
self.headers.update(headers)
return
def url(self, privacy=False, *args, **kwargs):
"""
Returns the URL built dynamically based on specified arguments.
"""
# Define any URL parameters
params = {}
if self.file_url:
params['file_url'] = self.file_url
# Extend our parameters
params.update(self.url_parameters(privacy=privacy, *args, **kwargs))
# Append our headers into our parameters
params.update({'+{}'.format(k): v for k, v in self.headers.items()})
# Determine Authentication
auth = ''
if self.user and self.password:
auth = '{user}:{password}@'.format(
user=NotifySynology.quote(self.user, safe=''),
password=self.pprint(
self.password, privacy, mode=PrivacyMode.Secret, safe=''),
)
elif self.user:
auth = '{user}@'.format(
user=NotifySynology.quote(self.user, safe=''),
)
default_port = 443 if self.secure else 80
return '{schema}://{auth}{hostname}{port}/{token}' \
'{fullpath}?{params}'.format(
schema=self.secure_protocol if self.secure else self.protocol,
auth=auth,
# never encode hostname since we're expecting it to be a valid
# one
hostname=self.host,
port='' if self.port is None or self.port == default_port
else ':{}'.format(self.port),
token=self.pprint(self.token, privacy, safe=''),
fullpath=NotifySynology.quote(self.fullpath, safe='/')
if self.fullpath else '/',
params=NotifySynology.urlencode(params),
)
def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs):
"""
Perform Synology Chat Notification
"""
# Prepare HTTP Headers
headers = {
'User-Agent': self.app_id,
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*',
}
# Apply any/all header over-rides defined
headers.update(self.headers)
# prepare Synology Object
payload = {
'text': body,
}
if self.file_url:
payload['file_url'] = self.file_url
# Prepare our parameters
params = {
'api': 'SYNO.Chat.External',
'method': 'incoming',
'version': 2,
'token': self.token,
}
auth = None
if self.user:
auth = (self.user, self.password)
# Set our schema
schema = 'https' if self.secure else 'http'
url = '%s://%s' % (schema, self.host)
if isinstance(self.port, int):
url += ':%d' % self.port
# Prepare our Synology API URL
url += self.fullpath + '/webapi/entry.cgi'
self.logger.debug('Synology Chat POST URL: %s (cert_verify=%r)' % (
url, self.verify_certificate,
))
self.logger.debug('Synology Chat Payload: %s' % str(payload))
# Always call throttle before any remote server i/o is made
self.throttle()
try:
r = requests.post(
url,
data=f"payload={dumps(payload)}",
params=params,
headers=headers,
auth=auth,
verify=self.verify_certificate,
timeout=self.request_timeout,
)
if r.status_code < 200 or r.status_code >= 300:
# We had a problem
status_str = \
NotifySynology.http_response_code_lookup(r.status_code)
self.logger.warning(
'Failed to send Synology Chat %s notification: '
'%serror=%s.',
status_str,
', ' if status_str else '',
str(r.status_code))
self.logger.debug('Response Details:\r\n{}'.format(r.content))
# Return; we're done
return False
else:
self.logger.info('Sent Synology Chat notification.')
except requests.RequestException as e:
self.logger.warning(
'A Connection error occurred sending Synology '
'Chat notification to %s.' % self.host)
self.logger.debug('Socket Exception: %s' % str(e))
# Return; we're done
return False
return True
@staticmethod
def parse_url(url):
"""
Parses the URL and returns enough arguments that can allow
us to re-instantiate this object.
"""
results = NotifyBase.parse_url(url)
if not results:
# We're done early as we couldn't load the results
return results
# Add our headers that the user can potentially over-ride if they wish
# to to our returned result set and tidy entries by unquoting them
results['headers'] = {
NotifySynology.unquote(x): NotifySynology.unquote(y)
for x, y in results['qsd+'].items()}
# Set our token if found as an argument
if 'token' in results['qsd'] and len(results['qsd']['token']):
results['token'] = NotifySynology.unquote(results['qsd']['token'])
else:
# Get unquoted entries
entries = NotifySynology.split_path(results['fullpath'])
if entries:
# Pop the first element
results['token'] = entries.pop(0)
# Update our fullpath to not include our token
results['fullpath'] = \
results['fullpath'][len(results['token']) + 1:]
# Set upload/file_url if not otherwise set
if 'file_url' in results['qsd'] and len(results['qsd']['file_url']):
results['file_url'] = \
NotifySynology.unquote(results['qsd']['file_url'])
return results

View File

@ -1,4 +1,4 @@
# BSD 2-Clause License # BSD 3-Clause License
# #
# Apprise - Push Notification Library. # Apprise - Push Notification Library.
# Copyright (c) 2023, Chris Caron <lead2gold@gmail.com> # Copyright (c) 2023, Chris Caron <lead2gold@gmail.com>
@ -49,8 +49,8 @@ OneSignal, Opsgenie, PagerDuty, PagerTree, ParsePlatform, PopcornNotify,
Prowl, Pushalot, PushBullet, Pushjet, PushMe, Pushover, PushSafer, Pushy, Prowl, Pushalot, PushBullet, Pushjet, PushMe, Pushover, PushSafer, Pushy,
PushDeer, Reddit, Rocket.Chat, RSyslog, SendGrid, ServerChan, Signal, PushDeer, Reddit, Rocket.Chat, RSyslog, SendGrid, ServerChan, Signal,
SimplePush, Sinch, Slack, SMSEagle, SMTP2Go, Spontit, SparkPost, Super Toasty, SimplePush, Sinch, Slack, SMSEagle, SMTP2Go, Spontit, SparkPost, Super Toasty,
Streamlabs, Stride, Syslog, Techulus Push, Telegram, Threema Gateway, Twilio, Streamlabs, Stride, Synology Chat, Syslog, Techulus Push, Telegram, Threema
Twitter, Twist, XBMC, Voipms, Vonage, WhatsApp, Webex Teams} Gateway, Twilio, Twitter, Twist, XBMC, Voipms, Vonage, WhatsApp, Webex Teams}
Name: python-%{pypi_name} Name: python-%{pypi_name}
Version: 1.6.0 Version: 1.6.0

View File

@ -0,0 +1,174 @@
# -*- coding: utf-8 -*-
# BSD 2-Clause License
#
# Apprise - Push Notification Library.
# Copyright (c) 2023, Chris Caron <lead2gold@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import requests
from unittest import mock
from apprise.plugins.NotifySynology import NotifySynology
from helpers import AppriseURLTester
# Disable logging for a cleaner testing output
import logging
logging.disable(logging.CRITICAL)
# Our Testing URLs
apprise_url_tests = (
('synology://:@/', {
'instance': None,
}),
('synology://', {
'instance': None,
}),
('synologys://', {
'instance': None,
}),
('synology://localhost/token', {
'instance': NotifySynology,
}),
('synology://localhost/token?file_url=http://reddit.com/test.jpg', {
'instance': NotifySynology,
}),
('synology://user:pass@localhost/token', {
'instance': NotifySynology,
# Our expected url(privacy=True) startswith() response:
'privacy_url': 'synology://user:****@localhost/t...n',
}),
# No token was specified
('synology://user@localhost', {
'instance': TypeError,
}),
('synology://user@localhost/token', {
'instance': NotifySynology,
}),
# Continue testing other cases
('synology://localhost:8080/token', {
'instance': NotifySynology,
}),
('synology://user:pass@localhost:8080/token', {
'instance': NotifySynology,
}),
('synologys://localhost/token', {
'instance': NotifySynology,
}),
('synologys://localhost/?token=mytoken', {
'instance': NotifySynology,
# Our expected url(privacy=True) startswith() response:
'privacy_url': 'synologys://localhost/m...n',
}),
('synologys://user:pass@localhost/token', {
'instance': NotifySynology,
}),
('synologys://localhost:8080/token/path/', {
'instance': NotifySynology,
# Our expected url(privacy=True) startswith() response:
'privacy_url': 'synologys://localhost:8080/t...n/path/',
}),
('synologys://user:password@localhost:8080/token', {
'instance': NotifySynology,
# Our expected url(privacy=True) startswith() response:
'privacy_url': 'synologys://user:****@localhost:8080/t...n',
}),
# Test our Headers
('synology://localhost:8080/path?+HeaderKey=HeaderValue', {
'instance': NotifySynology,
}),
('synology://user:pass@localhost:8081/token', {
'instance': NotifySynology,
# force a failure
'response': False,
'requests_response_code': requests.codes.internal_server_error,
}),
('synology://user:pass@localhost:8082/token', {
'instance': NotifySynology,
# throw a bizzare code forcing us to fail to look it up
'response': False,
'requests_response_code': 999,
}),
('synology://user:pass@localhost:8083/token', {
'instance': NotifySynology,
# Throws a series of connection and transfer exceptions when this flag
# is set and tests that we gracfully handle them
'test_requests_exceptions': True,
}),
)
def test_plugin_custom_synology_urls():
"""
NotifySynology() Apprise URLs
"""
# Run our general tests
AppriseURLTester(tests=apprise_url_tests).run_all()
@mock.patch('requests.post')
def test_plugin_synology_edge_cases(mock_post):
"""
NotifySynology() Edge Cases
"""
# Prepare our response
response = requests.Request()
response.status_code = requests.codes.ok
# Prepare Mock
mock_post.return_value = response
# This string also tests that type is set to nothing
results = NotifySynology.parse_url(
'synology://user:pass@localhost:8080/token')
assert isinstance(results, dict)
assert results['user'] == 'user'
assert results['password'] == 'pass'
assert results['port'] == 8080
assert results['host'] == 'localhost'
assert results['fullpath'] == ''
assert results['path'] == '/'
assert results['query'] == 'token'
assert results['schema'] == 'synology'
assert results['url'] == 'synology://user:pass@localhost:8080/token'
instance = NotifySynology(**results)
assert isinstance(instance, NotifySynology)
response = instance.send(title='title', body='body')
assert response is True
assert mock_post.call_count == 1
details = mock_post.call_args_list[0]
assert details[0][0] == 'http://localhost:8080/webapi/entry.cgi'
assert details[1]['data'].startswith('payload=')