-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
executable file
·723 lines (530 loc) · 21.1 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
#!/usr/bin/env python3
from flask import Flask,session,request,render_template,Response,redirect,send_from_directory,make_response
from flask_caching import Cache
from flask_basicauth import BasicAuth
from yaml import load as yload,FullLoader
from starch import Archive,Package,Index
from starch.exceptions import RangeNotSupported
from contextlib import closing
from json import loads,dumps,load
from hashlib import md5,sha256
from starch.elastic import ElasticIndex
from starch.utils import decode_range,valid_path,max_iter,guess_content,flatten_structure
from os.path import join
from tempfile import NamedTemporaryFile,TemporaryFile,TemporaryDirectory
from time import time
from traceback import print_exc
from re import match
from requests import get
from math import log2
from tarfile import TarFile,TarInfo,open as taropen
from os import SEEK_END
from os.path import basename,dirname,exists
from starch.iterio import IterIO
import datetime
from sys import stdout
from io import UnsupportedOperation
from time import time
from urllib.parse import quote_plus
USE_NGINX_X_ACCEL = False
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
#app.use_x_sendfile = True
app.config.update(yload(open(join(app.root_path, 'config.yml')).read(), Loader=FullLoader))
app.jinja_env.line_statement_prefix = '#'
app.jinja_env.filters['quote_plus'] = lambda u: quote_plus(u)
cache = Cache(app, config={ 'CACHE_TYPE': 'filesystem', 'CACHE_DIR': app.config.get('flask_cache_dir', '/tmp/flask_cache') })
if 'auth' in app.config:
basic_auth = BasicAuth(app)
app.config['BASIC_AUTH_USERNAME'] = app.config['auth']['user']
app.config['BASIC_AUTH_PASSWORD'] = app.config['auth']['pass']
app.config['BASIC_AUTH_FORCE'] = True
archive = Archive(**app.config['archive'])
index = Index(**app.config['archive']['index']) if 'index' in app.config['archive'] else None
def make_key():
return request.args.get('q', '') + request.cookies.get('type', 'Package') + request.cookies.get('mode', 'light')
@app.route('/')
#@cache.cached(timeout=1, key_prefix=make_key)
def site_index():
q = request.args.get('q', {})
tpe = request.cookies.get('type', 'Package')
t0=time()
result = (index or archive).search(q, max=200 if tpe == 'Text' else 100, level=tpe, include=True)
t1=time()
#descriptions = [ (x, index.get(x) if index else archive.get(x).description()) for x in packages[3] ]
t2=time()
descriptions = [ x for x in result.keys ]
t3=time()
counts = (index or archive).count(
q,
{
#'type': { 'files': 'mime_type' },
'tag': 'tags',
'created': 'meta.year.keyword',
'size': 'sum(size)'
},
level=tpe) if tpe != 'Text' else {}
t4=time()
if 'size' in counts:
counts['size']['value'] = int(counts['size']['value'])
r = Response(
render_template('conspiracy.html',
start=result.start,
max=result.m,
n_packages=result.m,
#archive=archive,
descriptions=descriptions,
counts=counts,
query=q))
t5=time()
print(f'search: {t1-t0}, descriptions-1: {t2-t1}, descriptions-2: {t3-t2}, counts: {t4-t3}, render: {t5-t4}', flush=True)
return r
@app.route('/_set')
def set():
r = Response(headers={ 'Location': request.headers.get('Referer', '/') })
for p in request.args:
r.set_cookie(p, request.args[p])
return r, 302
@app.route('/<key>')
def view_thing(key):
_check_base(request)
p = archive.get(key)
if p == None:
return 'Not found', 404
return render_template(
'thing.html',
key=key,
structure=dumps(loads(archive.read(key, 'structure.json')) if 'structure.json' in p else []),
content=dumps(loads(archive.read(key, 'content.json')) if 'content.json' in p else []))
ret = (index or archive).get(key)
if ret:
return Response(dumps(ret, indent=4), mimetype='application/json')
else:
return 'Not found', 404
@app.route('/<key>/')
@app.route('/<key>/_package.json')
def package(key):
_check_base(request)
#return package_file(key, '_package.json')
#ret = (index or archive).get(key)
ret = archive.get(key)
if ret:
return Response(dumps(ret.description(), indent=4), mimetype='application/json')
else:
return 'Not found', 404
@app.route('/<key>/_tag', methods=[ 'POST' ])
def tag(key):
p = archive.get(key, mode='a')
if p:
if 'tag' in request.form or 'untag' in request.form:
for tag in request.form.getlist('tag'):
p.tag(tag)
for tag in request.form.getlist('untag'):
p.untag(tag)
return 'Done', 200
else:
return "parameter 'tag' or 'untag' missing", 400
else:
return 'Not found', 404
@app.route('/<key>/_view')
def view_package(key):
_check_base(request)
t0=time()
p = archive.get(key)
t1=time()
if p:
desc = p.description() if not isinstance(p, dict) else p
desc['files'] = { x['path']:x for x in desc['files'] }
mode = request.cookies.get('view', 'list')
if 'structure.json' not in p:
mode = 'list'
t2=time()
structure = loads(p.read('structure.json')) if 'structure.json' in p and mode == 'structure' else None
entities = loads(p.read('entities.json')) if 'entities.json' in p else None
structure = loads(p.read('structure.json')) if mode == 'structure' and 'structure.json' in p else []
t3=time()
r = Response(
render_template(
'package.html',
package=desc,
mode=mode,
read_only=app.config['archive'].get('mode', 'read-only') == 'read-only',
structure=flatten_structure(structure),
entities=entities),
mimetype='text/html')
t4=time()
print('time: ', t1-t0, t2-t1, t3-t2, t4-t3, t4-t0)
return r
else:
return 'Not found', 404
@app.route('/<key>/_log')
def log(key):
p = archive.get(key)
if p:
return Response(p.log(), mimetype='text/plain')
return 'Not found', 404
@app.route('/<key>/<path:path>/_view')
def view(key, path):
_assert_iiif()
i = _info(key, path)
if i:
return render_template('view.html', info=i)
else:
return 'Not found', 404
def _info(key, path):
_check_base(request)
if archive.exists(key, path):
p = archive.get(key)
callback = app.config.get('image_server', {}).get('callback_root', request.url_root)
url = f'{callback}{key}/{path}'
uri = f'{p.description()["@id"]}{path}'
if app.config.get('image_server', {}).get('send_location', False):
loc = archive.location(key, path)
if loc.startswith('file:'):
prefix = app.config.get('image_server', {}).get('prefix', None)
base = app.config.get('image_server', {}).get('archive_root', None)
if prefix:
url = loc.replace(base, f'{prefix}:')
if uri == '':
uri = f'{request.url_root}{key}/{path}'
image_url = app.config.get('image_server').get('root') + 'info'
print(image_url, uri, url, flush=True)
with closing(get(image_url, params={ 'uri': uri, 'url': url })) as r:
i = loads(r.text)
i['id'] = f'/{key}/{path}'
i['levels'] = [ 2**x for x in range(0, int(log2(min(i['width']-1, i['height']-1)) + 1 - int(log2(512)))) ]
return i
return None
# @todo avoid clash with files actually named info.json
@app.route('/<key>/<path:path>/info.json')
def iiif_info(key, path):
_check_base(request)
if archive.exists(key, path):
i = _info(key, path)
r = Response(render_template('info.json', **i), mimetype='application/json')
r.headers['Access-Control-Allow-Origin'] = '*'
return r
return f'/{key}/{path } not found', 404
@app.route('/<key>/<path:path>/<region>/<size>/<rot>/<quality>.<fmt>')
def iiif(key, path, region, size, rot, quality, fmt):
_check_base(request)
_assert_iiif()
if archive.exists(key, path):
iconf = app.config.get('image_server', {})
loc = archive.location(key, path)
if loc.startswith('file:'):
if iconf.get('send_location', False):
# send image using an internal prefix that is known by the image server
prefix = app.config['image_server']['prefix']
base = app.config['image_server']['archive_root']
url = loc.replace(base, f'{prefix}:')
elif iconf.get('callback_root', False):
# send image location to image server using callback since the internal
# name within Docker may not be the same as the external one
url = f'{iconf["callback_root"]}{key}/{path}'
else:
# simply use the request url
url = f'{request.url_root}{key}/{path}'
else:
url = loc
uri = app.config['archive']['base'] + key + '/' + path
image_url = iconf['root'] + 'image'
params = { 'uri': uri,
'url': url,
'region': region,
'size': size,
'rotation': rot,
'quality': quality,
'format': fmt, }
print(image_url, uri, url, flush=True)
r = get(image_url, params=params, stream=True)
if r.status_code != 200:
return f'Image server returned {r.status_code}', 500
return Response(
r.iter_content(100*1024),
mimetype=r.headers.get('Content-Type', 'application/unknown'))
return 'Not found', 404
@app.route('/<key>/_label', methods = [ 'POST' ])
def set_label(key):
_check_base(request)
try:
p = archive.get(key, mode='a')
if p:
#print(request.form.get('label'))
p.label = request.form.get('label')
return f'Changed label to "{p.label}"'
return 'Not found', 404
except Exception as e:
return str(e), 500
@app.route('/<key>/<path:path>/_manifest')
def iiif_manifest(key, path):
_assert_iiif()
return 'IIIF manifest'
@app.route('/<key>/_serialize')
def download(key):
_check_base(request)
p = archive.get(key)
if not p:
return 'Not found', 404
# set a 60 second timeout so that any lingering threads can be stopped
# client *must* validate resulting file
i = archive.serialize(
key,
resolve=request.args.get('resolve', 'true').lower() == 'true',
iter_content=True,
timeout=60,
buffer_size=1024*1024,
ignore=request.args.get('ignore', '').split(';'))
return Response(i, headers={ 'Content-Disposition': f'attachment; filename={key}.tar' }, mimetype='application/x-tar')
@app.route('/<key>/<path:path>', methods=[ 'GET' ])
def package_file(key, path):
_check_base(request)
# Fast x-send-file if possible
loc = archive.location(key, path)
if loc and loc.startswith('file://'):
if USE_NGINX_X_ACCEL:
r = make_response()
r.headers['X-Accel-Redirect'] = loc[7:]
r.headers['Content-Type'] = guess_content(path)
r.headers['filename'] = path
return r
# else:
# # quick fix for html
# if path.endswith('aspx') or path.endswith('html'):
# return Request(open(loc).read(), headers={ 'Content-Type': 'text/plain' })
#
# return send_from_directory(dirname(loc[7:]), basename(loc[7:]))
# Do things manually
p = archive.get(key)
if p and path in p:
size = int(p[path]['size'])
#headers = { 'Content-Disposition': f'inline; filename={basename(path)}' }
headers = {}
# fast hack for pretty JSON
if (p[path].get('mime_type', 'unknown') == 'application/json' or path.endswith('.json')) and 'pretty' in request.args:
return Response(dumps(loads(p.get_raw(path).read().decode('utf-8')), indent=2), mimetype='application/json'), 200
# quick fix for html
if p[path].get('mime_type', 'unknown') == 'text/html':
return Response(p.get_raw(path).read(), headers={ 'Content-Type': 'text/plain' })
if 'checksum' in p[path]:
headers.update({ 'ETag': p[path]['checksum'].split(':')[1] })
if 'size' in p[path]:
headers.update({ 'Content-Length': p[path]['size'] })
range = decode_range(request.headers.get('Range', default='bytes=0-'))
try:
i = p.get_iter(path, range=range)
headers.update({ 'Accept-Ranges': 'bytes' })
if range != ( 0, None ):
headers.update({ 'Content-Range': 'bytes %d-%s/%d' % (range[0], str(range[1]) if range[1] != None else size-1, size) })
headers.update({ 'Content-Length': range[1]-range[0] + 1 if range[1] != None else size-range[0] })
except UnsupportedOperation:
i = p.get_iter(path)
range = (0, None)
except:
raise
max_bytes = request.args.get('max_bytes', None)
if max_bytes:
headers['Content-Length'] = min(int(max_bytes), int(headers['Content-Length']))
return Response(
i if not max_bytes else max_iter(i, int(max_bytes)),
headers=headers,
mimetype=p[path].get('mime_type', 'application/unknown'),
status=200 if range == (0, None) else 206)
return 'Not found', 404
@app.route('/<key>/<path:path>', methods=[ 'PUT' ])
def put_file(key, path):
_check_base(request)
#print(request.args)
type = str(request.args.get('type', 'Resource'))
if type != 'Reference' and 'expected_hash' not in request.args:
#print(type, type == 'Reference', flush=True)
return 'parameter expected_hash missing', 400
try:
p = archive.get(key, mode='a')
if p:
path = valid_path(path)
url = request.args.get('url', None)
expected_hash = request.args.get('expected_hash', None)
replace = request.args.get('replace', 'False') == 'True'
args = { k:v for k,v in request.args.items() if k not in [ 'type', 'path', 'replace', 'url', 'expected_hash' ] }
if url and type == 'Reference':
p.add(path=path, url=url, replace=replace, type=type, **args)
return 'done', 204
else:
if path in request.files:
if expected_hash.startswith('MD5:'):
h = md5()
elif expected_hash.startswith('SHA256:'):
h = sha256()
else:
return 'unsupported hash function \'%s\'' % expected_hash.split(':')[0], 400
with NamedTemporaryFile() as tempfile:
with open(tempfile.name, 'wb') as o:
b = None
while b != b'':
b = request.files[path].read(100*1024)
o.write(b)
h.update(b)
h2 = expected_hash.split(':')[0] + ':' + h.digest().hex()
if h2 != expected_hash:
return 'expected hash %s, got %s' % (expected_hash, h2), 400
p = archive.get(key, mode='a')
p.add(tempfile.name, path=path, replace=replace, type=type, **args)
return 'done', 204
else:
return 'path (%s) not found in request' % path, 400
else:
return 'package not found', 400
except Exception as e:
print_exc()
print(flush=True)
return str(e), 500
@app.route('/<key>/<path:path>', methods=[ 'DELETE' ])
def delete_file(key, path):
_check_base(request)
package = archive.get(key, mode='a')
if package and path in package:
package.remove(path)
return 'deleted', 204
return 'Not found', 404
@app.route('/<key>/', methods=[ 'DELETE' ])
def delete_package(key):
try:
p = archive.get(key, mode='a')
if p:
archive.delete(key, force=True)
if index:
index.delete(key)
return 'deleted', 204
return 'Not found', 404
except Exception as e:
return e.message, 500
@app.route('/ingest', defaults={'key': None })
@app.route('/ingest/<key>', methods=[ 'POST' ])
def ingest(key):
_check_base(request)
if app.config['archive'].get('mode', 'read-only') != 'read-write':
return 'Archive is read-only', 500
with TemporaryDirectory() as tempdir:
# TODO: this probably breaks with very large packages
# TODO: implement serialize(...) so this can be done over TAR
# TODO: validate checksum
# TODO: cleanup on failure
for path in request.files:
temppath=join(tempdir, valid_path(path))
if not exists(dirname(temppath)):
makedirs(dirname(temppath))
with open(temppath, mode='wb') as o:
b=None
while b != b'':
b=request.files[path].read(100*1024)
o.write(b)
key = archive.ingest(Package(tempdir), key=key)
package = archive.get(key)
return redirect('/%s/' % key, code=201)
@app.route('/<key>/_deserialize', methods=[ 'POST' ])
def deserialize(key):
_check_base(request)
key = archive.deserialize(request.stream, key=key)
try:
if index:
_reindex(key)
except:
...
return redirect(f'/{key}/', code=201)
@app.route('/new', methods=[ 'POST' ])
def new():
_check_base(request)
#print(request.args)
key, package = archive.new(**{k:loads(v) if v[0] in [ '{', '[' ] else v for k,v in request.args.items() })
return redirect('/%s/' % key, code=201)
@app.route('/_packages')
@app.route('/packages')
def packages():
return Response(newliner(archive), mimetype='text/plain')
@app.route('/<key>/finalize', methods=[ 'POST' ])
def finalize(key):
_check_base(request)
p = archive.get(key, mode='a')
if p:
if p.status() == 'finalized':
return 'packet is finalized, use patches', 400
else:
p.finalize()
return 'finalized', 200
else:
return 'Not found', 404
@app.route('/base')
def base():
return app.config['archive']['base'] if 'base' in app.config['archive'] else request.url_root
@app.route('/_search')
@app.route('/search')
def search():
if request.args.get('q', '') == '':
return 'non-existant or empty q parameter', 500
tpe = request.args.get('@type', 'Package')
include = 'include' in request.args and request.args['include'] not in [ 'False', 'false' ]
query = request.args['q']
r = (index or archive).search(
query,
int(request.args.get('from', '0')),
int(request.args['max']) if 'max' in request.args else None,
request.args.get('sort', None),
level=tpe,
include=include)
return Response(
iter_search(r.start, r.n, r.m, r.keys),
mimetype='text/plain')
@app.route('/count')
def count():
return Response(
dumps(
(index or archive).count(
loads(request.args['q']),
loads(request.args['c']))) + '\n',
mimetype='application/json')
@app.route('/reindex/<key>')
def reindex(key):
if index:
return 'OK' if _reindex(key) else 'deleted'
return 'no index', 500
def _reindex(key):
p=archive.get(key)
if p:
index.update(key, p)
return True
else:
index.delete(key)
return False
@app.route('/deindex/<key>')
def deindex(key):
if index:
b = index.delete(key)
return "ok"
return 'no index', 500
@app.route('/favicon.ico')
def favicon():
return 'Not found', 404
def _check_base(request):
if 'base' not in app.config['archive']:
app.config['archive']['base'] = request.url_root
archive.base = request.url_root
def _assert_iiif():
if app.config.get('image_server', {}).get('url', '') != '':
raise Exception('No image server')
#@app.route('/static/<path:path>')
#def static(path):
# return send_from_directory('static', path)
def iter_search(start, returned, count, gen):
yield '%d %d %d\n' % (start, returned, count)
for id in gen:
if isinstance(id, tuple):
yield str(id[0]) + ',' + dumps(id[1]) + '\n'
else:
yield id + '\n'
def newliner(g):
for x in g:
yield x + '\n'
if __name__ == "__main__":
app.debug=True
app.run(host='0.0.0.0', threaded=True)