File size: 30,241 Bytes
8c44e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
# coding: utf-8
"""
VideoDL Pro - tai VIDEO va ANH tu website, chay tren iPhone bang Pythonista.

- Khong gui du lieu di dau: moi thu chay tren may ban.
- Video: dung yt-dlp (file ten `yt-dlp` de trong thu muc Pythonista).
  Neu CHUA co yt-dlp, script van chay: no tu quet trang de tim link .mp4 roi tai.
- Anh: tu quet anh trong trang roi tai ve, co the luu thang vao app Anh.
- Han che iOS: khong chay duoc ffmpeg nen khong ghep duoc luong hinh/tieng tach roi
  (kieu YouTube/DASH). Website cho file mp4 san thi tai binh thuong, toi 1080p.

Dung: mo file nay trong Pythonista roi bam nut play (tam giac ben phai tren).
"""

import os
import re
import sys
import time
import urllib.parse
from concurrent.futures import ThreadPoolExecutor

import ui
import console
import clipboard
import requests

# --------------------------------------------------------------- thu muc luu file

APP_DIR = os.path.expanduser('~/Documents/VideoDL')
VID_DIR = os.path.join(APP_DIR, 'Video')
IMG_DIR = os.path.join(APP_DIR, 'Anh')
for _d in (APP_DIR, VID_DIR, IMG_DIR):
    if not os.path.exists(_d):
        os.makedirs(_d)

YTDLP_CANDIDATES = [
    os.path.expanduser('~/Documents/yt-dlp'),
    os.path.expanduser('~/Documents/yt-dlp.zip'),
    os.path.expanduser('~/Documents/bin/yt-dlp'),
]

UA = ('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 '
      '(KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1')

IMG_EXT_RE = re.compile(r'\.(jpe?g|png|webp|gif|bmp|avif|heic|tiff?)(?:[?#]|$)', re.I)
MEDIA_EXT_RE = re.compile(r'\.(mp4|m4v|mov|webm|mkv|m4a|mp3|aac)(?:[?#]|$)', re.I)
JUNK_RE = re.compile(r'(sprite|blank|pixel|spacer|1x1|loading|placeholder|transparent'
                     r'|logo|icon|avatar|thumb)', re.I)
AD_HINT_RE = re.compile(r'(doubleclick|googlesyndication|2mdn|imasdk|adserver|vast|vpaid'
                        r'|advert|banner)', re.I)

MIN_IMG_BYTES = 25 * 1000
MAX_IMG_BYTES = 60 * 1000 * 1000

# ------------------------------------------------------------------- tien ich


def host_of(url):
    try:
        return (urllib.parse.urlparse(url).hostname or '').replace('www.', '')
    except Exception:
        return ''


def unique_path(folder, name):
    path = os.path.join(folder, name)
    if not os.path.exists(path):
        return path
    stem, ext = os.path.splitext(name)
    i = 2
    while i < 9999:
        cand = os.path.join(folder, '%s_%d%s' % (stem, i, ext))
        if not os.path.exists(cand):
            return cand
        i += 1
    return os.path.join(folder, '%s_%d%s' % (stem, int(time.time()), ext))


def human(n):
    n = float(n or 0)
    if n >= 1000000:
        return '%.1f MB' % (n / 1000000.0)
    if n >= 1000:
        return '%.0f KB' % (n / 1000.0)
    return '%.0f B' % n


def safe_name(name, limit=90):
    name = re.sub(r'[\x00-\x1f/\\:*?"<>|]+', '_', str(name or '')).strip(' ._')
    return name[:limit] or 'khac'


def abs_media_url(base, href):
    """Doi link tuong doi thanh tuyet doi; bo link rac."""
    try:
        href = (href or '').strip()
        if not href or href.startswith(('data:', 'javascript:', 'blob:', '#', 'mailto:')):
            return ''
        url = urllib.parse.urljoin(base, href)
        parts = urllib.parse.urlsplit(url)
        if parts.scheme not in ('http', 'https'):
            return ''
        return urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path,
                                        parts.query, ''))
    except Exception:
        return ''

