-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
531 lines (448 loc) · 22 KB
/
app.py
File metadata and controls
531 lines (448 loc) · 22 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
import os
from datetime import datetime, date, timedelta, time
from typing import Optional, List, Tuple
from dotenv import load_dotenv
load_dotenv()
from flask import Flask, jsonify, redirect, render_template, request, url_for, flash, session
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
from sqlalchemy import inspect, and_, text
from extensions import db, login_manager, csrf, cache, limiter
from utils.datetime_utils import utc_now
DEFAULT_CATEGORY_COLORS = {
# Spectrum from casual/ignorable (green/blue) to urgent/attention-demanding (orange/red)
"holiday": "#10b981", # Green - Casual, informational (least urgent)
"tv_show_release": "#14b8a6", # Teal - Entertainment, relaxed
"movie_release": "#06b6d4", # Cyan - Entertainment, planned leisure
"event": "#3b82f6", # Blue - Standard events, neutral priority
"birthday": "#8b5cf6", # Purple - Special occasions, important but joyful
"reminder": "#f97316", # Orange - Needs attention, action required
"meeting": "#ef4444", # Red - Urgent, high priority, demands attention
}
def create_app() -> Flask:
import os
import logging
from logging.handlers import RotatingFileHandler
# Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv()
# Initialize Sentry error tracking (if configured)
if os.environ.get('SENTRY_DSN'):
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(
dsn=os.environ['SENTRY_DSN'],
integrations=[FlaskIntegration()],
traces_sample_rate=0.1, # 10% of requests for performance monitoring
environment=os.environ.get('ENV', 'development'),
)
app = Flask(__name__)
# Use environment variables for production, fallback to dev values
secret_key = os.environ.get('SECRET_KEY', 'dev-secret-key')
# Check if running in test mode
testing_mode = os.environ.get('TESTING', 'False').lower() in ('true', '1', 'yes')
# PostgreSQL database configuration (SQLite removed - Roadmap #11)
# Priority: SQLALCHEMY_DATABASE_URI > DATABASE_URL > error
database_uri = os.environ.get('SQLALCHEMY_DATABASE_URI') or os.environ.get('DATABASE_URL')
if not database_uri:
raise RuntimeError(
"DATABASE_URL or SQLALCHEMY_DATABASE_URI environment variable is required. "
"Example: postgresql://user:password@localhost:5432/dbname"
)
app.config.from_mapping(
SECRET_KEY=secret_key,
TESTING=testing_mode,
SQLALCHEMY_DATABASE_URI=database_uri,
SQLALCHEMY_TRACK_MODIFICATIONS=False,
# APScheduler configuration
SCHEDULER_API_ENABLED=True,
# Session cookie security (production-ready)
SESSION_COOKIE_SECURE=False, # Allow HTTP for local network access
SESSION_COOKIE_HTTPONLY=True, # Prevent JavaScript access
SESSION_COOKIE_SAMESITE='Lax', # CSRF protection
SESSION_COOKIE_DOMAIN=None, # Allow cookie on any domain/IP
PERMANENT_SESSION_LIFETIME=timedelta(days=30),
# Remember Me cookie security
REMEMBER_COOKIE_SECURE=False, # Allow HTTP for local network access
REMEMBER_COOKIE_HTTPONLY=True,
REMEMBER_COOKIE_DURATION=timedelta(days=30),
REMEMBER_COOKIE_SAMESITE='Lax',
)
db.init_app(app)
login_manager.init_app(app)
csrf.init_app(app)
cache.init_app(app, config={'CACHE_TYPE': 'simple'})
limiter.init_app(app)
# Configure logging
if not app.debug and not app.testing:
# Production logging - rotating file handler
if not os.path.exists('logs'):
os.mkdir('logs')
file_handler = RotatingFileHandler(
'logs/pulsefeed.log',
maxBytes=10240000, # 10MB
backupCount=10
)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
app.logger.info('Pulsefeed startup')
else:
# Development logging - console output
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(
'%(levelname)s: %(message)s'
))
console_handler.setLevel(logging.DEBUG)
app.logger.addHandler(console_handler)
app.logger.setLevel(logging.DEBUG)
# Register SQLAlchemy event listeners for automatic user_id injection
from utils.query_scoping import auto_inject_user_id # noqa: F401
# Initialize APScheduler for background sync
from flask_apscheduler import APScheduler
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()
# Configure scheduler jobs (calendar sync, etc.)
from scheduler_jobs import configure_scheduler
configure_scheduler(scheduler, app)
with app.app_context():
from models import Event, User, InviteCode # noqa: F401
# Skip db.create_all() in testing - test fixtures handle database setup
if not app.config.get('TESTING', False):
db.create_all()
# Ensure system categories exist and are up-to-date
# This runs on app startup and syncs SYSTEM_CATEGORIES to the database
from utils.category_utils import ensure_system_categories_exist
ensure_system_categories_exist()
# Ensure system Pulses exist and are up-to-date
# Auto-creates reference data Pulses like US holidays (owned by admin user)
from utils.pulse_utils import ensure_system_pulses_exist
ensure_system_pulses_exist()
# Register activity hooks for decoupled side effects
import listeners
app.logger.info('Activity hooks registered')
@login_manager.user_loader
def load_user(user_id):
return db.session.get(User, int(user_id))
# Lightweight migration: ensure new columns exist, only if table is present
inspector = inspect(db.engine)
table_names = set(inspector.get_table_names())
if "tasks" in table_names:
columns = {col["name"] for col in inspector.get_columns("tasks")}
with db.engine.begin() as conn:
if "category" not in columns:
conn.execute(text("ALTER TABLE tasks ADD COLUMN category VARCHAR(20) NOT NULL DEFAULT 'event'"))
# Import category utilities (make available as template globals, not auto-injected)
from utils.category_utils import get_all_categories, get_all_category_colors, get_category_color
# Import entry access utilities (Roadmap #10 Phase 4)
from utils.entry_access import get_entry_source_info
@app.context_processor
def inject_category_utils():
"""
Inject category utility functions into templates.
Routes must explicitly pass CATEGORIES and category_colors to templates that need them.
This prevents automatic category loading on every page (including error pages).
"""
return {
"get_category_color": get_category_color,
"get_entry_source_info": get_entry_source_info # Roadmap #10 Phase 4
}
@app.context_processor
def inject_navigation_context():
"""
Inject navigation context for sidebar and navbar rendering.
Provides current section, group hierarchy, and active states.
"""
from flask import request
from flask_login import current_user
from repositories.group_repository import GroupRepository
nav_context = {
'active_section': None,
'current_group': None,
'user_groups': []
}
if current_user.is_authenticated:
# Fetch user's groups for navigation (Roadmap #13: flat model, no subgroups)
nav_context['user_groups'] = GroupRepository.get_user_groups(current_user.id)
# Detect current section from request path
if request.path == '/' or request.path == '/index':
nav_context['active_section'] = 'home'
elif request.path.startswith('/hub') or request.path.startswith('/pulse/'):
nav_context['active_section'] = 'hub'
elif request.path.startswith('/calendar/'):
nav_context['active_section'] = 'calendar'
elif request.path.startswith('/groups/'):
nav_context['active_section'] = 'groups'
# Extract group_id from URL
group_id = request.view_args.get('group_id') if request.view_args else None
if group_id:
group = GroupRepository.get(group_id)
if group:
nav_context['current_group'] = group
elif request.path.startswith('/entries'):
nav_context['active_section'] = 'entries'
elif request.path.startswith('/templates'):
nav_context['active_section'] = 'templates'
elif request.path.startswith('/chat'):
nav_context['active_section'] = 'messages'
elif request.path.startswith('/notifications'):
nav_context['active_section'] = 'notifications'
elif request.path.startswith('/profile') or request.path.startswith(f'/user/{current_user.username}'):
nav_context['active_section'] = 'profile'
elif request.path.startswith('/admin'):
nav_context['active_section'] = 'admin'
return {'nav_context': nav_context}
# Import RRULE utilities (imported but not used directly - available for context)
from utils.rrule_utils import build_rrule_from_form # noqa: F401
# Hybrid storage removed - instances now computed on-demand via instance_resolver.py
@app.before_request
def _auto_generate():
# Skip expensive operations for static files (CSS, JS, images)
if request.path.startswith('/static/'):
return
# NOTE: Automatic instance generation removed - was causing duplication issues
# Daily tasks and recurring series instances need alternative approach
pass
@app.after_request
def add_security_and_caching_headers(response):
"""
Add security headers and caching policies.
- Static files: Aggressive caching (1 year)
- Uploaded images: Moderate caching (1 week)
- Authenticated pages: No caching (security)
"""
# Static assets: Cache aggressively (versioned files)
if request.path.startswith('/static/'):
response.headers['Cache-Control'] = 'public, max-age=31536000, immutable'
return response
# Uploaded images: Cache for 1 week
if request.path.startswith('/uploads/'):
response.headers['Cache-Control'] = 'public, max-age=604800'
return response
# Skip auth pages (login, register) - CSRF tokens need to work
auth_pages = ['/login', '/register', '/logout']
if any(request.path.startswith(page) for page in auth_pages):
return response
# For authenticated users, prevent browser caching to avoid showing
# sensitive data after logout (back button security issue)
if current_user.is_authenticated:
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
# Cascading date/time display filter
@app.template_filter('cascading_datetime')
def cascading_datetime_filter(task):
"""
Smart date/time formatting based on proximity and time_type.
Examples:
- "by 10:30pm" (today with specific time)
- "by 10:30pm, Wednesday" (this week with specific time)
- "by Tuesday, Oct 27" (different week)
- "all day" (all_day time_type)
- "any time" (any_time time_type)
"""
today = date.today()
# Use new time fields if available, fallback to old fields
task_date = task.start_date if hasattr(task, 'start_date') and task.start_date else task.due_date
task_time = task.start_time if hasattr(task, 'start_time') and task.start_time else task.due_time
task_time_type = task.time_type if hasattr(task, 'time_type') and task.time_type else None
if not task_date:
return ""
# Handle time_type
if task_time_type == 'all_day':
time_str = "all day"
elif task_time_type == 'any_time':
time_str = "any time"
elif task_time and task_time.strftime('%H:%M') != '23:59':
# Specific time - use platform-appropriate format
try:
time_str = task_time.strftime('%-I:%M%p').lower()
except:
# Windows doesn't support -, use # instead
time_str = task_time.strftime('%I:%M%p').lower().lstrip('0')
else:
time_str = None
# Calculate days difference
days_diff = (task_date - today).days
# Same day
if days_diff == 0:
if time_str == 'any time':
return "any time today"
elif time_str == 'all day':
return "all day today"
elif time_str:
return f"by {time_str}"
return "today"
# Yesterday/Tomorrow
if days_diff == -1:
if time_str == 'any time':
return "any time on yesterday"
elif time_str == 'all day':
return "all day yesterday"
elif time_str:
return f"by {time_str}, yesterday"
return "yesterday"
if days_diff == 1:
if time_str == 'any time':
return "any time on tomorrow"
elif time_str == 'all day':
return "all day tomorrow"
elif time_str:
return f"by {time_str}, tomorrow"
return "tomorrow"
# Within a week
if 0 < days_diff <= 6:
day_name = task_date.strftime('%A')
if time_str == 'any time':
return f"any time on {day_name}"
elif time_str == 'all day':
return f"all day {day_name}"
elif time_str:
return f"by {time_str}, {day_name}"
return day_name
# More than a week but same year
if task_date.year == today.year:
day_name = task_date.strftime('%A')
month_day = task_date.strftime('%b %d')
if time_str == 'any time':
return f"any time on {day_name}, {month_day}"
elif time_str == 'all day':
return f"all day {day_name}, {month_day}"
elif time_str:
return f"by {time_str}, {day_name}, {month_day}"
return f"{day_name}, {month_day}"
# Different year
full_date = task_date.strftime('%b %d, %Y')
if time_str == 'any time':
return f"any time on {full_date}"
elif time_str == 'all day':
return f"all day {full_date}"
elif time_str:
return f"by {time_str}, {full_date}"
return full_date
# ===== ERROR HANDLERS =====
from werkzeug.exceptions import HTTPException
@app.errorhandler(403)
def handle_forbidden(error):
"""Handle 403 Forbidden errors."""
app.logger.warning(f"403 Forbidden: {request.url} - User: {current_user.id if current_user.is_authenticated else 'Anonymous'}")
flash("You don't have permission to access this resource", "error")
return render_template('errors/403.html'), 403
@app.errorhandler(404)
def handle_not_found(error):
"""Handle 404 Not Found errors."""
app.logger.warning(f"404 Not Found: {request.url}")
flash("Page not found", "error")
return render_template('errors/404.html'), 404
@app.errorhandler(500)
def handle_server_error(error):
"""Handle 500 Internal Server Error."""
import traceback as tb
app.logger.error(f"500 Server Error: {error}", exc_info=True)
db.session.rollback() # Critical: rollback failed transaction
flash("An unexpected error occurred. Please try again.", "error")
# Pass error details to template (only in debug mode)
error_message = str(error) if app.debug else None
error_traceback = tb.format_exc() if app.debug else None
return render_template('errors/500.html',
error_message=error_message,
error_traceback=error_traceback,
now=utc_now()), 500
@app.errorhandler(Exception)
def handle_exception(error):
"""Handle all unhandled exceptions."""
import traceback as tb
# Pass HTTPExceptions through (they have their own handlers)
if isinstance(error, HTTPException):
return error
# Log the error with full traceback
app.logger.error(f"Unhandled exception: {error}", exc_info=True)
db.session.rollback()
flash("An unexpected error occurred. Please try again.", "error")
# Pass error details to template (only in debug mode)
error_message = str(error) if app.debug else None
error_traceback = tb.format_exc() if app.debug else None
return render_template('errors/500.html',
error_message=error_message,
error_traceback=error_traceback,
now=utc_now()), 500
# ===== ALL ROUTES MOVED TO BLUEPRINTS =====
# Routes previously defined here have been migrated to:
# - routes/core_routes.py (homepage)
# - routes/api_routes.py (AJAX endpoints)
# - routes/calendar_routes.py (calendar view)
# - routes/event_routes.py (event CRUD)
# - routes/entry_routes.py (entry CRUD)
# - routes/quick_routes.py (quick modals)
# - routes/series_routes.py (series management)
# - routes/template_routes.py (templates page)
# - routes/entries_routes.py (all entries view)
# - routes/settings_routes.py (user settings)
# - routes/auth_routes.py (authentication)
# - routes/social_routes.py (friends, profiles, notifications)
# - routes/sharing_routes.py (friend-to-friend sharing)
# - routes/groups_routes.py (group collaboration)
# - routes/oauth_calendar_routes.py (Google/Microsoft OAuth)
# - routes/chat_routes.py (real-time messaging)
# See routes/__init__.py for blueprint registration
# Register modular blueprints
from routes import register_blueprints
register_blueprints(app)
# Serve uploaded images (Phase 2.2: Image Upload)
@app.route('/uploads/images/<path:subpath>')
def serve_uploaded_image(subpath):
"""Serve uploaded images from instance/uploads/images/."""
from flask import send_from_directory
import os
upload_dir = os.path.join(app.instance_path, 'uploads', 'images')
return send_from_directory(upload_dir, subpath)
# Initialize Celery with Flask app context
from celery_app import celery, init_celery
init_celery(celery, app)
return app
def create_socketio(app: Flask):
"""Create SocketIO instance for real-time features."""
from flask_socketio import SocketIO
from routes import register_socketio_handlers
from services.broadcast_service import BroadcastService
# Threading mode: stable with Flask reloader (good for development)
# Eventlet mode: better performance but crashes with reloader in Python 3.11+
async_mode = os.environ.get('SOCKETIO_ASYNC_MODE', 'threading')
socketio = SocketIO(app, cors_allowed_origins="*", async_mode=async_mode)
# Initialize BroadcastService with socketio reference
# This allows broadcasts without passing socketio every time
BroadcastService.initialize(socketio)
# Register WebSocket handlers for chat
register_socketio_handlers(socketio)
return socketio
# Singleton instances for Flask CLI and module-level imports
_app_instance = None
_socketio_instance = None
def get_app() -> Flask:
"""Get or create app singleton (for Flask CLI)."""
global _app_instance
if _app_instance is None:
_app_instance = create_app()
return _app_instance
def get_socketio():
"""Get or create socketio singleton."""
global _socketio_instance
if _socketio_instance is None:
app = get_app()
_socketio_instance = create_socketio(app)
return _socketio_instance
if __name__ == "__main__":
# Direct run: python app.py (WebSocket support)
# Use get_app() and get_socketio() to ensure singletons are set
app = get_app()
socketio = get_socketio()
port = int(os.environ.get('PORT', 1994))
# allow_unsafe_werkzeug needed for threading mode in development
socketio.run(app, debug=True, host='0.0.0.0', port=port, allow_unsafe_werkzeug=True)
# For Flask CLI: flask run (lazy initialization)
app = get_app()
socketio = get_socketio()