summaryrefslogtreecommitdiffhomepage
path: root/libs/apprise/utils.py
blob: b33ec0749f82379988af0a5deeaaeba58b77fb16 (plain)
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
# -*- 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.

import re
import sys
import json
import contextlib
import os
import locale
from itertools import chain
from os.path import expanduser
from functools import reduce
from . import common
from .logger import logger
from urllib.parse import unquote
from urllib.parse import quote
from urllib.parse import urlparse
from urllib.parse import urlencode as _urlencode

import importlib.util


def import_module(path, name):
    """
    Load our module based on path
    """
    spec = importlib.util.spec_from_file_location(name, path)
    try:
        module = importlib.util.module_from_spec(spec)
        sys.modules[name] = module

        spec.loader.exec_module(module)

    except Exception as e:
        # module isn't loadable
        try:
            del sys.modules[name]

        except KeyError:
            # nothing to clean up
            pass

        module = None

        logger.debug(
            'Module exception raised from %s (name=%s) %s',
            path, name, str(e))

    return module


# URL Indexing Table for returns via parse_url()
# The below accepts and scans for:
#  - schema://
#  - schema://path
#  - schema://path?kwargs
#
VALID_URL_RE = re.compile(
    r'^[\s]*((?P<schema>[^:\s]+):[/\\]+)?((?P<path>[^?]+)'
    r'(\?(?P<kwargs>.+))?)?[\s]*$',
)
VALID_QUERY_RE = re.compile(r'^(?P<path>.*[/\\])(?P<query>[^/\\]+)?$')

# delimiters used to separate values when content is passed in by string.
# This is useful when turning a string into a list
STRING_DELIMITERS = r'[\[\]\;,\s]+'

# String Delimiters without the whitespace
STRING_DELIMITERS_NO_WS = r'[\[\]\;,]+'

# Pre-Escape content since we reference it so much
ESCAPED_PATH_SEPARATOR = re.escape('\\/')
ESCAPED_WIN_PATH_SEPARATOR = re.escape('\\')
ESCAPED_NUX_PATH_SEPARATOR = re.escape('/')

TIDY_WIN_PATH_RE = re.compile(
    r'(^[%s]{2}|[^%s\s][%s]|[\s][%s]{2}])([%s]+)' % (
        ESCAPED_WIN_PATH_SEPARATOR,
        ESCAPED_WIN_PATH_SEPARATOR,
        ESCAPED_WIN_PATH_SEPARATOR,
        ESCAPED_WIN_PATH_SEPARATOR,
        ESCAPED_WIN_PATH_SEPARATOR,
    ),
)
TIDY_WIN_TRIM_RE = re.compile(
    r'^(.+[^:][^%s])[\s%s]*$' % (
        ESCAPED_WIN_PATH_SEPARATOR,
        ESCAPED_WIN_PATH_SEPARATOR,
    ),
)

TIDY_NUX_PATH_RE = re.compile(
    r'([%s])([%s]+)' % (
        ESCAPED_NUX_PATH_SEPARATOR,
        ESCAPED_NUX_PATH_SEPARATOR,
    ),
)

TIDY_NUX_TRIM_RE = re.compile(
    r'([^%s])[\s%s]+$' % (
        ESCAPED_NUX_PATH_SEPARATOR,
        ESCAPED_NUX_PATH_SEPARATOR,
    ),
)

# The handling of custom arguments passed in the URL; we treat any
# argument (which would otherwise appear in the qsd area of our parse_url()
# function differently if they start with a +, - or : value
NOTIFY_CUSTOM_ADD_TOKENS = re.compile(r'^( |\+)(?P<key>.*)\s*')
NOTIFY_CUSTOM_DEL_TOKENS = re.compile(r'^-(?P<key>.*)\s*')
NOTIFY_CUSTOM_COLON_TOKENS = re.compile(r'^:(?P<key>.*)\s*')

# Used for attempting to acquire the schema if the URL can't be parsed.
GET_SCHEMA_RE = re.compile(r'\s*(?P<schema>[a-z0-9]{1,12})://.*$', re.I)

# Used for validating that a provided entry is indeed a schema
# this is slightly different then the GET_SCHEMA_RE above which
# insists the schema is only valid with a :// entry.  this one
# extrapolates the individual entries
URL_DETAILS_RE = re.compile(
    r'\s*(?P<schema>[a-z0-9]{1,12})(://(?P<base>.*))?$', re.I)

# Regular expression based and expanded from:
# http://www.regular-expressions.info/email.html
# Extended to support colon (:) delimiter for parsing names from the URL
# such as:
#   - 'Optional Name':user@example.com
#   - 'Optional Name' <user@example.com>
#
# The expression also parses the general email as well such as:
#   - user@example.com
#   - label+user@example.com
GET_EMAIL_RE = re.compile(
    r'(([\s"\']+)?(?P<name>[^:<\'"]+)?[:<\s\'"]+)?'
    r'(?P<full_email>((?P<label>[^+]+)\+)?'
    r'(?P<email>(?P<userid>[a-z0-9_!#$%&*/=?%`{|}~^-]+'
    r'(?:\.[a-z0-9_!#$%&\'*/=?%`{|}~^-]+)'
    r'*)@(?P<domain>('
    r'(?:[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?\.)+'
    r'[a-z0-9](?:[a-z0-9_-]*[a-z0-9]))|'
    r'[a-z0-9][a-z0-9_-]{5,})))'
    r'\s*>?', re.IGNORECASE)

# A simple verification check to make sure the content specified
# rougly conforms to a phone number before we parse it further
IS_PHONE_NO = re.compile(r'^\+?(?P<phone>[0-9\s)(+-]+)\s*$')

# Regular expression used to destinguish between multiple phone numbers
PHONE_NO_DETECTION_RE = re.compile(
    r'\s*([+(\s]*[0-9][0-9()\s-]+[0-9])(?=$|[\s,+(]+[0-9])', re.I)

