-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver.py
More file actions
2670 lines (2285 loc) · 104 KB
/
server.py
File metadata and controls
2670 lines (2285 loc) · 104 KB
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
#!/usr/bin/env python3
"""
Arsenal Ship Tracker API Server
Zero external dependencies - uses only Python standard library
"""
import gzip
import json
import os
import sqlite3
import sys
import threading
from contextlib import contextmanager
from datetime import datetime
from http.server import HTTPServer, SimpleHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
from utils import haversine
# Import vessel intelligence module
try:
from vessel_intel import analyze_vessel_intel, quick_vessel_bluf
INTEL_AVAILABLE = True
except ImportError:
INTEL_AVAILABLE = False
# Import weather module
try:
from weather import get_weather_service, enrich_position_with_weather
WEATHER_AVAILABLE = True
except ImportError:
WEATHER_AVAILABLE = False
# Import SAR detection module
try:
from sar_import import (
get_sar_detections, get_dark_vessels, import_sar_file,
parse_detections, correlate_with_ais, save_detections_to_db
)
SAR_AVAILABLE = True
except ImportError:
SAR_AVAILABLE = False
# Import confidence scoring module
try:
from confidence import (
calculate_vessel_confidence, save_confidence_to_db,
get_vessel_confidence
)
CONFIDENCE_AVAILABLE = True
except ImportError:
CONFIDENCE_AVAILABLE = False
# Import intelligence module
try:
from intelligence import produce_vessel_intelligence, get_intel_summary
INTELLIGENCE_AVAILABLE = True
except ImportError:
INTELLIGENCE_AVAILABLE = False
# Import behavior detection module
try:
from behavior import (
validate_mmsi, get_flag_country, analyze_vessel_behavior,
detect_encounters, detect_loitering, detect_ais_gaps, detect_spoofing,
downsample_track, segment_track
)
BEHAVIOR_AVAILABLE = True
except ImportError:
BEHAVIOR_AVAILABLE = False
# Import Venezuela dark fleet detection module
try:
from venezuela import (
is_in_venezuela_zone, check_venezuela_alerts,
calculate_venezuela_risk_score, detect_ais_spoofing,
detect_circle_spoofing, KNOWN_DARK_FLEET_VESSELS,
get_venezuela_monitoring_config
)
VENEZUELA_AVAILABLE = True
except ImportError:
VENEZUELA_AVAILABLE = False
# Import sanctions database module
try:
from sanctions import (
SanctionsDatabase, check_venezuela_sanctions,
calculate_sanction_confidence, enrich_vessel_with_sanctions,
fetch_fleetleaks_map_data
)
SANCTIONS_AVAILABLE = True
except ImportError:
SANCTIONS_AVAILABLE = False
# Import multi-region dark fleet detection module
try:
from dark_fleet import (
Region, is_in_region_zone, is_in_any_monitored_zone,
get_nearby_key_points, calculate_dark_fleet_risk_score,
check_dark_fleet_alerts, get_dark_fleet_config,
get_known_vessels_by_region, get_dark_fleet_statistics,
KNOWN_DARK_FLEET_VESSELS as DARK_FLEET_VESSELS
)
DARK_FLEET_AVAILABLE = True
except ImportError:
DARK_FLEET_AVAILABLE = False
# Import infrastructure threat analysis module
try:
from infra_analysis import (
get_baltic_infrastructure, get_global_infrastructure,
analyze_vessel_for_incident, analyze_infrastructure_incident,
BALTIC_INFRASTRUCTURE
)
INFRA_ANALYSIS_AVAILABLE = True
except ImportError:
INFRA_ANALYSIS_AVAILABLE = False
# Import laden status detection module
try:
from laden_status import (
analyze_laden_status, get_laden_status_summary,
LadenState, CargoEventType
)
LADEN_STATUS_AVAILABLE = True
except ImportError:
LADEN_STATUS_AVAILABLE = False
# Import satellite intelligence module
try:
from satellite_intel import (
get_satellite_service, search_vessel_imagery, get_area_imagery,
get_storage_facilities, analyze_storage_levels
)
SATELLITE_AVAILABLE = True
except ImportError:
SATELLITE_AVAILABLE = False
# Import shoreside photography module
try:
from shoreside_photos import get_photo_service
PHOTOS_AVAILABLE = True
except ImportError:
PHOTOS_AVAILABLE = False
# Import Global Fishing Watch integration
try:
from gfw_integration import (
is_configured as gfw_is_configured,
search_vessel as gfw_search_vessel,
get_vessel_events as gfw_get_vessel_events,
get_dark_fleet_indicators as gfw_get_dark_fleet_indicators,
check_sts_zone as gfw_check_sts_zone,
save_token as gfw_save_token,
reload_token as gfw_reload_token,
get_sar_detections as gfw_get_sar_detections,
find_dark_vessels as gfw_find_dark_vessels
)
GFW_AVAILABLE = True
except ImportError:
GFW_AVAILABLE = False
# Import fallback port database
try:
from ports_database import (
get_ports_nearby as fallback_get_ports_nearby,
get_database_stats as get_ports_stats
)
PORTS_DB_AVAILABLE = True
except ImportError:
PORTS_DB_AVAILABLE = False
# Configuration
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DB_PATH = os.path.join(SCRIPT_DIR, 'arsenal_tracker.db')
SCHEMA_PATH = os.path.join(SCRIPT_DIR, 'schema.sql')
STATIC_DIR = os.path.join(SCRIPT_DIR, 'static')
DOCS_DIR = os.path.join(SCRIPT_DIR, 'docs')
PHOTOS_DIR = os.path.join(STATIC_DIR, 'photos')
LIVE_VESSELS_PATH = os.path.join(DOCS_DIR, 'live_vessels.json')
CONFIG_PATH = os.path.join(SCRIPT_DIR, 'ais_config.json')
PORT = 8080
# Database connection pool (thread-local storage)
_db_local = threading.local()
def get_db():
"""Get database connection with row factory (thread-safe with connection reuse)."""
# Check if we have a cached connection and if it's still valid
if hasattr(_db_local, 'conn') and _db_local.conn is not None:
try:
# Test if connection is still valid
_db_local.conn.execute("SELECT 1")
return _db_local.conn
except (sqlite3.ProgrammingError, sqlite3.OperationalError):
# Connection is closed or invalid, clear it
_db_local.conn = None
# Create new connection
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL") # Faster writes, still safe
conn.execute("PRAGMA cache_size=-64000") # 64MB cache
conn.execute("PRAGMA temp_store=MEMORY") # Temp tables in memory
conn.row_factory = sqlite3.Row
_db_local.conn = conn
return _db_local.conn
@contextmanager
def db_connection():
"""Context manager for database operations with automatic error handling."""
conn = get_db()
try:
yield conn
conn.commit()
except Exception as e:
conn.rollback()
raise e
def dict_from_row(row):
"""Convert sqlite3.Row to dictionary."""
return dict(zip(row.keys(), row)) if row else None
# =============================================================================
# AIS Source Manager (parallel API usage)
# =============================================================================
_ais_manager = None
_ais_manager_lock = threading.Lock()
def get_ais_manager():
"""
Get or create the AIS source manager instance.
Uses both APIs in parallel:
- AISStream for real-time position streaming
- Marinesia for ports, area queries, vessel images, history
"""
global _ais_manager
with _ais_manager_lock:
if _ais_manager is not None:
return _ais_manager
try:
from ais_sources.manager import create_manager
import os
# Load API keys from environment
aisstream_key = os.environ.get('AISSTREAM_API_KEY')
marinesia_key = os.environ.get('MARINESIA_API_KEY')
gfw_key = os.environ.get('GFW_API_KEY')
# Create manager with available sources
_ais_manager = create_manager(
aisstream_key=aisstream_key,
marinesia_key=marinesia_key,
gfw_key=gfw_key,
enable_marinesia=True # Always enable Marinesia for ports/images
)
# Connect sources
_ais_manager.start()
print(f"[AIS Manager] Initialized with sources: {list(_ais_manager.sources.keys())}")
return _ais_manager
except ImportError as e:
print(f"[AIS Manager] Module not available: {e}")
return None
except Exception as e:
print(f"[AIS Manager] Failed to initialize: {e}")
return None
def init_database():
"""Initialize database with schema."""
if os.path.exists(DB_PATH):
os.remove(DB_PATH)
print(f"Removed existing database: {DB_PATH}")
conn = get_db()
with open(SCHEMA_PATH, 'r') as f:
conn.executescript(f.read())
conn.commit()
conn.close()
print(f"Database initialized: {DB_PATH}")
# =============================================================================
# API Handlers
# =============================================================================
def get_vessels():
"""Get all vessels with their latest position."""
conn = get_db()
cursor = conn.execute('''
SELECT v.*,
p.latitude as last_lat,
p.longitude as last_lon,
p.heading as last_heading,
p.speed_knots as last_speed,
p.timestamp as last_position_time,
p.source as position_source
FROM vessels v
LEFT JOIN (
SELECT vessel_id, latitude, longitude, heading, speed_knots, timestamp, source,
ROW_NUMBER() OVER (PARTITION BY vessel_id ORDER BY timestamp DESC) as rn
FROM positions
) p ON v.id = p.vessel_id AND p.rn = 1
ORDER BY v.threat_level DESC, v.name
''')
vessels = [dict_from_row(row) for row in cursor.fetchall()]
conn.close()
return vessels
def get_vessel(vessel_id):
"""Get single vessel with full details."""
conn = get_db()
cursor = conn.execute('''
SELECT v.*,
p.latitude as last_lat,
p.longitude as last_lon,
p.heading as last_heading,
p.speed_knots as last_speed,
p.timestamp as last_position_time
FROM vessels v
LEFT JOIN (
SELECT vessel_id, latitude, longitude, heading, speed_knots, timestamp,
ROW_NUMBER() OVER (PARTITION BY vessel_id ORDER BY timestamp DESC) as rn
FROM positions
) p ON v.id = p.vessel_id AND p.rn = 1
WHERE v.id = ?
''', (vessel_id,))
vessel = dict_from_row(cursor.fetchone())
conn.close()
return vessel
def get_vessel_track(vessel_id, days=90):
"""Get position history for vessel."""
conn = get_db()
cursor = conn.execute('''
SELECT * FROM positions
WHERE vessel_id = ?
AND timestamp >= datetime('now', ?)
ORDER BY timestamp ASC
''', (vessel_id, f'-{days} days'))
positions = [dict_from_row(row) for row in cursor.fetchall()]
conn.close()
return positions
def get_vessel_events(vessel_id):
"""Get events timeline for vessel."""
conn = get_db()
cursor = conn.execute('''
SELECT * FROM events
WHERE vessel_id = ?
ORDER BY event_date DESC
''', (vessel_id,))
events = [dict_from_row(row) for row in cursor.fetchall()]
conn.close()
return events
def get_shipyards():
"""Get all monitored shipyards."""
conn = get_db()
cursor = conn.execute('SELECT * FROM shipyards ORDER BY name')
shipyards = [dict_from_row(row) for row in cursor.fetchall()]
conn.close()
return shipyards
def get_events(severity=None, limit=50):
"""Get all events, optionally filtered by severity."""
conn = get_db()
if severity:
cursor = conn.execute('''
SELECT e.*, v.name as vessel_name
FROM events e
JOIN vessels v ON e.vessel_id = v.id
WHERE e.severity = ?
ORDER BY e.event_date DESC
LIMIT ?
''', (severity, limit))
else:
cursor = conn.execute('''
SELECT e.*, v.name as vessel_name
FROM events e
JOIN vessels v ON e.vessel_id = v.id
ORDER BY e.event_date DESC
LIMIT ?
''', (limit,))
events = [dict_from_row(row) for row in cursor.fetchall()]
conn.close()
return events
def get_alerts(acknowledged=False):
"""Get alerts, by default unacknowledged only."""
conn = get_db()
cursor = conn.execute('''
SELECT a.*, v.name as vessel_name
FROM alerts a
LEFT JOIN vessels v ON a.vessel_id = v.id
WHERE a.acknowledged = ?
ORDER BY a.created_at DESC
''', (1 if acknowledged else 0,))
alerts = [dict_from_row(row) for row in cursor.fetchall()]
conn.close()
return alerts
def get_osint_reports(vessel_id=None):
"""Get OSINT reports, optionally filtered by vessel."""
conn = get_db()
if vessel_id:
cursor = conn.execute('''
SELECT o.*, v.name as vessel_name
FROM osint_reports o
LEFT JOIN vessels v ON o.vessel_id = v.id
WHERE o.vessel_id = ?
ORDER BY o.publish_date DESC
''', (vessel_id,))
else:
cursor = conn.execute('''
SELECT o.*, v.name as vessel_name
FROM osint_reports o
LEFT JOIN vessels v ON o.vessel_id = v.id
ORDER BY o.publish_date DESC
''')
reports = [dict_from_row(row) for row in cursor.fetchall()]
conn.close()
return reports
def get_watchlist():
"""Get watchlist with vessel details."""
conn = get_db()
cursor = conn.execute('''
SELECT w.*, v.name, v.mmsi, v.classification, v.threat_level,
p.latitude as last_lat, p.longitude as last_lon, p.timestamp as last_seen
FROM watchlist w
JOIN vessels v ON w.vessel_id = v.id
LEFT JOIN (
SELECT vessel_id, latitude, longitude, timestamp,
ROW_NUMBER() OVER (PARTITION BY vessel_id ORDER BY timestamp DESC) as rn
FROM positions
) p ON v.id = p.vessel_id AND p.rn = 1
ORDER BY w.priority ASC
''')
watchlist = [dict_from_row(row) for row in cursor.fetchall()]
conn.close()
return watchlist
def get_stats():
"""Get dashboard statistics."""
conn = get_db()
stats = {}
cursor = conn.execute('SELECT COUNT(*) as count FROM vessels')
stats['total_vessels'] = cursor.fetchone()['count']
cursor = conn.execute("SELECT COUNT(*) as count FROM vessels WHERE classification = 'confirmed'")
stats['confirmed_arsenal'] = cursor.fetchone()['count']
cursor = conn.execute("SELECT COUNT(*) as count FROM vessels WHERE threat_level = 'critical'")
stats['critical_threats'] = cursor.fetchone()['count']
cursor = conn.execute('SELECT COUNT(*) as count FROM alerts WHERE acknowledged = 0')
stats['active_alerts'] = cursor.fetchone()['count']
cursor = conn.execute('SELECT COUNT(*) as count FROM watchlist')
stats['watchlist_count'] = cursor.fetchone()['count']
cursor = conn.execute('SELECT COUNT(*) as count FROM osint_reports')
stats['osint_reports'] = cursor.fetchone()['count']
cursor = conn.execute('SELECT COUNT(*) as count FROM events')
stats['total_events'] = cursor.fetchone()['count']
cursor = conn.execute("SELECT COUNT(*) as count FROM events WHERE severity IN ('critical', 'high')")
stats['high_severity_events'] = cursor.fetchone()['count']
conn.close()
return stats
def get_live_vessels():
"""Get live vessels from stream_area.py output file."""
if not os.path.exists(LIVE_VESSELS_PATH):
return {'timestamp': None, 'vessel_count': 0, 'vessels': []}
try:
with open(LIVE_VESSELS_PATH, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, IOError) as e:
print(f"[Error] Failed to read live vessels: {e}")
return {'timestamp': None, 'vessel_count': 0, 'vessels': []}
def add_vessel(data):
"""Add new vessel to tracking."""
conn = get_db()
cursor = conn.execute('''
INSERT INTO vessels (name, mmsi, imo, flag_state, vessel_type, classification, threat_level, intel_notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (
data.get('name'),
data.get('mmsi'),
data.get('imo'),
data.get('flag_state'),
data.get('vessel_type'),
data.get('classification', 'monitoring'),
data.get('threat_level', 'unknown'),
data.get('intel_notes')
))
vessel_id = cursor.lastrowid
conn.commit()
conn.close()
return {'id': vessel_id, 'status': 'created'}
def add_position(vessel_id, data):
"""Add position update for vessel."""
conn = get_db()
conn.execute('''
INSERT INTO positions (vessel_id, latitude, longitude, heading, speed_knots, source)
VALUES (?, ?, ?, ?, ?, ?)
''', (
vessel_id,
data.get('latitude'),
data.get('longitude'),
data.get('heading'),
data.get('speed_knots'),
data.get('source', 'manual')
))
conn.execute('UPDATE vessels SET last_updated = CURRENT_TIMESTAMP WHERE id = ?', (vessel_id,))
conn.commit()
conn.close()
return {'status': 'position_logged'}
def add_event(vessel_id, data):
"""Add event for vessel."""
conn = get_db()
conn.execute('''
INSERT INTO events (vessel_id, event_type, severity, title, description, source, source_url, latitude, longitude)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
vessel_id,
data.get('event_type'),
data.get('severity', 'info'),
data.get('title'),
data.get('description'),
data.get('source'),
data.get('source_url'),
data.get('latitude'),
data.get('longitude')
))
conn.commit()
conn.close()
return {'status': 'event_logged'}
def add_osint_report(data):
"""Add OSINT report."""
conn = get_db()
cursor = conn.execute('''
INSERT INTO osint_reports (vessel_id, title, source_name, source_url, publish_date, summary, full_content, key_findings, reliability, tags)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
data.get('vessel_id'),
data.get('title'),
data.get('source_name'),
data.get('source_url'),
data.get('publish_date'),
data.get('summary'),
data.get('full_content'),
json.dumps(data.get('key_findings', [])),
data.get('reliability', 'unconfirmed'),
data.get('tags')
))
report_id = cursor.lastrowid
conn.commit()
conn.close()
return {'id': report_id, 'status': 'created'}
def acknowledge_alert(alert_id):
"""Acknowledge an alert."""
conn = get_db()
conn.execute('''
UPDATE alerts SET acknowledged = 1, acknowledged_at = CURRENT_TIMESTAMP
WHERE id = ?
''', (alert_id,))
conn.commit()
conn.close()
return {'status': 'acknowledged'}
def load_poc_scenario(poc_name):
"""Load a POC scenario into the database."""
if poc_name == 'baltic':
return _load_baltic_poc()
elif poc_name == 'venezuela':
return _load_venezuela_poc()
elif poc_name == 'china':
return _load_china_poc()
else:
return {'error': f'Unknown POC: {poc_name}', 'available': ['baltic', 'venezuela', 'china']}
def _load_baltic_poc():
"""Load Baltic Cable Incident POC data."""
conn = get_db()
results = {'vessels_added': [], 'infrastructure_added': [], 'events_added': []}
# Vessel data
vessels = [
{
"name": "FITBURG",
"mmsi": "518100989",
"imo": "9187629",
"flag_state": "Cook Islands",
"vessel_type": "Cargo Ship",
"classification": "suspected",
"threat_level": "high",
"intel_notes": "Baltic Cable Incident - Dec 31, 2025. Seized by Finnish authorities after C-Lion1 cable damage. Anchor dragging detected in cable zone."
},
{
"name": "EAGLE S",
"mmsi": "255806583",
"imo": "9037155",
"flag_state": "Malta",
"vessel_type": "Oil Tanker",
"classification": "suspected",
"threat_level": "high",
"intel_notes": "Estlink-2 cable incident - Dec 25, 2025. Shadow fleet tanker, anchor dragged damaging Finland-Estonia power cable."
}
]
for v in vessels:
cursor = conn.execute("SELECT id FROM vessels WHERE mmsi = ?", (v['mmsi'],))
existing = cursor.fetchone()
if not existing:
conn.execute('''
INSERT INTO vessels (name, mmsi, imo, flag_state, vessel_type, classification, threat_level, intel_notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (v['name'], v['mmsi'], v['imo'], v['flag_state'], v['vessel_type'], v['classification'], v['threat_level'], v['intel_notes']))
results['vessels_added'].append(v['name'])
# Infrastructure locations (as shipyards)
infrastructure = [
{"name": "C-Lion1 Cable Zone", "latitude": 59.45, "longitude": 24.75, "geofence_radius_km": 10.0,
"facility_type": "anchorage", "notes": "Finland-Germany telecom cable. Damaged Dec 31, 2025."},
{"name": "Estlink-2 Cable Zone", "latitude": 59.55, "longitude": 25.00, "geofence_radius_km": 10.0,
"facility_type": "anchorage", "notes": "650MW HVDC power cable. Damaged Dec 25, 2025."},
{"name": "Balticconnector Zone", "latitude": 59.60, "longitude": 24.80, "geofence_radius_km": 15.0,
"facility_type": "anchorage", "notes": "Finland-Estonia gas pipeline. Damaged Oct 2023."},
]
for infra in infrastructure:
cursor = conn.execute("SELECT id FROM shipyards WHERE name = ?", (infra['name'],))
existing = cursor.fetchone()
if not existing:
conn.execute('''
INSERT INTO shipyards (name, latitude, longitude, geofence_radius_km, facility_type, notes)
VALUES (?, ?, ?, ?, ?, ?)
''', (infra['name'], infra['latitude'], infra['longitude'], infra['geofence_radius_km'], infra['facility_type'], infra['notes']))
results['infrastructure_added'].append(infra['name'])
# Get vessel IDs for events
cursor = conn.execute("SELECT id FROM vessels WHERE name = 'FITBURG'")
fitburg = cursor.fetchone()
fitburg_id = fitburg['id'] if fitburg else None
if fitburg_id:
events = [
{"event_type": "anomaly_detected", "severity": "critical", "title": "C-Lion1 cable damage detected",
"description": "Finnish authorities detect damage to undersea telecom cable.", "latitude": 59.45, "longitude": 24.75},
{"event_type": "geofence_enter", "severity": "high", "title": "Fitburg enters cable zone",
"description": "Vessel enters Gulf of Finland cable protection zone.", "latitude": 59.55, "longitude": 25.00},
]
for e in events:
conn.execute('''
INSERT INTO events (vessel_id, event_type, severity, title, description, latitude, longitude)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (fitburg_id, e['event_type'], e['severity'], e['title'], e['description'], e['latitude'], e['longitude']))
results['events_added'].append(e['title'])
# Update config for Baltic Sea
config = {}
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH, 'r') as f:
config = json.load(f)
config['area_tracking'] = {
'enabled': True,
'bounding_box': {
'lat_min': 53.0, 'lon_min': 9.0, 'lat_max': 66.0, 'lon_max': 30.0,
'description': 'Baltic Sea - Cable Infrastructure Monitoring Zone'
}
}
with open(CONFIG_PATH, 'w') as f:
json.dump(config, f, indent=2)
conn.commit()
conn.close()
return {
'status': 'success',
'poc': 'baltic',
'name': 'Baltic Cable Incident',
'results': results,
'message': 'POC loaded. Refresh the page to see vessels and infrastructure.'
}
def _load_venezuela_poc():
"""Load Venezuela Dark Fleet POC data."""
conn = get_db()
results = {'vessels_added': [], 'infrastructure_added': [], 'events_added': []}
# Known dark fleet vessels
vessels = [
{
"name": "SKIPPER",
"mmsi": "352001234",
"imo": "9123456",
"flag_state": "Cameroon",
"vessel_type": "Oil Tanker",
"classification": "confirmed",
"threat_level": "critical",
"intel_notes": "Seized dark fleet tanker. 80+ days AIS spoofing on Iran-Venezuela-China route. Sanctioned."
},
{
"name": "BELLA 1",
"mmsi": "667001234",
"flag_state": "Cameroon",
"vessel_type": "Oil Tanker",
"classification": "suspected",
"threat_level": "high",
"intel_notes": "Currently tracked by U.S. Navy. Suspected sanctions evasion, Venezuela oil trade."
},
{
"name": "CENTURIES",
"mmsi": "538001234",
"flag_state": "Palau",
"vessel_type": "Oil Tanker",
"classification": "confirmed",
"threat_level": "critical",
"intel_notes": "Seized December 2025. Venezuela dark fleet operator."
}
]
for v in vessels:
cursor = conn.execute("SELECT id FROM vessels WHERE name = ?", (v['name'],))
existing = cursor.fetchone()
if not existing:
conn.execute('''
INSERT INTO vessels (name, mmsi, imo, flag_state, vessel_type, classification, threat_level, intel_notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (v['name'], v.get('mmsi'), v.get('imo'), v['flag_state'], v['vessel_type'], v['classification'], v['threat_level'], v['intel_notes']))
results['vessels_added'].append(v['name'])
# Venezuela monitoring zones
infrastructure = [
{"name": "Jose Terminal", "latitude": 10.15, "longitude": -64.68, "geofence_radius_km": 15.0,
"facility_type": "port", "threat_association": "Critical", "notes": "Main Venezuela oil export terminal."},
{"name": "La Borracha STS Zone", "latitude": 10.08, "longitude": -64.89, "geofence_radius_km": 20.0,
"facility_type": "anchorage", "threat_association": "Critical", "notes": "Ship-to-ship transfer zone for dark fleet."},
{"name": "Amuay Refinery", "latitude": 11.74, "longitude": -70.21, "geofence_radius_km": 10.0,
"facility_type": "port", "threat_association": "High", "notes": "Major Venezuela refinery complex."},
]
for infra in infrastructure:
cursor = conn.execute("SELECT id FROM shipyards WHERE name = ?", (infra['name'],))
existing = cursor.fetchone()
if not existing:
conn.execute('''
INSERT INTO shipyards (name, latitude, longitude, geofence_radius_km, facility_type, threat_association, notes)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (infra['name'], infra['latitude'], infra['longitude'], infra['geofence_radius_km'],
infra['facility_type'], infra.get('threat_association'), infra['notes']))
results['infrastructure_added'].append(infra['name'])
# Update config for Caribbean/Venezuela
config = {}
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH, 'r') as f:
config = json.load(f)
config['area_tracking'] = {
'enabled': True,
'bounding_box': {
'lat_min': 8.0, 'lon_min': -75.0, 'lat_max': 15.0, 'lon_max': -60.0,
'description': 'Venezuela - Dark Fleet Monitoring Zone'
}
}
with open(CONFIG_PATH, 'w') as f:
json.dump(config, f, indent=2)
conn.commit()
conn.close()
return {
'status': 'success',
'poc': 'venezuela',
'name': 'Venezuela Dark Fleet',
'results': results,
'message': 'POC loaded. Map centered on Venezuela/Caribbean.'
}
def _load_china_poc():
"""Load China Arsenal Ship POC data."""
conn = get_db()
results = {'vessels_added': [], 'infrastructure_added': [], 'events_added': []}
# Arsenal ships and related vessels
vessels = [
{
"name": "ZHONG DA 79",
"mmsi": "413456789",
"imo": "9876543",
"flag_state": "China",
"vessel_type": "Container Feeder",
"classification": "confirmed",
"threat_level": "critical",
"intel_notes": """Arsenal Ship - Confirmed containerized weapons platform.
WEAPONS CONFIG:
- 60+ containerized cruise/ballistic missiles
- CIWS close-in weapon systems
- Radar arrays disguised as shipping containers
- Retains civilian AIS classification
OPERATIONAL PATTERN:
- Operates in East/South China Sea
- Frequent port calls: Shanghai, Ningbo, Xiamen
- Exercises with PLAN vessels observed"""
},
{
"name": "YUAN WANG 5",
"mmsi": "413123456",
"flag_state": "China",
"vessel_type": "Research Vessel",
"classification": "confirmed",
"threat_level": "high",
"intel_notes": "Space/missile tracking ship. Dual-use military research vessel. Monitored by regional navies."
},
{
"name": "HAI YANG 26",
"mmsi": "413789012",
"flag_state": "China",
"vessel_type": "Research Vessel",
"classification": "suspected",
"threat_level": "medium",
"intel_notes": "Survey vessel. Possible subsea cable mapping operations. Frequent South China Sea presence."
}
]
for v in vessels:
cursor = conn.execute("SELECT id FROM vessels WHERE name = ?", (v['name'],))
existing = cursor.fetchone()
if not existing:
conn.execute('''
INSERT INTO vessels (name, mmsi, imo, flag_state, vessel_type, classification, threat_level, intel_notes)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (v['name'], v.get('mmsi'), v.get('imo'), v['flag_state'], v['vessel_type'], v['classification'], v['threat_level'], v['intel_notes']))
results['vessels_added'].append(v['name'])
# China/Taiwan Strait facilities
infrastructure = [
{"name": "Shanghai Jiangnan Shipyard", "latitude": 31.35, "longitude": 121.50, "geofence_radius_km": 5.0,
"facility_type": "shipyard", "threat_association": "Military", "notes": "Major PLAN shipbuilding. Aircraft carriers, destroyers."},
{"name": "Ningbo-Zhoushan Port", "latitude": 29.87, "longitude": 122.10, "geofence_radius_km": 10.0,
"facility_type": "port", "threat_association": "Dual-use", "notes": "World's largest port. Military logistics hub."},
{"name": "Taiwan Strait Zone", "latitude": 24.50, "longitude": 119.50, "geofence_radius_km": 100.0,
"facility_type": "anchorage", "threat_association": "Critical", "notes": "Strategic chokepoint. High military activity."},
{"name": "Xiamen Naval Base", "latitude": 24.45, "longitude": 118.08, "geofence_radius_km": 8.0,
"facility_type": "military", "threat_association": "Military", "notes": "PLAN Eastern Theater base. Amphibious forces."},
]
for infra in infrastructure:
cursor = conn.execute("SELECT id FROM shipyards WHERE name = ?", (infra['name'],))
existing = cursor.fetchone()
if not existing:
conn.execute('''
INSERT INTO shipyards (name, latitude, longitude, geofence_radius_km, facility_type, threat_association, notes)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (infra['name'], infra['latitude'], infra['longitude'], infra['geofence_radius_km'],
infra['facility_type'], infra.get('threat_association'), infra['notes']))
results['infrastructure_added'].append(infra['name'])
# Update config for East China Sea / Taiwan Strait
config = {}
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH, 'r') as f:
config = json.load(f)
config['area_tracking'] = {
'enabled': True,
'bounding_box': {
'lat_min': 20.0, 'lon_min': 115.0, 'lat_max': 35.0, 'lon_max': 130.0,
'description': 'East China Sea - Arsenal Ship Monitoring Zone'
}
}
with open(CONFIG_PATH, 'w') as f:
json.dump(config, f, indent=2)
conn.commit()
conn.close()
return {
'status': 'success',
'poc': 'china',
'name': 'China Arsenal Ships',
'results': results,
'message': 'POC loaded. Map centered on East China Sea.'
}
def search_news(query, max_results=10):
"""Search Google News for vessel information."""
try:
from gnews import GNews
gn = GNews(language='en', country='US', max_results=max_results)
results = gn.get_news(query)
articles = []
for item in results:
articles.append({
'title': item.get('title', ''),
'url': item.get('url', ''),
'source': item.get('publisher', {}).get('title', 'Unknown'),
'published': item.get('published date', ''),
'description': item.get('description', '')
})
return {'query': query, 'count': len(articles), 'articles': articles}
except ImportError:
return {'error': 'gnews not installed. Run: pip install gnews', 'articles': []}
except Exception as e:
print(f"[Error] News search failed: {e}")
return {'error': str(e), 'articles': []}
def track_live_vessel(data):
"""Add a live vessel to tracking with its current position."""
conn = get_db()
# Check if vessel already exists by MMSI
mmsi = data.get('mmsi')
if mmsi:
cursor = conn.execute('SELECT id FROM vessels WHERE mmsi = ?', (str(mmsi),))
existing = cursor.fetchone()
if existing:
conn.close()
return {'error': 'Vessel with this MMSI already tracked', 'vessel_id': existing['id']}
# Process weapons config
weapons_config = data.get('weapons_config')
if weapons_config and isinstance(weapons_config, dict):
weapons_config = json.dumps(weapons_config)
elif weapons_config:
weapons_config = str(weapons_config)
else:
weapons_config = None
# Insert new vessel with all fields
cursor = conn.execute('''
INSERT INTO vessels (name, mmsi, imo, flag_state, vessel_type, length_m,
classification, threat_level, intel_notes, weapons_config)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
data.get('name', f"MMSI {mmsi}"),
str(mmsi) if mmsi else None,
data.get('imo'),
data.get('flag'),
data.get('ship_type', data.get('vessel_type')),
data.get('length_m'),
data.get('classification', 'monitoring'),
data.get('threat_level', 'unknown'),
data.get('intel_notes', 'Added from live AIS stream'),
weapons_config
))
vessel_id = cursor.lastrowid