-
Notifications
You must be signed in to change notification settings - Fork 3
/
QuantumENDEC.py
2437 lines (2152 loc) · 112 KB
/
QuantumENDEC.py
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
# This is QuantumENDEC, devloped by ApatheticDELL alongside Aaron and BunnyTub
QuantumENDEC_Version = "QuantumENDEC v5 source"
XMLhistory_Folder = "./history"
XMLqueue_Folder = "./queue"
Assets_Folder = "./assets" # contains all webserver files (html, css) and audio files for EAS
Tmp_Folder = "./assets/tmp"
Config_File = "./config.json"
QuantumStatus = 0
# 0 = Normal
# 1 = Restart
# 2 = Shutdown
def QEinterrupt():
global QuantumStatus
if QuantumStatus != 0: return True
return False
try: import pythoncom
except: pass
import re
import pyttsx3
import requests
import shutil
import time
import socket
import threading
import json
import os
import argparse
import base64
import subprocess
import importlib
import signal
import sounddevice as sd
from scipy.io import wavfile
from datetime import datetime, timezone, timedelta
from urllib.request import Request, urlopen
from pydub import AudioSegment
from EASGen import EASGen
from EAS2Text import EAS2Text
try:
import matplotlib
import matplotlib.pyplot as plt
#from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
from matplotlib.lines import Line2D
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.io.shapereader as shpreader
MapGenAvil = True
except Exception as e:
print("Alert map generation will not be available due to an import error: ", e)
MapGenAvil = False
import smtplib
from discord_webhook import DiscordWebhook, DiscordEmbed
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import random
import string
import sys
import queue
import wave
import contextlib
import ffmpeg
import soundfile as sf
from scipy.fft import *
import numpy
assert numpy
from flask import Flask, request, jsonify, send_from_directory, redirect, url_for, make_response, session
import hashlib, secrets, logging
CapCatToSameOrg = { "Met": "WXR", "Admin": "EAS", "Other": "CIV", }
SameOrgToCapCat = { "WXR":"Met", "EAS":"Admin", "CIV":"Other" }
CapEventToSameEvent = {
"911Service": "TOE",
"accident": "CDW",
"admin":"ADR",
"aircraftCras":"LAE",
"airportClose":"ADR",
"airQuality":"SPS",
"airspaceClos":"ADR",
"amber":"CAE",
"ambulance":"LAE",
"animalDang":"CDW",
"animalDiseas":"CDW",
"animalFeed":"CEM",
"animalHealth":"CEM",
"arcticOut":"SVS",
"avalanche":"AVW",
"aviation":"LAE",
"biological":"BHW",
"blizzard":"BZW",
"bloodSupply":"LAE",
"blowingSnow":"WSW",
"bridgeClose":"LAE",
"cable":"ADR",
"chemical":"CHW",
"civil":"CEM",
"civilEmerg":"CEM",
"civilEvent":"CEM",
"cold":"SVS",
"coldWave":"SVS",
"crime":"CDW",
"damBreach":"DBW",
"damOverflow":"DBW",
"dangerPerson":"CDW",
"diesel":"LAE",
"drinkingWate":"CWW",
"dustStorm":"DSW",
"earthquake":"EQW",
"electric":"POS",
"emergFacil":"CEM",
"emergSupport":"CEM",
"explosive":"HMW",
"facility":"CEM",
"fallObject":"HMW",
"fire":"FRW",
"flashFlood":"FFW",
"flashFreeze":"FSW",
"flood":"FLW",
"fog":"SPS",
"foodSupply":"LAE",
"forestFire":"WFW",
"freezeDrzl":"WSW",
"freezeRain":"WSW",
"freezngSpray":"WSW",
"frost":"SPS",
"galeWind":"HWW",
"gasoline":"LAE",
"geophyiscal":"CEM",
"hazmat":"BHW",
"health":"BHW",
"heat":"SVS",
"heatHumidity":"SVS",
"heatingOil":"LAE",
"heatWave":"SVS",
"highWater":"SVS",
"homeCrime":"CEM",
"hospital":"LAE",
"hurricane":"HUW",
"hurricFrcWnd":"HUW",
"ice":"SPS",
"iceberg":"IBW",
"icePressure":"SPS",
"industCrime":"CEM",
"industryFire":"IFW",
"infectious":"DEW",
"internet":"ADR",
"lahar":"VOW",
"landslide":"LSW",
"lavaFlow":"VOW",
"magnetStorm":"CDW",
"marine":"SMW",
"marineSecure":"SMW",
"meteor":"CDW",
"missingPer":"MEP",
"missingVPer":"MEP",
"naturalGas":"LAE",
"nautical":"ADR",
"notam":"ADR",
"other":"CEM",
"overflood":"FLW",
"plant":"LAE",
"plantInfect":"LAE",
"product":"LAE",
"publicServic":"LAE",
"pyroclasFlow":"VOW",
"pyroclaSurge":"VOW",
"radiological":"RHW",
"railway":"LAE",
"rainfall":"SPS",
"rdCondition":"LAE",
"reminder":"CEM",
"rescue":"CEM",
"retailCrime":"CEM",
"road":"LAE",
"roadClose":"ADR",
"roadDelay":"ADR",
"roadUsage":"ADR",
"rpdCloseLead":"ADR",
"satellite":"ADR",
"schoolBus":"ADR",
"schoolClose":"ADR",
"schoolLock":"CDW",
"sewer":"LAE",
"silver":"CEM",
"snowfall":"WSW",
"snowSquall":"WSW",
"spclIce":"SPS",
"spclMarine":"SMW",
"squall":"SMW",
"storm":"SVS",
"stormFrcWnd":"SVS",
"stormSurge":"SSW",
"strongWind":"HWW",
"telephone":"LAE",
"temperature":"SPS",
"terrorism":"CDW",
"testMessage":"DMO",
"thunderstorm":"SVR",
"tornado":"TOR",
"traffic":"ADR",
"train":"ADR",
"transit":"ADR",
"tropStorm":"TRW",
"tsunami":"TSW",
"urbanFire":"FRW",
"utility":"ADR",
"vehicleCrime":"CEM",
"volcanicAsh":"VOW",
"volcano":"VOW",
"volunteer":"ADR",
"waste":"ADR",
"water":"ADR",
"waterspout":"SMW",
"weather":"SPS",
"wildFire":"FRW",
"wind":"HWW",
"windchill":"SPS",
"winterStorm":"WSW"
}
def CheckFolder(dir, Clear=False):
if not os.path.exists(dir): os.makedirs(dir)
else:
if Clear is True:
for f in os.listdir(dir): os.remove(os.path.join(dir, f))
def CheckConfigVersion(InputConfig):
try:
if InputConfig['version'] == QuantumENDEC_Version: return True
else: return False
except: return False
def createDefaultConfig():
NewConfig = {
"version": QuantumENDEC_Version,
"WebserverHost": "0.0.0.0",
"WebserverPort": "8050",
"PlayoutNoSAME": False,
"relay_en": True,
"relay_fr": False,
"Force120": False,
"AttentionTone": "AttnCAN.wav",
"Attn_BasedOnCountry": False,
"SAME_callsign": "QUANTUM0",
"SAME_ORGallowed": [],
"SAME_EVENTallowed": [],
"SAME_EVENTblocked": [],
"SAME_FIPSfilter": [],
"CGENcolor_warning": "ff2a2a",
"CGENcolor_watch": "ffcc00",
"CGENcolor_advisory": "00aa00",
"CGEN_ClearAfterAlert": False,
"ProduceImages": False,
"SkipMap":False,
"enable_discord_webhook": False,
"webhook_author_name": "",
"webhook_author_URL": "",
"webhook_author_iconURL": "",
"webhook_URL": "",
"webhook_sendAudio": False,
"enable_email": False,
"FancyHTML": False,
"email_server": "",
"email_server_port": "587",
"email_user": "",
"email_user_pass": "",
"email_sendto": [],
"enable_LogToTxt": True,
"UseSpecified_AudioOutput": False,
"Specified_AudioOutput": "",
"EnablePassThru": False,
"UseSpecified_Passthrough_AudioInput": False,
"Passthrough_AudioInput": "",
"UseDefaultVoices": True,
"TTS_Service": "pyttsx3",
"VoiceEN": "",
"VoiceFR": "",
"FliteVoice_EN": "",
"FliteVoice_FR": "",
"statusTest": True,
"statusActual": True,
"messagetypeAlert": True,
"messagetypeUpdate": True,
"messagetypeCancel": True,
"messagetypeTest": True,
"severityExtreme": True,
"severitySevere": True,
"severityModerate": True,
"severityMinor": True,
"severityUnknown": True,
"urgencyImmediate": True,
"urgencyExpected": True,
"urgencyFuture": True,
"urgencyPast": True,
"urgencyUnknown": True,
"AllowedLocations_Geocodes": [],
"TCP": False,
"TCP1": "streaming1.naad-adna.pelmorex.com:8080",
"TCP2": "streaming2.naad-adna.pelmorex.com:8080",
"HTTP_CAP": False,
"HTTP_CAP_ADDR": "",
"HTTP_CAP_ADDR1": "",
"HTTP_CAP_ADDR2": "",
"HTTP_CAP_ADDR3": "",
"HTTP_CAP_ADDR4": "",
"Enable_NWSCAP": False,
"NWSCAP_AtomLink": "https://api.weather.gov/alerts/active.atom",
"SAME-AudioDevice-Monitor": False,
"SAME_AudioStream_Monitors": False,
"SAME-AudioStream-Monitor1": "",
"SAME-AudioStream-Monitor2": "",
"SAME-AudioStream-Monitor3": "",
"SAME-AudioStream-Monitor4": ""
}
try:
with open(Config_File, 'w') as json_file: json.dump(NewConfig, json_file, indent=2)
except: return False
return True
def DuplicateSAME(ZCZC):
"""Returns True if there is a Duplicate SAME header (if header was already transmitted)"""
file = f"{Tmp_Folder}/SameHistory.txt"
try:
with open(file, "r") as f:
content = f.read()
if ZCZC in content: return True
except:
with open(file, "a") as f: f.write(f"ZXZX-STARTER-\n")
with open(file, "a") as f: f.write(f"{ZCZC}\n")
return False
def Setup():
CheckFolder(XMLhistory_Folder, True)
CheckFolder(XMLqueue_Folder, True)
CheckFolder(Assets_Folder, False)
CheckFolder(Tmp_Folder, True)
CheckFolder(f"{Assets_Folder}/stats", True)
UpdateCGEN("000000", "EMERGENCY ALERT DETAILS", "", False)
if os.path.isfile(f"{Assets_Folder}/alertlog.txt") is True: pass
else:
with open(f"{Assets_Folder}/alertlog.txt", "w", encoding='utf-8') as f: f.write("")
with open(f"{Tmp_Folder}/SameHistory.txt", "w") as f: f.write(f"ZXZX-STARTER-\n")
if os.path.isfile(Config_File) is True:
with open(Config_File, "r") as JCfile: config = JCfile.read()
ConfigData = json.loads(config)
if CheckConfigVersion(ConfigData) is False: print(f"<<ATTENTION!>> Your configuration file is out of date! Go to the web interface and save (overwrite) a new one, or delete the current configuration file ({Config_File}).")
else:
if createDefaultConfig() is True: pass
else: print("Error, failed to create default config file, QuantumENDEC can't run without a config file!"); exit()
if os.path.isfile(f"./{Assets_Folder}/GeoToCLC.csv") is True: pass
else: print("The GeoToCLC CSV file is missing, you don't have to worry about this if you're not using Canada's CAP and relaying in S.A.M.E. If you are using Canada's CAP and relaying in S.A.M.E, all CAP-CP alerts will have a 000000 location (FIPS/CLC) code.")
def UpdateStatus(service, content):
try:
with open(f"{Assets_Folder}/stats/{service}_status.txt", "w") as f: f.write(content)
except: pass
def DeconstructSAME(SAMEheader):
try:
SAME = SAMEheader.split("+")
Section1 = SAME[0].split("-", 3)
Section2 = SAME[1].split("-")
OrginatorCode = Section1[1]
EventCode = Section1[2]
LocationCodes = Section1[3].split("-")
PurgeTime = Section2[0]
date = Section2[1][:3]
hour = Section2[1][3:5]
minute = Section2[1][5:]
IssueDate = {"date":date, "hour":hour, "minute":minute}
Callsign = Section2[2]
SAMEdata = {
"OrginatorCode":OrginatorCode,
"EventCode":EventCode,
"LocationCodes":LocationCodes,
"PurgeTime":PurgeTime,
"Issue":IssueDate,
"Callsign":Callsign }
return SAMEdata
except: return None
def Plugins_Run(mode=None, ZCZC=None, BROADCASTTEXT=None, XML=None):
"""Run modes: startup, beforeRelay, afterRelay"""
# Execute plugin with: GeneratedHeader, BroadcastText, InfoXML
pluginFolder = "plugins"
ZCZC = str(ZCZC).replace("\n","")
BROADCASTTEXT = str(BROADCASTTEXT).replace("\n"," ")
XML = str(XML).replace("\n"," ")
if os.path.exists(pluginFolder) and mode is not None:
print("Attempting to run plugins...")
pluginList = os.listdir(pluginFolder)
for plug in pluginList:
if ".py" in plug:
plug = plug.replace(".py", "")
plug = f"{pluginFolder}.{plug}"
try:
print("Running plugin: ", plug)
module = importlib.import_module(plug)
if mode == "beforeRelay": module.ExecutePlugin_BeforeRelay(ZCZC, BROADCASTTEXT, XML)
elif mode == "afterRelay": module.ExecutePlugin_AfterRelay(ZCZC, BROADCASTTEXT, XML)
elif mode == "startup": module.ExecutePlugin_OnStart()
except Exception as e: print(f"{plug} has failed to run.", e)
def GetAlertLevelColor(ConfigData, ZCZC=None):
colEvtlist = {
"AVA": 1,
"CFA": 1,
"FFA": 1,
"FLA": 1,
"HUA": 1,
"HWA": 1,
"SSA": 1,
"SVA": 1,
"TOA": 1,
"TRA": 1,
"TSA": 1,
"WSA": 1,
"DBA": 1,
"EVA": 1,
"WFA": 1,
"AVW": 0,
"BLU": 0,
"BZW": 0,
"CDW": 0,
"CEM": 0,
"CFW": 0,
"DSW": 0,
"EAN": 0,
"EQW": 0,
"EVI": 0,
"EWW": 0,
"FFW": 0,
"FLW": 0,
"FRW": 0,
"FSW": 0,
"FZW": 0,
"HMW": 0,
"HUW": 0,
"HWW": 0,
"LEW": 0,
"NUW": 0,
"RHW": 0,
"SMW": 0,
"SPW": 0,
"SQW": 0,
"SSW": 0,
"SVR": 0,
"TOR": 0,
"TRW": 0,
"TSW": 0,
"VOW": 0,
"WSW": 0,
"BHW": 0,
"BWW": 0,
"CHW": 0,
"CWW": 0,
"DBW": 0,
"DEW": 0,
"FCW": 0,
"IBW": 0,
"IFW": 0,
"LSW": 0,
"WFW": 0,
"MEP": 0
}
if ZCZC is not None:
try:
ZCZC = ZCZC.split("-")
evnt = ZCZC[2]
if evnt in colEvtlist:
if colEvtlist[evnt] == 0: embed_color = ConfigData["CGENcolor_warning"]
elif colEvtlist[evnt] == 1: embed_color = ConfigData["CGENcolor_watch"]
else: embed_color = ConfigData["CGENcolor_advisory"]
except: embed_color = ConfigData["CGENcolor_warning"]
else: embed_color = ConfigData["CGENcolor_warning"]
return embed_color
def FilterCheck_CAP(InputConfig, AlertInfo):
# Returns True if passed
Urgency = re.search(r'<urgency>\s*(.*?)\s*</urgency>', AlertInfo, re.MULTILINE | re.IGNORECASE | re.DOTALL).group(1)
Severity = re.search(r'<severity>\s*(.*?)\s*</severity>', AlertInfo, re.MULTILINE | re.IGNORECASE | re.DOTALL).group(1)
try:
current_time = datetime.now(timezone.utc)
Expires = re.search(r'<expires>\s*(.*?)\s*</expires>', AlertInfo, re.MULTILINE | re.IGNORECASE | re.DOTALL).group(1)
Expires = datetime.fromisoformat(datetime.fromisoformat(Expires).astimezone(timezone.utc).isoformat())
if current_time > Expires: Expired = True
else: Expired = False
except: Expired = False
try: Broadcast_Immediately = re.search(r'<valueName>layer:SOREM:1.0:Broadcast_Immediately</valueName>\s*<value>\s*(.*?)\s*</value>', AlertInfo, re.MULTILINE | re.IGNORECASE | re.DOTALL).group(1)
except: Broadcast_Immediately = "no"
if "yes" in Broadcast_Immediately.lower(): Broadcast_Immediately = True
else: Broadcast_Immediately = False
# To check the 'CAP-CP Geocodes' - not for FIPS/CLC
if len(InputConfig['AllowedLocations_Geocodes']) == 0: GecodeResult = True
else:
GecodeResult = False
try:
GeocodeList = re.findall(r'<geocode>\s*<valueName>profile:CAP-CP:Location:0.3</valueName>\s*<value>\s*(.*?)\s*</value>', AlertInfo, re.MULTILINE | re.IGNORECASE | re.DOTALL)
for i in GeocodeList:
if i[:2] in InputConfig['AllowedLocations_Geocodes']: GecodeResult = True
if i[:3] in InputConfig['AllowedLocations_Geocodes']: GecodeResult = True
if i[:4] in InputConfig['AllowedLocations_Geocodes']: GecodeResult = True
if i in InputConfig['AllowedLocations_Geocodes']: GecodeResult = True
except: GecodeResult = True
try:
Language = re.search(r'<language>\s*(.*?)\s*</language>', AlertInfo, re.MULTILINE | re.IGNORECASE | re.DOTALL).group(1)
Language = Language.lower()
if "fr-ca" in Language: Language = "fr"
elif "en-ca" in Language or "en-us" in Language: Language = "en"
else: Language = "NOT_SUPPORTED"
Language_Result = ConfigData[f"relay_{Language}"]
except:
Language_Result = False
print("<< Filter Check (CAP) >>")
print("Severity: ", InputConfig[f"severity{Severity}"])
print("Urgency: ", InputConfig[f"urgency{Urgency}"])
print("Broadcat Immedately (CAP-CP only): ", Broadcast_Immediately)
print("Geocode result (CAP-CP only): ", GecodeResult)
print("Language result: ", Language_Result)
print("Expired: ", Expired)
if ((InputConfig[f"severity{Severity}"] and InputConfig[f"urgency{Urgency}"]) or Broadcast_Immediately) and GecodeResult and Language_Result and not Expired: print("Final result: Pass")
else: print("Final result: Failed... alert will be skipped.")
return ((InputConfig[f"severity{Severity}"] and InputConfig[f"urgency{Urgency}"]) or Broadcast_Immediately) and GecodeResult and Language_Result and not Expired
def FilterCheck_SAME(ConfigData, ZCZC):
"""Returns True if the filter matches alert"""
SAME_DICT = DeconstructSAME(ZCZC)
EVENT = SAME_DICT['EventCode']
if "EAN" in EVENT or "NIC" in EVENT or "NPT" in EVENT or "RMT" in EVENT or "RWT" in EVENT:
EventAllowed = True
EventBlocked = False # EventBlocked will be True if an event is blocked
else:
if len(ConfigData['SAME_EVENTblocked']) == 0: EventBlocked = False
else:
if EVENT in ConfigData['SAME_EVENTblocked']: EventBlocked = True
else: EventBlocked = False
if len(ConfigData['SAME_EVENTallowed']) == 0: EventAllowed = True
else:
if EVENT in ConfigData['SAME_EVENTallowed']: EventAllowed = True
else: EventAllowed = False
if len(ConfigData['SAME_ORGallowed']) == 0: OrgiResult = True
else:
if SAME_DICT['OrginatorCode'] in ConfigData['SAME_ORGallowed']: OrgiResult = True
else: OrgiResult = False
if len(ConfigData['SAME_FIPSfilter']) == 0: LocationResult = True
else:
LocationResult = False
for i in SAME_DICT['LocationCodes']:
# Partial county wildcard filter
partial = "*" + i[1:]
if partial[:2] in ConfigData['SAME_FIPSfilter']: LocationResult = True
if partial[:3] in ConfigData['SAME_FIPSfilter']: LocationResult = True
if partial[:4] in ConfigData['SAME_FIPSfilter']: LocationResult = True
if partial in ConfigData['SAME_FIPSfilter']: LocationResult = True
if i[:2] in ConfigData['SAME_FIPSfilter']: LocationResult = True
if i[:3] in ConfigData['SAME_FIPSfilter']: LocationResult = True
if i[:4] in ConfigData['SAME_FIPSfilter']: LocationResult = True
if i in ConfigData['SAME_FIPSfilter']: LocationResult = True
print("<< Filter check (S.A.M.E) >>")
print("Originator result: ", OrgiResult)
print("Location code result: ", LocationResult)
print("Event code allowed: ", EventAllowed)
print("Event code blocked: ", EventBlocked)
if (OrgiResult and LocationResult and EventAllowed) and not EventBlocked: print("Final result: pass")
else: print("Final result: fail... alert will be skipped.")
return (OrgiResult and LocationResult and EventAllowed) and not EventBlocked
def WatchNotify(ListenFolder, HistoryFolder):
print(f"Waiting for an alert...")
while QEinterrupt() is False:
ExitTicket = False
QueueList = os.listdir(f"{ListenFolder}")
for file in QueueList:
with open(f"{ListenFolder}/{file}", "r", encoding='UTF-8') as f: RelayXML = f.read()
AlertListXML = re.findall(r'<alert\s*(.*?)\s*</alert>', RelayXML, re.MULTILINE | re.IGNORECASE | re.DOTALL)
if len(AlertListXML) > 1:
print("WHY THE F*** IS THERE 2 ALERT ELEMENTS IN A SINGLE XML FILE?!!?")
AlertCount = 0
for AlertXML in AlertListXML:
AlertCount = AlertCount + 1
print("Alert", AlertCount)
Sent = re.search(r'<sent>\s*(.*?)\s*</sent>', AlertXML, re.MULTILINE | re.IGNORECASE | re.DOTALL).group(1).replace("-", "_").replace("+", "p").replace(":", "_").replace("\n", "")
Ident = re.search(r'<identifier>\s*(.*?)\s*</identifier>', AlertXML, re.MULTILINE | re.IGNORECASE | re.DOTALL).group(1).replace("-", "_").replace("+", "p").replace(":", "_").replace("\n", "")
NAADsFilename = f"{Sent}I{Ident}.xml"
AlertXML = f"<alert {AlertXML}</alert>"
with open(f"{ListenFolder}/{NAADsFilename}", 'w', encoding='utf-8') as f: f.write(AlertXML)
os.remove(f"{ListenFolder}/{file}")
elif file in os.listdir(f"{HistoryFolder}"):
print("No relay: watch folder files matched.")
os.remove(f"{ListenFolder}/{file}")
ExitTicket = False
else:
ExitTicket = True
break
if ExitTicket is True: break
else: time.sleep(1) # Wait a little bit between looking for new files
if QEinterrupt() is False: return file
def Heartbeat(References, QueueFolder, HistoryFolder):
print("Downloading (Pelmorex NAADs) alerts from received heartbeat...")
RefList = References.split(" ")
for i in RefList:
j = re.sub(r'^.*?,', '', i)
j = j.split(",")
sent = j[1]
sentDT = sent.split("T", 1)[0]
sent = sent.replace("-","_").replace("+", "p").replace(":","_")
identifier = j[0]
identifier = identifier.replace("-","_").replace("+", "p").replace(":","_")
Dom1 = 'capcp1.naad-adna.pelmorex.com'
Dom2 = 'capcp2.naad-adna.pelmorex.com'
Output = f"{QueueFolder}/{sent}I{identifier}.xml"
if f"{sent}I{identifier}.xml" in os.listdir(f"{HistoryFolder}"):
print("Heartbeat, no download: Files matched.")
else:
print(f"Downloading: {sent}I{identifier}.xml...")
req1 = Request(url = f'http://{Dom1}/{sentDT}/{sent}I{identifier}.xml', headers={'User-Agent': 'Mozilla/5.0'})
req2 = Request(url = f'http://{Dom2}/{sentDT}/{sent}I{identifier}.xml', headers={'User-Agent': 'Mozilla/5.0'})
try: xml = urlopen(req1).read()
except:
try: xml = urlopen(req2).read()
except: pass
try:
with open(Output, "wb") as f: f.write(xml)
except: print("Heartbeat, download aborted: a general exception occurred, it could be that the URLs are temporarily unavailable.")
def UpdateCGEN(color="000000", headline="", text="", stat=True):
try:
CGEN_Dict = { "color": color, "headline": headline, "text": text, "alertStat": stat }
with open(f"{Assets_Folder}/AlertText.json", 'w') as json_file: json.dump(CGEN_Dict, json_file, indent=2)
except: pass
def ConvertAudioFormat(inputAudio, outputAudio):
result = subprocess.run(["ffmpeg", "-y", "-i", inputAudio, outputAudio], capture_output=True, text=True)
if result.returncode == 0: print(f"{inputAudio} --> {outputAudio} ... Conversion successful!")
else: print(f"{inputAudio} --> {outputAudio} ... Conversion failed: {result.stderr}")
def LoudenAudio(inputAudio, outputAudio):
result = subprocess.run(["ffmpeg", "-y", "-i", inputAudio, "-filter:a", "volume=2.5", outputAudio], capture_output=True, text=True)
if result.returncode == 0: print(f"Filter loudening success.")
else: print(f"Filter loudening failure: {result.stderr}")
def GenerateTTS(Output, InputConfig=None, InputText=None, Language="EN"):
# This function will generate TTS and output it to an audio file.
try: os.remove(Output)
except: pass
try: pythoncom.CoInitialize()
except: pass
if InputConfig["TTS_Service"] == "pyttsx3":
engine = pyttsx3.init()
if InputConfig["UseDefaultVoices"] is False:
if Language == "FR": ActiveVoice = InputConfig["VoiceFR"]
else: ActiveVoice = InputConfig["VoiceEN"]
voices = engine.getProperty('voices')
ActiveVoice = next((voice for voice in voices if voice.name == ActiveVoice), None)
if ActiveVoice: engine.setProperty('voice', ActiveVoice.id)
engine.save_to_file(str(InputText), Output)
engine.runAndWait()
# i don't like the execution of this... maybe let the end user just setup a custom TTS in plugins!
elif InputConfig["TTS_Service"] == "flite":
InputText = InputText.replace("\n", " ")
if InputConfig["UseDefaultVoices"] is False:
if Language == "FR": ActiveVoice = InputConfig["FliteVoice_FR"]
else: ActiveVoice = InputConfig["FliteVoice_EN"]
subprocess.run(["flite", "-t", InputText, "-voice", ActiveVoice, "-o", Output], capture_output=True, text=True)
else: subprocess.run(["flite", "-t", InputText, "-o", Output], capture_output=True, text=True)
def EventSuffix(EventIn):
target_words = {"test", "watch", "warning", "alert", "emergency", "notification"}
words = EventIn.split()
if words:
last_word = words[-1].lower()
return last_word in target_words
return False
def TrimAudio(input_file, max_duration_ms=120000):
# For broadcast audio
output_file = input_file + ".trimmed"
audio = AudioSegment.from_file(input_file)
duration_ms = len(audio)
if duration_ms > max_duration_ms:
trimmed_audio = audio[:max_duration_ms]
trimmed_audio.export(output_file, format="wav")
print(f"Broadcast Audio trimmed to {max_duration_ms / 1000} seconds.")
shutil.move(output_file, input_file)
else: pass
# Actual, Update, Cancel, Test
MsgTypeConv = {
"EN":{ "Alert":"has issued", "Update":"has updated", "Cancel":"has ended", "Test":"has issued" },
"FR":{ "Alert":"a émis", "Update":"a mis à jour", "Cancel":"est terminé", "Test":"a émis" }
}
def GeoToCLC(InfoXML):
GeocodeList = re.findall(r'<geocode>\s*<valueName>profile:CAP-CP:Location:0.3</valueName>\s*<value>\s*(.*?)\s*</value>', InfoXML, re.MULTILINE | re.IGNORECASE | re.DOTALL)
filepath = f"{Assets_Folder}/GeoToCLC.csv"
SameDict = {}
try:
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
line = line.replace('\n', '')
SAMESPLIT = line.split(",")
SameDict[SAMESPLIT[0]] = SAMESPLIT[1]
line = fp.readline()
cnt += 1
except: return "000000"
CLC = ""
for i in GeocodeList:
try: C = SameDict[i]
except: C = ""
if C == "": pass
else: CLC = f"{CLC}" + f"{C},"
# Aaron i know you're kinda gonna cringe at this, but we need it
CLC = "".join(CLC.rsplit(",",1))
CLC = CLC.split(",")
CLC = "-".join(CLC)
CLC = CLC.split("-")
CLC = list(set(CLC))
CLC = "-".join(CLC)
return CLC
def GetMedia(InputSource, OutputAudio, DecodeType):
if DecodeType == 1:
print("Decoding media from BASE64...")
with open(OutputAudio, "wb") as fh: fh.write(base64.decodebytes(InputSource))
elif DecodeType == 0:
print("Downloading media...")
r = requests.get(InputSource)
with open(OutputAudio, 'wb') as f: f.write(r.content)
def GetAlertRegion(XML):
# Get the alert region of CAP XML
try:
CODE = re.findall(r'<code>\s*(.*?)\s*</code>', XML, re.MULTILINE | re.IGNORECASE | re.DOTALL)
if "profile:CAP-CP:0.4" in str(CODE): CODE = "CANADA"
elif "IPAWSv1.0" in str(CODE): CODE = "USA"
else: CODE = None
return CODE
except: return None
def CreateSAMEmonitorXML(SAME, audioInput, monitorName):
try:
SAME = SAME.replace("\n", "")
oof = EAS2Text(SAME)
sent = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S-00:00')
sent_rp = sent.replace("-","").replace(":","")
ident_code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
ident = f"{sent_rp}{ident_code}"
output = f"{XMLqueue_Folder}/{monitorName}-{sent_rp}I{ident}.xml"
current_time = datetime.strptime(sent, "%Y-%m-%dT%H:%M:%S-00:00")
try: hours, minutes = map(int, oof.purge)
except: hours, minutes = map(int, ['01','30'])
expiry_time = current_time + timedelta(hours=hours, minutes=minutes)
expiry_timestamp = expiry_time.strftime("%Y-%m-%dT%H:%M:%S-00:00")
monitorName = monitorName.replace("\n", "")
try: Cate = SameOrgToCapCat[oof.org]
except: Cate = "Other"
FIPs = "-".join(oof.FIPS)
try:
with open(audioInput, 'rb') as wav_file: wav_data = wav_file.read()
encoded_data = base64.b64encode(wav_data).decode('utf-8')
embedded_audio = f"""
<resource>
<resourceDesc>broadcast audio</resourceDesc>
<mimeType>audio/wave</mimeType>
<derefUri>{encoded_data}</derefUri>
</resource>
"""
except: embedded_audio = ""
XML = f"""
<alert>
<identifier>{ident}</identifier>
<sender>{monitorName}</sender>
<sent>{sent}</sent>
<status>Actual</status>
<msgType>Alert</msgType>
<source>QuantumENDEC Internal Monitor</source>
<scope>Public</scope>
<info>
<language>en-US</language>
<category>{Cate}</category>
<event>{oof.evntText}</event>
<responseType>Monitor</responseType>
<urgency>Immediate</urgency>
<severity>Extreme</severity>
<certainty>Observed</certainty>
<eventCode><valueName>SAME</valueName><value>{oof.evnt}</value></eventCode>
<effective>{sent}</effective>
<expires>{expiry_timestamp}</expires>
<senderName>{oof.orgText}</senderName>
<headline>{oof.evntText}</headline>
<description>From {oof.callsign}</description>
{embedded_audio}
<parameter><valueName>EAS-ORG</valueName><value>{oof.org}</value></parameter>
<area><areaDesc>{oof.strFIPS}</areaDesc><geocode><valueName>SAME</valueName><value>{FIPs}</value></geocode></area>
</info>
</alert>
"""
with open(output, "w") as f: f.write(XML)
except: pass
def GetPlatform():
if sys.platform == "win32": platform = "win"
else: platform = "other"
return platform
def get_len(fname):
with contextlib.closing(wave.open(fname,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
return duration
def freq(file, start_time, end_time):
sr, data = wavfile.read(file)
if data.ndim > 1: data = data[:, 0]
else: pass
dataToRead = data[int(start_time * sr / 1000) : int(end_time * sr / 1000) + 1]
N = len(dataToRead)
yf = rfft(dataToRead)
xf = rfftfreq(N, 1 / sr)
idx = numpy.argmax(numpy.abs(yf)) # Get the most dominant frequency and return it
freq = xf[idx]
return freq
def RemoveEOMpATTN(AudioFile):
try:
# Remove END (EOMs)
# audio = AudioSegment.from_file(f"Audio/tmp/{moniName}out.wav")
audio = AudioSegment.from_file(AudioFile)
lengthaudio = len(audio)
start = 0
threshold = lengthaudio - 1200
end = 0
counter = 0
end += threshold
chunk = audio[start:end]
filename = f"{AudioFile}.rmend"
chunk.export(filename, format="wav")
counter +=1
start += threshold
except: pass
try:
# Remove attention tone
timelist = []
freqlist = []
ATTNCUT = 0
file_length = get_len(f"{AudioFile}.rmend")
if file_length < 23: file_length = round(file_length)
else: file_length = 80
cnt = 0
for e in range(file_length):
cnt = cnt + 1
val = 300
start = e * val
offset = start + val
timelist.append(start)
frequency = freq(f"{AudioFile}.rmend", start, offset)
freqlist.append(frequency)
freqlist = list(freqlist)
mainlen = len(freqlist)
found = False
for e in range(len(freqlist)):
if found == False:
if 810 < round(int(freqlist[e])) < 1070:
if 810 < round(int(freqlist[e + 1])) < 1070 and 810 < round(int(freqlist[e + 2])) < 1070:
found = True
elif found == True:
if freqlist[e] < 810 or freqlist[e] > 1070:
if e + 5 < mainlen:
if freqlist[e + 1] < 810 or freqlist[e + 1] > 1070 and freqlist[e + 2] < 810 or freqlist[e + 2] > 1070 and freqlist[e + 3] < 810 or freqlist[e + 3] > 1070 and freqlist[e + 4] < 810 or freqlist[e + 4] > 1070 and freqlist[e + 5] < 810 or freqlist[e + 5] > 1070:
end_point = e
found = None
if(found == None): pass
else:
gl = round(get_len(f"{AudioFile}.rmend"))
if(gl > 4): end_point = 17 #5 seconds
else: end_point = gl // 2
audio = AudioSegment.from_file(f"{AudioFile}.rmend")
lengthaudio = len(audio)
cut = 300 * end_point
start = cut
threshold = lengthaudio - cut
end = lengthaudio
counter = 0
shutil.move(AudioFile, f"{AudioFile}.backup")
while start < len(audio):
end += threshold
chunk = audio[start:end]
chunk.export(AudioFile, format="wav")
counter +=1
start += threshold
os.remove(f"{AudioFile}.backup")
except Exception as e:
print("Error in removing the attention tone or EOM header: ", e)
shutil.move(f"{AudioFile}.backup", AudioFile)
def ZCZC_test(inp):
inp = inp.split("-")
num = len(inp) - 6
if len(inp[num + 3]) != 7: return False
elif len(inp[num + 4]) != 8: return False
elif len(inp[0]) != 4: return False #ZCZC
elif len(inp[1]) != 3: return False #"EAS"
elif len(inp[2]) != 3: return False #"DMO"
if num == 1 and len(inp[3]) == 11: return True
elif num > 1:
for e in range(num):
if (e + 1) == num:
if len(inp[e+3]) == 11: return True
else: return False
elif len(inp[e+3]) != 6: return False
else: return False
class Webserver:
def __init__(self):
self.QEWEB_flaskapp = Flask(__name__)
self.setup_routes()
self.QEWEB_flaskapp.secret_key = secrets.token_hex(16)
self.PASSWORD_FILE = './password.json'
self.SESSION_COOKIE_NAME = 'session_id'
self.SESSIONS = {}
self.DEFAULT_PASSWORD_HASH = hashlib.sha256('hackme'.encode()).hexdigest()
def save_password(self, password_hash):
with open(self.PASSWORD_FILE, 'w') as file: json.dump({'password': password_hash}, file)
def get_audio_devices(self):
devices = sd.query_devices()
output_devices = [device for device in devices if device['max_output_channels'] > 0]
return [f"{device['name']}, {sd.query_hostapis()[device['hostapi']]['name']}" for device in output_devices]
def get_audio_inputs(self):
devices = sd.query_devices()
input_devices = [device for device in devices if device['max_input_channels'] > 0]
return [f"{device['name']}, {sd.query_hostapis()[device['hostapi']]['name']}" for device in input_devices]
def list_tts_voices(self):
try:
try: pythoncom.CoInitialize()
except: pass
engine = pyttsx3.init()
voices = engine.getProperty('voices')
return [voice.name for voice in voices]
except Exception as e: print("[Webserver]: Exception getting the list of TTS voices (pyttsx3): ", e)
def load_config(self):
try:
with open(Config_File, 'r') as file: return json.load(file)
except FileNotFoundError: return {}