# A simple verification check to make sure the content specified
# rougly conforms to a ham radio call sign before we parse it further
IS_CALL_SIGN = re.compile(
    r'^(?P<callsign>[a-z0-9]{2,3}[0-9][a-z0-9]{3})'
    r'(?P<ssid>-[a-z0-9]{1,2})?\s*$', re.I)

# Regular expression used to destinguish between multiple ham radio call signs
CALL_SIGN_DETECTION_RE = re.compile(
    r'\s*([a-z0-9]{2,3}[0-9][a-z0-9]{3}(?:-[a-z0-9]{1,2})?)'
    r'(?=$|[\s,]+[a-z0-9]{4,6})', re.I)

# Regular expression used to destinguish between multiple URLs
URL_DETECTION_RE = re.compile(
    r'([a-z0-9]+?:\/\/.*?)(?=$|[\s,]+[a-z0-9]{1,12}?:\/\/)', re.I)

EMAIL_DETECTION_RE = re.compile(
    r'[\s,]*([^@]+@.*?)(?=$|[\s,]+'
    r'(?:[^:<]+?[:<\s]+?)?'
    r'[^@\s,]+@[^\s,]+)',
    re.IGNORECASE)

# Used to prepare our UUID regex matching
UUID4_RE = re.compile(
    r'[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}',
    re.IGNORECASE)

# Validate if we're a loadable Python file or not
VALID_PYTHON_FILE_RE = re.compile(r'.+\.py(o|c)?$', re.IGNORECASE)

# validate_regex() utilizes this mapping to track and re-use pre-complied
# regular expressions
REGEX_VALIDATE_LOOKUP = {}


class Singleton(type):
    """
    Our Singleton MetaClass
    """
    _instances = {}

    def __call__(cls, *args, **kwargs):
        """
        instantiate our singleton meta entry
        """
        if cls not in cls._instances:
            # we have not every built an instance before.  Build one now.
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]


class TemplateType:
    """
    Defines the different template types we can perform parsing on
    """
    # RAW does nothing at all to the content being parsed
    # data is taken at it's absolute value
    RAW = 'raw'

    # Data is presumed to be of type JSON and is therefore escaped
    # if required to do so (such as single quotes)
    JSON = 'json'


def is_ipaddr(addr, ipv4=True, ipv6=True):
    """
    Validates against IPV4 and IPV6 IP Addresses
    """

    if ipv4:
        # Based on https://stackoverflow.com/questions/5284147/\
        #       validating-ipv4-addresses-with-regexp
        re_ipv4 = re.compile(
            r'^(?P<ip>((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}'
            r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))$'
        )
        match = re_ipv4.match(addr)
        if match is not None:
            # Return our matched IP
            return match.group('ip')

    if ipv6:
        # Based on https://stackoverflow.com/questions/53497/\
        #              regular-expression-that-matches-valid-ipv6-addresses
        #
        # IPV6 URLs should be enclosed in square brackets when placed on a URL
        #   Source: https://tools.ietf.org/html/rfc2732
        #   - For this reason, they are additionally checked for existance
        re_ipv6 = re.compile(
            r'\[?(?P<ip>(([0-9a-f]{1,4}:){7,7}[0-9a-f]{1,4}|([0-9a-f]{1,4}:)'
            r'{1,7}:|([0-9a-f]{1,4}:){1,6}:[0-9a-f]{1,4}|([0-9a-f]{1,4}:){1,5}'
            r'(:[0-9a-f]{1,4}){1,2}|([0-9a-f]{1,4}:){1,4}'
            r'(:[0-9a-f]{1,4}){1,3}|([0-9a-f]{1,4}:){1,3}'
            r'(:[0-9a-f]{1,4}){1,4}|([0-9a-f]{1,4}:){1,2}'
            r'(:[0-9a-f]{1,4}){1,5}|[0-9a-f]{1,4}:'
            r'((:[0-9a-f]{1,4}){1,6})|:((:[0-9a-f]{1,4}){1,7}|:)|'
            r'fe80:(:[0-9a-f]{0,4}){0,4}%[0-9a-z]{1,}|::'
            r'(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]'
            r'|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|'
            r'1{0,1}[0-9]){0,1}[0-9])|([0-9a-f]{1,4}:){1,4}:((25[0-5]|'
            r'(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|'
            r'1{0,1}[0-9]){0,1}[0-9])))\]?', re.I,
        )

        match = re_ipv6.match(addr)
        if match is not None:
            # Return our matched IP between square brackets since that is
            # required for URL formatting as per RFC 2732.
            return '[{}]'.format(match.group('ip'))

    # There was no match
    return False


def is_hostname(hostname, ipv4=True, ipv6=True, underscore=True):
    """
    Validate hostname
    """
    # The entire hostname, including the delimiting dots, has a maximum of 253
    # ASCII characters.
    if len(hostname) > 253 or len(hostname) == 0:
        return False

    # Strip trailing period on hostname (if one exists)
    if hostname[-1] == ".":
        hostname = hostname[:-1]

    # Split our hostname up
    labels = hostname.split(".")

    # ipv4 check
    if len(labels) == 4 and re.match(r'[0-9.]+', hostname):
        return is_ipaddr(hostname, ipv4=ipv4, ipv6=False)

    # - RFC 1123 permits hostname labels to start with digits
    #     - digit must be followed by alpha/numeric so we don't end up
    #       processing IP addresses here
    # - Hostnames can ony be comprised of alpha-numeric characters and the
    #   hyphen (-) character.
    # - Hostnames can not start with the hyphen (-) character.
    # - as a workaround for https://github.com/docker/compose/issues/229 to
    #   being able to address services in other stacks, we also allow
    #   underscores in hostnames (if flag is set accordingly)
    # - labels can not exceed 63 characters
    # - allow single character alpha characters
    allowed = re.compile(
        r'^([a-z0-9][a-z0-9_-]{1,62}|[a-z_-])(?<![_-])$' if underscore else
        r'^([a-z0-9][a-z0-9-]{1,62}|[a-z-])(?<!-)$',
        re.IGNORECASE,
    )

    if not all(allowed.match(x) for x in labels):
        return is_ipaddr(hostname, ipv4=ipv4, ipv6=ipv6)

    return hostname


