-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdataloader.lua
More file actions
1564 lines (1438 loc) · 54 KB
/
dataloader.lua
File metadata and controls
1564 lines (1438 loc) · 54 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
local DataStorage = require("datastorage")
local lfs = require("libs/libkoreader-lfs")
local logger = require("logger")
local ffiutil = require("ffi/util")
local DataLoader = {}
local DASHBOARD_CACHE_TTL_SEC = 8
local function cache_dashboard_payload(payload)
DataLoader._dashboard_cache = {
ts = os.time(),
payload = payload,
}
return payload
end
local function build_hourly_slots()
local slots = {}
for hour = 0, 23 do
slots[hour] = { sessions = 0, duration_sec = 0 }
end
return slots
end
local function append_hourly_series(target, slots)
for hour = 0, 23 do
local v = slots[hour] or { sessions = 0, duration_sec = 0 }
table.insert(target, {
hour = hour,
sessions = tonumber(v.sessions) or 0,
duration_sec = tonumber(v.duration_sec) or 0,
})
end
end
local function parse_date_ymd(s)
if type(s) ~= "string" then return nil end
local y, m, d = s:match("^(%d%d%d%d)%-(%d%d)%-(%d%d)$")
if not y then return nil end
return os.time({
year = tonumber(y),
month = tonumber(m),
day = tonumber(d),
hour = 12, min = 0, sec = 0,
})
end
local function day_diff(a, b)
if not a or not b then return nil end
return math.floor((a - b) / 86400 + 0.5)
end
local function sort_desc_num(key)
return function(a, b)
return (tonumber(a[key]) or 0) > (tonumber(b[key]) or 0)
end
end
local function sanitize_title_for_match(s)
s = tostring(s or "")
s = s:lower()
-- Normalize common full-width/CJK punctuation to improve matching for Chinese titles.
s = s:gsub(":", ":")
s = s:gsub(",", ",")
s = s:gsub("。", ".")
s = s:gsub(";", ";")
s = s:gsub("!", "!")
s = s:gsub("?", "?")
s = s:gsub("(", "(")
s = s:gsub(")", ")")
s = s:gsub("【", "[")
s = s:gsub("】", "]")
s = s:gsub("《", " ")
s = s:gsub("》", " ")
s = s:gsub("、", " ")
s = s:gsub(" ", " ")
s = s:gsub("z%-library", " ")
s = s:gsub("1lib%.sk", " ")
s = s:gsub("z%-lib%.sk", " ")
s = s:gsub("zlibrary%.sk", " ")
s = s:gsub("%b()", " ")
s = s:gsub("%b[]", " ")
s = s:gsub("[\226\128\152\226\128\153\226\128\156\226\128\157]", "") -- ‘ ’ “ ”
s = s:gsub("[\226\128\147\226\128\148]", " ") -- – —
s = s:gsub("[_%-%.,:;!%?\"'`•]+", " ")
s = s:gsub("%s+", " ")
s = s:gsub("^%s+", "")
s = s:gsub("%s+$", "")
return s
end
local function score_book_match(book, candidate)
local bt = sanitize_title_for_match(book.title)
local ct = sanitize_title_for_match(candidate.title)
if bt == "" or ct == "" then return 0 end
local bt_compact = bt:gsub("%s+", "")
local ct_compact = ct:gsub("%s+", "")
local score = 0
if bt == ct then score = score + 100 end
if ct:find(bt, 1, true) or bt:find(ct, 1, true) then score = score + 60 end
if bt_compact ~= "" and ct_compact ~= "" then
if bt_compact == ct_compact then score = score + 80 end
if ct_compact:find(bt_compact, 1, true) or bt_compact:find(ct_compact, 1, true) then
score = score + 40
end
end
local ba = sanitize_title_for_match(book.authors)
local ca = sanitize_title_for_match(candidate.authors)
if ba ~= "" and ca ~= "" then
local ba_compact = ba:gsub("%s+", "")
local ca_compact = ca:gsub("%s+", "")
if ba == ca then score = score + 30 end
if ca:find(ba, 1, true) or ba:find(ca, 1, true) then score = score + 15 end
if ba_compact ~= "" and ca_compact ~= "" then
if ba_compact == ca_compact then score = score + 20 end
if ca_compact:find(ba_compact, 1, true) or ba_compact:find(ca_compact, 1, true) then
score = score + 10
end
end
end
if (book.pages or 0) > 0 and (candidate.pages or 0) > 0 then
if tonumber(book.pages) == tonumber(candidate.pages) then
score = score + 20
end
end
return score
end
local function image_ctype_from_path(path)
local ext = tostring(path or ""):lower():match("%.([^.]+)$") or ""
if ext == "jpg" or ext == "jpeg" then return "image/jpeg" end
if ext == "png" then return "image/png" end
if ext == "webp" then return "image/webp" end
if ext == "gif" then return "image/gif" end
return nil
end
local function slugify_cover_key(s)
s = tostring(s or ""):lower()
s = s:gsub("[/%\\:%*%?\"<>|]", " ")
s = s:gsub("%s+", "-")
s = s:gsub("%-+", "-")
s = s:gsub("^%-+", "")
s = s:gsub("%-+$", "")
return s
end
local function stable_cover_hash_key(s)
s = tostring(s or "")
local h = 0
for i = 1, #s do
h = (h * 131 + s:byte(i)) % 4294967296
end
return string.format("f-%08x", h)
end
local function trim_string(s)
s = tostring(s or "")
s = s:gsub("^%s+", "")
s = s:gsub("%s+$", "")
return s
end
local function compute_book_ref(doc_path, md5)
local md5v = trim_string(md5)
if md5v ~= "" then
return md5v, "md5"
end
local path_key = stable_cover_hash_key(trim_string(doc_path))
return "path-" .. path_key, "pathhash"
end
local function normalize_book_ref(book_ref)
local ref = trim_string(book_ref)
if ref == "" then return nil end
return ref
end
local function normalize_cover_query(s)
s = tostring(s or "")
s = s:gsub("^%s+", "")
s = s:gsub("%s+$", "")
s = s:gsub("%b()", " ")
s = s:gsub("%b[]", " ")
s = s:gsub("%b{}", " ")
s = s:gsub("[||].*$", " ")
s = s:gsub("%f[%a]novel chapters?%f[%A].*$", " ")
s = s:gsub("%f[%a]light novel pub%f[%A].*$", " ")
s = s:gsub("%f[%a]z%-library%f[%A].*$", " ")
s = s:gsub("%f[%a]zlibrary%f[%A].*$", " ")
s = s:gsub("%f[%a]1lib%.sk%f[%A].*$", " ")
s = s:gsub("%f[%a]z%-lib%.sk%f[%A].*$", " ")
s = s:gsub("[%-%._]+", " ")
s = s:gsub("%s+", " ")
s = s:gsub("^%s+", "")
s = s:gsub("%s+$", "")
return s
end
local function add_unique_path(paths, path)
if not path or path == "" then return end
for _, existing in ipairs(paths) do
if existing == path then return end
end
table.insert(paths, path)
end
local function find_existing_path(paths)
for _, p in ipairs(paths) do
if lfs.attributes(p, "mode") == "file" or lfs.attributes(p, "mode") == "directory" then
return p
end
end
return nil
end
local function each_parent_dir(start_dir, fn, max_depth)
local dir = start_dir
local depth = 0
local limit = max_depth or 8
while dir and dir ~= "" and depth < limit do
fn(dir)
local parent = dir:match("^(.*)/[^/]+$")
if not parent or parent == dir then break end
dir = parent
depth = depth + 1
end
end
local function resolve_doc_path(doc_path)
if not doc_path or doc_path == "" then return doc_path end
if lfs.attributes(doc_path, "mode") then return doc_path end
local suffix = doc_path:match("^/mnt/[^/]+/documents(.*)$")
if suffix then
local cwd = lfs.currentdir() or ""
local candidates = {}
each_parent_dir(cwd, function(dir)
add_unique_path(candidates, dir .. "/documents" .. suffix)
add_unique_path(candidates, dir .. "/koreader/documents" .. suffix)
end, 10)
local resolved = find_existing_path(candidates)
if resolved then return resolved end
end
return doc_path
end
local function resolve_statistics_db_path()
local candidates = {}
local settings_dir = DataStorage:getSettingsDir()
if settings_dir and settings_dir ~= "" then
add_unique_path(candidates, settings_dir .. "/statistics.sqlite3")
end
local data_dir = DataStorage:getDataDir()
if data_dir and data_dir ~= "" then
add_unique_path(candidates, data_dir .. "/statistics.sqlite3")
add_unique_path(candidates, data_dir .. "/settings/statistics.sqlite3")
end
local cwd = lfs.currentdir() or ""
each_parent_dir(cwd, function(dir)
add_unique_path(candidates, dir .. "/settings/statistics.sqlite3")
add_unique_path(candidates, dir .. "/koreader/settings/statistics.sqlite3")
add_unique_path(candidates, dir .. "/statistics.sqlite3")
end, 10)
return find_existing_path(candidates) or (candidates[1] or "statistics.sqlite3")
end
local function new_dashboard_payload()
return {
summary = {
total_books = 0,
reading_books = 0,
finished_books = 0,
total_read_time_sec = 0,
total_read_pages = 0,
total_highlights = 0,
total_notes = 0,
active_days_90d = 0,
best_streak_days = 0,
current_streak_days = 0,
last_read_date = "",
},
kpis = {
last_7_days_time_sec = 0,
last_30_days_time_sec = 0,
avg_daily_time_30d_sec = 0,
longest_day_sec = 0,
books_touched_30d = 0,
books_touched_90d = 0,
books_touched_180d = 0,
books_touched_365d = 0,
},
series = {
daily_90d = {},
daily_180d = {},
daily_365d = {},
monthly_12m = {},
weekday_avg = {},
hourly_activity = {},
hourly_activity_30d = {},
hourly_activity_90d = {},
hourly_activity_180d = {},
hourly_activity_365d = {},
},
calendar = {
days = {},
legend = { max_daily_sec_90d = 0 },
},
top_books = {
by_time = {},
by_pages = {},
by_time_30d = {},
by_time_90d = {},
by_time_180d = {},
by_time_365d = {},
by_pages_30d = {},
by_pages_90d = {},
by_pages_180d = {},
by_pages_365d = {},
},
}
end
function DataLoader:getHistoryItems()
local history_file = ffiutil.joinPath(DataStorage:getDataDir(), "history.lua")
local ok, history = pcall(dofile, history_file)
if not ok or type(history) ~= "table" then
logger.warn("KoDashboard: Failed to load history.lua")
return {}
end
return history
end
function DataLoader:findHistoryItemByRef(book_ref)
local want = normalize_book_ref(book_ref)
if not want then return nil end
local history = self:getHistoryItems()
for i, item in ipairs(history) do
if item and item.file then
local sdr_data = self:loadSidecar(item.file)
local md5 = sdr_data and sdr_data.partial_md5_checksum or nil
local ref, id_type = compute_book_ref(item.file, md5)
if ref == want then
return item, i, sdr_data, ref, id_type
end
end
end
return nil
end
function DataLoader:getBooks()
local history = self:getHistoryItems()
local books = {}
for i, item in ipairs(history) do
local doc_path = item.file
local resolved_doc_path = resolve_doc_path(doc_path)
if lfs.attributes(resolved_doc_path, "mode") ~= "file" then
-- Skip stale history entries whose source file no longer exists.
goto continue
end
local sdr_data = self:loadSidecar(doc_path)
local title = doc_path:match("([^/]+)%.[^.]+$") or doc_path
local authors = ""
local doc_pages = 0
local percent = 0
local language = ""
local status = "reading"
local last_open = ""
local highlights_count = 0
local notes_count = 0
local md5 = nil
if sdr_data then
if sdr_data.doc_props then
title = sdr_data.doc_props.title or title
authors = sdr_data.doc_props.authors or ""
language = sdr_data.doc_props.language or ""
end
md5 = sdr_data.partial_md5_checksum
doc_pages = sdr_data.doc_pages or 0
percent = sdr_data.percent_finished or 0
if sdr_data.summary then
status = sdr_data.summary.status or "reading"
last_open = sdr_data.summary.modified or ""
end
local ann_count = 0
local note_count = 0
if sdr_data.annotations then
for _, ann in ipairs(sdr_data.annotations) do
if ann.text and ann.text ~= "" then
ann_count = ann_count + 1
end
if ann.note then
note_count = note_count + 1
end
end
end
highlights_count = ann_count
notes_count = note_count
end
local book_ref, id_type = compute_book_ref(doc_path, md5)
local cover_info = self:getCoverInfoForPath(doc_path, sdr_data)
table.insert(books, {
id = book_ref,
legacy_index = i,
id_type = id_type,
file = doc_path,
title = title,
authors = authors,
language = language,
pages = doc_pages,
percent = math.floor(percent * 1000) / 10,
status = status,
last_open = last_open,
last_open_ts = item.time,
highlights = highlights_count,
notes = notes_count,
md5 = md5,
cover_available = cover_info ~= nil,
cover_content_type = cover_info and cover_info.content_type or nil,
})
::continue::
end
return books
end
function DataLoader:getAnnotations(book_ref)
local item, _, sdr_data = self:findHistoryItemByRef(book_ref)
if not item then return nil end
if not sdr_data then return {} end
local raw = sdr_data.annotations or {}
local annotations = {}
for _, ann in ipairs(raw) do
table.insert(annotations, {
text = ann.text or "",
note = ann.note,
chapter = ann.chapter or "",
page = ann.page,
pageno = ann.pageno,
pos0 = ann.pos0,
pos1 = ann.pos1,
datetime = ann.datetime or "",
datetime_updated = ann.datetime_updated,
color = ann.color or "yellow",
drawer = ann.drawer or "lighten",
total_pages = ann.total_pages or sdr_data.doc_pages,
})
end
return annotations, sdr_data.doc_props
end
function DataLoader:getBookTimeline(book_ref)
local books = self:getBooks()
local book = nil
for _, b in ipairs(books) do
if b and tostring(b.id) == tostring(book_ref) then
book = b
break
end
end
if not book then return nil end
local db_path = resolve_statistics_db_path()
if lfs.attributes(db_path, "mode") ~= "file" then
return {
book_id = book.id,
book_ref = book.id,
title = book.title,
authors = book.authors,
stats_book_id = nil,
sessions = {},
total = 0,
}
end
local load_ok, SQ3 = pcall(require, "lua-ljsqlite3/init")
if not load_ok then
logger.warn("KoDashboard: Failed to load lua-ljsqlite3:", SQ3)
return {
book_id = book.id,
book_ref = book.id,
title = book.title,
authors = book.authors,
stats_book_id = nil,
sessions = {},
total = 0,
}
end
local open_ok, conn = pcall(SQ3.open, db_path)
if not open_ok then
logger.warn("KoDashboard: Failed to open statistics db:", conn)
return {
book_id = book.id,
book_ref = book.id,
title = book.title,
authors = book.authors,
stats_book_id = nil,
sessions = {},
total = 0,
}
end
local has_book = false
local has_page_stat = false
pcall(function()
local c1 = conn:rowexec("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='book'")
has_book = c1 and tonumber(c1) > 0
local c2 = conn:rowexec("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='page_stat_data'")
has_page_stat = c2 and tonumber(c2) > 0
end)
if not has_book or not has_page_stat then
conn:close()
return {
book_id = book.id,
book_ref = book.id,
title = book.title,
authors = book.authors,
stats_book_id = nil,
sessions = {},
total = 0,
}
end
local matched = nil
local best_score = -1
if book.md5 and tostring(book.md5) ~= "" then
pcall(function()
local stmt = conn:prepare([[
SELECT id, title, authors, pages, last_open
FROM book
WHERE md5 = ?
LIMIT 1
]])
local row = stmt:reset():bind(tostring(book.md5)):step()
if row then
matched = {
id = tonumber(row[1]) or 0,
title = row[2] and tostring(row[2]) or "",
authors = row[3] and tostring(row[3]) or "",
pages = tonumber(row[4]) or 0,
last_open = tonumber(row[5]) or 0,
}
best_score = 999
end
stmt:close()
end)
end
if not matched then pcall(function()
local stmt = conn:prepare([[
SELECT id, title, authors, pages, last_open
FROM book
ORDER BY last_open DESC
]])
local row = stmt:step()
while row do
local candidate = {
id = tonumber(row[1]) or 0,
title = row[2] and tostring(row[2]) or "",
authors = row[3] and tostring(row[3]) or "",
pages = tonumber(row[4]) or 0,
last_open = tonumber(row[5]) or 0,
}
local score = score_book_match(book, candidate)
if score > best_score then
best_score = score
matched = candidate
end
row = stmt:step()
end
stmt:close()
end) end
if not matched or best_score < 40 then
conn:close()
return {
book_id = book.id,
book_ref = book.id,
title = book.title,
authors = book.authors,
stats_book_id = nil,
sessions = {},
total = 0,
}
end
local sessions = {}
local daily = {}
local total_sessions = 0
local first_session = nil
local last_session = nil
local function row_to_session(row)
local start_ts = tonumber(row[2]) or 0
return {
page = tonumber(row[1]) or 0,
start_time = start_ts,
duration = tonumber(row[3]) or 0,
total_pages = tonumber(row[4]) or 0,
date = start_ts > 0 and os.date("%Y-%m-%d", start_ts) or "",
time = start_ts > 0 and os.date("%H:%M", start_ts) or "",
}
end
pcall(function()
local stmt = conn:prepare([[
SELECT COUNT(*)
FROM page_stat_data
WHERE id_book = ?
AND start_time > 0
]])
local row = stmt:reset():bind(matched.id):step()
if row then
total_sessions = tonumber(row[1]) or 0
end
stmt:close()
end)
pcall(function()
local stmt = conn:prepare([[
SELECT page, start_time, duration, total_pages
FROM page_stat_data
WHERE id_book = ?
AND start_time > 0
ORDER BY start_time ASC
LIMIT 1
]])
local row = stmt:reset():bind(matched.id):step()
if row then first_session = row_to_session(row) end
stmt:close()
end)
pcall(function()
local stmt = conn:prepare([[
SELECT page, start_time, duration, total_pages
FROM page_stat_data
WHERE id_book = ?
AND start_time > 0
ORDER BY start_time DESC
LIMIT 1
]])
local row = stmt:reset():bind(matched.id):step()
if row then last_session = row_to_session(row) end
stmt:close()
end)
pcall(function()
local stmt = conn:prepare([[
SELECT page, start_time, duration, total_pages
FROM page_stat_data
WHERE id_book = ?
AND start_time > 0
ORDER BY start_time DESC
LIMIT 200
]])
local row = stmt:reset():bind(matched.id):step()
while row do
table.insert(sessions, row_to_session(row))
row = stmt:step()
end
stmt:close()
end)
pcall(function()
local stmt = conn:prepare([[
SELECT date(start_time, 'unixepoch', 'localtime') as day,
SUM(duration) as total_duration,
COUNT(*) as session_count,
COUNT(DISTINCT page) as pages_touched
FROM page_stat_data
WHERE id_book = ?
AND start_time > 0
GROUP BY day
ORDER BY day DESC
LIMIT 420
]])
local row = stmt:reset():bind(matched.id):step()
while row do
table.insert(daily, {
date = row[1] and tostring(row[1]) or "",
duration_sec = tonumber(row[2]) or 0,
sessions = tonumber(row[3]) or 0,
pages = tonumber(row[4]) or 0,
})
row = stmt:step()
end
stmt:close()
end)
conn:close()
return {
book_id = book.id,
book_ref = book.id,
title = book.title,
authors = book.authors,
stats_book_id = matched.id,
matched_title = matched.title,
matched_authors = matched.authors,
sessions = sessions,
first_session = first_session,
last_session = last_session,
daily = daily,
total = total_sessions > 0 and total_sessions or #sessions,
}
end
function DataLoader:getCoverInfoForPath(doc_path, sdr_data)
if not doc_path then return nil end
doc_path = resolve_doc_path(doc_path)
local candidates = {}
local function add_candidate(p)
if not p or p == "" then return end
for _, c in ipairs(candidates) do
if c == p then return end
end
table.insert(candidates, p)
end
sdr_data = sdr_data or self:loadSidecar(doc_path)
-- Independent cover storage: <KOReader data>/kodashboard/covers/
-- Naming priority: md5.* -> title--authors.* -> filename.*
local data_dir = DataStorage:getDataDir()
local cover_dir = data_dir and (data_dir .. "/kodashboard/covers") or nil
if cover_dir and lfs.attributes(cover_dir, "mode") == "directory" then
local filename = doc_path:match("([^/]+)$") or ""
local stem = filename:match("(.+)%.[^.]+$") or filename
local keys = {}
local md5_key = nil
if sdr_data and sdr_data.partial_md5_checksum and sdr_data.partial_md5_checksum ~= "" then
md5_key = tostring(sdr_data.partial_md5_checksum)
table.insert(keys, md5_key)
end
if sdr_data and sdr_data.doc_props then
local raw_title = sdr_data.doc_props.title or ""
local raw_authors = sdr_data.doc_props.authors or ""
local title_key = slugify_cover_key(raw_title)
local authors_key = slugify_cover_key(raw_authors)
local norm_title_key = slugify_cover_key(normalize_cover_query(raw_title))
local norm_authors_key = slugify_cover_key(normalize_cover_query(raw_authors))
if title_key ~= "" then
table.insert(keys, title_key)
if authors_key ~= "" then
table.insert(keys, title_key .. "--" .. authors_key)
end
end
if norm_title_key ~= "" then
table.insert(keys, norm_title_key)
if norm_authors_key ~= "" then
table.insert(keys, norm_title_key .. "--" .. norm_authors_key)
end
end
end
local stem_key = slugify_cover_key(stem)
if stem_key ~= "" then table.insert(keys, stem_key) end
local norm_stem_key = slugify_cover_key(normalize_cover_query(stem))
if norm_stem_key ~= "" then table.insert(keys, norm_stem_key) end
if stem ~= "" then table.insert(keys, stable_cover_hash_key(stem)) end
-- KoInsight-style lookup: any file that starts with md5
if md5_key then
pcall(function()
for entry in lfs.dir(cover_dir) do
if entry ~= "." and entry ~= ".." and entry:sub(1, #md5_key) == md5_key then
add_candidate(cover_dir .. "/" .. entry)
end
end
end)
end
for _, key in ipairs(keys) do
add_candidate(cover_dir .. "/" .. key .. ".jpg")
add_candidate(cover_dir .. "/" .. key .. ".jpeg")
add_candidate(cover_dir .. "/" .. key .. ".png")
add_candidate(cover_dir .. "/" .. key .. ".webp")
end
end
local sidecar_dirs = self:getSidecarCandidates(doc_path)
for _, sdr_dir in ipairs(sidecar_dirs) do
if lfs.attributes(sdr_dir, "mode") == "directory" then
add_candidate(sdr_dir .. "/cover.jpg")
add_candidate(sdr_dir .. "/cover.jpeg")
add_candidate(sdr_dir .. "/cover.png")
add_candidate(sdr_dir .. "/custom_cover.jpg")
add_candidate(sdr_dir .. "/custom_cover.png")
pcall(function()
for entry in lfs.dir(sdr_dir) do
if entry ~= "." and entry ~= ".." then
local lower = entry:lower()
if lower:match("^cover.*%.jpe?g$") or lower:match("^cover.*%.png$") or lower:match("^cover.*%.webp$") then
add_candidate(sdr_dir .. "/" .. entry)
end
end
end
end)
end
end
local dir = doc_path:match("^(.+)/[^/]+$") or ""
local filename = doc_path:match("([^/]+)$") or ""
local stem = filename:match("(.+)%.[^.]+$") or filename
if dir ~= "" then
add_candidate(dir .. "/" .. stem .. ".jpg")
add_candidate(dir .. "/" .. stem .. ".jpeg")
add_candidate(dir .. "/" .. stem .. ".png")
add_candidate(dir .. "/" .. stem .. ".webp")
add_candidate(dir .. "/cover.jpg")
add_candidate(dir .. "/cover.png")
end
for _, p in ipairs(candidates) do
if lfs.attributes(p, "mode") == "file" then
local ctype = image_ctype_from_path(p)
if ctype then
return { path = p, content_type = ctype }
end
end
end
return nil
end
function DataLoader:getBookCover(book_ref)
local item, _, sdr_data = self:findHistoryItemByRef(book_ref)
if not item or not item.file then return nil end
return self:getCoverInfoForPath(item.file, sdr_data)
end
function DataLoader:getAllHighlights()
local history = self:getHistoryItems()
local all = {}
for i, item in ipairs(history) do
local resolved_doc_path = resolve_doc_path(item.file)
if lfs.attributes(resolved_doc_path, "mode") ~= "file" then
goto continue
end
local sdr_data = self:loadSidecar(item.file)
if sdr_data and sdr_data.annotations then
local title = "Unknown"
local authors = ""
if sdr_data.doc_props then
title = sdr_data.doc_props.title or title
authors = sdr_data.doc_props.authors or ""
end
local book_md5 = sdr_data.partial_md5_checksum or ""
local book_ref, _ = compute_book_ref(item.file, book_md5)
for _, ann in ipairs(sdr_data.annotations) do
if ann.text and ann.text ~= "" then
table.insert(all, {
book_id = i,
book_ref = book_ref,
book_md5 = book_md5,
book_title = title,
book_authors = authors,
text = ann.text,
note = ann.note,
chapter = ann.chapter or "",
page = ann.page,
pageno = ann.pageno,
pos0 = ann.pos0,
pos1 = ann.pos1,
datetime = ann.datetime or "",
datetime_updated = ann.datetime_updated,
color = ann.color or "yellow",
drawer = ann.drawer or "lighten",
total_pages = ann.total_pages or sdr_data.doc_pages,
})
end
end
end
::continue::
end
return all
end
function DataLoader:getStats()
local db_path = resolve_statistics_db_path()
if lfs.attributes(db_path, "mode") ~= "file" then
return { books = {}, daily = {} }
end
local load_ok, SQ3 = pcall(require, "lua-ljsqlite3/init")
if not load_ok then
logger.warn("KoDashboard: Failed to load lua-ljsqlite3:", SQ3)
return { books = {}, daily = {} }
end
local open_ok, conn = pcall(SQ3.open, db_path)
if not open_ok then
logger.warn("KoDashboard: Failed to open statistics db:", conn)
return { books = {}, daily = {} }
end
local book_stats = {}
local has_book = false
pcall(function()
local check = conn:rowexec("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='book'")
has_book = check and tonumber(check) > 0
end)
if has_book then
pcall(function()
local stmt = conn:prepare("SELECT id, title, authors, total_read_time, total_read_pages, pages, last_open, md5 FROM book ORDER BY last_open DESC")
local row = stmt:step()
while row do
table.insert(book_stats, {
id = tonumber(row[1]) or 0,
title = row[2] and tostring(row[2]) or "",
authors = row[3] and tostring(row[3]) or "",
total_read_time = tonumber(row[4]) or 0,
total_read_pages = tonumber(row[5]) or 0,
pages = tonumber(row[6]) or 0,
last_open = tonumber(row[7]) or 0,
md5 = row[8] and tostring(row[8]) or "",
})
row = stmt:step()
end
stmt:close()
end)
end
local daily_stats = {}
local has_page_stat = false
pcall(function()
local check = conn:rowexec("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='page_stat_data'")
has_page_stat = check and tonumber(check) > 0
end)
if has_page_stat then
pcall(function()
local stmt = conn:prepare([[
SELECT date(start_time, 'unixepoch', 'localtime') as day,
SUM(duration) as total_duration,
COUNT(DISTINCT id_book) as books_count
FROM page_stat_data
WHERE start_time > 0
GROUP BY day
ORDER BY day DESC
LIMIT 90
]])
local row = stmt:step()
while row do
table.insert(daily_stats, {
date = row[1] and tostring(row[1]) or "",
duration = tonumber(row[2]) or 0,
books = tonumber(row[3]) or 0,
})
row = stmt:step()
end
stmt:close()
end)
end
conn:close()
return { books = book_stats, daily = daily_stats }
end
function DataLoader:getDashboard()
local cache = self._dashboard_cache
local now_ts = os.time()
if cache and cache.payload and (now_ts - (tonumber(cache.ts) or 0) <= DASHBOARD_CACHE_TTL_SEC) then
return cache.payload
end
local payload = new_dashboard_payload()
local books = self:getBooks()
local summary = payload.summary
summary.total_books = #books
for _, b in ipairs(books) do
if b.status == "complete" or b.status == "finished" then
summary.finished_books = summary.finished_books + 1
elseif (b.percent or 0) > 0 then
summary.reading_books = summary.reading_books + 1
end
summary.total_highlights = summary.total_highlights + (b.highlights or 0)
summary.total_notes = summary.total_notes + (b.notes or 0)
end