|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# BSD 2-Clause License |
| 3 | +# |
| 4 | +# Apprise - Push Notification Library. |
| 5 | +# Copyright (c) 2024, Chris Caron <[email protected]> |
| 6 | +# |
| 7 | +# Redistribution and use in source and binary forms, with or without |
| 8 | +# modification, are permitted provided that the following conditions are met: |
| 9 | +# |
| 10 | +# 1. Redistributions of source code must retain the above copyright notice, |
| 11 | +# this list of conditions and the following disclaimer. |
| 12 | +# |
| 13 | +# 2. Redistributions in binary form must reproduce the above copyright notice, |
| 14 | +# this list of conditions and the following disclaimer in the documentation |
| 15 | +# and/or other materials provided with the distribution. |
| 16 | +# |
| 17 | +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 18 | +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 19 | +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 20 | +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |
| 21 | +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 22 | +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 23 | +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 24 | +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 25 | +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 26 | +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 27 | +# POSSIBILITY OF SUCH DAMAGE. |
| 28 | +# Create an account https://www.seven.io if you don't already have one |
| 29 | +# |
| 30 | +# Get your (apikey) from here: |
| 31 | +# - https://help.seven.io/en/api-key-access |
| 32 | +# |
| 33 | +import requests |
| 34 | +import json |
| 35 | +from .base import NotifyBase |
| 36 | +from ..common import NotifyType |
| 37 | +from ..utils import is_phone_no |
| 38 | +from ..utils import parse_phone_no |
| 39 | +from ..locale import gettext_lazy as _ |
| 40 | + |
| 41 | + |
| 42 | +class NotifySeven(NotifyBase): |
| 43 | + """ |
| 44 | + A wrapper for seven Notifications |
| 45 | + """ |
| 46 | + |
| 47 | + # The default descriptive name associated with the Notification |
| 48 | + service_name = 'seven' |
| 49 | + |
| 50 | + # The services URL |
| 51 | + service_url = 'https://www.seven.io' |
| 52 | + |
| 53 | + # The default protocol |
| 54 | + secure_protocol = 'seven' |
| 55 | + |
| 56 | + # A URL that takes you to the setup/help of the specific protocol |
| 57 | + setup_url = 'https://github.com/caronc/apprise/wiki/Notify_seven' |
| 58 | + |
| 59 | + # Seven uses the http protocol with JSON requests |
| 60 | + notify_url = 'https://gateway.seven.io/api/sms' |
| 61 | + |
| 62 | + # The maximum length of the body |
| 63 | + body_maxlen = 160 |
| 64 | + |
| 65 | + # A title can not be used for SMS Messages. Setting this to zero will |
| 66 | + # cause any title (if defined) to get placed into the message body. |
| 67 | + title_maxlen = 0 |
| 68 | + |
| 69 | + # Define object templates |
| 70 | + templates = ( |
| 71 | + '{schema}://{apikey}/{targets}', |
| 72 | + ) |
| 73 | + |
| 74 | + # Define our template tokens |
| 75 | + template_tokens = dict(NotifyBase.template_tokens, **{ |
| 76 | + 'apikey': { |
| 77 | + 'name': _('API Key'), |
| 78 | + 'type': 'string', |
| 79 | + 'required': True, |
| 80 | + 'private': True, |
| 81 | + }, |
| 82 | + 'target_phone': { |
| 83 | + 'name': _('Target Phone No'), |
| 84 | + 'type': 'string', |
| 85 | + 'prefix': '+', |
| 86 | + 'regex': (r'^[0-9\s)(+-]+$', 'i'), |
| 87 | + 'map_to': 'targets', |
| 88 | + }, |
| 89 | + 'targets': { |
| 90 | + 'name': _('Targets'), |
| 91 | + 'type': 'list:string', |
| 92 | + } |
| 93 | + }) |
| 94 | + |
| 95 | + # Define our template arguments |
| 96 | + template_args = dict(NotifyBase.template_args, **{ |
| 97 | + 'to': { |
| 98 | + 'alias_of': 'targets', |
| 99 | + }, |
| 100 | + }) |
| 101 | + |
| 102 | + def __init__(self, apikey, targets=None, **kwargs): |
| 103 | + """ |
| 104 | + Initialize Seven Object |
| 105 | + """ |
| 106 | + super().__init__(**kwargs) |
| 107 | + # API Key (associated with project) |
| 108 | + self.apikey = apikey |
| 109 | + if not self.apikey: |
| 110 | + msg = 'An invalid seven API Key ' \ |
| 111 | + '({}) was specified.'.format(apikey) |
| 112 | + self.logger.warning(msg) |
| 113 | + raise TypeError(msg) |
| 114 | + |
| 115 | + # Parse our targets |
| 116 | + self.targets = list() |
| 117 | + |
| 118 | + for target in parse_phone_no(targets): |
| 119 | + # Validate targets and drop bad ones: |
| 120 | + result = is_phone_no(target) |
| 121 | + if not result: |
| 122 | + self.logger.warning( |
| 123 | + 'Dropped invalid phone # ' |
| 124 | + '({}) specified.'.format(target), |
| 125 | + ) |
| 126 | + continue |
| 127 | + # store valid phone number |
| 128 | + self.targets.append(result['full']) |
| 129 | + return |
| 130 | + |
| 131 | + @property |
| 132 | + def url_identifier(self): |
| 133 | + """ |
| 134 | + Returns all of the identifiers that make this URL unique from |
| 135 | + another simliar one. Targets or end points should never be identified |
| 136 | + here. |
| 137 | + """ |
| 138 | + return (self.secure_protocol, self.apikey) |
| 139 | + |
| 140 | + def send(self, body, title='', notify_type=NotifyType.INFO, **kwargs): |
| 141 | + """ |
| 142 | + Perform seven Notification |
| 143 | + """ |
| 144 | + |
| 145 | + if len(self.targets) == 0: |
| 146 | + # There were no services to notify |
| 147 | + self.logger.warning('There were no seven targets to notify.') |
| 148 | + return False |
| 149 | + |
| 150 | + # error tracking (used for function return) |
| 151 | + has_error = False |
| 152 | + |
| 153 | + # Prepare our headers |
| 154 | + headers = { |
| 155 | + 'Accept': 'application/json', |
| 156 | + 'Content-Type': 'application/json', |
| 157 | + 'SentWith': 'Apprise', |
| 158 | + 'X-Api-Key': self.apikey, |
| 159 | + } |
| 160 | + |
| 161 | + # Prepare our payload |
| 162 | + payload = { |
| 163 | + 'to': None, |
| 164 | + 'text': body, |
| 165 | + } |
| 166 | + # Create a copy of the targets list |
| 167 | + targets = list(self.targets) |
| 168 | + while len(targets): |
| 169 | + # Get our target to notify |
| 170 | + target = targets.pop(0) |
| 171 | + # Prepare our user |
| 172 | + payload['to'] = '+{}'.format(target) |
| 173 | + # Some Debug Logging |
| 174 | + self.logger.debug( |
| 175 | + 'seven POST URL: {} (cert_verify={})'.format( |
| 176 | + self.notify_url, self.verify_certificate)) |
| 177 | + self.logger.debug('seven Payload: {}' .format(payload)) |
| 178 | + # Always call throttle before any remote server i/o is made |
| 179 | + self.throttle() |
| 180 | + try: |
| 181 | + r = requests.post( |
| 182 | + self.notify_url, |
| 183 | + data=json.dumps(payload), |
| 184 | + headers=headers, |
| 185 | + verify=self.verify_certificate, |
| 186 | + timeout=self.request_timeout, |
| 187 | + ) |
| 188 | + # Sample output of a successful transmission |
| 189 | + # { |
| 190 | + # "success": "100", |
| 191 | + # "total_price": 0.075, |
| 192 | + # "balance": 46.748, |
| 193 | + # "debug": "false", |
| 194 | + # "sms_type": "direct", |
| 195 | + # "messages": [ |
| 196 | + # { |
| 197 | + # "id": "77229135982", |
| 198 | + # "sender": "492022839080", |
| 199 | + # "recipient": "4917661254799", |
| 200 | + # "text": "x", |
| 201 | + # "encoding": "gsm", |
| 202 | + # "label": null, |
| 203 | + # "parts": 1, |
| 204 | + # "udh": null, |
| 205 | + # "is_binary": false, |
| 206 | + # "price": 0.075, |
| 207 | + # "success": true, |
| 208 | + # "error": null, |
| 209 | + # "error_text": null |
| 210 | + # } |
| 211 | + # ] |
| 212 | + # } |
| 213 | + if r.status_code not in ( |
| 214 | + requests.codes.ok, requests.codes.created): |
| 215 | + # We had a problem |
| 216 | + status_str = \ |
| 217 | + NotifySeven.http_response_code_lookup( |
| 218 | + r.status_code) |
| 219 | + self.logger.warning( |
| 220 | + 'Failed to send seven notification to {}: ' |
| 221 | + '{}{}error={}.'.format( |
| 222 | + ','.join(target), |
| 223 | + status_str, |
| 224 | + ', ' if status_str else '', |
| 225 | + r.status_code)) |
| 226 | + self.logger.debug( |
| 227 | + 'Response Details:\r\n{}'.format(r.content)) |
| 228 | + # Mark our failure |
| 229 | + has_error = True |
| 230 | + continue |
| 231 | + else: |
| 232 | + self.logger.info( |
| 233 | + 'Sent seven notification to {}.'.format(target)) |
| 234 | + except requests.RequestException as e: |
| 235 | + self.logger.warning( |
| 236 | + 'A Connection error occurred sending seven:%s ' % ( |
| 237 | + target) + 'notification.' |
| 238 | + ) |
| 239 | + self.logger.debug('Socket Exception: %s' % str(e)) |
| 240 | + # Mark our failure |
| 241 | + has_error = True |
| 242 | + continue |
| 243 | + return not has_error |
| 244 | + |
| 245 | + def url(self, privacy=False, *args, **kwargs): |
| 246 | + """ |
| 247 | + Returns the URL built dynamically based on specified arguments. |
| 248 | + """ |
| 249 | + |
| 250 | + # Our URL parameters |
| 251 | + params = self.url_parameters(privacy=privacy, *args, **kwargs) |
| 252 | + return '{schema}://{apikey}/{targets}/?{params}'.format( |
| 253 | + schema=self.secure_protocol, |
| 254 | + apikey=self.pprint(self.apikey, privacy, safe=''), |
| 255 | + targets='/'.join( |
| 256 | + [NotifySeven.quote(x, safe='') for x in self.targets]), |
| 257 | + params=NotifySeven.urlencode(params)) |
| 258 | + |
| 259 | + def __len__(self): |
| 260 | + """ |
| 261 | + Returns the number of targets associated with this notification |
| 262 | + """ |
| 263 | + targets = len(self.targets) |
| 264 | + return targets if targets > 0 else 1 |
| 265 | + |
| 266 | + @staticmethod |
| 267 | + def parse_url(url): |
| 268 | + """ |
| 269 | + Parses the URL and returns enough arguments that can allow |
| 270 | + us to re-instantiate this object. |
| 271 | + """ |
| 272 | + |
| 273 | + results = NotifyBase.parse_url(url, verify_host=False) |
| 274 | + if not results: |
| 275 | + # We're done early as we couldn't load the results |
| 276 | + return results |
| 277 | + |
| 278 | + # Get our entries; split_path() looks after unquoting content for us |
| 279 | + # by default |
| 280 | + results['targets'] = NotifySeven.split_path(results['fullpath']) |
| 281 | + |
| 282 | + # The hostname is our authentication key |
| 283 | + results['apikey'] = NotifySeven.unquote(results['host']) |
| 284 | + |
| 285 | + # Support the 'to' variable so that we can support targets this way too |
| 286 | + # The 'to' makes it easier to use yaml configuration |
| 287 | + if 'to' in results['qsd'] and len(results['qsd']['to']): |
| 288 | + results['targets'] += \ |
| 289 | + NotifySeven.parse_phone_no(results['qsd']['to']) |
| 290 | + |
| 291 | + return results |
0 commit comments