File size: 8,859 Bytes
6b3f2a3
 
1c83fd3
 
4a15ecd
f6f6e30
 
 
 
 
d7a7bad
824fdfc
9c8d68c
 
1c83fd3
 
ef8a826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b770ad2
9c8d68c
 
d51c8cc
b770ad2
1c83fd3
 
 
 
 
 
9c8d68c
d51c8cc
f6f6e30
1c83fd3
f6f6e30
1c83fd3
 
 
b770ad2
9c8d68c
 
 
1c83fd3
 
 
9c8d68c
1c83fd3
b770ad2
9c8d68c
 
b770ad2
1c83fd3
 
 
 
f6f6e30
 
 
 
 
 
 
 
 
 
 
 
 
d7a7bad
f6f6e30
 
d7a7bad
 
 
 
 
 
 
 
 
 
 
f6f6e30
 
 
d7a7bad
 
 
 
 
 
 
 
f6f6e30
 
 
 
 
 
 
 
 
 
 
d7a7bad
 
 
4a15ecd
a6ab8b7
f6f6e30
 
 
 
 
 
 
 
d7a7bad
 
f6f6e30
 
 
 
b770ad2
f6f6e30
 
b770ad2
f6f6e30
 
4a15ecd
f6f6e30
4a15ecd
f6f6e30
 
cb55387
d51c8cc
 
b770ad2
 
8b00905
f6f6e30
b770ad2
f6f6e30
 
e8f1268
a1f1c77
 
 
 
 
 
a6ab8b7
a1f1c77
a6ab8b7
a1f1c77
f6f6e30
 
 
a1f1c77
2ff2199
 
f6f6e30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1f1c77
f6f6e30
a1f1c77
 
 
 
f6f6e30
 
d51c8cc
b770ad2
cb55387
b770ad2
d0baa2d
 
 
b770ad2
cb55387
b770ad2
d0baa2d
 
 
 
ef8a826
 
b770ad2
d0baa2d
b770ad2
d0baa2d
 
 
 
b770ad2
 
 
 
 
 
 
d0baa2d
 
b770ad2
d0baa2d
 
c275c0c
b770ad2
d0baa2d
 
9c8d68c
 
2600a3c
b696593
d0baa2d
b770ad2
d0baa2d
 
 
 
 
 
 
 
b770ad2
2a96281
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
import streamlit as st
import os
import json
import time
import subprocess
import random
import string
import tempfile
import shutil
import mimetypes
import datetime

BASE_FOLDER = "uploaded_files"
CATEGORIES = ["AVATAR WORLD", "BLOX FRUITS", "TOCA LIFE"]
EXPIRATION_FILE = "expirations.json"

# --- Estilos CSS ---
st.markdown("""
    <style>
    .file-box {
        border: 1px solid #ccc;
        padding: 10px;
        margin-bottom: 10px;
        border-radius: 5px;
        background-color: #f9f9f9;
    }
    .file-name {
        font-size: 18px;
        font-weight: bold;
    }
    .expire-text {
        font-size: 14px;
        color: #555;
    }
    </style>
""", unsafe_allow_html=True)

# Cria as pastas se não existirem
for cat in CATEGORIES:
    os.makedirs(os.path.join(BASE_FOLDER, cat), exist_ok=True)

# Carrega dados de expiração
if os.path.exists(EXPIRATION_FILE):
    with open(EXPIRATION_FILE, "r") as f:
        expirations = json.load(f)
else:
    expirations = {}

st.title("📂 File Manager por Categoria")

# --- Funções auxiliares ---
def remove_expired_files():
    """Remove arquivos expirados automaticamente"""
    changed = False
    now = time.time()
    expired_files = []

    for file_full, expire_time in list(expirations.items()):
        cat, file = file_full.split("|||")
        file_path = os.path.join(BASE_FOLDER, cat, file)
        if now > expire_time:
            if os.path.exists(file_path):
                os.remove(file_path)
                expired_files.append(file_full)
                changed = True

    for file_full in expired_files:
        expirations.pop(file_full)

    if changed:
        with open(EXPIRATION_FILE, "w") as f:
            json.dump(expirations, f)

