#!/usr/bin/env python3 """Pirata local engine. Shortcut arguments are a fixed verb and a SHA-256 digest.""" import ast import argparse import errno import hashlib import http.client import importlib.metadata import ipaddress import json import os import re import shutil import socket import ssl import subprocess import sys import tempfile import time import uuid import zipfile from contextlib import contextmanager from html.parser import HTMLParser from pathlib import Path from urllib.parse import unquote, urljoin, urlsplit, urlunsplit, quote VERSION = "1.0.1" ROOT = Path.home() / "Documents" / "Pirata" SOURCES = { "TikTok": ("tiktok.com",), "Facebook": ("facebook.com", "fb.watch"), "Instagram": ("instagram.com",), "X": ("x.com", "twitter.com"), "Pinterest": ("pinterest.com", "pin.it"), "YouTube": ("youtube.com", "youtu.be"), } KINDS = {"jpg":"Images","png":"Images","gif":"Images","webp":"Images","avif":"Images","heic":"Images", "mp4":"Videos","mov":"Videos","webm":"Videos","mp3":"Audio","m4a":"Audio","wav":"Audio","flac":"Audio","ogg":"Audio"} class Problem(ValueError): pass def address(raw): if not isinstance(raw, str) or not raw or any(ord(c)<33 for c in raw) or "\\" in raw: raise Problem("Enter one complete HTTPS URL.") p = urlsplit(raw) if p.scheme != "https" or not p.hostname or p.username is not None or p.password is not None or p.port not in (443, None): raise Problem("Use a public HTTPS address without credentials or a custom port.") host = p.hostname.encode("idna").decode().rstrip(".").lower() if not re.fullmatch(r"[a-z0-9.-]+",host) or "." not in host or host.endswith((".local",".localhost")): raise Problem("Use a public media host.") try: ip = ipaddress.ip_address(host) except ValueError: pass else: if not ip.is_global or ip.is_multicast or ip.is_reserved: raise Problem("Use a public media host.") # Keep already-escaped signed URLs intact while encoding Unicode for HTTP. path = quote(p.path or "/", safe="/%:@!$&'()*+,;=-._~") query = quote(p.query, safe="/?%:@!$&'()*+,;=-._~") return urlunsplit(("https", host, path, query, "")) def public_addresses(host): for info in socket.getaddrinfo(host,443,type=socket.SOCK_STREAM): ip=ipaddress.ip_address(info[4][0]) if ip.is_global and not ip.is_multicast and not ip.is_reserved: yield info class PublicHTTPS(http.client.HTTPSConnection): def connect(self): # Connect to the checked numeric address; still validate TLS for the hostname. for family, kind, proto, _, addr in public_addresses(self.host): sock = socket.socket(family,kind,proto) try: sock.settimeout(45) sock.connect(addr) self.sock = self._context.wrap_socket(sock, server_hostname=self.host) return except ssl.SSLError: sock.close() raise except OSError: sock.close() raise Problem("Public host unavailable. Check the link and your connection.") @contextmanager def fetch(raw): current = address(raw) for _ in range(7): u = urlsplit(current) connection = PublicHTTPS(u.hostname, timeout=45) try: connection.request("GET",urlunsplit(("","",u.path,u.query,"")),headers={"User-Agent":"Pirata/1.0","Accept-Encoding":"identity"}) res = connection.getresponse() if res.status in (301,302,303,307,308): current = address(urljoin(current,res.getheader("Location") or "")) continue if res.status in (401,403,451): raise Problem("Access restricted or link expired. Use the publisher’s download option.") if res.status in (404,410): raise Problem("Media unavailable. Request a fresh link.") if res.status != 200: raise Problem("The source returned HTTP %d. Try again later." % res.status) yield current,res return finally: connection.close() raise Problem("Too many redirects. Use the final media link.") def media_format(b): if b.startswith(b"\x89PNG\r\n\x1a\n"): return "png" if b.startswith(b"\xff\xd8\xff"): return "jpg" if b[:6] in (b"GIF87a",b"GIF89a"): return "gif" if b[:4] == b"RIFF": return {b"WEBP":"webp",b"WAVE":"wav"}.get(b[8:12]) if b[4:8] == b"ftyp": brand=b[8:12] return {b"M4A ":"m4a",b"qt ":"mov",b"avif":"avif",b"avis":"avif",b"heic":"heic",b"heix":"heic"}.get(brand,"mp4" if brand in (b"isom",b"iso2",b"mp41",b"mp42",b"avc1",b"M4V ",b"dash") else None) if b[:4]==b"fLaC": return "flac" if b[:4]==b"OggS": return "ogg" if b[:4]==b"\x1aE\xdf\xa3" and b"webm" in b[:128]: return "webm" if b[:3]==b"ID3" or (len(b)>3 and b[0]==255 and b[1]&0xe6==0xe2): return "mp3" return None def safe_name(value): name = re.sub(r"[^\w .()-]+","_",str(value),flags=re.UNICODE).strip(" .")[:90] name = name.encode("utf-8")[:216].decode("utf-8", errors="ignore").rstrip(" .") return name or "Media" def source(url): h=urlsplit(url).hostname return next((s for s,domains in SOURCES.items() if any(h==d or h.endswith("."+d) for d in domains)),"Direct") def direct_item(url, title=None): return {"url":address(url),"name":safe_name(title or Path(unquote(urlsplit(url).path)).stem),"label":"Original"} class StructuredMedia(HTMLParser): """Read publisher-declared original media only; skip thumbnails and embed players.""" def __init__(self): super().__init__(); self.active=False; self.blocks=[] def handle_starttag(self,tag,attrs): if tag=="script" and (dict(attrs).get("type") or "").split(";")[0].strip().lower()=="application/ld+json": self.active=True; self.blocks.append("") def handle_data(self,data): if self.active: self.blocks[-1]+=data def handle_endtag(self,tag): if tag=="script": self.active=False def structured_items(page,base): parser=StructuredMedia(); parser.feed(page) found={} def visit(node,group=None,parent_name=None): if isinstance(node,list): for child in node: visit(child,group,parent_name) if not isinstance(node,dict): return if str(node.get("isAccessibleForFree","true")).lower()=="false" or node.get("requiresSubscription") or node.get("conditionsOfAccess"): return kinds=node.get("@type",[]) if isinstance(kinds,str): kinds=[kinds] if not isinstance(kinds,list): kinds=[] is_media=any(k in ("MediaObject","VideoObject","ImageObject","AudioObject","Photograph") for k in kinds) title=node.get("name") or parent_name if is_media: group=group or uuid.uuid4().hex link=node.get("contentUrl") if isinstance(link,str): try: item=direct_item(urljoin(base,link),title) except (Problem,ValueError): pass else: item["group"]=group height=node.get("height") if isinstance(height,dict): height=height.get("value") if re.fullmatch(r"[0-9]{1,5}",str(height)) and int(height)>0: item["height"]=int(height) item["label"]=str(height)+"p" if "VideoObject" in kinds else str(height)+" px high" details=[node.get("duration"),node.get("contentSize")] author=node.get("creator") or node.get("author") if isinstance(author,dict): details.append(author.get("name")) for detail in details: if isinstance(detail,str) and detail: item["label"]+=" · "+safe_name(detail) found[item["url"]]=item visit(node.get("encoding"),group,title) for key in ("@graph","mainEntity","associatedMedia","video","audio","image","itemListElement","item","hasPart"): visit(node.get(key)) for block in parser.blocks: try: visit(json.loads(block)) except (ValueError,RecursionError): continue return list(found.values()) def inspect_direct(url): with fetch(url) as (final,res): mime=(res.getheader("Content-Type") or "").split(";")[0].lower() if mime and not (mime.startswith(("audio/","image/","video/")) or mime in ("application/ogg","application/octet-stream")): raise Problem("The link returned a page or an unsupported file. Use the original media URL.") ext=media_format(res.read(512)) if not ext: raise Problem("Unrecognized media format. Use a direct file link.") item=direct_item(final) item["ext"]=ext item["label"]="Original "+ext.upper() length=res.getheader("Content-Length") or "" if length.isdigit(): item["label"]+=" · "+length+" bytes" return [item] def public_page(url): with fetch(url) as (final,res): if source(final)!=source(url): raise Problem("Short link changed platforms. Paste the final post URL.") if "html" not in (res.getheader("Content-Type") or "").lower(): return [direct_item(final)] data=res.read(4*1024*1024+1) if len(data)>4*1024*1024: raise Problem("Page too large to inspect. Use a direct media link.") return structured_items(data.decode("utf-8","replace"),final) def youtube(url): raise Problem("Use Save to device for your own uploads in YouTube Studio, or paste a creator-provided file URL.") def adapter(platform, paths): def inspect(url): path=urlsplit(url).path if not re.search(paths,path,re.I): raise Problem("Share an individual %s post or media file." % platform) items=public_page(url) if not items: raise Problem("%s returned no public original media. Use its own Save option or a direct file link." % platform) return items return inspect ADAPTERS={"YouTube":youtube, "TikTok":adapter("TikTok",r"/(?:@[^/]+/(?:video|photo)/|t/|[A-Za-z0-9]+/?$)"), "Facebook":adapter("Facebook",r"/(?:.*?/videos/|reel/|watch|share/|[A-Za-z0-9]+/?$)"), "Instagram":adapter("Instagram",r"/(?:p|reel|reels|tv)/"), "Pinterest":adapter("Pinterest",r"/(?:pin/|[A-Za-z0-9]+/?$)"), "X":adapter("X",r"/(?:[^/]+/status|i/status)/"),"Direct":inspect_direct} def read_request(raw): raw=raw.strip() obj=json.loads(raw) if raw.startswith("{") else {"url":raw} if not isinstance(obj,dict): raise Problem("Invalid request.") return address(obj.get("url")),obj def download(item,folder): with fetch(item["url"]) as (url,res): mime=(res.getheader("Content-Type") or "").split(";")[0].strip().lower() if mime and not (mime.startswith(("video/","audio/","image/")) or mime=="application/octet-stream" or mime=="application/ogg"): raise Problem("The link returned a page or an unsupported file. Use the original media URL.") first=res.read(512); ext=media_format(first) if not ext: raise Problem("Unrecognized media format. Use the publisher’s original file.") length=int(res.getheader("Content-Length") or 0) if length and shutil.disk_usage(folder).free < length: raise Problem("Insufficient storage. Free space in Files and retry.") file=folder/(uuid.uuid4().hex+"."+ext) with file.open("xb") as out: out.write(first); shutil.copyfileobj(res,out,256*1024) if length and file.stat().st_size!=length: raise Problem("Transfer interrupted. Retry with a fresh link.") return file, url def encoders(): if not shutil.which("ffmpeg"): return {} try: result=subprocess.run(["ffmpeg","-hide_banner","-encoders"],capture_output=True,text=True,timeout=10,check=True) except (OSError,RuntimeError,subprocess.SubprocessError): return {} return {fmt:codec for fmt,codec in {"mp3":"libmp3lame","m4a":"aac","wav":"pcm_s16le"}.items() if re.search(r"\b"+codec+r"\b",result.stdout)} def choices(url,opts): items=ADAPTERS[source(url)](url) out=[{"label":i["name"]+" · "+i["label"],"items":[i],"mode":"original"} for i in items] groups={} for item in items: groups.setdefault(item.get("group",item["url"]),[]).append(item) target=str(opts.get("quality","")) ceiling=int(target[:-1]) if re.fullmatch(r"\d{3,4}p",target) else float("inf") preferred=[] for variants in groups.values(): ranked=sorted(variants,key=lambda i:i.get("height",0),reverse=True) preferred.append(next((v for v in ranked if v.get("height",0)<=ceiling),ranked[-1])) if len(preferred)>1: out.append({"label":"All originals · ZIP","items":preferred,"mode":"zip","preferred":True}) else: next(c for c in out if c["items"][0]==preferred[0])["preferred"]=True for item in items: ext=item.get("ext") or Path(urlsplit(item["url"]).path).suffix[1:].lower() if KINDS.get(ext) in ("Audio","Videos"): for fmt,codec in encoders().items(): out.append({"label":item["name"]+" · Audio "+fmt.upper(),"mode":fmt,"codec":codec,"items":[item]}) return out def store_file(src,name,category): folder=ROOT/category; folder.mkdir(exist_ok=True,parents=True) for index in range(1,sys.maxsize): suffix="" if index==1 else " (%d)"%index path=folder/(safe_name(name)+suffix+src.suffix) try: os.link(src,path) except FileExistsError: continue except OSError as exc: if exc.errno not in (errno.ENOTSUP,errno.EPERM,errno.EACCES): raise # A fresh private directory also permits an atomic move on filesystems without links. folder=Path(tempfile.mkdtemp(prefix="Export-",dir=folder)) path=folder/path.name os.replace(src,path) return path def save(choice,opts): ROOT.mkdir(parents=True,exist_ok=True) temp=ROOT/"Temporary"; temp.mkdir(exist_ok=True) with tempfile.TemporaryDirectory(dir=temp) as stage: folder=Path(stage); mode=choice["mode"]; items=choice["items"] if mode=="zip": z=folder/"collection.zip" with zipfile.ZipFile(z,"x",allowZip64=True) as archive: for n,i in enumerate(items,1): part, _ = download(i,folder); archive.write(part,f"{n:03d}-{safe_name(i['name'])}{part.suffix}"); part.unlink() return store_file(z,"Collection","Collections") part, final_url = download(items[0],folder) name = items[0]["name"] codec = choice.get("codec") if mode == "quick-direct": name = direct_item(final_url)["name"] mode = "original" requested = opts.get("audio") if requested in ("mp3", "m4a", "wav") and KINDS[part.suffix[1:]] in ("Audio", "Videos"): codec = encoders().get(requested) if codec: mode = requested if mode!="original": output=folder/("audio."+mode) bitrate=opts.get("bitrate","192k") if bitrate not in ("128k","192k","256k","320k"): bitrate="192k" cmd=["ffmpeg","-nostdin","-v","error","-protocol_whitelist","file,pipe","-format_whitelist","mov,mp3,wav,flac,ogg,matroska,webm","-i",str(part),"-map","0:a:0","-vn","-map_metadata","0","-c:a",codec] if mode!="wav": cmd+=["-b:a",bitrate] try: subprocess.run(cmd+[str(output)],check=True,capture_output=True) except (OSError,subprocess.SubprocessError): raise Problem("Audio conversion failed. Check for an audio track or choose Original.") part=output return store_file(part,name,KINDS[part.suffix[1:]]) def diagnostic(): return {"Pirata":VERSION,"Python":sys.version.split()[0],"FFmpeg audio outputs":list(encoders()),"engine folder":str(ROOT), "free bytes":shutil.disk_usage(Path.home()).free} def package_info(code): tree=ast.parse(code) compile(tree,"pirata.py","exec") version=next((n.value.value for n in tree.body if isinstance(n,ast.Assign) and isinstance(n.value,ast.Constant) and any(isinstance(t,ast.Name) and t.id=="VERSION" for t in n.targets)),None) if not isinstance(version,str) or not re.fullmatch(r"\d+\.\d+\.\d+",version): raise Problem("Invalid engine version.") return version def maintain(verb): current=Path(__file__).resolve() backup=current.with_name("pirata-previous.py") if verb=="restore": if not backup.is_file(): raise Problem("No previous version is available. Reinstall from your saved source ZIP.") data=backup.read_bytes(); version=package_info(data) else: staged=current.parent/"Pirata Update" data=(staged/"pirata.py").read_bytes() release=json.loads((staged/"release.json").read_text()) version=package_info(data) if release.get("sha256")!=hashlib.sha256(data).hexdigest() or release.get("version")!=version: raise Problem("Candidate does not match the release manifest. The installed engine was kept.") if verb=="check": return f"Installed {VERSION}; staged {version}. SHA-256 matches. Install only a release you trust." if tuple(map(int,version.split(".")))<=tuple(map(int,VERSION.split("."))): raise Problem("Candidate is the same version or older. Use Restore for recovery.") with tempfile.NamedTemporaryFile(dir=current.parent,delete=False) as out: out.write(data); candidate=Path(out.name) try: if verb=="update": with tempfile.NamedTemporaryFile(dir=current.parent,delete=False) as out: out.write(current.read_bytes()); previous=Path(out.name) os.replace(previous,backup) os.replace(candidate,current) finally: candidate.unlink(missing_ok=True) return f"Installed Pirata {version}. Run diagnostics and the sample download." def run(verb,key): if verb in ("check","update","restore"): return maintain(verb) if verb=="diagnostics": return json.dumps(diagnostic(),indent=2) if not key or not re.fullmatch(r"[a-fA-F0-9]{64}",key): raise Problem("The Shortcut must pass the SHA-256 hash of its input.") request=Path(key+".txt"); manifest=Path(key+".plan.json"); pick=Path(key+".choice.txt") raw=request.read_bytes() if hashlib.sha256(raw).hexdigest()!=key.lower(): raise Problem("Request changed. Re-share the URL using the documented Shortcut.") url,opts=read_request(raw.decode()) if verb=="plan": options=choices(url,opts) with tempfile.NamedTemporaryFile("w",dir=".",delete=False) as f: json.dump(options,f) os.replace(f.name,manifest) labels="\n".join(f"{n+1}. {c['label']}" for n,c in enumerate(options)) Path(key+".options.txt").write_text(labels) return labels try: if verb=="quick" and source(url)=="Direct": return str(save({"items":[direct_item(url)],"mode":"quick-direct"},opts)) if verb=="quick": options=choices(url,opts) choice=next(c for c in options if c.get("preferred")) if choice["mode"]!="zip": choice=next((c for c in options if c["items"]==choice["items"] and c["mode"]==opts.get("audio","original")),choice) else: if time.time()-manifest.stat().st_mtime>3600: raise Problem("Selection expired. Share the link again.") options=json.loads(manifest.read_text()) m=re.match(r"^(\d+)\. ",pick.read_text().strip()) if not m or not 1<=int(m[1])<=len(options): raise Problem("Select one of the listed media options.") choice=options[int(m[1])-1] return str(save(choice,opts)) finally: for p in (pick,manifest,request,Path(key+".options.txt")): p.unlink(missing_ok=True) if __name__=="__main__": parser=argparse.ArgumentParser() parser.add_argument("verb",choices=["plan","save","quick","diagnostics","check","update","restore"]); parser.add_argument("key",nargs="?") args=parser.parse_args() try: print(run(args.verb,args.key)) except Exception as exc: msg=str(exc) if isinstance(exc,Problem) else ("Free space in Files and retry." if getattr(exc,"errno",None)==errno.ENOSPC else "Could not finish. Check the URL, connection, Shortcut setup and available space.") print("Pirata: "+msg,file=sys.stderr); sys.exit(1)