# ------------------------------------------------------------ yt-dlp (tuy chon)

_YTDL = 'unknown'


def load_ytdlp():
    """Nap yt-dlp tu file zip tai tren GitHub. Tra ve module hoac None."""
    global _YTDL
    if _YTDL != 'unknown':
        return _YTDL
    for path in YTDLP_CANDIDATES:
        if os.path.exists(path):
            if path not in sys.path:
                sys.path.insert(0, path)
            break
    try:
        import yt_dlp
        _YTDL = yt_dlp
    except Exception:
        _YTDL = None
    return _YTDL


class _YtdlLogger(object):
    def __init__(self, log):
        self._log = log

    def debug(self, msg):
        m = str(msg)
        if m.startswith('[info]'):
            self._log(m[6:160].strip())

    def info(self, msg):
        pass

    def warning(self, msg):
        self._log('CANH BAO: ' + str(msg)[:180])

    def error(self, msg):
        self._log('LOI: ' + str(msg)[:200])


def friendly_error(text):
    t = text or ''
    if 'Subprocesses are not supported' in t or 'ffmpeg' in t.lower():
        return ('Trang nay tach hinh va tieng thanh 2 luong, can ffmpeg de ghep - '
                'iOS khong cho chay ffmpeg. Hay thu chat luong "mp4 (1 file)" hoac '
                'dung app Palladium cho loai nay.')
    if 'DRM' in t:
        return 'Noi dung co khoa bao ve (DRM) nen khong tai duoc. Khong phai loi cai dat.'
    if 'Sign in to confirm' in t or 'login' in t.lower() or 'cookies' in t.lower():
        return 'Trang can dang nhap. iPhone khong lay duoc cookie Safari cho yt-dlp.'
    if 'Unsupported URL' in t:
        return 'Link nay chua duoc ho tro. Thu dan link cua trang chua video.'
    if 'HTTP Error 403' in t or '403 Forbidden' in t:
        return 'Trang chan tai truc tiep (403). Co the can Referer hoac chong bot.'
    if 'No supported JavaScript runtime' in t:
        return 'Canh bao Deno - chi anh huong YouTube, cac trang khac khong sao.'
    for line in reversed(t.splitlines()):
        if line.strip().startswith('ERROR:'):
            return line.strip()[:260]
    return (t.strip().splitlines() or [''])[-1][:260] or 'Khong ro nguyen nhan.'


