-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmain.go
More file actions
1717 lines (1466 loc) · 47.6 KB
/
main.go
File metadata and controls
1717 lines (1466 loc) · 47.6 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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/asim/reminder/api"
"github.com/asim/reminder/app"
"github.com/asim/reminder/daily"
"github.com/asim/reminder/hadith"
"github.com/asim/reminder/names"
"github.com/asim/reminder/quran"
"github.com/asim/reminder/search"
"github.com/google/uuid"
)
var (
IndexFlag = flag.Bool("index", false, "Index data for search. Stored at $HOME/reminder.idx")
ExportFlag = flag.Bool("export", false, "Export the index data to $HOME/reminder.idx.gob.gz")
ImportFlag = flag.Bool("import", false, "Import the index data from $HOME/reminder.idx.gob.gz")
ServerFlag = flag.Bool("serve", false, "Run the server")
EnvFlag = flag.String("env", "dev", "Set the environment")
WebFlag = flag.Bool("web", false, "Without this flag, the lite version will be served")
)
var mtx sync.RWMutex
var history = map[string][]string{}
var dailyName, dailyVerse, dailyHadith, dailyMessage string
var links = map[string]string{}
var dailyUpdated = time.Time{}
var reminderDir = api.ReminderDir
var lastPushDateFile = api.ReminderPath("last_push_date.txt")
var lastPushDate = loadLastPushDate()
var dailyIndex = loadDailyIndex()
func min(a, b int) int {
if a < b {
return a
}
return b
}
func isCapital(s string) bool {
if len(s) == 0 {
return false // An empty string doesn't have a capitalized first letter
}
firstChar := []rune(s)[0] // Convert string to slice of runes to handle Unicode characters
// Check if the first character is a letter
if !unicode.IsLetter(firstChar) {
return false // If it's not a letter, it can't be capitalized
}
return unicode.IsUpper(firstChar)
}
func isAPIClient(r *http.Request) bool {
userAgent := r.Header.Get("User-Agent")
accept := r.Header.Get("Accept")
return strings.Contains(userAgent, "Wget") ||
strings.Contains(userAgent, "curl") ||
strings.Contains(userAgent, "Go-http-client") ||
strings.Contains(userAgent, "python-requests") ||
(accept != "" && !strings.Contains(accept, "text/html") && !strings.Contains(accept, "*/*"))
}
func registerLiteRoutes(q *quran.Quran, n *names.Names, b *hadith.Collection, a *api.Api) {
http.HandleFunc("/home", func(w http.ResponseWriter, r *http.Request) {
mtx.RLock()
verseLink := links["verse"]
hadithLink := links["hadith"]
nameLink := links["name"]
verse := dailyVerse
hadith := dailyHadith
name := dailyName
mtx.RUnlock()
// Populate Index template with actual data
indexContent := strings.ReplaceAll(app.Index, "{verse_link}", verseLink)
indexContent = strings.ReplaceAll(indexContent, "{verse_text}", verse)
indexContent = strings.ReplaceAll(indexContent, "{hadith_link}", hadithLink)
indexContent = strings.ReplaceAll(indexContent, "{hadith_text}", hadith)
indexContent = strings.ReplaceAll(indexContent, "{name_link}", nameLink)
indexContent = strings.ReplaceAll(indexContent, "{name_text}", name)
if isAPIClient(r) {
w.Write([]byte(app.RenderSimpleHTML("Home", "Quran, hadith, and more as an app and API", indexContent)))
} else {
w.Write([]byte(app.RenderHTML("Home", "Quran, hadith, and more as an app and API", indexContent)))
}
})
http.HandleFunc("/bookmarks", func(w http.ResponseWriter, r *http.Request) {
bookmarksContent := `
<div id="quran-bookmarks" class="mb-8">
<h2 class="text-2xl font-semibold mb-4">Quran</h2>
<div id="quran-list" class="space-y-3"></div>
</div>
<div id="hadith-bookmarks" class="mb-8">
<h2 class="text-2xl font-semibold mb-4">Hadith</h2>
<div id="hadith-list" class="space-y-3"></div>
</div>
<div id="names-bookmarks" class="mb-8">
<h2 class="text-2xl font-semibold mb-4">Names</h2>
<div id="names-list" class="space-y-3"></div>
</div>
<script>
function loadBookmarks() {
const bookmarks = JSON.parse(localStorage.getItem('reminder_bookmarks') || '{"quran":{},"hadith":{},"names":{}}');
// Quran bookmarks
const quranList = document.getElementById('quran-list');
const quranKeys = Object.keys(bookmarks.quran || {});
if (quranKeys.length > 0) {
quranList.innerHTML = quranKeys.map(key => {
const bookmark = bookmarks.quran[key];
return ` + "`" + `
<div class="flex items-center justify-between p-4 bg-white border border-gray-200 rounded-lg hover:border-gray-400 transition-colors">
<a href="${bookmark.url}" class="flex-grow text-blue-600 hover:text-blue-800">${bookmark.label}</a>
<button onclick="removeBookmark('quran', '${key}')" class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 transition-colors text-sm">Remove</button>
</div>
` + "`" + `;
}).join('');
} else {
quranList.innerHTML = '<p class="text-gray-500">No bookmarks yet</p>';
}
// Hadith bookmarks
const hadithList = document.getElementById('hadith-list');
const hadithKeys = Object.keys(bookmarks.hadith || {});
if (hadithKeys.length > 0) {
hadithList.innerHTML = hadithKeys.map(key => {
const bookmark = bookmarks.hadith[key];
return ` + "`" + `
<div class="flex items-center justify-between p-4 bg-white border border-gray-200 rounded-lg hover:border-gray-400 transition-colors">
<a href="${bookmark.url}" class="flex-grow text-blue-600 hover:text-blue-800">${bookmark.label}</a>
<button onclick="removeBookmark('hadith', '${key}')" class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 transition-colors text-sm">Remove</button>
</div>
` + "`" + `;
}).join('');
} else {
hadithList.innerHTML = '<p class="text-gray-500">No bookmarks yet</p>';
}
// Names bookmarks
const namesList = document.getElementById('names-list');
const namesKeys = Object.keys(bookmarks.names || {});
if (namesKeys.length > 0) {
namesList.innerHTML = namesKeys.map(key => {
const bookmark = bookmarks.names[key];
return ` + "`" + `
<div class="flex items-center justify-between p-4 bg-white border border-gray-200 rounded-lg hover:border-gray-400 transition-colors">
<a href="${bookmark.url}" class="flex-grow text-blue-600 hover:text-blue-800">${bookmark.label}</a>
<button onclick="removeBookmark('names', '${key}')" class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 transition-colors text-sm">Remove</button>
</div>
` + "`" + `;
}).join('');
} else {
namesList.innerHTML = '<p class="text-gray-500">No bookmarks yet</p>';
}
}
function removeBookmark(type, key) {
const bookmarks = JSON.parse(localStorage.getItem('reminder_bookmarks') || '{"quran":{},"hadith":{},"names":{}}');
if (bookmarks[type] && bookmarks[type][key]) {
delete bookmarks[type][key];
localStorage.setItem('reminder_bookmarks', JSON.stringify(bookmarks));
loadBookmarks();
}
}
loadBookmarks();
</script>
`
w.Write([]byte(app.RenderHTML("Bookmarks", "", bookmarksContent)))
})
http.HandleFunc("/quran", func(w http.ResponseWriter, r *http.Request) {
content := q.TOC()
if isAPIClient(r) {
qhtml := app.RenderSimpleHTML("Quran", quran.Description, content)
w.Write([]byte(qhtml))
} else {
qhtml := app.RenderHTML("Quran", quran.Description, content)
w.Write([]byte(qhtml))
}
})
http.HandleFunc("/hadith", func(w http.ResponseWriter, r *http.Request) {
content := b.TOC()
if isAPIClient(r) {
qhtml := app.RenderSimpleHTML("Hadith", hadith.Description, content)
w.Write([]byte(qhtml))
} else {
qhtml := app.RenderHTML("Hadith", hadith.Description, content)
w.Write([]byte(qhtml))
}
})
http.HandleFunc("/names", func(w http.ResponseWriter, r *http.Request) {
content := n.TOC()
if isAPIClient(r) {
qhtml := app.RenderSimpleHTML("Names", names.Description, content)
w.Write([]byte(qhtml))
} else {
qhtml := app.RenderHTML("Names", names.Description, content)
w.Write([]byte(qhtml))
}
})
http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
content := a.HTML(app.RenderString)
w.Write([]byte(app.RenderHTML("API", "", content)))
})
http.HandleFunc("/daily", func(w http.ResponseWriter, r *http.Request) {
template := `
<h3 class="text-lg font-semibold mt-6 mb-2">Verse</h3>
<a href="%s" class="block p-4 bg-white border border-gray-200 rounded-lg hover:border-gray-400 transition-colors mb-4">%s</a>
<h3 class="text-lg font-semibold mt-6 mb-2">Hadith</h3>
<a href="%s" class="block p-4 bg-white border border-gray-200 rounded-lg hover:border-gray-400 transition-colors mb-4">%s</a>
<h3 class="text-lg font-semibold mt-6 mb-2">Name</h3>
<a href="%s" class="block p-4 bg-white border border-gray-200 rounded-lg hover:border-gray-400 transition-colors mb-4">%s</a>
<p class="text-sm text-gray-500 mt-4">Updated %s</p>
`
mtx.RLock()
verseLink := links["verse"]
hadithLink := links["hadith"]
nameLink := links["name"]
data := fmt.Sprintf(template, verseLink, dailyVerse, hadithLink, dailyHadith, nameLink, dailyName, dailyUpdated.Format(time.RFC3339))
mtx.RUnlock()
html := app.RenderHTML("Daily Reminder", "Daily reminder from the quran, hadith and names of Allah", data)
w.Write([]byte(html))
})
http.HandleFunc("/quran/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if len(id) == 0 {
return
}
ch, _ := strconv.Atoi(id)
if ch < 1 || ch > 114 {
return
}
head := fmt.Sprintf("%d | Quran", ch)
content := q.Get(ch).HTML()
qhtml := app.RenderHTML(head, "", content)
w.Write([]byte(qhtml))
})
http.HandleFunc("/quran/{id}/{ver}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if len(id) == 0 {
return
}
ver := r.PathValue("ver")
if len(ver) == 0 {
return
}
ch, _ := strconv.Atoi(id)
ve, _ := strconv.Atoi(ver)
if ch < 1 || ch > 114 {
return
}
cc := q.Get(ch)
if ve < 1 || ve > len(cc.Verses) {
return
}
vv := cc.Verses[ve-1]
head := fmt.Sprintf("%d:%d | Quran", ch, ve)
vhtml := app.RenderHTML(head, "", vv.HTML())
w.Write([]byte(vhtml))
})
http.HandleFunc("/names/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if len(id) == 0 {
return
}
name, _ := strconv.Atoi(id)
if name < 1 || name > len(*n) {
return
}
head := fmt.Sprintf("%d | Names", name)
content := n.Get(name).HTML()
qhtml := app.RenderHTML(head, "", content)
w.Write([]byte(qhtml))
})
http.HandleFunc("/hadith/{book}", func(w http.ResponseWriter, r *http.Request) {
book := r.PathValue("book")
if len(book) == 0 {
return
}
ch, _ := strconv.Atoi(book)
if ch < 1 || ch > len(b.Books) {
return
}
head := fmt.Sprintf("%d | Hadith", ch)
content := b.Get(ch).HTML()
qhtml := app.RenderHTML(head, "", content)
w.Write([]byte(qhtml))
})
http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
shtml := app.RenderHTML("Search", "", app.SearchTemplate)
w.Write([]byte(shtml))
})
http.HandleFunc("/islam", func(w http.ResponseWriter, r *http.Request) {
html := app.Get("islam.html")
page := app.RenderHTML("Islam", "An overview of Islam", html)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(page))
})
// Serve static files (bookmarks.js, manifest, etc.)
staticFiles := []string{"bookmarks.js", "reminder.js", "manifest.webmanifest", "arabic.otf", "reminder.png", "icon-192.png", "icon-96.png"}
for _, file := range staticFiles {
fileName := file
http.HandleFunc("/"+fileName, func(w http.ResponseWriter, r *http.Request) {
content := app.Get(fileName)
if strings.HasSuffix(fileName, ".js") {
w.Header().Set("Content-Type", "application/javascript")
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
} else if strings.HasSuffix(fileName, ".json") || strings.HasSuffix(fileName, ".webmanifest") {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
} else if strings.HasSuffix(fileName, ".otf") {
w.Header().Set("Content-Type", "font/otf")
w.Header().Set("Cache-Control", "public, max-age=31536000")
} else if strings.HasSuffix(fileName, ".png") {
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Cache-Control", "public, max-age=31536000")
}
w.Write([]byte(content))
})
}
// Root route - redirect to /home
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Only handle exact "/" path, let other routes handle themselves
if r.URL.Path == "/" {
http.Redirect(w, r, "/home", http.StatusFound)
return
}
// For other paths, return 404 (no other handler matched)
http.NotFound(w, r)
})
}
func loadLastPushDate() string {
fmt.Println("Load last pushdate")
b, err := os.ReadFile(lastPushDateFile)
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
func saveLastPushDate(date string) {
_ = os.MkdirAll(reminderDir, 0700)
_ = os.WriteFile(lastPushDateFile, []byte(date), 0644)
}
// On startup, load daily index
func loadDailyIndex() map[string]interface{} {
fmt.Println("Load daily index")
dailyFile := api.ReminderPath("daily.json")
var idx map[string]interface{}
if b, err := os.ReadFile(dailyFile); err == nil {
json.Unmarshal(b, &idx)
}
if idx == nil {
idx = make(map[string]interface{})
}
return idx
}
func saveDaily(date string, data map[string]interface{}) {
// Save to daily.json
dailyFile := api.ReminderPath("daily.json")
var allDaily map[string]interface{}
if b, err := os.ReadFile(dailyFile); err == nil {
json.Unmarshal(b, &allDaily)
}
if allDaily == nil {
allDaily = make(map[string]interface{})
}
allDaily[date] = data
b, _ := json.MarshalIndent(allDaily, "", " ")
_ = os.MkdirAll(api.ReminderDir, 0700)
_ = os.WriteFile(dailyFile, b, 0644)
dailyIndex = allDaily // update in-memory index
}
func saveHourlyReminder(date, timestamp string, data map[string]interface{}) {
// Save to hourly reminders file
hourlyFile := api.ReminderPath(fmt.Sprintf("hourly_%s.json", date))
var hourlyReminders []interface{}
if b, err := os.ReadFile(hourlyFile); err == nil {
json.Unmarshal(b, &hourlyReminders)
}
if hourlyReminders == nil {
hourlyReminders = make([]interface{}, 0)
}
hourlyReminders = append(hourlyReminders, data)
b, _ := json.MarshalIndent(hourlyReminders, "", " ")
_ = os.MkdirAll(api.ReminderDir, 0700)
_ = os.WriteFile(hourlyFile, b, 0644)
}
func loadHourlyReminders(date string) []interface{} {
hourlyFile := api.ReminderPath(fmt.Sprintf("hourly_%s.json", date))
var hourlyReminders []interface{}
if b, err := os.ReadFile(hourlyFile); err == nil {
json.Unmarshal(b, &hourlyReminders)
}
return hourlyReminders
}
// generateMessage generates an LLM-based message using the verse, hadith, and name
// The askLLM function panics on errors, which is why we use panic recovery here.
func generateMessage(ctx context.Context, verse, hadith, name string) (message string) {
// Fallback message in case LLM fails
defaultMessage := "In the Name of Allah—the Most Beneficent, Most Merciful"
message = defaultMessage // Set default in case of panic
// Build context for the LLM
contexts := []string{
fmt.Sprintf("Verse from the Quran: %s", verse),
fmt.Sprintf("Hadith: %s", hadith),
fmt.Sprintf("Name of Allah: %s", name),
}
// Create a question that asks the LLM to generate a beneficial message
question := "Based on the provided Quranic verse, Hadith, and name of Allah, generate a short, beneficial, and factual message (2-3 sentences) that provides spiritual guidance and reflection for the reader."
// Use the LLM to generate the message
// Wrap in a recover to handle panics from askLLM (which panics on errors)
defer func() {
if r := recover(); r != nil {
fmt.Printf("Failed to generate contextual message via LLM: %v\n", r)
message = defaultMessage // Ensure we return default on panic
}
}()
llmMessage := askLLM(ctx, contexts, question)
// If message is not empty, use it
if len(strings.TrimSpace(llmMessage)) > 0 {
message = llmMessage
}
return message
}
func main() {
fmt.Println("New rand source")
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
flag.Parse()
// Load push subscriptions
fmt.Println("Loading subscriptions")
_ = api.LoadPushSubscriptions()
// Load or generate VAPID keys
fmt.Println("Loading VAPID keys")
_ = api.LoadOrGenerateVAPIDKeys()
// create a new indexa
fmt.Println("Generating index")
idx := search.New("reminder", false)
// async load the index
go func() {
// Load the pre-existing data
fmt.Println("Loading index")
if err := idx.Load(); err != nil {
fmt.Println(err)
}
fmt.Println("Loaded index")
}()
// load data
fmt.Println("Initialising data")
q := quran.Load()
fmt.Println("Loaded Quran")
n := names.Load()
fmt.Println("Loaded Names")
b := hadith.Load()
fmt.Println("Loaded Hadith")
a := api.Load()
fmt.Println("Loaded API")
// generate json
qjson := q.JSON()
njson := n.JSON()
hjson := b.JSON()
// index the quran in english
indexed := make(chan bool, 1)
if *IndexFlag {
// create a separate index that's persisted
// this is located in $HOME/reminder.idx
// it will need to be exported afterwards
sidx := search.New("reminder", true)
fmt.Println("Indexing data")
go func() {
indexQuran(sidx, q)
indexNames(sidx, n)
indexHadith(sidx, b)
indexTafsir(sidx, q)
// done
close(indexed)
}()
} else {
close(indexed)
}
if *ExportFlag {
fmt.Println("Exporting index")
if err := idx.Export(); err != nil {
fmt.Println(err)
}
return
}
if *ImportFlag {
fmt.Println("Importing index")
if err := idx.Import(); err != nil {
fmt.Println(err)
}
}
if *WebFlag {
fmt.Println("Registering web handler")
// Register TOC handlers for API clients only
http.HandleFunc("/quran", func(w http.ResponseWriter, r *http.Request) {
if isAPIClient(r) {
content := q.TOC()
qhtml := app.RenderSimpleHTML("Quran", quran.Description, content)
w.Write([]byte(qhtml))
} else {
// Let SPA handle it
app.ServeWeb().ServeHTTP(w, r)
}
})
http.HandleFunc("/hadith", func(w http.ResponseWriter, r *http.Request) {
if isAPIClient(r) {
content := b.TOC()
hhtml := app.RenderSimpleHTML("Hadith", hadith.Description, content)
w.Write([]byte(hhtml))
} else {
// Let SPA handle it
app.ServeWeb().ServeHTTP(w, r)
}
})
http.HandleFunc("/names", func(w http.ResponseWriter, r *http.Request) {
if isAPIClient(r) {
content := n.TOC()
nhtml := app.RenderSimpleHTML("Names", names.Description, content)
w.Write([]byte(nhtml))
} else {
// Let SPA handle it
app.ServeWeb().ServeHTTP(w, r)
}
})
// Create smart handlers that serve lite content for API clients, SPA for browsers
http.HandleFunc("/quran/{id}", func(w http.ResponseWriter, r *http.Request) {
if isAPIClient(r) {
// Serve server-rendered HTML
id := r.PathValue("id")
if len(id) == 0 {
return
}
ch, _ := strconv.Atoi(id)
if ch < 1 || ch > 114 {
return
}
head := fmt.Sprintf("%d | Quran", ch)
qhtml := app.RenderSimpleHTML(head, "", q.Get(ch).HTML())
w.Write([]byte(qhtml))
} else {
// Serve SPA
app.ServeWeb().ServeHTTP(w, r)
}
})
http.HandleFunc("/hadith/{book}", func(w http.ResponseWriter, r *http.Request) {
if isAPIClient(r) {
book := r.PathValue("book")
if len(book) == 0 {
return
}
ch, _ := strconv.Atoi(book)
if ch < 1 || ch > len(b.Books) {
return
}
head := fmt.Sprintf("%d | Hadith", ch)
qhtml := app.RenderSimpleHTML(head, "", b.Get(ch).HTML())
w.Write([]byte(qhtml))
} else {
app.ServeWeb().ServeHTTP(w, r)
}
})
http.HandleFunc("/names/{id}", func(w http.ResponseWriter, r *http.Request) {
if isAPIClient(r) {
id := r.PathValue("id")
if len(id) == 0 {
return
}
name, _ := strconv.Atoi(id)
if name < 1 || name > len(*n) {
return
}
head := fmt.Sprintf("%d | Names", name)
qhtml := app.RenderSimpleHTML(head, "", n.Get(name).HTML())
w.Write([]byte(qhtml))
} else {
// Serve SPA
app.ServeWeb().ServeHTTP(w, r)
}
})
// Everything else goes to SPA
http.Handle("/", app.ServeWeb())
} else {
fmt.Println("Registering lite handler")
registerLiteRoutes(q, n, b, a)
}
http.HandleFunc("/api/quran", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(qjson))
})
http.HandleFunc("/api/quran/{chapter}", func(w http.ResponseWriter, r *http.Request) {
ch := r.PathValue("chapter")
if len(ch) == 0 {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("{}"))
return
}
chapter, _ := strconv.Atoi(ch)
if chapter < 1 || chapter > 114 {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("{}"))
return
}
b := q.Get(chapter).JSON()
w.Write(b)
})
http.HandleFunc("/api/quran/chapters", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
b, _ := json.Marshal(q.Index().Chapters)
w.Write(b)
})
http.HandleFunc("/api/quran/{chapter}/{verse}", func(w http.ResponseWriter, r *http.Request) {
ch := r.PathValue("chapter")
if len(ch) == 0 {
return
}
chapter, _ := strconv.Atoi(ch)
if chapter < 1 || chapter > 114 {
return
}
ve := r.PathValue("verse")
if len(ch) == 0 {
return
}
cc := q.Get(chapter)
verse, _ := strconv.Atoi(ve)
if verse < 1 || verse > len(cc.Verses) {
return
}
vee := cc.Verses[verse-1]
b := vee.JSON()
w.Write(b)
})
http.HandleFunc("/api/daily", func(w http.ResponseWriter, r *http.Request) {
// GET: today's archived daily (saved at midnight UTC)
today := time.Now().UTC().Format("2006-01-02")
mtx.RLock()
var resp interface{}
if entry, ok := dailyIndex[today]; ok {
resp = entry
} else {
// If today's archived daily doesn't exist yet, return the hourly updated content
message := "In the Name of Allah—the Most Beneficent, Most Merciful"
resp = map[string]interface{}{
"name": dailyName,
"hadith": dailyHadith,
"verse": dailyVerse,
"links": links,
"updated": dailyUpdated.Format(time.RFC3339),
"message": message,
"hijri": daily.Date().Display,
"date": today,
}
}
mtx.RUnlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
})
// Add /api/latest endpoint for the hourly updated reminder
http.HandleFunc("/api/latest", func(w http.ResponseWriter, r *http.Request) {
mtx.RLock()
verse := dailyVerse
hadith := dailyHadith
name := dailyName
message := dailyMessage
updated := dailyUpdated
currentLinks := links
mtx.RUnlock()
resp := map[string]interface{}{
"name": name,
"hadith": hadith,
"verse": verse,
"links": currentLinks,
"updated": updated.Format(time.RFC3339),
"message": message,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
})
http.HandleFunc("/api/daily/{date}", func(w http.ResponseWriter, r *http.Request) {
date := r.PathValue("date")
if len(date) == 0 {
date = time.Now().Format("2006-01-02")
}
mtx.RLock()
var resp interface{}
if entry, ok := dailyIndex[date]; ok {
resp = entry
} else {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(`{"error":"Not found"}`))
mtx.RUnlock()
return
}
mtx.RUnlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
})
// Add daily index API endpoint
http.HandleFunc("/api/daily/index", func(w http.ResponseWriter, r *http.Request) {
mtx.RLock()
b, _ := json.MarshalIndent(dailyIndex, "", " ")
mtx.RUnlock()
w.Header().Set("Content-Type", "application/json")
w.Write(b)
})
// RSS feed for daily content
http.HandleFunc("/rss", func(w http.ResponseWriter, r *http.Request) {
mtx.RLock()
defer mtx.RUnlock()
w.Header().Set("Content-Type", "application/rss+xml; charset=utf-8")
// Get all dates and sort them
var dates []string
for date := range dailyIndex {
if date == "latest" {
continue
}
dates = append(dates, date)
}
// Sort dates in descending order (newest first)
for i := 0; i < len(dates); i++ {
for j := i + 1; j < len(dates); j++ {
if dates[i] < dates[j] {
dates[i], dates[j] = dates[j], dates[i]
}
}
}
// Start RSS feed
fmt.Fprintf(w, `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Daily Reminder</title>
<link>https://reminder.dev</link>
<description>Daily reminders from the Quran, Hadith, and Names of Allah</description>
<language>en-us</language>
<lastBuildDate>%s</lastBuildDate>
<atom:link href="https://reminder.dev/rss" rel="self" type="application/rss+xml" />
`, time.Now().Format(time.RFC1123Z))
// Add items for each date (limit to most recent 30 days)
maxDays := 30
if len(dates) < maxDays {
maxDays = len(dates)
}
for i := 0; i < maxDays; i++ {
date := dates[i]
// Parse date for pubDate base
basePubDate := date
if t, err := time.Parse("2006-01-02", date); err == nil {
basePubDate = t.Format(time.RFC1123Z)
}
// First, add hourly reminders for this date (most recent first)
hourlyReminders := loadHourlyReminders(date)
// Process each hourly reminder in reverse order (newest first)
for i := len(hourlyReminders) - 1; i >= 0; i-- {
reminderData := hourlyReminders[i]
reminder, ok := reminderData.(map[string]interface{})
if !ok {
continue
}
// Get timestamp for pubDate
pubDate := basePubDate
if ts, ok := reminder["timestamp"].(string); ok {
if t, err := time.Parse(time.RFC3339, ts); err == nil {
pubDate = t.Format(time.RFC1123Z)
}
}
// Extract verse metadata
if verseMeta, ok := reminder["verse_meta"].(map[string]interface{}); ok {
chapterName, _ := verseMeta["chapter_name"].(string)
chapter, _ := verseMeta["chapter"].(float64)
verseStart, _ := verseMeta["verse_start"].(float64)
verseEnd, _ := verseMeta["verse_end"].(float64)
text, _ := verseMeta["text"].(string)
verseTitle := ""
if verseStart == verseEnd {
verseTitle = fmt.Sprintf("%s %d:%d", chapterName, int(chapter), int(verseStart))
} else {
verseTitle = fmt.Sprintf("%s %d:%d-%d", chapterName, int(chapter), int(verseStart), int(verseEnd))
}
verseLink := fmt.Sprintf("https://reminder.dev/quran/%d#%d", int(chapter), int(verseStart))
fmt.Fprintf(w, ` <item>
<title>%s</title>
<link>%s</link>
<guid>%s</guid>
<pubDate>%s</pubDate>
<description><![CDATA[%s]]></description>
</item>
`, verseTitle, verseLink, verseLink, pubDate, text)
}
// Extract hadith metadata
if hadithMeta, ok := reminder["hadith_meta"].(map[string]interface{}); ok {
bookName, _ := hadithMeta["book_name"].(string)
book, _ := hadithMeta["book"].(float64)
info, _ := hadithMeta["info"].(string)
text, _ := hadithMeta["text"].(string)
// Get number as string
number := "1"
if num, ok := hadithMeta["number"].(string); ok {
number = num
}
hadithTitle := fmt.Sprintf("%s - %s", bookName, info)
hadithLink := fmt.Sprintf("https://reminder.dev/hadith/%d#%s", int(book), number)
fmt.Fprintf(w, ` <item>
<title>%s</title>
<link>%s</link>
<guid>%s</guid>
<pubDate>%s</pubDate>
<description><![CDATA[%s]]></description>
</item>
`, hadithTitle, hadithLink, hadithLink, pubDate, text)
}
// Extract name metadata
if nameMeta, ok := reminder["name_meta"].(map[string]interface{}); ok {
number, _ := nameMeta["number"].(float64)
english, _ := nameMeta["english"].(string)
arabic, _ := nameMeta["arabic"].(string)
meaning, _ := nameMeta["meaning"].(string)
summary, _ := nameMeta["summary"].(string)
nameTitle := fmt.Sprintf("%s - %s - %s", english, arabic, meaning)
nameLink := fmt.Sprintf("https://reminder.dev/names/%d", int(number))
fmt.Fprintf(w, ` <item>
<title>%s</title>
<link>%s</link>
<guid>%s</guid>
<pubDate>%s</pubDate>
<description><![CDATA[%s]]></description>
</item>
`, nameTitle, nameLink, nameLink, pubDate, summary)
}
}
// Then, add daily summary at the end (for single daily consumption)
entry, hasDaily := dailyIndex[date]
if hasDaily {
entryMap, ok := entry.(map[string]interface{})
if ok {
verse := ""
hadith := ""
name := ""
hijri := ""
if v, ok := entryMap["verse"].(string); ok {
verse = v
}
if h, ok := entryMap["hadith"].(string); ok {
hadith = h
}
if n, ok := entryMap["name"].(string); ok {
name = n
}
if hj, ok := entryMap["hijri"].(string); ok {
hijri = hj
}
title := fmt.Sprintf("Daily Reminder - %s", date)
if hijri != "" {
title = fmt.Sprintf("Daily Reminder - %s (%s)", date, hijri)
}
// Combine all three into one item description
description := ""
if verse != "" {
description += "<h3>Verse</h3>\n" + verse + "\n\n"
}
if hadith != "" {