Skip to content

Instantly share code, notes, and snippets.

@itszechs
Created December 31, 2023 10:05
Show Gist options
  • Select an option

  • Save itszechs/24ff7a602bfa6cef0211d0b003fefea0 to your computer and use it in GitHub Desktop.

Select an option

Save itszechs/24ff7a602bfa6cef0211d0b003fefea0 to your computer and use it in GitHub Desktop.
A python simple python script to play public google drive links using mpv
from typing import Union
import requests
import sys
import re
import subprocess
GOOGLE_FILE_ID_REGEX = r"file/d/(.*)/"
GOOGLE_DRIVE_API_URL = "https://www.googleapis.com/drive/v3"
API_KEY = ""
session = requests.Session()
def get_id_from_link(drive_link: str) -> Union[str, None]:
try:
return re.search(pattern=GOOGLE_FILE_ID_REGEX, string=drive_link).group(1)
except (IndexError, AttributeError):
return None
def get_stream_url(file_id):
return f"{GOOGLE_DRIVE_API_URL}/files/{file_id}?key={API_KEY}&alt=media"
def get_file(file_id: str):
try:
response = session.get(
url=f"{GOOGLE_DRIVE_API_URL}/files/{file_id}",
params={"key": API_KEY, "fields": "name"},
)
response.raise_for_status()
return response
except requests.exceptions.HTTPError as err:
print(f"Error: {err.response.status_code} - {err.response.text}")
sys.exit(1)
def get_mpv(id, title):
title = title.replace("'", "")
title = title.replace("!", "_")
title = title.replace('"', "")
return f'mpv "{get_stream_url(id)}" --force-media-title="{title}"'
def start_mpv(id, name):
mpv = get_mpv(id, name)
subprocess.run(mpv, shell=True)
if __name__ == "__main__":
args = sys.argv
if len(args) < 2 or not args[1].startswith("https://drive.google.com/"):
print("Error: Invalid or no Google Drive link provided")
sys.exit(1)
link = args[1]
file_id = get_id_from_link(link)
if file_id is not None:
file_response = get_file(file_id)
if file_response.status_code == 200:
start_mpv(file_id, file_response.json()["name"])
else:
print("Error: File not found, please make sure the link is public")
else:
print("Error: Invalid link")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment