tecuts commited on
Commit
52ee455
·
verified ·
1 Parent(s): 2e85721

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -30
app.py CHANGED
@@ -1,9 +1,11 @@
1
  # app.py
2
  from fastapi import FastAPI, HTTPException
 
3
  from pydantic import BaseModel
4
  import subprocess
5
  import os
6
- import tempfile
 
7
 
8
  app = FastAPI(
9
  title="GAMDL API",
@@ -11,6 +13,13 @@ app = FastAPI(
11
  version="1.0.0"
12
  )
13
 
 
 
 
 
 
 
 
14
  class DownloadRequest(BaseModel):
15
  url: str
16
 
@@ -18,39 +27,49 @@ class DownloadResponse(BaseModel):
18
  success: bool
19
  message: str
20
  filename: str = None
 
21
 
22
  @app.post("/download", response_model=DownloadResponse)
23
  async def download_file(request: DownloadRequest):
24
  try:
25
- # Create a temporary directory for downloads
26
- with tempfile.TemporaryDirectory() as temp_dir:
27
- # Change to temp directory
28
- original_dir = os.getcwd()
29
- os.chdir(temp_dir)
30
-
31
- # Run gamdl command
32
- process = subprocess.run(
33
- ["gamdl", request.url],
34
- capture_output=True,
35
- text=True,
36
- check=True
37
- )
38
-
39
- # Get the downloaded filename (last file in temp directory)
40
- files = os.listdir()
41
- if not files:
42
- raise Exception("No file was downloaded")
43
-
44
- downloaded_file = files[0]
45
-
46
- # Move back to original directory
47
- os.chdir(original_dir)
48
 
49
- return DownloadResponse(
50
- success=True,
51
- message="File downloaded successfully",
52
- filename=downloaded_file
53
- )
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  except subprocess.CalledProcessError as e:
56
  raise HTTPException(
@@ -66,4 +85,20 @@ async def download_file(request: DownloadRequest):
66
  # Add basic homepage with API documentation link
67
  @app.get("/")
68
  async def root():
69
- return {"message": " Visit /docs for API documentation."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # app.py
2
  from fastapi import FastAPI, HTTPException
3
+ from fastapi.staticfiles import StaticFiles
4
  from pydantic import BaseModel
5
  import subprocess
6
  import os
7
+ import shutil
8
+ from datetime import datetime
9
 
10
  app = FastAPI(
11
  title="GAMDL API",
 
13
  version="1.0.0"
14
  )
15
 
16
+ # Create downloads directory if it doesn't exist
17
+ DOWNLOADS_DIR = "downloads"
18
+ os.makedirs(DOWNLOADS_DIR, exist_ok=True)
19
+
20
+ # Mount the downloads directory
21
+ app.mount("/files", StaticFiles(directory=DOWNLOADS_DIR), name="files")
22
+
23
  class DownloadRequest(BaseModel):
24
  url: str
25
 
 
27
  success: bool
28
  message: str
29
  filename: str = None
30
+ download_url: str = None
31
 
32
  @app.post("/download", response_model=DownloadResponse)
33
  async def download_file(request: DownloadRequest):
34
  try:
35
+ # Create a unique subdirectory for this download
36
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
37
+ download_subdir = os.path.join(DOWNLOADS_DIR, timestamp)
38
+ os.makedirs(download_subdir, exist_ok=True)
39
+
40
+ # Change to download directory
41
+ original_dir = os.getcwd()
42
+ os.chdir(download_subdir)
43
+
44
+ # Run gamdl command
45
+ process = subprocess.run(
46
+ ["gamdl", request.url],
47
+ capture_output=True,
48
+ text=True,
49
+ check=True
50
+ )
51
+
52
+ # Get the downloaded filename
53
+ files = os.listdir()
54
+ if not files:
55
+ raise Exception("No file was downloaded")
 
 
56
 
57
+ downloaded_file = files[0]
58
+
59
+ # Generate the download URL
60
+ # Using the Space's domain - you'll need to replace this with your actual Space URL
61
+ space_url = os.getenv("SPACE_URL", "http://localhost:7860")
62
+ download_url = f"{space_url}/files/{timestamp}/{downloaded_file}"
63
+
64
+ # Move back to original directory
65
+ os.chdir(original_dir)
66
+
67
+ return DownloadResponse(
68
+ success=True,
69
+ message="File downloaded successfully",
70
+ filename=downloaded_file,
71
+ download_url=download_url
72
+ )
73
 
74
  except subprocess.CalledProcessError as e:
75
  raise HTTPException(
 
85
  # Add basic homepage with API documentation link
86
  @app.get("/")
87
  async def root():
88
+ return {"message": "Welcome to GAMDL API. Visit /docs for API documentation."}
89
+
90
+ # Optional: Add cleanup endpoint to manage disk space
91
+ @app.post("/cleanup")
92
+ async def cleanup_old_files():
93
+ """Remove files older than 24 hours"""
94
+ try:
95
+ for item in os.listdir(DOWNLOADS_DIR):
96
+ item_path = os.path.join(DOWNLOADS_DIR, item)
97
+ if os.path.isdir(item_path):
98
+ shutil.rmtree(item_path)
99
+ return {"message": "Cleanup completed successfully"}
100
+ except Exception as e:
101
+ raise HTTPException(
102
+ status_code=500,
103
+ detail=f"Cleanup failed: {str(e)}"
104
+ )