summaryrefslogtreecommitdiff
path: root/index.js
blob: 4a5264851d1522470d9c93e54e977ac64fc014d1 (plain)
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
// TODO set rootPath and filters from web

const exec = require('child_process').exec;
const express = require('express');
const fs = require('fs')

const maxFiles = 50;
const port = 8000
const rootPath = ""
const type = "written"
const filters = {
    "audio": ["flac", "ogg", "mp3", "aac", "midi", "mid", "opus", "wav"],
    "written": ["txt", "pdf", "html", "epub", "doc", "docx"]
}

const server = express();

server.use((req, res, next) => {
    console.debug(new Date(), req.ip, req.method, req.originalUrl);
    if(!["::1", "::ffff:127.0.0.1"].includes(req.ip )){
        res.status(404).send("you shall not pass")
        return
    }
    next();
})

server.get('/main.css', (req, res) => res.sendFile(__dirname + "/main.css"))

function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

var theFiles
server.get('/', async (req, res, next) => {
    theFiles = []
    listFiles = function(path){
        files = fs.readdirSync(path)
        files.forEach((file) => {
            let stat = fs.statSync(`${path}/${file}`)
            if(stat.isDirectory()){
                listFiles(`${path}/${file}`)
            } else {
                let idx = file.lastIndexOf(".")
                if(idx == -1){
                    return
                }
                let ext = file.substring(idx+1)
                console.log(ext)
                if(filters[type].includes(ext)){
                    theFiles.push({
                        path: path,
                        name: file,
                        created: String(stat.birthtime).substring(0, 24),
                        accessed: String(stat.atime).substring(0, 24),
                    })
                }
                
            }
        }) 
    }
    listFiles(rootPath)
    shuffle(theFiles)
    theFiles = theFiles.slice(0, maxFiles)
    var html = []
    html.push(`<!doctype html>
    <html lang="en">
    <head>
        <title>Files</title>
        <link rel="stylesheet" type="text/css" href="/main.css">
        <script>
            function fetchOpen(index){
                fetch("/open/"+index)
                    .then(response => console.log("ok"))
                    .catch((error) => {
                        console.error('Error:', error);
                      });                      
            }
            function fetchOpenDir(index){
                event.stopPropagation();
                console.log("test")
                fetch("/openDir/"+index)
                    .then(response => console.log("ok"))
                    .catch((error) => {
                        console.error('Error:', error);
                      });  
            }
        </script>
    </head>
    <body>
    <h1>Check out these files!</h1>
    <ul>`)
    theFiles.forEach((file, index) => {
        html.push(`<li onclick="fetchOpen(${index})">`)
        html.push(`<span class="name" >${file.name}</span>`)
        html.push(`<span class="path" >${file.path} <span class="btn" onclick="fetchOpenDir(${index})">browse</span></span>`)
        html.push(`<span class="date" >Created: ${file.created}</span>`)
        html.push(`<span class="date" >Accessed: ${file.accessed}</span>`)
        html.push(`</li>`)
    })
    html.push(`</ul>
    </body>
    </html>`)
    res.status(200).send(html.join(""))
})

server.get("/open/:index", (req, res, next)=>{
    let index = Number(req.params.index)
    let f = theFiles[index]
    exec(`xdg-open "${f.path}/${f.name}"`)

    res.status(200).send("");
})

server.get("/openDir/:index", (req, res, next)=>{
    let index = Number(req.params.index)
    let f = theFiles[index]
    exec(`xdg-open "${f.path}"`)

    res.status(200).send("");
})

server.listen(port, () => console.info(`Listening on port ${port}`))