Repository navigation
Expand file tree
/
Copy pathService.qml
More file actions
2561 lines (2364 loc) · 98.1 KB
/
Copy pathService.qml
File metadata and controls
2561 lines (2364 loc) · 98.1 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
import QtQuick
import Quickshell
import Quickshell.Io
import "Model.js" as Model
import "SurahNames.js" as SurahData
Item {
id: root
property var shell: null
property var pluginRegistry: null
signal openTabRequested(string tabName)
signal searchRequested(string query) // open the UI on the surah tab with this query
readonly property string dataDir: Quickshell.env("HOME") + "/.local/state/omarchy/quran"
readonly property string bookmarksPath: dataDir + "/bookmarks.json"
readonly property string statePath: Quickshell.env("HOME") + "/.local/state/omarchy/settings/quran.json"
property var bookmarks: []
// mpv IPC socket lives in a private 0700 runtime dir (created on startup),
// never /tmp. Falls back under the cache root when XDG_RUNTIME_DIR is unset.
readonly property string mpvRuntimeDir: (function () {
var rt = Quickshell.env("XDG_RUNTIME_DIR");
if (rt && rt !== "")
return rt + "/mus-quran";
return Quickshell.env("HOME") + "/.cache/omarchy/quran/run";
})()
readonly property string mpvSocketPath: root.mpvRuntimeDir + "/mpv.sock"
// --- playback state (read by the bar widget + IPC) ---
readonly property var player: playerFacade
property string reciterId: Model.DEFAULT_RECITER
property int surahNumber: 1
property string playbackMode: Model.MODE_SINGLE
property int resumePosition: 0
// Last meaningful playback position. Only updated while media is loaded and
// not at EOF (Playing/Paused equivalents, explicit seeks, periodic saves) so
// a teardown/crash "stopped" state never persists 0 and wipes the resume
// point on shell restart.
property int savedPosition: 0
readonly property bool isPlaying: root.hasMedia && !root.mpvPaused && !root.mpvEof
readonly property bool isPaused: root.hasMedia && root.mpvPaused && !root.mpvEof
readonly property bool hasMedia: root.currentSource !== ""
// --- mpv engine state (mirrored from observed properties) ---
property string currentSource: "" // source the user asked to play
property string playbackSourceKind: "" // download | cache | stream
property var playbackSourceTarget: null // { id, n } for local validation failures
property var localValidationQueue: []
property var localValidationPlaybackTarget: null
property bool mpvPaused: true // observed `pause`
property bool mpvEof: false // true after end-file reason "eof"
property double mpvPositionMs: 0 // observed `time-pos` in ms
property double mpvDurationMs: 0 // observed `duration` in ms
property bool mpvSeekable: false // observed `seekable`
property bool mpvReady: false // socket connected + observes sent
property bool shuttingDown: false
property int mpvRestartCount: 0 // mpv relaunch attempts (crash recovery)
property int mpvConnectAttempts: 0 // socket connect attempts
property var mpvSock: null // live Socket instance
property var resumeLoadTarget: null // { positionMs } seek on file-loaded
property bool endHandled: true // EndOfMedia dedupe guard
property int mpvRequestId: 0
property string lastSource: "" // crash recovery: source to reload
property bool stateLoaded: false
property bool resumePending: false
// --- data ---
readonly property var surahs: SurahData.SURAHS
property var reciters: []
property string language: Model.DEFAULT_LANGUAGE
property var reciterStatus: ({}) // id -> prompt/failure history; not completion truth
property var downloadedSurahs: ({}) // "reciterId:n" -> true
property var downloadedCounts: ({}) // reciterId -> count derived from downloadedSurahs
property double catalogFetchedAt: 0
// --- errors / status ---
property string errorMessage: ""
property bool recitersLoading: false
property bool catalogError: false // last failure was the reciter fetch, not playback
property bool syncingBookmarks: false
property string syncStatusMessage: ""
property var pendingAyahSeek: null // { surah, ayah, totalVerses } fallback seek when timestamp_ms == 0
property bool searchingQuran: false
property string lastSearchQuery: ""
property string lastSearchMode: ""
property var semanticSearchResults: []
property var currentAyahData: null // { ayah_key, surah, ayah, arabic, translation, tafsir, juz, page, timestamp_ms }
property bool loadingAyahData: false
property bool loadingTafsir: false
property var ayahCache: ({}) // "surah:ayah" -> AyahDetailResponse
// --- download state (shared between widget + IPC) ---
property bool downloading: false
property int downloadDone: 0
property int downloadTotal: 114
property int downloadRevision: 0
property string downloadReciter: "" // reciter currently being downloaded
property var lastDownload: null // { id, surah } for retry after failure
// The audio engine is the Go quranproxyd daemon + quranctl CLI. Their paths
// are resolved once at startup (onToolProbe): a prebuilt binary in the
// plugin folder wins (from install.sh or manual placement), then the
// user-installed ~/.local/bin copy. When neither exists, setupRequired
// turns on and the engine actions fail with a "run install.sh" hint
// instead of silently breaking.
property string quranctlBinary: ""
property bool setupRequired: false
readonly property string cacheDir: Quickshell.env("HOME") + "/.cache/omarchy/quran"
// --- local range-caching proxy (quranproxyd) ---
// The daemon serves non-downloaded surahs at
// http://127.0.0.1:<proxyPort>/stream?tok=..&reciter=..&surah=.., validates
// and promotes fully-fetched files into dataDir, and reports progress as
// `promoted <id> <n>` on stdout. proxyReady turns on only after a valid
// handoff file (port + 32-hex token) has been read.
property string proxyBinary: ""
readonly property string proxyHandoffPath: root.mpvRuntimeDir + "/quranproxy.json"
property string proxySocketPath: root.mpvRuntimeDir + "/quranproxy.sock"
property int proxyPort: 0
property string proxyToken: ""
property bool proxyReady: false
property int proxySizeBytes: 0 // proxy-owned cache bytes (combined readout)
property int proxyFilesCount: 0 // proxy-owned cache files (cacheInfo)
property int proxyRestartCount: 0
// --- proxy control plane (unix socket) ---
// The daemon also listens on a unix socket in mpvRuntimeDir (announced as
// "sock" in the handoff) and serves raw HTTP over it — the plugin reads
// /cache/usage and POSTs /api/cache/clear through a QLocalSocket, the same
// primitive mpv uses. No curl, no extra processes.
property int cacheLimitMb: 500 // eviction budget (persisted; read by the daemon)
// Per-reciter:surah fetch cooldown. After a failed fetch or a forced
// playback error, re-fetches are refused for Model.COOLDOWN_MS so repeated
// IPC/retries cannot become a download storm.
property var fetchCooldowns: ({}) // "reciter:n" -> epoch ms when the window ends
property var pendingPlayback: null // { id, n, autoplay, positionMs } play after download completes
property var mushafPending: null // reciter id whose mushaf download was preempted by playback
// Persisted across shell restarts: { id, surah, list, pb? } describing the
// download that was in flight when the shell died, so the next instance
// resumes it (quranctl re-validates/skips finished files and resumes
// interrupted transfers). pb = playback request persisted while preempting a
// mushaf. Cleared on completion; one-shot resumed on startup.
property var downloadIntent: null
property bool downloadResumeTried: false
property string mpvMprisScript: "" // resolved mpv-mpris plugin path ("" = not found)
function _inCooldown(id, n) {
return Model.cooldownActive(root.fetchCooldowns, id + ":" + n, Date.now());
}
function _markFetchAttempt(id, n) {
Model.markCooldown(root.fetchCooldowns, id + ":" + n, Date.now());
}
function _clearCooldown(id, n) {
Model.clearCooldown(root.fetchCooldowns, id + ":" + n);
}
// Cap any string arriving over IPC before it is parsed or stored, so a
// hostile caller can't force unbounded memory/state growth.
function _capString(s, max) {
s = String(s || "");
return s.length > max ? s.substring(0, max) : s;
}
// current surah/reciter convenience lookups
readonly property var currentSurah: currentSurahFor(surahNumber)
readonly property var currentReciter: reciterFor(reciterId)
// `player` facade mirrors the old MediaPlayer surface (ms units) so the
// bar widget and IPC see identical values; only the backend changed.
QtObject {
id: playerFacade
readonly property int position: Math.round(root.mpvPositionMs)
readonly property int duration: Math.round(root.mpvDurationMs)
readonly property bool seekable: root.mpvSeekable && root.hasMedia
function downloadSurah(id, n) {
root.downloadSurah(id, n);
}
function downloadMushaf(id) {
root.downloadMushaf(id);
}
readonly property int downloadDone: root.downloadDone
readonly property int downloadTotal: root.downloadTotal
readonly property bool downloading: root.downloading
}
function currentSurahFor(n) {
if (!surahs || n < 1 || n > surahs.length)
return null;
return surahs[n - 1];
}
function reciterFor(id) {
if (!reciters)
return null;
for (var i = 0; i < reciters.length; i++) {
if (reciters[i].identifier === id)
return reciters[i];
}
return null;
}
function surahLabel(n) {
return Model.surahDisplayLabel(currentSurahFor(n), root.language);
}
function reciterLabel() {
return Model.reciterDisplayLabel(currentReciter, root.language);
}
function downloadedCount(id) {
return root.downloadedCounts[id] || 0;
}
function rebuildDownloadedCounts() {
var counts = {};
for (var key in root.downloadedSurahs) {
if (root.downloadedSurahs[key] !== true)
continue;
var sep = key.lastIndexOf(":");
if (sep <= 0)
continue;
var id = key.substring(0, sep);
counts[id] = (counts[id] || 0) + 1;
}
root.downloadedCounts = counts;
}
// Completion is derived from the per-surah map. reciterStatus is persisted
// history and may be stale if a file is removed or a prior batch was partial.
function isMushafDownloaded(id) {
return root.downloadedCount(id) === 114;
}
// Compatibility alias for callers that used the old coarse API.
function isDownloaded(id) {
return root.isMushafDownloaded(id);
}
function isSurahDownloaded(id, n) {
return root.downloadedSurahs[id + ":" + n] === true;
}
function markSurahDownloaded(id, n) {
var key = id + ":" + n;
var next = Object.assign({}, root.downloadedSurahs);
var wasDownloaded = next[key] === true;
next[key] = true;
root.downloadedSurahs = next;
if (!wasDownloaded) {
var counts = Object.assign({}, root.downloadedCounts);
counts[id] = (counts[id] || 0) + 1;
root.downloadedCounts = counts;
}
root.downloadRevision++;
root.saveState();
}
function invalidateSurahDownload(id, n) {
var key = id + ":" + n;
if (root.downloadedSurahs[key] !== true)
return;
var next = Object.assign({}, root.downloadedSurahs);
delete next[key];
root.downloadedSurahs = next;
var counts = Object.assign({}, root.downloadedCounts);
counts[id] = Math.max(0, (counts[id] || 0) - 1);
root.downloadedCounts = counts;
root.downloadRevision++;
root.saveState();
}
// true while a download is actively fetching this exact surah
function isSurahDownloading(id, n) {
return root.downloading && downloadProc.targetSurah === n && downloadProc.targetReciter === id;
}
// true while a download is actively fetching this reciter's mushaf
function isReciterDownloading(id) {
return root.downloading && downloadProc.targetSurah === 0 && downloadProc.targetReciter === id;
}
// First time a reciter is touched (no status recorded yet), the widget
// should prompt the user about downloading the full mushaf. Also re-prompt
// partially-downloaded reciters (even if previously declined) so the
// remaining surahs can be fetched in one click. A decline with zero
// downloads is respected.
function shouldPrompt(id) {
return !root.isMushafDownloaded(id) && root.reciterStatus[id] === undefined;
}
function hasAnyDownloaded(id) {
for (var i = 1; i <= 114; i++) {
if (root.downloadedSurahs[id + ":" + i])
return true;
}
return false;
}
// Count of this reciter's surahs not yet available offline.
function missingCount(id) {
var count = 0;
for (var i = 1; i <= 114; i++) {
if (!root.isSurahDownloaded(id, i))
count++;
}
return count;
}
function setReciterStatus(id, status) {
root.reciterStatus[id] = status;
root.saveState();
}
// --- mpv IPC --------------------------------------------------------------
// Send one JSON command to mpv. Dropped silently if not connected (the
// connect/recover machinery will re-issue playback state on connect).
function _mpvCommand(cmd) {
if (!root.mpvSock || !root.mpvSock.connected)
return;
root.mpvRequestId++;
root.mpvSock.write(JSON.stringify({
command: cmd,
request_id: root.mpvRequestId
}) + "\n");
root.mpvSock.flush();
}
function _observeMpv() {
root._mpvCommand(["observe_property", 1, "pause"]);
root._mpvCommand(["observe_property", 2, "time-pos"]);
root._mpvCommand(["observe_property", 3, "duration"]);
root._mpvCommand(["observe_property", 4, "eof-reached"]);
root._mpvCommand(["observe_property", 5, "seekable"]);
}
function onMpvLine(line) {
var obj = null;
try {
obj = JSON.parse(line);
} catch (e) {
obj = null;
}
if (!obj)
return;
if (obj.event === "property-change")
root.onMpvProperty(obj.name, obj.data);
else if (obj.event === "start-file")
root.onMpvStartFile();
else if (obj.event === "file-loaded")
root.onMpvFileLoaded();
else if (obj.event === "end-file")
root.onMpvEndFile(obj.reason);
}
function onMpvProperty(name, data) {
var v = (data === undefined) ? null : data;
if (name === "pause") {
root.mpvPaused = (v === true);
} else if (name === "time-pos") {
if (typeof v === "number" && isFinite(v)) {
root.mpvPositionMs = Math.round(v * 1000);
// Persist only while media is loaded and not at EOF — never from the
// idle/teardown nulls mpv sends after the file ends.
if (root.hasMedia && !root.mpvEof)
root.savedPosition = root.mpvPositionMs;
}
} else if (name === "duration") {
if (typeof v === "number" && isFinite(v) && v > 0) {
root.mpvDurationMs = Math.round(v * 1000);
if (root.pendingAyahSeek && root.pendingAyahSeek.surah === root.surahNumber && root.pendingAyahSeek.ayah > 1) {
var ps = root.pendingAyahSeek;
root.pendingAyahSeek = null;
var tv = ps.totalVerses > 0 ? ps.totalVerses : 100;
var targetMs = Math.round(((ps.ayah - 1) / tv) * root.mpvDurationMs);
if (targetMs > 0)
root._mpvCommand(["set_property", "time-pos", targetMs / 1000]);
}
}
} else if (name === "eof-reached") {
if (v === true)
root.mpvEof = true;
else if (v === false)
root.mpvEof = false;
} else if (name === "seekable") {
root.mpvSeekable = (v === true);
}
}
function onMpvStartFile() {
root.mpvEof = false;
root.endHandled = false;
root.errorMessage = "";
}
function onMpvFileLoaded() {
var t = root.resumeLoadTarget;
if (t && t.positionMs > 0) {
root.resumeLoadTarget = null;
root._mpvCommand(["set_property", "time-pos", t.positionMs / 1000]);
}
}
function onMpvEndFile(reason) {
if (reason === "eof") {
root.mpvEof = true;
root._handleEndOfMedia();
} else if (reason === "error") {
// A failed load (404 / dead link) must not read as "playing": pin pause
// so isPlaying goes false and the play button stops showing pause.
root.mpvPaused = true;
if (root.playbackSourceKind === "download" && root.playbackSourceTarget) {
root.invalidateSurahDownload(root.playbackSourceTarget.id, root.playbackSourceTarget.n);
} else if (root.playbackSourceKind === "stream" && root.playbackSourceTarget) {
// A proxy stream failed (origin/CDN problem, oversized file, dead
// link). The proxy arms its own 10 s cooldown (425) server-side;
// mirror it here so an aggressive retry loop cannot re-enter playback
// during the window.
root._markFetchAttempt(root.playbackSourceTarget.id, root.playbackSourceTarget.n);
}
root.errorMessage = Model.tr(root.language, "playbackFailed");
}
// "stop" / "quit" / "redirect" / "unknown" (e.g. switching surahs) ignored.
}
// --- playback control -----------------------------------------------------
function playSurah(reciterId_, surahNumber_) {
if (!Model.isValidSurahNumber(surahNumber_)) {
root.errorMessage = Model.tr(root.language, "invalidInput");
return;
}
root.reciterId = reciterId_ || root.reciterId;
root.surahNumber = surahNumber_;
root.resumePosition = 0;
root.savedPosition = 0;
root.errorMessage = "";
pendingTarget = {
id: root.reciterId,
n: root.surahNumber
};
surahDebounce.restart();
}
function localAudioPath(id, n) {
return root.dataDir + "/" + id + "/" + n + ".mp3";
}
// Playback source resolution (download-only backend). A surah that is not
// yet downloaded is streamed through the proxy (validating and promoting
// into the state dir) or fetched into the permanent state dir first, then
// played. mpv only ever receives local files or the proxy stream URL.
function _playSurahOrDownload(id, n, autoplay, positionMs) {
var shouldPlay = autoplay !== false;
var resumeMs = positionMs || 0;
if (root.isSurahDownloaded(id, n)) {
root.requestLocalValidation(id, n, shouldPlay, resumeMs);
return;
}
// Stream through the local range-caching proxy; it validates and promotes
// the surah to a permanent download on completion (no full-file download
// needed before playback starts).
if (root.proxyReady && root.proxyPort > 0) {
root._playStream(id, n, shouldPlay, resumeMs);
return;
}
// Everything else downloads to permanent storage, then plays. Playing a
// surah never waits on a full-mushaf download: the mushaf is preempted
// and resumes after the requested surah has played (see downloadProc).
if (root._inCooldown(id, n)) {
root.errorMessage = Model.tr(root.language, "playbackFailed");
return;
}
root.pendingPlayback = {
id: id,
n: n,
autoplay: shouldPlay,
positionMs: resumeMs
};
if (root.downloading) {
// A mushaf download (running, or still promoting cached files) is
// preempted for playback; other single-surah downloads just queue
// behind themselves.
if (downloadProc.targetSurah === 0) {
root.mushafPending = downloadProc.targetReciter;
// Persist the playback request with the intent so a shell restart
// mid-preempt resumes this surah's download (then the mushaf).
if (root.downloadIntent) {
var intent = Object.assign({}, root.downloadIntent);
intent.pb = {
id: id,
n: n,
autoplay: shouldPlay,
positionMs: resumeMs
};
root.downloadIntent = intent;
root.saveState();
}
if (downloadProc.running)
downloadProc.running = false;
}
return;
}
root._markFetchAttempt(id, n);
root.startExplicitDownload(id, n);
}
function _playNow(id, n) {
if (root.reciters.length > 0 && !Model.reciterExists(root.reciters, id)) {
root.errorMessage = Model.tr(root.language, "invalidInput");
return;
}
root._playSurahOrDownload(id, n, true, 0);
}
// Play a non-downloaded surah through the local proxy. The source URL is
// built only from already-validated inputs (see _proxyStreamUrl); mpv then
// streams it while the proxy fills its cache and, on completion, promotes
// the file to a permanent download (onProxyLine -> markSurahDownloaded).
function _playStream(id, n, autoplay, positionMs) {
var url = root._proxyStreamUrl(id, n);
if (url === "") {
root.errorMessage = Model.tr(root.language, "playbackFailed");
return;
}
root.reciterId = id;
root.surahNumber = n;
root.playbackSourceKind = "stream";
root.playbackSourceTarget = {
id: id,
n: n
};
root._setMprisMetadata(id, n);
root.resumePending = false;
root._mpvLoad(url, autoplay, positionMs);
root.saveState();
}
function requestLocalValidation(id, n, autoplay, positionMs) {
if (!root.quranctlBinary) {
root.errorMessage = Model.tr(root.language, "setupRequired");
return;
}
var target = {
id: id,
n: n,
autoplay: autoplay !== false,
positionMs: positionMs || 0
};
if (localValidationProc.running) {
localValidationPlaybackTarget = target;
return;
}
localValidationProc.mode = "playback";
localValidationProc.target = target;
// Deep media validation (size, MIME type, ffprobe) via the quranctl
// companion binary — fails closed when file(1) is missing. A non-zero
// exit means the local file is unusable.
localValidationProc.command = [root.quranctlBinary, "validate", root.localAudioPath(id, n)];
localValidationProc.running = true;
}
function queueDownloadedFileValidation() {
var queue = [];
for (var key in root.downloadedSurahs) {
if (root.downloadedSurahs[key] !== true)
continue;
var sep = key.lastIndexOf(":");
if (sep <= 0)
continue;
queue.push({
id: key.substring(0, sep),
n: parseInt(key.substring(sep + 1))
});
}
localValidationQueue = queue;
pumpLocalValidation();
}
function pumpLocalValidation() {
if (localValidationProc.running)
return;
var target = null;
var mode = "";
if (localValidationPlaybackTarget) {
target = localValidationPlaybackTarget;
localValidationPlaybackTarget = null;
mode = "playback";
} else if (localValidationQueue.length > 0) {
target = localValidationQueue.shift();
mode = "startup";
} else {
return;
}
localValidationProc.mode = mode;
localValidationProc.target = target;
localValidationProc.command = ["test", "-s", root.localAudioPath(target.id, target.n)];
localValidationProc.running = true;
}
function onLocalValidationExited(exitCode) {
var target = localValidationProc.target;
var mode = localValidationProc.mode;
localValidationProc.target = null;
localValidationProc.mode = "";
if (target && exitCode !== 0) {
root.invalidateSurahDownload(target.id, target.n);
if (mode === "playback") {
// Corrupt downloaded file: delete it from disk (fail-closed whitelist
// inside quranctl) and refuse re-fetches for the cooldown window so a
// bad CDN file can't trigger a re-download loop. A retry after the
// window re-fetches clean.
localRemoveProc.command = [root.quranctlBinary, "remove", "--state-dir", root.dataDir, target.id, String(target.n)];
localRemoveProc.running = true;
root._markFetchAttempt(target.id, target.n);
root.errorMessage = Model.tr(root.language, "playbackFailed");
}
} else if (target && mode === "playback") {
root.playbackSourceKind = "download";
root.playbackSourceTarget = target;
root.reciterId = target.id;
root.surahNumber = target.n;
root._mpvLoad(Model.localAudioUrl(root.dataDir, target.id, target.n), target.autoplay, target.positionMs);
root._setMprisMetadata(target.id, target.n);
root.resumePending = false;
root.saveState();
}
pumpLocalValidation();
}
// Set mpv's force-media-title and artist so mpv-mpris surfaces surah/reciter
// names instead of the raw CDN URL in playerctl metadata.
function _setMprisMetadata(id, n) {
var surah = root.currentSurahFor(n);
var reciter = root.reciterFor(id);
var title = surah ? Model.surahDisplayLabel(surah, root.language) : ("Surah " + n);
var artist = reciter ? Model.reciterDisplayLabel(reciter, root.language) : id;
root._mpvCommand(["set_property", "force-media-title", title]);
root._mpvCommand(["set_property", "audio-display-metadata/by-key/artist", artist]);
}
// Load a source into mpv. `loadfile` replaces whatever is playing, then the
// pause property pins the desired start state; resume positions are applied
// on `file-loaded` (mpv can't set time-pos before the file exists).
// SECURITY: mpv only ever receives local files OR this plugin's own
// loopback proxy stream URL (http://127.0.0.1:<proxyPort>/stream?... — the
// exact prefix + query we built in _proxyStreamUrl). Anything else — a
// hostile catalog URL, a tampered state file, a stray IPC call — is refused
// here; currentSource/lastSource are therefore always local or proxy, and
// every replay path (playPause, seek, crash recovery) inherits this guard.
function _mpvLoad(source, autoplay, positionMs) {
var isLocal = (typeof source === "string" && source.indexOf("file://") === 0);
var isProxyStream = (typeof source === "string" && root.proxyReady && root.proxyPort > 0 && source.indexOf("http://127.0.0.1:" + root.proxyPort + "/stream?") === 0);
if (!isLocal && !isProxyStream) {
root.errorMessage = Model.tr(root.language, "playbackFailed");
return;
}
root.currentSource = source;
root.lastSource = source;
root.mpvEof = false;
root.endHandled = false;
root.errorMessage = "";
root.mpvPaused = !autoplay;
root.resumeLoadTarget = (positionMs > 0) ? {
positionMs: positionMs
} : null;
root._mpvCommand(["loadfile", source]);
root._mpvCommand(["set_property", "pause", !autoplay]);
}
function playPause() {
if (!root.hasMedia) {
if (root.resumePending && root.resumePosition > 0) {
root._playNow(root.reciterId, root.surahNumber);
} else {
root.playSurah(root.reciterId, root.surahNumber);
}
return;
}
// A finished surah sits idle in mpv; toggling pause does nothing, so play
// replays it from the start like the old backend did.
if (root.mpvEof) {
root._mpvLoad(root.currentSource, true, 0);
root.saveState();
return;
}
if (root.isPlaying)
root._mpvCommand(["set_property", "pause", true]);
else
root._mpvCommand(["set_property", "pause", false]);
root.saveState();
}
function stopPlayback() {
root._mpvCommand(["stop"]);
root.currentSource = "";
root.lastSource = "";
root.mpvEof = false;
root.mpvPaused = true;
root.mpvPositionMs = 0;
root.mpvDurationMs = 0;
root.endHandled = true;
root.resumePosition = 0;
root.savedPosition = 0;
// An in-flight download keeps running (the file stays useful), but it
// must not start playing on completion.
root.pendingPlayback = null;
root.saveState();
}
function next() {
if (root.surahNumber < surahs.length)
root._playNow(root.reciterId, root.surahNumber + 1);
}
function previous() {
if (root.surahNumber > 1)
root._playNow(root.reciterId, root.surahNumber - 1);
}
function seek(ms) {
if (!root.hasMedia) {
root.savedPosition = Math.max(0, Math.round(ms));
root.saveState();
return;
}
var target = Math.max(0, Math.round(ms));
if (root.mpvEof) {
root._mpvLoad(root.currentSource, false, target);
root.saveState();
return;
}
root._mpvCommand(["set_property", "time-pos", target / 1000]);
root.savedPosition = target;
root.saveState();
}
function cycleMode() {
var i = Model.MODES.indexOf(root.playbackMode);
root.playbackMode = Model.MODES[(i + 1) % Model.MODES.length];
root.saveState();
}
function setLanguage(code) {
root.language = Model.isValidLanguage(code) ? code : Model.DEFAULT_LANGUAGE;
root.saveState();
}
function selectReciter(id) {
root.reciterId = id;
root.saveState();
}
// --- end of media (repeat-mode logic hooks here) ---
function _handleEndOfMedia() {
if (root.endHandled)
return;
root.endHandled = true;
root.resumePosition = 0;
root.savedPosition = 0;
root.saveState();
root._onEndOfMedia();
}
function _onEndOfMedia() {
var n = root.surahNumber;
var id = root.reciterId;
switch (root.playbackMode) {
case Model.MODE_REPEAT_ONE:
root._playNow(id, n);
break;
case Model.MODE_CONTINUE:
if (n < surahs.length)
root._playNow(id, n + 1);
break;
case Model.MODE_REPEAT_ALL:
root._playNow(id, (n % surahs.length) + 1);
break;
case Model.MODE_SINGLE:
default:
break;
}
}
// --- resume-on-startup (load paused at the saved position) ---
function _maybeResume() {
if (!root.stateLoaded || !root.mpvReady)
return;
if (root.lastSource !== "")
return;
if (!root.resumePending || root.resumePosition <= 0)
return;
root.resumePending = false;
root._playSurahOrDownload(root.reciterId, root.surahNumber, false, root.resumePosition);
}
// --- mpv lifecycle --------------------------------------------------------
// (Re)create the socket. Each attempt uses a fresh Socket so a failed
// connect is always retryable (QLocalSocket can't be re-targeted in place).
// The unix connect can complete synchronously, firing onConnectionStateChanged
// DURING createObject — before the assignment below runs. So connect is
// triggered manually AFTER root.mpvSock is set, or onMpvConnected would see
// a null socket and never issue the observe_property commands.
function _mpvConnect() {
if (root.shuttingDown || !mpvProc.running)
return;
if (root.mpvSock) {
root.mpvSock.connected = false;
root.mpvSock.destroy();
root.mpvSock = null;
}
root.mpvSock = mpvSocketComponent.createObject(root);
root.mpvSock.connected = true;
}
function _mpvRetryConnect() {
if (root.shuttingDown || !mpvProc.running)
return;
root.mpvConnectAttempts++;
if (root.mpvConnectAttempts > 30)
return;
root._mpvConnect();
}
function onMpvConnected() {
if (root.shuttingDown)
return;
root.mpvConnectAttempts = 0;
root.mpvRestartCount = 0;
root.mpvReady = true;
root._observeMpv();
root._mpvRecoverLast();
root._maybeResume();
}
// After mpv restarts, re-issue the last known playback state so a crash is
// transparent apart from a brief playback gap. Routed through _mpvLoad so
// the file://-only guard applies here too.
function _mpvRecoverLast() {
if (root.lastSource === "")
return;
var shouldPlay = root.isPlaying;
var pos = root.mpvPositionMs > 0 ? root.mpvPositionMs : root.savedPosition;
root._mpvLoad(root.lastSource, shouldPlay, pos);
}
function onMpvExited(exitCode) {
root.mpvReady = false;
mpvConnectTimer.stop();
if (root.mpvSock) {
root.mpvSock.connected = false;
root.mpvSock.destroy();
root.mpvSock = null;
}
if (root.shuttingDown)
return;
if (root.mpvRestartCount < 5) {
root.mpvRestartCount++;
mpvRestartTimer.restart();
} else {
root.errorMessage = Model.tr(root.language, "mpvMissing");
}
}
// --- downloads (explicit, state dir) ---------------------------------------
function downloadSurah(id, n) {
if (root.downloading || !Model.isValidSurahNumber(n))
return;
// Cooldown gate: a still-flagged corrupt file can be re-downloaded, but
// not more than once per reciter:surah inside the cooldown window — even
// via repeated IPC/retry calls.
if (root._inCooldown(id, n))
return;
root._markFetchAttempt(id, n);
root.startExplicitDownload(id, n);
}
function startExplicitDownload(id, n) {
if (!root.quranctlBinary) {
root.errorMessage = Model.tr(root.language, "setupRequired");
return;
}
root.downloading = true;
root.downloadReciter = id;
root.lastDownload = {
id: id,
surah: n
};
root.downloadDone = 0;
root.downloadTotal = 1;
root.errorMessage = "";
downloadProc.targetReciter = id;
downloadProc.targetSurah = n;
// Persist the active download so a shell restart resumes it.
root.downloadIntent = {
id: id,
surah: n,
list: [n]
};
root.saveState();
var reciter = root.reciterFor(id);
// quranctl shares the daemon's validation/fetch policy (same internal
// packages); it validates the origin URL in-process and reports the
// quranctl progress lines (download.sh-compatible) on stdout.
var cmd = [root.quranctlBinary, "download", id, String(n)];
if (reciter && reciter.server) {
cmd.push("--server");
cmd.push(reciter.server);
}
downloadProc.command = cmd;
downloadProc.running = true;
}
function downloadMushaf(id) {
if (root.downloading)
return;
// Only fetch surahs not already present offline. If your download flow
// still wants quranctl to re-validate/repair files that exist but are
// corrupt, this needs a different check than isSurahDownloaded() — see
// note below.
var work = [];
for (var i = 1; i <= 114; i++) {
if (!root.isSurahDownloaded(id, i))
work.push(i);
}
if (work.length === 0) {
// Already fully downloaded — nothing to do.
return;
}
root.downloading = true;
root.downloadReciter = id;
root.lastDownload = {
id: id,
surah: 0
};
downloadProc.targetReciter = id;
downloadProc.targetSurah = 0;
// Progress now reflects only the surahs actually being fetched.
root.downloadDone = 0;
root.downloadTotal = work.length;
root.errorMessage = "";
root.startMushafDownload(id, work);
}
// function downloadMushaf(id) {
// if (root.downloading)
// return;
// // Always validate the complete reciter set. The persisted downloaded flag
// // is only a cache of prior work and cannot prove that files still exist or
// // are intact. quranctl's complete() check skips valid files and fetches
// // only missing/corrupt ones.
// var work = [];
// for (var i = 1; i <= 114; i++)
// work.push(i);
// root.downloading = true;
// root.downloadReciter = id;
// root.lastDownload = {
// id: id,
// surah: 0
// };
// // Mark the in-flight target up front so playback can preempt this mushaf
// // before the process has actually started.
// downloadProc.targetReciter = id;
// downloadProc.targetSurah = 0;
// // Progress reflects validation/download of all 114 surahs.
// root.downloadDone = 0;
// root.downloadTotal = 114;
// root.errorMessage = "";
// root.startMushafDownload(id, work);
// }
function startMushafDownload(id, list) {
if (!root.quranctlBinary) {
root.errorMessage = Model.tr(root.language, "setupRequired");
return;
}
// Playback preempted this mushaf while its cached files were being
// promoted (the process never started): don't launch it now — serve the
// pending playback download first; downloadProc.onExited resumes the
// mushaf once nothing else is queued.
if (root.mushafPending === id) {
var pb = root.pendingPlayback;
if (pb) {
root._markFetchAttempt(pb.id, pb.n);
root.startExplicitDownload(pb.id, pb.n);