def ytdlp_download(yt, url, quality, log, progress):
    """Tai bang yt-dlp. Chi dung dinh dang 1 file (iOS khong co ffmpeg)."""
    fmt = 'ba[ext=m4a]/ba' if quality == 'm4a' else 'b[ext=mp4]/b[ext=webm]/b'

    def hook(d):
        status = d.get('status')
        if status == 'downloading':
            total = d.get('total_bytes') or d.get('total_bytes_estimate') or 0
            got = d.get('downloaded_bytes') or 0
            pct = (got * 100.0 / total) if total else 0
            speed = d.get('speed')
            extra = human(got) + (' / ' + human(total) if total else '')
            if speed:
                extra += ' - %s/s' % human(speed)
            progress(pct, extra)
        elif status == 'finished':
            progress(100, 'dang hoan tat...')

    opts = {
        'format': fmt,
        'outtmpl': os.path.join(VID_DIR, '%(title).80B [%(id)s].%(ext)s'),
        'noplaylist': True,
        'quiet': True,
        'no_warnings': False,
        'noprogress': True,
        'progress_hooks': [hook],
        'logger': _YtdlLogger(log),
        'cachedir': os.path.join(APP_DIR, 'cache'),
        'socket_timeout': 30,
        'retries': 5,
        'fragment_retries': 5,
        'concurrent_fragment_downloads': 4,
        'http_headers': {'User-Agent': UA},
    }
    info = None
    path = None
    try:
        with yt.YoutubeDL(opts) as ydl:
            info = ydl.extract_info(url, download=True)
            try:
                path = ydl.prepare_filename(info)
            except Exception:
                path = None
    except Exception as exc:
        msg = '%s: %s' % (type(exc).__name__, exc)
        log('LOI: ' + msg[:220])
        log('GOI Y: ' + friendly_error(msg))
        return None

    candidate = None
    if isinstance(info, dict):
        for req in (info.get('requested_downloads') or []):
            for key in ('filepath', '_filename'):
                if req.get(key) and os.path.exists(req[key]):
                    candidate = req[key]
        if not candidate:
            for key in ('filepath', '_filename'):
                if info.get(key) and os.path.exists(info[key]):
                    candidate = info[key]
    if not candidate and isinstance(path, str) and os.path.exists(path):
        candidate = path
    if not candidate:
        try:
            files = [os.path.join(VID_DIR, f) for f in os.listdir(VID_DIR)
                     if not f.startswith('.')]
            if files:
                candidate = max(files, key=os.path.getmtime)
        except Exception:
            pass
    if candidate:
        log('XONG: %s (%s)' % (os.path.basename(candidate),
                               human(os.path.getsize(candidate))))
    return candidate

# --------------------------------------------------------- tai file truc tiep


def download_direct(url, folder, log, progress, referer=None):
    """Tai file media truc tiep (.mp4, .jpg...) bang requests."""
    name = safe_name(os.path.basename(urllib.parse.urlparse(url).path) or 'download')
    if not os.path.splitext(name)[1]:
        name += '.mp4'
    path = unique_path(folder, name)
    headers = {'User-Agent': UA, 'Accept': '*/*'}
    if referer:
        headers['Referer'] = referer
    got = 0
    try:
        with requests.get(url, headers=headers, stream=True, timeout=60) as resp:
            resp.raise_for_status()
            ctype = (resp.headers.get('Content-Type') or '').lower()
            if ctype.startswith('text/html'):
                log('LOI: Link nay tra ve trang web chu khong phai file media.')
                return None
            total = int(resp.headers.get('Content-Length') or 0)
            last = 0
            with open(path, 'wb') as fh:
                for chunk in resp.iter_content(262144):
                    if not chunk:
                        continue
                    fh.write(chunk)
                    got += len(chunk)
                    now = time.time()
                    if now - last > 0.25:
                        last = now
                        pct = (got * 100.0 / total) if total else 0
                        progress(pct, human(got) + (' / ' + human(total) if total else ''))
    except Exception as exc:
        log('LOI tai: %s' % str(exc)[:180])
        try:
            if os.path.exists(path):
                os.remove(path)
        except Exception:
            pass
        return None
    progress(100, human(got))
    log('XONG: %s (%s)' % (os.path.basename(path), human(got)))
    return path

# ------------------------------------------------------------------ quet trang


def fetch_html(url, log=None):
    try:
        resp = requests.get(url, headers={'User-Agent': UA, 'Accept-Language': 'vi,en;q=0.8'},
                            timeout=30)
        resp.raise_for_status()
        return resp.text
    except Exception as exc:
        if log:
            log('LOI mo trang: %s' % str(exc)[:160])
        return ''


def find_video_urls(page_url, log=None):
    """Tim link video/audio trong HTML cua trang (khong can yt-dlp)."""
    html = fetch_html(page_url, log)
    if not html:
        return []
    found = []
    patterns = (
        r'(?:src|href|data-src|data-video|data-file|data-mp4|content|file|url)'
        r'\s*[=:]\s*["\']([^"\']+\.(?:mp4|m4v|mov|webm|mkv|m4a|mp3)(?:\?[^"\']*)?)["\']',
        r'["\'](https?://[^\s"\'<>]+?\.(?:mp4|m4v|mov|webm|mkv|m4a|mp3)(?:\?[^\s"\'<>]*)?)["\']',
        r'(https?://[^\s"\'<>]+?\.(?:mp4|m4v|mov|webm|mkv)(?:\?[^\s"\'<>]*)?)',
    )
    for pattern in patterns:
        for m in re.finditer(pattern, html, re.I):
            found.append(m.group(1))
    if re.search(r'\.m3u8', html, re.I) and log:
        log('Trang nay dung luong HLS (.m3u8) - can yt-dlp de tai dung.')

    out, seen = [], set()
    for href in found:
        u = abs_media_url(page_url, href)
        if not u or u in seen or not MEDIA_EXT_RE.search(u):
            continue
        seen.add(u)
        out.append(u)
    out.sort(key=lambda u: (0 if re.search(r'(1080|720|hd|high|orig)', u, re.I) else 1,
                            1 if AD_HINT_RE.search(u) else 0))
    return out


def page_image_urls(page_url, log=None):
    """Quet anh trong HTML cua trang."""
    html = fetch_html(page_url, log)
    if not html:
        return []
    raw = []

    for m in re.finditer(r'srcset\s*=\s*["\']([^"\']+)["\']', html, re.I):
        best, best_w = None, -1
        for part in m.group(1).split(','):
            bits = part.strip().split()
            if not bits:
                continue
            width = 0
            if len(bits) > 1:
                mm = re.match(r'(\d+)w', bits[1])
                width = int(mm.group(1)) if mm else 0
            if width >= best_w:
                best, best_w = bits[0], width
        if best:
            raw.append(best)

    for m in re.finditer(
            r'(?:src|data-src|data-original|data-lazy-src|data-lazy|data-full|data-large'
            r'|data-image|data-hi-res|data-zoom-image|content)\s*=\s*["\']([^"\']+)["\']',
            html, re.I):
        raw.append(m.group(1))

    for m in re.finditer(r'https?://[^\s"\'<>()]+?\.(?:jpe?g|png|webp|gif|avif)', html, re.I):
        raw.append(m.group(0))

    out, seen = [], set()
    for href in raw:
        u = abs_media_url(page_url, href)
        if not u or u in seen or not IMG_EXT_RE.search(u):
            continue
        if JUNK_RE.search(u) or AD_HINT_RE.search(u):
            continue
        seen.add(u)
        out.append(u)
    return out[:400]


def download_image(url, folder, referer=None, skip_small=True):
    headers = {'User-Agent': UA, 'Accept': 'image/*,*/*'}
    if referer:
        headers['Referer'] = referer
    ctype = ''
    try:
        with requests.get(url, headers=headers, stream=True, timeout=40) as resp:
            resp.raise_for_status()
            ctype = (resp.headers.get('Content-Type') or '').split(';')[0].strip().lower()
            if ctype and not (ctype.startswith('image/') or
                              ctype == 'application/octet-stream'):
                return None
            chunks, size = [], 0
            for chunk in resp.iter_content(131072):
                if not chunk:
                    continue
                chunks.append(chunk)
                size += len(chunk)
                if size > MAX_IMG_BYTES:
                    return None
            if size < MIN_IMG_BYTES and skip_small:
                return None
            data = b''.join(chunks)
    except Exception:
        return None

    name = safe_name(os.path.basename(urllib.parse.urlparse(url).path) or 'anh')
    if not os.path.splitext(name)[1]:
        ext = {'image/jpeg': '.jpg', 'image/png': '.png', 'image/webp': '.webp',
               'image/gif': '.gif', 'image/avif': '.avif',
               'image/heic': '.heic'}.get(ctype, '.jpg')
        name += ext
    path = unique_path(folder, name)
    try:
        with open(path, 'wb') as fh:
            fh.write(data)
    except Exception:
        return None
    return path

