souliya_pps commited on
Commit
b413eb7
·
1 Parent(s): 2ac4f60

fix: preserve .env API URLs on HF deploy, add auto-sync, return sutra data from sync endpoint

Browse files
app/Controllers/ApiController.php CHANGED
@@ -18,10 +18,10 @@ class ApiController {
18
  header('Content-Type: application/json');
19
  try {
20
  set_time_limit(60);
21
- Sutra::getAll(true);
22
  $cacheFile = __DIR__ . '/../../storage/cache/sutra_api.json';
23
  $version = file_exists($cacheFile) ? filemtime($cacheFile) : time();
24
- echo json_encode(['success' => true, 'version' => $version], JSON_UNESCAPED_UNICODE);
25
  } catch (\Exception $e) {
26
  http_response_code(500);
27
  echo json_encode(['success' => false, 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
 
18
  header('Content-Type: application/json');
19
  try {
20
  set_time_limit(60);
21
+ $sutras = Sutra::getAll(true);
22
  $cacheFile = __DIR__ . '/../../storage/cache/sutra_api.json';
23
  $version = file_exists($cacheFile) ? filemtime($cacheFile) : time();
24
+ echo json_encode(['success' => true, 'data' => $sutras, 'version' => $version], JSON_UNESCAPED_UNICODE);
25
  } catch (\Exception $e) {
26
  http_response_code(500);
27
  echo json_encode(['success' => false, 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
app/Helpers/view.php CHANGED
@@ -1,7 +1,7 @@
1
  <?php
2
 
3
  function getSiteUrl() {
4
- $siteUrl = $_ENV['SITE_URL'] ?? '';
5
  $canonical = 'https://buddhaword-web.hf.space';
6
 
7
  // If SITE_URL is set and it's a free.nf address, override to canonical
 
1
  <?php
2
 
3
  function getSiteUrl() {
4
+ $siteUrl = $_ENV['SITE_URL'] ?? getenv('SITE_URL') ?: '';
5
  $canonical = 'https://buddhaword-web.hf.space';
6
 
7
  // If SITE_URL is set and it's a free.nf address, override to canonical
app/Models/Book.php CHANGED
@@ -9,7 +9,7 @@ class Book {
9
  if (!$refresh && file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
10
  $json = file_get_contents($cacheFile);
11
  } else {
12
- $url = $_ENV['BOOK_API_URL'] ?? '';
13
  if (!$url) {
14
  if (file_exists($cacheFile)) {
15
  $json = file_get_contents($cacheFile);
 
9
  if (!$refresh && file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
10
  $json = file_get_contents($cacheFile);
11
  } else {
12
+ $url = $_ENV['BOOK_API_URL'] ?? getenv('BOOK_API_URL') ?: '';
13
  if (!$url) {
14
  if (file_exists($cacheFile)) {
15
  $json = file_get_contents($cacheFile);
app/Models/Calendar.php CHANGED
@@ -9,7 +9,7 @@ class Calendar {
9
  if (!$refresh && file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
10
  $json = file_get_contents($cacheFile);
11
  } else {
12
- $url = $_ENV['CALENDAR_API_URL'] ?? '';
13
  if (!$url) {
14
  if (file_exists($cacheFile)) {
15
  $json = file_get_contents($cacheFile);
 
9
  if (!$refresh && file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
10
  $json = file_get_contents($cacheFile);
11
  } else {
12
+ $url = $_ENV['CALENDAR_API_URL'] ?? getenv('CALENDAR_API_URL') ?: '';
13
  if (!$url) {
14
  if (file_exists($cacheFile)) {
15
  $json = file_get_contents($cacheFile);
app/Models/Sutra.php CHANGED
@@ -16,7 +16,7 @@ class Sutra {
16
  if (!$refresh && file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
17
  $json = file_get_contents($cacheFile);
18
  } else {
19
- $url = $_ENV['SUTRA_API_URL'] ?? null;
20
  if (!$url) {
21
  if (file_exists($cacheFile)) {
22
  $json = file_get_contents($cacheFile);
 
16
  if (!$refresh && file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
17
  $json = file_get_contents($cacheFile);
18
  } else {
19
+ $url = $_ENV['SUTRA_API_URL'] ?? getenv('SUTRA_API_URL') ?: null;
20
  if (!$url) {
21
  if (file_exists($cacheFile)) {
22
  $json = file_get_contents($cacheFile);
app/Models/Video.php CHANGED
@@ -9,7 +9,7 @@ class Video {
9
  if (!$refresh && file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
10
  $json = file_get_contents($cacheFile);
11
  } else {
12
- $url = $_ENV['VIDEO_API_URL'] ?? '';
13
  if (!$url) {
14
  if (file_exists($cacheFile)) {
15
  $json = file_get_contents($cacheFile);
 
9
  if (!$refresh && file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
10
  $json = file_get_contents($cacheFile);
11
  } else {
12
+ $url = $_ENV['VIDEO_API_URL'] ?? getenv('VIDEO_API_URL') ?: '';
13
  if (!$url) {
14
  if (file_exists($cacheFile)) {
15
  $json = file_get_contents($cacheFile);
entrypoint.sh CHANGED
@@ -1,9 +1,30 @@
1
  #!/bin/sh
2
  set -e
3
 
4
- # Overwrite .env from environment variables so the app's custom loader picks them up
 
 
 
 
 
 
5
  env > /var/www/html/.env
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  # Decompress SQLite databases at runtime (avoids OOM during Docker build on HF)
8
  for f in /var/www/html/databases/*.sqlite.gz; do
9
  code=$(basename "$f" .sqlite.gz)
 
1
  #!/bin/sh
2
  set -e
3
 
4
+ # Merge environment variables into .env without destroying existing config
5
+ # System env vars (Hugging Face secrets) take precedence over .env defaults
6
+ # Preserve original .env values (API URLs, etc.) not set as system env vars
7
+ if [ -f /var/www/html/.env ]; then
8
+ cp /var/www/html/.env /var/www/html/.env.orig
9
+ fi
10
+
11
  env > /var/www/html/.env
12
 
13
+ # Append original .env entries that are NOT already set as system env vars
14
+ if [ -f /var/www/html/.env.orig ]; then
15
+ while IFS='=' read -r line || [ -n "$line" ]; do
16
+ line=$(echo "$line" | tr -d '\r')
17
+ case "$line" in
18
+ ''|'#'*) continue;;
19
+ esac
20
+ key="${line%%=*}"
21
+ if ! grep -q "^${key}=" /var/www/html/.env 2>/dev/null; then
22
+ echo "$line" >> /var/www/html/.env
23
+ fi
24
+ done < /var/www/html/.env.orig
25
+ rm -f /var/www/html/.env.orig
26
+ fi
27
+
28
  # Decompress SQLite databases at runtime (avoids OOM during Docker build on HF)
29
  for f in /var/www/html/databases/*.sqlite.gz; do
30
  code=$(basename "$f" .sqlite.gz)
views/layouts/main.php CHANGED
@@ -159,30 +159,86 @@
159
 
160
  <script>
161
  var ttsWords = [];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  function speakBrowser(opt) {
163
  if (!('speechSynthesis' in window) || !opt || !opt.text) return;
164
  try {
165
  speechSynthesis.cancel();
 
166
  var text = opt.text;
167
  var lang = { 'lo-LA': 'lo-LA', 'th-TH': 'th-TH', 'en-US': 'en-US' }[opt.lang] || 'lo-LA';
 
 
 
168
  ttsWords = [].slice.call(document.querySelectorAll('.tts-w'));
 
 
 
169
 
170
  var doSpeak = function() {
171
  var u = new SpeechSynthesisUtterance(text);
172
- u.lang = lang;
173
  u.rate = 0.85;
174
 
175
  var voices = speechSynthesis.getVoices();
176
- var match = voices.find(function(v) { return v.lang.startsWith(lang.split('-')[0]); });
177
- if (match) {
 
 
 
 
 
 
 
178
  u.voice = match;
179
- } else if (lang === 'lo-LA') {
180
- // No Lao voice — try Thai (linguistically closest)
181
- var thaiVoice = voices.find(function(v) { return v.lang.startsWith('th'); });
182
- if (thaiVoice) u.voice = thaiVoice;
 
183
  } else {
184
- return;
 
 
185
  }
 
186
 
187
  if (ttsWords.length > 0) {
188
  var wordRanges = [];
@@ -195,7 +251,6 @@
195
  var lastIdx = -1;
196
  var startTime = null;
197
 
198
- // Build cumulative character-position array for time-based estimation
199
  var charPositions = [];
200
  var totalChars = 0;
201
  for (var i = 0; i < wordCount; i++) {
@@ -207,16 +262,11 @@
207
  startTime = performance.now();
208
  };
209
 
210
- // Primary: time-based estimation (works for all languages)
211
  var timer = setInterval(function() {
212
  if (!startTime || wordCount === 0 || !ttsWords.length) return;
213
  var elapsed = performance.now() - startTime;
214
- // ~8.5 chars/sec for Lao at rate 0.85
215
  var estimatedChars = elapsed * 0.0085;
216
- if (estimatedChars >= totalChars) {
217
- estimatedChars = totalChars - 1;
218
- }
219
- // Binary search: find word at this character position
220
  var lo = 0, hi = wordCount - 1;
221
  while (lo <= hi) {
222
  var mid = (lo + hi) >>> 1;
@@ -234,7 +284,6 @@
234
  }
235
  }, 40);
236
 
237
- // Corrector: onboundary fires when available (may be unreliable for Lao)
238
  u.onboundary = function(e) {
239
  if (e.name !== 'word' || wordCount === 0) return;
240
  var ci = e.charIndex;
@@ -262,26 +311,32 @@
262
  _restoreBrowserDOM();
263
  }, { once: true });
264
  } else {
265
- u.addEventListener('end', function() {
266
- _restoreBrowserDOM();
267
- }, { once: true });
268
  }
269
  speechSynthesis.speak(u);
270
  };
271
 
272
  function _restoreBrowserDOM() {
273
- window.ttsPlaying = false;
274
- var icon = document.getElementById('ttsIcon');
275
- if (icon) { icon.classList.remove('fa-stop'); icon.classList.add('fa-play'); }
276
- var btn = document.getElementById('ttsBtn');
277
- if (btn) {
278
- btn.classList.remove('text-green-300', 'bg-green-500/20');
279
- btn.classList.add('text-white/70');
280
- }
 
 
 
 
 
 
 
 
 
 
281
  }
282
 
283
- // iOS Safari: getVoices() returns empty until 'voiceschanged' fires.
284
- // Without loaded voices, no lang match is found and English is used.
285
  if (speechSynthesis.getVoices().length === 0) {
286
  var handler = function() {
287
  speechSynthesis.removeEventListener('voiceschanged', handler);
@@ -742,6 +797,10 @@
742
  this.checkForUpdates();
743
  this.restoreSearchState();
744
  this.$watch('searchQuery', (value) => this.saveSearchState());
 
 
 
 
745
  }
746
  }">
747
  <div id="navbarWrapper" class="fixed top-0 left-0 right-0 z-50 transition-transform duration-300">
@@ -1064,6 +1123,28 @@
1064
  window.history.replaceState({}, document.title, url.pathname + url.search);
1065
  }
1066
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1067
 
1068
  /* Auto-hide navbar & bottom nav on scroll */
1069
  (function() {
 
159
 
160
  <script>
161
  var ttsWords = [];
162
+ function wrapTTSText(textEl) {
163
+ if (!textEl) return;
164
+ if (typeof ttsOrigHTML === 'undefined' || ttsOrigHTML === null) {
165
+ ttsOrigHTML = textEl.innerHTML;
166
+ }
167
+ if (textEl.querySelector('.tts-w')) return;
168
+ textEl.innerHTML = textEl.innerHTML.replace(/(<[^>]+>)|(\S+)|(\s+)/gi, function(m, tag) {
169
+ if (tag) return tag;
170
+ return '<span class="tts-w">' + m + '</span>';
171
+ });
172
+ }
173
+ /* Helper: tries browser Lao TTS; calls onNoVoice if no Lao voice available */
174
+ function tryBrowserTTS(text, lang, onNoVoice) {
175
+ if (!('speechSynthesis' in window) || typeof speakBrowser !== 'function') {
176
+ if (typeof onNoVoice === 'function') onNoVoice();
177
+ return;
178
+ }
179
+ var voices = speechSynthesis.getVoices();
180
+ if (voices.length === 0) {
181
+ var handler = function() {
182
+ speechSynthesis.removeEventListener('voiceschanged', handler);
183
+ var v = speechSynthesis.getVoices();
184
+ if (v.some(function(x) { return x.lang.startsWith('lo'); })) {
185
+ speakBrowser({ text: text, lang: lang });
186
+ } else if (typeof onNoVoice === 'function') {
187
+ onNoVoice();
188
+ }
189
+ };
190
+ speechSynthesis.addEventListener('voiceschanged', handler);
191
+ return;
192
+ }
193
+ if (voices.some(function(v) { return v.lang.startsWith('lo'); })) {
194
+ speakBrowser({ text: text, lang: lang });
195
+ } else if (typeof onNoVoice === 'function') {
196
+ onNoVoice();
197
+ }
198
+ }
199
+
200
+ /* Browser speechSynthesis with word highlighting */
201
  function speakBrowser(opt) {
202
  if (!('speechSynthesis' in window) || !opt || !opt.text) return;
203
  try {
204
  speechSynthesis.cancel();
205
+ if (typeof stopTTS === 'function') stopTTS();
206
  var text = opt.text;
207
  var lang = { 'lo-LA': 'lo-LA', 'th-TH': 'th-TH', 'en-US': 'en-US' }[opt.lang] || 'lo-LA';
208
+ var textEl = document.getElementById('sutraText') || document.getElementById('readerContent');
209
+ if (!textEl) { _restoreBrowserDOM(); return; }
210
+ wrapTTSText(textEl);
211
  ttsWords = [].slice.call(document.querySelectorAll('.tts-w'));
212
+ window.ttsPlaying = true;
213
+ var btn = document.getElementById('ttsBtn');
214
+ if (btn) { btn.classList.remove('text-white/70'); btn.classList.add('text-green-300', 'bg-green-500/20'); }
215
 
216
  var doSpeak = function() {
217
  var u = new SpeechSynthesisUtterance(text);
 
218
  u.rate = 0.85;
219
 
220
  var voices = speechSynthesis.getVoices();
221
+ if (lang === 'lo-LA') {
222
+ var match = voices.find(function(v) { return v.lang === 'lo-LA'; })
223
+ || voices.find(function(v) { return v.lang.startsWith('lo'); });
224
+ if (!match) {
225
+ clearInterval(timer);
226
+ ttsWords = [];
227
+ _restoreBrowserDOM();
228
+ return;
229
+ }
230
  u.voice = match;
231
+ } else if (lang === 'th-TH') {
232
+ u.voice = voices.find(function(v) { return v.lang === 'th-TH'; })
233
+ || voices.find(function(v) { return v.lang.startsWith('th'); })
234
+ || voices.find(function(v) { return v.lang.startsWith('en'); })
235
+ || voices[0];
236
  } else {
237
+ u.voice = voices.find(function(v) { return v.lang.startsWith('en-US'); })
238
+ || voices.find(function(v) { return v.lang.startsWith('en'); })
239
+ || voices[0];
240
  }
241
+ u.lang = lang;
242
 
243
  if (ttsWords.length > 0) {
244
  var wordRanges = [];
 
251
  var lastIdx = -1;
252
  var startTime = null;
253
 
 
254
  var charPositions = [];
255
  var totalChars = 0;
256
  for (var i = 0; i < wordCount; i++) {
 
262
  startTime = performance.now();
263
  };
264
 
 
265
  var timer = setInterval(function() {
266
  if (!startTime || wordCount === 0 || !ttsWords.length) return;
267
  var elapsed = performance.now() - startTime;
 
268
  var estimatedChars = elapsed * 0.0085;
269
+ if (estimatedChars >= totalChars) estimatedChars = totalChars - 1;
 
 
 
270
  var lo = 0, hi = wordCount - 1;
271
  while (lo <= hi) {
272
  var mid = (lo + hi) >>> 1;
 
284
  }
285
  }, 40);
286
 
 
287
  u.onboundary = function(e) {
288
  if (e.name !== 'word' || wordCount === 0) return;
289
  var ci = e.charIndex;
 
311
  _restoreBrowserDOM();
312
  }, { once: true });
313
  } else {
314
+ u.addEventListener('end', function() { _restoreBrowserDOM(); }, { once: true });
 
 
315
  }
316
  speechSynthesis.speak(u);
317
  };
318
 
319
  function _restoreBrowserDOM() {
320
+ try {
321
+ window.ttsPlaying = false;
322
+ if (typeof ttsPlaying !== 'undefined') ttsPlaying = false;
323
+ if (typeof updateTTSIcon === 'function') updateTTSIcon();
324
+ var icon = document.getElementById('ttsIcon');
325
+ var btn = document.getElementById('ttsBtn');
326
+ if (btn) {
327
+ btn.classList.remove('text-green-300', 'bg-green-500/20');
328
+ btn.classList.add('text-white/70');
329
+ }
330
+ var controls = document.getElementById('ttsControls');
331
+ if (controls) controls.style.display = 'none';
332
+ if (typeof updateTTSPlayPauseIcon === 'function') updateTTSPlayPauseIcon(false);
333
+ if (typeof ttsOrigHTML !== 'undefined' && ttsOrigHTML) {
334
+ var el = document.getElementById('sutraText') || document.getElementById('readerContent');
335
+ if (el) { el.innerHTML = ttsOrigHTML; ttsOrigHTML = null; }
336
+ }
337
+ } catch(e) {}
338
  }
339
 
 
 
340
  if (speechSynthesis.getVoices().length === 0) {
341
  var handler = function() {
342
  speechSynthesis.removeEventListener('voiceschanged', handler);
 
797
  this.checkForUpdates();
798
  this.restoreSearchState();
799
  this.$watch('searchQuery', (value) => this.saveSearchState());
800
+ /* Auto-sync when online on page load if no cached data */
801
+ if (navigator.onLine && !localStorage.getItem('buddhaword_sutras')) {
802
+ this.syncData(true);
803
+ }
804
  }
805
  }">
806
  <div id="navbarWrapper" class="fixed top-0 left-0 right-0 z-50 transition-transform duration-300">
 
1123
  window.history.replaceState({}, document.title, url.pathname + url.search);
1124
  }
1125
  });
1126
+
1127
+ /* Force clear stale caches on version mismatch to always show latest UI */
1128
+ (function() {
1129
+ var appVer = '10';
1130
+ var cachedVer = localStorage.getItem('buddhaword_app_version');
1131
+ if (cachedVer !== appVer) {
1132
+ var reloaded = sessionStorage.getItem('buddhaword_cache_cleared');
1133
+ if (!reloaded) {
1134
+ sessionStorage.setItem('buddhaword_cache_cleared', '1');
1135
+ if ('caches' in window) {
1136
+ caches.keys().then(function(keys) {
1137
+ return Promise.all(keys.map(function(k) { return caches.delete(k); }));
1138
+ }).catch(function() {});
1139
+ }
1140
+ if (typeof bwdb !== 'undefined') {
1141
+ try { bwdb.clearAll(); } catch(e) {}
1142
+ }
1143
+ localStorage.setItem('buddhaword_app_version', appVer);
1144
+ window.location.reload(true);
1145
+ }
1146
+ }
1147
+ })();
1148
 
1149
  /* Auto-hide navbar & bottom nav on scroll */
1150
  (function() {
views/pages/video/index.php CHANGED
@@ -74,6 +74,10 @@ sort($dharmaCategories);
74
  const navbar = document.getElementById('navbarWrapper');
75
  this.navbarHidden = navbar?.classList.contains('-translate-y-full') ?? false;
76
  }, { passive: true });
 
 
 
 
77
  }
78
  }" class="flex flex-col items-center justify-center mb-5 page-enter">
79
 
 
74
  const navbar = document.getElementById('navbarWrapper');
75
  this.navbarHidden = navbar?.classList.contains('-translate-y-full') ?? false;
76
  }, { passive: true });
77
+
78
+ window.addEventListener('sync-complete', () => {
79
+ this.fetchVideos();
80
+ });
81
  }
82
  }" class="flex flex-col items-center justify-center mb-5 page-enter">
83