def is_uuid(uuid):
    """Determine if the specified entry is uuid v4 string

    Args:
        address (str): The string you want to check.

    Returns:
        bool: Returns False if the specified element is not a uuid otherwise
              it returns True
    """

    try:
        match = UUID4_RE.match(uuid)

    except TypeError:
        # not parseable content
        return False

    return True if match else False


def is_phone_no(phone, min_len=10):
    """Determine if the specified entry is a phone number

    Args:
        phone (str): The string you want to check.
        min_len (int): Defines the smallest expected length of the phone
                       before it's to be considered invalid. By default
                       the phone number can't be any larger then 14

    Returns:
        bool: Returns False if the address specified is not a phone number
              and a dictionary of the parsed phone number if it is as:
                {
                    'country': '1',
                    'area': '800',
                    'line': '1234567',
                    'full': '18001234567',
                    'pretty': '+1 800-123-4567',
                }

        Non conventional numbers such as 411 would look like provided that
        `min_len` is set to at least a 3:
                {
                    'country': '',
                    'area': '',
                    'line': '411',
                    'full': '411',
                    'pretty': '411',
                }

    """

    try:
        if not IS_PHONE_NO.match(phone):
            # not parseable content as it does not even conform closely to a
            # phone number)
            return False

    except TypeError:
        return False

    # Tidy phone number up first
    phone = re.sub(r'[^\d]+', '', phone)
    if len(phone) > 14 or len(phone) < min_len:
        # Invalid phone number
        return False

    # Full phone number without any markup is as is now
    full = phone

    # Break apart our phone number
    line = phone[-7:]
    phone = phone[:len(phone) - 7] if len(phone) > 7 else ''

    # the area code (if present)
    area = phone[-3:] if phone else ''

    # The country code is the leftovers
    country = phone[:len(phone) - 3] if len(phone) > 3 else ''

    # Prepare a nicely (consistently) formatted phone number
    pretty = ''

    if country:
        # The leftover is the country code
        pretty += '+{} '.format(country)

    if area:
        pretty += '{}-'.format(area)

    if len(line) >= 7:
        pretty += '{}-{}'.format(line[:3], line[3:])

    else:
        pretty += line

    return {
        # The line code (last 7 digits)
        'line': line,
        # Area code
        'area': area,
        # The country code (if identified)
        'country': country,

        # A nicely formatted phone no
        'pretty': pretty,

        # All digits in-line
        'full': full,
    }


def is_call_sign(callsign):
    """Determine if the specified entry is a ham radio call sign

    Args:
        callsign (str): The string you want to check.

    Returns:
        bool: Returns False if the address specified is not a phone number
    """

    try:
        result = IS_CALL_SIGN.match(callsign)
        if not result:
            # not parseable content as it does not even conform closely to a
            # callsign
            return False

    except TypeError:
        # not parseable content
        return False

    ssid = result.group('ssid')
    return {
        # always treat call signs as uppercase content
        'callsign': result.group('callsign').upper(),
        # Prevent the storing of the None keyword in the event the SSID was
        # not detected
        'ssid': ssid if ssid else '',
    }


def is_email(address):
    """Determine if the specified entry is an email address

    Args:
        address (str): The string you want to check.

    Returns:
        bool: Returns False if the address specified is not an email address
              and a dictionary of the parsed email if it is as:
                {
                    'name': 'Parse Name'
                    'email': 'user@domain.com'
                    'full_email': 'label+user@domain.com'
                    'label': 'label'
                    'user': 'user',
                    'domain': 'domain.com'
                }

    """

    try:
        match = GET_EMAIL_RE.match(address)

    except TypeError:
        # not parseable content
        return False

    if match:
        return {
            # The name parsed from the URL (if one exists)
            'name': '' if match.group('name') is None
            else match.group('name').strip(),
            # The email address
            'email': match.group('email'),
            # The full email address (includes label if specified)
            'full_email': match.group('full_email'),
            # The label (if specified) e.g: label+user@example.com
            'label': '' if match.group('label') is None
            else match.group('label').strip(),
            # The user (which does not include the label) from the email
            # parsed.
            'user': match.group('userid'),
            # The domain associated with the email address
            'domain': match.group('domain'),
        }

    return False


def tidy_path(path):
    """take a filename and or directory and attempts to tidy it up by removing
    trailing slashes and correcting any formatting issues.

    For example: ////absolute//path// becomes:
        /absolute/path

    """
    # Windows
    path = TIDY_WIN_PATH_RE.sub('\\1', path.strip())
    # Linux
    path = TIDY_NUX_PATH_RE.sub('\\1', path)

    # Windows Based (final) Trim
    path = expanduser(TIDY_WIN_TRIM_RE.sub('\\1', path))
    return path


def parse_qsd(qs, simple=False, plus_to_space=False, sanitize=True):
    """
    Query String Dictionary Builder

    A custom implimentation of the parse_qsl() function already provided
    by Python.  This function is slightly more light weight and gives us
    more control over parsing out arguments such as the plus/+ symbol
    at the head of a key/value pair.

    qs should be a query string part made up as part of the URL such as
       a=1&c=2&d=

        a=1 gets interpreted as { 'a': '1' }
        a=  gets interpreted as { 'a': '' }
        a   gets interpreted as { 'a': '' }


    This function returns a result object that fits with the apprise
    expected parameters (populating the 'qsd' portion of the dictionary

    if simple is set to true, then a ONE dictionary is returned and is not
    sub-parsed for additional elements

    plus_to_space will cause all `+` references to become a space as
    per normal URL Encoded defininition. Normal URL parsing applies
    this, but `+` is very actively used character with passwords,
    api keys, tokens, etc.  So Apprise does not do this by default.

    if sanitize is set to False, then kwargs are not placed into lowercase
    """

    # Our return result set:
    result = {
        # The arguments passed in (the parsed query). This is in a dictionary
        # of {'key': 'val', etc }.  Keys are all made lowercase before storing
        # to simplify access to them.
        'qsd': {},

        # Detected Entries that start with + or - are additionally stored in
        # these values (un-touched).  The :,+,- however are stripped from their
        # name before they are stored here.
        'qsd+': {},
        'qsd-': {},
        'qsd:': {},
    } if not simple else {'qsd': {}}

    pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
    for name_value in pairs:
        nv = name_value.split('=', 1)
        # Handle case of a control-name with no equal sign
        if len(nv) != 2:
            nv.append('')

        # Apprise keys can start with a + symbol; so we need to skip over
        # the very first entry
        key = '{}{}'.format(
            '' if len(nv[0]) == 0 else nv[0][0],
            '' if len(nv[0]) <= 1 else nv[0][1:].replace('+', ' '),
        )

        key = unquote(key)
        key = '' if not key else key

        val = nv[1].replace('+', ' ') if plus_to_space else nv[1]
        val = unquote(val)
        val = '' if not val else val.strip()

        # Always Query String Dictionary (qsd) for every entry we have
        # content is always made lowercase for easy indexing
        result['qsd'][key.lower().strip() if sanitize else key] = val

        if simple:
            # move along
            continue

        # Check for tokens that start with a addition/plus symbol (+)
        k = NOTIFY_CUSTOM_ADD_TOKENS.match(key)
        if k is not None:
            # Store content 'as-is'
            result['qsd+'][k.group('key')] = val

        # Check for tokens that start with a subtraction/hyphen symbol (-)
        k = NOTIFY_CUSTOM_DEL_TOKENS.match(key)
        if k is not None:
            # Store content 'as-is'
            result['qsd-'][k.group('key')] = val

        # Check for tokens that start with a colon symbol (:)
        k = NOTIFY_CUSTOM_COLON_TOKENS.match(key)
        if k is not None:
            # Store content 'as-is'
            result['qsd:'][k.group('key')] = val

    return result


def parse_url(url, default_schema='http', verify_host=True, strict_port=False,
              simple=False, plus_to_space=False, sanitize=True):
    """A function that greatly simplifies the parsing of a url
    specified by the end user.

     Valid syntaxes are:
        <schema>://<user>@<host>:<port>/<path>
        <schema>://<user>:<passwd>@<host>:<port>/<path>
        <schema>://<host>:<port>/<path>
        <schema>://<host>/<path>
        <schema>://<host>
        <host>

     Argument parsing is also supported:
        <schema>://<user>@<host>:<port>/<path>?key1=val&key2=val2
        <schema>://<user>:<passwd>@<host>:<port>/<path>?key1=val&key2=val2
        <schema>://<host>:<port>/<path>?key1=val&key2=val2
        <schema>://<host>/<path>?key1=val&key2=val2
        <schema>://<host>?key1=val&key2=val2

     The function returns a simple dictionary with all of
     the parsed content within it and returns 'None' if the
     content could not be extracted.

     The output of 'http://hostname' would look like:
        {
          'schema': 'http',
          'url': 'http://hostname',
          'host': 'hostname',

          'user': None,
          'password': None,
          'port': None,
          'fullpath': None,
          'path': None,
          'query': None,

          'qsd': {},

          'qsd+': {},
          'qsd-': {},
          'qsd:': {}
        }

     The simple switch cleans the dictionary response to only include the
     fields that were detected.

     The output of 'http://hostname' with the simple flag set would look like:
        {
          'schema': 'http',
          'url': 'http://hostname',
          'host': 'hostname',
        }

     If the URL can't be parsed then None is returned

     If sanitize is set to False, then kwargs are not placed in lowercase
     and wrapping whitespace is not removed
    """

    if not isinstance(url, str):
        # Simple error checking
        return None

    # Default Results
    result = {
        # The username (if specified)
        'user': None,
        # The password (if specified)
        'password': None,
        # The port (if specified)
        'port': None,
        # The hostname
        'host': '',
        # The full path (query + path)
        'fullpath': None,
        # The path
        'path': None,
        # The query
        'query': None,
        # The schema
        'schema': None,
        # The schema
        'url': None,
        # The arguments passed in (the parsed query). This is in a dictionary
        # of {'key': 'val', etc }.  Keys are all made lowercase before storing
        # to simplify access to them.
        # qsd = Query String Dictionary
        'qsd': {},

        # Detected Entries that start with +, - or : are additionally stored in
        # these values (un-touched).  The +, -, and : however are stripped
        # from their name before they are stored here.
        'qsd+': {},
        'qsd-': {},
        'qsd:': {},
    } if not simple else {}

    qsdata = ''
    match = VALID_URL_RE.search(url)
    if match:
        # Extract basic results (with schema present)
        result['schema'] = match.group('schema').lower().strip() \
            if match.group('schema') else default_schema
        host = match.group('path').strip() \
            if match.group('path') else ''
        qsdata = match.group('kwargs').strip() \
            if match.group('kwargs') else None

    else:
        # Could not extract basic content from the URL
        return None

    # Parse Query Arugments ?val=key&key=val
    # while ensuring that all keys are lowercase
    if qsdata:
        result.update(parse_qsd(
            qsdata, simple=simple, plus_to_space=plus_to_space,
            sanitize=sanitize))

    # Now do a proper extraction of data; http:// is just substitued in place
    # to allow urlparse() to function as expected, we'll swap this back to the
    # expected schema after.
    parsed = urlparse('http://%s' % host)

    # Parse results
    result['host'] = parsed[1].strip()
    result['fullpath'] = quote(unquote(tidy_path(parsed[2].strip())))

    try:
        # Handle trailing slashes removed by tidy_path
        if result['fullpath'][-1] not in ('/', '\\') and \
           url[-1] in ('/', '\\'):
            result['fullpath'] += url.strip()[-1]

    except IndexError:
        # No problem, there simply isn't any returned results
        # and therefore, no trailing slash
        pass

    if not result['fullpath']:
        if not simple:
            # Default
            result['fullpath'] = None
        else:
            # Remove entry
            del result['fullpath']

    else:
        # Using full path, extract query from path
        match = VALID_QUERY_RE.search(result['fullpath'])
        result['path'] = match.group('path')
        result['query'] = match.group('query')
        if not result['query']:
            if not simple:
                result['query'] = None
            else:
                del result['query']

    try:
        (result['user'], result['host']) = \
            re.split(r'[@]+', result['host'])[:2]

    except ValueError:
        # no problem then, host only exists
        # and it's already assigned
        pass

    if result.get('user') is not None:
        try:
            (result['user'], result['password']) = \
                re.split(r'[:]+', result['user'])[:2]

        except ValueError:
            # no problem then, user only exists
            # and it's already assigned
            pass

    # Port Parsing
    pmatch = re.search(
        r'^(?P<host>(\[[0-9a-f:]+\]|[^:]+)):(?P<port>[^:]*)$',
        result['host'])

    if pmatch:
        # Separate our port from our hostname (if port is detected)
        result['host'] = pmatch.group('host')
        try:
            # If we're dealing with an integer, go ahead and convert it
            # otherwise return an 'x' which will raise a ValueError
            #
            # This small extra check allows us to treat floats/doubles
            # as strings. Hence a value like '4.2' won't be converted to a 4
            # (and the .2 lost)
            result['port'] = int(
                pmatch.group('port')
                if re.search(r'[0-9]', pmatch.group('port')) else 'x')

        except ValueError:
            if verify_host:
                # Invalid Host Specified
                return None

    # Acquire our port (if defined)
    _port = result.get('port')

    if verify_host:
        # Verify and Validate our hostname
        result['host'] = is_hostname(result['host'])
        if not result['host']:
            # Nothing more we can do without a hostname; give the user
            # some indication as to what went wrong
            return None

        # Max port is 65535 and min is 1
        if isinstance(_port, int) and not ((
            not strict_port or (
                strict_port and _port > 0 and _port <= 65535))):

            # An invalid port was specified
            return None

    elif pmatch and not isinstance(_port, int):
        if strict_port:
            # Store port
            result['port'] = pmatch.group('port').strip()

        else:
            # Fall back
            result['port'] = None
            result['host'] = '{}:{}'.format(
                pmatch.group('host'), pmatch.group('port'))

    # Re-assemble cleaned up version of the url
    result['url'] = '%s://' % result['schema']
    if isinstance(result.get('user'), str):
        result['url'] += result['user']

        if isinstance(result.get('password'), str):
            result['url'] += ':%s@' % result['password']

        else:
            result['url'] += '@'
    result['url'] += result['host']

    if result.get('port') is not None:
        try:
            result['url'] += ':%d' % result['port']

        except TypeError:
            result['url'] += ':%s' % result['port']

    elif 'port' in result and simple:
        # Eliminate empty fields
        del result['port']

    if result.get('fullpath'):
        result['url'] += result['fullpath']

    if simple and not result['host']:
        # simple mode does not carry over empty host names
        del result['host']

    return result


