cdosea-play/cdoseaplay/update.py

103 lines
3 KiB
Python
Raw Normal View History

2017-08-25 19:21:36 +00:00
#!/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)
2017-10-12 16:45:57 +00:00
from .config import base, lang
2017-08-25 19:21:36 +00:00
lock = '/tmp/update.lock'
prefix = os.path.expanduser('~/Videos/CDOSEA')
if not os.path.exists(prefix):
os.makedirs(prefix)
os.chdir(prefix)
def get_subtitle(url, name):
try:
2017-10-04 09:02:34 +00:00
r = requests.get(url)
if r.status_code == 200:
2021-12-29 10:47:31 +00:00
with open('%s.tmp' % name, 'wb') as fd:
fd.write(r.content)
2017-10-04 09:02:34 +00:00
shutil.move('%s.tmp' % name, name)
else:
print('%s failed (%s)' % (url, r.status_code))
except KeyboardInterrupt:
os.unlink(lock)
sys.exit(-1)
2017-08-25 19:21:36 +00:00
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):
2017-10-04 23:49:32 +00:00
try:
head = requests.head(url, allow_redirects=True)
except KeyboardInterrupt:
sys.exit(-1)
2017-10-03 23:28:31 +00:00
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)
2017-08-25 19:21:36 +00:00
else:
get = True
if get:
print(url)
try:
r = requests.get(url, stream=True)
2017-10-04 23:44:12 +00:00
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))
2017-08-25 19:21:36 +00:00
except KeyboardInterrupt:
os.unlink(lock)
sys.exit(-1)
except:
print(url, 'failed')
def update_videos():
if os.path.exists(lock):
2018-07-05 11:12:40 +00:00
print('another update is already running')
2017-08-25 19:21:36 +00:00
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)
2017-10-04 09:02:34 +00:00
2017-08-25 19:21:36 +00:00
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == 'subtitles':
get_all_subtitles()
else:
update_videos()