forked from thewheat/brunei_bus_routes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1922 lines (1678 loc) · 71.2 KB
/
Copy pathapp.py
File metadata and controls
1922 lines (1678 loc) · 71.2 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
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import (
Flask, render_template, send_from_directory, jsonify, json, request, Response,
url_for, session, redirect,
)
import csv
import datetime
import io
import os
import re
import math
import zipfile
import xml.etree.ElementTree as ET
from xml.sax.saxutils import escape as _xml_escape
import db
import gtfs
import planner
import ratelimit
import auth
# Prefer defusedxml to guard against XXE / entity-expansion attacks; fall back
# to the stdlib parser (our KML files are trusted, shipped-in-repo assets).
try:
from defusedxml.ElementTree import parse as _xml_parse
except ImportError:
_xml_parse = ET.parse
app = Flask(
__name__,
static_folder="static",
template_folder="templates",
)
# On Replit (and most PaaS) the app sits behind one reverse proxy, so the real
# client IP arrives in X-Forwarded-For. Trust exactly one hop so request.remote_addr
# reflects the client — rate limiting keys on it. Locally there's no such header,
# so remote_addr stays the loopback address. See ratelimit.py.
from werkzeug.middleware.proxy_fix import ProxyFix # noqa: E402
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)
# Signed-cookie sessions back the editor login (see auth.py). SECRET_KEY must be
# set in production so the cookie validates across gunicorn workers and autoscale
# instances (same rationale as DATABASE_URL); the random fallback is dev-only and
# resets sessions on restart. SameSite=Lax is the CSRF baseline — the cookie isn't
# sent on cross-site POST/DELETE/fetch — and the write endpoints already require
# JSON. Secure is on only when SECRET_KEY is set, so local http login still works.
app.secret_key = os.environ.get("SECRET_KEY") or os.urandom(32)
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
SESSION_COOKIE_SECURE=bool(os.environ.get("SECRET_KEY")),
PERMANENT_SESSION_LIFETIME=datetime.timedelta(days=14),
# Cap request bodies so an oversized stop-photo upload is rejected (413) before
# it reaches our code. Every other endpoint takes small JSON, so this is safe.
MAX_CONTENT_LENGTH=6 * 1024 * 1024,
)
# The route data is segregated by year so new datasets live alongside the repo
# owner's original 2016 set (under sibling folders, e.g. data/2026). DATA_YEAR is
# the default; clients may request a specific year via the ?year= query param.
DATA_YEAR = "2016"
# Users may create brand-new routes only for this dataset year. New routes have
# no shipped file — they live entirely in the edits DB.
USER_ROUTE_YEAR = "2026"
# GTFS export. The Brunei data has real geometry + named stops but no timetables,
# so the feed is frequency-based with synthetic stop times (see gtfs.py). The
# single agency is a documented placeholder: ~5 operators are suspected but only
# ADBS is on record (docs/2016/reference/notes.txt). Route -> operator mapping is
# unknown, so every route references this one agency for now.
GTFS_AGENCY = {
"id": "ADBS",
"name": "ADBS Sdn Bhd",
"url": "https://www.jpd.gov.bn/",
"timezone": "Asia/Brunei",
"lang": "ms",
"phone": "+673 239 0241",
"email": "",
}
# Feed-wide schedule defaults. Headway/window are nominal placeholders until real
# values are transcribed from the JPD timing signboards. Calendar validity is a
# fixed window (kept deterministic — no wall-clock dependency).
GTFS_PARAMS = {
"headway_secs": 1800, # 30 min
"start_time": "06:00:00",
"end_time": "20:00:00",
"service_id": "DAILY",
"days": [1, 1, 1, 1, 1, 1, 1], # Mon..Sun
"start_date": "20160101",
"end_date": "20261231",
"feed_version": "2016.1",
"publisher_name": "Brunei Bus Routes project",
"publisher_url": "https://github.com/danialothman/brunei_bus_routes",
"feed_lang": "ms",
}
# Route edits live in a versioned DB, so the shipped route files are never
# modified. Backend is chosen at runtime (see db.py): Postgres when DATABASE_URL
# is set (e.g. Replit's managed Postgres, which survives redeploys), otherwise a
# local SQLite file under Flask's instance folder (gitignored). Init at import
# time so it runs under `flask run`, `python app.py`, and gunicorn alike.
os.makedirs(app.instance_path, exist_ok=True)
db.init_db(db_path=os.path.join(app.instance_path, "edits.db"))
@app.context_processor
def _asset_version():
"""Cache-buster for our own static assets: templates append ?v={{ asset_v }}
so browsers re-fetch JS/CSS whenever any of it changes on disk."""
latest = 0
for sub in ("js", "css"):
base = os.path.join(app.static_folder, sub)
for root, _dirs, files in os.walk(base):
for f in files:
try:
latest = max(latest, int(os.path.getmtime(os.path.join(root, f))))
except OSError:
continue
return {"asset_v": latest}
def _available_years():
"""Year folders under static/data that hold a routes.json (sorted)."""
base = os.path.join(app.static_folder, "data")
years = []
if os.path.isdir(base):
for name in os.listdir(base):
if re.fullmatch(r"\d{4}", name) and os.path.exists(
os.path.join(base, name, "routes.json")
):
years.append(name)
return sorted(years)
def _resolve_year(year):
"""Validate a requested year (4 digits + existing folder), else DATA_YEAR."""
if year and re.fullmatch(r"\d{4}", year) and os.path.isdir(
os.path.join(app.static_folder, "data", year)
):
return year
return DATA_YEAR
def _find_kml(filename, year=None):
"""Locate a KML file: static/data/<year>/kml first, then top-level data/<year>/kml."""
# Reject path traversal / absolute paths — only serve plain KML filenames.
if os.path.isabs(filename) or ".." in filename.replace("\\", "/").split("/"):
return None
year = _resolve_year(year)
static_kml = os.path.join(app.static_folder, "data", year, "kml", filename)
if os.path.exists(static_kml):
return static_kml
data_kml = os.path.join("data", year, "kml", filename)
if os.path.exists(data_kml):
return data_kml
return None
def _find_geojson(filename, year=None):
"""Locate a GeoJSON file under the chosen year (static first, then data/)."""
if os.path.isabs(filename) or ".." in filename.replace("\\", "/").split("/"):
return None
year = _resolve_year(year)
static_gj = os.path.join(app.static_folder, "data", year, "geojson", filename)
if os.path.exists(static_gj):
return static_gj
data_gj = os.path.join("data", year, "geojson", filename)
if os.path.exists(data_gj):
return data_gj
return None
# Official JPD stop-list signboards live under docs/<year>/images/stops/ (outside
# static/, so they need their own serving route). Resolved from this file's dir so
# the working directory doesn't matter.
DOCS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "docs")
def _stop_images_dir(year):
return os.path.join(DOCS_DIR, year, "images", "stops")
def _route_from_image(filename):
"""Derive a route label from a signboard filename:
'20 [20150131].jpg' -> '20', '01A.jpg' -> '01A'."""
stem = os.path.splitext(filename)[0]
return re.split(r"\s*\[", stem)[0].strip()
def _find_stop_image(year, filename):
"""Locate a signboard image, rejecting path traversal / bad years."""
if not re.fullmatch(r"\d{4}", year or ""):
return None
if os.path.isabs(filename) or ".." in filename.replace("\\", "/").split("/"):
return None
path = os.path.join(_stop_images_dir(year), filename)
return path if os.path.isfile(path) else None
def _localname(tag):
"""Strip the XML namespace from a tag, e.g. '{ns}LineString' -> 'LineString'."""
return tag.rsplit("}", 1)[-1]
def _parse_coords(text):
"""Parse a KML <coordinates> blob ('lon,lat[,alt] lon,lat[,alt] ...')."""
points = []
for token in text.split():
parts = token.split(",")
if len(parts) < 2:
continue
try:
lon = float(parts[0])
lat = float(parts[1])
except ValueError:
continue
points.append([lon, lat])
return points
def parse_route_geometry(path):
"""Extract drive-path LineStrings and named stop Points from a KML file."""
root = _xml_parse(path).getroot()
segments = []
stops = []
for elem in root.iter():
name = _localname(elem.tag)
if name == "LineString":
for child in elem:
if _localname(child.tag) == "coordinates" and child.text:
pts = _parse_coords(child.text)
if len(pts) >= 2:
segments.append(pts)
elif name == "Placemark":
stop_name = None
point = None
for child in elem.iter():
cname = _localname(child.tag)
if cname == "name" and child.text and stop_name is None:
stop_name = child.text.strip()
elif cname == "Point":
for pc in child:
if _localname(pc.tag) == "coordinates" and pc.text:
coords = _parse_coords(pc.text)
if coords:
point = coords[0]
if point:
stops.append({"name": stop_name or "", "lon": point[0], "lat": point[1]})
# Bounds across all path vertices (fall back to stops if no segments).
all_points = [pt for seg in segments for pt in seg]
if not all_points:
all_points = [[s["lon"], s["lat"]] for s in stops]
bounds = None
if all_points:
lons = [p[0] for p in all_points]
lats = [p[1] for p in all_points]
bounds = {
"minLon": min(lons),
"minLat": min(lats),
"maxLon": max(lons),
"maxLat": max(lats),
}
return {"segments": segments, "stops": stops, "bounds": bounds}
def parse_geojson_geometry(path):
"""Extract LineString drive paths from a GeoJSON file (no named stops)."""
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
segments = []
def add_line(coords):
pts = []
for c in coords or []:
if isinstance(c, (list, tuple)) and len(c) >= 2:
try:
pts.append([float(c[0]), float(c[1])])
except (TypeError, ValueError):
continue
if len(pts) >= 2:
segments.append(pts)
def handle_geom(geom):
if not isinstance(geom, dict):
return
gtype = geom.get("type")
coords = geom.get("coordinates")
if gtype == "LineString":
add_line(coords)
elif gtype == "MultiLineString":
for line in coords or []:
add_line(line)
elif gtype == "GeometryCollection":
for g in geom.get("geometries", []):
handle_geom(g)
if isinstance(data, dict) and data.get("type") == "FeatureCollection":
for feat in data.get("features", []):
handle_geom((feat or {}).get("geometry"))
elif isinstance(data, dict) and data.get("type") == "Feature":
handle_geom(data.get("geometry"))
elif isinstance(data, dict):
handle_geom(data) # bare geometry
all_points = [pt for seg in segments for pt in seg]
bounds = None
if all_points:
lons = [p[0] for p in all_points]
lats = [p[1] for p in all_points]
bounds = {
"minLon": min(lons),
"minLat": min(lats),
"maxLon": max(lons),
"maxLat": max(lats),
}
return {"segments": segments, "stops": [], "bounds": bounds}
# --- Editing: canonical geometry helpers -------------------------------------
def _bounds(segments, stops):
"""Bounding box over all path vertices (falling back to stop points)."""
pts = [p for seg in segments for p in seg]
if not pts:
pts = [[s["lon"], s["lat"]] for s in stops]
if not pts:
return None
lons = [p[0] for p in pts]
lats = [p[1] for p in pts]
return {"minLon": min(lons), "minLat": min(lats),
"maxLon": max(lons), "maxLat": max(lats)}
def _validate_geometry(payload):
"""Validate an edit payload. Returns (geometry_dict, error_str)."""
if not isinstance(payload, dict):
return None, "body must be a JSON object"
segments_in = payload.get("segments", [])
stops_in = payload.get("stops", [])
if not isinstance(segments_in, list) or not isinstance(stops_in, list):
return None, "segments and stops must be arrays"
def num(v):
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
segments = []
total = 0
for seg in segments_in:
if not isinstance(seg, list) or len(seg) < 2:
return None, "each segment needs at least 2 points"
pts = []
for c in seg:
if (not isinstance(c, (list, tuple)) or len(c) < 2
or not num(c[0]) or not num(c[1])):
return None, "coordinates must be [lon, lat] numbers"
lon, lat = float(c[0]), float(c[1])
if not (-180 <= lon <= 180 and -90 <= lat <= 90):
return None, "coordinates out of range"
pts.append([round(lon, 7), round(lat, 7)])
total += len(pts)
segments.append(pts)
if not segments:
return None, "a route needs at least one segment"
if total > 100000:
return None, "too many vertices"
stops = []
for s in stops_in:
if not isinstance(s, dict) or not num(s.get("lon")) or not num(s.get("lat")):
return None, "each stop needs numeric lon/lat"
lon, lat = float(s["lon"]), float(s["lat"])
if not (-180 <= lon <= 180 and -90 <= lat <= 90):
return None, "stop coordinates out of range"
name = s.get("name", "")
if not isinstance(name, str):
return None, "stop name must be a string"
stop = {"name": name[:200], "lon": round(lon, 7), "lat": round(lat, 7)}
code = s.get("code", "")
if not isinstance(code, str):
return None, "stop code must be a string"
if code.strip(): # public stop number (GTFS stop_code)
stop["code"] = code.strip()[:30]
stops.append(stop)
label = payload.get("label")
if label is not None and not isinstance(label, str):
return None, "label must be a string"
name = payload.get("name")
if name is not None and not isinstance(name, str):
return None, "name must be a string"
geom = {"segments": segments, "stops": stops}
if name and name.strip():
geom["name"] = name.strip()[:200]
return geom, None
def geometry_to_kml(geom, name):
"""Synthesize minimal KML from canonical geometry (re-readable by our parser)."""
title = geom.get("name") or name or ""
parts = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<kml xmlns="http://www.opengis.net/kml/2.2"><Document>',
f"<name>{_xml_escape(title)}</name>",
]
for seg in geom.get("segments", []):
coords = " ".join(f"{lon},{lat},0" for lon, lat in seg)
parts.append(
f"<Placemark><LineString><coordinates>{coords}</coordinates>"
"</LineString></Placemark>"
)
for s in geom.get("stops", []):
parts.append(
f"<Placemark><name>{_xml_escape(s.get('name') or '')}</name>"
f"<Point><coordinates>{s['lon']},{s['lat']},0</coordinates>"
"</Point></Placemark>"
)
parts.append("</Document></kml>")
return "".join(parts)
def geometry_to_geojson(geom):
"""Synthesize a path-only GeoJSON FeatureCollection (one LineString per segment)."""
features = [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [[lon, lat] for lon, lat in seg],
},
}
for seg in geom.get("segments", [])
]
return {"type": "FeatureCollection", "features": features}
# --- GTFS export -------------------------------------------------------------
# "Points - *" KML layers are marker overlays (feeder stops, mosques, proposed
# interchanges), not bus services with a drive path — excluded from the feed.
_GTFS_SKIP = re.compile(r"^points\s*-", re.IGNORECASE)
def _gtfs_route_meta(filename):
"""(route_id, short_name, long_name) from a KML filename.
Pulls a leading route code (e.g. 'Muara 01' -> '01') into short_name."""
stem = os.path.splitext(os.path.basename(filename))[0]
route_id = re.sub(r"\s+", "-", stem.strip())
m = re.search(r"(\d+[A-Za-z]?)\s*$", stem)
short = m.group(1) if m else ""
return route_id, short, stem
def gather_gtfs_routes(year):
"""Collect this year's KML routes as gtfs.build_feed inputs, preferring an
edited geometry from the DB over the shipped file. Skips marker-only layers
and routes with no stops (a frequency-based feed needs stops to time).
Per-route GTFS metadata saved via the editor (names, color, schedule)
overrides the derived defaults."""
rp = os.path.join(app.static_folder, "data", year, "routes.json")
if not os.path.exists(rp):
return []
with open(rp, "r") as f:
filenames = json.load(f)
meta_by_file = db.all_gtfs_meta(year)
routes = []
def add(filename, geom):
if not geom or len(geom.get("stops") or []) < 2:
return # a valid trip needs at least 2 stops to time against
route_id, short, long_name = _gtfs_route_meta(filename)
meta = meta_by_file.get(filename, {})
routes.append({
"route_id": route_id,
"short_name": meta.get("short_name") or short,
"long_name": meta.get("long_name") or geom.get("name") or long_name,
"color": meta.get("color", ""),
"agency_id": meta.get("agency_id", ""),
"direction": meta.get("direction", ""),
"headsign": meta.get("headsign", ""),
"return_headsign": meta.get("return_headsign", ""),
"desc": meta.get("desc", ""),
"hail": bool(meta.get("hail")),
"schedules": meta.get("schedules")
or ([meta["schedule"]] if meta.get("schedule") else None),
"segments": geom.get("segments", []),
"stops": geom.get("stops", []),
})
for filename in filenames:
if _GTFS_SKIP.match(os.path.basename(filename)):
continue
geom = db.latest_geometry(year, filename)
if geom is None:
path = _find_kml(filename, year)
if not path:
continue
try:
geom = parse_route_geometry(path)
except (ValueError, ET.ParseError):
continue
add(filename, geom)
# User-created routes (DB-only, no shipped file) belong in the feed too —
# the workbench flow is draw -> schedule -> export.
user_files = sorted(
f for f in db.distinct_files(year)
if not _find_kml(f, year) and not _find_geojson(f, year)
)
for filename in user_files:
add(filename, db.latest_geometry(year, filename))
return routes
_TIME_RE = re.compile(r"^(\d{1,2}):([0-5]\d)(?::([0-5]\d))?$")
def _norm_time(t):
"""Normalize 'H:MM[:SS]' to 'HH:MM:SS', or None if invalid. GTFS allows
hours past 24 for service spanning midnight."""
m = _TIME_RE.match((t or "").strip())
if not m:
return None
h, mi, s = int(m.group(1)), m.group(2), m.group(3) or "00"
if h > 47:
return None
return f"{h:02d}:{mi}:{s}"
def _validate_gtfs_route_meta(payload):
"""Validate a per-route GTFS metadata payload. Returns (meta, error)."""
if not isinstance(payload, dict):
return None, "meta must be a JSON object"
meta = {}
for field in ("short_name", "long_name"):
v = payload.get(field)
if v is not None:
if not isinstance(v, str):
return None, f"{field} must be a string"
if v.strip():
meta[field] = v.strip()[:200]
color = payload.get("color")
if color:
if not isinstance(color, str) or not re.fullmatch(
r"#?[0-9A-Fa-f]{6}", color.strip()
):
return None, "color must be a 6-digit hex value"
meta["color"] = color.strip().lstrip("#").upper()
agency_id = payload.get("agency_id")
if agency_id:
if not isinstance(agency_id, str):
return None, "agency_id must be a string"
if agency_id.strip():
meta["agency_id"] = agency_id.strip()[:30]
direction = payload.get("direction")
if direction:
if direction != "outback":
return None, "direction must be 'outback' or omitted (loop/one-way)"
meta["direction"] = "outback"
for field in ("headsign", "return_headsign"):
v = payload.get(field)
if v is not None:
if not isinstance(v, str):
return None, f"{field} must be a string"
if v.strip():
meta[field] = v.strip()[:120]
desc = payload.get("desc")
if desc is not None:
if not isinstance(desc, str):
return None, "desc must be a string"
if desc.strip():
meta["desc"] = desc.strip()[:500]
if payload.get("hail"):
meta["hail"] = True # hail & ride: continuous pickup/drop-off
# Schedules: a list of day-type blocks (weekday/weekend…). The legacy
# single `schedule` key is accepted as one block.
sched_in = payload.get("schedule")
if sched_in:
sched, err = _validate_schedule_block(sched_in)
if err:
return None, err
if sched:
meta["schedule"] = sched
scheds_in = payload.get("schedules")
if scheds_in is not None:
if not isinstance(scheds_in, list) or len(scheds_in) > 7:
return None, "schedules must be a list of blocks (max 7)"
blocks = []
for b in scheds_in:
sched, err = _validate_schedule_block(b)
if err:
return None, err
if sched:
blocks.append(sched)
if blocks:
meta["schedules"] = blocks
return meta, None
def _validate_schedule_block(sched_in):
"""Validate one schedule block. Returns (sched_dict, error)."""
if not isinstance(sched_in, dict):
return None, "schedule must be an object"
sched = {}
hw = sched_in.get("headway_secs")
if hw is not None:
if not isinstance(hw, (int, float)) or isinstance(hw, bool) \
or not (60 <= hw <= 24 * 3600):
return None, "headway_secs must be 60..86400"
sched["headway_secs"] = int(hw)
for field in ("start_time", "end_time"):
v = sched_in.get(field)
if v:
t = _norm_time(v)
if t is None:
return None, f"{field} must be HH:MM or HH:MM:SS"
sched[field] = t
# Time-of-day frequency bands (peak/off-peak): each becomes its own
# frequencies.txt row. The legacy top-level fields above act as band one.
bands_in = sched_in.get("bands")
if bands_in is not None:
if not isinstance(bands_in, list) or len(bands_in) > 10:
return None, "bands must be a list (max 10)"
bands = []
for b in bands_in:
if not isinstance(b, dict):
return None, "each band must be an object"
band = {}
bh = b.get("headway_secs")
if bh is not None:
if not isinstance(bh, (int, float)) or isinstance(bh, bool) \
or not (60 <= bh <= 24 * 3600):
return None, "band headway_secs must be 60..86400"
band["headway_secs"] = int(bh)
for field in ("start_time", "end_time"):
v = b.get(field)
if v:
t = _norm_time(v)
if t is None:
return None, f"band {field} must be HH:MM or HH:MM:SS"
band[field] = t
if band:
bands.append(band)
if bands:
sched["bands"] = bands
days = sched_in.get("days")
if days is not None:
if (not isinstance(days, list) or len(days) != 7
or any(d not in (0, 1, True, False) for d in days)):
return None, "days must be 7 values of 0/1"
sched["days"] = [int(bool(d)) for d in days]
# Exact departure times transcribed from the timing signboard. When
# present the export emits one real trip per departure for this route
# instead of a synthetic frequency entry.
for field in ("departures", "return_departures"):
deps = sched_in.get(field)
if deps is not None:
if not isinstance(deps, list) or len(deps) > 300:
return None, f"{field} must be a list of times (max 300)"
norm = []
for d in deps:
t = _norm_time(d) if isinstance(d, str) else None
if t is None:
return None, f"bad departure time: {str(d)[:20]!r}"
norm.append(t)
if norm:
sched[field] = sorted(set(norm))
run = sched_in.get("run_secs")
if run is not None:
if not isinstance(run, (int, float)) or isinstance(run, bool) \
or not (60 <= run <= 6 * 3600):
return None, "run_secs must be 60..21600"
sched["run_secs"] = int(run)
return sched, None
def _validate_gtfs_feed_config(payload):
"""Validate feed-level config (operators + fare). Returns (config, error)."""
if not isinstance(payload, dict):
return None, "config must be a JSON object"
config = {}
# Operators: a list of agencies; the first is the default for routes
# without an explicit assignment.
agencies_in = payload.get("agencies")
if agencies_in is not None:
if not isinstance(agencies_in, list) or len(agencies_in) > 20:
return None, "agencies must be a list (max 20)"
agencies = []
seen = set()
for a in agencies_in:
if not isinstance(a, dict):
return None, "each operator must be an object"
name = a.get("name")
if not isinstance(name, str) or not name.strip():
continue # blank rows are dropped silently
name = name.strip()[:200]
aid = a.get("id")
if aid is not None and not isinstance(aid, str):
return None, "operator id must be a string"
aid = (aid or "").strip()[:30]
if not aid:
aid = re.sub(r"[^A-Za-z0-9]+", "-", name).strip("-").upper()[:30] or "OP"
if aid in seen:
return None, f"duplicate operator id: {aid}"
seen.add(aid)
entry = {"id": aid, "name": name}
for field in ("url", "phone", "email"):
v = a.get(field)
if v is not None:
if not isinstance(v, str):
return None, f"operator {field} must be a string"
if v.strip():
entry[field] = v.strip()[:300]
agencies.append(entry)
if agencies:
config["agencies"] = agencies
agency_in = payload.get("agency")
if agency_in:
if not isinstance(agency_in, dict):
return None, "agency must be an object"
agency = {}
for field in ("name", "url", "phone", "email"):
v = agency_in.get(field)
if v is not None:
if not isinstance(v, str):
return None, f"agency.{field} must be a string"
if v.strip():
agency[field] = v.strip()[:300]
if agency:
config["agency"] = agency
# Holiday exceptions -> calendar_dates.txt.
holidays_in = payload.get("holidays")
if holidays_in is not None:
if not isinstance(holidays_in, list) or len(holidays_in) > 50:
return None, "holidays must be a list (max 50)"
holidays = []
for h in holidays_in:
if not isinstance(h, dict):
return None, "each holiday must be an object"
date = h.get("date", "")
if not isinstance(date, str):
return None, "holiday date must be a string"
date = date.replace("-", "").strip()
try:
datetime.datetime.strptime(date, "%Y%m%d")
except ValueError:
return None, f"bad holiday date: {date[:12]!r}"
mode = h.get("mode", "none")
if mode not in ("none", "sunday"):
return None, "holiday mode must be 'none' or 'sunday'"
entry = {"date": date, "mode": mode}
name = h.get("name")
if name is not None:
if not isinstance(name, str):
return None, "holiday name must be a string"
if name.strip():
entry["name"] = name.strip()[:100]
holidays.append(entry)
if holidays:
config["holidays"] = sorted(holidays, key=lambda x: x["date"])
fare_in = payload.get("fare")
if fare_in:
if not isinstance(fare_in, dict):
return None, "fare must be an object"
fare = {}
price = fare_in.get("price")
if price is not None and price != "":
try:
price = float(price)
except (TypeError, ValueError):
return None, "fare.price must be a number"
if not (0 <= price <= 1000):
return None, "fare.price out of range"
fare["price"] = price
currency = fare_in.get("currency")
if currency:
if not isinstance(currency, str) or not re.fullmatch(
r"[A-Za-z]{3}", currency.strip()
):
return None, "fare.currency must be a 3-letter code"
fare["currency"] = currency.strip().upper()
if fare:
config["fare"] = fare
return config, None
# --- Hiring: freelance field data-collection applications --------------------
# Districts of Brunei a collector can cover, and how they get around. Kept as
# closed sets so the public form can't store arbitrary values.
APPLICATION_DISTRICTS = ("Brunei-Muara", "Tutong", "Belait", "Temburong")
APPLICATION_TRANSPORT = ("Own vehicle", "Motorcycle", "Public transport", "Other")
# Admin review workflow stages for a submitted application.
APPLICATION_STATUSES = ("New", "Reviewing", "Contacted", "Accepted", "Rejected")
# Hiring-page per-route bounty, editable by admins (stored in the settings table
# under key "bounty"). Amounts are free text (e.g. "15" or "10–20") so ranges are
# allowed; blank amounts render as "confirmed on onboarding" on /join.
BOUNTY_FIELDS = {
"currency": 8,
"per_route": 40,
"payment_note": 500,
}
BOUNTY_DEFAULTS = {
"currency": "BND",
"per_route": "",
"payment_note": (
"Paid after a route passes quality review. We agree the exact rate and "
"payment method with you when you're onboarded."
),
}
def _get_bounty():
"""Current bounty settings merged over the defaults (always a full dict)."""
out = dict(BOUNTY_DEFAULTS)
raw = db.get_setting("bounty")
if raw:
try:
data = json.loads(raw)
except ValueError:
data = {}
if isinstance(data, dict):
for k in BOUNTY_FIELDS:
v = data.get(k)
if isinstance(v, str) and v.strip():
out[k] = v.strip()
return out
def _validate_application(form):
"""Validate a /join application. `form` has name, email, phone, districts
(list), transport, availability, experience, message. Returns (fields, error)
where fields is ready for db.add_application (districts joined to a string)."""
name = (form.get("name") or "").strip()
if not name:
return None, "Please enter your name."
email = (form.get("email") or "").strip()
phone = (form.get("phone") or "").strip()
if not email and not phone:
return None, "Please give an email or a phone number so we can reach you."
if email and "@" not in email:
return None, "That email doesn't look right — check it, or leave it blank."
districts_in = form.get("districts") or []
if isinstance(districts_in, str):
districts_in = [districts_in]
districts = [d for d in districts_in if d in APPLICATION_DISTRICTS]
if len(districts) != len(districts_in):
return None, "Unknown district selected."
transport = (form.get("transport") or "").strip()
if transport and transport not in APPLICATION_TRANSPORT:
return None, "Unknown transport option."
email = email[:200]
phone = phone[:60]
fields = {
"name": name[:120],
"email": email,
"phone": phone,
# Combined contact kept for the legacy column / quick display.
"contact": " · ".join(c for c in (email, phone) if c),
"districts": ", ".join(districts),
"transport": transport[:40],
"availability": (form.get("availability") or "").strip()[:300],
"experience": (form.get("experience") or "").strip()[:1000],
"message": (form.get("message") or "").strip()[:2000],
}
return fields, None
@app.route("/join")
def join_page():
# Public hiring page for freelance field data collectors.
return render_template(
"join.html", submitted=False, error=None, form={},
districts=APPLICATION_DISTRICTS, transport_options=APPLICATION_TRANSPORT,
bounty=_get_bounty(),
)
@app.route("/join", methods=["POST"])
@ratelimit.rate_limited(limits=[(5, 60), (20, 3600)], scope="apply")
def join_apply():
# Plain form POST (public, unauthenticated contact form — no privileged
# session action, so the editor's JSON/CSRF baseline doesn't apply here).
form = {
"name": request.form.get("name", ""),
"email": request.form.get("email", ""),
"phone": request.form.get("phone", ""),
"districts": request.form.getlist("districts"),
"transport": request.form.get("transport", ""),
"availability": request.form.get("availability", ""),
"experience": request.form.get("experience", ""),
"message": request.form.get("message", ""),
}
fields, err = _validate_application(form)
if err:
return render_template(
"join.html", submitted=False, error=err, form=form,
districts=APPLICATION_DISTRICTS, transport_options=APPLICATION_TRANSPORT,
bounty=_get_bounty(),
), 400
db.add_application(fields)
return render_template(
"join.html", submitted=True, error=None, form={},
districts=APPLICATION_DISTRICTS, transport_options=APPLICATION_TRANSPORT,
bounty=_get_bounty(),
)
@app.route("/applications")
@auth.admin_required()
def applications_page():
# Admin view of submitted applications (newest first).
return render_template(
"applications.html",
applications=db.list_applications(),
statuses=APPLICATION_STATUSES,
bounty=_get_bounty(),
is_editor=auth.is_authed(),
)
@app.route("/applications/<int:app_id>", methods=["POST"])
@auth.admin_required(api=True)
@ratelimit.rate_limited()
def update_application(app_id):
# Update an application's review status and/or admin note.
payload = request.get_json(silent=True) or {}
updated = False
if "status" in payload:
status = payload.get("status")
if status not in APPLICATION_STATUSES:
return jsonify({"error": "unknown status"}), 400
if not db.set_application_status(app_id, status):
return jsonify({"error": "application not found"}), 404
updated = True
if "note" in payload:
note = payload.get("note", "")
if not isinstance(note, str):
return jsonify({"error": "note must be a string"}), 400
if not db.set_application_note(app_id, note[:2000]):
return jsonify({"error": "application not found"}), 404
updated = True
if not updated:
return jsonify({"error": "nothing to update"}), 400
return jsonify({"ok": True})
@app.route("/applications/<int:app_id>", methods=["DELETE"])
@auth.admin_required(api=True)
@ratelimit.rate_limited()
def remove_application(app_id):
if not db.delete_application(app_id):
return jsonify({"error": "application not found"}), 404
return jsonify({"ok": True})
@app.route("/applications.csv")
@auth.admin_required()
def applications_csv():
# Download all applications as CSV (authed page download).
cols = ("id", "created_at", "name", "email", "phone", "districts",
"transport", "availability", "experience", "message", "status", "admin_note")
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(cols)
for a in db.list_applications():
writer.writerow([a.get(c, "") for c in cols])
return Response(
buf.getvalue(),
mimetype="text/csv",
headers={"Content-Disposition": 'attachment; filename="applications.csv"'},
)
@app.route("/applications/bounty", methods=["POST"])
@auth.admin_required(api=True)
@ratelimit.rate_limited()