File size: 13,170 Bytes
595a623
 
 
bd812cc
595a623
 
 
 
 
 
 
 
bd812cc
595a623
bd812cc
68317c1
 
595a623
68317c1
24728ac
 
 
595a623
24728ac
bd812cc
 
 
 
 
 
 
 
 
 
8d7f994
595a623
 
 
 
 
68317c1
 
595a623
68317c1
24728ac
68317c1
 
 
 
595a623
68317c1
24728ac
8d7f994
24728ac
 
595a623
 
 
24728ac
 
 
 
595a623
 
 
 
 
 
 
 
 
 
 
 
 
 
24728ac
595a623
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd812cc
 
 
 
 
 
 
 
 
 
595a623
 
24728ac
bd812cc
 
 
 
 
 
 
 
 
 
 
24728ac
 
 
 
 
595a623
24728ac
bd812cc
 
 
 
 
 
 
 
 
24728ac
 
 
 
 
 
 
 
 
8d7f994
 
 
 
bd812cc
24728ac
8d7f994
 
68317c1
e77f2cd
595a623
 
 
8d7f994
 
 
 
 
595a623
8d7f994
595a623
8d7f994
 
 
bd812cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24728ac
 
 
e77f2cd
595a623
 
 
 
 
 
 
 
 
 
 
 
8d7f994
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595a623
 
8d7f994
bd812cc
 
 
8d7f994
 
595a623
 
 
 
 
 
 
 
 
 
 
308a27e
595a623
 
 
 
8d7f994
24728ac
 
 
68317c1
8d7f994
 
24728ac
 
68317c1
bd812cc
 
 
 
 
 
 
595a623
24728ac
595a623
 
 
bd812cc
 
 
 
 
 
e77f2cd
24728ac
 
 
68317c1
d634104
24728ac
8d7f994
 
24728ac
8d7f994
 
 
24728ac
8d7f994
24728ac
595a623
8d7f994
 
d634104
8d7f994
 
 
 
24728ac
595a623
24728ac
8d7f994
 
 
 
 
 
 
 
 
 
 
 
24728ac
8d7f994
 
 
 
68317c1
8d7f994
595a623
 
 
 
e77f2cd
24728ac
595a623
8d7f994
e77f2cd
595a623
 
c16ddde
8d7f994
 
 
 
 
 
 
 
 
595a623
68317c1
595a623
24728ac
68317c1
e77f2cd
24728ac
595a623
 
 
e77f2cd
68317c1
f9e4bd1
bd812cc
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
# app.py
# Google Drive → Dropbox mirror (refresh-token based)
# ---------------------------------------------------------------
# pip install gradio dropbox google-api-python-client google-auth requests httplib2
#
# Secrets to set in Space settings:
# - DBX_APP_KEY
# - DBX_APP_SECRET
# - GDRIVE_SA_JSON         (full JSON of a service account with Drive read access)
# - APP_PASSWORD           (optional gate)
# - TRANSLATOR_MAP_JSON    (optional, e.g. {"FirstName LastName":"es","Vorname Nachname":"de"})

import os, io, re, json, time, random, socket
from typing import List, Tuple, Optional, Dict, Callable, Type

import gradio as gr
import dropbox
from dropbox.exceptions import ApiError, AuthError, HttpError as DbxHttpError

from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from googleapiclient.errors import HttpError as GHttpError

import requests
from requests import exceptions as req_exc

try:
    # urllib3 v2
    from urllib3.exceptions import NameResolutionError as Url3NameResolutionError
except Exception:  # urllib3 v1 shim
    class Url3NameResolutionError(Exception): ...
import httplib2

# ===== Secrets / Config =====
DBX_APP_KEY     = os.environ.get("DBX_APP_KEY", "")
DBX_APP_SECRET  = os.environ.get("DBX_APP_SECRET", "")
SA_JSON         = os.environ.get("GDRIVE_SA_JSON", "")
APP_PASSWORD    = os.environ.get("APP_PASSWORD", "")
HARDCODED_MAP   = {k.lower(): v for k, v in json.loads(os.environ.get("TRANSLATOR_MAP_JSON", "{}")).items()}

FORBIDDEN = {"/": " - ", "\0": ""}
GDRIVE_SCOPE = ["https://www.googleapis.com/auth/drive.readonly"]

# ===== Utilities =====
def sanitize(name: str) -> str:
    s = (name or "").strip()
    for bad, repl in FORBIDDEN.items():
        s = s.replace(bad, repl)
    return s[:255] or "untitled"

def extract_folder_id_from_url(url: str) -> Optional[str]:
    m = re.search(r"/folders/([a-zA-Z0-9_-]+)", (url or "").strip())
    return m.group(1) if m else None

def guard(pw: str) -> bool:
    return (APP_PASSWORD == "") or (pw == APP_PASSWORD)

def gdrive_service():
    if not SA_JSON:
        raise RuntimeError("Missing GDRIVE_SA_JSON secret.")
    info = json.loads(SA_JSON)
    creds = service_account.Credentials.from_service_account_info(info, scopes=GDRIVE_SCOPE)
    return build("drive", "v3", credentials=creds, cache_discovery=False)

def dbx_from_refresh(rt: str) -> dropbox.Dropbox:
    if not (DBX_APP_KEY and DBX_APP_SECRET):
        raise RuntimeError("Missing DBX_APP_KEY/DBX_APP_SECRET on server.")
    if not rt.strip():
        raise RuntimeError("Dropbox refresh token missing.")
    # Official SDK will auto-exchange/refresh using key+secret+RT.
    return dropbox.Dropbox(
        app_key=DBX_APP_KEY,
        app_secret=DBX_APP_SECRET,
        oauth2_refresh_token=rt.strip(),
        timeout=300,
    )

def retry(
    exceptions: Tuple[Type[BaseException], ...],
    tries: int = 3,
    base_delay: float = 0.5,
    max_delay: float = 5.0,
):
    def deco(fn: Callable):
        def wrapped(*args, **kwargs):
            attempt = 0
            while True:
                try:
                    return fn(*args, **kwargs)
                except exceptions as e:
                    attempt += 1
                    if attempt >= tries:
                        raise
                    sleep = min(max_delay, base_delay * (2 ** (attempt - 1))) * (1 + 0.1 * random.random())
                    time.sleep(sleep)
        return wrapped
    return deco

# Network-ish exceptions we want to back off on
NET_EXC = (
    req_exc.ConnectionError,
    req_exc.Timeout,
    Url3NameResolutionError,
    socket.gaierror,
    httplib2.ServerNotFoundError,
)

@retry((AuthError, DbxHttpError, ApiError) + NET_EXC, tries=5, base_delay=0.8, max_delay=8.0)
def ping_dropbox(dbx: dropbox.Dropbox):
    dbx.users_get_current_account()

def _should_retry_ghttp(e: GHttpError) -> bool:
    try:
        code = int(getattr(e, "resp", None).status)
    except Exception:
        code = None
    return code in {500, 502, 503, 504}

@retry((GHttpError, httplib2.ServerNotFoundError, socket.gaierror), tries=5, base_delay=0.8, max_delay=8.0)
def _list_children_page(svc, folder_id: str, page_token: Optional[str]) -> dict:
    try:
        return svc.files().list(
            q=f"'{folder_id}' in parents and trashed=false",
            fields="nextPageToken, files(id, name, mimeType)",
            pageToken=page_token,
            pageSize=1000,
            supportsAllDrives=True,
            includeItemsFromAllDrives=True,
        ).execute()
    except GHttpError as e:
        if _should_retry_ghttp(e):
            raise
        raise

def list_children(svc, folder_id: str) -> List[dict]:
    items, page_token = [], None
    while True:
        resp = _list_children_page(svc, folder_id, page_token)
        items.extend(resp.get("files", []))
        page_token = resp.get("nextPageToken")
        if not page_token:
            break
    return items

def is_folder(item: dict) -> bool:
    return item.get("mimeType") == "application/vnd.google-apps.folder"

def dpath_join(*parts: str) -> str:
    p = "/".join(x.strip("/") for x in parts if x and x != "/")
    return f"/{p}" if p else "/"

