tecuts commited on
Commit
2b31489
·
verified ·
1 Parent(s): dff444f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -44
app.py CHANGED
@@ -2,24 +2,25 @@
2
  from fastapi import FastAPI, HTTPException
3
  from fastapi.staticfiles import StaticFiles
4
  from pydantic import BaseModel
5
- from dotenv import load_dotenv
6
  import subprocess
7
  import os
8
  import shutil
9
  import logging
10
  from datetime import datetime
 
 
 
11
 
12
  # Set up logging
13
  logging.basicConfig(level=logging.INFO)
14
  logger = logging.getLogger(__name__)
15
 
16
  def env_to_cookies(env_content: str, output_file: str) -> None:
17
- """Convert environment variable content back to cookie file"""
18
  try:
19
  # Extract content from env format
20
  if '="' not in env_content:
21
  raise ValueError("Invalid env content format")
22
-
23
  content = env_content.split('="', 1)[1].strip('"')
24
 
25
  # Replace escaped newlines with actual newlines
@@ -29,53 +30,34 @@ def env_to_cookies(env_content: str, output_file: str) -> None:
29
  with open(output_file, 'w') as f:
30
  f.write(cookie_content)
31
 
 
32
  except Exception as e:
 
33
  raise ValueError(f"Error converting to cookie file: {str(e)}")
34
 
35
- def save_to_env_file(env_content: str, env_file: str = '.env') -> None:
36
- """Save environment variable content to .env file"""
37
- try:
38
- with open(env_file, 'w') as f:
39
- f.write(env_content)
40
- #print(f"Successfully saved to {env_file}")
41
- except Exception as e:
42
- raise ValueError(f"Error saving to env file: {str(e)}")
43
 
44
  def env_to_cookies_from_env(output_file: str) -> None:
45
  """Convert environment variable from .env file to cookie file"""
46
  try:
47
- load_dotenv() # Load from .env file
48
  env_content = os.getenv('COOKIES')
49
- #print(f"Printing env content: \n{env_content}")
 
50
  if not env_content:
51
- raise ValueError("COOKIES not found in .env file")
52
 
53
  env_to_cookies(f'COOKIES="{env_content}"', output_file)
54
  except Exception as e:
 
55
  raise ValueError(f"Error converting to cookie file: {str(e)}")
56
 
