# 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 ('', size) if bold else ('', 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()