def parse_bool(arg, default=False):
    """
    Support string based boolean settings.

    If the content could not be parsed, then the default is returned.
    """

    if isinstance(arg, str):
        # no = no - False
        # of = short for off - False
        # 0  = int for False
        # fa = short for False - False
        # f  = short for False - False
        # n  = short for No or Never - False
        # ne  = short for Never - False
        # di  = short for Disable(d) - False
        # de  = short for Deny - False
        if arg.lower()[0:2] in (
                'de', 'di', 'ne', 'f', 'n', 'no', 'of', '0', 'fa'):
            return False
        # ye = yes - True
        # on = short for off - True
        # 1  = int for True
        # tr = short for True - True
        # t  = short for True - True
        # al = short for Always (and Allow) - True
        # en  = short for Enable(d) - True
        elif arg.lower()[0:2] in (
                'en', 'al', 't', 'y', 'ye', 'on', '1', 'tr'):
            return True
        # otherwise
        return default

    # Handle other types
    return bool(arg)


def parse_phone_no(*args, store_unparseable=True, **kwargs):
    """
    Takes a string containing phone numbers separated by comma's and/or spaces
    and returns a list.
    """

    result = []
    for arg in args:
        if isinstance(arg, str) and arg:
            _result = PHONE_NO_DETECTION_RE.findall(arg)
            if _result:
                result += _result

            elif not _result and store_unparseable:
                # we had content passed into us that was lost because it was
                # so poorly formatted that it didn't even come close to
                # meeting the regular expression we defined. We intentially
                # keep it as part of our result set so that parsing done
                # at a higher level can at least report this to the end user
                # and hopefully give them some indication as to what they
                # may have done wrong.
                result += \
                    [x for x in filter(bool, re.split(STRING_DELIMITERS, arg))]

        elif isinstance(arg, (set, list, tuple)):
            # Use recursion to handle the list of phone numbers
            result += parse_phone_no(
                *arg, store_unparseable=store_unparseable)

    return result


def parse_call_sign(*args, store_unparseable=True, **kwargs):
    """
    Takes a string containing ham radio call signs separated by
    comma and/or spacesand returns a list.
    """

    result = []
    for arg in args:
        if isinstance(arg, str) and arg:
            _result = CALL_SIGN_DETECTION_RE.findall(arg)
            if _result:
                result += _result

            elif not _result and store_unparseable:
                # we had content passed into us that was lost because it was
                # so poorly formatted that it didn't even come close to
                # meeting the regular expression we defined. We intentially
                # keep it as part of our result set so that parsing done
                # at a higher level can at least report this to the end user
                # and hopefully give them some indication as to what they
                # may have done wrong.
                result += \
                    [x for x in filter(bool, re.split(STRING_DELIMITERS, arg))]

        elif isinstance(arg, (set, list, tuple)):
            # Use recursion to handle the list of call signs
            result += parse_call_sign(
                *arg, store_unparseable=store_unparseable)

    return result


