Repository navigation
Expand file tree
/
Copy pathrssreader_html_resources.lua
More file actions
638 lines (570 loc) · 21.1 KB
/
Copy pathrssreader_html_resources.lua
File metadata and controls
638 lines (570 loc) · 21.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
local http = require("socket.http")
local ltn12 = require("ltn12")
local socketutil = require("socketutil")
local urlmod = require("socket.url")
local util = require("util")
local ffiutil = require("ffi/util")
local socket = require("socket")
local lfs = require("libs/libkoreader-lfs")
local logger = require("logger")
local DataStorage = require("datastorage")
local HtmlResources = {}
local mimetype_to_extension = {
["image/jpeg"] = "jpg",
["image/jpg"] = "jpg",
["image/png"] = "png",
["image/gif"] = "gif",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["image/avif"] = "avif",
["image/bmp"] = "bmp",
}
-- Extensions we accept from the URL itself. Anything else (".php", a dotted
-- path segment, no extension at all) is left to the Content-Type header:
-- crengine sniffs image format by extension, so a wrong one is worse than
-- none.
local known_image_extensions = {
jpg = true, jpeg = true, png = true, gif = true, svg = true,
webp = true, avif = true, bmp = true, ico = true, tif = true, tiff = true,
}
local function extensionFromUrl(absolute_src)
-- Cut the query and fragment off first: "pic.png?w=600" is a PNG.
local path_only = absolute_src:match("^([^%?#]*)")
local ext = path_only and path_only:match("%.(%w+)$")
if not ext then
return nil
end
ext = ext:lower()
if not known_image_extensions[ext] then
return nil
end
return ext
end
local function matchAttribute(tag, attribute)
local pattern = attribute:gsub("%-", "%%-")
return tag:match(pattern .. '%s*=%s*"([^"]*)"')
or tag:match(pattern .. "%s*=%s*'([^']*)'")
end
local function parsePixelLength(value)
if type(value) ~= "string" or value == "" then
return nil
end
local trimmed = value:match("^%s*(.-)%s*$")
if not trimmed or trimmed == "" then
return nil
end
local number_part, unit_part = trimmed:match("^([%d%.]+)%s*([%a%%]*)$")
if not number_part then
return nil
end
if unit_part and unit_part ~= "" then
unit_part = unit_part:lower()
if unit_part ~= "px" then
return nil
end
end
return tonumber(number_part)
end
local function parseStylePixelLength(style, property)
if type(style) ~= "string" or style == "" then
return nil
end
local lowered = style:lower()
local value = lowered:match(property .. "%s*:%s*([^;]+)")
if value then
return parsePixelLength(value)
end
return nil
end
local function isTinyPixelImage(tag)
local width_attr = matchAttribute(tag, "width")
local height_attr = matchAttribute(tag, "height")
local style_attr = matchAttribute(tag, "style")
local width = parsePixelLength(width_attr) or parseStylePixelLength(style_attr, "width")
local height = parsePixelLength(height_attr) or parseStylePixelLength(style_attr, "height")
if width and width <= 1 and height and height <= 1 then
return true
end
return false
end
local function ensureDirectory(path)
local ok, err = util.makePath(path)
if not ok then
logger.warn("RSSReader", "Failed to create directory", path, err)
return false
end
return true
end
function HtmlResources.ensureBaseDirectory()
local base_dir = DataStorage:getDataDir() .. "/cache/rssreader"
if ensureDirectory(base_dir) then
return base_dir
end
return nil
end
local function wipeDirectoryContents(path)
local attr = lfs.attributes(path, "mode")
if attr ~= "directory" then
return
end
for entry in lfs.dir(path) do
if entry ~= "." and entry ~= ".." then
local full = path .. "/" .. entry
local mode = lfs.attributes(full, "mode")
if mode == "directory" then
wipeDirectoryContents(full)
local ok, err = lfs.rmdir(full)
if not ok then
logger.warn("RSSReader", "Failed to remove directory", full, err)
end
else
local ok, err = os.remove(full)
if not ok then
logger.warn("RSSReader", "Failed to remove file", full, err)
end
end
end
end
end
local function resetAssetDirectories(asset_paths)
if not asset_paths or not asset_paths.assets_root then
return false
end
if lfs.attributes(asset_paths.assets_root, "mode") == "directory" then
wipeDirectoryContents(asset_paths.assets_root)
end
return ensureDirectory(asset_paths.images_dir)
end
function HtmlResources.prepareAssetPaths(base_dir, base_name)
if type(base_dir) ~= "string" or base_dir == "" then
return nil
end
if type(base_name) ~= "string" or base_name == "" then
base_name = tostring(os.time())
end
base_name = base_name:gsub("[^%w%._-]", "_")
local assets_root = string.format("%s/assets/%s", base_dir, base_name)
return {
base_dir = base_dir,
base_name = base_name,
assets_root = assets_root,
images_dir = assets_root .. "/images",
relative_prefix = string.format("assets/%s/images", base_name),
}
end
local function replaceAttributeValue(tag, attribute, new_value)
local attr_pattern = attribute:gsub("%-", "%%-")
local updated, count = tag:gsub(attr_pattern .. '%s*=%s*"([^"]*)"', attribute .. '="' .. new_value .. '"', 1)
if count == 0 then
updated = tag:gsub(attr_pattern .. "%s*=%s*'([^']*)'", attribute .. "='" .. new_value .. "'", 1)
end
return updated
end
local function replaceSrcAttribute(tag, new_src)
local function replacer(prefix, attr, _, suffix)
return prefix .. attr .. new_src .. suffix
end
local replaced, count = tag:gsub('([%s<])([Ss][Rr][Cc]%s*=%s*")([^"]*)(")', replacer, 1)
if count == 0 then
replaced, count = tag:gsub("([%s<])([Ss][Rr][Cc]%s*=%s*')([^']*)(')", replacer, 1)
end
if count == 0 then
replaced = tag:gsub("(<%s*[Ii][Mm][Gg])", "%1 src=\"" .. new_src .. "\"", 1)
end
return replaced
end
-- Per-image download timeouts. We deliberately use values shorter than
-- socketutil.LARGE_BLOCK_TIMEOUT (10s) / LARGE_TOTAL_TIMEOUT (30s): a single
-- slow image must not stall the whole article download for tens of seconds.
local IMAGE_BLOCK_TIMEOUT = 5
local IMAGE_TOTAL_TIMEOUT = 10
-- Image downloads are latency-bound: nearly all the time of a single request
-- is spent waiting for DNS, the TCP/TLS handshake and the remote server, so
-- fetching N images one after the other costs roughly N times the latency of
-- one. We fan the work out to a few forked worker processes instead (see
-- downloadTasksInParallel). The image bytes never travel through a pipe:
-- every worker writes straight to its own file in images_dir, and the parent
-- picks the results up from the filesystem.
local DEFAULT_WORKERS = 4
local MAX_WORKERS = 8
local POLL_INTERVAL = 0.25 -- seconds between "are the workers done?" checks
local function downloadFile(url, target_path)
local sink = {}
socketutil:set_timeout(IMAGE_BLOCK_TIMEOUT, IMAGE_TOTAL_TIMEOUT)
local ok, status_code, headers, status_text = http.request{
url = url,
method = "GET",
sink = ltn12.sink.table(sink),
headers = {
["Accept-Encoding"] = "identity",
["User-Agent"] = "KOReader RSSReader",
},
}
socketutil:reset_timeout()
if not ok or tostring(status_code):sub(1, 1) ~= "2" then
logger.info("RSSReader", "Image download failed", url, status_text or status_code)
return nil
end
local directory = target_path:match("^(.*)/")
if directory and directory ~= "" then
ensureDirectory(directory)
end
local file = io.open(target_path, "wb")
if not file then
logger.warn("RSSReader", "Unable to open image path for writing", target_path)
return nil
end
file:write(table.concat(sink))
file:close()
return headers or {}
end
local function extensionFromContentType(content_type)
if type(content_type) ~= "string" then
return nil
end
-- "image/jpeg; charset=binary" -> "image/jpeg"
local mimetype = content_type:lower():match("^%s*([^;%s]+)")
if not mimetype then
return nil
end
return mimetype_to_extension[mimetype]
end
-- Download one task to a temporary ".part" file and only then move it to its
-- final name. The detour buys us two things: the extension may only be known
-- from the Content-Type header (crengine sniffs image format by extension),
-- and a half-written file is never visible under the name the HTML points at
-- -- which is what lets the parent count finished downloads by listing the
-- directory while the workers are still running.
-- Returns the final file name (not the path) and its full path, or nil.
local function performDownload(task, images_dir)
local part_path = task.image_path .. ".part"
local headers = downloadFile(task.url, part_path)
if not headers then
os.remove(part_path)
return nil
end
local ext = task.ext
if not ext or ext == "" then
ext = extensionFromContentType(headers["content-type"])
end
local filename = (ext and ext ~= "")
and string.format("%s.%s", task.imgid, ext)
or task.imgid
local final_path = string.format("%s/%s", images_dir, filename)
local ok, err = os.rename(part_path, final_path)
if not ok then
logger.warn("RSSReader", "Failed to rename image", part_path, err)
os.remove(part_path)
return nil
end
return filename, final_path
end
local function listFinishedFiles(images_dir)
local by_imgid = {}
local count = 0
local ok = pcall(function()
for entry in lfs.dir(images_dir) do
if entry ~= "." and entry ~= ".." and not entry:find("%.part$") then
local imgid = entry:match("^(img%d+)")
if imgid then
by_imgid[imgid] = entry
count = count + 1
end
end
end
end)
if not ok then
return {}, 0
end
return by_imgid, count
end
-- kill()ed children still have to be reaped. Hand the leftovers to UIManager
-- (the same approach as Trapper:dismissableRunInSubprocess) instead of
-- blocking the UI here waiting for them.
local function collectWorkersLater(pids)
if #pids == 0 then
return
end
local ok, UIManager = pcall(require, "ui/uimanager")
if not ok or not UIManager then
return
end
local pending = {}
for _, pid in ipairs(pids) do
table.insert(pending, pid)
end
local collect
collect = function()
for i = #pending, 1, -1 do
if ffiutil.isSubProcessDone(pending[i]) then
table.remove(pending, i)
end
end
if #pending > 0 then
UIManager:scheduleIn(5, collect)
end
end
UIManager:scheduleIn(5, collect)
end
-- Fan the downloads out to `worker_count` forked processes.
-- Returns ran, cancelled: ran == false means forking is unavailable and the
-- caller has to fall back to the sequential loop.
local function downloadTasksInParallel(tasks, images_dir, worker_count, options)
if type(ffiutil.runInSubProcess) ~= "function" then
return false, false
end
local total = #tasks
local progress_callback = options.progress_callback
local yield_callback = options.yield_callback
-- Round-robin, so a worker that draws a slow host does not also get all
-- the images that happen to sit next to it in the document.
local buckets = {}
for i = 1, worker_count do
buckets[i] = {}
end
for i = 1, total do
local bucket = buckets[(i - 1) % worker_count + 1]
bucket[#bucket + 1] = tasks[i]
end
local pids = {}
for _, bucket in ipairs(buckets) do
if #bucket > 0 then
local pid = ffiutil.runInSubProcess(function()
for _, task in ipairs(bucket) do
performDownload(task, images_dir)
end
end)
if pid then
pids[#pids + 1] = pid
else
-- fork() failed: this bucket is on us, right here.
logger.warn("RSSReader", "Could not fork image download worker")
for _, task in ipairs(bucket) do
performDownload(task, images_dir)
end
end
end
end
local cancelled = false
local reported = -1
while #pids > 0 do
for i = #pids, 1, -1 do
if ffiutil.isSubProcessDone(pids[i]) then
table.remove(pids, i)
end
end
local _, done = listFinishedFiles(images_dir)
if progress_callback and done ~= reported then
reported = done
-- Keep the caller's "image X / N" wording meaningful: report the
-- next image being worked on, not the last one that landed.
if progress_callback(math.min(done + 1, total), total) == false then
cancelled = true
end
end
if cancelled or #pids == 0 then
break
end
if yield_callback then
if yield_callback(POLL_INTERVAL) == false then
cancelled = true
break
end
else
socket.sleep(POLL_INTERVAL)
end
end
if cancelled then
for _, pid in ipairs(pids) do
ffiutil.terminateSubProcess(pid)
end
collectWorkersLater(pids)
end
return true, cancelled
end
local function resolveUrl(src, base_url)
if not src or src == "" then
return nil
end
if src:find("^data:") then
return nil
end
if src:find("^[%w][%w%+%-.]*:") then
return src
end
if not base_url or base_url == "" then
return nil
end
return urlmod.absolute(base_url, src)
end
function HtmlResources.downloadAndRewrite(html, page_url, asset_paths, options)
if type(html) ~= "string" or html == "" then
return html, { downloads = {} }
end
if not asset_paths then
return html, { downloads = {} }
end
if not resetAssetDirectories(asset_paths) then
return html, { downloads = {} }
end
options = options or {}
local progress_callback = options.progress_callback
local seen = {} -- absolute_src -> relative_src (for in-document de-dup)
local tasks = {} -- ordered list of unique downloads to perform later
local imagenum = 1
-- ------------------------------------------------------------
-- Phase 1: scan & rewrite. Pure Lua; no I/O, no coroutine yields.
-- This is safe to run inside a `string.gsub` replacement: gsub is
-- a C function and yielding from a Lua callback nested inside C
-- silently fails under our Trapper:wrap coroutine, so we MUST NOT
-- call progress_callback (which calls Trapper:info -> yield) here.
-- ------------------------------------------------------------
local function scanTag(img_tag)
if isTinyPixelImage(img_tag) then
return ""
end
local original_src
local original_attribute
local function consider(value, attribute)
if value and value ~= "" then
original_src = value
original_attribute = attribute
return true
end
return false
end
consider(img_tag:match('[%s<][Ss][Rr][Cc]%s*=%s*"([^"]*)"'), "src")
if not original_src then
consider(img_tag:match("[%s<][Ss][Rr][Cc]%s*=%s*'([^']*)'"), "src")
end
if not original_src then
local data_attributes = { "data-src", "data-original", "data-lazy-src" }
for _, attribute in ipairs(data_attributes) do
local pattern_base = attribute:gsub("%-", "%%-")
if consider(img_tag:match(pattern_base .. '%s*=%s*"([^"]*)"'), attribute) then
break
end
if consider(img_tag:match(pattern_base .. "%s*=%s*'([^']*)'"), attribute) then
break
end
end
end
if not original_src then
return img_tag
end
local absolute_src = resolveUrl(original_src, page_url)
if not absolute_src then
return img_tag
end
local relative_src = seen[absolute_src]
if not relative_src then
local ext = extensionFromUrl(absolute_src)
local imgid = string.format("img%05d", imagenum)
imagenum = imagenum + 1
local filename = ext and ext ~= "" and string.format("%s.%s", imgid, ext) or imgid
local image_path = string.format("%s/%s", asset_paths.images_dir, filename)
relative_src = string.format("%s/%s", asset_paths.relative_prefix, filename)
seen[absolute_src] = relative_src
tasks[#tasks + 1] = {
url = absolute_src,
imgid = imgid,
ext = ext,
image_path = image_path,
relative_src = relative_src,
}
end
local updated_tag = replaceSrcAttribute(img_tag, relative_src)
if original_attribute and original_attribute ~= "src" then
updated_tag = replaceAttributeValue(updated_tag, original_attribute, relative_src)
end
return updated_tag
end
local rewritten = html:gsub("(<%s*[Ii][Mm][Gg][^>]*>)", scanTag)
-- ------------------------------------------------------------
-- Phase 2: download. Either in a few forked workers (the default), or,
-- when forking is unavailable or a single worker was requested, in a
-- plain Lua for-loop. Either way we are out of `string.gsub`, so
-- progress_callback may call Trapper:info() and yield safely back to
-- UIManager between images. That's what gives the user a live
-- "Downloading image X / N ..." widget plus tap-to-cancel.
-- ------------------------------------------------------------
local total = #tasks
local downloads = {}
local renames = {}
local cancelled = false
local finished = {} -- task -> final file name
local worker_count = tonumber(options.workers) or DEFAULT_WORKERS
worker_count = math.max(1, math.min(MAX_WORKERS, math.floor(worker_count)))
worker_count = math.min(worker_count, total)
local ran_in_parallel = false
if worker_count > 1 then
local ran, was_cancelled = downloadTasksInParallel(tasks, asset_paths.images_dir, worker_count, options)
if ran then
ran_in_parallel = true
cancelled = was_cancelled
local by_imgid = listFinishedFiles(asset_paths.images_dir)
for _, task in ipairs(tasks) do
finished[task] = by_imgid[task.imgid]
end
end
end
if not ran_in_parallel then
for i, task in ipairs(tasks) do
if progress_callback then
local go_on = progress_callback(i, total)
if go_on == false then
cancelled = true
break
end
end
finished[task] = performDownload(task, asset_paths.images_dir)
end
end
-- The name a file ended up with may differ from the one phase 1 wrote
-- into the HTML (when the extension could only come from Content-Type),
-- so collect those for phase 3.
for _, task in ipairs(tasks) do
local filename = finished[task]
if filename then
local relative_src = string.format("%s/%s", asset_paths.relative_prefix, filename)
if relative_src ~= task.relative_src then
renames[task.relative_src] = relative_src
task.relative_src = relative_src
end
task.image_path = string.format("%s/%s", asset_paths.images_dir, filename)
downloads[#downloads + 1] = {
url = task.url,
path = task.image_path,
relative_src = task.relative_src,
}
end
end
-- ------------------------------------------------------------
-- Phase 3: patch HTML for any extension-from-headers renames.
-- Plain literal-string substitution; no callback, no yields.
-- ------------------------------------------------------------
if next(renames) then
for old_src, new_src in pairs(renames) do
local escaped_old = old_src:gsub("([%(%)%.%%%+%-%*%?%[%]%^%$])", "%%%1")
local escaped_new = new_src:gsub("%%", "%%%%")
rewritten = rewritten:gsub(escaped_old, escaped_new)
end
end
return rewritten, {
downloads = downloads,
assets_root = asset_paths.assets_root,
images_dir = asset_paths.images_dir,
cancelled = cancelled,
}
end
function HtmlResources.cleanupAssets(assets_root)
if type(assets_root) ~= "string" or assets_root == "" then
return
end
wipeDirectoryContents(assets_root)
local ok, err = lfs.rmdir(assets_root)
if not ok then
logger.debug("RSSReader", "Unable to remove asset directory (may be fine)", assets_root, err)
end
end
return HtmlResources