cdosea-play/cdoseaplay/update.py

96 lines
2.8 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, stream=True)
with open('%s.tmp' % name, 'wb') as fd:
shutil.copyfileobj(r.raw, fd)
shutil.move('%s.tmp' % name, name)
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):
head = requests.head(url)
mtime = time.mktime(datetime.strptime(head.headers.get("Last-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)
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'))
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()