@retry((ApiError, DbxHttpError) + NET_EXC, tries=5, base_delay=0.8, max_delay=8.0)
def ensure_dropbox_folder(dbx: dropbox.Dropbox, path: str):
    if path == "/":
        return
    try:
        dbx.files_create_folder_v2(path, autorename=False)
    except ApiError:
        # Exists or conflict → fine
        pass

def should_skip(dbx: dropbox.Dropbox, dest_path: str, overwrite: bool) -> bool:
    if overwrite:
        return False
    try:
        dbx.files_get_metadata(dest_path)
        return True
    except ApiError:
        return False

def drive_download_to_buffer(svc, file_id: str) -> io.BytesIO:
    @retry((GHttpError, httplib2.ServerNotFoundError, socket.gaierror), tries=5, base_delay=0.8, max_delay=8.0)
    def _dl():
        buf = io.BytesIO()
        request = svc.files().get_media(fileId=file_id)
        downloader = MediaIoBaseDownload(buf, request)
        done = False
        while not done:
            try:
                _, done = downloader.next_chunk()
            except GHttpError as e:
                if _should_retry_ghttp(e):
                    raise
                raise
        buf.seek(0)
        return buf
    return _dl()

@retry((ApiError, DbxHttpError) + NET_EXC, tries=5, base_delay=0.8, max_delay=8.0)
def upload_file(dbx: dropbox.Dropbox, dest_path: str, stream: io.BytesIO):
    stream.seek(0)
    dbx.files_upload(stream.read(), dest_path, mode=dropbox.files.WriteMode("overwrite"))

# ===== Recursive mirror =====
def mirror_tree(
    svc,
    dbx,
    drive_folder_id: str,
    dest_root: str,
    overwrite: bool,
    dry_run: bool,
    logs: List[str],
    counters: Dict[str, int],
    actor_label: str,
):
    ensure_dropbox_folder(dbx, dest_root)
    for item in list_children(svc, drive_folder_id):
        name = sanitize(item["name"])
        if is_folder(item):
            sub_dest = dpath_join(dest_root, name)
            ensure_dropbox_folder(dbx, sub_dest)
            mirror_tree(svc, dbx, item["id"], sub_dest, overwrite, dry_run, logs, counters, actor_label)
        else:
            dp = dpath_join(dest_root, name)
            if dry_run:
                logs.append(f"[DRY] {actor_label} → {dp}")
                counters["planned"] += 1
                continue
            if should_skip(dbx, dp, overwrite):
                logs.append(f"• Exists, skipped: {dp}")
                counters["skipped"] += 1
                continue
            try:
                buf = drive_download_to_buffer(svc, item["id"])
                upload_file(dbx, dp, buf)
                logs.append(f"✓ {dp}")
                counters["uploaded"] += 1
            except (ApiError, DbxHttpError, GHttpError) as e:
                logs.append(f"× {dp} :: {type(e).__name__}: {str(e)[:400]}")
                counters["failed"] += 1
            except (req_exc.ConnectionError, req_exc.Timeout, Url3NameResolutionError, socket.gaierror, httplib2.ServerNotFoundError) as e:
                logs.append(f"× {dp} :: NetworkError: {type(e).__name__}: {str(e)[:200]}")
                counters["failed"] += 1