# ------------------------------------------------------ luu vao app Anh (Photos)


def save_to_photos(path, log):
    ext = os.path.splitext(path)[1].lower()
    if ext in ('.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.heic', '.tiff', '.tif'):
        try:
            import photos
        except Exception as exc:
            log('Khong mo duoc module photos: %s' % str(exc)[:80])
            return False
        try:
            if photos.create_image_asset(path):
                return True
        except Exception:
            pass
        try:
            from PIL import Image
            return bool(photos.save_image(Image.open(path)))
        except Exception as exc:
            log('Khong luu duoc anh vao app Anh: %s' % str(exc)[:100])
            return False

    # video: goi thang UIKit
    try:
        from objc_util import c, load_framework, ns
        load_framework('UIKit')
        fn = c.UISaveVideoAtPathToSavedPhotosAlbum
        fn(ns(str(path)), None, None, None)
        return True
    except Exception as exc:
        log('Khong tu dua video vao app Anh duoc (%s).' % type(exc).__name__)
        log('   -> Bam "Mo file" roi bam nut Chia se -> Save Video de luu vao Anh.')
        return False

# ------------------------------------------------------------- thanh tien do


class Bar(ui.View):
    def __init__(self, **kwargs):
        self.value = 0.0
        super(Bar, self).__init__(**kwargs)

    def draw(self):
        w, h = self.width, self.height
        radius = h / 2.0
        ui.set_color('#1d2530')
        ui.Path.rounded_rect(0, 0, w, h, radius).fill()
        if self.value > 0:
            filled = max(h, w * min(100.0, self.value) / 100.0)
            ui.set_color('#16a34a')
            ui.Path.rounded_rect(0, 0, filled, h, radius).fill()

    def set_value(self, value):
        self.value = max(0.0, min(100.0, float(value)))
        self.set_needs_display()

# ------------------------------------------------------------------ giao dien

PAD = 12
BG = '#0f1216'
CARD = '#12161c'
TXT = '#e8ecf1'
DIM = '#8b98a8'
GREEN = '#16a34a'


def F(size, bold=False):
    return ('<System-Bold>', size) if bold else ('<System>', size)


