-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
369 lines (320 loc) · 12.5 KB
/
app.py
File metadata and controls
369 lines (320 loc) · 12.5 KB
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
from flask import Flask, jsonify, request, redirect, url_for, make_response, abort
from flask_sqlalchemy import SQLAlchemy
from flask_uuid import FlaskUUID
from sqlalchemy_utils import UUIDType
from sqlalchemy.orm import joinedload
from markupsafe import escape
import uuid
app = Flask(__name__)
# ------------------------------------------------------------
# DATABASE CONFIGURATION (MySQL)
# ------------------------------------------------------------
# Load config from file
app.config.from_object('config')
db = SQLAlchemy(app)
FlaskUUID(app)
# ------------------------------------------------------------
# DATABASE MODELS
# ------------------------------------------------------------
class Object(db.Model):
id = db.Column(db.Integer, primary_key=True)
uuid = db.Column(UUIDType(binary=False), default=uuid.uuid4, unique=True, nullable=False)
type_id = db.Column(db.Integer, db.ForeignKey('object_type.id'), nullable=False)
type = db.relationship('ObjectType', lazy=False, backref=db.backref('objects', lazy=True))
primary_id = db.Column(db.String(64))
class ObjectType(db.Model):
__tablename__ = 'object_type'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
url_construct = db.Column(db.String(256), nullable=True)
class Identifier(db.Model):
id = db.Column(db.String(128), primary_key=True)
object_id = db.Column(db.Integer, db.ForeignKey('object.id'), nullable=False)
object = db.relationship('Object', backref=db.backref('identifiers', lazy=True))
type_id = db.Column(db.Integer, db.ForeignKey('identifier_type.id'), nullable=False)
type = db.relationship('IdentifierType', lazy=False, backref=db.backref('identifiers', lazy=True))
class IdentifierType(db.Model):
__tablename__ = 'identifier_type'
id = db.Column(db.Integer, primary_key=True)
shortcode = db.Column(db.String(32), nullable=False)
description = db.Column(db.String(128), nullable=False)
url_construct = db.Column(db.String(256), nullable=True)
# ------------------------------------------------------------
# ARK MINTING
# ------------------------------------------------------------
NAAN = "83794"
def mint_ark():
suffix = str(uuid.uuid4())
return f"ark:/{NAAN}/{suffix}"
# ------------------------------------------------------------
# HELPERS
# ------------------------------------------------------------
def construct_url(url_format, id):
if url_format and id:
return url_format.replace("<id>", id)
return None
def init_identifier_types():
defaults = [
("ark", "Archival Resource Key", "https://n2t.net/ark:/83794/<id>"),
("luna", "LUNA Image ID", "https://images.is.ed.ac.uk/luna/servlet/detail/<id>"),
("arch", "Archipelago UUID", "https://digital.collections.ed.ac.uk/do/<id>"),
("file", "Source Filename", None),
("cantaloupe", "IIIF Cantaloupe ID",
"https://digital.collections.ed.ac.uk/cantaloupe/iiif/2/<id>/full/600,/0/default.jpg")
]
for shortcode, desc, url in defaults:
if not IdentifierType.query.filter_by(shortcode=shortcode).first():
db.session.add(IdentifierType(shortcode=shortcode, description=desc, url_construct=url))
db.session.commit()
# ------------------------------------------------------------
# ERROR HANDLING
# ------------------------------------------------------------
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'status': 404, 'error': 'Not found'}), 404)
# ------------------------------------------------------------
# ROUTES
# ------------------------------------------------------------
@app.route('/')
def index():
return 'Welcome to ERIC!'
@app.route('/object/<uuid:user_uuid>')
def view_object(user_uuid):
uuid_hex = user_uuid.hex
obj = (
Object.query
.options(joinedload(Object.identifiers).joinedload(Identifier.type))
.filter(Object.uuid == uuid_hex)
.first_or_404()
)
return jsonify({
"id": obj.id,
"uuid": obj.uuid,
"type": obj.type.name,
"primary_id": obj.primary_id,
"identifiers": [
{
"shortcode": ident.type.shortcode,
"description": ident.type.description,
"identifier": ident.id
}
for ident in obj.identifiers
]
})
@app.route('/identifier/<identifier>')
def view_identifier(identifier):
obj = Identifier.query.get_or_404(identifier)
return jsonify({
"identifier": obj.id,
"type": obj.type.description,
"eric_uuid": str(obj.object.uuid),
"eric_url": url_for('view_object', uuid=obj.object.uuid, _external=True),
"url": construct_url(obj.type.url_construct, obj.id),
})
# ------------------------------------------------------------
# LOOKUP (your existing resolver)
# ------------------------------------------------------------
@app.route("/lookup/<path:identifier_value>")
def lookup(identifier_value):
ident = Identifier.query.filter_by(id=identifier_value).first()
if not ident:
return jsonify({"error": "Identifier not found"}), 404
obj = (
Object.query
.options(joinedload(Object.identifiers).joinedload(Identifier.type))
.filter_by(id=ident.object_id)
.first()
)
if not obj:
return jsonify({"error": "Object not found"}), 404
all_ids = {}
html_rows = []
for i in obj.identifiers:
url = construct_url(i.type.url_construct, i.id) or i.id
all_ids[i.type.shortcode] = url
html_rows.append(
f"<tr><td>{escape(i.type.shortcode)}</td>"
f"<td><a href='{escape(url)}'>{escape(i.id)}</a></td></tr>"
)
# Default redirect → ARCH record
if request.args.get("format") is None:
arch_ident = next((i for i in obj.identifiers if i.type.shortcode == "arch"), None)
if arch_ident:
arch_url = construct_url(arch_ident.type.url_construct, arch_ident.id)
return redirect(arch_url, code=302)
if request.args.get("format") == "html":
html = f"""
<html>
<head>
<title>Lookup: {escape(identifier_value)}</title>
<style>
body {{ font-family: sans-serif; margin: 40px; }}
table {{ border-collapse: collapse; width: 80%; }}
td, th {{ border: 1px solid #ddd; padding: 8px; }}
th {{ background-color: #f4f4f4; }}
</style>
</head>
<body>
<h2>Object Lookup</h2>
<p><strong>Internal UUID:</strong> {escape(obj.uuid)}</p>
<p><strong>Primary ID:</strong> {escape(obj.primary_id)}</p>
<table>
<tr><th>Identifier Type</th><th>Value</th></tr>
{''.join(html_rows)}
</table>
</body>
</html>
"""
return html
return jsonify({
"uuid": str(obj.uuid),
"primary_id": obj.primary_id,
"object_type": obj.type.name if obj.type else None,
"identifiers": all_ids
})
# ------------------------------------------------------------
# NEW: LUNA DETAIL → ARCH
# ------------------------------------------------------------
@app.route("/luna/servlet/detail/<identifier>")
def luna_detail(identifier):
ident = Identifier.query.filter_by(id=identifier).first()
if not ident:
abort(404)
obj = (
Object.query
.options(joinedload(Object.identifiers).joinedload(Identifier.type))
.filter_by(id=ident.object_id)
.first()
)
if not obj:
abort(404)
arch_ident = next((i for i in obj.identifiers if i.type.shortcode == "arch"), None)
if not arch_ident:
abort(404)
arch_url = construct_url(arch_ident.type.url_construct, arch_ident.id)
return redirect(arch_url, code=302)
# ------------------------------------------------------------
# NEW: LUNA IIIF → CANTALOUPE
# ------------------------------------------------------------
@app.route("/luna/servlet/iiif/<identifier>/<path:iiif_params>")
def luna_iiif(identifier, iiif_params):
ident = Identifier.query.filter_by(id=identifier).first()
if not ident:
abort(404)
obj = (
Object.query
.options(joinedload(Object.identifiers).joinedload(Identifier.type))
.filter_by(id=ident.object_id)
.first()
)
if not obj:
abort(404)
cant_ident = next((i for i in obj.identifiers if i.type.shortcode == "cantaloupe"), None)
if not cant_ident:
abort(404)
# Base URL from DB is ".../<id>/full/600,/0/default.jpg"
cant_url = construct_url(cant_ident.type.url_construct, cant_ident.id)
# Trim everything after the identifier
cant_url = cant_url.rsplit("/", 4)[0]
final_url = f"{cant_url}/{iiif_params}"
return redirect(final_url, code=302)
# ------------------------------------------------------------
# NEW: Test images.is.ed.ac.uk paths without DNS changes
# ------------------------------------------------------------
@app.route("/images.is.ed.ac.uk/<path:subpath>")
def simulate_images_host(subpath):
return redirect(f"/{subpath}", code=302)
# ------------------------------------------------------------
# ARK RESOLUTION WITH MULTIPLE FORMATS
# ------------------------------------------------------------
@app.route("/ark:/<naan>/<path:suffix>")
def resolve_ark(naan, suffix):
if naan != NAAN:
abort(404)
full_ark = f"ark:/{naan}/{suffix}"
ident = Identifier.query.filter_by(id=full_ark).first()
if not ident:
abort(404)
obj = (
Object.query
.options(joinedload(Object.identifiers).joinedload(Identifier.type))
.filter_by(id=ident.object_id)
.first()
)
if not obj:
abort(404)
# Determine requested format
fmt = request.args.get("format")
# --- HTML Metadata ---
if fmt == "html":
html_rows = []
for i in obj.identifiers:
url = construct_url(i.type.url_construct, i.id) or i.id
html_rows.append(
f"<tr><td>{escape(i.type.shortcode)}</td>"
f"<td><a href='{escape(url)}'>{escape(i.id)}</a></td></tr>"
)
html = f"""
<html>
<head>
<title>ARK Lookup: {escape(full_ark)}</title>
<style>
body {{ font-family: sans-serif; margin: 40px; }}
table {{ border-collapse: collapse; width: 80%; }}
td, th {{ border: 1px solid #ddd; padding: 8px; }}
th {{ background-color: #f4f4f4; }}
</style>
</head>
<body>
<h2>ARK Lookup</h2>
<p><strong>ARK:</strong> {escape(full_ark)}</p>
<p><strong>Internal UUID:</strong> {escape(str(obj.uuid))}</p>
<p><strong>Primary ID:</strong> {escape(obj.primary_id)}</p>
<table>
<tr><th>Identifier Type</th><th>Value</th></tr>
{''.join(html_rows)}
</table>
</body>
</html>
"""
return html
# --- JSON Metadata ---
elif fmt == "json":
all_ids = {}
for i in obj.identifiers:
url = construct_url(i.type.url_construct, i.id) or i.id
all_ids[i.type.shortcode] = url
return jsonify({
"ark": full_ark,
"uuid": str(obj.uuid),
"primary_id": obj.primary_id,
"object_type": obj.type.name if obj.type else None,
"identifiers": all_ids
})
# --- Future ARK Info endpoint ---
elif fmt == "info":
# Minimal info page per ARK specification
info = {
"ark": full_ark,
"naan": naan,
"policy": "This ARK is maintained by University of Edinburgh Digital Collections.",
"target": construct_url(
next((i.type.url_construct for i in obj.identifiers if i.type.shortcode=="arch"), None),
next((i.id for i in obj.identifiers if i.type.shortcode=="arch"), None)
)
}
return jsonify(info)
# --- Default: redirect to canonical detail page ---
arch_ident = next((i for i in obj.identifiers if i.type.shortcode == "arch"), None)
if not arch_ident:
abort(404)
arch_url = construct_url(arch_ident.type.url_construct, arch_ident.id)
return redirect(arch_url, code=302)
# ------------------------------------------------------------
# MAIN
# ------------------------------------------------------------
if __name__ == '__main__':
with app.app_context():
db.create_all()
init_identifier_types()
app.run(debug=True)