-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
822 lines (737 loc) · 34.8 KB
/
app.py
File metadata and controls
822 lines (737 loc) · 34.8 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
from flask import Flask, render_template, jsonify, request, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_bcrypt import Bcrypt
from flask_socketio import SocketIO
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
import os
from datetime import datetime, timezone,timedelta
import logging
import requests
from functools import wraps
from typing import Optional, Dict, Any, List
from flask_caching import Cache
from flask_migrate import Migrate
from datetime import datetime, timezone
from flask_wtf import CSRFProtect
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, SelectField
from wtforms.validators import DataRequired , EqualTo
from flask_wtf.csrf import CSRFProtect, generate_csrf
import pytz
from werkzeug.utils import secure_filename
from PIL import Image
# Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('werkzeug')
logger.setLevel(logging.DEBUG)
socketio_logger = logging.getLogger('engineio')
socketio_logger.setLevel(logging.DEBUG)
socketio_logger = logging.getLogger('socketio')
socketio_logger.setLevel(logging.DEBUG)
# Configuration
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY')
from dotenv import load_dotenv
load_dotenv()
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
SQLALCHEMY_TRACK_MODIFICATIONS = False # Disable to suppress warnings
SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY')
CACHE_TYPE = 'simple' # Use 'redis' in production
CACHE_DEFAULT_TIMEOUT = 300 # 5 minutes
app = Flask(__name__)
app.config.from_object(Config)
app.config['WTF_CSRF_CHECK_DEFAULT'] = True
app.config['WTF_CSRF_HEADER'] = 'X-CSRFToken' # Ensure Flask-WTF looks for 'X-CSRFToken' header
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
socketio = SocketIO(app, cors_allowed_origins="*")
cache = Cache(app)
sendgrid_client = SendGridAPIClient(app.config['SENDGRID_API_KEY'])
sendgrid_client = SendGridAPIClient(app.config['SENDGRID_API_KEY'])
csrf = CSRFProtect(app)
# Cache decorator
@cache.cached(timeout=300)
def fetch_weather(city: str) -> Optional[Dict[str, Any]]:
"""Fetch weather data with caching."""
api_key = os.environ.get('OPENWEATHERMAP_API_KEY')
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
logger.error(f"Failed to fetch weather for {city}: {str(e)}")
return None
# Ensure the upload directory exists
UPLOAD_FOLDER = 'static/uploads'
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # Limit to 16MB
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def is_valid_image(file):
try:
# Open the image file to verify its content
img = Image.open(file)
# Verify the image (checks the file signature and structure)
img.verify()
# Reload the image to reset the file pointer
img = Image.open(file)
# Get the format to ensure it matches an image type
format = img.format
return format in ['JPEG', 'PNG', 'GIF']
except (IOError, SyntaxError):
return False
# Models
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
role = db.Column(db.String(20), default='public') # admin, responder, public
# Incidents reported by this user (via user_id)
incidents = db.relationship('Incident', foreign_keys='Incident.user_id', back_populates='reported_by')
# Incidents assigned to this user as a responder (via responder_id)
responded_incidents = db.relationship('Incident', foreign_keys='Incident.responder_id', back_populates='responded_by')
__table_args__ = (db.Index('idx_username', 'username'),)
class Incident(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
description = db.Column(db.Text)
location = db.Column(db.String(100), nullable=False)
severity = db.Column(db.String(20), nullable=False) # e.g., low, medium, high, critical
people_affected = db.Column(db.Integer, nullable=False)
incident_type = db.Column(db.String(50), nullable=False) # e.g., road_accident, fire
accident_type = db.Column(db.String(50)) # Optional, for road_accident
contact_number = db.Column(db.String(15),nullable = False) # Optional, 10-digit mobile number
status = db.Column(db.String(20), default='pending')
responder_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
timestamp = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
updates = db.relationship('IncidentUpdate', backref='incident', lazy=True)
reported_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.UTC)) # Add this line
image_path = db.Column(db.String(255), nullable=True) # New field for image path
# Relationships
reported_by = db.relationship('User', foreign_keys=[user_id], back_populates='incidents')
responded_by = db.relationship('User', foreign_keys=[responder_id], back_populates='responded_incidents')
def to_dict(self) -> Dict[str, Any]:
return {
'id': self.id,
'title': self.title,
'description': self.description,
'location': self.location,
'severity': self.severity,
'people_affected': self.people_affected,
'incident_type': self.incident_type,
'accident_type': self.accident_type,
'contact_number': self.contact_number,
'status': self.status,
'lat': getattr(self, 'lat', None),
'lon': getattr(self, 'lon', None),
'timestamp': self.timestamp.isoformat()
}
class IncidentUpdate(db.Model):
id = db.Column(db.Integer, primary_key=True)
incident_id = db.Column(db.Integer, db.ForeignKey('incident.id'), nullable=False)
update_text = db.Column(db.Text, nullable=False)
resources_needed = db.Column(db.String(200))
timestamp = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
updated_by = db.Column(db.Integer, db.ForeignKey('user.id'))
user = db.relationship('User', backref='updates')
class Donation(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
amount = db.Column(db.Float, nullable=False)
message = db.Column(db.String(500), nullable=True) # Add message field
status = db.Column(db.String(50), nullable=False, default='completed') # Add status field
created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
user = db.relationship('User', backref='donations') # Assuming a User model exists
__table_args__ = (db.Index('idx_user_id', 'user_id'),)
def to_dict(self) -> Dict[str, Any]:
return {
'id': self.id,
'user': self.user.username if self.user else 'Anonymous',
'amount': self.amount,
'timestamp': self.timestamp.isoformat()
}
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
class RegisterForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password', message='Passwords must match')])
role = SelectField('Role', choices=[('public', 'Public User'), ('responder', 'Emergency Responder'), ('admin', 'Administrator')], default='public')
submit = SubmitField('Register')
@login_manager.user_loader
def load_user(user_id: int) -> Optional[User]:
return db.session.get(User, user_id)
# Ensure CSRF token is available in templates
@app.before_request
def add_csrf_token():
# Only generate a CSRF token for authenticated users and specific routes
if current_user.is_authenticated and request.endpoint in ['report_page', 'report_disaster']:
if 'csrf_token' not in session:
session['csrf_token'] = generate_csrf()
app.logger.info(f"Generated new CSRF token: {session['csrf_token']}")
else:
app.logger.info(f"Using existing CSRF token: {session['csrf_token']}")
@app.errorhandler(400)
def bad_request_error(error):
return jsonify({'error': str(error) or 'Bad Request'}), 400
# Routes
@app.route('/')
def home():
return render_template('main.html')
@app.route('/report')
@login_required
def report_page():
if 'csrf_token' not in session:
session['csrf_token'] = generate_csrf()
app.logger.info(f"Generated CSRF token for report page: {session['csrf_token']}")
return render_template('report.html')
@app.route('/donate')
@login_required
def donate_page():
app.logger.info('Rendering donate.html')
token = generate_csrf() # Generate CSRF token
app.logger.info(f'CSRF Token: {token}')
return render_template('donate.html')
@app.route('/map')
@login_required
def map_page():
return render_template('map.html')
@socketio.on('connect')
def handle_connect(auth=None):
if current_user.is_authenticated:
socketio.emit('incident_update', {'incidents': [i.to_dict() for i in Incident.query.all()]})
socketio.emit('donation_update', {'donations': [d.to_dict() for d in Donation.query.all()]})
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if request.method == 'POST' and form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user)
return redirect(url_for('home'))
flash('Invalid credentials', 'danger')
return render_template('login.html', form=form)
return render_template('login.html', form=form)
@app.route('/clear-sessions')
def clear_sessions():
session.pop('user_id', None)
return redirect(url_for('home'))
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
if User.query.filter_by(username=form.username.data).first():
flash('Username already exists.', 'danger')
return redirect(url_for('register'))
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
user = User(username=form.username.data, password=hashed_password, role=form.role.data)
db.session.add(user)
db.session.commit()
flash('Registration successful! Please log in.', 'success')
return redirect(url_for('login'))
return render_template('register.html', form=form)
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('home'))
@app.route('/responder/dashboard')
@login_required
def responder_dashboard():
if current_user.role not in ['responder', 'admin']:
flash('Unauthorized access.', 'danger')
return 'Unauthorized', 403
incidents = Incident.query.all()
responders = User.query.filter_by(role='responder').all()
if current_user.role == 'admin':
# Admins see all incidents that are assigned or in progress
assigned_incidents = Incident.query.filter(Incident.status.in_(['assigned', 'in-progress', 'resolved', 'closed'])).all()
# Preload responders for assigned incidents
responder_ids = {incident.responder_id for incident in assigned_incidents if incident.responder_id}
responder_map = {user.id: user.username for user in User.query.filter(User.id.in_(responder_ids)).all()}
else:
# Responders see only their assigned incidents
assigned_incidents = Incident.query.filter_by(responder_id=current_user.id).all()
# No need for responder_map for responders since they don't see this field
responder_map = {}
return render_template('responder_dashboard.html', incidents=incidents, responders=responders, assigned_incidents=assigned_incidents, responder_map=responder_map)
# API Routes
@app.route('/api/health')
def health_check():
return jsonify({'status': 'healthy', 'timestamp': datetime.now(timezone.utc).isoformat()})
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")
@app.route('/api/alerts')
@login_required
def get_alerts():
cities = ['Delhi', 'Mumbai', 'Chennai', 'Kolkata', 'Bengaluru', 'Hyderabad', 'Pune', 'Jaipur', 'Ahmedabad', 'Kanpur']
weather_list = []
for city in cities:
response = requests.get(f"https://api.openweathermap.org/data/2.5/weather", params={"q": city, "appid": OPENWEATHER_API_KEY, "units": "metric"})
if response.status_code == 200:
weather_list.append(response.json())
earthquake_response = requests.get("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojson")
if earthquake_response.status_code == 200:
earthquakes = earthquake_response.json().get('features', [])
india_earthquakes = []
indian_regions = ['india', 'andaman', 'nicobar', 'tamil nadu', 'gujarat', 'kerala', 'karnataka', 'maharashtra', 'west bengal', 'odisha']
exclude_regions = ['nepal', 'pakistan', 'afghanistan', 'china', 'indonesia', 'southeast indian ridge']
for quake in earthquakes:
properties = quake.get('properties', {})
geometry = quake.get('geometry', {})
coordinates = geometry.get('coordinates', [])
place = properties.get('place', '').lower()
#print(f"Quake: {place}, Coordinates: {coordinates}") # Debug raw data
if coordinates and len(coordinates) >= 2:
lon, lat = coordinates[0], coordinates[1]
# Check place name first
place_match = any(region in place for region in indian_regions)
exclude_match = any(region in place for region in exclude_regions)
coord_match = (5 <= lat <= 39 and 67 <= lon <= 99)
# Include if: (place explicitly mentions India or a region AND not excluded) OR (coordinates match AND place explicitly mentions India)
if (place_match and not exclude_match) or (coord_match and 'india' in place):
india_earthquakes.append(quake)
print(f"Filtered Quake: {place}, Coordinates: {coordinates}") # Debug filtered data
else:
print(f"USGS API failed with status: {earthquake_response.status_code}")
india_earthquakes = []
# Placeholder for disasters (assuming a list of dictionaries)
disasters = [] # Replace with actual disaster data logic
return jsonify({
'weather': weather_list, # List of weather objects
'earthquakes': india_earthquakes,
'disasters': disasters
})
@app.route('/report', methods=['GET', 'POST'])
def report():
if not current_user.is_authenticated:
flash('Please log in to report an incident.', 'danger')
return redirect(url_for('login'))
if request.method == 'POST':
try:
title = request.form['title']
location = request.form['location']
severity = request.form['severity']
description = request.form['description']
contact_number = request.form.get('contact_number')
incident = Incident(title=title, location=location, severity=severity, description=description, user_id=current_user.id,contact_number=contact_number,status='pending')
db.session.add(incident)
db.session.commit()
flash('Incident reported successfully!', 'success')
return redirect(url_for('report_success'))
except Exception as e:
db.session.rollback()
flash(f'Error reporting incident: {str(e)}', 'danger')
return redirect(url_for('report'))
return render_template('report.html')
@app.route('/report_success')
def report_success():
return render_template('report_success.html')
@app.route('/api/report-disaster', methods=['POST'])
@login_required
@csrf.exempt # Disable Flask-WTF CSRF for this endpoint
def report_disaster():
app.logger.info(f"Received request headers: {request.headers}")
app.logger.info(f"Received data: {request.form}")
app.logger.info(f"Received files: {request.files}")
# Get form data and file
data = request.form.to_dict()
file = request.files.get('image')
# Validate CSRF token from the request body
received_token = data.get('csrf_token')
expected_token = session.get('csrf_token')
app.logger.info(f"Received CSRF token in body: {received_token}")
app.logger.info(f"Expected CSRF token in session: {expected_token}")
if not received_token or received_token != expected_token:
app.logger.error("CSRF token validation failed")
return jsonify({'error': 'Invalid CSRF token'}), 400
if not data or 'title' not in data or 'description' not in data or 'location' not in data or 'severity' not in data:
app.logger.error("Missing required fields in request data")
return jsonify({'error': 'Missing required fields'}), 400
# Handle image upload
image_path = None
if file:
if not allowed_file(file.filename):
return jsonify({'error': 'Invalid file type. Only PNG, JPG, JPEG, and GIF are allowed.'}), 400
if not is_valid_image(file):
return jsonify({'error': 'Uploaded file is not a valid image.'}), 400
filename = secure_filename(file.filename)
# Generate a unique filename to avoid conflicts
unique_filename = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{filename}"
file.save(os.path.join(app.config['UPLOAD_FOLDER'], unique_filename))
image_path = f"/uploads/{unique_filename}"
elif file and not allowed_file(file.filename):
return jsonify({'error': 'Invalid file type. Only PNG, JPG, JPEG, and GIF are allowed.'}), 400
try:
new_incident = Incident(
title=data['title'],
description=data['description'],
location=data['location'],
severity=data['severity'],
people_affected=int(data.get('people_affected', 0)), # Convert to int
incident_type=data.get('incident_type', 'Other'),
accident_type=data.get('accident_type', None),
contact_number=data.get('contact_number', None),
user_id=current_user.id,
reported_at=datetime.now(timezone.utc),
image_path=image_path # Save the image path
)
db.session.add(new_incident)
db.session.commit()
return jsonify({'message': 'Incident reported successfully','image_path': image_path}), 200
except Exception as e:
db.session.rollback()
app.logger.error(f"Error reporting incident: {str(e)}")
return jsonify({'error': 'Failed to report incident'}), 500
# Decorator to ensure the user is an admin
def admin_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.is_authenticated or current_user.role != 'admin':
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
@app.route('/admin/users')
@login_required
@admin_required
def admin_users():
print("Admin users route hit") # Debug statement
users = User.query.all()
return render_template('admin_users.html', users=users)
@app.route('/admin')
@login_required
def admin_dashboard():
if current_user.role != 'admin':
flash('Unauthorized access.', 'danger')
return redirect(url_for('index'))
users = User.query.all() # Assuming a User model
return render_template('admin_dashboard.html', users=users)
@app.route('/admin/change_role/<int:user_id>', methods=['POST'])
@login_required
def change_user_role(user_id):
if current_user.role != 'admin':
flash('Unauthorized access.', 'danger')
return redirect(url_for('index'))
user = User.query.get_or_404(user_id)
new_role = request.form['role']
user.role = new_role
db.session.commit()
flash(f"Updated role for {user.username} to {new_role}.", 'success')
return redirect(url_for('admin_dashboard'))
@app.route('/admin/update-role', methods=['POST'])
@login_required
@admin_required
def update_user_role():
data = request.get_json()
user_id = data.get('user_id')
new_role = data.get('role')
try:
user_id = int(user_id) # Convert to integer
except (ValueError, TypeError):
return jsonify({'success': False, 'message': 'Invalid user_id'}), 400
if not user_id or not new_role:
return jsonify({'success': False, 'message': 'Missing user_id or role'}), 400
user = User.query.get(user_id)
if not user:
return jsonify({'success': False, 'message': 'User not found'}), 404
if new_role not in ['user', 'responder', 'admin']:
return jsonify({'success': False, 'message': 'Invalid role'}), 400
if user.id == current_user.id and new_role != 'admin':
return jsonify({'success': False, 'message': 'Cannot remove admin role from yourself'}), 403
user.role = new_role
db.session.commit()
return jsonify({'success': True})
@app.route('/admin/delete/<int:user_id>', methods=['POST'])
@login_required
@admin_required
def delete_user(user_id):
if current_user.role != 'admin':
flash('Unauthorized access.', 'danger')
return redirect(url_for('index'))
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
flash('User deleted successfully.', 'success')
return redirect(url_for('admin'))
@app.route('/api/map-data')
@login_required
def get_map_data():
# Fetch incidents
incidents = Incident.query.all()
incident_data = []
for i in incidents:
# For simplicity, assign coordinates based on location (in a real app, use geocoding)
# Using approximate coordinates for major cities for now
city_coords = {
'delhi': [28.6139, 77.2090],
'mumbai': [19.0760, 72.8777],
'chennai': [13.0827, 80.2707],
'kolkata': [22.5726, 88.3639],
'bengaluru': [12.9716, 77.5946],
}
location_lower = i.location.lower()
coords = city_coords.get(location_lower, [28.6139, 77.2090]) # Default to Delhi if not found
incident_data.append({
'location': i.location,
'lat': coords[0],
'lon': coords[1],
'title': i.title,
'severity': i.severity,
'type': 'incident',
'image_path': i.image_path # Add image_path
})
# Fetch earthquakes from the existing alerts endpoint logic
earthquake_response = requests.get("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojson")
earthquake_data = []
if earthquake_response.status_code == 200:
earthquakes = earthquake_response.json().get('features', [])
indian_regions = ['india', 'andaman', 'nicobar', 'tamil nadu', 'gujarat', 'kerala', 'karnataka', 'maharashtra', 'west bengal', 'odisha']
exclude_regions = ['nepal', 'pakistan', 'afghanistan', 'china', 'indonesia', 'indian ocean', 'southeast indian ridge']
for quake in earthquakes:
properties = quake.get('properties', {})
geometry = quake.get('geometry', {})
coordinates = geometry.get('coordinates', [])
place = properties.get('place', '').lower()
if coordinates and len(coordinates) >= 2:
lon, lat = coordinates[0], coordinates[1]
place_match = any(region in place for region in indian_regions)
exclude_match = any(region in place for region in exclude_regions)
coord_match = (5 <= lat <= 39 and 67 <= lon <= 99)
if (place_match and not exclude_match) or (coord_match and 'india' in place):
earthquake_data.append({
'location': properties.get('place', 'Unknown'),
'lat': lat,
'lon': lon,
'title': f"Earthquake - Mag: {properties.get('mag', 'N/A')}",
'severity': 'high', # Earthquakes are treated as high severity for now
'type': 'earthquake'
})
# Placeholder data for relief centers and medical facilities
relief_centers = [
{'location': 'Mumbai Relief Center', 'lat': 19.0760, 'lon': 72.8777, 'title': 'Mumbai Relief Center', 'type': 'relief_center'},
{'location': 'Chennai Relief Center', 'lat': 13.0827, 'lon': 80.2707, 'title': 'Chennai Relief Center', 'type': 'relief_center'}
]
medical_facilities = [
{'location': 'Delhi Medical Facility', 'lat': 28.6139, 'lon': 77.2090, 'title': 'Delhi Medical Facility', 'type': 'medical_facility'},
{'location': 'Kolkata Medical Facility', 'lat': 22.5726, 'lon': 88.3639, 'title': 'Kolkata Medical Facility', 'type': 'medical_facility'}
]
return jsonify({
'incidents': incident_data,
'earthquakes': earthquake_data,
'relief_centers': relief_centers,
'medical_facilities': medical_facilities
})
@app.route('/api/donate', methods=['POST'])
@login_required
def donate():
app.logger.info('Received POST request to /api/donate')
try:
data = request.get_json()
amount = float(data.get('amount'))
message = data.get('message', '')
if not amount or amount <= 0:
app.logger.warning('Invalid donation amount received')
return jsonify({'status': 'error', 'message': 'Invalid donation amount'}), 400
# Save the donation to the database
donation = Donation(
user_id=current_user.id if current_user.is_authenticated else None,
amount=amount,
message=message,
status='completed' # Since there's no payment gateway, mark as completed
)
db.session.add(donation)
db.session.commit()
app.logger.info('Donation saved to database')
return jsonify({'status': 'success', 'message': 'Donation successful'})
except Exception as e:
app.logger.error(f'Error in /api/donate: {str(e)}')
return jsonify({'status': 'error', 'message': 'Internal server error'}), 500
@app.route('/api/donation-progress')
def donation_progress():
app.logger.info('Received request for /api/donation-progress')
try:
# Calculate total donations
total_donations = db.session.query(db.func.sum(Donation.amount)).filter(Donation.status == 'completed').scalar() or 0
# Get recent donors
recent_donors = Donation.query.filter(Donation.status == 'completed').order_by(Donation.created_at.desc()).limit(5).all()
# Define the goal (you can make this dynamic if needed)
goal = 1000000 # Example goal of 10,00,000 INR
# Calculate progress percentage
progress = (total_donations / goal) * 100 if goal > 0 else 0
recent_donors_list = [
{
'user': donation.user.username if donation.user else 'Anonymous',
'amount': float(donation.amount)
}
for donation in recent_donors
]
app.logger.info('Donation progress data prepared successfully')
return jsonify({
'total_donations': float(total_donations),
'goal': float(goal),
'progress': float(progress),
'recent_donors': recent_donors_list
})
except Exception as e:
app.logger.error(f'Error in /api/donation-progress: {str(e)}')
return jsonify({'status': 'error', 'message': 'Internal server error'}), 500
@app.route('/api/navigation')
@login_required
def get_navigation():
start = request.args.get('start')
end = request.args.get('end')
if not start or not end:
return jsonify({'error': 'Missing start or end parameters'}), 400
# Use Nominatim geocoding API to convert locations to coordinates
def geocode(location):
try:
response = requests.get(
f"https://nominatim.openstreetmap.org/search?q={location}&format=json&limit=1",
headers={'User-Agent': 'DisasterWatchIndia/1.0'}
)
if response.status_code == 200 and response.json():
data = response.json()[0]
return {'lat': float(data['lat']), 'lon': float(data['lon'])}
return None
except Exception as e:
logger.error(f"Geocoding error for {location}: {str(e)}")
return None
start_coords = geocode(start)
end_coords = geocode(end)
if not start_coords or not end_coords:
return jsonify({'error': 'Unable to geocode one or both locations'}), 400
return jsonify({
'start': start_coords,
'end': end_coords,
'route': f"Route from {start} to {end}" # Placeholder; actual routing is handled by Leaflet on the frontend
})
@app.route('/responder/assign', methods=['POST'])
@login_required
def assign_incident():
if current_user.role not in ['admin', 'responder']:
return jsonify({'success': False, 'message': 'Unauthorized access.'}), 403
data = request.get_json()
incident_id = data.get('incident_id')
responder_id = data.get('responder_id')
incident = Incident.query.get_or_404(incident_id)
if current_user.role == 'responder' and responder_id != str(current_user.id):
return jsonify({'success': False, 'message': 'Responders can only assign themselves.'}), 403
incident.responder_id = responder_id
incident.status = 'assigned'
db.session.commit()
return jsonify({'success': True, 'message': 'Incident assigned successfully!'})
@app.route('/api/incident/update-status', methods=['POST'])
@login_required
def update_incident_status():
if current_user.role not in ['responder', 'admin']:
return jsonify({'error': 'Unauthorized'}), 403
data = request.json
incident_id = data.get('incident_id')
new_status = data.get('status') # Get the new status from the request
if not incident_id or not new_status:
return jsonify({'error': 'Missing incident_id or status'}), 400
incident = Incident.query.get_or_404(incident_id)
if incident.responder_id != current_user.id and current_user.role != 'admin':
return jsonify({'error': 'Not your incident'}), 403
# Validate the new status
valid_statuses = ['pending', 'assigned', 'in-progress', 'resolved', 'closed']
if new_status not in valid_statuses:
return jsonify({'error': 'Invalid status'}), 400
incident.status = new_status
try:
db.session.commit()
socketio.emit('incident_update', {'incident_id': incident_id, 'status': new_status})
return jsonify({'success': True, 'message': f'Status updated to {new_status}'})
except Exception as e:
db.session.rollback()
logger.error(f"Error updating status: {str(e)}")
return jsonify({'error': 'Database error'}), 500
@app.route('/api/incident/add-update', methods=['POST'])
@login_required
def add_incident_update():
if current_user.role not in ['responder', 'admin']:
return jsonify({'error': 'Unauthorized'}), 403
data = request.json
if not data or 'incident_id' not in data or 'update_text' not in data:
return jsonify({'error': 'Missing incident_id or update_text'}), 400
incident = Incident.query.get(data['incident_id'])
if not incident:
return jsonify({'error': 'Incident not found'}), 404
update = IncidentUpdate(
incident_id=incident.id,
update_text=data['update_text'].strip(),
resources_needed=data.get('resources_needed', '').strip(),
updated_by=current_user.id
)
try:
db.session.add(update)
db.session.commit()
socketio.emit('incident_update', {'incident_id': incident.id, 'status': incident.status})
return jsonify({'success': True, 'message': 'Update added successfully'})
except Exception as e:
db.session.rollback()
logger.error(f"Error adding update: {str(e)}")
return jsonify({'error': 'Database error'}), 500
@app.route('/api/broadcast', methods=['POST'])
@login_required
def broadcast():
if current_user.role != 'admin':
return jsonify({'error': 'Unauthorized'}), 403
data = request.json
if not data or 'title' not in data or 'description' not in data or 'location' not in data:
return jsonify({'error': 'Missing title, description, or location'}), 400
incident = Incident(
title=data['title'].strip(),
description=data['description'].strip(),
location=data['location'].strip(),
severity='high', # Default severity for broadcasts
people_affected=0,
incident_type='broadcast',
status='pending'
)
try:
db.session.add(incident)
db.session.commit()
broadcast_data = {
'title': incident.title,
'description': incident.description,
'location': incident.location
}
socketio.emit('new_incident', broadcast_data)
# Email broadcast to all responders
responders = User.query.filter_by(role='responder').all()
emails = [f"{r.username}@example.com" for r in responders] # Adjust email format as needed
if emails:
message = Mail(
from_email='alerts@disasterwatch.com',
to_emails=emails,
subject=f"Emergency Broadcast: {incident.title}",
html_content=f"<strong>{incident.description}</strong><br>Location: {incident.location}"
)
try:
sendgrid_client.send(message)
logger.info(f"Broadcast email sent to {len(emails)} responders")
except Exception as e:
logger.error(f"Failed to send broadcast email: {str(e)}")
return jsonify({'status': 'broadcast_sent'})
except Exception as e:
db.session.rollback()
logger.error(f"Error in broadcast: {str(e)}")
return jsonify({'error': 'Broadcast failed'}), 500
# Rest of your app config...
if __name__ == '__main__':
socketio.run(app, debug=True, host='0.0.0.0', port=5000)