def parse_emails(*args, store_unparseable=True, **kwargs):
    """
    Takes a string containing emails separated by comma's and/or spaces and
    returns a list.
    """

    result = []
    for arg in args:
        if isinstance(arg, str) and arg:
            _result = EMAIL_DETECTION_RE.findall(arg)
            if _result:
                result += _result

            elif not _result and store_unparseable:
                # we had content passed into us that was lost because it was
                # so poorly formatted that it didn't even come close to
                # meeting the regular expression we defined. We intentially
                # keep it as part of our result set so that parsing done
                # at a higher level can at least report this to the end user
                # and hopefully give them some indication as to what they
                # may have done wrong.
                result += \
                    [x for x in filter(bool, re.split(STRING_DELIMITERS, arg))]

        elif isinstance(arg, (set, list, tuple)):
            # Use recursion to handle the list of Emails
            result += parse_emails(*arg, store_unparseable=store_unparseable)

    return result


def parse_urls(*args, store_unparseable=True, **kwargs):
    """
    Takes a string containing URLs separated by comma's and/or spaces and
    returns a list.
    """

    result = []
    for arg in args:
        if isinstance(arg, str) and arg:
            _result = URL_DETECTION_RE.findall(arg)
            if _result:
                result += _result

            elif not _result and store_unparseable:
                # we had content passed into us that was lost because it was
                # so poorly formatted that it didn't even come close to
                # meeting the regular expression we defined. We intentially
                # keep it as part of our result set so that parsing done
                # at a higher level can at least report this to the end user
                # and hopefully give them some indication as to what they
                # may have done wrong.
                result += \
                    [x for x in filter(bool, re.split(STRING_DELIMITERS, arg))]

        elif isinstance(arg, (set, list, tuple)):
            # Use recursion to handle the list of URLs
            result += parse_urls(*arg, store_unparseable=store_unparseable)

    return result


def url_assembly(**kwargs):
    """
    This function reverses the parse_url() function by taking in the provided
    result set and re-assembling a URL

    """
    # Determine Authentication
    auth = ''
    if kwargs.get('user') is not None and \
            kwargs.get('password') is not None:

        auth = '{user}:{password}@'.format(
            user=quote(kwargs.get('user'), safe=''),
            password=quote(kwargs.get('password'), safe=''),
        )

    elif kwargs.get('user') is not None:
        auth = '{user}@'.format(
            user=quote(kwargs.get('user'), safe=''),
        )

    return '{schema}://{auth}{hostname}{port}{fullpath}{params}'.format(
        schema='' if not kwargs.get('schema') else kwargs.get('schema'),
        auth=auth,
        # never encode hostname since we're expecting it to be a valid one
        hostname='' if not kwargs.get('host') else kwargs.get('host', ''),
        port='' if not kwargs.get('port')
        else ':{}'.format(kwargs.get('port')),
        fullpath=quote(kwargs.get('fullpath', ''), safe='/'),
        params='' if not kwargs.get('qsd')
        else '?{}'.format(urlencode(kwargs.get('qsd'))),
    )


def urlencode(query, doseq=False, safe='', encoding=None, errors=None):
    """Convert a mapping object or a sequence of two-element tuples

    Wrapper to Python's unquote while remaining compatible with both
    Python 2 & 3 since the reference to this function changed between
    versions.

    The resulting string is a series of key=value pairs separated by '&'
    characters, where both key and value are quoted using the quote()
    function.

    Note: If the dictionary entry contains an entry that is set to None
          it is not included in the final result set. If you want to
          pass in an empty variable, set it to an empty string.

    Args:
        query (str): The dictionary to encode
        doseq (:obj:`bool`, optional): Handle sequences
        safe (:obj:`str`): non-ascii characters and URI specific ones that
            you do not wish to escape (if detected). Setting this string
            to an empty one causes everything to be escaped.
        encoding (:obj:`str`, optional): encoding type
        errors (:obj:`str`, errors): how to handle invalid character found
            in encoded string (defined by encoding)

    Returns:
        str: The escaped parameters returned as a string
    """
    # Tidy query by eliminating any records set to None
    _query = {k: v for (k, v) in query.items() if v is not None}
    return _urlencode(
        _query, doseq=doseq, safe=safe, encoding=encoding,
        errors=errors)


def parse_list(*args, cast=None, allow_whitespace=True):
    """
    Take a string list and break it into a delimited
    list of arguments. This funciton also supports
    the processing of a list of delmited strings and will
    always return a unique set of arguments. Duplicates are
    always combined in the final results.

    You can append as many items to the argument listing for
    parsing.

    Hence: parse_list('.mkv, .iso, .avi') becomes:
        ['.mkv', '.iso', '.avi']

    Hence: parse_list('.mkv, .iso, .avi', ['.avi', '.mp4']) becomes:
        ['.mkv', '.iso', '.avi', '.mp4']

    The parsing is very forgiving and accepts spaces, slashes, commas
    semicolons, and pipes as delimiters
    """

    result = []
    for arg in args:
        if not isinstance(arg, (str, set, list, bool, tuple)) and arg and cast:
            arg = cast(arg)

        if isinstance(arg, str):
            result += re.split(
                STRING_DELIMITERS if allow_whitespace
                else STRING_DELIMITERS_NO_WS, arg)

        elif isinstance(arg, (set, list, tuple)):
            result += parse_list(*arg, allow_whitespace=allow_whitespace)

    #
    # filter() eliminates any empty entries
    #
    # Since Python v3 returns a filter (iterator) whereas Python v2 returned
    # a list, we need to change it into a list object to remain compatible with
    # both distribution types.
    return sorted([x for x in filter(bool, list(set(result)))]) \
        if allow_whitespace else sorted(
            [x.strip() for x in filter(bool, list(set(result))) if x.strip()])


