Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 472e2eac45 | |||
| ce42cb3883 | |||
| e80137dfb5 | |||
| a04547c57b | |||
| 80e48333be | |||
| b5577d57cd | |||
| af9c1bc8ff | |||
| febfe374ed | |||
| c4088df999 | |||
| b1dff396d9 | |||
| 992f7f90a7 | |||
| 360fc6b4be | |||
| a8008c37b4 | |||
| 228e52b9a4 | |||
| 59bccd5ca8 | |||
| 03a5a405f3 | |||
| e3bc69f0f8 | |||
| d1213f68dd | |||
| 742c817d39 | |||
| c888b1995e | |||
| 5f681ae589 | |||
| 9b9cf0d400 | |||
| 2a5d1d504e | |||
| e22f523f2c | |||
| 71b1dc3532 | |||
| 6d63a736cd | |||
| 1676c774bd | |||
| b947b94202 | |||
| 2cf518b903 | |||
| 1c019b6c08 | |||
| bd9db790cb | |||
| d7e475e41a | |||
| 90c76418db | |||
| 4386421459 | |||
| 72c3831eb4 | |||
| 141d97b329 | |||
| 0e163cab8b | |||
| 19cd7eafd9 | |||
| e70952dba6 | |||
| a632775da9 | |||
| 24911e2ec0 |
@ -121,7 +121,7 @@ def search_page(request):
|
||||
- AND across tokens, OR across the selected fields
|
||||
|
||||
Special power term:
|
||||
- 'invalidscripture' -> entries whose Scripture would show red (invalid)
|
||||
- 'invalidscripture' -> entries whose Scripture would be INVALID per the JS validator
|
||||
"""
|
||||
default_fields = {
|
||||
"subject": True,
|
||||
@ -147,25 +147,134 @@ def search_page(request):
|
||||
|
||||
q = (request.GET.get("q") or "").strip()
|
||||
if q:
|
||||
# ===== SPECIAL POWER TERM =====
|
||||
# ===== SPECIAL POWER TERM (JS-compatible scripture validation) =====
|
||||
if q.lower() == "invalidscripture":
|
||||
# A simple server-side validity check that mirrors the front-end idea:
|
||||
# each piece must look like "<book> <chapter[:verses...]>"
|
||||
book_ch_re = re.compile(r"^.+?\s+\d{1,3}(?::\s*.+)?$")
|
||||
import re
|
||||
|
||||
# --- JS validator port (same logic as ScriptureValidator.isValidSingleRef) ---
|
||||
FULL_TO_CODE = {
|
||||
# OT
|
||||
"genesis":"Ge","exodus":"Ex","leviticus":"Le","numbers":"Nu","deuteronomy":"De",
|
||||
"joshua":"Jos","judges":"Jg","ruth":"Ru",
|
||||
"1 samuel":"1Sa","2 samuel":"2Sa","1 kings":"1Ki","2 kings":"2Ki",
|
||||
"1 chronicles":"1Ch","2 chronicles":"2Ch",
|
||||
"ezra":"Ezr","nehemiah":"Ne","esther":"Es","job":"Job","psalms":"Ps","psalm":"Ps",
|
||||
"proverbs":"Pr","ecclesiastes":"Ec","song of solomon":"Ca","song of songs":"Ca",
|
||||
"isaiah":"Isa","jeremiah":"Jer","lamentations":"La","ezekiel":"Eze","daniel":"Da",
|
||||
"hosea":"Ho","joel":"Joe","amos":"Am","obadiah":"Ob","jonah":"Jon","micah":"Mic",
|
||||
"nahum":"Na","habakkuk":"Hab","zephaniah":"Zep","haggai":"Hag","zechariah":"Zec","malachi":"Mal",
|
||||
# NT
|
||||
"matthew":"Mt","mark":"Mr","luke":"Lu","john":"Joh","acts":"Ac","romans":"Ro",
|
||||
"1 corinthians":"1Co","2 corinthians":"2Co",
|
||||
"galatians":"Ga","ephesians":"Eph","philippians":"Php","colossians":"Col",
|
||||
"1 thessalonians":"1Th","2 thessalonians":"2Th",
|
||||
"1 timothy":"1Ti","2 timothy":"2Ti",
|
||||
"titus":"Tit","philemon":"Phm","hebrews":"Heb","james":"Jas",
|
||||
"1 peter":"1Pe","2 peter":"2Pe",
|
||||
"1 john":"1Jo","2 john":"2Jo","3 john":"3Jo",
|
||||
"jude":"Jude","revelation":"Re",
|
||||
}
|
||||
ALIAS_TO_CODE = {
|
||||
# OT
|
||||
"gen":"Ge","exod":"Ex","lev":"Le","num":"Nu","deut":"De",
|
||||
"josh":"Jos","judg":"Jg","ps":"Ps","prov":"Pr","eccl":"Ec","song":"Ca","cant":"Ca",
|
||||
"isa":"Isa","jer":"Jer","lam":"La","ezek":"Eze","dan":"Da","hos":"Ho","joel":"Joe",
|
||||
"amos":"Am","obad":"Ob","jon":"Jon","mic":"Mic","nah":"Na","hab":"Hab","zeph":"Zep",
|
||||
"hag":"Hag","zech":"Zec","mal":"Mal",
|
||||
# NT
|
||||
"matt":"Mt","mark":"Mr","luke":"Lu","john":"Joh","acts":"Ac","rom":"Ro",
|
||||
"gal":"Ga","eph":"Eph","phil":"Php","col":"Col","heb":"Heb","jas":"Jas",
|
||||
"jude":"Jude","rev":"Re",
|
||||
}
|
||||
CODE_TO_NUM = {
|
||||
# OT
|
||||
"Ge":1,"Ex":2,"Le":3,"Nu":4,"De":5,"Jos":6,"Jg":7,"Ru":8,"1Sa":9,"2Sa":10,
|
||||
"1Ki":11,"2Ki":12,"1Ch":13,"2Ch":14,"Ezr":15,"Ne":16,"Es":17,"Job":18,
|
||||
"Ps":19,"Pr":20,"Ec":21,"Ca":22,"Isa":23,"Jer":24,"La":25,"Eze":26,"Da":27,"Ho":28,
|
||||
"Joe":29,"Am":30,"Ob":31,"Jon":32,"Mic":33,"Na":34,"Hab":35,"Zep":36,"Hag":37,"Zec":38,"Mal":39,
|
||||
# NT
|
||||
"Mt":40,"Mr":41,"Lu":42,"Joh":43,"Ac":44,"Ro":45,"1Co":46,"2Co":47,"Ga":48,"Eph":49,
|
||||
"Php":50,"Col":51,"1Th":52,"2Th":53,"1Ti":54,"2Ti":55,"Tit":56,"Phm":57,
|
||||
"Heb":58,"Jas":59,"1Pe":60,"2Pe":61,"1Jo":62,"2Jo":63,"3Jo":64,"Jude":65,"Re":66,
|
||||
}
|
||||
SERIES = [
|
||||
{"prefixes":["sam","samu","samuel"], "codes":{1:"1Sa",2:"2Sa"}},
|
||||
{"prefixes":["ki","king","kings","kgs"], "codes":{1:"1Ki",2:"2Ki"}},
|
||||
{"prefixes":["chron","chr","ch","chronicles"], "codes":{1:"1Ch",2:"2Ch"}},
|
||||
{"prefixes":["cor","corin","corinth","corinthians","co","c"], "codes":{1:"1Co",2:"2Co"}},
|
||||
{"prefixes":["thes","thess","thessalon","thessalonians","th"], "codes":{1:"1Th",2:"2Th"}},
|
||||
{"prefixes":["tim","ti","timothy","t"], "codes":{1:"1Ti",2:"2Ti"}},
|
||||
{"prefixes":["pet","pe","peter","pt","p"], "codes":{1:"1Pe",2:"2Pe"}},
|
||||
{"prefixes":["jo","jn","joh","john","jno","jhn"], "codes":{1:"1Jo",2:"2Jo",3:"3Jo"}},
|
||||
]
|
||||
WOL_ABBR = set(CODE_TO_NUM.keys())
|
||||
versesRe = re.compile(r"""
|
||||
^
|
||||
(?:
|
||||
(\d{1,3}) # chapter only
|
||||
|
|
||||
(\d{1,3})\s*:\s*
|
||||
(
|
||||
\d{1,3} # v1
|
||||
(?:\s*-\s*(?:\d{1,3}|\d{1,3}:\d{1,3}))? # -v2 OR -ch:vs
|
||||
(?:\s*,\s*\d{1,3}(?:\s*-\s*(?:\d{1,3}|\d{1,3}:\d{1,3}))?)* # ,vN[-…]
|
||||
)
|
||||
)
|
||||
$
|
||||
""", re.VERBOSE)
|
||||
|
||||
def _norm_spaces(s): return re.sub(r"\s+", " ", (s or "").strip())
|
||||
def _strip_dots(s): return re.sub(r"\.+$", "", s or "")
|
||||
def _lower(s): return (s or "").lower()
|
||||
|
||||
def _lookup_book_code(book_raw: str):
|
||||
b = _norm_spaces(_strip_dots(book_raw))
|
||||
# Full names
|
||||
c = FULL_TO_CODE.get(_lower(b))
|
||||
if c: return c
|
||||
# Aliases
|
||||
c = ALIAS_TO_CODE.get(_lower(b))
|
||||
if c: return c
|
||||
# WOL abbr (allow a space after the number, and arbitrary spaces)
|
||||
tightened = re.sub(r"^([1-3])\s+([A-Za-z].*)$", r"\1\2", b)
|
||||
if tightened in WOL_ABBR: return tightened
|
||||
no_space = re.sub(r"\s+", "", b)
|
||||
if no_space in WOL_ABBR: return no_space
|
||||
# Numbered prose (e.g., "2 Sam", "1 Chron", "3 Jo")
|
||||
m = re.match(r"^([1-3])\s*([A-Za-z]+)$", _lower(b))
|
||||
if m:
|
||||
n = int(m.group(1)); base = m.group(2)
|
||||
for fam in SERIES:
|
||||
if any(base.startswith(p) for p in fam["prefixes"]):
|
||||
code = fam["codes"].get(n)
|
||||
if code: return code
|
||||
return None
|
||||
|
||||
def _split_book_and_rest(s: str):
|
||||
m = re.match(r"^(.+?)\s+(\d{1,3}(?:\s*:\s*.*)?)$", s)
|
||||
return {"book": m.group(1), "rest": m.group(2)} if m else None
|
||||
|
||||
def _is_valid_single_ref(ref: str) -> bool:
|
||||
s = (ref or "").strip()
|
||||
if not s: return False
|
||||
parts = _split_book_and_rest(s)
|
||||
if not parts: return False
|
||||
if not _lookup_book_code(parts["book"]): return False
|
||||
rest = (parts.get("rest") or "").trim() if hasattr(str, "trim") else (parts.get("rest") or "").strip()
|
||||
if not rest: return False
|
||||
return bool(versesRe.match(rest))
|
||||
|
||||
def _field_is_valid(text: str) -> bool:
|
||||
pieces = [p.strip() for p in (text or "").split(";") if p.strip()]
|
||||
if not pieces: # empty field considered neutral/invalid? UI treats empty as neither; we exclude empties anyway
|
||||
return False
|
||||
return all(_is_valid_single_ref(p) for p in pieces)
|
||||
# --- end JS port ---
|
||||
|
||||
invalid_ids = []
|
||||
qs_all = Entry.objects.exclude(scripture_raw="").only("id", "scripture_raw", "date_added")
|
||||
for e in qs_all.iterator(chunk_size=1000):
|
||||
original = (e.scripture_raw or "").strip()
|
||||
norm, warns = normalize_scripture_field(original)
|
||||
|
||||
# Split into pieces as the UI does
|
||||
pieces = [p.strip() for p in original.split(";") if p.strip()]
|
||||
# Invalid if:
|
||||
# - normalizer produced warnings (e.g., verses but no book), OR
|
||||
# - any piece fails "<book> <chapter[:verses...]>" quick check
|
||||
any_bad_shape = any(not book_ch_re.match(p) for p in pieces)
|
||||
if warns or any_bad_shape:
|
||||
qs = Entry.objects.exclude(scripture_raw="").only("id", "scripture_raw", "date_added")
|
||||
for e in qs.iterator(chunk_size=1000):
|
||||
if not _field_is_valid(e.scripture_raw or ""):
|
||||
invalid_ids.append(e.id)
|
||||
|
||||
ids = list(
|
||||
@ -183,8 +292,7 @@ def search_page(request):
|
||||
request.session["last_search"] = {"q": q, "fields": ["scripture_raw"]}
|
||||
request.session.modified = True
|
||||
|
||||
count = len(ids)
|
||||
if count:
|
||||
if ids:
|
||||
entry = Entry.objects.get(pk=ids[0])
|
||||
ctx = entry_context(entry, ids)
|
||||
ctx.update({"from_search": True})
|
||||
@ -207,6 +315,7 @@ def search_page(request):
|
||||
)
|
||||
# ===== END SPECIAL TERM =====
|
||||
|
||||
# --- existing search flow ---
|
||||
tokens = terms(q)
|
||||
fields = [f for f, sel in selected.items() if sel] or ["subject"]
|
||||
|
||||
@ -242,11 +351,10 @@ def search_page(request):
|
||||
pass
|
||||
|
||||
request.session["result_ids"] = ids
|
||||
count = len(ids)
|
||||
request.session["last_search"] = {"q": q, "fields": fields}
|
||||
request.session.modified = True
|
||||
|
||||
if count:
|
||||
if ids:
|
||||
entry = Entry.objects.get(pk=ids[0])
|
||||
ctx = entry_context(entry, ids)
|
||||
ctx.update({"from_search": True})
|
||||
@ -1137,4 +1245,51 @@ def set_theme(request):
|
||||
|
||||
request.session["theme"] = theme
|
||||
messages.success(request, f"Theme set to {theme.title()}.")
|
||||
return redirect("settings_home")
|
||||
return redirect("settings_home")
|
||||
|
||||
# web/core/views.py
|
||||
import json
|
||||
import os
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.decorators import login_required, user_passes_test
|
||||
from django.http import JsonResponse, HttpResponseBadRequest
|
||||
from django.views.decorators.http import require_POST
|
||||
|
||||
@require_POST
|
||||
@login_required
|
||||
@user_passes_test(lambda u: u.is_superuser)
|
||||
def api_update_pub_codes(request):
|
||||
"""
|
||||
Accepts a 'json' field (string) that should parse to {"pub_codes": [..]}.
|
||||
Normalizes, de-duplicates, and writes to web/static/data/wol-pub-codes.v1.json.
|
||||
"""
|
||||
payload = request.POST.get("json") or (request.body.decode("utf-8") if request.body else "")
|
||||
if not payload:
|
||||
return HttpResponseBadRequest("Missing 'json'.")
|
||||
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
except Exception as e:
|
||||
return HttpResponseBadRequest(f"Invalid JSON: {e}")
|
||||
|
||||
if not isinstance(data, dict) or "pub_codes" not in data or not isinstance(data["pub_codes"], list):
|
||||
return HttpResponseBadRequest('JSON must be an object with a "pub_codes" array.')
|
||||
|
||||
# Normalize to unique, lowercase, trimmed strings
|
||||
seen = set()
|
||||
codes = []
|
||||
for c in data["pub_codes"]:
|
||||
s = str(c or "").strip().lower()
|
||||
if s and s not in seen:
|
||||
seen.add(s)
|
||||
codes.append(s)
|
||||
|
||||
# Write back to static data file
|
||||
target_path = os.path.join(settings.BASE_DIR, "web", "static", "data", "wol-pub-codes.v1.json")
|
||||
try:
|
||||
with open(target_path, "w", encoding="utf-8") as f:
|
||||
json.dump({"pub_codes": codes}, f, ensure_ascii=False, indent=2)
|
||||
except Exception as e:
|
||||
return HttpResponseBadRequest(f"Could not write file: {e}")
|
||||
|
||||
return JsonResponse({"ok": True, "count": len(codes)})
|
||||
@ -1,6 +1,6 @@
|
||||
# illustrations/urls.py
|
||||
from django.contrib import admin
|
||||
from django.urls import path, re_path
|
||||
from django.urls import path, re_path, include
|
||||
from django.contrib.auth import views as auth_views
|
||||
from django.views.generic import TemplateView # NEW: for manifest / service worker / offline
|
||||
|
||||
@ -54,6 +54,7 @@ urlpatterns = [
|
||||
path("api/get-recent-views/", feat_views.api_get_recent_views, name="api_get_recent_views"),
|
||||
path("settings/", core_views.settings_home, name="settings_home"),
|
||||
path("settings/theme/", core_views.set_theme, name="set_theme"), # ✅ FIXED
|
||||
path("api/update-pub-codes/", core_views.api_update_pub_codes, name="api_update_pub_codes"),
|
||||
|
||||
# --- NEW (PWA) ---
|
||||
re_path(
|
||||
|
||||
10
web/static/data/wol-pub-codes.v1.json
Normal file
10
web/static/data/wol-pub-codes.v1.json
Normal file
@ -0,0 +1,10 @@
|
||||
{
|
||||
"pub_codes": [
|
||||
"wp", "ws", "yb", "mwb", "w", "g",
|
||||
"ap", "apf", "be", "bh", "br", "bt", "btg", "cf", "cl", "ct", "dp",
|
||||
"fg", "fy", "gt", "hb", "im", "ip", "it", "jv", "ka", "kj", "kl",
|
||||
"lf", "lff", "ll", "ly", "my", "od", "pe", "po", "pt", "rr", "rs",
|
||||
"sg", "sh", "si", "td", "tp", "tr", "ts", "un", "jy",
|
||||
"uw", "su", "re", "lvs", "lp", "yy", "yp2", "yp", "sl", "pm", "kc", "jd", "jr", "ia", "hs", "ia", "hs", "lv", "kr", "km", "wcg", "bw", "ce", "ad"
|
||||
]
|
||||
}
|
||||
@ -1,22 +1,47 @@
|
||||
/* source-validator.v1.js
|
||||
Centralizes logic for deciding if a "Source" string should link to WOL.
|
||||
Loads publication codes from /static/data/wol-pub-codes.v1.json.
|
||||
|
||||
Exposes:
|
||||
- SourceValidator.isWOLSource(text) -> boolean
|
||||
- SourceValidator.buildWOLSearchURL(text) -> string
|
||||
*/
|
||||
window.SourceValidator = (function () {
|
||||
// Publications / codes that produce valid WOL links.
|
||||
// Added: uw, su, re, lvs, rs (rs was already present).
|
||||
const PUB_CODES = [
|
||||
"wp","ws","yb","mwb","w","g","ap","apf","be","bh","br","bt","btg","cf","cl","ct","dp",
|
||||
"fg","fy","gt","hb","im","ip","it","jv","ka","kj","kl","lf","lff","ll","ly","my","od",
|
||||
"pe","po","pt","rr","rs","sg","sh","si","td","tp","tr","ts","un","jy",
|
||||
"uw","su","re","lvs","lp","yy","yp2","yp","jv","sl","pm"// new
|
||||
];
|
||||
// ---- Load publication codes (sync so callers can use API immediately) ----
|
||||
function loadPubCodesSync() {
|
||||
try {
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.open("GET", "/static/data/wol-pub-codes.v1.json", false); // synchronous
|
||||
xhr.send(null);
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
var data = JSON.parse(xhr.responseText || "{}");
|
||||
if (data && Array.isArray(data.pub_codes)) {
|
||||
// de-duplicate and normalize to lowercase strings
|
||||
var uniq = Object.create(null), out = [];
|
||||
for (var i = 0; i < data.pub_codes.length; i++) {
|
||||
var c = String(data.pub_codes[i] || "").trim().toLowerCase();
|
||||
if (!c) continue;
|
||||
if (!uniq[c]) { uniq[c] = 1; out.push(c); }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// fall through to fallback
|
||||
}
|
||||
// Fallback (very small set) — only used if JSON cannot be loaded
|
||||
return ["w", "wp", "ws", "g", "rs"];
|
||||
}
|
||||
|
||||
// Publications / codes loaded from JSON
|
||||
var PUB_CODES = loadPubCodesSync();
|
||||
|
||||
// Choose the longest matching code at the start (so "ws" beats "w").
|
||||
var PUB_CODES_SORTED = PUB_CODES.slice().sort(function (a, b) { return b.length - a.length; });
|
||||
|
||||
// Year validation rules (applies only if a year can be parsed from the source).
|
||||
// Watchtower (w/wp/ws) back to 1950; Awake (g) back to 1970.
|
||||
const YEAR_RULES = [
|
||||
var YEAR_RULES = [
|
||||
{ codes: ["w","wp","ws"], minYear: 1950 },
|
||||
{ codes: ["g"], minYear: 1970 }
|
||||
];
|
||||
@ -24,12 +49,10 @@ window.SourceValidator = (function () {
|
||||
// Normalize helper
|
||||
function normalize(s) { return (s || "").trim().toLowerCase(); }
|
||||
|
||||
// Choose the longest matching code at the start (so "ws" beats "w").
|
||||
const PUB_CODES_SORTED = [...PUB_CODES].sort((a,b)=>b.length-a.length);
|
||||
|
||||
function leadingCode(textLower) {
|
||||
for (const code of PUB_CODES_SORTED) {
|
||||
if (textLower.startsWith(code)) return code;
|
||||
for (var i = 0; i < PUB_CODES_SORTED.length; i++) {
|
||||
var code = PUB_CODES_SORTED[i];
|
||||
if (textLower.indexOf(code) === 0) return code;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@ -37,60 +60,51 @@ window.SourceValidator = (function () {
|
||||
// Try to extract a year that appears right after the leading code (allow spaces),
|
||||
// accepting either 4-digit (e.g., 1955, 2001) or 2-digit (e.g., 55, 95, 12) forms.
|
||||
function extractYearAfterCode(textLower, code) {
|
||||
let s = textLower.slice(code.length).trim();
|
||||
var s = textLower.slice(code.length).trim();
|
||||
|
||||
// 1) Look for a 4-digit year first
|
||||
let m = s.match(/\b(1[89]\d{2}|20\d{2})\b/); // 1800-2099 (broad, but OK)
|
||||
if (m) {
|
||||
return parseInt(m[1], 10);
|
||||
}
|
||||
// 1) Look for a 4-digit year first (1800–2099)
|
||||
var m = s.match(/\b(1[89]\d{2}|20\d{2})\b/);
|
||||
if (m) return parseInt(m[1], 10);
|
||||
|
||||
// 2) If not found, accept a 2-digit year at the *start* of the remainder,
|
||||
// or right after an optional space: e.g., "w55 1/1", "w 95", "g70 1/22"
|
||||
// 2) If not found, accept a 2-digit year at the *start* of the remainder
|
||||
// (e.g., "w55 1/1", "w 95", "g70 1/22")
|
||||
m = s.match(/^\s*(\d{2})\b/);
|
||||
if (m) {
|
||||
const yy = parseInt(m[1], 10);
|
||||
// Infer century based on publication + threshold logic
|
||||
// - For Watchtower: 50–99 -> 1950–1999; 00–49 -> 2000–2049
|
||||
// - For Awake: 70–99 -> 1970–1999; 00–69 -> 2000–2069
|
||||
if (code === "g") {
|
||||
return yy >= 70 ? (1900 + yy) : (2000 + yy);
|
||||
}
|
||||
if (code === "w" || code === "wp" || code === "ws") {
|
||||
return yy >= 50 ? (1900 + yy) : (2000 + yy);
|
||||
}
|
||||
// For other pubs, if they ever include 2-digit years, assume 1900+yy≥70 else 2000+yy
|
||||
var yy = parseInt(m[1], 10);
|
||||
if (code === "g") return yy >= 70 ? (1900 + yy) : (2000 + yy);
|
||||
if (code === "w" || code === "wp" || code === "ws")
|
||||
return yy >= 50 ? (1900 + yy) : (2000 + yy);
|
||||
return yy >= 70 ? (1900 + yy) : (2000 + yy);
|
||||
}
|
||||
|
||||
// No recognizable year → don't enforce year limits
|
||||
return null;
|
||||
}
|
||||
|
||||
function passesYearRuleIfPresent(textLower, code) {
|
||||
const rule = YEAR_RULES.find(r => r.codes.includes(code));
|
||||
var rule = null;
|
||||
for (var i=0;i<YEAR_RULES.length;i++){
|
||||
if (YEAR_RULES[i].codes.indexOf(code) !== -1) { rule = YEAR_RULES[i]; break; }
|
||||
}
|
||||
if (!rule) return true; // no year rule for this pub
|
||||
|
||||
const y = extractYearAfterCode(textLower, code);
|
||||
var y = extractYearAfterCode(textLower, code);
|
||||
if (y == null) return true; // no year present → allow
|
||||
return y >= rule.minYear;
|
||||
}
|
||||
|
||||
function isWOLSource(text) {
|
||||
const t = normalize(text);
|
||||
var t = normalize(text);
|
||||
if (!t) return false;
|
||||
|
||||
const code = leadingCode(t);
|
||||
var code = leadingCode(t);
|
||||
if (!code) return false;
|
||||
|
||||
// If starts with a known pub code, it’s WOL-capable — but enforce year rules where applicable.
|
||||
return passesYearRuleIfPresent(t, code);
|
||||
}
|
||||
|
||||
function buildWOLSearchURL(text) {
|
||||
const q = encodeURIComponent(text || "");
|
||||
return `https://wol.jw.org/en/wol/l/r1/lp-e?q=${q}`;
|
||||
var q = encodeURIComponent(text || "");
|
||||
return "https://wol.jw.org/en/wol/l/r1/lp-e?q=" + q;
|
||||
}
|
||||
|
||||
return { isWOLSource, buildWOLSearchURL };
|
||||
return { isWOLSource: isWOLSource, buildWOLSearchURL: buildWOLSearchURL };
|
||||
})();
|
||||
@ -11,6 +11,7 @@
|
||||
<span class="rt-count">Editing: #{{ entry.id }}</span>
|
||||
</div>
|
||||
<div class="rt-right">
|
||||
<a class="btn btn-danger" href="{% url 'entry_delete' entry.id %}">Delete</a>
|
||||
<a class="btn" href="{% url 'entry_view' entry.id %}">Cancel</a>
|
||||
<button form="entry-edit-form" class="btn btn-primary">Save</button>
|
||||
</div>
|
||||
|
||||
@ -55,7 +55,6 @@
|
||||
<!-- Edit/Delete for staff -->
|
||||
{% if user.is_authenticated and user.is_staff %}
|
||||
<a class="btn btn-outline" href="{% url 'entry_edit' entry.id %}">Edit</a>
|
||||
<a class="btn btn-danger" href="{% url 'entry_delete' entry.id %}">Delete</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -3,7 +3,6 @@
|
||||
<div class="modal-card">
|
||||
<div class="modal-header">
|
||||
<h3 id="release-title">{{ pending_announcement.title|default:"What’s new" }}</h3>
|
||||
<button class="modal-close" type="button" aria-label="Close" data-dismiss>×</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="prose">{{ pending_announcement.message|linebreaks }}</div>
|
||||
|
||||
@ -122,18 +122,16 @@
|
||||
<h2 class="cc-panel-title">Release Announcement</h2>
|
||||
</div>
|
||||
<div class="cc-panel-body">
|
||||
<form method="post" action="{% url 'announcement_tools' %}" class="cc-form">
|
||||
<form id="announcement-form" method="post" action="{% url 'announcement_tools' %}" class="cc-form">
|
||||
{% csrf_token %}
|
||||
{% if announcement_form %}
|
||||
{{ announcement_form.as_p }}
|
||||
{% else %}
|
||||
<label class="cc-label">Title</label>
|
||||
<input type="text" name="title" class="tool-input">
|
||||
<label class="cc-label">Message</label>
|
||||
<textarea name="message" rows="5" class="tool-input" placeholder="What’s new…"></textarea>
|
||||
<label class="cc-check"><input type="checkbox" name="is_active" checked> Active</label>
|
||||
{% endif %}
|
||||
<label class="cc-label">Title</label>
|
||||
<input type="text" name="title" class="tool-input" id="annc-title" />
|
||||
<label class="cc-label">Message</label>
|
||||
<textarea name="message" rows="5" class="tool-input" id="annc-message" placeholder="What’s new…"></textarea>
|
||||
<!-- Always active -->
|
||||
<input type="hidden" name="is_active" value="on" />
|
||||
<div class="cc-actions">
|
||||
<button type="button" id="annc-preview-btn" class="btn">Preview</button>
|
||||
<button class="btn btn-primary">Publish</button>
|
||||
</div>
|
||||
</form>
|
||||
@ -164,10 +162,43 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Publication Codes (JSON) – superusers only -->
|
||||
<section class="card cc-panel">
|
||||
<div class="cc-panel-head">
|
||||
<div class="cc-kicker">Comms</div>
|
||||
<h2 class="cc-panel-title">Publication Codes (JSON)</h2>
|
||||
</div>
|
||||
<div class="cc-panel-body">
|
||||
<div class="cc-row">
|
||||
<textarea id="pubCodesEditor" class="tool-input" rows="14"
|
||||
style="width:100%; font-family: ui-monospace, SFMono-Regular, Menlo, monospace;"></textarea>
|
||||
</div>
|
||||
<div class="cc-actions">
|
||||
<button type="button" id="pubCodesReloadBtn" class="btn">Reload</button>
|
||||
<button type="button" id="pubCodesSaveBtn" class="btn btn-primary">Save</button>
|
||||
</div>
|
||||
<div id="pubCodesStatus" class="tiny" style="margin-top:6px; color:#64748b;"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Announcement Preview Modal -->
|
||||
<div id="annc-preview-modal" style="position:fixed;inset:0;display:none;align-items:center;justify-content:center;z-index:10000;background:rgba(15,23,42,.35);backdrop-filter:blur(2px);">
|
||||
<div role="dialog" aria-modal="true" aria-labelledby="annc-prev-title" class="card" style="max-width:680px;width:min(92vw,680px);padding:18px 18px 12px;border-radius:16px;box-shadow:0 20px 60px rgba(0,0,0,.25);background:#fff;position:relative;">
|
||||
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px;">
|
||||
<div style="font-size:13px;letter-spacing:.08em;text-transform:uppercase;color:#64748b;font-weight:700;">Announcement Preview</div>
|
||||
<button type="button" id="annc-prev-close" class="btn btn-secondary">Close</button>
|
||||
</div>
|
||||
<div style="border:1px solid #e5e7eb;border-radius:12px;padding:14px;background:linear-gradient(180deg,#ffffff, #fbfdff);">
|
||||
<div id="annc-prev-title" style="font-weight:800;font-size:18px;color:#0f172a;margin-bottom:6px;"></div>
|
||||
<div id="annc-prev-message" style="font-size:15px;line-height:1.45;color:#111827;white-space:pre-wrap;"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Toast for Clear History -->
|
||||
<div id="toast-clear-history"
|
||||
style="position:fixed; right:16px; bottom:16px; padding:10px 14px; border-radius:10px;
|
||||
@ -193,6 +224,9 @@
|
||||
.cc-label{display:block;font-weight:600;margin:8px 0 6px;color:#0f172a}
|
||||
.cc-actions{display:flex;align-items:center;gap:10px;margin-top:10px}
|
||||
.cc-form .tool-input{border:1px solid var(--border,#d1d5db);border-radius:10px;padding:8px 10px;font-size:14px}
|
||||
/* make announcement inputs full-width */
|
||||
.cc-form .tool-input{width:100%;}
|
||||
textarea.tool-input{min-height:140px;resize:vertical;width:100%;}
|
||||
/* Switch */
|
||||
.switch{position:relative;display:inline-block;width:46px;height:26px}
|
||||
.switch input{display:none}
|
||||
@ -283,6 +317,108 @@
|
||||
.catch(()=>alert("Could not save the setting. Please try again."));
|
||||
});
|
||||
})();
|
||||
|
||||
// === Announcement Preview ===
|
||||
(function(){
|
||||
const form = document.getElementById('announcement-form');
|
||||
const btn = document.getElementById('annc-preview-btn');
|
||||
const modal = document.getElementById('annc-preview-modal');
|
||||
const close = document.getElementById('annc-prev-close');
|
||||
const titleI = document.getElementById('annc-title');
|
||||
const msgI = document.getElementById('annc-message');
|
||||
const titleO = document.getElementById('annc-prev-title');
|
||||
const msgO = document.getElementById('annc-prev-message');
|
||||
if (!form || !btn || !modal) return;
|
||||
|
||||
function openModal(){
|
||||
modal.style.display = 'flex';
|
||||
document.documentElement.style.overflow = 'hidden';
|
||||
}
|
||||
function closeModal(){
|
||||
modal.style.display = 'none';
|
||||
document.documentElement.style.overflow = '';
|
||||
}
|
||||
btn.addEventListener('click', function(){
|
||||
const t = (titleI?.value || '').trim();
|
||||
const m = (msgI?.value || '').trim();
|
||||
if (!m){
|
||||
alert('Please enter a Message to preview.');
|
||||
return;
|
||||
}
|
||||
titleO.textContent = t || 'Release Notes';
|
||||
msgO.textContent = m;
|
||||
openModal();
|
||||
});
|
||||
(close||modal).addEventListener('click', (ev)=>{
|
||||
if (ev.target === modal || ev.target === close) closeModal();
|
||||
});
|
||||
window.addEventListener('keydown', (e)=>{ if (e.key === 'Escape' && modal.style.display === 'flex') closeModal(); });
|
||||
})();
|
||||
|
||||
// === Publication Codes Editor (superuser) ===
|
||||
(function(){
|
||||
const ta = document.getElementById('pubCodesEditor');
|
||||
const btnR = document.getElementById('pubCodesReloadBtn');
|
||||
const btnS = document.getElementById('pubCodesSaveBtn');
|
||||
const stat = document.getElementById('pubCodesStatus');
|
||||
if (!ta || !btnR || !btnS) return; // not superuser or card missing
|
||||
|
||||
function setStatus(msg, ok=true){
|
||||
if (!stat) return;
|
||||
stat.textContent = msg;
|
||||
stat.style.color = ok ? '#64748b' : '#b91c1c';
|
||||
}
|
||||
|
||||
async function reloadJSON(){
|
||||
try{
|
||||
setStatus('Loading…');
|
||||
const r = await fetch('/static/data/wol-pub-codes.v1.json', { cache:'no-store' });
|
||||
if (!r.ok) throw new Error('HTTP '+r.status);
|
||||
const data = await r.json();
|
||||
ta.value = JSON.stringify(data, null, 2);
|
||||
setStatus('Loaded.');
|
||||
}catch(err){
|
||||
setStatus('Failed to load JSON: ' + (err?.message||err), false);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveJSON(){
|
||||
let parsed;
|
||||
try{
|
||||
parsed = JSON.parse(ta.value);
|
||||
if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.pub_codes))
|
||||
throw new Error('JSON must be an object with a "pub_codes" array.');
|
||||
}catch(err){
|
||||
setStatus('Invalid JSON: ' + (err?.message||err), false);
|
||||
return;
|
||||
}
|
||||
|
||||
try{
|
||||
setStatus('Saving…');
|
||||
const fd = new FormData();
|
||||
fd.append('json', JSON.stringify(parsed));
|
||||
const r = await fetch("{% url 'api_update_pub_codes' %}", {
|
||||
method: 'POST',
|
||||
body: fd,
|
||||
credentials: 'same-origin',
|
||||
headers: { 'X-CSRFToken': (document.cookie.match(/(^|;)\s*csrftoken\s*=\s*([^;]+)/)||[]).pop() || '' }
|
||||
});
|
||||
if (!r.ok) {
|
||||
const txt = await r.text().catch(()=>String(r.status));
|
||||
throw new Error(txt.slice(0,200));
|
||||
}
|
||||
const out = await r.json().catch(()=>({ok:false}));
|
||||
if (!out.ok) throw new Error('Server rejected the update.');
|
||||
setStatus('Saved. ' + out.count + ' codes.');
|
||||
}catch(err){
|
||||
setStatus('Save failed: ' + (err?.message||err), false);
|
||||
}
|
||||
}
|
||||
|
||||
btnR.addEventListener('click', reloadJSON);
|
||||
btnS.addEventListener('click', saveJSON);
|
||||
reloadJSON(); // initial load
|
||||
})();
|
||||
})();
|
||||
</script>
|
||||
|
||||
|
||||
@ -1 +1 @@
|
||||
v4.1.22
|
||||
v4.1.24
|
||||
Loading…
Reference in New Issue
Block a user