CBV01 commited on
Commit
5e005fe
·
1 Parent(s): 0c764e2

Fix syntax error, add campaign names, add admin debug logs, and fix auth API URLs

Browse files
backend/database.py CHANGED
@@ -113,10 +113,12 @@ def get_db_connection():
113
  auth_token = os.getenv("TURSO_AUTH_TOKEN", "")
114
 
115
  if db_url and (db_url.startswith("libsql://") or db_url.startswith("https://")):
 
116
  return TursoConnection(db_url, auth_token)
117
 
118
  # Local SQLite fallback
119
  local_path = db_url.replace("file:", "") if db_url else "./telegram_app.db"
 
120
  conn = sqlite3.connect(local_path)
121
  conn.row_factory = sqlite3.Row
122
  return conn
@@ -145,6 +147,7 @@ def init_db():
145
  """CREATE TABLE IF NOT EXISTS tasks (
146
  id INTEGER PRIMARY KEY AUTOINCREMENT,
147
  user_id TEXT NOT NULL,
 
148
  phone_number TEXT,
149
  scheduled_time TEXT NOT NULL,
150
  message_text TEXT NOT NULL,
 
113
  auth_token = os.getenv("TURSO_AUTH_TOKEN", "")
114
 
115
  if db_url and (db_url.startswith("libsql://") or db_url.startswith("https://")):
116
+ # print("DB: Using Turso Cloud")
117
  return TursoConnection(db_url, auth_token)
118
 
119
  # Local SQLite fallback
120
  local_path = db_url.replace("file:", "") if db_url else "./telegram_app.db"
121
+ # print(f"DB: Using local SQLite ({local_path})")
122
  conn = sqlite3.connect(local_path)
123
  conn.row_factory = sqlite3.Row
124
  return conn
 
147
  """CREATE TABLE IF NOT EXISTS tasks (
148
  id INTEGER PRIMARY KEY AUTOINCREMENT,
149
  user_id TEXT NOT NULL,
150
+ name TEXT,
151
  phone_number TEXT,
152
  scheduled_time TEXT NOT NULL,
153
  message_text TEXT NOT NULL,
backend/main.py CHANGED
@@ -11,12 +11,20 @@ from telethon.sessions import StringSession
11
  from config import TELEGRAM_API_ID, TELEGRAM_API_HASH
12
  from auth import get_password_hash, verify_password, create_access_token, get_current_user_id
13
  import uuid
14
- import asyncio
15
- import random
16
  from datetime import datetime, timedelta
 
17
 
18
  app = FastAPI(title="Telegram Automation API")
19
 
 
 
 
 
 
 
 
 
 
20
  app.add_middleware(
21
  CORSMiddleware,
22
  allow_origins=["*"], # In production, set this to process.env.FRONTEND_URL
@@ -489,8 +497,8 @@ async def create_campaign(req: CampaignRequest, user_id: str = Depends(get_curre
489
  conn = get_db_connection()
490
  try:
491
  conn.execute(
492
- "INSERT INTO tasks (user_id, phone_number, scheduled_time, message_text, target_groups, status, interval_hours) VALUES (?, ?, ?, ?, ?, ?, ?)",
493
- (user_id, req.phone_number, req.schedule_time, req.message, str(req.groups), "pending", req.interval_hours)
494
  )
495
  if hasattr(conn, "commit"): conn.commit()
496
  return {"status": "success", "message": "Campaign scheduled successfully."}
@@ -605,6 +613,10 @@ async def admin_get_users(admin_id: str = Depends(get_current_admin)):
605
  if hasattr(conn, "close"): conn.close()
606
  return {"users": [dict(id=u[0], username=u[1], role=u[2], is_active=u[3]) for u in users]}
607
 
 
 
 
 
608
  @app.get("/api/admin/stats")
609
  async def admin_get_stats(admin_id: str = Depends(get_current_admin)):
610
  conn = get_db_connection()
@@ -691,10 +703,11 @@ import asyncio
691
  async def task_poller():
692
  while True:
693
  try:
694
- from datetime import datetime, timedelta
695
- now_str = datetime.now().isoformat()
696
-
697
  conn = get_db_connection()
 
 
 
 
698
  # Only pick pending tasks that are due now or in the past
699
  tasks = conn.execute(
700
  "SELECT id, message_text, target_groups, phone_number, user_id, interval_hours FROM tasks WHERE status = 'pending' AND scheduled_time <= ?",
 
11
  from config import TELEGRAM_API_ID, TELEGRAM_API_HASH
12
  from auth import get_password_hash, verify_password, create_access_token, get_current_user_id
13
  import uuid
 
 
14
  from datetime import datetime, timedelta
15
+ import collections
16
 
17
  app = FastAPI(title="Telegram Automation API")
18
 
19
+ # Simple in-memory log buffer
20
+ LOG_BUFFER = collections.deque(maxlen=100)
21
+
22
+ def log_debug(msg: str):
23
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
24
+ formatted = f"[{timestamp}] {msg}"
25
+ print(formatted)
26
+ LOG_BUFFER.append(formatted)
27
+
28
  app.add_middleware(
29
  CORSMiddleware,
30
  allow_origins=["*"], # In production, set this to process.env.FRONTEND_URL
 
497
  conn = get_db_connection()
498
  try:
499
  conn.execute(
500
+ "INSERT INTO tasks (user_id, name, phone_number, scheduled_time, message_text, target_groups, status, interval_hours) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
501
+ (user_id, req.name, req.phone_number, req.schedule_time, req.message, str(req.groups), "pending", req.interval_hours)
502
  )
503
  if hasattr(conn, "commit"): conn.commit()
504
  return {"status": "success", "message": "Campaign scheduled successfully."}
 
613
  if hasattr(conn, "close"): conn.close()
614
  return {"users": [dict(id=u[0], username=u[1], role=u[2], is_active=u[3]) for u in users]}
615
 
616
+ @app.get("/api/admin/debug-logs")
617
+ async def get_debug_logs(admin_id: str = Depends(get_current_admin)):
618
+ return {"logs": list(LOG_BUFFER)}
619
+
620
  @app.get("/api/admin/stats")
621
  async def admin_get_stats(admin_id: str = Depends(get_current_admin)):
622
  conn = get_db_connection()
 
703
  async def task_poller():
704
  while True:
705
  try:
 
 
 
706
  conn = get_db_connection()
707
+ # Normalize comparison: Browser sends YYYY-MM-DDTHH:MM.
708
+ # now_str should match or be slightly ahead.
709
+ now_str = datetime.now().strftime('%Y-%m-%dT%H:%M')
710
+
711
  # Only pick pending tasks that are due now or in the past
712
  tasks = conn.execute(
713
  "SELECT id, message_text, target_groups, phone_number, user_id, interval_hours FROM tasks WHERE status = 'pending' AND scheduled_time <= ?",
backend/run_migration.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import urllib.request
3
+ import urllib.error
4
+ import urllib.parse
5
+ import json
6
+ import os
7
+ import sqlite3
8
+ import ssl
9
+
10
+ def get_env():
11
+ env = {}
12
+ if os.path.exists(".env"):
13
+ with open(".env", "r") as f:
14
+ for line in f:
15
+ if "=" in line:
16
+ k, v = line.strip().split("=", 1)
17
+ env[k] = v
18
+ return env
19
+
20
+ def run_migration():
21
+ env = get_env()
22
+ db_url = env.get("TURSO_DATABASE_URL", "")
23
+ auth_token = env.get("TURSO_AUTH_TOKEN", "")
24
+
25
+ sql = "ALTER TABLE tasks ADD COLUMN name TEXT;"
26
+
27
+ if db_url and (db_url.startswith("libsql://") or db_url.startswith("https://")):
28
+ print(f"DEBUG: Connecting to Turso: {db_url}")
29
+ if db_url.startswith("libsql://"):
30
+ db_url = db_url.replace("libsql://", "https://", 1)
31
+ url = db_url.rstrip("/") + "/v2/pipeline"
32
+
33
+ headers = {
34
+ "Authorization": f"Bearer {auth_token}",
35
+ "Content-Type": "application/json",
36
+ }
37
+ payload = {
38
+ "requests": [
39
+ {
40
+ "type": "execute",
41
+ "stmt": { "sql": sql }
42
+ },
43
+ {"type": "close"}
44
+ ]
45
+ }
46
+ data = json.dumps(payload).encode('utf-8')
47
+ req = urllib.request.Request(url, data=data, headers=headers)
48
+
49
+ try:
50
+ # Bypass SSL verification if any issues
51
+ ctx = ssl.create_default_context()
52
+ ctx.check_hostname = False
53
+ ctx.verify_mode = ssl.CERT_NONE
54
+
55
+ with urllib.request.urlopen(req, context=ctx) as response:
56
+ resp_data = json.loads(response.read().decode('utf-8'))
57
+ if resp_data["results"][0].get("type") == "error":
58
+ print(f"Turso Error (likely column exists): {resp_data['results'][0]['error']['message']}")
59
+ else:
60
+ print("Turso Migration: Added 'name' column to 'tasks' table.")
61
+ except urllib.error.HTTPError as e:
62
+ print(f"Turso Connection Failed: {e.code} {e.read().decode('utf-8')}")
63
+ except Exception as e:
64
+ print(f"Error: {e}")
65
+ else:
66
+ print("DEBUG: Connecting to Local SQLite")
67
+ try:
68
+ conn = sqlite3.connect("./telegram_app.db")
69
+ conn.execute(sql)
70
+ conn.commit()
71
+ conn.close()
72
+ print("Local Migration: Added 'name' column to 'tasks' table.")
73
+ except Exception as e:
74
+ print(f"Local Migration Error (likely exists): {e}")
75
+
76
+ if __name__ == "__main__":
77
+ run_migration()
frontend/src/app/accounts/page.tsx CHANGED
@@ -21,9 +21,14 @@ export default function AccountsPage() {
21
  setFetchingAccounts(true);
22
  try {
23
  const res = await apiFetch('/api/telegram/accounts');
24
- const data = await res.json();
25
  if (res.ok) {
26
- setAccounts(data.accounts || []);
 
 
 
 
 
27
  }
28
  } catch (err) {
29
  console.error("Failed to fetch accounts:", err);
 
21
  setFetchingAccounts(true);
22
  try {
23
  const res = await apiFetch('/api/telegram/accounts');
24
+ const text = await res.text();
25
  if (res.ok) {
26
+ try {
27
+ const data = JSON.parse(text);
28
+ setAccounts(data.accounts || []);
29
+ } catch (e) {
30
+ console.error("Accounts: Non-JSON response:", text);
31
+ }
32
  }
33
  } catch (err) {
34
  console.error("Failed to fetch accounts:", err);
frontend/src/app/admin/page.tsx CHANGED
@@ -12,7 +12,8 @@ import {
12
  Play,
13
  Trash2,
14
  Database,
15
- Search
 
16
  } from 'lucide-react';
17
 
18
  export default function AdminDashboard() {
@@ -31,9 +32,20 @@ export default function AdminDashboard() {
31
  ]);
32
 
33
  if (statsRes.ok && usersRes.ok) {
34
- setStats(await statsRes.json());
35
- const usersData = await usersRes.json();
36
- setUsers(usersData.users || []);
 
 
 
 
 
 
 
 
 
 
 
37
  }
38
  } catch (err) {
39
  console.error("Failed to fetch admin data", err);
@@ -251,7 +263,7 @@ export default function AdminDashboard() {
251
  <div className="bg-red-500/5 border border-red-500/10 p-8 rounded-3xl space-y-6">
252
  <div className="flex items-center gap-3">
253
  <div className="p-3 rounded-2xl bg-red-500/10 text-red-500">
254
- <Lock size={24} />
255
  </div>
256
  <div>
257
  <h2 className="text-xl font-bold">Admin Password</h2>
 
12
  Play,
13
  Trash2,
14
  Database,
15
+ Search,
16
+ Lock as MasterLock
17
  } from 'lucide-react';
18
 
19
  export default function AdminDashboard() {
 
32
  ]);
33
 
34
  if (statsRes.ok && usersRes.ok) {
35
+ const statsText = await statsRes.text();
36
+ const usersText = await usersRes.text();
37
+ try {
38
+ setStats(JSON.parse(statsText));
39
+ const usersData = JSON.parse(usersText);
40
+ setUsers(usersData.users || []);
41
+ } catch (e) {
42
+ console.error("Failed to parse admin data JSON:", e, { statsText, usersText });
43
+ }
44
+ } else {
45
+ console.error("Admin API returned error:", {
46
+ statsStatus: statsRes.status,
47
+ usersStatus: usersRes.status
48
+ });
49
  }
50
  } catch (err) {
51
  console.error("Failed to fetch admin data", err);
 
263
  <div className="bg-red-500/5 border border-red-500/10 p-8 rounded-3xl space-y-6">
264
  <div className="flex items-center gap-3">
265
  <div className="p-3 rounded-2xl bg-red-500/10 text-red-500">
266
+ <MasterLock size={24} />
267
  </div>
268
  <div>
269
  <h2 className="text-xl font-bold">Admin Password</h2>
frontend/src/app/campaigns/page.tsx CHANGED
@@ -1,7 +1,7 @@
1
  "use client";
2
 
3
  import React, { useState } from 'react';
4
- import { Megaphone, Plus, Clock, Users, X, Send, Calendar, CheckCircle2, Loader2 } from 'lucide-react';
5
  import { apiFetch } from '@/lib/auth';
6
 
7
  export default function CampaignsPage() {
@@ -65,8 +65,15 @@ export default function CampaignsPage() {
65
  const fetchAccounts = async () => {
66
  try {
67
  const res = await apiFetch('/api/telegram/accounts');
68
- const data = await res.json();
69
- if (res.ok) setAccounts(data.accounts || []);
 
 
 
 
 
 
 
70
  } catch (err) {
71
  console.error("Failed to fetch accounts", err);
72
  }
 
1
  "use client";
2
 
3
  import React, { useState } from 'react';
4
+ import { Megaphone, Plus, Clock, Users, X, Send, Calendar, CheckCircle2, Loader2, Search } from 'lucide-react';
5
  import { apiFetch } from '@/lib/auth';
6
 
7
  export default function CampaignsPage() {
 
65
  const fetchAccounts = async () => {
66
  try {
67
  const res = await apiFetch('/api/telegram/accounts');
68
+ const text = await res.text();
69
+ if (res.ok) {
70
+ try {
71
+ const data = JSON.parse(text);
72
+ setAccounts(data.accounts || []);
73
+ } catch (e) {
74
+ console.error("Campaigns: Non-JSON response for accounts", text);
75
+ }
76
+ }
77
  } catch (err) {
78
  console.error("Failed to fetch accounts", err);
79
  }
frontend/src/app/page.tsx CHANGED
@@ -12,9 +12,13 @@ export default function Dashboard() {
12
  const fetchStats = async () => {
13
  try {
14
  const res = await apiFetch('/api/dashboard/stats');
15
- const data = await res.json();
16
  if (res.ok) {
17
- setStats(data);
 
 
 
 
18
  }
19
  } catch (err) {
20
  console.error("Dashboard: Failed to fetch stats", err);
 
12
  const fetchStats = async () => {
13
  try {
14
  const res = await apiFetch('/api/dashboard/stats');
15
+ const text = await res.text();
16
  if (res.ok) {
17
+ try {
18
+ setStats(JSON.parse(text));
19
+ } catch (e) {
20
+ console.error("Dashboard: Non-JSON response", text);
21
+ }
22
  }
23
  } catch (err) {
24
  console.error("Dashboard: Failed to fetch stats", err);
frontend/src/lib/auth.ts CHANGED
@@ -25,8 +25,8 @@ export const getAuthHeaders = (): Record<string, string> => {
25
  export const apiFetch = async (endpoint: string, options: any = {}) => {
26
  const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/$/, '');
27
  const isAbsolute = /^https?:\/\//i.test(endpoint);
28
- const useRelative = !isAbsolute && endpoint.startsWith('/api/');
29
- const url = useRelative ? endpoint : (isAbsolute ? endpoint : (apiBase ? `${apiBase}${endpoint}` : endpoint));
30
 
31
  const method = (options.method || 'GET').toUpperCase();
32
  const defaultHeaders: Record<string, string> = {
 
25
  export const apiFetch = async (endpoint: string, options: any = {}) => {
26
  const apiBase = (process.env.NEXT_PUBLIC_API_URL || '').replace(/\/$/, '');
27
  const isAbsolute = /^https?:\/\//i.test(endpoint);
28
+ // On production/when apiBase is set, we want ALL /api calls to go to the backend
29
+ const url = isAbsolute ? endpoint : (apiBase ? `${apiBase}${endpoint}` : endpoint);
30
 
31
  const method = (options.method || 'GET').toUpperCase();
32
  const defaultHeaders: Record<string, string> = {