Athspi commited on
Commit
2b09d25
·
verified ·
1 Parent(s): a190574

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -61
app.py CHANGED
@@ -1,11 +1,10 @@
1
- from fastapi import FastAPI, HTTPException, Request, Query
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
- from typing import List, Optional
5
  import datetime
6
  import json
7
  import os
8
- from pathlib import Path
9
 
10
  app = FastAPI()
11
 
@@ -17,85 +16,42 @@ app.add_middleware(
17
  allow_headers=["*"],
18
  )
19
 
20
- class SMSMessage(BaseModel):
21
- sender: str
22
- text: str
23
- timestamp: int
 
24
 
25
- class BackupRequest(BaseModel):
26
- phone: str
27
- messages: List[SMSMessage]
28
 
29
  # Use /tmp directory which has write permissions
30
  DATA_DIR = "/tmp/sms_data"
31
  os.makedirs(DATA_DIR, exist_ok=True)
32
 
33
- @app.post("/backup")
34
- async def backup_sms(request: BackupRequest):
35
  try:
36
- # Create filename with phone number and timestamp
37
  timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
38
- filename = f"{DATA_DIR}/{request.phone}_{timestamp}.json"
39
 
40
- # Save messages to file
41
  with open(filename, "w") as f:
42
- json.dump({
43
- "phone": request.phone,
44
- "timestamp": timestamp,
45
- "messages": [msg.dict() for msg in request.messages]
46
- }, f)
47
 
48
  return {
49
  "status": "success",
50
- "saved_count": len(request.messages),
51
  "filename": filename
52
  }
53
  except Exception as e:
54
  raise HTTPException(status_code=500, detail=str(e))
55
 
56
- @app.get("/retrieve")
57
- async def retrieve_sms(
58
- phone: str = Query(..., description="Phone number to retrieve messages for"),
59
- limit: Optional[int] = Query(50, description="Maximum number of messages to retrieve")
60
- ):
61
- try:
62
- # Find all files for this phone number
63
- matching_files = []
64
- for entry in os.scandir(DATA_DIR):
65
- if entry.name.startswith(f"{phone}_") and entry.is_file():
66
- matching_files.append(entry.path)
67
-
68
- if not matching_files:
69
- raise HTTPException(status_code=404, detail="No messages found for this phone number")
70
-
71
- # Sort by newest first
72
- matching_files.sort(reverse=True)
73
-
74
- # Read all messages
75
- all_messages = []
76
- for filename in matching_files:
77
- with open(filename, "r") as f:
78
- data = json.load(f)
79
- all_messages.extend(data["messages"])
80
-
81
- # Apply limit and sort by timestamp (newest first)
82
- all_messages.sort(key=lambda x: x["timestamp"], reverse=True)
83
- limited_messages = all_messages[:limit] if limit else all_messages
84
-
85
- return {
86
- "status": "success",
87
- "phone": phone,
88
- "count": len(limited_messages),
89
- "messages": limited_messages
90
- }
91
- except Exception as e:
92
- raise HTTPException(status_code=500, detail=str(e))
93
-
94
  @app.get("/")
95
  async def health_check():
96
  return {
97
  "status": "healthy",
98
  "timestamp": datetime.datetime.now().isoformat(),
99
- "storage_path": DATA_DIR,
100
- "writable": os.access(DATA_DIR, os.W_OK)
101
  }
 
1
+ from fastapi import FastAPI, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
+ from typing import List
5
  import datetime
6
  import json
7
  import os
 
8
 
9
  app = FastAPI()
10
 
 
16
  allow_headers=["*"],
17
  )
18
 
19
+ class SmsItem(BaseModel):
20
+ address: str
21
+ body: str
22
+ date: int
23
+ type: str
24
 
25
+ class SmsRequest(BaseModel):
26
+ sms_list: List[SmsItem]
 
27
 
28
  # Use /tmp directory which has write permissions
29
  DATA_DIR = "/tmp/sms_data"
30
  os.makedirs(DATA_DIR, exist_ok=True)
31
 
32
+ @app.post("/save-sms")
33
+ async def save_sms(request: SmsRequest):
34
  try:
35
+ # Create filename with timestamp
36
  timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
37
+ filename = f"{DATA_DIR}/backup_{timestamp}.json"
38
 
39
+ # Save to file
40
  with open(filename, "w") as f:
41
+ json.dump([sms.dict() for sms in request.sms_list], f, indent=2)
 
 
 
 
42
 
43
  return {
44
  "status": "success",
45
+ "message": f"{len(request.sms_list)} SMS saved",
46
  "filename": filename
47
  }
48
  except Exception as e:
49
  raise HTTPException(status_code=500, detail=str(e))
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  @app.get("/")
52
  async def health_check():
53
  return {
54
  "status": "healthy",
55
  "timestamp": datetime.datetime.now().isoformat(),
56
+ "sms_storage": DATA_DIR
 
57
  }