import hashlib, os, time, urllib.request
from asc import rufe
SATZ = '48bdeaf0-5df6-4f34-9c2f-3861c4db6e53'; ALT = '5e400019-72b7-8bea-8020-62d4e5535b26'
name = '5-slides.png'
daten = open(os.path.expanduser('~/workspace/git.mqtec.de/software/amj-namaztimes-ds/app/store/screenshots-6.9/' + name), 'rb').read()
print('loeschen', rufe('DELETE', f'/v1/appScreenshots/{ALT}')[0])
s, j = rufe('POST', '/v1/appScreenshots', {'data': {'type': 'appScreenshots', 'attributes': {'fileName': name, 'fileSize': len(daten)},
    'relationships': {'appScreenshotSet': {'data': {'type': 'appScreenshotSets', 'id': SATZ}}}}})
bid = j['data']['id']
for op in j['data']['attributes']['uploadOperations']:
    req = urllib.request.Request(op['url'], data=daten[op['offset']:op['offset'] + op['length']], method=op['method'], headers={h['name']: h['value'] for h in op['requestHeaders']})
    urllib.request.urlopen(req, timeout=120).read()
print('fertig gemeldet', rufe('PATCH', f'/v1/appScreenshots/{bid}', {'data': {'type': 'appScreenshots', 'id': bid, 'attributes': {'uploaded': True, 'sourceFileChecksum': hashlib.md5(daten).hexdigest()}}})[0])
for _ in range(24):
    time.sleep(10)
    s, j = rufe('GET', f'/v1/appScreenshots/{bid}')
    zust = j['data']['attributes']['assetDeliveryState']['state']
    if zust in ('COMPLETE', 'FAILED'): break
print('Zustand', zust)
s, j = rufe('GET', f'/v1/appScreenshotSets/{SATZ}/appScreenshots')
reihe = sorted(j['data'], key=lambda d: d['attributes']['fileName'])
print('Reihenfolge', rufe('PATCH', f'/v1/appScreenshotSets/{SATZ}/relationships/appScreenshots', {'data': [{'type': 'appScreenshots', 'id': d['id']} for d in reihe]})[0])
s, j = rufe('GET', f'/v1/appScreenshotSets/{SATZ}/appScreenshots')
print([(d['attributes']['fileName'], d['attributes']['assetDeliveryState']['state']) for d in j['data']])
