-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathus-faa.py
1807 lines (1325 loc) · 57.6 KB
/
us-faa.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
import csv
import os
import json
import requests
import shutil
from urllib.parse import urlparse
import zipfile
import sqlite3
import logging
import logging.handlers as handlers
import sys
from datetime import datetime
from progress.bar import Bar
import time
import hashlib
from yaspin import yaspin
from bson.objectid import ObjectId
import mysql.connector #pip3 install mysql-connector-python
import argparse
###################
# Content below for restricting TLS 1.3
###################
import ssl
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
from requests.packages.urllib3.util import ssl_
class TlsAdapter(HTTPAdapter):
def __init__(self, ssl_options=0, **kwargs):
self.ssl_options = ssl_options
super(TlsAdapter, self).__init__(**kwargs)
def init_poolmanager(self, *pool_args, **pool_kwargs):
ctx = ssl_.create_urllib3_context(cert_reqs=ssl.CERT_REQUIRED, options=self.ssl_options)
self.poolmanager = PoolManager(*pool_args, ssl_context=ctx, **pool_kwargs)
###################
# End TLS 1.3 Restriction
###################
# Supports extracts 2017 and later. Prior to 2017 the FAA had different column positions.
# https://registry.faa.gov/database/ReleasableAircraft.zip
def setup(args):
global logger
global applicationName
global settings
global import_sql
settings = {}
try:
filePath = os.path.dirname(os.path.realpath(__file__)) + "/"
applicationName = "FAA Registration Manager"
#Setup the logger, 10MB maximum log size
logger = logging.getLogger(applicationName)
formatter = logging.Formatter('%(asctime)s [%(levelname)s] - %(message)s')
logHandler = handlers.RotatingFileHandler(filePath + 'events.log', maxBytes=10485760, backupCount=1)
logHandler.setFormatter(formatter)
logger.addHandler(logHandler)
logger.setLevel(logging.INFO)
logger.info(applicationName + " application started.")
#Make sure the settings file exists
if os.path.exists(filePath + 'settings.json') == False:
raise Exception("Settings file does not exist. Expected file " + filePath + 'settings.json')
#Get the settings file
if os.path.exists(filePath + 'settings.json.private') == True:
with open(filePath + 'settings.json.private') as settingsFile:
settings = json.load(settingsFile)
else:
with open(filePath + 'settings.json') as settingsFile:
settings = json.load(settingsFile)
settings['filePath'] = filePath
settings['tempPath'] = os.path.join(settings['filePath'] , "tmp")
settings['download_url'] = args.download_url
#By default, do not skip the download
if "skip_download" not in settings:
settings['skip_download'] = False
if settings['skip_download'] != False:
settings['skip_download'] = True
print("Skipping file download; Will use the cached copy.")
logger.warning("Skipping file download; Will use the cached copy.")
if "mySQL" not in settings:
raise Exception("The database information (mySQL) is not populated in the settings.json file.")
if "uri" not in settings['mySQL']:
raise Exception("The database uri (mySQL -> uri) is not populated in the settings.json file.")
if "username" not in settings['mySQL']:
raise Exception("The database username (mySQL -> username) is not populated in the settings.json file.")
if "password" not in settings['mySQL']:
raise Exception("The database password (mySQL -> password) is not populated in the settings.json file.")
if "database" not in settings['mySQL']:
raise Exception("The database name (mySQL -> database) is not populated in the settings.json file.")
#Get the SQL mode, defaulting to "memory"
if 'local_database_mode' not in settings:
settings['local_database_mode'] = "memory"
if str(settings['local_database_mode']).lower() == "memory":
import_sql = sqlite3.connect(":memory:")
else:
settings['local_database_mode'] = "disk"
databaseFile = os.path.join(filePath, "us-faa-registration.db")
if os.path.exists(databaseFile):
#Delete the old database
os.remove(databaseFile)
if os.path.exists(os.path.join(filePath, "us-faa-registration.db-journal")):
#Delete the old database journal
os.remove(os.path.join(filePath, "us-faa-registration.db-journal"))
import_sql = sqlite3.connect(os.path.join(filePath, "us-faa-registration.db"))
cursor = import_sql.cursor()
#Create the temporary tables in memory
cursor.execute("CREATE TABLE aircraft (code text, manufacturer text, model text, aircraft_type text, engine_type text, category text, builder_certification text, engine_count int, seat_count int, weight text, speed int)")
cursor.execute("CREATE TABLE engines (code text, manufacturer text, model text, engine_type text, power_value int, power_type text)")
cursor.execute("CREATE TABLE registrations (registration text, serial_number text, code_aircraft text, code_engine text, manufactured_year text, registrant_type text, name text, street list, city text, state text, postal_code text, region text, country text, last_action text, certificate_issue text, certification text, operations text, aircraft_type text, engine_type text, status text, icao24_octal text, fractional_ownership text, airworthiness_date text, expiration_date text, kit_manufacturer text, kit_model text, icao24_hex text)")
except Exception as ex:
logger.error(ex)
print(ex)
exitApp(1)
def main():
try:
#Get the files
if settings['skip_download'] != True:
download()
#Import the engine file
import_engines()
#Import the aircraft file
import_aircraft()
#Import the registrations
import_registrations()
#Export the data to disk
export_data()
#Success, exit the app
exitApp()
except Exception as ex:
logger.error(ex)
print(ex)
exitApp(1)
def exitApp(exitCode=None):
if exitCode is None:
exitCode = 0
#Commit the database if it is not memory
if settings['local_database_mode'] == "disk":
logger.info("Committing database to disk.")
import_sql.commit()
#Delete the temp folder if it exists
if os.path.exists(settings['tempPath']) and exitCode == 0:
logger.info("Deleting temporary folder.")
#Delete the old temp directory
shutil.rmtree(settings['tempPath'])
if exitCode == 0:
print(applicationName + " application finished successfully.")
logger.info(applicationName + " application finished successfully.")
if exitCode != 0:
logger.info("Error; Exiting with code " + str(exitCode))
sys.exit(exitCode)
def totalLines(filename):
with open(filename) as f:
return (sum(1 for line in f)) - 1
def download():
if os.path.exists(settings['tempPath']):
#Delete the old temp directory
shutil.rmtree(settings['tempPath'])
if os.path.exists(settings['tempPath']) == False:
#Create a new, empty temp directory
os.mkdir(settings['tempPath'])
#Set the files' name
downloadFileName = os.path.basename(urlparse(settings['download_url']).path)
downloadFileDestination = os.path.join(settings['tempPath'], downloadFileName)
#Get the file from the FAA
logger.info("Beginning file download from FAA. File: " + settings['download_url'])
###################
# Content below for restricting TLS 1.3
###################
session = requests.session()
adapter = TlsAdapter(ssl.OP_NO_TLSv1_3)
session.mount("https://", adapter)
###################
# End TLS 1.3 Restriction
###################
headers = {"User-Agent":"P5Software AROI"}
with yaspin(text="Downloading file from FAA...") as spinner:
response = session.get(settings['download_url'], headers=headers)
spinner.text = "Completed file download from FAA.\n"
spinner.ok()
if response.status_code != 200:
raise Exception("Response code from download was " + str(response.status_code) + ".")
#Write the file to disk
with open(downloadFileDestination, 'wb') as downloadedFile:
downloadedFile.write(response.content)
logger.info("Completed file download from FAA.")
#Extract the file
logger.info("Extracting ZIP file.")
with zipfile.ZipFile(downloadFileDestination, 'r') as downloadedFile:
with yaspin(text="Extracting files...") as spinner:
downloadedFile.extractall(settings['tempPath'])
spinner.text = "Files extracted.\n"
spinner.ok()
logger.info("ZIP file extracted.")
#Delete the original zip file
os.remove(downloadFileDestination)
#Rename the files to be lower case, since the FAA is sometimes inconsistent
for extractedFile in os.listdir(settings['tempPath']):
os.rename(os.path.join(settings['tempPath'], extractedFile), os.path.join(settings['tempPath'], extractedFile.lower()))
#Rename the files to not have duplicate extensions, since the FAA is sometimes inconsistent
for extractedFile in os.listdir(settings['tempPath']):
if ".txt.txt" in extractedFile:
os.rename(os.path.join(settings['tempPath'], extractedFile), os.path.join(settings['tempPath'], os.path.splitext(extractedFile)[0]))
def import_engines():
engineFile = os.path.join(settings['tempPath'], "engine.txt")
logger.info("Beginning Engine Import.")
#Make sure the file exists
if os.path.exists(engineFile) == False:
raise Exception ("Engine file does not exist. Expected " + engineFile)
rowCount = totalLines(engineFile)
with open(engineFile, "r") as csvfile:
fileReader = csv.reader(csvfile)
#Skip the headers
fileReader.__next__()
with Bar("Importing Engines...", max=rowCount) as bar:
for row in fileReader:
tmpEngine = engine()
#Import data by address
tmpEngine.code = str(row[0])
tmpEngine.manufacturer = str(row[1]).strip()
tmpEngine.model = str(row[2]).strip()
tmpEngine.set_engine_type(str(row[3]).strip())
tmpEngine.set_power(int(row[4]), int(row[5]))
#Store it in the DB
tmpEngine.commit()
#Increment the bar
bar.next()
bar.message = "Done Importing Engines."
bar.finish()
logger.info("Completed Engine Import, total row count " + str(rowCount) + ".")
def import_aircraft():
aircraftFile = os.path.join(settings['tempPath'], "acftref.txt")
logger.info("Beginning Aircraft Import.")
#Make sure the file exists
if os.path.exists(aircraftFile) == False:
raise Exception ("Aircraft file does not exist. Expected " + aircraftFile)
rowCount = totalLines(aircraftFile)
with open(aircraftFile, "r") as csvfile:
fileReader = csv.reader(csvfile)
#Skip the headers
fileReader.__next__()
with Bar("Importing Aircraft...", max=rowCount) as bar:
for row in fileReader:
tmpAircraft = aircraft()
#Import data by address
tmpAircraft.code = str(row[0]).strip()
tmpAircraft.manufacturer = str(row[1]).strip()
tmpAircraft.model = str(row[2]).strip()
tmpAircraft.set_aircraft_type(str(row[3]).strip())
tmpAircraft.set_engine_type(str(int(row[4])))
tmpAircraft.set_category(str(row[5]).strip())
tmpAircraft.set_builder_certification(str(row[6]).strip())
tmpAircraft.engine_count = str(int(row[7]))
tmpAircraft.seat_count = str(int(row[8]))
tmpAircraft.set_weight(str(row[9]).strip())
tmpAircraft.speed = int(row[10])
#Store it in the DB
tmpAircraft.commit()
#Increment the bar
bar.next()
bar.finish()
logger.info("Completed Aircraft Import, total row count " + str(rowCount) + ".")
def import_registrations():
registrationFile = os.path.join(settings['tempPath'], "master.txt")
logger.info("Beginning Registration Import.")
#Make sure the file exists
if os.path.exists(registrationFile) == False:
raise Exception ("Registration file does not exist. Expected " + registrationFile)
rowCount = totalLines(registrationFile)
with open(registrationFile, "r") as csvfile:
fileReader = csv.reader(csvfile)
#Skip the headers
fileReader.__next__()
with Bar("Importing Registrations...", max=rowCount) as bar:
for row in fileReader:
#Limit the number of registrations if requested in the settings file (dev only)
if "limit" in settings:
if settings['limit'] == True:
if bar.index >= 500:
bar.finish()
break
tmpRegistration = registration()
#Import data by address
tmpRegistration.registration = "N" + str(row[0]).strip()
tmpRegistration.serial_number = str(row[1]).strip()
tmpRegistration.code_aircraft = str(row[2]).strip()
tmpRegistration.code_engine = str(row[3]).strip()
tmpRegistration.manufactured_year = str(row[4]).strip()
tmpRegistration.set_type_registrant(str(row[5]).strip())
tmpRegistration.set_name(str(row[6]).strip())
tmpRegistration.set_street(str(row[7]).strip(), str(row[8]).strip())
tmpRegistration.city = str(row[9]).strip()
tmpRegistration.state = str(row[10]).strip()
tmpRegistration.postal_code = str(row[11]).strip()
tmpRegistration.set_region(str(row[12]).strip())
tmpRegistration.country = str(row[14]).strip()
tmpRegistration.last_action = parseYYYYMMDD(str(row[15]).strip())
tmpRegistration.certificate_issue = parseYYYYMMDD(str(row[16]).strip())
tmpRegistration.set_certification(str(row[17]).strip())
tmpRegistration.set_aircraft_type(str(row[18]).strip())
tmpRegistration.set_engine_type(str(row[19]).strip())
tmpRegistration.set_status(str(row[20]).strip())
tmpRegistration.icao24_octal = str(row[21]).strip()
tmpRegistration.set_fractional_ownership(str(row[22]).strip())
tmpRegistration.airworthiness_date = parseYYYYMMDD(str(row[23]).strip())
tmpRegistration.set_name(str(row[24]).strip())
tmpRegistration.set_name(str(row[25]).strip())
tmpRegistration.set_name(str(row[26]).strip())
tmpRegistration.set_name(str(row[27]).strip())
tmpRegistration.set_name(str(row[28]).strip())
tmpRegistration.expiration_date = parseYYYYMMDD(str(row[29]).strip())
tmpRegistration.kit_manufacturer = str(row[31]).strip()
tmpRegistration.kit_model = str(row[32]).strip()
tmpRegistration.icao24_hex = str(row[33]).strip()
#Store it in the DB
tmpRegistration.commit()
#Increment the bar
bar.next()
bar.finish()
logger.info("Completed Registration Import, total row count " + str(rowCount) + ".")
def export_data():
import_sql.row_factory = sqlite3.Row
sqliteCur = import_sql.cursor()
logger.info("Querying data from SQLite.")
with yaspin(text="Querying data from SQLite...") as spinner:
sqliteCur.execute("SELECT registrations.registration, registrations.serial_number, registrations.manufactured_year, \
registrations.registrant_type, registrations.name, registrations.street, registrations.city, \
registrations.state, registrations.postal_code, registrations.region, registrations.country, \
registrations.last_action, registrations.certificate_issue, registrations.certification, \
registrations.operations, registrations.aircraft_type, \
registrations.status, \
registrations.airworthiness_date, registrations.expiration_date as registration_expiration_date, registrations.kit_manufacturer, \
registrations.kit_model, registrations.icao24_hex as icao_hex, \
aircraft.manufacturer as aircraft_manufacturer, aircraft.model as aircraft_model, \
aircraft.category as aircraft_category, aircraft.builder_certification, \
aircraft.engine_count, aircraft.seat_count as seats, aircraft.weight, aircraft.speed, \
engines.manufacturer as engine_manufacturer, engines.model as engine_model, engines.engine_type as engine_type, \
engines.power_value as power_value, engines.power_type as power_type \
FROM registrations LEFT JOIN aircraft ON registrations.code_aircraft = aircraft.code \
LEFT JOIN engines ON registrations.code_engine = engines.code")
rows = sqliteCur.fetchall()
spinner.stop()
logger.info("SQLite returned " + str(len(rows)) + " rows of data.")
registrationsDb = mysql.connector.connect(
host=settings['mySQL']['uri'],
user=settings['mySQL']['username'],
password=settings['mySQL']['password'],
database=settings['mySQL']['database'])
mysqlCur = registrationsDb.cursor()
#Ensure the source exists
mysqlCur.execute("INSERT INTO sources (agency) \
SELECT * FROM (SELECT 'US-FAA') AS tmp \
WHERE NOT EXISTS ( \
SELECT agency FROM sources WHERE agency = 'US-FAA' \
) LIMIT 1;")
logger.info("Creating temp table in MySQL.")
mysqlCur.execute("CREATE TEMPORARY TABLE import (icao_hex char(6) NOT NULL, registration varchar(8) NOT NULL, data json NULL, hash char(32) NOT NULL, KEY icao_hex (icao_hex), KEY hash (hash));")
logger.info("Exporting data to MySQL.")
sqlInsert = "INSERT INTO import (icao_hex, registration, data, hash) VALUES (%s,%s,%s,%s)"
with Bar("Exporting Data to MySQL...", max=len(rows)) as bar:
for row in rows:
objCompleted = {}
objCompleted['icao_hex'] = row['icao_hex']
objCompleted['registration'] = row['registration']
objCompleted['serial_number'] = row['serial_number']
objCompleted['manufactured_year'] = row['manufactured_year']
objCompleted['airworthiness_date'] = row['airworthiness_date']
objCompleted['registration_expiration_date'] = row['registration_expiration_date']
objCompleted['registrant_type'] = row['registrant_type']
objCompleted['name'] = json.loads(row['name'])
objCompleted['street'] = json.loads(row['street'])
objCompleted['city'] = row['city']
objCompleted['state'] = row['state']
objCompleted['postal_code'] = row['postal_code']
objCompleted['region'] = row['region']
objCompleted['country'] = row['country']
objCompleted['last_action'] = row['last_action']
objCompleted['certificate_issue'] = row['certificate_issue']
objCompleted['certification'] = json.loads(row['certification'])
objCompleted['operations'] = json.loads(row['operations'])
objCompleted['status'] = row['status']
objCompleted['aircraft'] = {}
objCompleted['aircraft']['manufacturer'] = row['aircraft_manufacturer']
objCompleted['aircraft']['model'] = row['aircraft_model']
objCompleted['aircraft']['type'] = row['aircraft_type']
objCompleted['aircraft']['category'] = row['aircraft_category']
objCompleted['aircraft']['builder_certification'] = row['builder_certification']
objCompleted['aircraft']['seats'] = row['seats']
objCompleted['aircraft']['weight'] = row['weight']
if row['kit_manufacturer'] != "":
objCompleted['aircraft']['kit_manufacturer'] = row['kit_manufacturer']
if row['kit_model'] != "":
objCompleted['aircraft']['kit_model'] = row['kit_model']
objCompleted['powerplant'] = {}
if row['engine_manufacturer']:
objCompleted['powerplant']['manufacturer'] = row['engine_manufacturer']
if row['engine_model']:
objCompleted['powerplant']['model'] = row['engine_model']
if row['power_value']:
objCompleted['powerplant']['power_value'] = row['power_value']
if row['power_type']:
objCompleted['powerplant']['power_type'] = row['power_type']
if row['engine_count']:
objCompleted['powerplant']['count'] = row['engine_count']
if row['engine_type']:
objCompleted['powerplant']['type'] = row['engine_type']
if objCompleted['certification'] == []:
del objCompleted['certification']
if objCompleted['operations'] == []:
del objCompleted['operations']
if objCompleted['aircraft'] == {}:
del objCompleted['aircraft']
if objCompleted['powerplant'] == {}:
del objCompleted['powerplant']
mysqlCur.execute(sqlInsert, (objCompleted['icao_hex'], objCompleted['registration'], json.dumps(objCompleted), hashlib.md5(json.dumps(objCompleted).encode('utf-8')).hexdigest(), ))
#Increment the bar
bar.next()
bar.finish()
logger.info("Committing import data to MySQL.")
with yaspin(text="Committing import data to MySQL...") as spinner:
registrationsDb.commit()
spinner.text = "Committed " + str(mysqlCur.rowcount) + " rows of import data to MySQL.\n"
spinner.ok()
logger.info("Committed " + str(mysqlCur.rowcount) + " rows of import data to MySQL.")
#Delete registrations that don't exist in the import
logger.info("Deleting deregistered registrations.")
with yaspin(text="Deleting deregistered registrations...") as spinner:
mysqlCur.execute("UPDATE registrations, \
(SELECT registrations.unique_id FROM registrations \
LEFT OUTER JOIN import ON registrations.icao_hex = import.icao_hex \
INNER JOIN sources ON registrations.source = sources.unique_id \
WHERE import.icao_hex IS NULL AND registrations.deleted IS NULL AND sources.agency = 'US-FAA') as d \
SET registrations.deleted = CURRENT_TIMESTAMP \
WHERE registrations.unique_id = d.unique_id;")
logger.info("Committing deletion of deregistered registrations to MySQL.")
registrationsDb.commit()
spinner.text = "Marked " + str(mysqlCur.rowcount) + " missing registrations as deleted.\n"
spinner.ok("")
logger.info("Marked " + str(mysqlCur.rowcount) + " missing registrations as deleted.")
#Delete registrations if we have a new record coming in where the hashes don't match
logger.info("Deleting obsolete registrations.")
with yaspin(text="Deleting obsolete registrations...") as spinner:
mysqlCur.execute("UPDATE registrations, \
(SELECT registrations.unique_id FROM registrations \
INNER JOIN import ON import.icao_hex = registrations.icao_hex and import.hash <> registrations.hash \
INNER JOIN sources ON registrations.source = sources.unique_id \
WHERE registrations.deleted IS NULL AND sources.agency = 'US-FAA') AS d \
SET registrations.deleted = CURRENT_TIMESTAMP \
WHERE registrations.unique_id = d.unique_id ;")
logger.info("Committing deletion of obsolete registrations to MySQL.")
registrationsDb.commit()
spinner.text = "Marked " + str(mysqlCur.rowcount) + " obsolete registrations as deleted.\n"
spinner.ok("")
logger.info("Marked " + str(mysqlCur.rowcount) + " obsolete registrations as deleted.")
# Create new registrations and mark deleted registrations with a matching has as undeleted
logger.info("Creating new registrations.")
with yaspin(text="Creating new registrations...") as spinner:
mysqlCur.execute("INSERT INTO registrations (icao_hex, registration, data, hash, source) \
(SELECT import.icao_hex, import.registration, import.data, import.hash, sources.unique_id FROM import \
LEFT OUTER JOIN registrations on import.icao_hex = registrations.icao_hex \
LEFT OUTER JOIN sources ON sources.agency = 'US-FAA') ON DUPLICATE KEY UPDATE deleted = NULL;")
logger.info("Committing new registrations to MySQL.")
registrationsDb.commit()
spinner.text = "Created " + str(mysqlCur.rowcount) + " new registrations.\n"
spinner.ok("")
logger.info("Created " + str(mysqlCur.rowcount) + " new registrations.")
mysqlCur.close()
registrationsDb.close()
def parseYYYYMMDD(value):
if value == "":
return ""
return datetime.strptime(value, '%Y%m%d').strftime('%Y-%m-%d')
class registration():
def __init__(self):
self.registration = ""
self.serial_number = ""
self.code_aircraft = ""
self.code_engine = ""
self.manufactured_year = ""
self.registrant_type = ""
self.name = []
self.street = []
self.city = ""
self.state = ""
self.postal_code = ""
self.region = ""
self.country = ""
self.last_action = ""
self.certificate_issue = ""
self.certification = []
self.operations = []
self.aircraft_type = ""
self.engine_type = ""
self.status = ""
self.icao24_octal = ""
self.fractional_ownership = False
self.airworthiness_date = ""
self.expiration_date = ""
self.kit_manufacturer = ""
self.kit_model = ""
self.icao24_hex = ""
def set_name(self, value):
if len(value) > 0:
self.name.append(value)
def set_type_registrant(self, value):
if value == "1":
self.registrant_type = "Individual"
return
if value == "2":
self.registrant_type = "Partnership"
return
if value == "3":
self.registrant_type = "Corporation"
return
if value == "4":
self.registrant_type = "Co-Owned"
return
if value == "5":
self.registrant_type = "Government"
return
if value == "7":
self.registrant_type = "LLC"
return
if value == "8":
self.registrant_type = "Non-Citizen Corporation"
return
if value == "9":
self.registrant_type = "Non-Citizen Co-Owned"
return
if value == "":
self.registrant_type = "None"
return
self.registrant_type = "Unknown"
logger.warning("Unknown registrant type provided: " + value + " " + str(self.toDict()))
return
def set_street(self, street1, street2):
if street1 != "":
self.street.append(street1)
if street2 != "":
self.street.append(street2)
def set_region(self, value):
if value == "1":
self.region = "Eastern"
return
if value == "2":
self.region = "Southwestern"
return
if value == "3":
self.region = "Central"
return
if value == "4":
self.region = "Western-Pacific"
return
if value == "5":
self.region = "Alaskan"
return
if value == "7":
self.region = "Southern"
return
if value == "8":
self.region = "European"
return
if value == "C":
self.region = "Great Lakes"
return
if value == "E":
self.region = "New England"
return
if value == "S":
self.region = "Northwest Mountain"
return
if value == "":
self.region = "None"
return
self.region = "Unknown"
logger.warning("Unknown region type provided: " + value + " " + str(self.toDict()))
return
def set_certification(self, value):
value = str(value).upper()
if value == "":
self.certification.append("None")
return
#Set the airworthiness
if value[0] == "0":
self.certification.append("Unknown")
return
if value[0] == "1":
self.certification.append("Standard")
self.operations_standard(value)
return
if value[0] == "2":
self.certification.append("Limited")
self.operations_limited(value)
return
if value[0] == "3":
self.certification.append("Restricted")
self.operations_restricted(value)
return
if value[0] == "4":
self.certification.append("Experimental")
self.operations_experimental(value)
return
if value[0] == "5":
self.certification.append("Provisional")
self.operations_provisional(value)
return
if value[0] == "6":
self.operations_multiple(value)
return
if value[0] == "7":
self.certification.append("Primary")
self.operations_primary(value)
return
if value[0] == "8":
self.certification.append("Special Flight Permit")
self.operations_sfp(value)
return
if value[0] == "9":
self.certification.append("Light Sport")
self.operations_ls(value)
return
self.certification.append("Unknown")
logger.warning("Unknown certification type provided: " + value + " " + str(self.toDict()))
def operations_standard(self, value):
if len(value) < 2:
return
for entry in value[1:]:
if entry == "N":
self.operations.append("Normal")
continue
if entry == "U":
self.operations.append("Utility")
continue
if entry == "A":
self.operations.append("Acrobatic")
continue
if entry == "T":
self.operations.append("Transport")
continue
if entry == "G":
self.operations.append("Glider")
continue
if entry == "B":
self.operations.append("Balloon")
continue
if entry == "C":
self.operations.append("Commuter")
continue
if entry == "O":
self.operations.append("Other")
continue
logger.warning("Standard airworthiness type has an unknown operation provided: " + entry + " " + str(self.toDict()))
def operations_limited(self, value):
if len(value) < 2:
return
logger.warning("Limited airworthiness type has an unknown operation provided: " + value + " " + str(self.toDict()))
def operations_restricted(self, value):
if len(value) < 2:
return
for entry in value[1:]:
if entry == "0":
self.operations.append("Other")
continue
if entry == "1":
self.operations.append("Agriculture and Pest Control")
continue
if entry == "2":
self.operations.append("Aerial Surveying")
continue
if entry == "3":
self.operations.append("Aerial Advertising")
continue
if entry == "4":
self.operations.append("Forest")
continue
if entry == "5":
self.operations.append("Patrolling")
continue
if entry == "6":
self.operations.append("Weather Control")
continue
if entry == "7":
self.operations.append("Carriage of Cargo")
continue
logger.warning("Restricted airworthiness type has an unknown operation provided: " + value + " " + str(self.toDict()))
def operations_experimental(self, value):
if len(value) < 2:
return
prior_entry = 0
for entry in value[1:]:
if entry == "0":
prior_entry = 0
self.operations.append("To show compliance with FAR")
continue
if entry == "1":
prior_entry = 0
self.operations.append("Research and Development")
continue
if entry == "2":
prior_entry = 0
self.operations.append("Amateur Built")
continue
if entry == "3":
prior_entry = 0
self.operations.append("Exhibition")
continue
if entry == "4":
prior_entry = 0
self.operations.append("Racing")
continue
if entry == "5":
prior_entry = 0
self.operations.append("Crew Training")
continue
if entry == "6":
prior_entry = 0
self.operations.append("Market Survey")
continue
if entry == "7":
prior_entry = 0
self.operations.append("Operating Kit Built Aircraft")
continue
if entry == "8":
prior_entry = 8
continue
if prior_entry == 8 and entry == "A":
prior_entry = 0
self.operations.append("Reg. Prior to 01/31/08")
continue
if prior_entry == 8 and entry == "B":
prior_entry = 0
self.operations.append("Operating Light-Sport Kit-Built")
continue
if prior_entry == 8 and entry == "C":
prior_entry = 0
self.operations.append("Operating Light-Sport Previously issued cert under 21.190")
continue