class VideoDL(ui.View):
    def __init__(self):
        super(VideoDL, self).__init__()
        self.name = 'VideoDL Pro'
        self.background_color = BG
        self.last_file = None
        self.last_paths = []

        self.lbl_title = ui.Label()
        self.lbl_title.text = 'VideoDL Pro'
        self.lbl_title.font = F(22, True)
        self.lbl_title.text_color = TXT
        self.add_subview(self.lbl_title)

        self.lbl_sub = ui.Label()
        self.lbl_sub.text = 'Tai video & anh tu website - chay tren may ban'
        self.lbl_sub.font = F(12)
        self.lbl_sub.text_color = DIM
        self.add_subview(self.lbl_sub)

        self.tf = ui.TextField()
        self.tf.placeholder = 'Dan link trang web hoac link file media'
        self.tf.background_color = '#0e1319'
        self.tf.text_color = TXT
        self.tf.font = F(14)
        self.tf.border_width = 0
        try:
            self.tf.tint_color = GREEN
            self.tf.keyboard_type = ui.KEYBOARD_URL
            self.tf.autocapitalization_type = ui.AUTOCAPITALIZE_NONE
            self.tf.autocorrection_type = ui.AUTOCORRECTION_NO
            self.tf.clear_button_mode = 'while_editing'
            self.tf.spellchecking_type = ui.NO_SPELLCHECKING
        except Exception:
            pass
        self.add_subview(self.tf)

        shared = self.shared_url()
        if shared:
            self.tf.text = shared
            clipboard.set(shared)
        else:
            clip = (clipboard.get() or '').strip()
            if clip.startswith('http'):
                self.tf.text = clip

        self.seg_mode = ui.SegmentedControl()
        self.seg_mode.segments = ['Tu dong', 'Video', 'Anh', 'Ca hai']
        self.seg_mode.selected_index = 0
        try:
            self.seg_mode.tint_color = GREEN
        except Exception:
            pass
        self.add_subview(self.seg_mode)

        self.seg_q = ui.SegmentedControl()
        self.seg_q.segments = ['mp4 (1 file, toi 1080p)', 'chi nhac m4a']
        self.seg_q.selected_index = 0
        try:
            self.seg_q.tint_color = GREEN
        except Exception:
            pass
        self.add_subview(self.seg_q)

        self.lbl_photos = ui.Label()
        self.lbl_photos.text = 'Luu vao app Anh'
        self.lbl_photos.font = F(14)
        self.lbl_photos.text_color = '#cbd5e1'
        self.add_subview(self.lbl_photos)

        self.sw_photos = ui.Switch()
        self.sw_photos.value = True
        self.add_subview(self.sw_photos)

        self.lbl_filter = ui.Label()
        self.lbl_filter.text = 'Bo qua anh nho & icon quang cao'
        self.lbl_filter.font = F(14)
        self.lbl_filter.text_color = '#cbd5e1'
        self.add_subview(self.lbl_filter)

        self.sw_filter = ui.Switch()
        self.sw_filter.value = True
        self.add_subview(self.sw_filter)

        self.btn_go = ui.Button()
        self.btn_go.title = 'TAI NGAY'
        self.btn_go.font = F(19, True)
        self.btn_go.background_color = GREEN
        self.btn_go.tint_color = 'white'
        self.btn_go.corner_radius = 12
        self.btn_go.action = 'on_go'
        self.add_subview(self.btn_go)

        self.bar = Bar(background_color=BG)
        self.add_subview(self.bar)

        self.lbl_status = ui.Label()
        self.lbl_status.font = F(12)
        self.lbl_status.text_color = '#9fb3c8'
        self.add_subview(self.lbl_status)

        self.log = ui.TextView()
        self.log.editable = False
        self.log.background_color = CARD
        self.log.text_color = '#b9c4d1'
        self.log.font = F(11)
        self.log.text = ''
        self.add_subview(self.log)

        self.btn_paste = self.make_small('Dan link', 'on_paste')
        self.btn_open_file = self.make_small('Mo file', 'on_open_file')
        self.btn_save_photos = self.make_small('Luu vao Anh', 'on_save_photos')
        self.btn_folder = self.make_small('Vi tri file', 'on_folder')

        self.log_add('San sang. Dan link roi bam TAI NGAY.')
        self.info_startup()

    def make_small(self, title, action):
        btn = ui.Button()
        btn.title = title
        btn.font = F(12)
        btn.background_color = '#1b222c'
        btn.tint_color = TXT
        btn.corner_radius = 9
        btn.action = action
        self.add_subview(btn)
        return btn

    def shared_url(self):
        try:
            import appex
            if appex.is_running_extension():
                return (appex.get_url() or appex.get_text() or '').strip()
        except Exception:
            pass
        return ''

    def info_startup(self):
        yt = load_ytdlp()
        if yt:
            self.log_add('yt-dlp: OK (v%s)' % getattr(yt.version, '__version__', '?'))
        else:
            self.log_add('Chua co yt-dlp - van tai duoc mp4 truc tiep va anh.')
            self.log_add('   Muon tai moi loai trang: tai file "yt-dlp" tu GitHub,')
            self.log_add('   de vao Files -> On My iPhone -> Pythonista.')

    def log_add(self, text):
        stamp = time.strftime('%H:%M:%S')
        lines = (self.log.text or '').rstrip('\n').split('\n')
        lines.append('[%s] %s' % (stamp, text))
        lines = [ln for ln in lines if ln.strip()][-160:]
        self.log.text = '\n'.join(lines)
        try:
            cw, ch = self.log.content_size
            self.log.content_offset = (0, max(0, ch - self.log.height + 8))
        except Exception:
            pass

    def set_progress(self, pct, extra=''):
        try:
            self.bar.set_value(pct)
            self.lbl_status.text = ('%.0f%%  %s' % (pct, extra)).strip()
        except Exception:
            pass

    def layout(self):
        w, h = self.width, self.height
        inner = w - PAD * 2
        y = 8
        self.lbl_title.frame = (PAD, y, inner, 30)
        y += 30
        self.lbl_sub.frame = (PAD, y, inner, 16)
        y += 22
        self.tf.frame = (PAD, y, inner, 38)
        y += 45
        self.seg_mode.frame = (PAD, y, inner, 30)
        y += 36
        self.seg_q.frame = (PAD, y, inner, 30)
        y += 38
        self.lbl_photos.frame = (PAD, y, inner - 70, 26)
        self.sw_photos.frame = (w - PAD - 56, y - 1, 56, 28)
        y += 30
        self.lbl_filter.frame = (PAD, y, inner - 70, 26)
        self.sw_filter.frame = (w - PAD - 56, y - 1, 56, 28)
        y += 34
        self.btn_go.frame = (PAD, y, inner, 50)
        y += 58
        self.bar.frame = (PAD, y, inner, 9)
        y += 15
        self.lbl_status.frame = (PAD, y, inner, 20)
        y += 26

        bh = 34
        by2 = h - bh - 10
        by1 = by2 - bh - 6
        bw = (inner - 6) / 2.0
        self.btn_paste.frame = (PAD, by1, bw, bh)
        self.btn_open_file.frame = (PAD + bw + 6, by1, bw, bh)
        self.btn_save_photos.frame = (PAD, by2, bw, bh)
        self.btn_folder.frame = (PAD + bw + 6, by2, bw, bh)
        self.log.frame = (PAD, y, inner, max(70, by1 - y - 8))

    # -------------------------------------------------------------- nut nho

    def on_paste(self, sender):
        txt = (clipboard.get() or '').strip()
        if txt:
            self.tf.text = txt
            self.log_add('Da dan link tu clipboard.')
        else:
            self.log_add('Clipboard dang trong.')

    def on_open_file(self, sender):
        target = self.last_file
        if not target and self.last_paths:
            target = self.last_paths[-1]
        if target and os.path.exists(target):
            console.quicklook(target)
        else:
            self.log_add('Chua co file nao. Tai mot cai da nhe.')

    def on_save_photos(self, sender):
        targets = []
        if self.last_file and os.path.exists(self.last_file):
            targets = [self.last_file]
        elif self.last_paths:
            targets = self.last_paths
        if not targets:
            self.log_add('Chua co file nao de luu.')
            return
        done = 0
        for p in targets:
            if save_to_photos(p, self.log_add):
                done += 1
        self.log_add('Da luu %d/%d file vao app Anh.' % (done, len(targets)))

    def on_folder(self, sender):
        console.alert('File nam o dau?',
                      'Mo app Files -> On My iPhone -> Pythonista -> VideoDL\n\n'
                      'Video: %s\nAnh: %s' % (VID_DIR, IMG_DIR), 'OK',
                      hide_cancel_button=True)

    # ------------------------------------------------------------- tai chinh

    @ui.in_background
    def on_go(self, sender):
        url = (self.tf.text or '').strip()
        if not url.startswith('http'):
            self.log_add('Ban chua dan link (link phai bat dau bang http).')
            return

        mode = ['auto', 'video', 'image', 'both'][self.seg_mode.selected_index]
        if mode == 'auto':
            mode = 'image' if IMG_EXT_RE.search(url) else 'video'
        quality = 'm4a' if self.seg_q.selected_index == 1 else 'mp4'
        save_photos = bool(self.sw_photos.value)
        skip_small = bool(self.sw_filter.value)

        self.btn_go.enabled = False
        self.btn_go.title = 'DANG TAI...'
        self.set_progress(0, '')
        self.last_paths = []
        self.log_add('Bat dau: %s' % url[:110])
        t0 = time.time()
        try:
            if mode in ('video', 'both'):
                path = self.do_video(url, quality, save_photos)
                if path:
                    self.last_file = path
                    self.log_add('Thu muc: %s' % os.path.relpath(path, APP_DIR))
                    if save_photos and save_to_photos(path, self.log_add):
                        self.log_add('Da luu video vao app Anh.')
            if mode in ('image', 'both'):
                paths = self.do_images(url, save_photos, skip_small)
                if paths:
                    self.last_paths = paths
                    self.log_add('Da luu %d file vao thu muc Anh' % len(paths))
        except Exception as exc:
            self.log_add('Loi khong mong doi: %s: %s' % (type(exc).__name__,
                                                         str(exc)[:160]))
        finally:
            self.set_progress(100, 'hoan tat trong %.0f giay' % (time.time() - t0))
            self.btn_go.enabled = True
            self.btn_go.title = 'TAI NGAY'

    def do_video(self, url, quality, save_photos):
        if MEDIA_EXT_RE.search(url):
            self.log_add('Link la file media truc tiep - tai luon.')
            return download_direct(url, VID_DIR, self.log_add, self.set_progress)

        yt = load_ytdlp()
        if yt:
            self.log_add('Dang nho yt-dlp lay video...')
            path = ytdlp_download(yt, url, quality, self.log_add, self.set_progress)
            if path:
                return path
            self.log_add('yt-dlp khong lay duoc - chuyen sang tu quet trang.')

        self.log_add('Dang tu tim link video trong trang...')
        links = find_video_urls(url, self.log_add)
        if not links:
            self.log_add('Khong tim thay link video nao trong trang nay.')
            return None
        self.log_add('Thay %d link, tai cai dau tien.' % len(links))
        return download_direct(links[0], VID_DIR, self.log_add, self.set_progress,
                               referer=url)

    def do_images(self, url, save_photos, skip_small):
        if IMG_EXT_RE.search(url):
            self.log_add('Link la file anh truc tiep - tai luon.')
            path = download_image(url, IMG_DIR, '', skip_small)
            if not path:
                self.log_add('Khong tai duoc anh nay (qua nho hoac can dang nhap).')
                return []
            self.set_progress(100, '1 anh')
            if save_photos and save_to_photos(path, self.log_add):
                self.log_add('Da luu anh vao app Anh.')
            return [path]

        self.log_add('Dang quet anh trong trang...')
        urls = page_image_urls(url, self.log_add)
        if not urls:
            self.log_add('Khong thay anh nao trong HTML cua trang.')
            self.log_add('   (Trang chi hien anh bang JavaScript thi khong thay duoc.)')
            return []

        self.log_add('Thay %d anh - bat dau tai...' % len(urls))
        paths = []
        with ThreadPoolExecutor(max_workers=3) as pool:
            futures = [pool.submit(download_image, u, IMG_DIR, url, skip_small)
                       for u in urls]
            for index, fut in enumerate(futures, 1):
                try:
                    path = fut.result()
                except Exception:
                    path = None
                if path:
                    paths.append(path)
                self.set_progress(index * 100.0 / len(urls),
                                  '%d/%d anh' % (len(paths), index))

        self.log_add('Luu duoc %d/%d anh vao thu muc Anh.' % (len(paths), len(urls)))
        if paths and save_photos:
            saved = 0
            for path in paths:
                if save_to_photos(path, self.log_add):
                    saved += 1
            self.log_add('Da dua %d anh vao app Anh.' % saved)
        return paths


def main():
    try:
        console.set_idle_timer_disabled(True)  # khong cho man hinh tat khi dang tai
    except Exception:
        pass
    view = VideoDL()
    try:
        view.present('sheet')
    except Exception:
        view.present()


if __name__ == '__main__':
    main()