Skip to content

Instantly share code, notes, and snippets.

@zmwangx
Created December 7, 2018 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmwangx/912e2088b5a2ceaff7563d1963f8fa27 to your computer and use it in GitHub Desktop.
Save zmwangx/912e2088b5a2ceaff7563d1963f8fa27 to your computer and use it in GitHub Desktop.
Share sheet extension to download YouTube videos and save them to apps of your choice, powered by youtube-dl and Pythonista
import contextlib
import logging
import os
import shutil
import sys
import tempfile
import appex
import console
import youtube_dl
@contextlib.contextmanager
def chtmpdir():
try:
# In a share sheet extension, TMPDIR needs to be created.
os.mkdir(tempfile.gettempdir())
except OSError:
pass
tmpdir = tempfile.mkdtemp()
cwd = os.getcwd()
try:
os.chdir(tmpdir)
yield tmpdir
finally:
os.chdir(cwd)
shutil.rmtree(tmpdir)
def main():
if not appex.is_running_extension():
logging.warning("running in Pythonista app, using testing URL")
url = "https://youtu.be/M_XwzBMTJaM"
else:
url = appex.get_url()
if url is None:
text = appex.get_text()
if text is not None and text.startswith("http"):
url = text
else:
logging.critical(f"cannot extract URL (text: {text!r})")
sys.exit(1)
logging.info(f"URL: {url}")
with chtmpdir() as tmpdir:
logging.info(f"downloading to {tmpdir}...")
with youtube_dl.YoutubeDL() as ytdl:
ytdl.download([url])
file_list = os.listdir(tmpdir)
num_files = len(file_list)
if num_files == 0:
logging.critical("downloaded file not found")
sys.exit(1)
elif num_files > 1:
logging.critical(f"found {num_files} files: {file_list!r}")
sys.exit(1)
else:
console.open_in(file_list[0])
logging.info("done.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment