Created
June 6, 2017 03:33
-
-
Save mattrasband/86db7966badeb7d29b54a4a6505f170c to your computer and use it in GitHub Desktop.
Download chromecast background
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import collections | |
import concurrent.futures | |
import json | |
import os | |
import pathlib | |
import re | |
import requests | |
CHROMECAST_HOME = 'https://clients3.google.com/cast/chromecast/home/v/c9541b08' | |
PROJECT_DIR = pathlib.Path(__file__).parent | |
Background = collections.namedtuple('Background', [ | |
'href', | |
'author', | |
]) | |
def find_backgrounds(chromecast_url): | |
"""Find the background from chromecast""" | |
r = requests.get(chromecast_url) | |
r.raise_for_status() | |
body = r.content | |
if isinstance(body, bytes): | |
body = body.decode() | |
match = re.search(r'JSON\.parse\(([^\)]+)', body) | |
if not match: | |
raise SystemExit('Unable to find background, the page content may have' | |
'changed.') | |
raw_text = match.group(1).encode('utf-8').decode('unicode_escape')\ | |
.replace('\\u003d', '=')\ | |
.replace('\\', '')\ | |
.replace("'", '')\ | |
.replace("s1280-w1280-h720", "s1920-w1920-h1200")\ | |
.replace('\n', '') | |
js = json.loads(raw_text) | |
for background in js[0]: | |
bg = Background(*background[:2]) | |
if not any(x is None for x in [bg.href, bg.author]): | |
yield bg | |
def download_image_as(href, local_path): | |
r = requests.get(href) | |
r.raise_for_status() | |
with open(local_path, 'wb') as f: | |
for chunk in r.iter_content(chunk_size=1024): | |
if chunk: | |
f.write(chunk) | |
return local_path | |
def main(): | |
"""Do the main things""" | |
output_dir = PROJECT_DIR / 'output' | |
if not output_dir.is_dir(): | |
output_dir.mkdir() | |
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as pool: | |
downloaders = [] | |
for background in find_backgrounds(CHROMECAST_HOME): | |
output_name = output_dir / (os.path.basename(background.href) + '.jpg') | |
if output_name.is_file(): | |
print('Skipping known image:', output_name) | |
continue | |
downloaders.append(pool.submit( | |
download_image_as, | |
background.href, | |
str(output_name) | |
)) | |
for download in concurrent.futures.as_completed(downloaders): | |
if download.exception(): | |
print('Error during download:', download.exception()) | |
else: | |
print('finished download:', download.result()) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment