download-counter plugin

Massimo Melina committed Jan 12, 2022 at 19:40 UTC bf27d9145ca661de66af2f8caa9b2c3b48b09a3a
4 files changed +44 -3
config.yaml
+1 -1
@@ -5,7 +5,7 @@
5 #error_log:
6 mime:
7 "*.jpg|*.png|*.mp3|*.txt": auto
8 -disable_plugins: [ 'theme-example', 'middleware-example' ]
8 +disable_plugins: [ 'theme-example', 'middleware-example', 'download-counter' ]
9 plugins_config:
10 middleware-example:
11 message: ciao
plugins/download-counter/plugin.js new
+37
@@ -0,0 +1,37 @@
1 +const { writeFile, readFile } = require('fs')
2 +const _ = require('lodash')
3 +const yaml = require('yaml')
4 +
5 +const countersFile = 'counters.yaml'
6 +
7 +const counters = {}
8 +// load previous stats
9 +readFile(countersFile, 'utf8', (err, data) => {
10 + if (err)
11 + return err.code === 'ENOENT' || console.debug(countersFile, err)
12 + Object.assign(counters, yaml.parse(String(data)))
13 + console.debug('counters loaded')
14 +})
15 +
16 +const save = _.debounce(() => {
17 + writeFile(countersFile, yaml.stringify(counters), err => console.debug(err || 'counters saved'))
18 +}, 5_000, { maxWait:30_000 })
19 +
20 +exports.unload = ()=> save.flush() // we may have pending savings
21 +
22 +exports.middleware = (ctx) =>
23 + () => { // execute after other middlewares are done
24 + if (ctx.status >= 300 || !ctx.fileSource) return
25 + const { path } = ctx
26 + counters[path] = counters[path] + 1 || 1
27 + save()
28 + }
29 +
30 +exports.onDirEntry = ({ entry, listPath }) => {
31 + const path = listPath + entry.n
32 + const n = counters[path]
33 + if (n)
34 + entry.hits = n
35 +}
36 +
37 +exports.frontend_js = 'hits.js'
plugins/download-counter/public/hits.js new
+5
@@ -0,0 +1,5 @@
1 +HFS.onEvent('additionalEntryProps', ({ entry }) => {
2 + const n = entry.hits
3 + if (typeof n === 'number')
4 + return 'Hits: ' + n + ' - '
5 +})
todo.md
+1 -2
@@ -1,5 +1,4 @@
1 -# To do
2 -- download counter (as plugin?)
1 + To do
2 - update tests to SRP login
3 - upload
4 - upload unzipping (while streaming?)