def random_string(length=12):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def process_video(file_path, hard_mode=False):
    """Processa vídeo removendo metadados e mascarando vestígios do ffmpeg"""
    temp_fd, temp_out = tempfile.mkstemp(suffix=".mp4")
    os.close(temp_fd)

    if not hard_mode:
        shutil.copy(file_path, temp_out)
        return temp_out

    # Randomizações técnicas
    crf = str(random.randint(18, 26))  
    bitrate = f"{random.randint(96, 192)}k"
    fps = f"{random.uniform(29.5, 30.5):.2f}"

    # Rotação de brands
    major_brand = random.choice(["isom", "iso2", "mp42", "avc1", "dash", "iso3"])
    compatible_sets = [
        ["isom", "iso2", "avc1", "mp41"],
        ["mp42", "isom", "avc1"],
        ["iso5", "mp41", "isom"],
        ["iso2", "mp42", "isom"]
    ]
    compatible_brands = " ".join(random.choice(compatible_sets))

    compressor = random_string(random.randint(6, 12))
    encoder_name = random_string(random.randint(6, 14))

    # Datas nunca zeradas
    start_date = datetime.datetime.now() - datetime.timedelta(days=180)
    random_date = start_date + datetime.timedelta(
        days=random.randint(0, 180),
        seconds=random.randint(0, 86400)
    )
    date_str = random_date.strftime("%Y-%m-%d %H:%M:%S")

    # Metadados falsos
    meta = {
        "title": random_string(random.randint(8, 20)),
        "comment": random_string(random.randint(8, 20)),
        "description": random_string(random.randint(8, 20)),
        "artist": random_string(random.randint(8, 20)),
        "album": random_string(random.randint(8, 20)),
        "genre": random_string(random.randint(5, 15)),
        "publisher": random_string(random.randint(5, 15)),
        "encoded_by": random_string(random.randint(5, 15)),
        "location": random_string(random.randint(5, 15)),
        "encoder": encoder_name,
        "creation_time": date_str,
        "modify_time": date_str
    }

    cmd_ffmpeg = [
        "ffmpeg", "-y", "-i", file_path,
        "-map", "0:v", "-map", "0:a?",
        "-map_metadata", "-1",
        "-c:v", "libx264", "-preset", "fast", "-crf", crf,
        "-c:a", "aac", "-b:a", bitrate,
        "-r", fps,
        "-movflags", "use_metadata_tags+faststart",
        "-metadata", f"major_brand={major_brand}",
        "-metadata", f"compatible_brands={compatible_brands}",
        "-metadata", f"encoder={encoder_name}",
        "-metadata", f"CompressorName={compressor}",
        "-fflags", "+bitexact",
        "-flags", "+bitexact",
    ]
    for k, v in meta.items():
        cmd_ffmpeg += ["-metadata", f"{k}={v}"]

    cmd_ffmpeg.append(temp_out)
    subprocess.run(cmd_ffmpeg, check=True)

    return temp_out

# --- Apagar arquivos vencidos ao iniciar ---
remove_expired_files()

# --- Upload ---
st.header("📤 Upload de Arquivos")
st.subheader("Selecione uma categoria:")

categoria = st.radio("Categoria:", CATEGORIES, index=None)
hard_mode = st.checkbox("Ativar randomização HARD (vídeos apenas)")

if "last_upload" not in st.session_state:
    st.session_state.last_upload = None

if categoria:
    uploaded_files = st.file_uploader(
        f"Selecione arquivos para '{categoria}'",
        accept_multiple_files=True,
        key=f"uploader_{categoria}"
    )
    auto_delete = st.checkbox("Excluir automaticamente após 24 horas")

    if uploaded_files:
        for uploaded_file in uploaded_files:
            if st.session_state.last_upload == uploaded_file.name:
                continue  

            folder = os.path.join(BASE_FOLDER, categoria)
            os.makedirs(folder, exist_ok=True)

            mime, _ = mimetypes.guess_type(uploaded_file.name)
            is_video = mime and mime.startswith("video")

            with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]) as tmp:
                tmp.write(uploaded_file.read())
                tmp_path = tmp.name

            if is_video and hard_mode:
                final_tmp = process_video(tmp_path, hard_mode=True)
            else:
                final_tmp = tmp_path

            if hard_mode and is_video:
                new_name = random_string(16) + ".mp4"
            else:
                new_name = uploaded_file.name

            file_path = os.path.join(folder, new_name)
            shutil.move(final_tmp, file_path)

            if auto_delete:
                key = f"{categoria}|||{new_name}"
                expirations[key] = time.time() + 24 * 60 * 60
                with open(EXPIRATION_FILE, "w") as f:
                    json.dump(expirations, f)

            st.session_state.last_upload = uploaded_file.name
            st.success(f"Arquivo '{new_name}' enviado com sucesso!")

# --- Lista de Arquivos agrupada por pasta ---
st.header("📄 Arquivos Disponíveis")

for categoria in CATEGORIES:
    folder = os.path.join(BASE_FOLDER, categoria)
    files = os.listdir(folder)

    st.subheader(f"📁 {categoria}")

    if not files:
        st.info("Nenhum arquivo na categoria.")
    else:
        for file in files:
            st.markdown(f"<div class='file-box'>", unsafe_allow_html=True)
            st.markdown(f"<div class='file-name'>{file}</div>", unsafe_allow_html=True)

            key = f"{categoria}|||{file}"

            expira = expirations.get(key)
            if expira:
                restante = int(expira - time.time())
                if restante > 0:
                    restante_horas = restante // 3600
                    restante_min = (restante % 3600) // 60
                    st.markdown(
                        f"<div class='expire-text'>⏳ Expira em {restante_horas}h {restante_min}min</div>",
                        unsafe_allow_html=True)
                else:
                    st.markdown("<div class='expire-text'>⚠ Expiração iminente</div>", unsafe_allow_html=True)

            col1, col2, col3 = st.columns(3)

            with col1:
                with open(os.path.join(folder, file), "rb") as f_obj:
                    st.download_button("⬇ Download", f_obj, file_name=file, key=f"down_{categoria}_{file}")

            with col2:
                if st.button("🗑 Excluir", key=f"delete_{categoria}_{file}"):
                    os.remove(os.path.join(folder, file))
                    expirations.pop(key, None)
                    with open(EXPIRATION_FILE, "w") as f:
                        json.dump(expirations, f)
                    st.success(f"Arquivo '{file}' excluído.")

            with col3:
                with open(os.path.join(folder, file), "rb") as f_obj:
                    if st.download_button("⬇ Baixar & Apagar", f_obj, file_name=file, key=f"download_delete_{categoria}_{file}"):
                        os.remove(os.path.join(folder, file))
                        expirations.pop(key, None)
                        with open(EXPIRATION_FILE, "w") as f:
                            json.dump(expirations, f)
                        st.success(f"Arquivo '{file}' baixado e removido.")

            st.markdown("</div>", unsafe_allow_html=True)