VeuReu commited on
Commit
45ad1c4
·
verified ·
1 Parent(s): 7ce7b8c

Update storage/media_routers.py

Browse files
Files changed (1) hide show
  1. storage/media_routers.py +248 -248
storage/media_routers.py CHANGED
@@ -1,248 +1,248 @@
1
- import os
2
- import io
3
- from pathlib import Path
4
-
5
- from fastapi import APIRouter, UploadFile, File, Query, HTTPException
6
- from fastapi.responses import FileResponse, JSONResponse
7
-
8
- # Importa tu clase FileManager según donde la tengas
9
- from sotorage.files.file_manager import FileManager
10
-
11
- router = APIRouter(prefix="/media", tags=["Media Manager"])
12
- MEDIA_ROOT = Path("/data/media")
13
- file_manager = FileManager(MEDIA_ROOT)
14
- HF_TOKEN = os.getenv("HF_TOKEN")
15
-
16
- def validate_token(token: str):
17
- """
18
- Validate the provided token against the HF_TOKEN environment variable.
19
- Raises an HTTPException if validation fails.
20
- """
21
- if HF_TOKEN is None:
22
- raise RuntimeError("HF_TOKEN environment variable is not set on the server.")
23
-
24
- if token != HF_TOKEN:
25
- raise HTTPException(status_code=401, detail="Invalid token")
26
-
27
-
28
- @router.post("/upload_cast_csv/{sha1}", tags=["Media Manager"])
29
- async def upload_cast_csv(
30
- sha1: str,
31
- cast_file: UploadFile = File(...),
32
- token: str = Query(..., description="Token required for authorization")
33
- ):
34
- """
35
- Upload a cast CSV file for a specific video identified by its SHA-1.
36
-
37
- The CSV will be stored under:
38
- /data/media/<sha1>/cast/cast.csv
39
-
40
- Steps:
41
- - Validate the token.
42
- - Ensure /data/media/<sha1> exists.
43
- - Create /cast folder if missing.
44
- - Save the CSV file inside /cast.
45
- """
46
- validate_token(token)
47
-
48
- base_folder = MEDIA_ROOT / sha1
49
- if not base_folder.exists() or not base_folder.is_dir():
50
- raise HTTPException(status_code=404, detail="SHA1 folder not found")
51
-
52
- cast_folder = base_folder / "cast"
53
- cast_folder.mkdir(parents=True, exist_ok=True)
54
-
55
- final_path = cast_folder / "cast.csv"
56
-
57
- file_bytes = await cast_file.read()
58
- save_result = file_manager.upload_file(io.BytesIO(file_bytes), final_path)
59
- if not save_result["operation_success"]:
60
- raise HTTPException(status_code=500, detail=save_result["error"])
61
-
62
- return JSONResponse(
63
- status_code=200,
64
- content={"status": "ok", "saved_to": str(final_path)}
65
- )
66
-
67
-
68
- @router.get("/download_cast_csv/{sha1}", tags=["Media Manager"])
69
- def download_cast_csv(
70
- sha1: str,
71
- token: str = Query(..., description="Token required for authorization")
72
- ):
73
- """
74
- Download the cast CSV for a specific video identified by its SHA-1.
75
-
76
- The CSV is expected under:
77
- /data/media/<sha1>/cast/cast.csv
78
-
79
- Steps:
80
- - Validate the token.
81
- - Ensure /data/media/<sha1> and /cast exist.
82
- - Return the CSV as a FileResponse.
83
- - Raise 404 if any folder or file is missing.
84
- """
85
- MEDIA_ROOT = Path("/data/media")
86
- file_manager = FileManager(MEDIA_ROOT)
87
- HF_TOKEN = os.getenv("HF_TOKEN")
88
- validate_token(token)
89
-
90
- base_folder = MEDIA_ROOT / sha1
91
- cast_folder = base_folder / "cast"
92
- csv_path = cast_folder / "cast.csv"
93
-
94
- if not base_folder.exists() or not base_folder.is_dir():
95
- raise HTTPException(status_code=404, detail="SHA1 folder not found")
96
- if not cast_folder.exists() or not cast_folder.is_dir():
97
- raise HTTPException(status_code=404, detail="Cast folder not found")
98
- if not csv_path.exists() or not csv_path.is_file():
99
- raise HTTPException(status_code=404, detail="Cast CSV not found")
100
-
101
- # Convert to relative path for FileManager
102
- relative_path = csv_path.relative_to(MEDIA_ROOT)
103
- handler = file_manager.get_file(relative_path)
104
- if handler is None:
105
- raise HTTPException(status_code=404, detail="Cast CSV not accessible")
106
- handler.close()
107
-
108
- return FileResponse(
109
- path=csv_path,
110
- media_type="text/csv",
111
- filename="cast.csv"
112
- )
113
-
114
- @router.post("/upload_original_video", tags=["Media Manager"])
115
- async def upload_video(
116
- video: UploadFile = File(...),
117
- token: str = Query(..., description="Token required for authorization")
118
- ):
119
- """
120
- Saves an uploaded video by hashing it with SHA1 and placing it under:
121
- /data/media/<sha1>/clip/<original_filename>
122
-
123
- Steps:
124
- - Compute SHA1 of the uploaded video.
125
- - Ensure /data/media exists.
126
- - Create folder /data/media/<sha1> if missing.
127
- - Create folder /data/media/<sha1>/clip if missing.
128
- - Save the video inside /data/media/<sha1>/clip/.
129
- """
130
- MEDIA_ROOT = Path("/data/media")
131
- file_manager = FileManager(MEDIA_ROOT)
132
- HF_TOKEN = os.getenv("HF_TOKEN")
133
- validate_token(token)
134
-
135
- # Read content into memory (needed to compute hash twice)
136
- file_bytes = await video.read()
137
-
138
- # Create an in-memory file handler
139
- file_handler = io.BytesIO(file_bytes)
140
-
141
- # Compute SHA1 using your FileManager method
142
- try:
143
- sha1 = file_manager.compute_sha1(file_handler)
144
- except Exception as exc:
145
- raise HTTPException(status_code=500, detail=f"SHA1 computation failed: {exc}")
146
-
147
- # Ensure /data/media exists
148
- MEDIA_ROOT.mkdir(parents=True, exist_ok=True)
149
-
150
- # Path: /data/media/<sha1>
151
- video_root = MEDIA_ROOT / sha1
152
- video_root.mkdir(parents=True, exist_ok=True)
153
-
154
- # Path: /data/media/<sha1>/clip
155
- clip_dir = video_root / "clip"
156
- clip_dir.mkdir(parents=True, exist_ok=True)
157
-
158
- # Final file path
159
- final_path = clip_dir / video.filename
160
-
161
- # Save file using your FileManager.upload_file
162
- save_result = file_manager.upload_file(io.BytesIO(file_bytes), final_path)
163
-
164
- if not save_result["operation_success"]:
165
- raise HTTPException(status_code=500, detail=save_result["error"])
166
-
167
- return JSONResponse(
168
- status_code=200,
169
- content={
170
- "status": "ok",
171
- "sha1": sha1,
172
- "saved_to": str(final_path)
173
- }
174
- )
175
-
176
-
177
- @router.get("/download_original_video/{sha1}", tags=["Media Manager"])
178
- def download_video(
179
- sha1: str,
180
- token: str = Query(..., description="Token required for authorization")
181
- ):
182
- """
183
- Download a stored video by its SHA-1 directory name.
184
-
185
- This endpoint looks for a video stored under the path:
186
- /data/media/<sha1>/clip/
187
- and returns the first MP4 file found in that folder.
188
-
189
- The method performs the following steps:
190
- - Checks if the SHA-1 folder exists inside the media root.
191
- - Validates that the "clip" subfolder exists.
192
- - Searches for the first .mp4 file inside the clip folder.
193
- - Uses the FileManager.get_file method to ensure the file is accessible.
194
- - Returns the video directly as a FileResponse.
195
-
196
- Parameters
197
- ----------
198
- sha1 : str
199
- The SHA-1 hash corresponding to the directory where the video is stored.
200
-
201
- Returns
202
- -------
203
- FileResponse
204
- A streaming response containing the MP4 video.
205
-
206
- Raises
207
- ------
208
- HTTPException
209
- - 404 if the SHA-1 folder does not exist.
210
- - 404 if the clip folder is missing.
211
- - 404 if no MP4 files are found.
212
- - 404 if the file cannot be retrieved using FileManager.
213
- """
214
- MEDIA_ROOT = Path("/data/media")
215
- file_manager = FileManager(MEDIA_ROOT)
216
- HF_TOKEN = os.getenv("HF_TOKEN")
217
- validate_token(token)
218
-
219
- sha1_folder = MEDIA_ROOT / sha1
220
- clip_folder = sha1_folder / "clip"
221
-
222
- if not sha1_folder.exists() or not sha1_folder.is_dir():
223
- raise HTTPException(status_code=404, detail="SHA1 folder not found")
224
-
225
- if not clip_folder.exists() or not clip_folder.is_dir():
226
- raise HTTPException(status_code=404, detail="Clip folder not found")
227
-
228
- # Find first MP4 file
229
- mp4_files = list(clip_folder.glob("*.mp4"))
230
- if not mp4_files:
231
- raise HTTPException(status_code=404, detail="No MP4 files found")
232
-
233
- video_path = mp4_files[0]
234
-
235
- # Convert to relative path for FileManager
236
- relative_path = video_path.relative_to(MEDIA_ROOT)
237
-
238
- handler = file_manager.get_file(relative_path)
239
- if handler is None:
240
- raise HTTPException(status_code=404, detail="Video not accessible")
241
-
242
- handler.close()
243
-
244
- return FileResponse(
245
- path=video_path,
246
- media_type="video/mp4",
247
- filename=video_path.name
248
- )
 
