summaryrefslogtreecommitdiff
path: root/cacher.lua
diff options
context:
space:
mode:
authorDavid Vazgenovich Shakaryan <dvshakaryan@gmail.com>2026-01-03 14:08:17 -0800
committerDavid Vazgenovich Shakaryan <dvshakaryan@gmail.com>2026-01-03 14:08:17 -0800
commitd58a0a7abe32f668ee80efb9bb159d31863057fa (patch)
treece611046437e451f4ffbe9d0b38d7624adeefafb /cacher.lua
parent5fad0532ede395c106d90947d1270c90b8075344 (diff)
downloadmpv-iptv-menu-d58a0a7abe32f668ee80efb9bb159d31863057fa.tar.gz
mpv-iptv-menu-d58a0a7abe32f668ee80efb9bb159d31863057fa.tar.xz
add cacher module that's more invisible
Diffstat (limited to 'cacher.lua')
-rw-r--r--cacher.lua52
1 files changed, 52 insertions, 0 deletions
diff --git a/cacher.lua b/cacher.lua
new file mode 100644
index 0000000..486f238
--- /dev/null
+++ b/cacher.lua
@@ -0,0 +1,52 @@
+-- Copyright 2025 David Vazgenovich Shakaryan
+
+local util = require('util')
+
+local mp_utils = require('mp.utils')
+
+local cacher = {}
+
+local function wrap_func(obj, opts, func, func_name)
+ return function(_, ...)
+ local fn = table.concat({opts.prefix, func_name, ...}, '.')
+ local path = mp_utils.join_path(opts.directory, fn)
+ local f = mp_utils.file_info(path)
+ local data
+
+ if not f or os.time() - f.mtime > opts.time then
+ data = func(obj, ...)
+ if data then
+ util.write_json_file(path, data)
+ end
+ end
+
+ if f and not data then
+ print('using cached ' .. fn)
+ data = util.read_json_file(path)
+ end
+
+ return data
+ end
+end
+
+function cacher.wrap(obj, opts)
+ local proxy = {}
+
+ setmetatable(proxy, {
+ __index = function(t, k)
+ local v = obj[k]
+ if type(v) ~= 'function' or not opts.functions[k] then
+ return v
+ end
+
+ local fn = wrap_func(obj, opts, v, k)
+ t[k] = fn
+
+ return fn
+ end,
+ })
+
+ return proxy
+end
+
+return cacher