-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathmessage.py
More file actions
348 lines (294 loc) · 12.3 KB
/
Copy pathmessage.py
File metadata and controls
348 lines (294 loc) · 12.3 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
def _import_or_exit(module, pip_name=None, import_name=None):
try:
if import_name:
return __import__(import_name, fromlist=[module])
return __import__(module)
except ImportError:
pkg = pip_name if pip_name else module
print(f"\n[ERROR] Required package '{pkg}' is not installed.\nPlease install it with: pip install {pkg}\n")
exit(1)
smtplib = _import_or_exit('smtplib')
MIMEText = _import_or_exit('email.mime.text', 'email', 'email.mime.text').MIMEText
MIMEMultipart = _import_or_exit('email.mime.multipart', 'email', 'email.mime.multipart').MIMEMultipart
MIMEImage = _import_or_exit('email.mime.image', 'email', 'email.mime.image').MIMEImage
datetime = _import_or_exit('datetime')
cv2 = _import_or_exit('cv2')
os = _import_or_exit('os')
re = _import_or_exit('re')
dotenv = _import_or_exit('dotenv', 'python-dotenv')
try:
from dotenv import load_dotenv
except ImportError:
print("\n[ERROR] Required package 'python-dotenv' is not installed.\nPlease install it with: pip install python-dotenv\n")
exit(1)
try:
from twilio.rest import Client
except ImportError:
print("\n[ERROR] Required package 'twilio' is not installed.\nPlease install it with: pip install twilio\n")
exit(1)
phonenumbers = _import_or_exit('phonenumbers')
try:
from phonenumbers import geocoder, carrier
except ImportError:
print("\n[ERROR] Required package 'phonenumbers' is not installed.\nPlease install it with: pip install phonenumbers\n")
exit(1)
requests = _import_or_exit('requests')
logging = _import_or_exit('logging')
load_dotenv()
def is_valid_twilio_sid(sid):
# Must start with 'AC' and have 32 hex characters after that
pattern = r"^AC[a-fA-F0-9]{32}$"
return bool(re.match(pattern, sid))
def is_valid_email(email):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return re.match(pattern, email) is not None
def is_valid_password(password):
if not password:
return False
clean = password.replace(" ", "")
return bool(re.fullmatch(r"[a-zA-Z0-9]{16}", clean))
def is_valid_number(number, region="IN"):
try:
parsed = phonenumbers.parse(number, region)
return phonenumbers.is_valid_number(parsed)
except phonenumbers.NumberParseException:
return False
def location():
try:
response = requests.get('https://ipinfo.io/json', timeout=5)
response.raise_for_status()
data = response.json()
if 'city' not in data or 'region' not in data:
logging.warning("Location data missing expected fields.")
return ['Unknown City', 'Unknown Region'], '0,0'
city = data.get('city', 'Unknown City')
region = data.get('region', 'Unknown Region')
coords = data.get('loc', '0,0')
return [city, region], coords
except requests.exceptions.Timeout:
logging.error("[Location Error] Request timed out.")
except requests.exceptions.HTTPError as http_err:
if response.status_code == 429:
logging.error("[Location Error] Rate limit exceeded (HTTP 429).")
elif response.status_code == 503:
logging.error("[Location Error] Service unavailable (HTTP 503).")
else:
logging.error(f"[Location Error] HTTP error occurred: {http_err}")
except requests.exceptions.RequestException as req_err:
logging.error(f"[Location Error] Network-related error: {req_err}")
except ValueError as json_err:
logging.error(f"[Location Error] Failed to parse JSON: {json_err}")
except Exception as e:
logging.exception(f"[Location Error] Unexpected error: {e}")
return ['Unknown City', 'Unknown Region'], '0,0'
sender_email = os.getenv('SENDER_EMAIL')
sender_password = os.getenv('SENDER_PASSWORD')
receiver_emails = os.getenv('RECEIVER_EMAIL', '').split(',')
twilio_sid = os.getenv("TWILIO_ACCOUNT_SID")
twilio_token = os.getenv("TWILIO_AUTH_TOKEN")
twilio_phone = os.getenv("TWILIO_PHONE_NUMBER")
alert_phones = os.getenv("ALERT_PHONE_NUMBERS", "").split(",")
client = Client(twilio_sid, twilio_token)
if not is_valid_number(twilio_phone):
raise ValueError(f"Invalid Twilio phone number: {twilio_phone}")
for num in alert_phones:
num = num.strip()
if not is_valid_number(num):
raise ValueError(f"Invalid alert phone number: {num}")
if not is_valid_twilio_sid(twilio_sid):
raise ValueError(f"Invalid Twilio SID format: {twilio_sid}")
else:
print("Twilio SID format is valid.")
values = {
"SENDER_EMAIL": sender_email,
"SENDER_PASSWORD": sender_password,
"RECEIVER_EMAILS": receiver_emails,
"TWILIO_SID": twilio_sid,
"TWILIO_TOKEN": twilio_token,
"TWILIO_PHONE": twilio_phone,
"ALERT_PHONES": alert_phones
}
for name, value in values.items():
if not value:
raise ValueError(f"Missing `{name}` in .env file")
if not all(is_valid_email(email) for email in receiver_emails + [sender_email]):
raise ValueError("One or more email addresses are invalid.")
if not is_valid_password(sender_password):
raise ValueError("Invalid Gmail app password format")
def saving_failed_sms(name, confidence, number):
locate, coordinates = location()
latitude, longitude = map(float, coordinates.split(','))
googlemaps_link = f"https://www.google.com/maps?q={latitude},{longitude}"
# Save the failed SMS alert details to a file
with open("failed_sms_alerts.txt", "a") as f:
f.write(
f"Name: {name}, Confidence: {confidence}, Time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, "
f"City: {locate[0]}, Region: {locate[1]}, Phone: {number}, Map: {googlemaps_link}\n"
)
def saving_failed_email(name, confidence):
locate, coordinates = location()
latitude, longitude = map(float, coordinates.split(','))
googlemaps_link = f"https://www.google.com/maps?q={latitude},{longitude}"
# Save the failed email alert details to a file
with open("failed_email_alerts.txt", "a") as f:
f.write(
f"Name: {name}, Confidence: {confidence}, Time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, "
f"City: {locate[0]}, Region: {locate[1]}, Map: {googlemaps_link}, Receivers: {receiver_emails}\n"
)
def send_call(name, confidence):
print("📞 Sending call alert...")
locate, coordinates = location()
latitude, longitude = map(float, coordinates.split(','))
city = locate[0]
region = locate[1]
time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message_text = (
f"Alert! Security threat detected. "
f"Name: {name}. Confidence: {int(confidence)} percent. "
f"Location: {city}, {region}. "
f"Time: {time_now}. "
"Please check your security system immediately."
)
twiml_message = f'<Response><Say voice="alice">{message_text}</Say></Response>'
print(f"📞 Call message: {message_text}")
for number in alert_phones:
print(f"📞 Calling {number}...")
try:
call = client.calls.create(
twiml=twiml_message,
to=number.strip(),
from_=twilio_phone
)
print(f"📞 Call alert sent to {number}. Call SID: {call.sid}")
except Exception as e:
print(f"❌ Failed to make call to {number} - {e}")
def send_sms(name, confidence):
#city, region, googlemaps_link
locate, coordinates = location()
latitude, longitude = map(float, coordinates.split(','))
googlemaps_link = f"https://www.google.com/maps?q={latitude},{longitude}"
city=locate[0]
region=locate[1]
time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message_body = (
f"🚨 Security Alert!\n"
f"Name: {name}\n"
f"Confidence: {int(confidence)}%\n"
f"Time: {time_now}\n"
f"Location: {city}, {region}\n"
f"Map: {googlemaps_link}"
)
max_iterations=3
for number in alert_phones:
for i in range (max_iterations):
try:
client.messages.create(
body=message_body,
from_=twilio_phone,
to=number.strip()
)
except Exception as e:
print(f"SMS sending failed: {number}, attempt {i+1} - {e}")
if i==max_iterations-1:
print(f"Failed to send SMS to {number} after {max_iterations} attempts.")
saving_failed_sms(name, confidence, number)
else:
print(f"✅ SMS alert sent successfully to {number}.")
break
def send_email(name,frame,confidence):
locate, coordinates = location()
latitude, longitude = map(float, coordinates.split(','))
googlemaps_link = f"https://www.google.com/maps?q={latitude},{longitude}"
smtp_server = 'smtp.gmail.com'
smtp_port = 587
success, img_encoded = cv2.imencode('.jpg', frame)
if not success:
raise ValueError("Failed to encode the image for email attachment.")
img_data = img_encoded.tobytes()
msg = MIMEMultipart()
msg['Subject'] = f"Security Alert: {name} Detected!"
msg['From'] = sender_email
msg['To'] = ", ".join(receiver_emails)
body = f"""
<html>
<head>
<style>
.container {{
font-family: Arial, sans-serif;
padding: 20px;
background-color: #f9f9f9;
border: 1px solid #ddd;
border-radius: 10px;
width: 90%;
max-width: 600px;
margin: auto;
}}
.header {{
background-color: #f44336;
color: white;
padding: 10px;
border-radius: 10px 10px 0 0;
font-size: 20px;
text-align: center;
}}
.content {{
background-color: white;
padding: 20px;
border-radius: 0 0 10px 10px;
}}
.footer {{
font-size: 12px;
color: #777;
margin-top: 15px;
font-style: italic;
}}
a {{
color: #007bff;
}}
</style>
</head>
<body>
<div class="container">
<div class="header">🚨 Security Alert: {name} Detected</div>
<div class="content">
<p><strong>Emergency!</strong> A face match has been detected.</p>
<ul>
<li><strong>Name:</strong> {name}</li>
<li><strong>Confidence:</strong> {int(confidence)}%</li>
<li><strong>Time:</strong> {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</li>
<li><strong>City:</strong> {locate[0]}</li>
<li><strong>Region:</strong> {locate[1]}</li>
<li><strong>Location:</strong> <a href="{googlemaps_link}" target="_blank">View on Map</a></li>
</ul>
<p>Attached is the detected face image.</p>
<div class="footer">
Disclaimer: This alert is based on facial similarity. Always verify identity before action.
</div>
</div>
</div>
</body>
</html>
"""
msg.attach(MIMEText(body, 'html'))
# Attach face image
image = MIMEImage(img_data, name="detected_face.jpg")
msg.attach(image)
max_retries=3
for i in range(max_retries):
try:
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(sender_email, sender_password)
server.send_message(msg)
except smtplib.SMTPAuthenticationError:
raise ValueError("Failed to authenticate with the SMTP server. Check your email and password.")
except smtplib.SMTPConnectError:
print(f"⚠️ Attempt {i+1}: Connection to SMTP server failed.")
except Exception as e:
print(f"⚠️ Attempt {i+1}: Email sending failed: {e}")
if i == max_retries - 1:
print("❌ Failed to send email after multiple attempts.")
saving_failed_email(name, confidence)
else:
print("✅ Email alert sent successfully.")
break