def is_exclusive_match(logic, data, match_all=common.MATCH_ALL_TAG,
                       match_always=common.MATCH_ALWAYS_TAG):
    """

    The data variable should always be a set of strings that the logic can be
    compared against. It should be a set.  If it isn't already, then it will
    be converted as such. These identify the tags themselves.

    Our logic should be a list as well:
      - top level entries are treated as an 'or'
      - second level (or more) entries are treated as 'and'

      examples:
        logic="tagA, tagB"                = tagA or tagB
        logic=['tagA', 'tagB']            = tagA or tagB
        logic=[('tagA', 'tagC'), 'tagB']  = (tagA and tagC) or tagB
        logic=[('tagB', 'tagC')]          = tagB and tagC

    If `match_always` is not set to None, then its value is added as an 'or'
    to all specified logic searches.
    """

    if isinstance(logic, str):
        # Update our logic to support our delimiters
        logic = set(parse_list(logic))

    if not logic:
        # If there is no logic to apply then we're done early; we only match
        # if there is also no data to match against
        return not data

    if not isinstance(logic, (list, tuple, set)):
        # garbage input
        return False

    if match_always:
        # Add our match_always to our logic searching if secified
        logic = chain(logic, [match_always])

    # Track what we match against; but by default we do not match
    # against anything
    matched = False

    # Every entry here will be or'ed with the next
    for entry in logic:
        if not isinstance(entry, (str, list, tuple, set)):
            # Garbage entry in our logic found
            return False

        # treat these entries as though all elements found
        # must exist in the notification service
        entries = set(parse_list(entry))
        if not entries:
            # We got a bogus set of tags to parse
            # If there is no logic to apply then we're done early; we only
            # match if there is also no data to match against
            return not data

        if len(entries.intersection(data.union({match_all}))) == len(entries):
            # our set contains all of the entries found
            # in our notification data set
            matched = True
            break

        # else: keep looking

    # Return True if we matched against our logic (or simply none was
    # specified).
    return matched


def validate_regex(value, regex=r'[^\s]+', flags=re.I, strip=True, fmt=None):
    """
    A lot of the tokens, secrets, api keys, etc all have some regular
    expression validation they support.  This hashes the regex after it's
    compiled and returns it's content if matched, otherwise it returns None.

    This function greatly increases performance as it prevents apprise modules
    from having to pre-compile all of their regular expressions.

        value is the element being tested
        regex is the regular expression to be compiled and tested. By default
         we extract the first chunk of code while eliminating surrounding
         whitespace (if present)

        flags is the regular expression flags that should be applied
        format is used to alter the response format if the regular
         expression matches. You identify your format using {tags}.
         Effectively nesting your ID's between {}. Consider a regex of:
          '(?P<year>[0-9]{2})[0-9]+(?P<value>[A-Z])'
        to which you could set your format up as '{value}-{year}'. This
        would substitute the matched groups and format a response.
    """

    if flags:
        # Regex String -> Flag Lookup Map
        _map = {
            # Ignore Case
            'i': re.I,
            # Multi Line
            'm': re.M,
            # Dot Matches All
            's': re.S,
            # Locale Dependant
            'L': re.L,
            # Unicode Matching
            'u': re.U,
            # Verbose
            'x': re.X,
        }

        if isinstance(flags, str):
            # Convert a string of regular expression flags into their
            # respected integer (expected) Python values and perform
            # a bit-wise or on each match found:
            flags = reduce(
                lambda x, y: x | y,
                [0] + [_map[f] for f in flags if f in _map])

    else:
        # Handles None/False/'' cases
        flags = 0

    # A key is used to store our compiled regular expression
    key = '{}{}'.format(regex, flags)

    if key not in REGEX_VALIDATE_LOOKUP:
        REGEX_VALIDATE_LOOKUP[key] = re.compile(regex, flags)

    # Perform our lookup usig our pre-compiled result
    try:
        result = REGEX_VALIDATE_LOOKUP[key].match(value)
        if not result:
            # let outer exception handle this
            raise TypeError

        if fmt:
            # Map our format back to our response
            value = fmt.format(**result.groupdict())

    except (TypeError, AttributeError):
        return None

    # Return our response
    return value.strip() if strip else value


def cwe312_word(word, force=False, advanced=True, threshold=5):
    """
    This function was written to help mask secure/private information that may
    or may not be found within Apprise. The idea is to provide a presentable
    word response that the user who prepared it would understand, yet not
    reveal any private information for any potential intruder

    For more detail see CWE-312 @
       https://cwe.mitre.org/data/definitions/312.html

    The `force` is an optional argument used to keep the string formatting
    consistent and in one place. If set, the content passed in is presumed
    to be containing secret information and will be updated accordingly.

    If advanced is set to `True` then content is additionally checked for
    upper/lower/ascii/numerical variances. If an obscurity threshold is
    reached, then content is considered secret
    """

    class Variance:
        """
        A Simple List of Possible Character Variances
        """
        # An Upper Case Character (ABCDEF... etc)
        ALPHA_UPPER = '+'
        # An Lower Case Character (abcdef... etc)
        ALPHA_LOWER = '-'
        # A Special Character ($%^;... etc)
        SPECIAL = 's'
        # A Numerical Character (1234... etc)
        NUMERIC = 'n'

    if not (isinstance(word, str) and word.strip()):
        # not a password if it's not something we even support
        return word

    # Formatting
    word = word.strip()
    if force:
        # We're forcing the representation to be a secret
        # We do this for consistency
        return '{}...{}'.format(word[0:1], word[-1:])

    elif len(word) > 1 and \
            not is_hostname(word, ipv4=True, ipv6=True, underscore=False):
        # Verify if it is a hostname or not
        return '{}...{}'.format(word[0:1], word[-1:])

    elif len(word) >= 16:
        # an IP will be 15 characters so we don't want to use a smaller
        # value then 16 (e.g 101.102.103.104)
        # we can assume very long words are passwords otherwise
        return '{}...{}'.format(word[0:1], word[-1:])

    if advanced:
        #
        # Mark word a secret based on it's obscurity
        #

        # Our variances will increase depending on these variables:
        last_variance = None
        obscurity = 0

        for c in word:
            # Detect our variance
            if c.isdigit():
                variance = Variance.NUMERIC
            elif c.isalpha() and c.isupper():
                variance = Variance.ALPHA_UPPER
            elif c.isalpha() and c.islower():
                variance = Variance.ALPHA_LOWER
            else:
                variance = Variance.SPECIAL

            if last_variance != variance or variance == Variance.SPECIAL:
                obscurity += 1

                if obscurity >= threshold:
                    return '{}...{}'.format(word[0:1], word[-1:])

            last_variance = variance

    # Otherwise we're good; return our word
    return word


