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
|
# -*- coding: utf-8 -*-
# BSD 2-Clause License
#
# Apprise - Push Notification Library.
# Copyright (c) 2024, 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.
#
# To use this plugin, you need to be a licensed ham radio operator
#
# Plugin constraints:
#
# - message length = 67 chars max.
# - message content = ASCII 7 bit
# - APRS messages will be sent without msg ID, meaning that
# ham radio operators cannot acknowledge them
# - Bring your own APRS-IS passcode. If you don't know what
# this is or how to get it, then this plugin is not for you
# - Do NOT change the Device/ToCall ID setting UNLESS this
# module is used outside of Apprise. This identifier helps
# the ham radio community with determining the software behind
# a given APRS message.
# - With great (ham radio) power comes great responsibility; do
# not use this plugin for spamming other ham radio operators
#
# In order to digest text input which is not in plain English,
# users can install the optional 'unidecode' package as part
# of their venv environment. Details: see plugin description
#
#
# You're done at this point, you only need to know your user/pass that
# you signed up with.
# The following URLs would be accepted by Apprise:
# - aprs://{user}:{password}@{callsign}
# - aprs://{user}:{password}@{callsign1}/{callsign2}
# Optional parameters:
# - locale --> APRS-IS target server to connect with
# Default: EURO --> 'euro.aprs2.net'
# Details: https://www.aprs2.net/
#
# APRS message format specification:
# http://www.aprs.org/doc/APRS101.PDF
#
import socket
import sys
from itertools import chain
from .base import NotifyBase
from ..locale import gettext_lazy as _
from ..url import PrivacyMode
from ..common import NotifyType
from ..utils import is_call_sign
from ..utils import parse_call_sign
from .. import __version__
import re
# Fixed APRS-IS server locales
# Default is 'EURO'
# See https://www.aprs2.net/ for details
# Select the rotating server in case you
# don"t care about a specific locale
APRS_LOCALES = {
"NOAM": "noam.aprs2.net",
"SOAM": "soam.aprs2.net",
"EURO": "euro.aprs2.net",
"ASIA": "asia.aprs2.net",
"AUNZ": "aunz.aprs2.net",
"ROTA": "rotate.aprs2.net",
}
# Identify all unsupported characters
APRS_BAD_CHARMAP = {
r"Ä": "Ae",
r"Ö": "Oe",
r"Ü": "Ue",
r"ä": "ae",
r"ö": "oe",
r"ü": "ue",
r"ß": "ss",
}
# Our compiled mapping of bad characters
APRS_COMPILED_MAP = re.compile(
r'(' + '|'.join(APRS_BAD_CHARMAP.keys()) + r')')
class NotifyAprs(NotifyBase):
"""
A wrapper for APRS Notifications via APRS-IS
"""
# The default descriptive name associated with the Notification
service_name = "Aprs"
# The services URL
service_url = "https://www.aprs2.net/"
# The default secure protocol
secure_protocol = "aprs"
# A URL that takes you to the setup/help of the specific protocol
setup_url = "https://github.com/caronc/apprise/wiki/Notify_aprs"
# APRS default port, supported by all core servers
# Details: https://www.aprs-is.net/Connecting.aspx
notify_port = 10152
# The maximum length of the APRS message body
body_maxlen = 67
# Apprise APRS Device ID / TOCALL ID
# This is a FIXED value which is associated with this plugin.
# Its value MUST NOT be changed. If you use this APRS plugin
# code OUTSIDE of Apprise, please request your own TOCALL ID.
# Details: see https://github.com/aprsorg/aprs-deviceid
#
# Do NOT use the generic "APRS" TOCALL ID !!!!!
#
device_id = "APPRIS"
# A title can not be used for APRS Messages. Setting this to zero will
# cause any title (if defined) to get placed into the message body.
title_maxlen = 0
# Helps to reduce the number of login-related errors where the
# APRS-IS server "isn't ready yet". If we try to receive the rx buffer
# without this grace perid in place, we may receive "incomplete" responses
# where the login response lacks information. In case you receive too many
# "Rx: APRS-IS msg is too short - needs to have at least two lines" error
# messages, you might want to increase this value to a larger time span
# Per previous experience, do not use values lower than 0.5 (seconds)
request_rate_per_sec = 0.8
# Encoding of retrieved content
aprs_encoding = 'latin-1'
# Define object templates
templates = ("{schema}://{user}:{password}@{targets}",)
# Define our template tokens
template_tokens = dict(
NotifyBase.template_tokens,
**{
"user": {
"name": _("User Name"),
"type": "string",
"required": True,
},
"password": {
"name": _("Password"),
"type": "string",
"private": True,
"required": True,
},
"target_callsign": {
"name": _("Target Callsign"),
"type": "string",
"regex": (
r"^[a-z0-9]{2,5}(-[a-z0-9]{1,2})?$",
"i",
),
"map_to": "targets",
},
"targets": {
"name": _("Targets"),
"type": "list:string",
"required": True,
},
}
)
# Define our template arguments
template_args = dict(
NotifyBase.template_args,
**{
"to": {
"name": _("Target Callsign"),
"type": "string",
"map_to": "targets",
},
"delay": {
"name": _("Resend Delay"),
"type": "float",
"min": 0.0,
"max": 5.0,
"default": 0.0,
},
"locale": {
"name": _("Locale"),
"type": "choice:string",
"values": APRS_LOCALES,
"default": "EURO",
},
}
)
def __init__(self, targets=None, locale=None, delay=None, **kwargs):
"""
Initialize APRS Object
"""
super().__init__(**kwargs)
# Our (future) socket sobject
self.sock = None
# Parse our targets
self.targets = list()
"""
Check if the user has provided credentials
"""
if not (self.user and self.password):
msg = "An APRS user/pass was not provided."
self.logger.warning(msg)
raise TypeError(msg)
"""
Check if the user tries to use a read-only access
to APRS-IS. We need to send content, meaning that
read-only access will not work
"""
if self.password == "-1":
msg = "APRS read-only passwords are not supported."
self.logger.warning(msg)
raise TypeError(msg)
"""
Check if the password is numeric
"""
if not self.password.isnumeric():
msg = "Invalid APRS-IS password"
self.logger.warning(msg)
raise TypeError(msg)
"""
Convert given user name (FROM callsign) and
device ID to to uppercase
"""
self.user = self.user.upper()
self.device_id = self.device_id.upper()
"""
Check if the user has provided a locale for the
APRS-IS-server and validate it, if necessary
"""
if locale:
if locale.upper() not in APRS_LOCALES:
msg = (
"Unsupported APRS-IS server locale. "
"Received: {}. Valid: {}".format(
locale, ", ".join(str(x) for x in APRS_LOCALES.keys())
)
)
self.logger.warning(msg)
raise TypeError(msg)
# Update our delay
if delay is None:
self.delay = NotifyAprs.template_args["delay"]["default"]
else:
try:
self.delay = float(delay)
if self.delay < NotifyAprs.template_args["delay"]["min"]:
raise ValueError()
elif self.delay >= NotifyAprs.template_args["delay"]["max"]:
raise ValueError()
except (TypeError, ValueError):
msg = "Unsupported APRS-IS delay ({}) specified. ".format(
delay)
self.logger.warning(msg)
raise TypeError(msg)
# Bump up our request_rate
self.request_rate_per_sec += self.delay
# Set the transmitter group
self.locale = \
NotifyAprs.template_args["locale"]["default"] \
if not locale else locale.upper()
# Used for URL generation afterwards only
self.invalid_targets = list()
for target in parse_call_sign(targets):
# Validate targets and drop bad ones
# We just need to know if the call sign (including SSID, if
# provided) is valid and can then process the input as is
result = is_call_sign(target)
if not result:
self.logger.warning(
"Dropping invalid Amateur radio call sign ({}).".format(
target
),
)
self.invalid_targets.append(target.upper())
continue
# Store entry
self.targets.append(target.upper())
return
def socket_close(self):
"""
Closes the socket connection whereas present
"""
if self.sock:
try:
self.sock.close()
except Exception:
# No worries if socket exception thrown on close()
pass
self.sock = None
def socket_open(self):
"""
Establishes the connection to the APRS-IS
socket server
"""
self.logger.debug(
"Creating socket connection with APRS-IS {}:{}".format(
APRS_LOCALES[self.locale], self.notify_port
)
)
try:
self.sock = socket.create_connection(
(APRS_LOCALES[self.locale], self.notify_port),
self.socket_connect_timeout,
)
except ConnectionError as e:
self.logger.debug("Socket Exception socket_open: %s", str(e))
self.sock = None
return False
except socket.gaierror as e:
self.logger.debug("Socket Exception socket_open: %s", str(e))
self.sock = None
return False
except socket.timeout as e:
self.logger.debug(
"Socket Timeout Exception socket_open: %s", str(e))
self.sock = None
return False
except Exception as e:
self.logger.debug("General Exception socket_open: %s", str(e))
self.sock = None
return False
# We are connected.
# getpeername() is not supported by every OS. Therefore,
# we MAY receive an exception even though we are
# connected successfully.
try:
# Get the physical host/port of the server
host, port = self.sock.getpeername()
# and create debug info
self.logger.debug("Connected to {}:{}".format(host, port))
except ValueError:
# Seens as if we are running on an operating
# system that does not support getpeername()
# Create a minimal log file entry
self.logger.debug("Connected to APRS-IS")
# Return success
return True
def aprsis_login(self):
"""
Generate the APRS-IS login string, send it to the server
and parse the response
Returns True/False wrt whether the login was successful
"""
self.logger.debug("socket_login: init")
# Check if we are connected
if not self.sock:
self.logger.warning("socket_login: Not connected to APRS-IS")
return False
# APRS-IS login string, see https://www.aprs-is.net/Connecting.aspx
login_str = "user {0} pass {1} vers apprise {2}\r\n".format(
self.user, self.password, __version__
)
# Send the data & abort in case of error
if not self.socket_send(login_str):
self.logger.warning(
"socket_login: Login to APRS-IS unsuccessful,"
" exception occurred"
)
self.socket_close()
return False
rx_buf = self.socket_receive(len(login_str) + 100)
# Abort the remaining process in case an error has occurred
if not rx_buf:
self.logger.warning(
"socket_login: Login to APRS-IS "
"unsuccessful, exception occurred"
)
self.socket_close()
return False
# APRS-IS sends at least two lines of data
# The data that we need is in line #2 so
# let's split the content and see what we have
rx_lines = rx_buf.splitlines()
if len(rx_lines) < 2:
self.logger.warning(
"socket_login: APRS-IS msg is too short"
" - needs to have at least two lines"
)
self.socket_close()
return False
# Now split the 2nd line's content and extract
# both call sign and login status
try:
_, _, callsign, status, _ = rx_lines[1].split(" ", 4)
except ValueError:
# ValueError is returned if there were not enough elements to
# populate the response
self.logger.warning(
"socket_login: " "received invalid response from APRS-IS"
)
self.socket_close()
return False
if callsign != self.user:
self.logger.warning(
"socket_login: " "call signs differ: %s" % callsign
)
self.socket_close()
return False
if status.startswith("unverified"):
self.logger.warning(
"socket_login: "
"invalid APRS-IS password for given call sign"
)
self.socket_close()
return False
# all validations are successful; we are connected
return True
def socket_send(self, tx_data):
"""
Generic "Send data to a socket"
"""
self.logger.debug("socket_send: init")
# Check if we are connected
if not self.sock:
self.logger.warning("socket_send: Not connected to APRS-IS")
return False
# Encode our data if we are on Python3 or later
payload = (
tx_data.encode("utf-8") if sys.version_info[0] >= 3 else tx_data
)
# Always call throttle before any remote server i/o is made
self.throttle()
# Try to open the socket
# Send the content to APRS-IS
try:
self.sock.setblocking(True)
self.sock.settimeout(self.socket_connect_timeout)
self.sock.sendall(payload)
except socket.gaierror as e:
self.logger.warning("Socket Exception socket_send: %s" % str(e))
self.sock = None
return False
except socket.timeout as e:
self.logger.warning(
"Socket Timeout Exception " "socket_send: %s" % str(e)
)
self.sock = None
return False
except Exception as e:
self.logger.warning(
"General Exception " "socket_send: %s" % str(e)
)
self.sock = None
return False
self.logger.debug("socket_send: successful")
# mandatory on several APRS-IS servers
# helps to reduce the number of errors where
# the server only returns an abbreviated message
return True
def socket_reset(self):
"""
Resets the socket's buffer
"""
self.logger.debug("socket_reset: init")
_ = self.socket_receive(0)
self.logger.debug("socket_reset: successful")
return True
def socket_receive(self, rx_len):
"""
Generic "Receive data from a socket"
"""
self.logger.debug("socket_receive: init")
# Check if we are connected
if not self.sock:
self.logger.warning("socket_receive: not connected to APRS-IS")
return False
# len is zero in case we intend to
# reset the socket
if rx_len > 0:
self.logger.debug("socket_receive: Receiving data from APRS-IS")
# Receive content from the socket
try:
self.sock.setblocking(False)
self.sock.settimeout(self.socket_connect_timeout)
rx_buf = self.sock.recv(rx_len)
except socket.gaierror as e:
self.logger.warning(
"Socket Exception socket_receive: %s" % str(e)
)
self.sock = None
return False
except socket.timeout as e:
self.logger.warning(
"Socket Timeout Exception " "socket_receive: %s" % str(e)
)
self.sock = None
return False
except Exception as e:
self.logger.warning(
"General Exception " "socket_receive: %s" % str(e)
)
self.sock = None
return False
rx_buf = (
rx_buf.decode(self.aprs_encoding)
if sys.version_info[0] >= 3 else rx_buf
)
# There will be no data in case we reset the socket
if rx_len > 0:
self.logger.debug("Received content: {}".format(rx_buf))
self.logger.debug("socket_receive: successful")
return rx_buf.rstrip()
def send(self, body, title="", notify_type=NotifyType.INFO, **kwargs):
"""
Perform APRS Notification
"""
if not self.targets:
# There is no one to notify; we're done
self.logger.warning(
"There are no amateur radio call signs to notify"
)
return False
# prepare payload
payload = body
# sock object is "None" if we were unable to establish a connection
# In case of errors, the error message has already been sent
# to the logger object
if not self.socket_open():
return False
# We have established a successful connection
# to the socket server. Now send the login information
if not self.aprsis_login():
return False
# Login & authorization confirmed
# reset what is in our buffer
self.socket_reset()
# error tracking (used for function return)
has_error = False
# Create a copy of the targets list
targets = list(self.targets)
self.logger.debug("Starting Payload setup")
# Prepare the outgoing message
# Due to APRS's contraints, we need to do
# a lot of filtering before we can send
# the actual message
#
# First remove all characters from the
# payload that would break APRS
# see https://www.aprs.org/doc/APRS101.PDF pg. 71
payload = re.sub("[{}|~]+", "", payload)
payload = ( # pragma: no branch
APRS_COMPILED_MAP.sub(
lambda x: APRS_BAD_CHARMAP[x.group()], payload)
)
# Finally, constrain output string to 67 characters as
# APRS messages are limited in length
payload = payload[:67]
# Our outgoing message MUST end with a CRLF so
# let's amend our payload respectively
payload = payload.rstrip("\r\n") + "\r\n"
self.logger.debug("Payload setup complete: {}".format(payload))
# send the message to our target call sign(s)
for index in range(0, len(targets)):
# prepare the output string
# Format:
# Device ID/TOCALL - our call sign - target call sign - body
buffer = "{}>{}::{:9}:{}".format(
self.user, self.device_id, targets[index], payload
)
# and send the content to the socket
# Note that there will be no response from APRS and
# that all exceptions are handled within the 'send' method
self.logger.debug("Sending APRS message: {}".format(buffer))
# send the content
if not self.socket_send(buffer):
has_error = True
break
# Finally, reset our socket buffer
# we DO NOT read from the socket as we
# would simply listen to the default APRS-IS stream
self.socket_reset()
self.logger.debug("Closing socket.")
self.socket_close()
self.logger.info(
"Sent %d/%d APRS-IS notification(s)", index + 1, len(targets))
return not has_error
def url(self, privacy=False, *args, **kwargs):
"""
Returns the URL built dynamically based on specified arguments.
"""
# Define any URL parameters
params = {}
if self.locale != NotifyAprs.template_args["locale"]["default"]:
# Store our locale if not default
params['locale'] = self.locale
if self.delay != NotifyAprs.template_args["delay"]["default"]:
# Store our locale if not default
params['delay'] = "{:.2f}".format(self.delay)
# Extend our parameters
params.update(self.url_parameters(privacy=privacy, *args, **kwargs))
# Setup Authentication
auth = "{user}:{password}@".format(
user=NotifyAprs.quote(self.user, safe=""),
password=self.pprint(
self.password, privacy, mode=PrivacyMode.Secret, safe=""
),
)
return "{schema}://{auth}{targets}?{params}".format(
schema=self.secure_protocol,
auth=auth,
targets="/".join(chain(
[self.pprint(x, privacy, safe="") for x in self.targets],
[self.pprint(x, privacy, safe="")
for x in self.invalid_targets],
)),
params=NotifyAprs.urlencode(params),
)
def __len__(self):
"""
Returns the number of targets associated with this notification
"""
targets = len(self.targets)
return targets if targets > 0 else 1
def __del__(self):
"""
Ensure we close any lingering connections
"""
self.socket_close()
@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, verify_host=False)
if not results:
# We're done early as we couldn't load the results
return results
# All elements are targets
results["targets"] = [NotifyAprs.unquote(results["host"])]
# All entries after the hostname are additional targets
results["targets"].extend(NotifyAprs.split_path(results["fullpath"]))
# Get Delay (if set)
if 'delay' in results['qsd'] and len(results['qsd']['delay']):
results['delay'] = NotifyAprs.unquote(results['qsd']['delay'])
# Support the 'to' variable so that we can support rooms this way too
# The 'to' makes it easier to use yaml configuration
if "to" in results["qsd"] and len(results["qsd"]["to"]):
results["targets"] += NotifyAprs.parse_list(results["qsd"]["to"])
# Set our APRS-IS server locale's key value and convert it to uppercase
if "locale" in results["qsd"] and len(results["qsd"]["locale"]):
results["locale"] = NotifyAprs.unquote(
results["qsd"]["locale"]
).upper()
return results
|