plugin/download-counter: new file format

Massimo Melina committed Jun 21, 2024 at 10:54 UTC 183b68ffc604a99bfed388bbca5c75f98972b49b
2 files changed +16 -25
.gitignore
+2 -1
@@ -11,4 +11,5 @@ self.*
11 config.yaml*
12 custom.html
13 accounts.yaml
14 -.DS_Store
\ No newline at end of file
14 +.DS_Store
15 +storage
\ No newline at end of file
plugins/download-counter/plugin.js
+14 -24
@@ -1,8 +1,8 @@
1 // other plugins can use ctx.state.download_counter_ignore to mark downloads that shouldn't be counted
2
3 exports.description = "Counts downloads for each file, and displays the total in the list or file menu"
4 -exports.version = 5.11 // change in API
5 -exports.apiRequired = 8.3
4 +exports.version = 6 // new format
5 +exports.apiRequired = 8.89 // openDb
6
7 exports.config = {
8 where: { frontend: true, type: 'select', defaultValue: 'menu',
@@ -15,31 +15,22 @@ exports.configDialog = {
15 }
16
17 exports.init = async api => {
18 - const _ = api.require('lodash')
19 - const yaml = api.require('yaml')
20 - const { writeFile, readFile } = api.require('fs/promises')
21 - const { debounceAsync, newObj } = api.require('./misc')
18 + const db = await api.openDb('counters.kv', { defaultPutDelay: 5_000, maxPutDelay: 30_000 })
19
23 - const countersFile = 'counters.yaml'
24 -
25 - let counters = {}
26 - const save = debounceAsync(async () => {
27 - await writeFile(countersFile, yaml.stringify(counters))
28 - console.debug('counters saved')
29 - }, 5_000, { maxWait:30_000 })
30 -
31 - // load previous stats
32 - try {
20 + try { // load legacy file
21 + const countersFile = 'counters.yaml'
22 + const yaml = api.require('yaml')
23 + const { readFile, unlink } = api.require('fs/promises')
24 const data = await readFile(countersFile, 'utf8')
34 - counters = yaml.parse(data) || {}
35 - counters = newObj(counters, (v,k,setKey) => setKey(uri2key(k)) && v)
36 - console.debug('counters loaded')
25 + for (const [k,v] of Object.entries(yaml.parse(data)))
26 + db.put(uri2key(k), v)
27 + await unlink(countersFile)
28 + api.log("data converted")
29 }
30 catch(err) {
31 if (err.code !== 'ENOENT')
40 - console.debug(countersFile, err)
32 + api.log(err)
33 }
42 -
34 return {
35 frontend_js: 'main.js',
36 frontend_css: 'style.css',
@@ -53,13 +44,12 @@ exports.init = async api => {
44 : ctx.state.originalStream?.getArchiveEntries?.().filter(x => x.at(-1) !== '/').map(x => key + uri2key(x))
45 if (!entries) return
46 for (const k of entries)
56 - counters[k] = counters[k] + 1 || 1
57 - save()
47 + db.put(k, db.getSync(k) + 1)
48 })
49 },
50 onDirEntry({ entry, listUri }) {
51 const k = uri2key(listUri + entry.n)
62 - const n = counters[k]
52 + const n = db.getSync(k)
53 if (n)
54 entry.hits = n
55 }