Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
605 lines (522 loc) · 24.5 KB
/
Copy pathapp.py
File metadata and controls
605 lines (522 loc) · 24.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
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
#!/usr/bin/env python3
import json
import os
import re
import secrets
import sqlite3
import urllib.parse
import urllib.request
from contextlib import contextmanager
from functools import wraps
from flask import Flask, jsonify, request, render_template, session, redirect, url_for, abort, send_from_directory
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
DB_FILE = os.path.join(DATA_DIR, 'disc_tracker.db')
KEY_FILE = os.path.join(DATA_DIR, '.secret_key')
app = Flask(__name__)
os.makedirs(DATA_DIR, exist_ok=True)
if os.path.exists(KEY_FILE):
with open(KEY_FILE, 'rb') as f:
app.secret_key = f.read()
else:
key = os.urandom(32)
with open(KEY_FILE, 'wb') as f:
f.write(key)
app.secret_key = key
# ── Database ──────────────────────────────────────────────────────────────────
@contextmanager
def get_db():
# sqlite3.Connection's own context manager only commits/rolls back — it never closes the
# connection, leaving that to CPython's refcounting. Harmless under the old single-threaded
# server, but threaded=True means many connections can be live at once now, so close
# explicitly rather than relying on GC timing.
db = sqlite3.connect(DB_FILE)
db.row_factory = sqlite3.Row
db.execute('PRAGMA foreign_keys = ON')
try:
yield db
db.commit()
except Exception:
db.rollback()
raise
finally:
db.close()
def init_db():
with get_db() as db:
db.executescript('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL
);
CREATE TABLE IF NOT EXISTS discs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
disc_id INTEGER NOT NULL,
mfr TEXT DEFAULT '',
mold TEXT NOT NULL,
plastic TEXT DEFAULT '',
weight TEXT DEFAULT '',
speed REAL DEFAULT 0,
glide REAL DEFAULT 0,
turn REAL DEFAULT 0,
fade REAL DEFAULT 0,
use_desc TEXT DEFAULT '',
thr TEXT DEFAULT '',
notes TEXT DEFAULT '',
sort_order INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS user_meta (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
next_id INTEGER DEFAULT 100,
sort_mode TEXT DEFAULT 'speed-desc'
);
CREATE TABLE IF NOT EXISTS ms_pic_cache (
lookup_key TEXT PRIMARY KEY,
pic TEXT NOT NULL DEFAULT ''
);
''')
# Migrations for columns added after initial deploy
for col, ddl in [
('color', "ALTER TABLE discs ADD COLUMN color TEXT DEFAULT ''"),
('arc_view', "ALTER TABLE user_meta ADD COLUMN arc_view TEXT DEFAULT 'RHBH'"),
('in_bag', "ALTER TABLE discs ADD COLUMN in_bag INTEGER DEFAULT 0"),
# Website-parity track (website-parity-scope.md, Decision 2): same two columns the
# mobile app added in Disc Suggest Phase 1/3 (app/src/db/migrations.ts), same names,
# so /api/data's discs[] is structurally interchangeable with the app's BackupData.discs[].
('stability_adj', "ALTER TABLE discs ADD COLUMN stability_adj REAL DEFAULT 0"),
('role_tag', "ALTER TABLE discs ADD COLUMN role_tag TEXT DEFAULT ''"),
]:
try:
db.execute(ddl)
except Exception:
pass
init_db()
# ── Auth ──────────────────────────────────────────────────────────────────────
def login_required(f):
@wraps(f)
def decorated(*args, **kwargs):
if 'user_id' not in session:
return redirect(url_for('pick'))
return f(*args, **kwargs)
return decorated
def get_csrf_token():
if 'csrf_token' not in session:
session['csrf_token'] = secrets.token_hex(32)
return session['csrf_token']
def check_csrf():
token = request.form.get('_csrf') or request.headers.get('X-CSRF-Token')
if not token or not secrets.compare_digest(token, session.get('csrf_token', '')):
abort(403)
# ── Picker ────────────────────────────────────────────────────────────────────
@app.route('/pick', methods=['GET'])
def pick():
error = session.pop('pick_error', None)
with get_db() as db:
users = db.execute(
'SELECT id, username FROM users ORDER BY username COLLATE NOCASE'
).fetchall()
return render_template('pick.html', users=users, error=error, csrf_token=get_csrf_token())
@app.route('/pick', methods=['POST'])
def pick_post():
check_csrf()
user_id = request.form.get('user_id', type=int)
if not user_id:
return redirect(url_for('pick'))
with get_db() as db:
row = db.execute('SELECT id FROM users WHERE id = ?', (user_id,)).fetchone()
if not row:
return redirect(url_for('pick'))
session['user_id'] = user_id
return redirect(url_for('index'))
@app.route('/add_user', methods=['POST'])
def add_user():
check_csrf()
username = (request.form.get('username') or '').strip()
if not username:
session['pick_error'] = 'Username cannot be empty.'
return redirect(url_for('pick'))
if len(username) > 40:
session['pick_error'] = 'Username must be 40 characters or fewer.'
return redirect(url_for('pick'))
try:
with get_db() as db:
cur = db.execute('INSERT INTO users (username) VALUES (?)', (username,))
user_id = cur.lastrowid
except sqlite3.IntegrityError:
session['pick_error'] = f'"{username}" is already taken.'
return redirect(url_for('pick'))
session['user_id'] = user_id
return redirect(url_for('index'))
@app.route('/delete_user', methods=['POST'])
@login_required
def delete_user():
check_csrf()
user_id = request.form.get('user_id', type=int)
if user_id and user_id == session.get('user_id'):
with get_db() as db:
db.execute('DELETE FROM users WHERE id = ?', (user_id,))
session.clear()
return redirect(url_for('pick'))
@app.route('/switch', methods=['POST'])
def switch():
check_csrf()
session.clear()
return redirect(url_for('pick'))
# ── Tracker ───────────────────────────────────────────────────────────────────
@app.route('/')
@login_required
def index():
with get_db() as db:
row = db.execute(
'SELECT username FROM users WHERE id = ?', (session['user_id'],)
).fetchone()
if not row:
session.clear()
return redirect(url_for('pick'))
return render_template('index.html', username=row['username'], csrf_token=get_csrf_token())
@app.route('/flightshape')
@login_required
def flightshape():
with get_db() as db:
row = db.execute(
'SELECT username FROM users WHERE id = ?', (session['user_id'],)
).fetchone()
if not row:
session.clear()
return redirect(url_for('pick'))
return render_template('flightshape.html', username=row['username'], csrf_token=get_csrf_token(),
archetype_profile=ARCHETYPE_PROFILE)
@app.route('/api/data', methods=['GET'])
@login_required
def get_data():
user_id = session['user_id']
with get_db() as db:
meta = db.execute(
'SELECT next_id, sort_mode, arc_view FROM user_meta WHERE user_id = ?', (user_id,)
).fetchone()
if meta is None:
return jsonify(None), 404
rows = db.execute(
'SELECT disc_id, mfr, mold, plastic, weight, speed, glide, turn, fade, '
'use_desc, thr, notes, color, in_bag, stability_adj, role_tag FROM discs '
'WHERE user_id = ? ORDER BY sort_order',
(user_id,)
).fetchall()
discs = [
{
'id': r['disc_id'], 'mfr': r['mfr'], 'mold': r['mold'],
'plastic': r['plastic'], 'weight': r['weight'],
'speed': r['speed'], 'glide': r['glide'],
'turn': r['turn'], 'fade': r['fade'],
'use': r['use_desc'], 'thr': r['thr'], 'notes': r['notes'],
'color': r['color'] or '',
'inBag': bool(r['in_bag']),
'stabilityAdj': r['stability_adj'] or 0,
'roleTag': r['role_tag'] or '',
}
for r in rows
]
return jsonify({'discs': discs, 'nextId': meta['next_id'], 'sortMode': meta['sort_mode'],
'arcView': meta['arc_view'] or 'RHBH'})
def _to_num(v, cast, default=0):
try:
return cast(v)
except (TypeError, ValueError):
return default
@app.route('/api/data', methods=['POST'])
@login_required
def set_data():
check_csrf()
payload = request.get_json(silent=True)
if payload is None:
abort(400)
user_id = session['user_id']
discs = payload.get('discs', [])
if not isinstance(discs, list):
discs = []
next_id = max(1, min(_to_num(payload.get('nextId'), int, 100), 999_999_999))
sort_mode = payload.get('sortMode', 'speed-desc')
arc_view = payload.get('arcView', 'RHBH')
if arc_view not in ('RHBH', 'RHFH', 'LHBH', 'LHFH'):
arc_view = 'RHBH'
if sort_mode not in ('speed-desc', 'speed-asc', 'name', 'mfr', 'custom'):
sort_mode = 'speed-desc'
with get_db() as db:
db.execute('DELETE FROM discs WHERE user_id = ?', (user_id,))
db.executemany(
'INSERT INTO discs (user_id, disc_id, mfr, mold, plastic, weight, '
'speed, glide, turn, fade, use_desc, thr, notes, color, sort_order, in_bag, '
'stability_adj, role_tag) '
'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[
(user_id, _to_num(d.get('id'), int, 0), str(d.get('mfr') or '')[:80], str(d.get('mold') or '')[:80],
str(d.get('plastic') or '')[:80], str(d.get('weight') or '')[:20],
_to_num(d.get('speed'), float, 0), _to_num(d.get('glide'), float, 0),
_to_num(d.get('turn'), float, 0), _to_num(d.get('fade'), float, 0),
str(d.get('use') or '')[:200], str(d.get('thr') or '')[:10], str(d.get('notes') or '')[:1000],
(c if re.match(r'^#[0-9A-Fa-f]{6}$', c := str(d.get('color') or '')) else ''), i,
1 if d.get('inBag') else 0,
max(-2, min(2, _to_num(d.get('stabilityAdj'), float, 0))),
str(d.get('roleTag') or '')[:200])
for i, d in enumerate(discs)
if isinstance(d, dict) and str(d.get('mold') or '').strip() # skip discs with no mold name
]
)
db.execute(
'INSERT INTO user_meta (user_id, next_id, sort_mode, arc_view) VALUES (?, ?, ?, ?) '
'ON CONFLICT(user_id) DO UPDATE SET '
'next_id = excluded.next_id, sort_mode = excluded.sort_mode, arc_view = excluded.arc_view',
(user_id, next_id, sort_mode, arc_view)
)
return jsonify({'ok': True})
@app.route('/api/arcview', methods=['POST'])
@login_required
def set_arcview():
check_csrf()
payload = request.get_json(silent=True)
if not payload:
abort(400)
view = payload.get('arcView', 'RHBH')
if view not in ('RHBH', 'RHFH', 'LHBH', 'LHFH'):
abort(400)
with get_db() as db:
db.execute(
'INSERT INTO user_meta (user_id, arc_view) VALUES (?, ?) '
'ON CONFLICT(user_id) DO UPDATE SET arc_view = excluded.arc_view',
(session['user_id'], view)
)
return jsonify({'ok': True})
# ── Marshall Street reference images (DiscIt API) ──────────────────────────────
# Optional, read-only, best-effort. Never let a failure here affect the rest of
# the app — any error just means no reference image is shown.
MS_API_BASE = 'https://discit-api.fly.dev/disc'
def _ms_lookup_key(mfr, mold):
return f"{mfr.strip().lower()}|{mold.strip().lower()}"
def fetch_ms_pic(mfr, mold):
mfr, mold = (mfr or '').strip(), (mold or '').strip()
if not mold:
return None
key = _ms_lookup_key(mfr, mold)
with get_db() as db:
row = db.execute(
'SELECT pic FROM ms_pic_cache WHERE lookup_key = ?', (key,)
).fetchone()
if row is not None:
return row['pic'] or None
pic = ''
try:
url = MS_API_BASE + '?' + urllib.parse.urlencode({'name': mold})
with urllib.request.urlopen(url, timeout=2.5) as resp:
results = json.loads(resp.read().decode('utf-8'))
for r in results:
if str(r.get('name', '')).strip().lower() != mold.lower():
continue
brand = str(r.get('brand', '')).strip().lower()
if mfr and mfr.lower() not in brand and brand not in mfr.lower():
continue
if r.get('pic'):
pic = r['pic']
break
except Exception:
pic = ''
with get_db() as db:
db.execute(
'INSERT INTO ms_pic_cache (lookup_key, pic) VALUES (?, ?) '
'ON CONFLICT(lookup_key) DO UPDATE SET pic = excluded.pic',
(key, pic)
)
return pic or None
@app.route('/api/ms_pic', methods=['GET'])
@login_required
def get_ms_pic():
mfr = request.args.get('mfr', '')
mold = request.args.get('mold', '')
pic = fetch_ms_pic(mfr, mold)
return jsonify({'pic': pic})
@app.route('/api/ms_pic_img', methods=['GET'])
@login_required
def get_ms_pic_img():
# Proxies the actual image bytes so the browser only ever loads same-origin
# <img> sources — avoids relaxing the site's img-src CSP to a third-party host.
mfr = request.args.get('mfr', '')
mold = request.args.get('mold', '')
pic = fetch_ms_pic(mfr, mold)
# pic comes from the third-party DiscIt API response, cached verbatim — never fetch it
# server-side unless it's actually an https image URL, so a compromised/misbehaving
# upstream can't turn this proxy into an SSRF vector (file://, internal http hosts, etc).
if not pic or not pic.startswith('https://'):
abort(404)
try:
with urllib.request.urlopen(pic, timeout=4) as resp:
data = resp.read()
ctype = resp.headers.get('Content-Type', 'image/webp')
except Exception:
abort(502)
response = app.response_class(data, mimetype=ctype)
response.headers['Cache-Control'] = 'public, max-age=604800'
return response
# ── shotshaper physics simulation (Flight Shaper "Physics sim" mode) ───────────
# Vendored rigid-body disc flight simulator (vendor/shotshaper/, GPLv3, see NOTICE.md there).
# Only 4 archetypes have wind-tunnel/CFD aero coefficients upstream — no putter or midrange —
# so a slow disc still runs against the nearest driver archetype (see ARCHETYPE_PROFILE)
# as an extrapolation, not a real model of putter/midrange flight. Everything here is
# research/experimental: launch speed and spin are approximated from the PDGA speed number,
# not measured. Mass and wind (including crosswind) use real inputs to the same vendored API.
import threading as _threading
_shotshaper_lock = _threading.Lock()
SHOTSHAPER_ARCHETYPES = {
'fd2': 'Fairway driver',
'cd1': 'Control driver A',
'cd5': 'Control driver B',
'dd2': 'Distance driver',
}
# Empirical characterization, not invented data: each archetype was run once through
# shotshaper's own unmodified DiscGolfDisc.shoot(), using the exact throw parameters from
# upstream's own examples/disc_golf_throw.py (speed=24.2, omega=116.8, pitch=15.5, roll=14.7).
# Reproduce with the throwaway script referenced in the git history for this block if these
# numbers ever need re-deriving. Results (distance, final lateral drift):
# cd1: 61.5m, +25.6m drift (drifts one way the whole flight, never fades back)
# fd2: 65.8m, +29.4m drift (same shape as cd1, shortest distance)
# cd5: 83.0m, -6.5m drift (turns to -12m then fades back partway — mild S-curve)
# dd2: 81.9m, +4.1m drift (turns to -6.3m then fades all the way past center — full S-curve)
# This is used only to pick which of the 4 pre-built vendored discs best matches a real disc's
# recorded flight numbers — it never changes any coefficient inside vendor/shotshaper/.
ARCHETYPE_PROFILE = {
'cd1': {'label': 'Control driver A', 'speed_class': 'control', 'tendency': 'understable',
'char_dist_m': 61.5, 'char_drift_m': 25.6},
'fd2': {'label': 'Fairway driver', 'speed_class': 'fairway', 'tendency': 'understable',
'char_dist_m': 65.8, 'char_drift_m': 29.4},
'cd5': {'label': 'Control driver B', 'speed_class': 'control', 'tendency': 'overstable',
'char_dist_m': 83.0, 'char_drift_m': -6.5},
'dd2': {'label': 'Distance driver', 'speed_class': 'distance', 'tendency': 'overstable',
'char_dist_m': 81.9, 'char_drift_m': 4.1},
}
@app.route('/api/shotshaper_sim', methods=['POST'])
@login_required
def shotshaper_sim():
check_csrf()
try:
import numpy as np
from vendor.shotshaper import environment
from vendor.shotshaper.projectile import DiscGolfDisc
except ImportError:
return jsonify({'error': 'physics sim dependencies not installed'}), 501
data = request.get_json(force=True) or {}
archetype = data.get('archetype', 'dd2')
if archetype not in SHOTSHAPER_ARCHETYPES:
return jsonify({'error': 'unknown archetype'}), 400
pdga_speed = _to_num(data.get('pdgaSpeed'), float, 9)
hyzer = _to_num(data.get('hyzer'), float, 0)
nose = _to_num(data.get('nose'), float, 0)
wind = _to_num(data.get('wind'), float, 0)
crosswind = _to_num(data.get('crosswind'), float, 0)
arm_speed = _to_num(data.get('armSpeed'), float, 100)
spin_pct = _to_num(data.get('spin'), float, 100)
arc_view = data.get('arcView', 'RHBH')
weight_g = data.get('weightG')
mirror = -1 if arc_view in ('RHFH', 'LHBH') else 1
# Calibrated to shotshaper's own dd2 example: PDGA speed ~12 -> ~24.2 m/s launch speed.
base_launch_speed = 6.0 + pdga_speed * 1.3
U = max(4.0, base_launch_speed * (arm_speed / 100.0))
# Real recorded disc weight as sim mass, same input upstream's own disc_gui2d.py exposes
# via a slider (range 0.140-0.200 kg is that slider's own validated range).
try:
mass_kg = float(weight_g) / 1000.0
except (TypeError, ValueError):
mass_kg = 0.175
mass_kg = max(0.140, min(0.200, mass_kg))
with _shotshaper_lock:
disc = DiscGolfDisc(archetype, mass=mass_kg)
omega = max(disc.empirical_spin(U) * (spin_pct / 100.0), 1.0)
# environment module state is process-global; guarded by _shotshaper_lock since the
# dev server is single-threaded anyway, but this keeps it correct if that ever changes.
# headwind (wind>0) opposes +x travel, tailwind (wind<0) aids it; crosswind is the
# y-component of the same 3-axis winddir vector environment.py already exposes.
vx = abs(wind) * 0.45 * (1.0 if wind <= 0 else -1.0)
vy = abs(crosswind) * 0.45 * mirror * (1.0 if crosswind >= 0 else -1.0)
environment.Uref = (vx ** 2 + vy ** 2) ** 0.5
norm = environment.Uref or 1.0
environment.winddir = np.array((vx / norm, vy / norm, 0.0))
try:
shot = disc.shoot(
speed=U, omega=omega, pitch=15.0,
position=np.array((0.0, 0.0, 1.3)),
nose_angle=nose, roll_angle=mirror * hyzer,
)
except Exception as e:
return jsonify({'error': str(e)}), 500
finally:
environment.Uref = 0.0
x, y, _z = shot.position
points = [[round(float(px), 2), round(float(py), 2)] for px, py in zip(x, y)]
return jsonify({'points': points, 'archetype': archetype})
# ── Master disc library ───────────────────────────────────────────────────────
_master_cache = None
@app.route('/api/master')
@login_required
def get_master():
global _master_cache
if _master_cache is None:
master_path = os.path.join(os.path.dirname(__file__), 'static', 'discs_master.json')
try:
with open(master_path) as f:
_master_cache = f.read()
except (FileNotFoundError, IOError):
return jsonify({'error': 'Master disc library unavailable'}), 500
return app.response_class(_master_cache, mimetype='application/json')
# ── Optional downloaded disc catalog (Try Discs) ───────────────────────────────
#
# catalog-v2-scope.md / vps-catalog-hosting-proposal.md. Serves a maintainer-published catalog
# data pack + manifest to the mobile app's optional "Check for updates" download — the bundled
# library stays the default, this is never required. Deliberately shaped as two fixed-name
# static-file fetches (no query params, no search, no listing) per Try Discs' own terms: publicly
# fetchable by the app, but never a re-served public search API. Nothing here is written by this
# process — files land in CATALOG_DIR only via the separate `tools/trydiscs-sync.js publish` step
# (scp, maintainer-run, never through git). Deliberately NOT @login_required: the mobile app has
# no website session to send.
CATALOG_DIR = os.path.join(DATA_DIR, 'catalog')
@app.route('/catalog/manifest.json')
def get_catalog_manifest():
return send_from_directory(CATALOG_DIR, 'manifest.json', mimetype='application/json')
@app.route('/catalog/<path:asset>')
def get_catalog_asset(asset):
return send_from_directory(CATALOG_DIR, asset, mimetype='application/json')
# ── Website consumer of the same enhanced catalog ──────────────────────────────
#
# Authenticated (this is a logged-in-user feature, same as /api/master), reads straight off
# disk from CATALOG_DIR rather than looping back through the public /catalog/ routes over HTTP —
# same box, same files, no reason to round-trip through the network. Returns 404 (not an error)
# when nothing's been published yet, so the frontend can fall back to /api/master silently.
# catalog-v2-scope.md: this is the "website consumer" that was deliberately deferred until the
# catalog was actually live — see that doc for status.
_catalog_cache = None
@app.route('/api/catalog')
@login_required
def get_catalog():
global _catalog_cache
if _catalog_cache is None:
try:
with open(os.path.join(CATALOG_DIR, 'manifest.json')) as f:
manifest = json.load(f)
with open(os.path.join(CATALOG_DIR, manifest['asset'])) as f:
_catalog_cache = f.read()
except (FileNotFoundError, IOError, KeyError, ValueError):
return jsonify({'error': 'Enhanced catalog not available'}), 404
return app.response_class(_catalog_cache, mimetype='application/json')
@app.route('/discsuggestion')
@login_required
def discsuggestion():
with get_db() as db:
row = db.execute(
'SELECT username FROM users WHERE id = ?', (session['user_id'],)
).fetchone()
if not row:
session.clear()
return redirect(url_for('pick'))
return render_template('discsuggestion.html', username=row['username'], csrf_token=get_csrf_token())
# ── Entry point ───────────────────────────────────────────────────────────────
if __name__ == '__main__':
# threaded=True so a slow upstream call (e.g. the Marshall Street lookup, up to
# a few seconds on an uncached disc) doesn't block every other user's request —
# shotshaper's process-global environment state is already guarded by
# _shotshaper_lock for exactly this case.
app.run(host='127.0.0.1', port=5757, debug=False, threaded=True)