def cwe312_url(url):
    """
    This function was written to help mask secure/private information that may
    or may not be found on an Apprise URL. The idea is to not disrupt the
    structure of the previous URL too much, yet still protect the users
    private information from being logged directly to screen.

    For more detail see CWE-312 @
       https://cwe.mitre.org/data/definitions/312.html

    For example, consider the URL: http://user:password@localhost/

    When passed into this function, the return value would be:
      http://user:****@localhost/

    Since apprise allows you to put private information everywhere in it's
    custom URLs, it uses this function to manipulate the content before
    returning to any kind of logger.

    The idea is that the URL can still be interpreted by the person who
    constructed them, but not to an intruder.
    """
    # Parse our URL
    results = parse_url(url)
    if not results:
        # Nothing was returned (invalid data was fed in); return our
        # information as it was fed to us (without changing it)
        return url

    # Update our URL with values
    results['password'] = cwe312_word(results['password'], force=True)
    if not results['schema'].startswith('http'):
        results['user'] = cwe312_word(results['user'])
        results['host'] = cwe312_word(results['host'])

    else:
        results['host'] = cwe312_word(results['host'], advanced=False)
        results['user'] = cwe312_word(results['user'], advanced=False)

    # Apply our full path scan in all cases
    results['fullpath'] = '/' + \
        '/'.join([cwe312_word(x)
                 for x in re.split(
                     r'[\\/]+',
                     results['fullpath'].lstrip('/'))]) \
        if results['fullpath'] else ''

    #
    # Now re-assemble our URL for display purposes
    #

    # Determine Authentication
    auth = ''
    if results['user'] and results['password']:
        auth = '{user}:{password}@'.format(
            user=results['user'],
            password=results['password'],
        )
    elif results['user']:
        auth = '{user}@'.format(
            user=results['user'],
        )

    params = ''
    if results['qsd']:
        params = '?{}'.format(
            "&".join(["{}={}".format(k, cwe312_word(v, force=(
                k in ('password', 'secret', 'pass', 'token', 'key',
                      'id', 'apikey', 'to'))))
                      for k, v in results['qsd'].items()]))

    return '{schema}://{auth}{hostname}{port}{fullpath}{params}'.format(
        schema=results['schema'],
        auth=auth,
        # never encode hostname since we're expecting it to be a valid one
        hostname=results['host'],
        port='' if not results['port'] else ':{}'.format(results['port']),
        fullpath=results['fullpath'] if results['fullpath'] else '',
        params=params,
    )


@contextlib.contextmanager
def environ(*remove, **update):
    """
    Temporarily updates the ``os.environ`` dictionary in-place.

    The ``os.environ`` dictionary is updated in-place so that the modification
    is sure to work in all situations.

    :param remove: Environment variable(s) to remove.
    :param update: Dictionary of environment variables and values to
                   add/update.
    """

    # Create a backup of our environment for restoration purposes
    env_orig = os.environ.copy()
    loc_orig = locale.getlocale()
    try:
        os.environ.update(update)
        [os.environ.pop(k, None) for k in remove]
        yield

    finally:
        # Restore our snapshot
        os.environ = env_orig.copy()
        try:
            # Restore locale
            locale.setlocale(locale.LC_ALL, loc_orig)

        except locale.Error:
            # Thrown in py3.6
            pass


def apply_template(template, app_mode=TemplateType.RAW, **kwargs):
    """
    Takes a template in a str format and applies all of the keywords
    and their values to it.

    The app$mode is used to dictact any pre-processing that needs to take place
    to the escaped string prior to it being placed.  The idea here is for
    elements to be placed in a JSON response for example should be escaped
    early in their string format.

    The template must contain keywords wrapped in in double
    squirly braces like {{keyword}}.  These are matched to the respected
    kwargs passed into this function.

    If there is no match found, content is not swapped.

    """

    def _escape_raw(content):
        # No escaping necessary
        return content

    def _escape_json(content):
        # remove surounding quotes
        return json.dumps(content)[1:-1]

    # Our escape function
    fn = _escape_json if app_mode == TemplateType.JSON else _escape_raw

    lookup = [re.escape(x) for x in kwargs.keys()]

    # Compile this into a list
    mask_r = re.compile(
        re.escape('{{') + r'\s*(' + '|'.join(lookup) + r')\s*'
        + re.escape('}}'), re.IGNORECASE)

    # we index 2 characters off the head and 2 characters from the tail
    # to drop the '{{' and '}}' surrounding our match so that we can
    # re-index it back into our list
    return mask_r.sub(lambda x: fn(kwargs[x.group()[2:-2].strip()]), template)


def remove_suffix(value, suffix):
    """
    Removes a suffix from the end of a string.
    """
    return value[:-len(suffix)] if value.endswith(suffix) else value


def dict_full_update(dict1, dict2):
    """
    Takes 2 dictionaries (dict1 and dict2) that contain sub-dictionaries and
    gracefully merges them into dict1.

    This is similar to: dict1.update(dict2) except that internal dictionaries
    are also recursively applied.
    """
    def _merge(dict1, dict2):
        for k in dict2:
            if k in dict1 and isinstance(dict1[k], dict) \
                    and isinstance(dict2[k], dict):
                _merge(dict1[k], dict2[k])
            else:
                dict1[k] = dict2[k]

    _merge(dict1, dict2)
    return