1
+ import os
2
+ import io
3
+ from pathlib import Path
4
+
5
+ from fastapi import APIRouter, UploadFile, File, Query, HTTPException
6
+ from fastapi.responses import FileResponse, JSONResponse
7
+
8
+ # Importa tu clase FileManager según donde la tengas
9
+ from storage.files.file_manager import FileManager
10
+
11
+ router = APIRouter(prefix="/media", tags=["Media Manager"])
12
+ MEDIA_ROOT = Path("/data/media")
13
+ file_manager = FileManager(MEDIA_ROOT)
14
+ HF_TOKEN = os.getenv("HF_TOKEN")
15
+
16
+ def validate_token(token: str):
17
+ """
18
+ Validate the provided token against the HF_TOKEN environment variable.
19
+ Raises an HTTPException if validation fails.
20
+ """
21
+ if HF_TOKEN is None:
22
+ raise RuntimeError("HF_TOKEN environment variable is not set on the server.")
23
+
24
+ if token != HF_TOKEN:
25
+ raise HTTPException(status_code=401, detail="Invalid token")
26
+
27
+
28
+ @router.post("/upload_cast_csv/{sha1}", tags=["Media Manager"])
29
+ async def upload_cast_csv(
30
+ sha1: str,
31
+ cast_file: UploadFile = File(...),
32
+ token: str = Query(..., description="Token required for authorization")
33
+ ):
34
+ """
35
+ Upload a cast CSV file for a specific video identified by its SHA-1.
36
+
37
+ The CSV will be stored under:
38
+ /data/media/<sha1>/cast/cast.csv
39
+
40
+ Steps:
41
+ - Validate the token.
42
+ - Ensure /data/media/<sha1> exists.
43
+ - Create /cast folder if missing.
44
+ - Save the CSV file inside /cast.
45
+ """
46
+ validate_token(token)
47
+
48
+ base_folder = MEDIA_ROOT / sha1
49
+ if not base_folder.exists() or not base_folder.is_dir():
50
+ raise HTTPException(status_code=404, detail="SHA1 folder not found")
51
+
52
+ cast_folder = base_folder / "cast"
53
+ cast_folder.mkdir(parents=True, exist_ok=True)
54
+
55
+ final_path = cast_folder / "cast.csv"
56
+
57
+ file_bytes = await cast_file.read()
58
+ save_result = file_manager.upload_file(io.BytesIO(file_bytes), final_path)
59
+ if not save_result["operation_success"]:
60
+ raise HTTPException(status_code=500, detail=save_result["error"])
61
+
62
+ return JSONResponse(
63
+ status_code=200,
64
+ content={"status": "ok", "saved_to": str(final_path)}
65
+ )
66
+
67
+
68
+ @router.get("/download_cast_csv/{sha1}", tags=["Media Manager"])
69
+ def download_cast_csv(
70
+ sha1: str,
71
+ token: str = Query(..., description="Token required for authorization")
72
+ ):
73
+ """
74
+ Download the cast CSV for a specific video identified by its SHA-1.
75
+
76
+ The CSV is expected under:
77
+ /data/media/<sha1>/cast/cast.csv
78
+
79
+ Steps:
80
+ - Validate the token.
81
+ - Ensure /data/media/<sha1> and /cast exist.
82
+ - Return the CSV as a FileResponse.
83
+ - Raise 404 if any folder or file is missing.
84
+ """
85
+ MEDIA_ROOT = Path("/data/media")
86
+ file_manager = FileManager(MEDIA_ROOT)
87
+ HF_TOKEN = os.getenv("HF_TOKEN")
88
+ validate_token(token)
89
+
90
+ base_folder = MEDIA_ROOT / sha1
91
+ cast_folder = base_folder / "cast"
92
+ csv_path = cast_folder / "cast.csv"
93
+
94
+ if not base_folder.exists() or not base_folder.is_dir():
95
+ raise HTTPException(status_code=404, detail="SHA1 folder not found")
96
+ if not cast_folder.exists() or not cast_folder.is_dir():
97
+ raise HTTPException(status_code=404, detail="Cast folder not found")
98
+ if not csv_path.exists() or not csv_path.is_file():
99
+ raise HTTPException(status_code=404, detail="Cast CSV not found")
100
+
101
+ # Convert to relative path for FileManager
102
+ relative_path = csv_path.relative_to(MEDIA_ROOT)
103
+ handler = file_manager.get_file(relative_path)
104
+ if handler is None:
105
+ raise HTTPException(status_code=404, detail="Cast CSV not accessible")
106
+ handler.close()
107
+
108
+ return FileResponse(
109
+ path=csv_path,
110
+ media_type="text/csv",
111
+ filename="cast.csv"
112
+ )
113
+
114
+ @router.post("/upload_original_video", tags=["Media Manager"])
115
+ async def upload_video(
116
+ video: UploadFile = File(...),
117
+ token: str = Query(..., description="Token required for authorization")
118
+ ):
119
+ """
120
+ Saves an uploaded video by hashing it with SHA1 and placing it under:
121
+ /data/media/<sha1>/clip/<original_filename>
122
+
123
+ Steps:
124
+ - Compute SHA1 of the uploaded video.
125
+ - Ensure /data/media exists.
126
+ - Create folder /data/media/<sha1> if missing.
127
+ - Create folder /data/media/<sha1>/clip if missing.
128
+ - Save the video inside /data/media/<sha1>/clip/.
129
+ """
130
+ MEDIA_ROOT = Path("/data/media")
131
+ file_manager = FileManager(MEDIA_ROOT)
132
+ HF_TOKEN = os.getenv("HF_TOKEN")
133
+ validate_token(token)
134
+
135
+ # Read content into memory (needed to compute hash twice)
136
+ file_bytes = await video.read()
137
+
138
+ # Create an in-memory file handler
139
+ file_handler = io.BytesIO(file_bytes)
140
+
141
+ # Compute SHA1 using your FileManager method
142
+ try:
143
+ sha1 = file_manager.compute_sha1(file_handler)
144
+ except Exception as exc:
145
+ raise HTTPException(status_code=500, detail=f"SHA1 computation failed: {exc}")
146
+
147
+ # Ensure /data/media exists
148
+ MEDIA_ROOT.mkdir(parents=True, exist_ok=True)
149
+
150
+ # Path: /data/media/<sha1>
151
+ video_root = MEDIA_ROOT / sha1
152
+ video_root.mkdir(parents=True, exist_ok=True)
153
+
154
+ # Path: /data/media/<sha1>/clip
155
+ clip_dir = video_root / "clip"
156
+ clip_dir.mkdir(parents=True, exist_ok=True)
157
+
158
+ # Final file path
159
+ final_path = clip_dir / video.filename
160
+
161
+ # Save file using your FileManager.upload_file
162
+ save_result = file_manager.upload_file(io.BytesIO(file_bytes), final_path)
163
+
164
+ if not save_result["operation_success"]:
165
+ raise HTTPException(status_code=500, detail=save_result["error"])
166
+
167
+ return JSONResponse(
168
+ status_code=200,
169
+ content={
170
+ "status": "ok",
171
+ "sha1": sha1,
172
+ "saved_to": str(final_path)
173
+ }
174
+ )
175
+
176
+
177
+ @router.get("/download_original_video/{sha1}", tags=["Media Manager"])
178
+ def download_video(
179
+ sha1: str,
180
+ token: str = Query(..., description="Token required for authorization")
181
+ ):
182
+ """
183
+ Download a stored video by its SHA-1 directory name.
184
+
185
+ This endpoint looks for a video stored under the path:
186
+ /data/media/<sha1>/clip/
187
+ and returns the first MP4 file found in that folder.
188
+
189
+ The method performs the following steps:
190
+ - Checks if the SHA-1 folder exists inside the media root.
191
+ - Validates that the "clip" subfolder exists.
192
+ - Searches for the first .mp4 file inside the clip folder.
193
+ - Uses the FileManager.get_file method to ensure the file is accessible.
194
+ - Returns the video directly as a FileResponse.
195
+
196
+ Parameters
197
+ ----------
198
+ sha1 : str
199
+ The SHA-1 hash corresponding to the directory where the video is stored.
200
+
201
+ Returns
202
+ -------
203
+ FileResponse
204
+ A streaming response containing the MP4 video.
205
+
206
+ Raises
207
+ ------
208
+ HTTPException
209
+ - 404 if the SHA-1 folder does not exist.
210
+ - 404 if the clip folder is missing.
211
+ - 404 if no MP4 files are found.
212
+ - 404 if the file cannot be retrieved using FileManager.
213
+ """
214
+ MEDIA_ROOT = Path("/data/media")
215
+ file_manager = FileManager(MEDIA_ROOT)
216
+ HF_TOKEN = os.getenv("HF_TOKEN")
217
+ validate_token(token)
218
+
219
+ sha1_folder = MEDIA_ROOT / sha1
220
+ clip_folder = sha1_folder / "clip"
221
+
222
+ if not sha1_folder.exists() or not sha1_folder.is_dir():
223
+ raise HTTPException(status_code=404, detail="SHA1 folder not found")
224
+
225
+ if not clip_folder.exists() or not clip_folder.is_dir():
226
+ raise HTTPException(status_code=404, detail="Clip folder not found")
227
+
228
+ # Find first MP4 file
229
+ mp4_files = list(clip_folder.glob("*.mp4"))
230
+ if not mp4_files:
231
+ raise HTTPException(status_code=404, detail="No MP4 files found")
232
+
233
+ video_path = mp4_files[0]
234
+
235
+ # Convert to relative path for FileManager
236
+ relative_path = video_path.relative_to(MEDIA_ROOT)
237
+
238
+ handler = file_manager.get_file(relative_path)
239
+ if handler is None:
240
+ raise HTTPException(status_code=404, detail="Video not accessible")
241
+
242
+ handler.close()
243
+
244
+ return FileResponse(
245
+ path=video_path,
246
+ media_type="video/mp4",
247
+ filename=video_path.name
248
+ )