-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
381 lines (322 loc) · 13.3 KB
/
main.py
File metadata and controls
381 lines (322 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import http.server
import socketserver
import json
import os
import re
import webbrowser
import urllib.parse
import shutil
import subprocess
import hashlib
import sys
from datetime import datetime, timezone
from pathlib import Path
# -----------------------------
# CONFIGURAÇÕES
# -----------------------------
PORT = 8000
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Cache do CapCut (origem): usa o perfil do utilizador atual (qualquer PC / nome de user no Windows)
_user_home = os.environ.get("USERPROFILE") or os.path.expanduser("~")
CAPCUT_CACHE_DIR = os.path.join(
_user_home,
"AppData",
"Local",
"CapCut",
"User Data",
"Cache",
"MotionBlurCache",
)
# Pasta de trabalho da app: listar, pré-visualizar e excluir só aqui (não duplica no disco)
VIDEOS_DIR = os.path.join(BASE_DIR, "videos")
CACHE_DIR = os.path.join(BASE_DIR, ".thumb_cache")
# Vídeos SEM marca d'água: ex. 97f6d5d9f307af9fe26ea73e6b1b60f5_1.mp4
# Vídeos COM marca d'água (ignorados): ex. 97f6d5d9f307af9fe26ea73e6b1b60f5_1.mp4.alpha.mp4
VIDEO_PATTERN = re.compile(r"^[a-f0-9]+_\d+\.mp4$", re.IGNORECASE)
os.chdir(BASE_DIR)
os.makedirs(CACHE_DIR, exist_ok=True)
os.makedirs(VIDEOS_DIR, exist_ok=True)
# -----------------------------
# FUNÇÕES AUXILIARES
# -----------------------------
def mover_videos_do_cache():
"""Move (não copia) vídeos válidos do cache do CapCut para VIDEOS_DIR. Chamado ao listar."""
if not os.path.isdir(CAPCUT_CACHE_DIR):
return
for f in os.listdir(CAPCUT_CACHE_DIR):
if not VIDEO_PATTERN.match(f):
continue
src = os.path.join(CAPCUT_CACHE_DIR, f)
if not os.path.isfile(src):
continue
dst = os.path.join(VIDEOS_DIR, f)
alpha_src = src + ".alpha.mp4"
try:
if os.path.exists(dst):
if os.path.getsize(src) == os.path.getsize(dst):
os.remove(src)
else:
os.replace(src, dst)
else:
shutil.move(src, dst)
except OSError as e:
print(f"[move] {f}: {e}")
continue
if os.path.isfile(alpha_src):
try:
os.remove(alpha_src)
except OSError:
pass
def gerar_thumbnail(video_path):
"""Gera thumbnail do vídeo usando ffmpeg (se disponível) ou retorna None"""
hash_name = hashlib.md5(video_path.encode()).hexdigest()
thumb_path = os.path.join(CACHE_DIR, f"{hash_name}.jpg")
if os.path.exists(thumb_path):
return thumb_path
try:
subprocess.run(
["ffmpeg", "-version"],
capture_output=True,
check=True,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
)
subprocess.run(
["ffmpeg", "-i", video_path, "-ss", "00:00:01", "-vframes", "1", "-q:v", "2", thumb_path],
capture_output=True,
check=True,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
)
if os.path.exists(thumb_path):
return thumb_path
except (subprocess.CalledProcessError, FileNotFoundError):
pass
return None
def listar_videos():
resultados = []
mover_videos_do_cache()
if not os.path.isdir(VIDEOS_DIR):
return {"erro": f"Pasta não encontrada: {VIDEOS_DIR}"}
for file in sorted(os.listdir(VIDEOS_DIR)):
# Aceita apenas arquivos sem marca d'água
if not VIDEO_PATTERN.match(file):
continue
video_path = os.path.join(VIDEOS_DIR, file)
thumb_path = gerar_thumbnail(video_path)
st = os.stat(video_path)
mod_iso = datetime.fromtimestamp(st.st_mtime, tz=timezone.utc).isoformat()
resultados.append({
"pasta": "",
"arquivo": file,
"caminho": video_path,
"thumb": thumb_path,
"tamanho_bytes": st.st_size,
"modificado": mod_iso,
})
return {
"videos": resultados,
"total": len(resultados),
"pastas": 1,
}
def excluir_arquivo(caminho_completo=None, arquivo=None):
"""Exclui na pasta CapCut: preferir `arquivo` (ex.: hash_1.mp4); `caminho` é opcional e pode vir corrompido do browser."""
path = None
if arquivo:
arquivo = str(arquivo).strip()
if not VIDEO_PATTERN.match(arquivo):
return {"ok": False, "erro": "Nome de arquivo inválido."}
path = os.path.join(VIDEOS_DIR, arquivo)
elif caminho_completo:
caminho_completo = str(caminho_completo).strip()
path = caminho_completo
# Path vindo da URL/DOM sem "\" (ex.: C:Users...): recupera só o nome válido
if not os.path.isfile(path):
m = re.search(r"([a-f0-9]+_\d+\.mp4)\s*$", path, re.I)
if m and VIDEO_PATTERN.match(m.group(1)):
path = os.path.join(VIDEOS_DIR, m.group(1))
else:
return {"ok": False, "erro": "Nenhum arquivo especificado."}
print(f"[excluir] path resolvido: {repr(path)}")
caminho_real = os.path.realpath(path)
videos_real = os.path.realpath(VIDEOS_DIR)
pasta_pai = os.path.dirname(caminho_real)
print(f"[excluir] caminho_real: {repr(caminho_real)}")
print(f"[excluir] videos_dir: {repr(videos_real)}")
if os.path.normcase(pasta_pai) != os.path.normcase(videos_real):
return {"ok": False, "erro": f"Caminho fora da pasta permitida: {caminho_real}"}
if not os.path.exists(caminho_real):
return {"ok": False, "erro": f"Arquivo não encontrado: {caminho_real}"}
try:
os.remove(caminho_real)
# Remove também o .alpha.mp4 correspondente, se existir
alpha = caminho_real + ".alpha.mp4"
if os.path.exists(alpha):
os.remove(alpha)
return {"ok": True, "mensagem": f"Arquivo excluído: {os.path.basename(caminho_real)}"}
except Exception as e:
return {"ok": False, "erro": str(e)}
# -----------------------------
# HANDLER DO SERVIDOR
# -----------------------------
class Handler(http.server.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
return super().end_headers()
def do_OPTIONS(self):
self.send_response(200)
self.end_headers()
def send_video_response(self, video_path):
"""Envia vídeo com suporte a Range Requests"""
if not os.path.exists(video_path):
self.send_response(404)
self.end_headers()
self.wfile.write(b"Arquivo nao encontrado")
return
file_size = os.path.getsize(video_path)
range_header = self.headers.get("Range")
if range_header:
range_match = re.match(r"bytes=(\d+)-(\d*)", range_header)
if range_match:
start = int(range_match.group(1))
end = range_match.group(2)
end = int(end) if end else file_size - 1
end = min(end, file_size - 1)
length = end - start + 1
self.send_response(206)
self.send_header("Content-Type", "video/mp4")
self.send_header("Content-Range", f"bytes {start}-{end}/{file_size}")
self.send_header("Content-Length", str(length))
self.send_header("Accept-Ranges", "bytes")
self.end_headers()
with open(video_path, "rb") as f:
f.seek(start)
self.wfile.write(f.read(length))
return
self.send_response(200)
self.send_header("Content-Type", "video/mp4")
self.send_header("Content-Length", str(file_size))
self.send_header("Accept-Ranges", "bytes")
self.end_headers()
with open(video_path, "rb") as f:
shutil.copyfileobj(f, self.wfile)
def do_GET(self):
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
query = urllib.parse.parse_qs(parsed.query)
if path == "/api/videos":
data = listar_videos()
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8"))
return
if path == "/api/preview":
video_path = urllib.parse.unquote(query.get("path", [""])[0])
self.send_video_response(video_path)
return
if path == "/api/download":
video_path = urllib.parse.unquote(query.get("path", [""])[0])
self.send_video_response(video_path)
return
if path == "/api/thumb":
thumb_path = urllib.parse.unquote(query.get("path", [""])[0])
if not os.path.exists(thumb_path):
self.send_response(404)
self.end_headers()
self.wfile.write(b"Thumbnail nao encontrada")
return
self.send_response(200)
self.send_header("Content-Type", "image/jpeg")
self.end_headers()
with open(thumb_path, "rb") as f:
shutil.copyfileobj(f, self.wfile)
return
if path in ("/", "/index.html"):
idx = os.path.join(BASE_DIR, "index.html")
if os.path.isfile(idx):
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Cache-Control", "no-store, must-revalidate")
self.end_headers()
with open(idx, "rb") as f:
shutil.copyfileobj(f, self.wfile)
return
self.path = "/index.html"
return super().do_GET()
def _responder_exclusao(self, caminho=None, arquivo=None):
print(f"[DELETE] caminho={repr(caminho)} arquivo={repr(arquivo)}")
result = excluir_arquivo(caminho_completo=caminho, arquivo=arquivo)
print(f"[DELETE] Resultado: {result}")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(json.dumps(result, ensure_ascii=False).encode("utf-8"))
def do_POST(self):
parsed = urllib.parse.urlparse(self.path)
if parsed.path == "/api/delete":
# Lê o body JSON: { "caminho": "C:\\...\\arquivo.mp4" }
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length)
try:
data = json.loads(body.decode("utf-8"))
arquivo = (data.get("arquivo") or "").strip() or None
caminho = (data.get("caminho") or "").strip() or None
except Exception:
arquivo, caminho = None, None
if arquivo:
self._responder_exclusao(arquivo=arquivo)
else:
self._responder_exclusao(caminho=caminho)
return
self.send_response(404)
self.end_headers()
def do_DELETE(self):
"""HTTP DELETE /api/delete?path=... (evita 501 do BaseHTTPRequestHandler)."""
parsed = urllib.parse.urlparse(self.path)
if parsed.path != "/api/delete":
self.send_response(404)
self.end_headers()
return
query = urllib.parse.parse_qs(parsed.query)
arquivo_q = query.get("arquivo", [""])[0]
path_q = query.get("path", [""])[0]
if arquivo_q.strip():
self._responder_exclusao(arquivo=urllib.parse.unquote(arquivo_q))
else:
self._responder_exclusao(caminho=urllib.parse.unquote(path_q))
def log_message(self, format, *args):
# Mostra apenas DELETE no terminal
if args and 'DELETE' in str(args[0]):
super().log_message(format, *args)
# -----------------------------
# EXECUÇÃO DO SERVIDOR
# -----------------------------
if __name__ == "__main__":
api_only = "--no-browser" in sys.argv or os.environ.get("CAPCUT_NO_BROWSER", "").strip() in (
"1",
"true",
"yes",
)
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f"🚀 Abra no navegador: http://localhost:{PORT}/index.html")
print(f"📂 Cache CapCut (origem): {CAPCUT_CACHE_DIR}")
print(f"📁 Vídeos: {VIDEOS_DIR}")
print(f"💾 Thumbnails: {CACHE_DIR}")
if api_only:
print("💡 Modo só API (--no-browser) — abra o URL acima manualmente.")
try:
subprocess.run(
["ffmpeg", "-version"],
capture_output=True,
check=True,
creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
)
print("✅ FFmpeg detectado - thumbnails serão geradas automaticamente")
except (subprocess.CalledProcessError, FileNotFoundError):
print("⚠️ FFmpeg não encontrado - thumbnails não serão geradas")
print(" Instale FFmpeg: https://ffmpeg.org/download.html")
if not api_only:
webbrowser.open(f"http://localhost:{PORT}/index.html")
httpd.serve_forever()