-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1475 lines (1238 loc) · 58.4 KB
/
app.py
File metadata and controls
1475 lines (1238 loc) · 58.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
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
import os
import sqlite3
import logging
import datetime
import json
from flask import g, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
# Logging yapılandırması (early setup)
# Logging yapılandırması (early setup)
handlers = [logging.StreamHandler()]
# Only add FileHandler if we are locally developing (not on Vercel)
if not os.environ.get('VERCEL'):
try:
handlers.append(logging.FileHandler('pomodev.log'))
except IOError:
pass # Ignore if we can't write to file
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=handlers
)
logger = logging.getLogger(__name__)
# Optional imports with fallbacks
try:
from flask_cors import CORS
CORS_AVAILABLE = True
except ImportError:
CORS_AVAILABLE = False
logger.warning("flask-cors not installed. CORS support disabled. Install with: pip install flask-cors")
try:
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
LIMITER_AVAILABLE = True
except ImportError:
LIMITER_AVAILABLE = False
logger.warning("flask-limiter not installed. Rate limiting disabled. Install with: pip install flask-limiter")
try:
from flask_caching import Cache
CACHE_AVAILABLE = True
except ImportError:
CACHE_AVAILABLE = False
logger.warning("flask-caching not installed. Caching disabled. Install with: pip install flask-caching")
# Vercel için path ayarları
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')
# Environment variables
# Load from .env file if exists
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass # python-dotenv not installed, use environment variables directly
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Database Configuration
# Priority:
# 1. DATABASE_URL env var (Production DB like Postgres)
# 2. Local file if writable (Local development)
# 3. /tmp/pomodev.db (Vercel/Serverless fallback - ephemeral)
DATABASE_URL = os.environ.get('DATABASE_URL')
# Database Configuration Refined
DATABASE_URL = os.environ.get('DATABASE_URL')
if DATABASE_URL:
DATABASE = DATABASE_URL
if DATABASE.startswith('sqlite:///'):
DATABASE = DATABASE.replace('sqlite:///', '')
else:
# Check if we are on Vercel (or generally read-only filesystem)
# Using /tmp as fallback for serverless environments where root is read-only
# We rely on VERCEL env var or if we are in a lambda environment
if os.environ.get('VERCEL') or os.environ.get('AWS_LAMBDA_FUNCTION_NAME'):
DATABASE = '/tmp/pomodev.db'
else:
DATABASE = os.path.join(BASE_DIR, 'pomodev.db')
print(f"DEBUG: Using database at {DATABASE}") # Stdout log for Vercel
SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-secret-key-change-in-production')
DEBUG = os.environ.get('DEBUG', 'False').lower() == 'true'
TOKEN_EXPIRY_DAYS = int(os.environ.get('TOKEN_EXPIRY_DAYS', '30'))
app = Flask(__name__,
template_folder=TEMPLATE_DIR,
static_folder=STATIC_DIR)
app.config['SECRET_KEY'] = SECRET_KEY
# CORS Configuration
if CORS_AVAILABLE:
try:
CORS(app, origins=os.environ.get('ALLOWED_ORIGINS', '*').split(','))
except Exception:
pass
# Security Headers
@app.after_request
def add_security_headers(response):
if not CORS_AVAILABLE:
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
response.headers['X-XSS-Protection'] = '1; mode=block'
return response
# Rate Limiting
if LIMITER_AVAILABLE:
limiter = Limiter(
app=app,
key_func=get_remote_address,
default_limits=["200 per day", "50 per hour"],
storage_uri="memory://"
)
else:
class DummyLimiter:
def limit(self, *args, **kwargs):
def decorator(f): return f
return decorator
limiter = DummyLimiter()
# Cache
if CACHE_AVAILABLE:
cache = Cache(app, config={'CACHE_TYPE': 'simple', 'CACHE_DEFAULT_TIMEOUT': 300})
else:
class DummyCache:
def cached(self, *args, **kwargs):
def decorator(f): return f
return decorator
def delete(self, *args, **kwargs): pass
cache = DummyCache()
# DB Functions
def get_db():
db = getattr(g, '_database', None)
if db is None:
try:
db = g._database = sqlite3.connect(DATABASE)
db.row_factory = sqlite3.Row
except sqlite3.Error as e:
logger.error(f"Database connection error: {str(e)}")
raise
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
def init_db():
with app.app_context():
db = get_db()
db.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL, auth_token TEXT, token_expiry TIMESTAMP, level INTEGER DEFAULT 1, xp INTEGER DEFAULT 0, inventory TEXT DEFAULT "[]", stats TEXT DEFAULT "{}", settings TEXT DEFAULT "{}", tasks TEXT DEFAULT "[]", created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)')
try:
db.execute('ALTER TABLE users ADD COLUMN token_expiry TIMESTAMP')
except sqlite3.OperationalError:
pass
db.execute('CREATE TABLE IF NOT EXISTS sessions (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, mode TEXT NOT NULL, duration INTEGER NOT NULL, completed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, project TEXT, task_id TEXT, FOREIGN KEY (user_id) REFERENCES users (id))')
db.execute('CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, text TEXT NOT NULL, is_completed BOOLEAN DEFAULT 0, project TEXT DEFAULT "General", created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users (id))')
db.execute('CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, content TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users (id))')
db.execute('CREATE TABLE IF NOT EXISTS online_users (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, ip_address TEXT, last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP, mode TEXT DEFAULT "pomodoro")')
try:
db.execute('CREATE INDEX IF NOT EXISTS idx_user_token ON users(auth_token)')
except sqlite3.OperationalError:
pass
db.commit()
# Initialize DB on start with Error Handling
try:
init_db()
except Exception as e:
# Log error but allow app to start so we can see the logs
print(f"CRITICAL ERROR: Failed to initialize database: {e}")
# We might want to set a flag to show a maintenance page or error
app.config['DB_ERROR'] = str(e)
import uuid
# ===== Helper Functions =====
def get_auth_token():
"""Extract auth token from request"""
token = request.headers.get('Authorization')
if token and token.startswith('Bearer '):
token = token[7:].strip()
if not token:
token = request.args.get('token')
if not token:
data = request.get_json(silent=True)
if data:
token = data.get('token')
return token
def validate_token(token):
"""Validate token and check expiry"""
if not token:
return None, "No token provided"
db = get_db()
user = db.execute(
'SELECT id, username, level, xp, inventory, stats, settings, tasks, token_expiry FROM users WHERE auth_token = ?',
(token,)
).fetchone()
if not user:
return None, "Invalid token"
# Check token expiry
if user['token_expiry']:
expiry = datetime.datetime.fromisoformat(user['token_expiry'])
if datetime.datetime.now() > expiry:
logger.warning(f"Expired token used: {user['username']}")
return None, "Token expired"
return user, None
def generate_token_expiry():
"""Generate token expiry datetime"""
return datetime.datetime.now() + datetime.timedelta(days=TOKEN_EXPIRY_DAYS)
# ... existing code ...
# ===== INPUT VALIDATION UTILITIES =====
import re
import html
def sanitize_string(text, max_length=1000, allow_newlines=False):
"""Sanitize string input"""
if not text:
return ""
if not isinstance(text, str):
return str(text)
# Strip whitespace
text = text.strip()
# Truncate
if len(text) > max_length:
text = text[:max_length]
# Escape HTML
text = html.escape(text)
return text
def validate_username(username):
"""Validate username format"""
if not username:
return False, "Username is required"
username = username.strip()
if len(username) < 3:
return False, "Username must be at least 3 characters"
if len(username) > 20:
return False, "Username must be at most 20 characters"
# Alphanumeric and underscores only
if not re.match(r"^[a-zA-Z0-9_]+$", username):
return False, "Username can only contain letters, numbers, and underscores"
return True, username
def validate_password(password):
"""Validate password strength"""
if not password:
return False, "Password is required"
if len(password) < 6:
return False, "Password must be at least 6 characters"
if len(password) > 128:
return False, "Password must be at most 128 characters"
return True, password
def validate_task_text(text):
"""Validate task text"""
if not text or not isinstance(text, str):
return False, "Task text is required"
text = sanitize_string(text, max_length=500)
if len(text) < 1:
return False, "Task text cannot be empty"
return True, text
# ===== RESPONSE HELPERS =====
def success_response(data=None, message="Success", status_code=200):
"""Standardized success response"""
response = {
"success": True,
"data": data,
"message": message,
"error": None
}
return jsonify(response), status_code
def error_response(error="An error occurred", status_code=400, data=None):
"""Standardized error response"""
response = {
"success": False,
"data": data,
"message": None,
"error": error
}
return jsonify(response), status_code
# ===== SOCIAL & MULTIPLAYER API =====
@app.route('/api/social/heartbeat', methods=['POST'])
@limiter.limit("120 per minute") # Allow frequent polling (every 30s = 2 per min + buffer)
def social_heartbeat():
"""Update user's online status"""
try:
data = request.get_json() or {}
mode = data.get('mode', 'pomodoro')
# Try to identify user by token, otherwise by IP
token = get_auth_token()
user_id = None
if token:
user, _ = validate_token(token)
if user:
user_id = user['id']
ip_address = get_remote_address()
now = datetime.datetime.utcnow()
db = get_db()
# Check if entry exists for this IP or User
if user_id:
cursor = db.execute('SELECT id FROM online_users WHERE user_id = ?', (user_id,))
else:
cursor = db.execute('SELECT id FROM online_users WHERE ip_address = ? AND user_id IS NULL', (ip_address,))
entry = cursor.fetchone()
if entry:
# Update existing
db.execute('UPDATE online_users SET last_seen = ?, mode = ?, ip_address = ? WHERE id = ?',
(now, mode, ip_address, entry['id']))
else:
# Insert new
db.execute('INSERT INTO online_users (user_id, ip_address, last_seen, mode) VALUES (?, ?, ?, ?)',
(user_id, ip_address, now, mode))
db.commit()
return success_response(None, "Heartbeat received")
except Exception as e:
logger.error(f"Error in social_heartbeat: {str(e)}", exc_info=True)
return error_response("Heartbeat failed", 500)
@app.route('/api/social/status', methods=['GET'])
@limiter.limit("60 per minute")
def get_social_status():
"""Get active user count and stats"""
try:
db = get_db()
# Define "Active" as seen in last 5 minutes
threshold = datetime.datetime.utcnow() - datetime.timedelta(minutes=5)
# Count active users
count = db.execute('SELECT COUNT(*) FROM online_users WHERE last_seen > ?', (threshold,)).fetchone()[0]
# Get mode distribution (e.g., how many in pomodoro vs break)
modes = db.execute('''
SELECT mode, COUNT(*) as count
FROM online_users
WHERE last_seen > ?
GROUP BY mode
''', (threshold,)).fetchall()
mode_stats = {row['mode']: row['count'] for row in modes}
# Clean up very old entries (older than 1 hour) to keep DB small
# In a production app, use a cron job, but here we do lazy cleanup
cleanup_threshold = datetime.datetime.utcnow() - datetime.timedelta(hours=1)
db.execute('DELETE FROM online_users WHERE last_seen < ?', (cleanup_threshold,))
db.commit()
return success_response({
'active_users': max(1, count), # Always show at least 1 (yourself)
'modes': mode_stats
}, "Social status retrieved")
except Exception as e:
logger.error(f"Error in get_social_status: {str(e)}", exc_info=True)
return error_response("Failed to get status", 500)
def validate_note_content(content):
"""Validate note content"""
if not content or not isinstance(content, str):
return False, "Note content is required"
content = sanitize_string(content, max_length=2000, allow_newlines=True)
if len(content) < 1:
return False, "Note content cannot be empty"
return True, content
def validate_integer(value, min_val=None, max_val=None, default=0):
"""Validate and convert to integer"""
try:
value = int(value)
if min_val is not None and value < min_val:
value = min_val
if max_val is not None and value > max_val:
value = max_val
return value
except (ValueError, TypeError):
return default
def validate_json_string(value, max_length=10000):
"""Validate JSON string data"""
if not value:
return True, value
if not isinstance(value, str):
try:
value = json.dumps(value)
except (TypeError, ValueError):
return False, "Invalid JSON data"
if len(value) > max_length:
return False, f"Data too large (max {max_length} characters)"
# Verify it's valid JSON
try:
json.loads(value)
except json.JSONDecodeError:
return False, "Invalid JSON format"
return True, value
@app.route('/')
def index():
return render_template('index.html')
@app.route('/blog')
def blog_index():
return render_template('blog.html')
@app.route('/blog/pomodoro-nasil-uygulanir')
def blog_pomodoro():
return render_template('blog_pomodoro.html')
@app.route('/blog/derin-calisma-ipuclari')
def blog_deepwork():
return render_template('blog_deepwork.html')
@app.route('/blog/en-iyi-pomodoro-timer-uygulamalari-2024')
def blog_best_timers():
return render_template('blog_best_pomodoro_timers.html')
@app.route('/blog/ogrenciler-icin-pomodoro-rehberi')
def blog_students():
return render_template('blog_students_guide.html')
@app.route('/blog/programcilar-icin-deep-work')
def blog_programmers():
return render_template('blog_programmers_deepwork.html')
@app.route('/blog/adhd-icin-pomodoro')
def blog_adhd():
return render_template('blog_adhd_pomodoro.html')
@app.route('/llms.txt')
def llms_txt():
return send_from_directory(BASE_DIR, 'llms.txt', mimetype='text/plain')
@app.route('/sitemap.xml')
def sitemap():
"""Dynamic sitemap with lastmod dates for SEO"""
base_url = os.environ.get('SITE_URL', 'https://pomodev-omega.vercel.app')
today = datetime.datetime.utcnow().strftime('%Y-%m-%d')
# Pages with lastmod - blog posts can have individual dates
pages = [
('/', today, '1.0'),
('/blog', today, '0.9'),
('/blog/pomodoro-nasil-uygulanir', today, '0.8'),
('/blog/derin-calisma-ipuclari', today, '0.8'),
('/blog/en-iyi-pomodoro-timer-uygulamalari-2024', today, '0.8'),
('/blog/ogrenciler-icin-pomodoro-rehberi', today, '0.8'),
('/blog/programcilar-icin-deep-work', today, '0.8'),
('/blog/adhd-icin-pomodoro', today, '0.8'),
('/hakkimizda', today, '0.6'),
('/kullanim-kilavuzu', today, '0.7'),
('/gecmis', today, '0.7'),
('/dashboard', today, '0.7'),
('/mini-player', today, '0.6'),
('/gizlilik-politikasi', today, '0.4'),
('/kullanim-sartlari', today, '0.4'),
]
xml = ['<?xml version="1.0" encoding="UTF-8"?>']
xml.append('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">')
for path, lastmod, priority in pages:
xml.append(f' <url>')
xml.append(f' <loc>{base_url}{path}</loc>')
xml.append(f' <lastmod>{lastmod}</lastmod>')
xml.append(f' <changefreq>weekly</changefreq>')
xml.append(f' <priority>{priority}</priority>')
xml.append(f' </url>')
xml.append('</urlset>')
from flask import Response
return Response('\n'.join(xml), mimetype='application/xml')
@app.route('/mini-player')
def mini_player():
return render_template('mini_player.html')
@app.route('/hakkimizda')
def about():
return render_template('about.html')
@app.route('/kullanim-kilavuzu')
def guide():
return render_template('guide.html')
@app.route('/gecmis')
def history():
return render_template('history.html')
@app.route('/dashboard')
def dashboard():
return render_template('dashboard.html')
@app.route('/api/calendar/config', methods=['GET'])
def get_calendar_config():
"""Get Google Calendar API configuration"""
try:
# In production, load from environment variables
client_id = os.environ.get('GOOGLE_CALENDAR_CLIENT_ID', '')
return success_response({
'clientId': client_id,
'enabled': bool(client_id)
}, "Calendar config retrieved")
except Exception as e:
logger.error(f"Error in get_calendar_config: {str(e)}", exc_info=True)
return error_response("Failed to get calendar config", 500)
@app.route('/calendar/callback')
def calendar_callback():
"""OAuth callback page: reads token from URL hash and sends to opener window."""
return render_template('calendar_callback.html')
@app.route('/api/calendar/add-event', methods=['POST'])
@limiter.limit("30 per hour")
def add_calendar_event():
"""Add pomodoro session to Google Calendar via backend proxy"""
try:
token = get_auth_token()
user, error = validate_token(token)
if error:
return error_response(error, 401 if "No token" in error else 403)
data = request.get_json()
if not data or 'session' not in data or 'calendarToken' not in data:
return error_response("Missing session or calendarToken", 400)
session = data['session']
calendar_token = data['calendarToken']
# Create calendar event
start_time = datetime.datetime.fromisoformat(session['timestamp'].replace('Z', '+00:00'))
duration = session.get('duration', 25)
end_time = start_time + datetime.timedelta(minutes=duration)
event = {
'summary': f"⏱ Pomodoro - {session.get('mode', 'pomodoro')}",
'description': f"Pomodev ile tamamlanan {duration} dakikal─▒k pomodoro seans─▒",
'start': {
'dateTime': start_time.isoformat(),
'timeZone': 'UTC'
},
'end': {
'dateTime': end_time.isoformat(),
'timeZone': 'UTC'
}
}
# Make request to Google Calendar API
try:
import requests
except ImportError:
return error_response("requests library not installed", 500)
response = requests.post(
'https://www.googleapis.com/calendar/v3/calendars/primary/events',
headers={
'Authorization': f'Bearer {calendar_token}',
'Content-Type': 'application/json'
},
json=event,
timeout=10
)
if response.status_code != 200:
return error_response(f"Calendar API error: {response.text}", 500)
logger.info(f"User {user['username']} added calendar event")
return success_response(response.json(), "Event added to calendar")
except Exception as e:
logger.error(f"Error in add_calendar_event: {str(e)}", exc_info=True)
return error_response("Failed to add calendar event", 500)
@app.route('/gizlilik-politikasi')
def privacy():
return render_template('privacy.html')
@app.route('/kullanim-sartlari')
def terms():
return render_template('terms.html')
@app.route('/static/<path:filename>')
def static_files(filename):
return send_from_directory(STATIC_DIR, filename)
@app.route('/ads.txt')
def ads_txt():
try:
# Önce root dizinden dene
return send_from_directory(BASE_DIR, 'ads.txt', mimetype='text/plain')
except:
# Sonra static dizinden dene
return send_from_directory(STATIC_DIR, 'ads.txt', mimetype='text/plain')
# ===== Error Handlers =====
@app.errorhandler(404)
def not_found(error):
logger.warning(f"404 Error: {request.url}")
return error_response("Resource not found", 404)
@app.errorhandler(500)
def internal_error(error):
logger.error(f"500 Error: {str(error)}", exc_info=True)
return error_response("Internal server error", 500)
@app.errorhandler(Exception)
def handle_exception(e):
logger.error(f"Unhandled exception: {str(e)}", exc_info=True)
return error_response("An unexpected error occurred", 500)
# ===== MAIN API ROUTES START HERE =====
@app.route('/api/notes', methods=['GET'])
@limiter.limit("100 per hour")
def get_notes():
try:
token = get_auth_token()
user, error = validate_token(token)
if error:
return error_response(error, 401 if "No token" in error else 403)
db = get_db()
notes = db.execute('SELECT * FROM notes WHERE user_id = ? ORDER BY created_at DESC', (user['id'],)).fetchall()
notes_data = [{'id': r['id'], 'content': r['content']} for r in notes]
logger.info(f"User {user['username']} retrieved {len(notes_data)} notes")
return success_response(notes_data, "Notes retrieved successfully")
except Exception as e:
logger.error(f"Error in get_notes: {str(e)}", exc_info=True)
return error_response("Failed to retrieve notes", 500)
@app.route('/api/notes', methods=['POST'])
@limiter.limit("50 per hour")
def create_note():
try:
data = request.get_json()
token = get_auth_token()
content = data.get('content') if data else None
if not content:
return error_response("Content is required", 400)
user, error = validate_token(token)
if error:
return error_response(error, 401 if "No token" in error else 403)
db = get_db()
cursor = db.execute('INSERT INTO notes (user_id, content) VALUES (?, ?)', (user['id'], content))
db.commit()
logger.info(f"User {user['username']} created note {cursor.lastrowid}")
return success_response({'id': cursor.lastrowid, 'content': content}, "Note created successfully", 201)
except Exception as e:
logger.error(f"Error in create_note: {str(e)}", exc_info=True)
return error_response("Failed to create note", 500)
@app.route('/api/notes/<int:note_id>', methods=['DELETE'])
@limiter.limit("50 per hour")
def delete_note(note_id):
try:
token = get_auth_token()
user, error = validate_token(token)
if error:
return error_response(error, 401 if "No token" in error else 403)
db = get_db()
result = db.execute('DELETE FROM notes WHERE id = ? AND user_id = ?', (note_id, user['id']))
db.commit()
if result.rowcount == 0:
return error_response("Note not found", 404)
logger.info(f"User {user['username']} deleted note {note_id}")
return success_response(None, "Note deleted successfully")
except Exception as e:
logger.error(f"Error in delete_note: {str(e)}", exc_info=True)
return error_response("Failed to delete note", 500)
@app.route('/api/tasks', methods=['GET'])
@limiter.limit("100 per hour")
def get_tasks():
try:
token = get_auth_token()
user, error = validate_token(token)
if error:
return error_response(error, 401 if "No token" in error else 403)
db = get_db()
tasks = db.execute('SELECT * FROM tasks WHERE user_id = ? ORDER BY created_at DESC', (user['id'],)).fetchall()
tasks_data = [{
'id': row['id'],
'text': row['text'],
'completed': bool(row['is_completed']),
'project': row['project']
} for row in tasks]
logger.info(f"User {user['username']} retrieved {len(tasks_data)} tasks")
return success_response(tasks_data, "Tasks retrieved successfully")
except Exception as e:
logger.error(f"Error in get_tasks: {str(e)}", exc_info=True)
return error_response("Failed to retrieve tasks", 500)
@app.route('/api/tasks', methods=['POST'])
@limiter.limit("50 per hour")
def create_task():
try:
data = request.get_json()
token = get_auth_token()
text = data.get('text') if data else None
project = data.get('project', 'General') if data else 'General'
if not text:
return error_response("Text is required", 400)
user, error = validate_token(token)
if error:
return error_response(error, 401 if "No token" in error else 403)
db = get_db()
cursor = db.execute('INSERT INTO tasks (user_id, text, project) VALUES (?, ?, ?)', (user['id'], text, project))
db.commit()
logger.info(f"User {user['username']} created task {cursor.lastrowid}")
return success_response({
'id': cursor.lastrowid,
'text': text,
'project': project,
'completed': False
}, "Task created successfully", 201)
except Exception as e:
logger.error(f"Error in create_task: {str(e)}", exc_info=True)
return error_response("Failed to create task", 500)
@app.route('/api/tasks/<int:task_id>', methods=['PUT'])
@limiter.limit("100 per hour")
def update_task(task_id):
try:
data = request.get_json()
token = get_auth_token()
user, error = validate_token(token)
if error:
return error_response(error, 401 if "No token" in error else 403)
db = get_db()
task = db.execute('SELECT id FROM tasks WHERE id = ? AND user_id = ?', (task_id, user['id'])).fetchone()
if not task:
return error_response("Task not found", 404)
updates = []
if 'completed' in data:
db.execute('UPDATE tasks SET is_completed = ? WHERE id = ?', (data['completed'], task_id))
updates.append('completed')
if 'text' in data:
db.execute('UPDATE tasks SET text = ? WHERE id = ?', (data['text'], task_id))
updates.append('text')
if 'project' in data:
db.execute('UPDATE tasks SET project = ? WHERE id = ?', (data['project'], task_id))
updates.append('project')
db.commit()
logger.info(f"User {user['username']} updated task {task_id}: {', '.join(updates)}")
return success_response(None, "Task updated successfully")
except Exception as e:
logger.error(f"Error in update_task: {str(e)}", exc_info=True)
return error_response("Failed to update task", 500)
# ===== INTEGRATIONS (TODOIST) =====
@app.route('/api/integrations/todoist/import', methods=['POST'])
@limiter.limit("20 per hour")
def import_todoist_tasks():
"""Import tasks from Todoist"""
try:
data = request.get_json()
todoist_token = data.get('todoistToken')
if not todoist_token:
return error_response("Todoist token is required", 400)
token = get_auth_token()
user, error = validate_token(token)
if error:
return error_response(error, 401)
# Fetch from Todoist API
try:
import requests
headers = {"Authorization": f"Bearer {todoist_token}"}
# Fetch active tasks
response = requests.get("https://api.todoist.com/rest/v2/tasks", headers=headers, params={"filter": "today|overdue"})
if response.status_code != 200:
return error_response("Failed to connect to Todoist. Check your token.", 400)
tasks = response.json()
# Save to local DB
db = get_db()
imported_count = 0
for t in tasks:
content = t.get('content', '')
if not content: continue
# Check duplicate (simple check by text for today)
exists = db.execute('''
SELECT id FROM tasks
WHERE user_id = ? AND text = ? AND is_completed = 0
''', (user['id'], content)).fetchone()
if not exists:
db.execute('INSERT INTO tasks (user_id, text, project) VALUES (?, ?, ?)',
(user['id'], content, 'Todoist'))
imported_count += 1
db.commit()
return success_response({
"count": imported_count,
"message": f"Successfully imported {imported_count} tasks from Todoist"
}, "Import successful")
except ImportError:
return error_response("Requests library missing on server", 500)
except Exception as e:
logger.error(f"Todoist API Error: {str(e)}")
return error_response("Error communicating with Todoist", 502)
except Exception as e:
logger.error(f"Error in import_todoist_tasks: {str(e)}", exc_info=True)
return error_response("Internal Server Error", 500)
# ===== AI TASK BREAKDOWN =====
@app.route('/api/ai/breakdown-task', methods=['POST'])
@limiter.limit("10 per hour")
def ai_breakdown_task():
"""Break down a task into subtasks using 'AI' (Mock or Real)"""
try:
data = request.get_json()
task_text = data.get('text')
if not task_text:
return error_response("Task text is required", 400)
# Simulating AI Processing delay
import time
import random
time.sleep(1.5)
# --- MOCK AI LOGIC (Rule Based) ---
# In a real app, you would call OpenAI/Gemini API here
# api_key = os.environ.get('OPENAI_API_KEY')
subtasks = []
lower_text = task_text.lower()
if "python" in lower_text or "kod" in lower_text or "app" in lower_text:
subtasks = [
f"Research requirements for {task_text}",
"Setup development environment",
"Draft initial code structure",
"Write core functions",
"Debug and test",
"Refactor and optimize"
]
elif "spor" in lower_text or "egzersiz" in lower_text:
subtasks = [
"Isınma hareketleri (5 dk)",
"Ana antrenman seti 1",
"Ana antrenman seti 2",
"Soğuma ve esneme"
]
elif "ders" in lower_text or "çalış" in lower_text or "okul" in lower_text:
subtasks = [
"Materyalleri hazırla",
"Konu özetini oku (25 dk)",
"Pratik test çöz (25 dk)",
"Hataları analiz et"
]
elif "temiz" in lower_text:
subtasks = [
"Dağınıklığı topla",
"Yüzeyleri sil",
"Süpür ve paspasla",
"Çöpleri at"
]
else:
# Generic breakdown
subtasks = [
f"Plan: {task_text} için hazırlık yap",
"İlk 25 dakika: Giriş ve araştırma",
"İkinci 25 dakika: Ana işe odaklan",
"Son kontrol ve bitiriş"
]
return success_response({
"subtasks": subtasks,
"message": "AI logic generated subtasks"
}, "Success")
except Exception as e:
logger.error(f"Error in ai_breakdown_task: {str(e)}", exc_info=True)
return error_response("AI Processing Failed", 500)
@app.route('/api/tasks/<int:task_id>', methods=['DELETE'])
@limiter.limit("50 per hour")
def delete_task(task_id):
try:
token = get_auth_token()
user, error = validate_token(token)
if error:
return error_response(error, 401 if "No token" in error else 403)
db = get_db()
result = db.execute('DELETE FROM tasks WHERE id = ? AND user_id = ?', (task_id, user['id']))
db.commit()
if result.rowcount == 0:
return error_response("Task not found", 404)
logger.info(f"User {user['username']} deleted task {task_id}")
return success_response(None, "Task deleted successfully")
except Exception as e:
logger.error(f"Error in delete_task: {str(e)}", exc_info=True)
return error_response("Failed to delete task", 500)
@app.route('/api/register', methods=['POST'])
@limiter.limit("5 per minute")
def register():
try:
data = request.get_json()
if not data:
return error_response("No data provided", 400)
raw_username = data.get('username')
raw_password = data.get('password')
# Validate username with strict rules
valid, result = validate_username(raw_username)
if not valid:
return error_response(result, 400)
username = result