57
- def get_cookies():
58
- """Get cookies from environment variable"""
59
- load_dotenv()
60
- cookie_content = os.getenv('COOKIES')
61
- #print(cookie_content)
62
- if not cookie_content:
63
- raise ValueError("COOKIES environment variable not set")
64
- return cookie_content
65
-
66
- def create_temp_cookie_file():
67
- """Create temporary cookie file from environment variable"""
68
- temp_cookie = tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.txt')
69
- try:
70
- cookie_content = get_cookies()
71
- # Replace escaped newlines with actual newlines
72
- cookie_content = cookie_content.replace('\\n', '\n')
73
- temp_cookie.write()
74
- temp_cookie.flush()
75
- return Path(temp_cookie.name)
76
- finally:
77
- temp_cookie.close()
78
-
79
  app = FastAPI(
80
  title="GAMDL API",
81
  description="API for downloading Google Drive files using gamdl",
@@ -100,8 +82,6 @@ class DownloadResponse(BaseModel):
100
 
101
  @app.post("/download", response_model=DownloadResponse)
102
  async def download_file(request: DownloadRequest):
103
- cookiefile = "cookies.txt"
104
- env_to_cookies_from_env("cookies.txt")
105
  try:
106
  # Create a unique subdirectory for this download
107
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
@@ -112,6 +92,11 @@ async def download_file(request: DownloadRequest):
112
  logger.info(f"Current working directory: {os.getcwd()}")
113
  logger.info(f"Download directory: {download_subdir}")
114
 
 
 
 
 
 
115
  # Change to download directory
116
  original_dir = os.getcwd()
117
  os.chdir(download_subdir)
@@ -135,7 +120,7 @@ async def download_file(request: DownloadRequest):
135
  process.check_returncode()
136
 
137
  # Get the downloaded filename
138
- files = os.listdir()
139
  logger.info(f"Files in download directory: {files}")
140
 
141
  if not files:
@@ -176,17 +161,21 @@ async def download_file(request: DownloadRequest):
176
  if 'original_dir' in locals():
177
  os.chdir(original_dir)
178
 
179
- @app.get("/")
180
- async def root():
181
- return {"message": "Welcome to GAMDL API. Visit /docs for API documentation."}
182
-
183
  @app.get("/test")
184
  async def test():
185
- """Test endpoint to verify gamdl installation"""
186
  try:
 
 
 
 
 
187
  process = subprocess.run(["gamdl", "--version"], capture_output=True, text=True)
 
188
  return {
189
  "gamdl_version": process.stdout.strip(),
 
 
190
  "installed": True,
191
  "error": process.stderr if process.stderr else None
192
  }
 
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
  import logging
9
  from datetime import datetime
10
+ import tempfile
11
+ from pathlib import Path
12
+ from dotenv import load_dotenv
13
 
14
  # Set up logging
15
  logging.basicConfig(level=logging.INFO)
16
  logger = logging.getLogger(__name__)
17
 
18
  def env_to_cookies(env_content: str, output_file: str) -> None:
19
+ """Convert environment variable content to cookie file"""
20
  try:
21
  # Extract content from env format
22
  if '="' not in env_content:
23
  raise ValueError("Invalid env content format")
 
24
  content = env_content.split('="', 1)[1].strip('"')
25
 
26
  # Replace escaped newlines with actual newlines
 
30
  with open(output_file, 'w') as f:
31
  f.write(cookie_content)
32
 
33
+ logger.info(f"Successfully created cookie file at {output_file}")
34
  except Exception as e:
35
+ logger.error(f"Error creating cookie file: {str(e)}")
36
  raise ValueError(f"Error converting to cookie file: {str(e)}")
37
 
38
+ def get_cookies() -> str:
39
+ """Get cookies from environment variable"""
40
+ load_dotenv()
41
+ cookie_content = os.getenv('COOKIES')
42
+ if not cookie_content:
43
+ raise ValueError("COOKIES environment variable not set")
44
+ return cookie_content
 
45
 
46
  def env_to_cookies_from_env(output_file: str) -> None:
47
  """Convert environment variable from .env file to cookie file"""
48
  try:
49
+ load_dotenv()
50
  env_content = os.getenv('COOKIES')
51
+ logger.info("Retrieved cookies from environment variable")
52
+
53
  if not env_content:
54
+ raise ValueError("COOKIES not found in environment variables")
55
 
56
  env_to_cookies(f'COOKIES="{env_content}"', output_file)
57
  except Exception as e:
58
+ logger.error(f"Error creating cookie file from env: {str(e)}")
59
  raise ValueError(f"Error converting to cookie file: {str(e)}")
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  app = FastAPI(
62
  title="GAMDL API",
63
  description="API for downloading Google Drive files using gamdl",
 
82
 
83
  @app.post("/download", response_model=DownloadResponse)
84
  async def download_file(request: DownloadRequest):
 
 
85
  try:
86
  # Create a unique subdirectory for this download
87
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 
92
  logger.info(f"Current working directory: {os.getcwd()}")
93
  logger.info(f"Download directory: {download_subdir}")
94
 
95
+ # Create cookies file from environment variable
96
+ cookie_path = os.path.join(download_subdir, "cookies.txt")
97
+ logger.info(f"Creating cookies file at: {cookie_path}")
98
+ env_to_cookies_from_env(cookie_path)
99
+
100
  # Change to download directory
101
  original_dir = os.getcwd()
102
  os.chdir(download_subdir)
 
120
  process.check_returncode()
121
 
122
  # Get the downloaded filename
123
+ files = [f for f in os.listdir() if f != "cookies.txt"]
124
  logger.info(f"Files in download directory: {files}")
125
 
126
  if not files:
 
161
  if 'original_dir' in locals():
162
  os.chdir(original_dir)
163
 
 
 
 
 
164
  @app.get("/test")
165
  async def test():
166
+ """Test endpoint to verify setup"""
167
  try:
168
+ # Test cookie creation
169
+ temp_cookie = os.path.join(DOWNLOADS_DIR, "test_cookies.txt")
170
+ env_to_cookies_from_env(temp_cookie)
171
+
172
+ # Test gamdl installation
173
  process = subprocess.run(["gamdl", "--version"], capture_output=True, text=True)
174
+
175
  return {
176
  "gamdl_version": process.stdout.strip(),
177
+ "cookies_created": os.path.exists(temp_cookie),
178
+ "cookies_size": os.path.getsize(temp_cookie) if os.path.exists(temp_cookie) else 0,
179
  "installed": True,
180
  "error": process.stderr if process.stderr else None
181
  }