cdosea-play/cdoseaplay/update.py

110 lines
3.3 KiB
Python
Executable file

#!/usr/bin/python3
from datetime import datetime
import json
import os
import requests
import shutil
import socket
import string
import sys
import time
import ox
socket.setdefaulttimeout(10)
base = 'https://cdosea.0x2620.org/static/render/'
lock = '/tmp/update.lock'
prefix = os.path.expanduser('~/Videos/CDOSEA')
if not os.path.exists(prefix):
os.makedirs(prefix)
os.chdir(prefix)
lang = '1080p'
conf = os.path.expanduser('~/.config/cdosea.json')
if os.path.exists(conf):
with open(conf) as fd:
config = json.load(fd)
if 'lang' in config:
lang = config['lang']
if 'base' in config:
base = config['base']
def get_subtitle(url, name):
try:
r = requests.get(url)
if r.status_code == 200:
with open('%s.tmp' % name, 'w') as fd:
fd.write(r.text)
shutil.move('%s.tmp' % name, name)
else:
print('%s failed (%s)' % (url, r.status_code))
except KeyboardInterrupt:
os.unlink(lock)
sys.exit(-1)
except:
pass
def get_all_subtitles():
for i in range(10):
for letter in string.ascii_lowercase:
name = '%s%02d.%s.srt' % (letter, i, '1080p')
rname = '%s%02d.%s.srt' % (letter, i, lang)
url = '%s%s' % (base, rname)
get_subtitle(url, name)
def update_video(url, name):
folder = os.path.dirname(name)
if folder and not os.path.exists(folder):
os.makedirs(folder)
if os.path.exists(name):
try:
head = requests.head(url, allow_redirects=True)
except KeyboardInterrupt:
sys.exit(-1)
modified = head.headers.get("Last-Modified")
if modified:
mtime = time.mktime(datetime.strptime(modified, "%a, %d %b %Y %X GMT").timetuple())
get = mtime > os.path.getmtime(name) or int(head.headers.get("Content-Length")) != os.path.getsize(name)
else:
get = True
if get:
print(url)
try:
r = requests.get(url, stream=True)
if r.status_code == 200:
with open('%s.tmp' % name, 'wb') as fd:
shutil.copyfileobj(r.raw, fd)
ox.avinfo('%s.tmp' % name)['duration']
shutil.move('%s.tmp' % name, name)
mtime = time.mktime(datetime.strptime(r.headers.get("Last-Modified"), "%a, %d %b %Y %X GMT").timetuple())
os.utime(name, (mtime, mtime))
ox.avinfo(name)['duration']
get_subtitle(url.replace('1080p.mp4', lang + '.srt'), name.replace('.mp4', '.srt'))
else:
raise Exception('failed to download %s (%s)' % (url, r.status_code))
except KeyboardInterrupt:
os.unlink(lock)
sys.exit(-1)
except:
print(url, 'failed')
def update_videos():
if os.path.exists(lock):
sys.exit(0)
with open(lock, 'w') as f:
f.write('')
for i in range(10):
for letter in string.ascii_lowercase:
name = '%s%02d.1080p.mp4' % (letter, i)
url = '%s%s' % (base, name)
update_video(url, name)
os.unlink(lock)
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == 'subtitles':
get_all_subtitles()
else:
update_videos()