pandora_cms/backup_films.py
2018-08-10 11:33:32 +01:00

78 lines
2.6 KiB
Python
Executable file

#!/usr/bin/env python3
import os
import sys
import unicodedata
import ox
import ox.api
def get_extension(api, oshash):
r = api.findMedia({'query': {
'conditions': [{'key': 'oshash', 'value': oshash}]
}, 'keys': ['extension']})['data']
return r['items'][0]['extension']
if __name__ == '__main__':
if len(sys.argv) > 1:
target = sys.argv[1]
else:
target = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Films')
if not target.endswith('/'):
target += '/'
site = 'pandora.cinemusespace.com'
api = ox.api.signin('https://%s/api/' % site)
keep = []
r = api.find({'range': [0, 1000], 'keys': ['id']})
for i in r['data']['items']:
item = api.get(id=i['id'], keys=['id', 'streams', 'title', 'director', 'year', 'instances'])['data']
director = item.get('director', ['Unknown Director'])
path = os.path.join('; '.join(director), '%s' % (item['title']))
if 'year' in item:
path += ' (%s)' % item['year']
path = ox.decode_html(path)
prefix = ox.decode_html(item['title'])
keep.append(unicodedata.normalize('NFD', os.path.join(target, path, 'annotations.json')))
parts = []
if len(item['streams']) == 1:
id = item['streams'][0]
ext = get_extension(api, id)
name = '%s.%s' % (item['title'], ext)
name = ox.decode_html(name)
part = 1
parts.append([os.path.join(path, name), item['id'], id, part])
else:
part = 1
for id in item['streams']:
ext = get_extension(api, id)
name = '%s.Part %d.%s' % (prefix, part, ext)
name = ox.decode_html(name)
parts.append([os.path.join(path, name), item['id'], id, part])
part += 1
for path, id, oshash, part in parts:
abspath = os.path.join(target, path)
if os.path.exists(abspath) and ox.oshash(abspath) != oshash:
os.unlink(abspath)
if not os.path.exists(abspath):
url = 'https://%s/%s/download/source/%s' % (site, id, part)
print('downloading', abspath[len(target):])
try:
api.save_url(url, abspath)
except:
print('failed to download', url)
keep.append(unicodedata.normalize('NFD', abspath))
for root, folders, files in os.walk(target):
for f in files:
path = os.path.join(root, f)
if unicodedata.normalize('NFD', path) not in keep:
print('deleting', path)
os.unlink(path)