-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshadowhunter_scheduler.py
More file actions
1321 lines (1106 loc) · 43.4 KB
/
shadowhunter_scheduler.py
File metadata and controls
1321 lines (1106 loc) · 43.4 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
"""
ShadowHunter - Dark Web Credential Intelligence Platform
Module: Scheduled Site Monitoring & Change Detection
Author: Fevra
Version: 0.1.0
Consolidated from Darkweb Monitor research - provides:
- Scheduled .onion site monitoring with configurable intervals
- Content change detection using content hashing
- Keyword monitoring with contextual alerts
- Content snapshots for forensic analysis
- Database-backed monitoring history
- Integration with ShadowHunter alert system
References:
- darkweb_monitor_script.py patterns
- Raspberry Pi Dark Web Monitor research
"""
import asyncio
import hashlib
import json
import re
import sqlite3
from datetime import datetime, timezone, timedelta
from typing import List, Dict, Optional, Any, Callable, Set
from dataclasses import dataclass, field
from pathlib import Path
from enum import Enum
from collections import defaultdict
import threading
# Import ShadowHunter modules
try:
from shadowhunter_logger import get_logger, LogLevel
from shadowhunter_tor import TorConnection, TorScraper
except ImportError:
import logging
def get_logger(name, **kwargs):
return logging.getLogger(name)
TorConnection = None
TorScraper = None
# Initialize module logger
logger = get_logger("Scheduler", log_level=LogLevel.DEBUG)
# ============================================================================
# CONFIGURATION & ENUMS
# ============================================================================
class MonitorStatus(str, Enum):
"""Site monitoring status."""
ONLINE = "online"
OFFLINE = "offline"
ERROR = "error"
TIMEOUT = "timeout"
CHANGED = "changed"
class ChangeType(str, Enum):
"""Types of detected changes."""
CONTENT = "content"
KEYWORD = "keyword"
STRUCTURE = "structure"
NEW_LINKS = "new_links"
STATUS = "status"
class CheckInterval(Enum):
"""Predefined check intervals in seconds."""
RAPID = 300 # 5 minutes - for critical sites
FREQUENT = 900 # 15 minutes
STANDARD = 3600 # 1 hour - default
RELAXED = 7200 # 2 hours
DAILY = 86400 # 24 hours
# ============================================================================
# DATA MODELS
# ============================================================================
@dataclass
class MonitoredSite:
"""
Configuration for a monitored .onion site.
Attributes:
id: Unique site identifier
url: Full .onion URL
name: Human-readable site name
category: Site category (marketplace, forum, paste, etc.)
keywords: List of keywords to monitor for
check_interval: Seconds between checks
active: Whether monitoring is enabled
priority: Priority level (1=highest)
last_checked: Last check timestamp
last_status: Last known status
metadata: Additional site metadata
"""
id: int
url: str
name: str
category: str = "unknown"
keywords: List[str] = field(default_factory=list)
check_interval: int = 3600
active: bool = True
priority: int = 5
last_checked: Optional[datetime] = None
last_status: MonitorStatus = MonitorStatus.OFFLINE
metadata: Dict[str, Any] = field(default_factory=dict)
def is_due_for_check(self) -> bool:
"""Check if site is due for monitoring."""
if not self.last_checked:
return True
elapsed = (datetime.now(timezone.utc) - self.last_checked).total_seconds()
return elapsed >= self.check_interval
def get_domain(self) -> str:
"""Extract .onion domain from URL."""
from urllib.parse import urlparse
parsed = urlparse(self.url)
return parsed.netloc
@dataclass
class ContentSnapshot:
"""
Content snapshot for change tracking.
Stores both the hash and preview for efficient comparison
while maintaining ability to review actual content changes.
"""
site_id: int
timestamp: datetime
content_hash: str
content_preview: str # First 1000 chars
title: str
word_count: int
link_count: int
links_hash: str # Hash of all extracted links
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class ChangeDetection:
"""
Detected change on a monitored site.
Captures what changed, when, and provides context
for alert generation and analysis.
"""
site_id: int
site_name: str
site_url: str
change_type: ChangeType
timestamp: datetime
severity: str # CRITICAL, HIGH, MEDIUM, LOW
description: str
old_value: Optional[str] = None
new_value: Optional[str] = None
context: str = ""
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class KeywordMatch:
"""
Keyword match detection.
Captures where and how a keyword was found
with surrounding context for analysis.
"""
site_id: int
site_name: str
keyword: str
context: str # Surrounding text
match_count: int
timestamp: datetime
url: str
@dataclass
class CheckResult:
"""
Result from a single site check.
Contains all information about a monitoring check
including status, timing, and extracted data.
"""
site: MonitoredSite
status: MonitorStatus
timestamp: datetime
response_time_ms: float
content_hash: Optional[str] = None
title: Optional[str] = None
content_preview: Optional[str] = None
word_count: int = 0
links: List[str] = field(default_factory=list)
changes: List[ChangeDetection] = field(default_factory=list)
keyword_matches: List[KeywordMatch] = field(default_factory=list)
error: Optional[str] = None
# ============================================================================
# DATABASE MANAGER
# ============================================================================
class SchedulerDatabase:
"""
SQLite database manager for scheduled monitoring.
Provides persistent storage for:
- Monitored sites configuration
- Check history and results
- Content snapshots for change detection
- Keyword match alerts
- Activity logging
"""
def __init__(self, db_path: str = "shadowhunter_scheduler.db"):
"""
Initialize database connection.
Args:
db_path: Path to SQLite database file
"""
self.db_path = Path(db_path)
self._lock = threading.Lock()
self._init_database()
logger.info("Scheduler database initialized", {
"db_path": str(self.db_path)
})
def _get_connection(self) -> sqlite3.Connection:
"""Get database connection with row factory."""
conn = sqlite3.connect(str(self.db_path))
conn.row_factory = sqlite3.Row
return conn
def _init_database(self):
"""Initialize database schema."""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
# Monitored sites table
cursor.execute('''
CREATE TABLE IF NOT EXISTS monitored_sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
category TEXT DEFAULT 'unknown',
keywords TEXT DEFAULT '[]',
check_interval INTEGER DEFAULT 3600,
priority INTEGER DEFAULT 5,
active INTEGER DEFAULT 1,
last_checked TIMESTAMP,
last_status TEXT DEFAULT 'offline',
last_content_hash TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
metadata TEXT DEFAULT '{}'
)
''')
# Site checks history
cursor.execute('''
CREATE TABLE IF NOT EXISTS site_checks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
site_id INTEGER NOT NULL,
check_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status TEXT NOT NULL,
response_time_ms REAL,
content_hash TEXT,
title TEXT,
word_count INTEGER DEFAULT 0,
link_count INTEGER DEFAULT 0,
error TEXT,
FOREIGN KEY (site_id) REFERENCES monitored_sites(id)
)
''')
# Content snapshots for forensics
cursor.execute('''
CREATE TABLE IF NOT EXISTS content_snapshots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
site_id INTEGER NOT NULL,
snapshot_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
content_hash TEXT NOT NULL,
content_preview TEXT,
title TEXT,
word_count INTEGER,
link_count INTEGER,
links_hash TEXT,
metadata TEXT DEFAULT '{}',
FOREIGN KEY (site_id) REFERENCES monitored_sites(id)
)
''')
# Change detections
cursor.execute('''
CREATE TABLE IF NOT EXISTS change_detections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
site_id INTEGER NOT NULL,
detected_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
change_type TEXT NOT NULL,
severity TEXT NOT NULL,
description TEXT,
old_value TEXT,
new_value TEXT,
context TEXT,
alerted INTEGER DEFAULT 0,
FOREIGN KEY (site_id) REFERENCES monitored_sites(id)
)
''')
# Keyword alerts
cursor.execute('''
CREATE TABLE IF NOT EXISTS keyword_alerts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
site_id INTEGER NOT NULL,
keyword TEXT NOT NULL,
context TEXT,
match_count INTEGER DEFAULT 1,
detected_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
alerted INTEGER DEFAULT 0,
FOREIGN KEY (site_id) REFERENCES monitored_sites(id)
)
''')
# Create indices for performance
cursor.execute('CREATE INDEX IF NOT EXISTS idx_checks_site ON site_checks(site_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_checks_time ON site_checks(check_time)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_snapshots_site ON content_snapshots(site_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_changes_site ON change_detections(site_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_keywords_site ON keyword_alerts(site_id)')
conn.commit()
conn.close()
def add_site(
self,
url: str,
name: str,
category: str = "unknown",
keywords: List[str] = None,
check_interval: int = 3600,
priority: int = 5,
metadata: Dict[str, Any] = None
) -> Optional[int]:
"""
Add a new site to monitoring.
Args:
url: .onion URL to monitor
name: Human-readable name
category: Site category
keywords: Keywords to monitor
check_interval: Check frequency in seconds
priority: Priority level (1=highest)
metadata: Additional metadata
Returns:
Site ID if successful, None if already exists
"""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
try:
cursor.execute('''
INSERT INTO monitored_sites
(url, name, category, keywords, check_interval, priority, metadata)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
url,
name,
category,
json.dumps(keywords or []),
check_interval,
priority,
json.dumps(metadata or {})
))
conn.commit()
site_id = cursor.lastrowid
logger.info(f"Added site to monitoring: {name}", {
"site_id": site_id,
"url": url[:50],
"category": category
})
return site_id
except sqlite3.IntegrityError:
logger.warn(f"Site already exists: {url[:50]}")
return None
finally:
conn.close()
def get_active_sites(self) -> List[MonitoredSite]:
"""Get all active monitored sites."""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM monitored_sites WHERE active = 1
ORDER BY priority ASC, last_checked ASC
''')
sites = []
for row in cursor.fetchall():
sites.append(MonitoredSite(
id=row['id'],
url=row['url'],
name=row['name'],
category=row['category'],
keywords=json.loads(row['keywords']) if row['keywords'] else [],
check_interval=row['check_interval'],
active=bool(row['active']),
priority=row['priority'],
last_checked=datetime.fromisoformat(row['last_checked']) if row['last_checked'] else None,
last_status=MonitorStatus(row['last_status']) if row['last_status'] else MonitorStatus.OFFLINE,
metadata=json.loads(row['metadata']) if row['metadata'] else {}
))
conn.close()
return sites
def get_sites_due_for_check(self) -> List[MonitoredSite]:
"""Get sites that are due for checking based on their intervals."""
sites = self.get_active_sites()
return [site for site in sites if site.is_due_for_check()]
def get_last_snapshot(self, site_id: int) -> Optional[ContentSnapshot]:
"""Get the last content snapshot for a site."""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT * FROM content_snapshots
WHERE site_id = ?
ORDER BY snapshot_time DESC
LIMIT 1
''', (site_id,))
row = cursor.fetchone()
conn.close()
if row:
return ContentSnapshot(
site_id=row['site_id'],
timestamp=datetime.fromisoformat(row['snapshot_time']),
content_hash=row['content_hash'],
content_preview=row['content_preview'],
title=row['title'],
word_count=row['word_count'],
link_count=row['link_count'],
links_hash=row['links_hash'],
metadata=json.loads(row['metadata']) if row['metadata'] else {}
)
return None
def save_check_result(self, result: CheckResult):
"""Save check result to database."""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
# Save check record
cursor.execute('''
INSERT INTO site_checks
(site_id, check_time, status, response_time_ms, content_hash,
title, word_count, link_count, error)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
result.site.id,
result.timestamp.isoformat(),
result.status.value,
result.response_time_ms,
result.content_hash,
result.title,
result.word_count,
len(result.links),
result.error
))
# Update site last checked
cursor.execute('''
UPDATE monitored_sites
SET last_checked = ?, last_status = ?, last_content_hash = ?
WHERE id = ?
''', (
result.timestamp.isoformat(),
result.status.value,
result.content_hash,
result.site.id
))
# Save snapshot if we have content
if result.content_hash and result.content_preview:
links_hash = hashlib.sha256(
json.dumps(sorted(result.links)).encode()
).hexdigest()[:16]
cursor.execute('''
INSERT INTO content_snapshots
(site_id, content_hash, content_preview, title,
word_count, link_count, links_hash)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
result.site.id,
result.content_hash,
result.content_preview,
result.title,
result.word_count,
len(result.links),
links_hash
))
# Save change detections
for change in result.changes:
cursor.execute('''
INSERT INTO change_detections
(site_id, change_type, severity, description,
old_value, new_value, context)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
result.site.id,
change.change_type.value,
change.severity,
change.description,
change.old_value,
change.new_value,
change.context
))
# Save keyword matches
for match in result.keyword_matches:
cursor.execute('''
INSERT INTO keyword_alerts
(site_id, keyword, context, match_count)
VALUES (?, ?, ?, ?)
''', (
result.site.id,
match.keyword,
match.context,
match.match_count
))
conn.commit()
conn.close()
def get_recent_changes(
self,
hours: int = 24,
severity: Optional[str] = None
) -> List[ChangeDetection]:
"""Get recent change detections."""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
query = '''
SELECT cd.*, ms.name as site_name, ms.url as site_url
FROM change_detections cd
JOIN monitored_sites ms ON cd.site_id = ms.id
WHERE cd.detected_time >= datetime('now', ?)
'''
params = [f'-{hours} hours']
if severity:
query += ' AND cd.severity = ?'
params.append(severity)
query += ' ORDER BY cd.detected_time DESC'
cursor.execute(query, params)
changes = []
for row in cursor.fetchall():
changes.append(ChangeDetection(
site_id=row['site_id'],
site_name=row['site_name'],
site_url=row['site_url'],
change_type=ChangeType(row['change_type']),
timestamp=datetime.fromisoformat(row['detected_time']),
severity=row['severity'],
description=row['description'],
old_value=row['old_value'],
new_value=row['new_value'],
context=row['context']
))
conn.close()
return changes
def get_statistics(self) -> Dict[str, Any]:
"""Get monitoring statistics."""
with self._lock:
conn = self._get_connection()
cursor = conn.cursor()
stats = {}
# Total sites
cursor.execute('SELECT COUNT(*) FROM monitored_sites')
stats['total_sites'] = cursor.fetchone()[0]
# Active sites
cursor.execute('SELECT COUNT(*) FROM monitored_sites WHERE active = 1')
stats['active_sites'] = cursor.fetchone()[0]
# Online sites (last check)
cursor.execute('''
SELECT COUNT(*) FROM monitored_sites
WHERE active = 1 AND last_status = 'online'
''')
stats['online_sites'] = cursor.fetchone()[0]
# Checks in last 24h
cursor.execute('''
SELECT COUNT(*) FROM site_checks
WHERE check_time >= datetime('now', '-24 hours')
''')
stats['checks_24h'] = cursor.fetchone()[0]
# Changes in last 24h
cursor.execute('''
SELECT COUNT(*) FROM change_detections
WHERE detected_time >= datetime('now', '-24 hours')
''')
stats['changes_24h'] = cursor.fetchone()[0]
# Keyword matches in last 24h
cursor.execute('''
SELECT COUNT(*) FROM keyword_alerts
WHERE detected_time >= datetime('now', '-24 hours')
''')
stats['keyword_matches_24h'] = cursor.fetchone()[0]
conn.close()
return stats
# ============================================================================
# CONTENT ANALYZER
# ============================================================================
class ContentAnalyzer:
"""
Analyzes content for changes and keyword matches.
Provides:
- Content hashing for change detection
- Keyword extraction with context
- Link extraction and comparison
- Structural change detection
"""
def __init__(self):
"""Initialize content analyzer."""
self.link_pattern = re.compile(
r'href=["\']([^"\']+)["\']',
re.IGNORECASE
)
self.onion_pattern = re.compile(
r'[a-z2-7]{16,56}\.onion',
re.IGNORECASE
)
def compute_hash(self, content: str) -> str:
"""
Compute content hash for change detection.
Args:
content: Raw text content
Returns:
SHA-256 hash of normalized content
"""
# Normalize whitespace for consistent hashing
normalized = ' '.join(content.split())
return hashlib.sha256(normalized.encode('utf-8')).hexdigest()
def extract_text(self, html: str) -> str:
"""
Extract clean text from HTML.
Args:
html: Raw HTML content
Returns:
Cleaned text content
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
# Remove script and style elements
for element in soup(['script', 'style', 'meta', 'link']):
element.decompose()
text = soup.get_text(separator=' ', strip=True)
return text
def extract_title(self, html: str) -> str:
"""Extract page title from HTML."""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
if soup.title and soup.title.string:
return soup.title.string.strip()
return "No title"
def extract_links(self, html: str, base_url: str) -> List[str]:
"""
Extract all links from HTML.
Args:
html: Raw HTML content
base_url: Base URL for resolving relative links
Returns:
List of absolute URLs
"""
from urllib.parse import urljoin, urlparse
links = set()
# Extract from href attributes
for match in self.link_pattern.finditer(html):
href = match.group(1)
if href and not href.startswith(('#', 'javascript:', 'mailto:')):
absolute = urljoin(base_url, href)
links.add(absolute)
# Extract .onion addresses
for match in self.onion_pattern.finditer(html):
onion = match.group()
if not onion.startswith('http'):
onion = f"http://{onion}"
links.add(onion)
return list(links)
def find_keywords(
self,
content: str,
keywords: List[str],
context_chars: int = 100
) -> List[KeywordMatch]:
"""
Find keyword matches with context.
Args:
content: Text content to search
keywords: Keywords to find
context_chars: Characters of context to extract
Returns:
List of keyword matches
"""
matches = []
content_lower = content.lower()
for keyword in keywords:
keyword_lower = keyword.lower()
if keyword_lower not in content_lower:
continue
# Find all occurrences with context
pattern = re.compile(
f'.{{0,{context_chars}}}{re.escape(keyword_lower)}.{{0,{context_chars}}}',
re.IGNORECASE | re.DOTALL
)
found = pattern.findall(content)
if found:
# Take first 3 matches for context
context = ' ... '.join(found[:3])
matches.append(KeywordMatch(
site_id=0, # Set by caller
site_name="", # Set by caller
keyword=keyword,
context=context[:500],
match_count=len(found),
timestamp=datetime.now(timezone.utc),
url="" # Set by caller
))
return matches
def detect_changes(
self,
current_snapshot: ContentSnapshot,
previous_snapshot: Optional[ContentSnapshot]
) -> List[ChangeDetection]:
"""
Detect changes between snapshots.
Args:
current_snapshot: Current content snapshot
previous_snapshot: Previous content snapshot
Returns:
List of detected changes
"""
changes = []
if not previous_snapshot:
# First snapshot - no changes to detect
return changes
# Content hash change
if current_snapshot.content_hash != previous_snapshot.content_hash:
# Calculate word count difference
word_diff = current_snapshot.word_count - previous_snapshot.word_count
# Determine severity based on change magnitude
change_pct = abs(word_diff) / max(previous_snapshot.word_count, 1) * 100
if change_pct > 50:
severity = "CRITICAL"
elif change_pct > 20:
severity = "HIGH"
elif change_pct > 5:
severity = "MEDIUM"
else:
severity = "LOW"
changes.append(ChangeDetection(
site_id=current_snapshot.site_id,
site_name="",
site_url="",
change_type=ChangeType.CONTENT,
timestamp=current_snapshot.timestamp,
severity=severity,
description=f"Content changed ({word_diff:+d} words, {change_pct:.1f}% change)",
old_value=f"{previous_snapshot.word_count} words",
new_value=f"{current_snapshot.word_count} words"
))
# Title change
if current_snapshot.title != previous_snapshot.title:
changes.append(ChangeDetection(
site_id=current_snapshot.site_id,
site_name="",
site_url="",
change_type=ChangeType.STRUCTURE,
timestamp=current_snapshot.timestamp,
severity="MEDIUM",
description="Page title changed",
old_value=previous_snapshot.title,
new_value=current_snapshot.title
))
# Links change
if current_snapshot.links_hash != previous_snapshot.links_hash:
link_diff = current_snapshot.link_count - previous_snapshot.link_count
changes.append(ChangeDetection(
site_id=current_snapshot.site_id,
site_name="",
site_url="",
change_type=ChangeType.NEW_LINKS,
timestamp=current_snapshot.timestamp,
severity="MEDIUM" if abs(link_diff) > 5 else "LOW",
description=f"Links changed ({link_diff:+d} links)",
old_value=f"{previous_snapshot.link_count} links",
new_value=f"{current_snapshot.link_count} links"
))
return changes
# ============================================================================
# SITE MONITOR
# ============================================================================
class SiteMonitor:
"""
Monitors .onion sites through Tor.
Provides:
- Async site checking via Tor
- Content extraction and hashing
- Change detection
- Keyword monitoring
"""
def __init__(
self,
tor_connection: Optional[TorConnection] = None,
timeout: int = 30
):
"""
Initialize site monitor.
Args:
tor_connection: Existing Tor connection (creates new if None)
timeout: Request timeout in seconds
"""
self.tor = tor_connection
self.timeout = timeout
self.scraper: Optional[TorScraper] = None
self.analyzer = ContentAnalyzer()
logger.info("Site monitor initialized", {"timeout": timeout})
async def initialize(self) -> bool:
"""Initialize Tor connection."""
if self.tor is None:
self.tor = TorConnection()
if await self.tor.connect():
self.scraper = TorScraper(self.tor)
await self.scraper.create_session()
logger.info("Site monitor Tor connection established")
return True
logger.error("Failed to establish Tor connection")
return False
async def check_site(
self,
site: MonitoredSite,
previous_snapshot: Optional[ContentSnapshot] = None
) -> CheckResult:
"""
Check a single site.
Args:
site: Site to check
previous_snapshot: Previous content snapshot for comparison
Returns:
Check result with status, content, and changes
"""
start_time = datetime.now(timezone.utc)
logger.info(f"Checking site: {site.name}", {
"site_id": site.id,
"url": site.url[:50]
})
try:
# Fetch page
fetch_start = datetime.now()
html = await self.scraper.fetch(site.url, timeout=self.timeout)
response_time = (datetime.now() - fetch_start).total_seconds() * 1000
if html is None:
return CheckResult(
site=site,
status=MonitorStatus.OFFLINE,
timestamp=start_time,
response_time_ms=response_time,
error="Failed to fetch page"
)
# Extract content
text = self.analyzer.extract_text(html)
title = self.analyzer.extract_title(html)
links = self.analyzer.extract_links(html, site.url)
content_hash = self.analyzer.compute_hash(text)
word_count = len(text.split())
# Create current snapshot
links_hash = hashlib.sha256(
json.dumps(sorted(links)).encode()
).hexdigest()[:16]
current_snapshot = ContentSnapshot(
site_id=site.id,
timestamp=start_time,
content_hash=content_hash,
content_preview=text[:1000],
title=title,
word_count=word_count,
link_count=len(links),
links_hash=links_hash
)
# Detect changes
changes = self.analyzer.detect_changes(current_snapshot, previous_snapshot)
# Update change metadata
for change in changes:
change.site_name = site.name