summaryrefslogtreecommitdiff
path: root/index.js
blob: f48f9ca87437b6763582b8a2542a9e2e1b3b8aa8 (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
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
const express = require('express')
const fetch = require('node-fetch')

const config = require('./config.js')

const server = express();

server.use((req, res, next) => {
    console.log(req.method, req.path)
    next()
})

const credentials = Buffer.from(`${config.user}:${config.pass}`).toString('base64')
const authorization = `Basic ${credentials}`

var cached_sounds = []

function headers(){
  return {
      "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
      "Authorization": authorization,
  }
}

function fetch_library(page, tags=""){
  return fetch(`${config.baseURL}/library`, {
      "credentials": "include",
      "headers": headers(),
      "body": `type=file,url&dir=.&tags=${tags}&keywords=&page=${page}&action=query`,
      "method": "POST",
  }).then(response => response.json())
}

async function fetch_total_pages(){
    return fetch_library(1).then(data => data.total_pages)
}

async function fetch_page(page){
    return fetch_library(page).then(data => data.items)
}

function enqueue(id){
  fetch(`${config.baseURL}/post`, {
    "credentials": "include",
    "headers": headers(),
    "body": `add_item_next=${id}`,
    "method": "POST",
  }).then(response => response.json())
  .then(data => console.log(`Added ${id} to queue`));
}

async function get_all_sounds(){
  let sounds = []
  total_pages = await fetch_total_pages()
  let i = 1
  while(i <= total_pages){
    let items = await fetch_page(i)
    items.forEach(item => {
      if(item.type =="File"){
        let parts = item.path.split("-", 2)
        let name = item.path
        if(parts.length > 1){
          name = parts[1]
        }
        let parts2 = name.split("/", 2)
        if(parts2.length > 1){
            name = parts2[1]
        }
        // NOTE: tags is index here to unpack the list it comes in...
        // [ [tag1, tag2] ]
        sounds.push({
          "id": item.id,
          "name": name,
          "path": item.path,
          "tags": item.tags[0],
          "type": "file",
        })
      } else if (item.type == "URL") {
        sounds.push({
          "id": item.id,
          "name": item.title,
          "type": "url",
          "tags": item.tags[0],
        })
      }
    })
    i++
  }
  cached_sounds = sounds
  return sounds
}

async function organize_sounds(){
  let sounds = {}
  config.names.forEach(name => {
    sounds[name] = []
  })
  let other = []
  let tags = {}
  all_sounds = await get_all_sounds()
  all_sounds.forEach(item => {
    if (item.tags){
        item.tags.forEach(tag => {
          if(!tags.hasOwnProperty(tag)){
            tags[tag] = []
          }
          tags[tag].push(item)
        })
    }
    let matched = false
    Object.keys(sounds).forEach(name => {
      if(item.type == "file"){
        path = item.path.split("-")[0]
        if(path.toLowerCase().indexOf(name) != -1){
          sounds[name].push(item)
          matched = true
        }
      }
    })
    if(!matched){
      other.push(item)
    }
  })
  sounds["other"] = other
  return {"sounds": sounds, "tags": tags}
}

server.get('/', async (req, res) => {
  var html = `
  <style>
    div.btn {
        cursor: pointer;
        background-color: #ddd;
        border: 1px solid black;
        padding: 0.25em;
        margin: 0.25em;
    }
    div.tags {
        margin-left: 2em;
        font-style: italic;
    }
    div.container {
        display: flex;
        flex-wrap: wrap;
    }
  </style>
  <script>
    function enqueue(ids){
        ids.forEach(id => {
            fetch("/"+id)
        })
    }
    function random(){
        fetch("/random")
    }
  </script>
  <button onclick="random()">random</button>
  <body>
   `
  try {
    let soundObj = await organize_sounds()
    let sounds = soundObj["sounds"]
    let tags = soundObj["tags"]
    Object.keys(sounds).forEach(title => {
      html += `<h1>${title.toUpperCase()}</h1><div class="container">`
      sounds[title].forEach(item => {
        let tags = ""
        if(item.tags){
          tags = `<div class="tags">${item.tags.join(", ")}</div>`
        }
          try {
            html += `<div class="btn" onclick="enqueue(['${item.id}'])"><div>${item.name}</div>${tags}</div>\n`
          } catch (error) {
              console.log(error)
          }
      })
      html += `</div>`
    })
    html += `<h1>Tags</h1><div class="container">`
    Object.keys(tags).forEach(tagName => {
      let idsForTag = tags[tagName].map( item => {return item.id})
      let idsString = idsForTag.join("', '")
      html += `<div class="btn" onclick="enqueue(['${idsString}'])">Add all '${tagName}'</div>\n`
    })
    html += `</div>`
    html += "</body>"
    res.send(html);
  } catch (error){
    console.log(error)
  }
})

server.get('/random', async (req, res, next) => {
  let all_sounds = cached_sounds
  let filtered_sounds = all_sounds.filter(item => {
    return item.type == "file" && !item.path.startsWith("uploads/")
  })
  let rand_sound = filtered_sounds[Math.floor(Math.random() * filtered_sounds.length)]
  enqueue(rand_sound.id)
  res.send("ok")
})

server.get('/:id', async (req, res, next) => {
  enqueue(req.params.id)
  res.send("ok")
})


console.log("listening...")
server.listen(config.port)