import json import os ''' minpackage = {'id': target_id, 'thumb': package['thumb'], 'subtitles': package['subtitles'], 'sources': package['sources']} ''' class Updater: def __init__(self, storage, jsonfile): self.storage = storage self.jsonfile = jsonfile def integrate_update(self, package): if package['origin'] != 'update': return package orig_id = package['orig_id'] workbase = package['workbase'] origbase = os.path.join(self.storage, orig_id) origjson = os.path.join(origbase, self.jsonfile) origpackage = None if not os.path.isfile(origjson): raise UpdateException(json.dumps(package), f'{origjson} not found.') with open(origjson) as f: origpackage = json.load(f) # Import untouched items from the original for key in ['thumb', 'subtitles']: if key not in package: # has to use .get() due to subs not always being there # should change to origpackage[key] origvalue = origpackage.get(key, '') package[key] = origvalue if origvalue: self._copy(origbase, workbase, origvalue) # deal with the sources # list modified sources by name updatesources = {source['name']: source for source in package['sources']} # list original sources by name origsources = {source['name']: source for source in origpackage['sources']} # prepare a fresh collection of sources combosources = {} for sourcename, origsource in origsources.items(): if sourcename in updatesources: # the source has been modified, copy untouched items updatesource = updatesources[sourcename] combosources[sourcename] = updatesource # name and playAudio are mandatory and can be ignored if 'poster' not in updatesource: # copy the unchanged poster combosources[sourcename]['poster'] = origsource['poster'] self._copy(origbase, workbase, origsource['poster']) if 'video' not in updatesource: # copy the unchanged video files combosources[sourcename]['video'] = origsource['video'] for variant in origsource['video']: self._copy(origbase, workbase, variant) elif sourcename not in package['delete']: # the source was untouched, copy everything combosources[sourcename] = origsource self._copy(origbase, workbase, origsource['poster']) for variant in origsource['video'].values(): self._copy(origbase, workbase, variant) package['sources'] = combosources return package def _copy(self, orig, dest, item): return shutil.copy(os.path.join(orig, item), os.path.join(dest, item)) class UpdateException(Exception): def __init__(self, package, message): self.package = package self.message = message