# ===== Core op =====
def mirror_course(
    intake_url: str,
    course_name: str,
    base_root: str,
    only_translators: str,
    overwrite: bool,
    dry_run: bool,
    password: str,
    dbx_refresh_token: str,
) -> Tuple[str, str]:
    if not guard(password):
        return "", "Wrong password."
    if not (DBX_APP_KEY and DBX_APP_SECRET):
        return "", "Missing Dropbox app key/secret on server."
    if not dbx_refresh_token.strip():
        return "", "Dropbox refresh token missing."

    course_name = sanitize(course_name)
    if not course_name:
        return "", "Course name required."

    base_root = "/" if not base_root.strip() else ("/" + base_root.strip().strip("/"))
    root_id = extract_folder_id_from_url(intake_url)
    if not root_id:
        return "", "Invalid Google Drive folder URL."

    # DNS warm-up (clear signal if host networking is borked)
    for host in ("www.googleapis.com", "api.dropboxapi.com"):
        try:
            socket.gethostbyname(host)
        except Exception:
            return "", f"DNS/network failure resolving {host} from host environment."

    # Clients
    svc = gdrive_service()
    dbx = dbx_from_refresh(dbx_refresh_token)
    try:
        ping_dropbox(dbx)
    except AuthError:
        return "", "Dropbox auth failed."
    except (ApiError, DbxHttpError):
        return "", "Dropbox connectivity failed."
    except (req_exc.ConnectionError, req_exc.Timeout, Url3NameResolutionError, socket.gaierror, httplib2.ServerNotFoundError):
        return "", "Dropbox DNS/network failure from host environment."

    course_root = dpath_join(base_root, course_name)
    ensure_dropbox_folder(dbx, base_root)
    ensure_dropbox_folder(dbx, course_root)

    allow = {x.strip().lower() for x in (only_translators or "").split(",") if x.strip()}

    logs: List[str] = []
    counters = {"uploaded": 0, "skipped": 0, "failed": 0, "planned": 0}
    translators = list_children(svc, root_id)

    found_any = False

    for t in translators:
        if not is_folder(t):
            continue
        t_name = (t["name"] or "").strip()
        t_key = t_name.lower()
        if allow and t_key not in allow:
            continue

        # find matching course folder(s) beneath this translator
        for c in list_children(svc, t["id"]):
            if not is_folder(c):
                continue
            if (c["name"] or "").strip().lower() != course_name.lower():
                continue

            found_any = True
            lang = HARDCODED_MAP.get(t_key)
            dest_root = dpath_join(course_root, lang) if lang else course_root
            ensure_dropbox_folder(dbx, dest_root)

            # mirror everything below the course folder (Intro/Lesson/Quiz/Title/Files…)
            mirror_tree(svc, dbx, c["id"], dest_root, overwrite, dry_run, logs, counters, actor_label=t_name)

    if not found_any:
        return "", f"No matching course '{course_name}' found under any translator."

    if dry_run:
        summary = f"Dry run. Would upload: {counters['planned']}"
    else:
        summary = f"Done. Uploaded: {counters['uploaded']} · Skipped: {counters['skipped']} · Failed: {counters['failed']}"
    return "\n".join(logs)[:200000], summary  # cap logs

# ===== UI =====
with gr.Blocks(
    title="Drive → Dropbox Course Ingest",
    analytics_enabled=False,
) as demo:
    gr.Markdown(
        "### Drive → Dropbox Course Ingest\n"
        "Mirrors files from a shared Google Drive intake into Dropbox.\n"
        "Drive: `{IntakeRoot}/{Translator}/{Course}/...` → Dropbox: `/{Base}/{Course}/[Language]/...`"
    )
    with gr.Row():
        pw  = gr.Textbox(type="password", label="Access password")
        dbx_refresh = gr.Textbox(type="password", label="Dropbox refresh token (paste per run)")
    with gr.Row():
        intake = gr.Textbox(label="Drive intake folder URL", placeholder="https://drive.google.com/drive/folders/<ID>")
        base_root = gr.Textbox(value="/Course Translations", label="Dropbox base root")
    with gr.Row():
        course = gr.Textbox(label="Course name (exact match)")
        only_translators = gr.Textbox(label="Only these translators (comma-separated, optional)")
    with gr.Row():
        overwrite = gr.Checkbox(value=False, label="Overwrite existing files in Dropbox")
        dry = gr.Checkbox(value=True, label="Dry run (no uploads)")
    run_btn = gr.Button("Run", variant="primary")

    logs = gr.Textbox(lines=22, label="Log", interactive=False, show_copy_button=True)
    status = gr.Markdown()

    run_btn.click(
        fn=mirror_course,
        inputs=[intake, course, base_root, only_translators, overwrite, dry, pw, dbx_refresh],
        outputs=[logs, status],
        api_name="mirror",
    )

if __name__ == "__main__":
    demo.queue().launch()