Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
9b4c0b24ef
|
|||
|
c418634515
|
|||
|
87ac0cecb7
|
|||
|
1d49689171
|
|||
|
fdd41397bf
|
|||
|
7e5c92dd63
|
|||
|
83f2b76cbc
|
|||
|
546385a484
|
|||
|
d8470d0f4b
|
|||
|
85a6c2b859
|
|||
|
057e21285b
|
|||
|
e485d1a8c5
|
|||
|
e3de41fe07
|
|||
|
8a2c8dd8b2
|
|||
|
abc0096ade
|
|||
|
e170c8b842
|
|||
|
d556bbe0c8
|
8
Makefile
8
Makefile
@@ -1,10 +1,6 @@
|
|||||||
dist:
|
dist:
|
||||||
mkdir -p dist
|
cd web && npm install
|
||||||
minify web/index.js web/*.html web/*.css -o dist/
|
cd web && npm run build
|
||||||
cp -rf web/*.png dist/web/
|
|
||||||
cp -f web/axios.min.js dist/web/axios.min.js
|
|
||||||
cp -f web/vue.global.prod.js dist/web/vue.js
|
|
||||||
cp -f web/vue-router.global.prod.js dist/web/vue-router.js
|
|
||||||
|
|
||||||
linux:
|
linux:
|
||||||
go build
|
go build
|
||||||
|
|||||||
250
README.md
250
README.md
@@ -1,66 +1,76 @@
|
|||||||
# MSW Open Music Project
|
# MSW Open Music Project
|
||||||
|
|
||||||
## 简介
|
## Introduction
|
||||||
|
|
||||||
Fork from `msw-file`,目前是一个音乐播放器。
|
A light weight personal music streaming platform.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
[toc]
|
[toc]
|
||||||
|
|
||||||
## 编译 & 构建
|
## How to build
|
||||||
|
|
||||||
### 编译后端
|
### Build the back-end server
|
||||||
|
|
||||||
`go build`
|
`make linux` or `make windows`
|
||||||
|
|
||||||
如无任何输出,说明构建成功,可执行程序位于 `msw-open-music`
|
The executable file is named `msw-open-music` or `msw-open-music.exe`
|
||||||
|
|
||||||
### 构建前端
|
### Build the font-end web pages
|
||||||
|
|
||||||
`make`
|
To build production web page `make web`
|
||||||
|
|
||||||
说明:`Makefile` 脚本中的代码会在 `dist` 目录生成用于生产环境的前端 web 文件。这个脚本做的事情是简单地将 `vue` `vue-router` 等 js 文件替换成生产版本。并使用 `minify` 工具处理 `css` 和 `html` 文件。
|
This command will go into `web` directory and install `node_modules`. Then execute `npm run build` command. The built web pages is under `web/build` directory.
|
||||||
|
|
||||||
## 使用
|
To start the development, run `cd web` and `npm start`
|
||||||
|
|
||||||
### 后端使用
|
## Usage
|
||||||
|
|
||||||
初次使用请配置 `config.json`, **最重要的是配置 `token`** 。
|
Start back-end server. Server will listen on 8080 port.
|
||||||
|
|
||||||
默认 ffmpeg 线程 `ffmpeg_threads` 为 1 ,大于 1 以上的值似乎对编码音频没有效果。
|
Build the font-end web page, then go to <http://127.0.0.1:8080>
|
||||||
|
|
||||||
#### config.json 说明
|
By default:
|
||||||
|
|
||||||
- `database_name` 字符串类型,指定 sqlite3 单文件数据库的位置,如果不存在则会自动创建。
|
- URL matched `/api/*` will process by back-end server.
|
||||||
- `addr` api 服务监听端口,该参数会被传入 `http.Serve.Addr`
|
- Others URL matched `/*` will be served files under `web/build/`
|
||||||
- `token` 字符串,作为管理密码
|
|
||||||
- `ffmpeg_configs`,字典,其键是 ffmpeg 配置的名称,其值是放入 `ffmpeg -i input.mp3 -vn [此处] -f matroska -` 的参数,类型是字符串。 **注意:** 前端会按键名来排序配置列表,并以列表中的第一项作为默认配置。
|
|
||||||
- `file_life_time` 临时文件生存时间,超过该时间没有访问该临时文件,tmpfs 将删除此文件。
|
|
||||||
- `cleaner_internal` 清理器的检查间隔。
|
|
||||||
- `root` 存放该临时文件目录, **Windows 用户请替换成合适的目录。**
|
|
||||||
|
|
||||||
### 前端使用
|
### Run back-end server
|
||||||
|
|
||||||
前端文件引用均使用相对路径,将前端文件放到同一目录下即可。
|
Configuration file is `config.json`, **Please modify your `token`** 。
|
||||||
|
|
||||||
前端在调用后端 api 时使用的是绝对路径,例如 `/api/v1/hello`。如需更改,可以修改后端 `api.go` 中的 `apiMux` 和 `mux` 的相关属性。
|
Default `ffmpeg_threads` is 1. Seems value larger than 1 will not increase the audio encode speed.
|
||||||
|
|
||||||
## 关于临时文件夹的说明
|
#### config.json description
|
||||||
|
|
||||||
前端播放器中勾选了 `Prepare` ,后端将转码文件到临时文件夹,然后直链提供文件。这有助于修复网路不稳定时 TCP 链接断开,stream 模式下 ffmpeg 中断输出并且不能断点续传的问题。
|
- `database_name` string type. The filename of `sqlite3` database. Will create if that file doesn't exist.
|
||||||
|
- `addr` string type. The listen address and port.
|
||||||
|
- `token` string type. Password.
|
||||||
|
- `ffmpeg_config_list` list type, include `ffmpegConfig` object.
|
||||||
|
- `file_life_time` integer type (second). Life time for temporary file. If the temporary file is not accessed for more than this time, back-end server will delete this file.
|
||||||
|
- `cleaner_internal` integer type (second). Interval for `tmpfs` checking temporary file.
|
||||||
|
- `root` string type. Directory to store temporary files. Default is `/tmp`, **please modify this directory if you are using Windows.**
|
||||||
|
|
||||||
临时文件夹管理器位于 `internal/pkg/tmpfs` 中,默认删除时间是 10 分钟。10分钟内如果没有对该临时文件的访问,则会删除此临时文件。
|
### Run font-end web page
|
||||||
|
|
||||||
|
Open your web browser to <http://127.0.0.1:8080> you will see the web pages.
|
||||||
|
|
||||||
|
## About tmpfs
|
||||||
|
|
||||||
|
If the `Prepare` mode is enabled in the font-wed player, back-end server will convert the whole file into the temporary folder, then serve file using native method. This can avoid ffmpeg pipe break problem cause by unstable network connection while streaming audio.
|
||||||
|
|
||||||
|
The default temporary folder is `/tmp`, which is a `tmpfs` file system in Linux operating system. Default life time for temporary files is 600 seconds (10 minutes). If the temporary file is not accessed for more than this time, back-end server will delete this file.
|
||||||
|
|
||||||
## Change log
|
## Change log
|
||||||
|
|
||||||
- `v1.0.0` 首个版本
|
- `v1.0.0` First version. Ready to use in production environment.
|
||||||
|
- `v1.1.0` Use `React` to rewrite the font-end web pages (Previous using `Vue`).
|
||||||
|
|
||||||
## 后端 API 文档
|
## Back-end API references
|
||||||
|
|
||||||
说明中带有 `stream` 或 `流` 相关字样的,说明该 API 以 `io.Copy` 方式传输文件,不支持断点续传
|
API named `stream` means it transfer data using `io.Copy`, which **DO NOT** support continue getting a partially-downloaded audio.
|
||||||
|
|
||||||
无需返回数据的 API 将返回 OK,某些 API 可能会在 `status` 字段中返回详细的执行信息。
|
API does not need to respond any data will return the following JSON object.
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -68,13 +78,15 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 公开 API
|
### Anonymous API
|
||||||
|
|
||||||
- `/api/v1/hello` OK 测试
|
Anonymous API can be called by anonymous.
|
||||||
|
|
||||||
- `/api/v1/get_file` 以流方式获取文件
|
- `/api/v1/hello` Just for test purpose.
|
||||||
|
|
||||||
- 请求示例
|
- `/api/v1/get_file` Get a file with `stream` mode.
|
||||||
|
|
||||||
|
- Request example
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -82,15 +94,15 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- `/api/v1/get_file_direct` http 标准方式获取文件,支持断点续传,由 `http.ServeFile` 实现
|
- `/api/v1/get_file_direct` Get a file with standart `http` methods, implement by `http.ServeFile` method.
|
||||||
|
|
||||||
- 请求示例
|
- Request example
|
||||||
|
|
||||||
`/api/v1/get_file_direct?id=30`
|
`/api/v1/get_file_direct?id=30`
|
||||||
|
|
||||||
- `/api/v1/search_files` 搜索文件
|
- `/api/v1/search_files` Search files by filename.
|
||||||
|
|
||||||
- 请求示例
|
- Request example
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -100,13 +112,13 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
搜索所有文件名中包含 "miku" 的文件
|
Search all files' name like `%miku%`. `%` is the wildcard in SQL. For example, `"filename": "miku%hatsune"` can match `hatsune miku`.
|
||||||
|
|
||||||
`limit` 限制返回结果的数量,该值必须在 0~10 之间
|
`limit` Numbers of files in the respond. Should be within 1 - 10;
|
||||||
|
|
||||||
`offset` 是返回结构的偏移量,用于实现翻页功能。
|
`offset` It is the offset of the result, related to the page turning function.
|
||||||
|
|
||||||
- 返回示例
|
- Respond example
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -119,29 +131,29 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
"filesize": 1048576
|
"filesize": 1048576
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": 30,
|
"id": 31,
|
||||||
"folder_id": 100,
|
"folder_id": 100,
|
||||||
"folder_name": "wonderful",
|
"folder_name": "wonderful",
|
||||||
"filename": "memories.flac",
|
"filename": "memories (instrunment).flac",
|
||||||
"filesize": 1048576
|
"filesize": 1248531
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`id` 为文件的唯一标识
|
`id` Identification of file.
|
||||||
|
|
||||||
`folder_id` 为该文件所在的文件夹标识
|
`folder_id` Identification of folder.
|
||||||
|
|
||||||
`foldername` 为该文件所在的文件夹名
|
`foldername` Folder name where the file in.
|
||||||
|
|
||||||
`filename` 为该文件名
|
`filename` File name.
|
||||||
|
|
||||||
`filesize` 为该文件的大小,单位字节
|
`filesize` File size, unit is byte.
|
||||||
|
|
||||||
- `/api/v1/search_folders` 搜索文件夹
|
- `/api/v1/search_folders` Search folders.
|
||||||
|
|
||||||
- 请求示例
|
- Request example.
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -151,13 +163,13 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
搜索所有文件夹名中包含 "miku" 的文件夹。
|
Search all folders' name like `%miku%`. `%` is the wildcard in SQL. For example, `"filename": "miku%hatsune"` can match `hatsune miku`.
|
||||||
|
|
||||||
`limit` 限制返回结果的数量,该值必须在 0~10 之间
|
`limit` Numbers of files in the respond. Should be within 1 - 10;
|
||||||
|
|
||||||
`offset` 是返回结构的偏移量,用于实现翻页功能。
|
`offset` It is the offset of the result, related to the page turning function.
|
||||||
|
|
||||||
- 返回示例
|
- Respond example
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -167,20 +179,20 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
"foldername": "folder name"
|
"foldername": "folder name"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": 100,
|
"id": 101,
|
||||||
"foldername": "folder name"
|
"foldername": "folder name (another)"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`id` 为该文件夹的唯一标识
|
`id` Identification of folder.
|
||||||
|
|
||||||
`foldername` 为该文件夹的名字
|
`foldername` Folder name.
|
||||||
|
|
||||||
- `/api/v1/get_files_in_folder` 获取指定文件夹中的所有文件
|
- `/api/v1/get_files_in_folder` Get files in a specify folder.
|
||||||
|
|
||||||
- 请求示例
|
- Request example.
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -190,52 +202,50 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- 返回示例
|
- Respond example.
|
||||||
|
|
||||||
同 `/api/v1/search_files`
|
Same with `/api/v1/search_files`
|
||||||
|
|
||||||
- `/api/v1/get_random_files`
|
- `/api/v1/get_random_files` Randomly get 10 files.
|
||||||
|
|
||||||
此 API 随机返回 files 表中 10 个文件。请注意,该操作会造成全表查询,在 AMD 2200G CPU 40000条数据记录情况下最大处理量为 100 请求每秒。
|
- Request example.
|
||||||
|
|
||||||
- 请求示例
|
GET `/api/v1/get_random_files`
|
||||||
|
|
||||||
直接 GET `/api/v1/get_random_files`
|
- Respond example.
|
||||||
|
|
||||||
- 返回示例
|
Same with `/api/v1/search_files`
|
||||||
|
|
||||||
同 `/api/v1/search_files`
|
|
||||||
|
|
||||||
- `/api/v1/get_file_stream`
|
- `/api/v1/get_file_stream`
|
||||||
|
|
||||||
以流方式返回文件
|
Stream file with a ffmpeg config name.
|
||||||
|
|
||||||
- 请求示例
|
- Request example.
|
||||||
|
|
||||||
GET `/api/v1/get_file_stream?id=123`
|
GET `/api/v1/get_file_stream?id=123&config=OPUS%20128k`
|
||||||
|
|
||||||
- `/api/v1/get_ffmpeg_config_list`
|
- `/api/v1/get_ffmpeg_config_list`
|
||||||
|
|
||||||
获取 ffmpeg 配置列表
|
Get ffmpeg config list
|
||||||
|
|
||||||
- 请求示例
|
- Request example
|
||||||
|
|
||||||
GET `/api/v1/get_ffmpeg_config_list`
|
GET `/api/v1/get_ffmpeg_config_list`
|
||||||
|
|
||||||
- 返回示例
|
- Respond example
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"ffmpeg_configs": {
|
"ffmpeg_config_list": [
|
||||||
"OPUS 256k": {"args": "-c:a libopus -ab 256k"},
|
{"name": "OPUS 256k", "args": "-c:a libopus -ab 256k"},
|
||||||
"WAV": {"args": "-c:a wav"}
|
{"name": "WAV", "args": "-c:a wav"}
|
||||||
}
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- `/api/v1/feedback` 反馈
|
- `/api/v1/feedback` Send a feedback.
|
||||||
|
|
||||||
- 请求示例
|
- Request example
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -243,11 +253,11 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- 返回 OK
|
- Respond OK.
|
||||||
|
|
||||||
- `/api/v1/get_file_info` 获取单个文件的信息
|
- `/api/v1/get_file_info` Get information of a specify file.
|
||||||
|
|
||||||
- 请求示例
|
- Request example.
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -255,7 +265,7 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- 返回示例
|
- Respond example.
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -267,15 +277,15 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
},
|
},
|
||||||
```
|
```
|
||||||
|
|
||||||
- `/api/v1/get_file_stream_direct` 获取已提前转码好的文件,该 API 支持断点续传
|
- `/api/v1/get_file_stream_direct` Get a ffmpeg converted file with native http method. This API support continue getting a partially-downloaded audio. Note, you should call `/api/v1/prepare_file_stream_direct` first and wait for its respond, then call this API.
|
||||||
|
|
||||||
- 请求示例
|
- Request example
|
||||||
|
|
||||||
GET `/api/v1/get_file_stream_direct?id=123&config=OPUS 128k`
|
GET `/api/v1/get_file_stream_direct?id=123&config=OPUS%20128k`
|
||||||
|
|
||||||
- `/api/v1/prepare_file_stream_direct` 请求提前转码文件,该 API 将返回转码后的文件大小
|
- `/api/v1/prepare_file_stream_direct` Ask server to convert a file with specific ffmpeg config name. When the conver process is finished, server will reply with the converted file size.
|
||||||
|
|
||||||
- 请求示例
|
- Request example
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -284,7 +294,7 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- 返回示例
|
- Respond example
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -292,13 +302,11 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### API needs token
|
||||||
|
|
||||||
|
- `/api/v1/walk` Walk directory, add all files and folders to database.
|
||||||
|
|
||||||
### 需要 token 的 API
|
- Request example
|
||||||
|
|
||||||
- `/api/v1/walk` 遍历目录,并将文件和文件夹添加到数据库中
|
|
||||||
|
|
||||||
- 请求示例
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -308,17 +316,17 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`token` 此 API 需要 token
|
`token` The token in `config.json` file.
|
||||||
|
|
||||||
`root` 遍历目录
|
`root` Root directory server will walk throught
|
||||||
|
|
||||||
`pattern` 文件扩展名列表(包含 `.` ),匹配扩展名的文件才会被添加到数据库
|
`pattern` A list of pattern that files ends with. Only files matched a pattern in list will be add to database.
|
||||||
|
|
||||||
- 返回 OK
|
- Respond OK
|
||||||
|
|
||||||
- `/api/v1/reset` 重置数据库(feedbacks 不会清空)
|
- `/api/v1/reset` Rest the **files and folders table**
|
||||||
|
|
||||||
- 请求示例
|
- Request example
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -326,13 +334,13 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- 返回 OK
|
- Respond OK
|
||||||
|
|
||||||
- `/api/v1/add_ffmpeg_config` 添加 ffmpeg 配置
|
- `/api/v1/add_ffmpeg_config` Add ffmpeg config.
|
||||||
|
|
||||||
注意:目前前端中没有实现此功能
|
Will be changed in future.
|
||||||
|
|
||||||
- 请求示例
|
- Request example
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -344,26 +352,22 @@ Fork from `msw-file`,目前是一个音乐播放器。
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`name` 该配置的名字
|
`name` Name of the ffmpeg config.
|
||||||
|
|
||||||
`ffmpeg_config` 一个 ffmpeg 的配置
|
`ffmpeg_config`
|
||||||
|
|
||||||
`args` 该 ffmpeg 配置的参数
|
`args`
|
||||||
|
|
||||||
- 返回 OK
|
- Respond OK
|
||||||
|
|
||||||
- `/web/*` 返回程序同目录下 web 文件夹中的内容
|
## Font-end API references
|
||||||
|
|
||||||
此 api 仅用于方便开发,项目根目录中 web 文件夹中的内容并不是生产用(for production)的 js 文件,这个 API 不应该用来提供前端的 web 服务,web 服务应该由其他程序负责(例如 apache caddy nginx 等)
|
Currently only few APIs in font-end.
|
||||||
|
|
||||||
## 前端 API 文档
|
- `/#/files/39/share`
|
||||||
|
|
||||||
前端只有少量 API ,允许用户直接打开链接就执行某些功能
|
Share a specific file.
|
||||||
|
|
||||||
- `/web/#/share?id=39`
|
- `/#/folders/2614`
|
||||||
|
|
||||||
分享文件,id 是文件的唯一标识。
|
Show files in a specific folder.
|
||||||
|
|
||||||
- `/web/#/search_folders?folder_id=2614`
|
|
||||||
|
|
||||||
显示该文件夹中的文件, folder_id 是文件夹的唯一标识。
|
|
||||||
|
|||||||
20
config.json
20
config.json
@@ -4,16 +4,16 @@
|
|||||||
"addr": ":8080",
|
"addr": ":8080",
|
||||||
"token": "!! config your very strong token here !!",
|
"token": "!! config your very strong token here !!",
|
||||||
"ffmpeg_threads": 1,
|
"ffmpeg_threads": 1,
|
||||||
"ffmpeg_configs": {
|
"ffmpeg_config_list": [
|
||||||
"0. OPUS 128k": {"args": "-c:a libopus -ab 128k"},
|
{"name": "OPUS 128k", "args": "-c:a libopus -ab 128k"},
|
||||||
"1. OPUS 96k": {"args": "-c:a libopus -ab 96k"},
|
{"name": "OPUS 96k", "args": "-c:a libopus -ab 96k"},
|
||||||
"2. OPUS 256k": {"args": "-c:a libopus -ab 256k"},
|
{"name": "OPUS 256k", "args": "-c:a libopus -ab 256k"},
|
||||||
"3. OPUS 320k": {"args": "-c:a libopus -ab 320k"},
|
{"name": "OPUS 320k", "args": "-c:a libopus -ab 320k"},
|
||||||
"4. OPUS 512k": {"args": "-c:a libopus -ab 512k"},
|
{"name": "OPUS 512k", "args": "-c:a libopus -ab 512k"},
|
||||||
"5. AAC 128k": {"args": "-c:a aac -ab 128k"},
|
{"name": "AAC 128k", "args": "-c:a aac -ab 128k"},
|
||||||
"6. AAC 256k": {"args": "-c:a aac -ab 256k"},
|
{"name": "AAC 256k", "args": "-c:a aac -ab 256k"},
|
||||||
"7. 全损音质 32k": {"args": "-c:a libopus -ab 32k"}
|
{"name": "全损音质 32k", "args": "-c:a libopus -ab 32k"}
|
||||||
}
|
]
|
||||||
},
|
},
|
||||||
"tmpfs": {
|
"tmpfs": {
|
||||||
"file_life_time": 600,
|
"file_life_time": 600,
|
||||||
|
|||||||
@@ -1,729 +0,0 @@
|
|||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"msw-open-music/internal/pkg/database"
|
|
||||||
"msw-open-music/internal/pkg/tmpfs"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type API struct {
|
|
||||||
Db *database.Database
|
|
||||||
Server http.Server
|
|
||||||
token string
|
|
||||||
APIConfig APIConfig
|
|
||||||
Tmpfs *tmpfs.Tmpfs
|
|
||||||
}
|
|
||||||
|
|
||||||
type FfmpegConfigs struct {
|
|
||||||
FfmpegConfigs map[string]*FfmpegConfig `json:"ffmpeg_configs"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type AddFfmpegConfigRequest struct {
|
|
||||||
Token string `json:"token"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
FfmpegConfig FfmpegConfig `json:"ffmpeg_config"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type FfmpegConfig struct {
|
|
||||||
Args string `json:"args"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Status struct {
|
|
||||||
Status string `json:"status,omitempty"`
|
|
||||||
}
|
|
||||||
var ok Status = Status{
|
|
||||||
Status: "OK",
|
|
||||||
}
|
|
||||||
|
|
||||||
type WalkRequest struct {
|
|
||||||
Token string `json:"token"`
|
|
||||||
Root string `json:"root"`
|
|
||||||
Pattern []string `json:"pattern"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type ResetRequest struct {
|
|
||||||
Token string `json:"token"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type SearchFilesRequest struct {
|
|
||||||
Filename string `json:"filename"`
|
|
||||||
Limit int64 `json:"limit"`
|
|
||||||
Offset int64 `json:"offset"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type SearchFoldersRequest struct {
|
|
||||||
Foldername string `json:"foldername"`
|
|
||||||
Limit int64 `json:"limit"`
|
|
||||||
Offset int64 `json:"offset"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type SearchFilesResponse struct {
|
|
||||||
Files []database.File `json:"files"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type SearchFoldersResponse struct {
|
|
||||||
Folders []database.Folder `json:"folders"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetFilesInFolderRequest struct {
|
|
||||||
Folder_id int64 `json:"folder_id"`
|
|
||||||
Limit int64 `json:"limit"`
|
|
||||||
Offset int64 `json:"offset"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetFilesInFolderResponse struct {
|
|
||||||
Files *[]database.File `json:"files"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetRandomFilesResponse struct {
|
|
||||||
Files *[]database.File `json:"files"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleGetRandomFiles(w http.ResponseWriter, r *http.Request) {
|
|
||||||
files, err := api.Db.GetRandomFiles(10);
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
getRandomFilesResponse := &GetRandomFilesResponse{
|
|
||||||
Files: &files,
|
|
||||||
}
|
|
||||||
log.Println("[api] Get random files")
|
|
||||||
json.NewEncoder(w).Encode(getRandomFilesResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleGetFilesInFolder(w http.ResponseWriter, r *http.Request) {
|
|
||||||
getFilesInFolderRequest := &GetFilesInFolderRequest{
|
|
||||||
Folder_id: -1,
|
|
||||||
}
|
|
||||||
|
|
||||||
err := json.NewDecoder(r.Body).Decode(getFilesInFolderRequest)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check empyt
|
|
||||||
if getFilesInFolderRequest.Folder_id < 0 {
|
|
||||||
api.HandleErrorString(w, r, `"folder_id" can't be none or negative`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
files, err := api.Db.GetFilesInFolder(getFilesInFolderRequest.Folder_id, getFilesInFolderRequest.Limit, getFilesInFolderRequest.Offset)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
getFilesInFolderResponse := &GetFilesInFolderResponse{
|
|
||||||
Files: &files,
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[api] Get files in folder", getFilesInFolderRequest.Folder_id)
|
|
||||||
|
|
||||||
json.NewEncoder(w).Encode(getFilesInFolderResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) CheckToken(w http.ResponseWriter, r *http.Request, token string) (error) {
|
|
||||||
if token != api.token {
|
|
||||||
err := errors.New("token not matched")
|
|
||||||
log.Println("[api] [Warning] Token not matched", token)
|
|
||||||
api.HandleErrorCode(w, r, err, 403)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
log.Println("[api] Token passed")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleError(w http.ResponseWriter, r *http.Request, err error) {
|
|
||||||
api.HandleErrorString(w, r, err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleErrorCode(w http.ResponseWriter, r *http.Request, err error, code int) {
|
|
||||||
api.HandleErrorStringCode(w, r, err.Error(), code)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleErrorString(w http.ResponseWriter, r *http.Request, errorString string) {
|
|
||||||
api.HandleErrorStringCode(w, r, errorString, 500)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleErrorStringCode(w http.ResponseWriter, r *http.Request, errorString string, code int) {
|
|
||||||
log.Println("[api] [Error]", code, errorString)
|
|
||||||
errStatus := &Status{
|
|
||||||
Status: errorString,
|
|
||||||
}
|
|
||||||
w.WriteHeader(code)
|
|
||||||
json.NewEncoder(w).Encode(errStatus)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleReset(w http.ResponseWriter, r *http.Request) {
|
|
||||||
resetRequest := &ResetRequest{}
|
|
||||||
err := json.NewDecoder(r.Body).Decode(resetRequest)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check token
|
|
||||||
err = api.CheckToken(w, r, resetRequest.Token)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// reset
|
|
||||||
err = api.Db.ResetFiles()
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
err = api.Db.ResetFolder()
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
api.HandleStatus(w, r, "Database reseted")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleWalk(w http.ResponseWriter, r *http.Request) {
|
|
||||||
walkRequest := &WalkRequest{}
|
|
||||||
err := json.NewDecoder(r.Body).Decode(walkRequest)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check token match
|
|
||||||
err = api.CheckToken(w, r, walkRequest.Token)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check root empty
|
|
||||||
if walkRequest.Root == "" {
|
|
||||||
api.HandleErrorString(w, r, `key "root" can't be empty`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check pattern empty
|
|
||||||
if len(walkRequest.Pattern) == 0 {
|
|
||||||
api.HandleErrorString(w, r, `"[]pattern" can't be empty`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// walk
|
|
||||||
err = api.Db.Walk(walkRequest.Root, walkRequest.Pattern)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
api.HandleStatus(w, r, "Database udpated")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleOK(w http.ResponseWriter, r *http.Request) {
|
|
||||||
json.NewEncoder(w).Encode(&ok)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleStatus(w http.ResponseWriter, r *http.Request, status string) {
|
|
||||||
s := &Status{
|
|
||||||
Status: status,
|
|
||||||
}
|
|
||||||
|
|
||||||
json.NewEncoder(w).Encode(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleSearchFiles(w http.ResponseWriter, r *http.Request) {
|
|
||||||
searchFilesRequest := &SearchFilesRequest{}
|
|
||||||
err := json.NewDecoder(r.Body).Decode(searchFilesRequest)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check empty
|
|
||||||
if searchFilesRequest.Filename == "" {
|
|
||||||
api.HandleErrorString(w, r, `"filename" can't be empty`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if api.CheckLimit(w, r, searchFilesRequest.Limit) != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
searchFilesResponse := &SearchFilesResponse{}
|
|
||||||
|
|
||||||
searchFilesResponse.Files, err = api.Db.SearchFiles(searchFilesRequest.Filename, searchFilesRequest.Limit, searchFilesRequest.Offset)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[api] Search files", searchFilesRequest.Filename, searchFilesRequest.Limit, searchFilesRequest.Offset)
|
|
||||||
|
|
||||||
json.NewEncoder(w).Encode(searchFilesResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) CheckLimit(w http.ResponseWriter, r *http.Request, limit int64) (error) {
|
|
||||||
if limit <= 0 || limit > 10 {
|
|
||||||
log.Println("[api] [Warning] Limit error", limit)
|
|
||||||
err := errors.New(`"limit" can't be zero or more than 10`)
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleSearchFolders(w http.ResponseWriter, r *http.Request) {
|
|
||||||
searchFoldersRequest := &SearchFoldersRequest{}
|
|
||||||
err := json.NewDecoder(r.Body).Decode(searchFoldersRequest)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check empty
|
|
||||||
if searchFoldersRequest.Foldername == "" {
|
|
||||||
api.HandleErrorString(w, r, `"foldername" can't be empty`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if api.CheckLimit(w, r, searchFoldersRequest.Limit) != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
searchFoldersResponse := &SearchFoldersResponse{}
|
|
||||||
|
|
||||||
searchFoldersResponse.Folders, err = api.Db.SearchFolders(searchFoldersRequest.Foldername, searchFoldersRequest.Limit, searchFoldersRequest.Offset)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[api] Search folders", searchFoldersRequest.Foldername, searchFoldersRequest.Limit, searchFoldersRequest.Offset)
|
|
||||||
|
|
||||||
json.NewEncoder(w).Encode(searchFoldersResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
type GetFileRequest struct {
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleGetFileInfo(w http.ResponseWriter, r *http.Request) {
|
|
||||||
getFileRequest := &GetFileRequest{
|
|
||||||
ID: -1,
|
|
||||||
}
|
|
||||||
|
|
||||||
err := json.NewDecoder(r.Body).Decode(getFileRequest)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check empty
|
|
||||||
if getFileRequest.ID < 0 {
|
|
||||||
api.HandleErrorString(w, r, `"id" can't be none or negative`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := api.Db.GetFile(getFileRequest.ID)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err = json.NewEncoder(w).Encode(file)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) CheckGetFileStream(w http.ResponseWriter, r *http.Request) (error) {
|
|
||||||
var err error
|
|
||||||
q := r.URL.Query()
|
|
||||||
ids := q["id"]
|
|
||||||
if len(ids) == 0 {
|
|
||||||
err = errors.New(`parameter "id" can't be empty`)
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err = strconv.Atoi(ids[0])
|
|
||||||
if err != nil {
|
|
||||||
err = errors.New(`parameter "id" should be an integer`)
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
configs := q["config"]
|
|
||||||
if len(configs) == 0 {
|
|
||||||
err = errors.New(`parameter "config" can't be empty`)
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleGetFileStream(w http.ResponseWriter, r *http.Request) {
|
|
||||||
err := api.CheckGetFileStream(w, r)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
q := r.URL.Query()
|
|
||||||
ids := q["id"]
|
|
||||||
id, err := strconv.Atoi(ids[0])
|
|
||||||
configs := q["config"]
|
|
||||||
configName := configs[0]
|
|
||||||
file, err := api.Db.GetFile(int64(id))
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
path, err := file.Path()
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[api] Stream file", path, configName)
|
|
||||||
|
|
||||||
ffmpegConfig, ok := api.APIConfig.FfmpegConfigs[configName]
|
|
||||||
if !ok {
|
|
||||||
api.HandleErrorStringCode(w, r, `ffmpeg config not found`, 404)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
args := strings.Split(ffmpegConfig.Args, " ")
|
|
||||||
startArgs := []string {"-threads", strconv.FormatInt(api.APIConfig.FfmpegThreads, 10), "-i", path}
|
|
||||||
endArgs := []string {"-vn", "-f", "ogg", "-"}
|
|
||||||
ffmpegArgs := append(startArgs, args...)
|
|
||||||
ffmpegArgs = append(ffmpegArgs, endArgs...)
|
|
||||||
cmd := exec.Command("ffmpeg", ffmpegArgs...)
|
|
||||||
cmd.Stdout = w
|
|
||||||
err = cmd.Run()
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type PrepareFileStreamDirectRequest struct {
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
ConfigName string `json:"config_name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type PrepareFileStreamDirectResponse struct {
|
|
||||||
Filesize int64 `json:"filesize"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandlePrepareFileStreamDirect(w http.ResponseWriter, r *http.Request) {
|
|
||||||
prepareFileStreamDirectRequst := &PrepareFileStreamDirectRequest{
|
|
||||||
ID: -1,
|
|
||||||
}
|
|
||||||
err := json.NewDecoder(r.Body).Decode(prepareFileStreamDirectRequst)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check empty
|
|
||||||
if prepareFileStreamDirectRequst.ID < 0 {
|
|
||||||
api.HandleErrorString(w, r, `"id" can't be none or negative`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if prepareFileStreamDirectRequst.ConfigName == "" {
|
|
||||||
api.HandleErrorString(w, r, `"config_name" can't be empty`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := api.Db.GetFile(prepareFileStreamDirectRequst.ID)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
srcPath, err := file.Path()
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[api] Prepare stream direct file", srcPath, prepareFileStreamDirectRequst.ConfigName)
|
|
||||||
ffmpegConfig, ok := api.APIConfig.FfmpegConfigs[prepareFileStreamDirectRequst.ConfigName]
|
|
||||||
if !ok {
|
|
||||||
api.HandleErrorStringCode(w, r, `ffmpeg config not found`, 404)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
objPath := api.Tmpfs.GetObjFilePath(prepareFileStreamDirectRequst.ID, prepareFileStreamDirectRequst.ConfigName)
|
|
||||||
|
|
||||||
// check obj file exists
|
|
||||||
exists := api.Tmpfs.Exits(objPath)
|
|
||||||
if exists {
|
|
||||||
fileInfo, err := os.Stat(objPath)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
prepareFileStreamDirectResponse := &PrepareFileStreamDirectResponse{
|
|
||||||
Filesize: fileInfo.Size(),
|
|
||||||
}
|
|
||||||
json.NewEncoder(w).Encode(prepareFileStreamDirectResponse)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
api.Tmpfs.Record(objPath)
|
|
||||||
args := strings.Split(ffmpegConfig.Args, " ")
|
|
||||||
startArgs := []string {"-threads", strconv.FormatInt(api.APIConfig.FfmpegThreads, 10), "-i", srcPath}
|
|
||||||
endArgs := []string {"-vn", "-y", objPath}
|
|
||||||
ffmpegArgs := append(startArgs, args...)
|
|
||||||
ffmpegArgs = append(ffmpegArgs, endArgs...)
|
|
||||||
cmd := exec.Command("ffmpeg", ffmpegArgs...)
|
|
||||||
err = cmd.Run()
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
fileInfo, err := os.Stat(objPath)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
prepareFileStreamDirectResponse := &PrepareFileStreamDirectResponse{
|
|
||||||
Filesize: fileInfo.Size(),
|
|
||||||
}
|
|
||||||
json.NewEncoder(w).Encode(prepareFileStreamDirectResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleGetFileStreamDirect(w http.ResponseWriter, r *http.Request) {
|
|
||||||
err := api.CheckGetFileStream(w, r)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
q := r.URL.Query()
|
|
||||||
ids := q["id"]
|
|
||||||
id, err := strconv.Atoi(ids[0])
|
|
||||||
configs := q["config"]
|
|
||||||
configName := configs[0]
|
|
||||||
|
|
||||||
path := api.Tmpfs.GetObjFilePath(int64(id), configName)
|
|
||||||
if api.Tmpfs.Exits(path) {
|
|
||||||
api.Tmpfs.Record(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[api] Get direct cached file", path)
|
|
||||||
|
|
||||||
http.ServeFile(w, r, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleGetFileDirect(w http.ResponseWriter, r *http.Request) {
|
|
||||||
q := r.URL.Query()
|
|
||||||
ids := q["id"]
|
|
||||||
if len(ids) == 0 {
|
|
||||||
api.HandleErrorString(w, r, `parameter "id" can't be empty`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
id, err := strconv.Atoi(ids[0])
|
|
||||||
if err != nil {
|
|
||||||
api.HandleErrorString(w, r, `parameter "id" should be an integer`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
file, err := api.Db.GetFile(int64(id))
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
path, err := file.Path()
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[api] Get direct raw file", path)
|
|
||||||
|
|
||||||
http.ServeFile(w, r, path)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleGetFile(w http.ResponseWriter, r *http.Request) {
|
|
||||||
getFileRequest := &GetFileRequest{
|
|
||||||
ID: -1,
|
|
||||||
}
|
|
||||||
|
|
||||||
err := json.NewDecoder(r.Body).Decode(getFileRequest)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check empty
|
|
||||||
if getFileRequest.ID < 0 {
|
|
||||||
api.HandleErrorString(w, r, `"id" can't be none or negative`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := api.Db.GetFile(getFileRequest.ID)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
path, err := file.Path()
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[api] Get pipe raw file", path)
|
|
||||||
|
|
||||||
src, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer src.Close()
|
|
||||||
io.Copy(w, src)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleGetFfmpegConfigs(w http.ResponseWriter, r *http.Request) {
|
|
||||||
log.Println("[api] Get ffmpeg config list")
|
|
||||||
ffmpegConfigs:= &FfmpegConfigs{
|
|
||||||
FfmpegConfigs: api.APIConfig.FfmpegConfigs,
|
|
||||||
}
|
|
||||||
json.NewEncoder(w).Encode(&ffmpegConfigs)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleAddFfmpegConfig(w http.ResponseWriter, r *http.Request) {
|
|
||||||
addFfmpegConfigRequest := AddFfmpegConfigRequest{}
|
|
||||||
err := json.NewDecoder(r.Body).Decode(&addFfmpegConfigRequest)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check token
|
|
||||||
err = api.CheckToken(w, r, addFfmpegConfigRequest.Token)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check name and args not null
|
|
||||||
if addFfmpegConfigRequest.Name == "" {
|
|
||||||
api.HandleErrorString(w, r, `"ffmpeg_config.name" can't be empty`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if addFfmpegConfigRequest.FfmpegConfig.Args == "" {
|
|
||||||
api.HandleErrorString(w, r, `"ffmpeg_config.args" can't be empty`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[api] Add ffmpeg config")
|
|
||||||
|
|
||||||
api.APIConfig.FfmpegConfigs[addFfmpegConfigRequest.Name] = &addFfmpegConfigRequest.FfmpegConfig
|
|
||||||
api.HandleOK(w, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
type FeedbackRequest struct {
|
|
||||||
Feedback string `json:"feedback"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (api *API) HandleFeedback(w http.ResponseWriter, r *http.Request) {
|
|
||||||
feedbackRequest := &FeedbackRequest{}
|
|
||||||
err :=json.NewDecoder(r.Body).Decode(feedbackRequest)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// check empty feedback
|
|
||||||
if feedbackRequest.Feedback == "" {
|
|
||||||
api.HandleErrorString(w, r, `"feedback" can't be empty`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("[api] Feedback", feedbackRequest.Feedback)
|
|
||||||
|
|
||||||
headerBuff := &bytes.Buffer{}
|
|
||||||
err = r.Header.Write(headerBuff)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
header := headerBuff.String()
|
|
||||||
|
|
||||||
err = api.Db.InsertFeedback(time.Now().Unix(), feedbackRequest.Feedback, header)
|
|
||||||
if err != nil {
|
|
||||||
api.HandleError(w, r, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
api.HandleOK(w, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewAPIConfig() (APIConfig) {
|
|
||||||
apiConfig := APIConfig{
|
|
||||||
FfmpegConfigs: make(map[string]*FfmpegConfig),
|
|
||||||
}
|
|
||||||
return apiConfig
|
|
||||||
}
|
|
||||||
|
|
||||||
type APIConfig struct {
|
|
||||||
DatabaseName string `json:"database_name"`
|
|
||||||
Addr string `json:"addr"`
|
|
||||||
Token string `json:"token"`
|
|
||||||
FfmpegThreads int64 `json:"ffmpeg_threads"`
|
|
||||||
FfmpegConfigs map[string]*FfmpegConfig `json:"ffmpeg_configs"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewAPI(apiConfig APIConfig, tmpfsConfig tmpfs.TmpfsConfig) (*API, error) {
|
|
||||||
var err error
|
|
||||||
|
|
||||||
db, err := database.NewDatabase(apiConfig.DatabaseName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
|
||||||
apiMux := http.NewServeMux()
|
|
||||||
|
|
||||||
api := &API{
|
|
||||||
Db: db,
|
|
||||||
Server: http.Server{
|
|
||||||
Addr: apiConfig.Addr,
|
|
||||||
Handler: mux,
|
|
||||||
},
|
|
||||||
APIConfig: apiConfig,
|
|
||||||
}
|
|
||||||
api.Tmpfs = tmpfs.NewTmpfs(tmpfsConfig)
|
|
||||||
|
|
||||||
// mount api
|
|
||||||
apiMux.HandleFunc("/hello", api.HandleOK)
|
|
||||||
apiMux.HandleFunc("/get_file", api.HandleGetFile)
|
|
||||||
apiMux.HandleFunc("/get_file_direct", api.HandleGetFileDirect)
|
|
||||||
apiMux.HandleFunc("/search_files", api.HandleSearchFiles)
|
|
||||||
apiMux.HandleFunc("/search_folders", api.HandleSearchFolders)
|
|
||||||
apiMux.HandleFunc("/get_files_in_folder", api.HandleGetFilesInFolder)
|
|
||||||
apiMux.HandleFunc("/get_random_files", api.HandleGetRandomFiles)
|
|
||||||
apiMux.HandleFunc("/get_file_stream", api.HandleGetFileStream)
|
|
||||||
apiMux.HandleFunc("/get_ffmpeg_config_list", api.HandleGetFfmpegConfigs)
|
|
||||||
apiMux.HandleFunc("/feedback", api.HandleFeedback)
|
|
||||||
apiMux.HandleFunc("/get_file_info", api.HandleGetFileInfo)
|
|
||||||
apiMux.HandleFunc("/get_file_stream_direct", api.HandleGetFileStreamDirect)
|
|
||||||
apiMux.HandleFunc("/prepare_file_stream_direct", api.HandlePrepareFileStreamDirect)
|
|
||||||
// below needs token
|
|
||||||
apiMux.HandleFunc("/walk", api.HandleWalk)
|
|
||||||
apiMux.HandleFunc("/reset", api.HandleReset)
|
|
||||||
apiMux.HandleFunc("/add_ffmpeg_config", api.HandleAddFfmpegConfig)
|
|
||||||
|
|
||||||
mux.Handle("/api/v1/", http.StripPrefix("/api/v1", apiMux))
|
|
||||||
mux.Handle("/web/", http.StripPrefix("/web", http.FileServer(http.Dir("web"))))
|
|
||||||
|
|
||||||
api.token = apiConfig.Token
|
|
||||||
|
|
||||||
return api, nil
|
|
||||||
}
|
|
||||||
@@ -1,441 +0,0 @@
|
|||||||
package database
|
|
||||||
|
|
||||||
import (
|
|
||||||
"database/sql"
|
|
||||||
"errors"
|
|
||||||
"log"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
|
|
||||||
_ "github.com/mattn/go-sqlite3"
|
|
||||||
)
|
|
||||||
|
|
||||||
var initFilesTableQuery = `CREATE TABLE IF NOT EXISTS files (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
folder_id INTEGER NOT NULL,
|
|
||||||
filename TEXT NOT NULL,
|
|
||||||
filesize INTEGER NOT NULL
|
|
||||||
);`
|
|
||||||
var initFoldersTableQuery = `CREATE TABLE IF NOT EXISTS folders (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
folder TEXT NOT NULL,
|
|
||||||
foldername TEXT NOT NULL
|
|
||||||
);`
|
|
||||||
var initFeedbacksTableQuery = `CREATE TABLE IF NOT EXISTS feedbacks (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
time INTEGER NOT NULL,
|
|
||||||
feedback TEXT NOT NULL,
|
|
||||||
header TEXT NOT NULL
|
|
||||||
);`
|
|
||||||
var insertFolderQuery = `INSERT INTO folders (folder, foldername) VALUES (?, ?);`
|
|
||||||
var findFolderQuery = `SELECT id FROM folders WHERE folder = ? LIMIT 1;`
|
|
||||||
var insertFileQuery = `INSERT INTO files (folder_id, filename, filesize) VALUES (?, ?, ?);`
|
|
||||||
var searchFilesQuery = `SELECT files.id, files.folder_id, files.filename, folders.foldername, files.filesize FROM files JOIN folders ON files.folder_id = folders.id WHERE filename LIKE ? LIMIT ? OFFSET ?;`
|
|
||||||
var getFolderQuery = `SELECT folder FROM folders WHERE id = ? LIMIT 1;`
|
|
||||||
var dropFilesQuery = `DROP TABLE files;`
|
|
||||||
var dropFolderQuery = `DROP TABLE folders;`
|
|
||||||
var getFileQuery = `SELECT files.id, files.folder_id, files.filename, folders.foldername, files.filesize FROM files JOIN folders ON files.folder_id = folders.id WHERE files.id = ? LIMIT 1;`
|
|
||||||
var searchFoldersQuery = `SELECT id, folder, foldername FROM folders WHERE foldername LIKE ? LIMIT ? OFFSET ?;`
|
|
||||||
var getFilesInFolderQuery = `SELECT files.id, files.filename, files.filesize, folders.foldername FROM files JOIN folders ON files.folder_id = folders.id WHERE folder_id = ? LIMIT ? OFFSET ?;`
|
|
||||||
var getRandomFilesQuery = `SELECT files.id, files.folder_id, files.filename, folders.foldername, files.filesize FROM files JOIN folders on files.folder_id = folders.id ORDER BY RANDOM() LIMIT ?;`
|
|
||||||
var insertFeedbackQuery = `INSERT INTO feedbacks (time, feedback, header) VALUES (?, ?, ?);`
|
|
||||||
|
|
||||||
type Database struct {
|
|
||||||
sqlConn *sql.DB
|
|
||||||
stmt *Stmt
|
|
||||||
}
|
|
||||||
|
|
||||||
type Stmt struct {
|
|
||||||
initFilesTable *sql.Stmt
|
|
||||||
initFoldersTable *sql.Stmt
|
|
||||||
initFeedbacksTable *sql.Stmt
|
|
||||||
insertFolder *sql.Stmt
|
|
||||||
insertFile *sql.Stmt
|
|
||||||
findFolder *sql.Stmt
|
|
||||||
searchFiles *sql.Stmt
|
|
||||||
getFolder *sql.Stmt
|
|
||||||
dropFiles *sql.Stmt
|
|
||||||
dropFolder *sql.Stmt
|
|
||||||
getFile *sql.Stmt
|
|
||||||
searchFolders *sql.Stmt
|
|
||||||
getFilesInFolder *sql.Stmt
|
|
||||||
getRandomFiles *sql.Stmt
|
|
||||||
insertFeedback *sql.Stmt
|
|
||||||
}
|
|
||||||
|
|
||||||
type File struct {
|
|
||||||
Db *Database `json:"-"`
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
Folder_id int64 `json:"folder_id"`
|
|
||||||
Foldername string `json:"foldername"`
|
|
||||||
Filename string `json:"filename"`
|
|
||||||
Filesize int64 `json:"filesize"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Folder struct {
|
|
||||||
Db *Database `json:"-"`
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
Folder string `json:"-"`
|
|
||||||
Foldername string `json:"foldername"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) InsertFeedback(time int64, feedback string, header string) (error) {
|
|
||||||
_, err := database.stmt.insertFeedback.Exec(time, feedback, header)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) GetRandomFiles(limit int64) ([]File, error) {
|
|
||||||
rows, err := database.stmt.getRandomFiles.Query(limit)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
files := make([]File, 0)
|
|
||||||
for rows.Next() {
|
|
||||||
file := File{
|
|
||||||
Db: database,
|
|
||||||
}
|
|
||||||
err = rows.Scan(&file.ID, &file.Folder_id, &file.Filename, &file.Foldername, &file.Filesize)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
files = append(files, file)
|
|
||||||
}
|
|
||||||
return files, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) GetFilesInFolder(folder_id int64, limit int64, offset int64) ([]File, error) {
|
|
||||||
rows, err := database.stmt.getFilesInFolder.Query(folder_id, limit, offset)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
files := make([]File, 0)
|
|
||||||
for rows.Next() {
|
|
||||||
file := File{
|
|
||||||
Db: database,
|
|
||||||
Folder_id: folder_id,
|
|
||||||
}
|
|
||||||
err = rows.Scan(&file.ID, &file.Filename, &file.Filesize, &file.Foldername)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
files = append(files, file)
|
|
||||||
}
|
|
||||||
return files, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) SearchFolders(foldername string, limit int64, offset int64) ([]Folder, error) {
|
|
||||||
rows, err := database.stmt.searchFolders.Query("%"+foldername+"%", limit, offset)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("Error searching folders at query " + err.Error())
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
folders := make([]Folder, 0)
|
|
||||||
for rows.Next() {
|
|
||||||
folder := Folder{
|
|
||||||
Db: database,
|
|
||||||
}
|
|
||||||
err = rows.Scan(&folder.ID, &folder.Folder, &folder.Foldername)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("Error scanning SearchFolders" + err.Error())
|
|
||||||
}
|
|
||||||
folders = append(folders, folder)
|
|
||||||
}
|
|
||||||
return folders, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) GetFile(id int64) (*File, error) {
|
|
||||||
file := &File{
|
|
||||||
Db: database,
|
|
||||||
}
|
|
||||||
err := database.stmt.getFile.QueryRow(id).Scan(&file.ID, &file.Folder_id, &file.Filename, &file.Foldername, &file.Filesize)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return file, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) ResetFiles() (error) {
|
|
||||||
log.Println("[db] Reset files")
|
|
||||||
var err error
|
|
||||||
_, err = database.stmt.dropFiles.Exec()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err = database.stmt.initFilesTable.Exec()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) ResetFolder() (error) {
|
|
||||||
log.Println("[db] Reset folders")
|
|
||||||
var err error
|
|
||||||
_, err = database.stmt.dropFolder.Exec()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err = database.stmt.initFoldersTable.Exec()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) Walk(root string, pattern []string) (error) {
|
|
||||||
patternDict := make(map[string]bool)
|
|
||||||
for _, v := range pattern {
|
|
||||||
patternDict[v] = true
|
|
||||||
}
|
|
||||||
log.Println("[db] Walk", root, patternDict)
|
|
||||||
return filepath.Walk(root, func (path string, info os.FileInfo, err error) (error) {
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if info.IsDir() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// check pattern
|
|
||||||
ext := filepath.Ext(info.Name())
|
|
||||||
if _, ok := patternDict[ext]; !ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// insert file, folder will aut created
|
|
||||||
err = database.Insert(path, info.Size())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *File) Path() (string, error) {
|
|
||||||
folder, err := f.Db.GetFolder(f.Folder_id)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return filepath.Join(folder.Folder, f.Filename), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) GetFolder(folderId int64) (*Folder, error) {
|
|
||||||
folder := &Folder{
|
|
||||||
Db: database,
|
|
||||||
}
|
|
||||||
err := database.stmt.getFolder.QueryRow(folderId).Scan(&folder.Folder)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return folder, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) SearchFiles(filename string, limit int64, offset int64) ([]File, error) {
|
|
||||||
rows, err := database.stmt.searchFiles.Query("%"+filename+"%", limit, offset)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("Error searching files at query " + err.Error())
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
files := make([]File, 0)
|
|
||||||
for rows.Next() {
|
|
||||||
var file File = File{
|
|
||||||
Db: database,
|
|
||||||
}
|
|
||||||
err = rows.Scan(&file.ID, &file.Folder_id, &file.Filename, &file.Foldername, &file.Filesize)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("Error scanning SearchFiles " + err.Error())
|
|
||||||
}
|
|
||||||
files = append(files, file)
|
|
||||||
}
|
|
||||||
if err = rows.Err(); err != nil {
|
|
||||||
return nil, errors.New("Error scanning SearchFiles exit without full result" + err.Error())
|
|
||||||
}
|
|
||||||
return files, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) FindFolder(folder string) (int64, error) {
|
|
||||||
var id int64
|
|
||||||
err := database.stmt.findFolder.QueryRow(folder).Scan(&id)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return id, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) InsertFolder(folder string) (int64, error) {
|
|
||||||
result, err := database.stmt.insertFolder.Exec(folder, filepath.Base(folder))
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
lastInsertId, err := result.LastInsertId()
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return lastInsertId, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) InsertFile(folderId int64, filename string, filesize int64) (error) {
|
|
||||||
_, err := database.stmt.insertFile.Exec(folderId, filename, filesize)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (database *Database) Insert(path string, filesize int64) (error) {
|
|
||||||
folder, filename := filepath.Split(path)
|
|
||||||
folderId, err := database.FindFolder(folder)
|
|
||||||
if err != nil {
|
|
||||||
folderId, err = database.InsertFolder(folder)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
err = database.InsertFile(folderId, filename, filesize)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPreparedStatement(sqlConn *sql.DB) (*Stmt, error) {
|
|
||||||
var err error
|
|
||||||
|
|
||||||
stmt := &Stmt{}
|
|
||||||
|
|
||||||
// init files table
|
|
||||||
stmt.initFilesTable, err = sqlConn.Prepare(initFilesTableQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init folders table
|
|
||||||
stmt.initFoldersTable, err = sqlConn.Prepare(initFoldersTableQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init feedbacks tables
|
|
||||||
stmt.initFeedbacksTable, err = sqlConn.Prepare(initFeedbacksTableQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// run init statement
|
|
||||||
_, err = stmt.initFilesTable.Exec()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
_, err = stmt.initFoldersTable.Exec()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
_, err = stmt.initFeedbacksTable.Exec()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init insert folder statement
|
|
||||||
stmt.insertFolder, err = sqlConn.Prepare(insertFolderQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init findFolder statement
|
|
||||||
stmt.findFolder, err = sqlConn.Prepare(findFolderQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init insertFile stmt
|
|
||||||
stmt.insertFile, err = sqlConn.Prepare(insertFileQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init searchFile stmt
|
|
||||||
stmt.searchFiles, err = sqlConn.Prepare(searchFilesQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init getFolder stmt
|
|
||||||
stmt.getFolder, err = sqlConn.Prepare(getFolderQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init dropFolder stmt
|
|
||||||
stmt.dropFolder, err = sqlConn.Prepare(dropFolderQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init dropFiles stmt
|
|
||||||
stmt.dropFiles, err = sqlConn.Prepare(dropFilesQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init getFile stmt
|
|
||||||
stmt.getFile, err = sqlConn.Prepare(getFileQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init searchFolder stmt
|
|
||||||
stmt.searchFolders, err = sqlConn.Prepare(searchFoldersQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init getFilesInFolder stmt
|
|
||||||
stmt.getFilesInFolder, err = sqlConn.Prepare(getFilesInFolderQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init getRandomFiles
|
|
||||||
stmt.getRandomFiles, err = sqlConn.Prepare(getRandomFilesQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// init insertFeedback
|
|
||||||
stmt.insertFeedback, err = sqlConn.Prepare(insertFeedbackQuery)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return stmt, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDatabase(dbName string) (*Database, error) {
|
|
||||||
var err error
|
|
||||||
|
|
||||||
// open database
|
|
||||||
sqlConn, err := sql.Open("sqlite3", dbName)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// prepare statement
|
|
||||||
stmt, err := NewPreparedStatement(sqlConn)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// new database
|
|
||||||
database := &Database{
|
|
||||||
sqlConn: sqlConn,
|
|
||||||
stmt: stmt,
|
|
||||||
}
|
|
||||||
|
|
||||||
return database, nil
|
|
||||||
}
|
|
||||||
11
main.go
11
main.go
@@ -4,8 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"flag"
|
"flag"
|
||||||
"log"
|
"log"
|
||||||
"msw-open-music/internal/pkg/api"
|
"msw-open-music/pkg/api"
|
||||||
"msw-open-music/internal/pkg/tmpfs"
|
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -15,16 +14,12 @@ func init() {
|
|||||||
flag.StringVar(&ConfigFilePath, "config", "config.json", "backend config file path")
|
flag.StringVar(&ConfigFilePath, "config", "config.json", "backend config file path")
|
||||||
}
|
}
|
||||||
|
|
||||||
type Config struct {
|
|
||||||
APIConfig api.APIConfig `json:"api"`
|
|
||||||
TmpfsConfig tmpfs.TmpfsConfig `json:"tmpfs"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var err error
|
var err error
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
config := Config{}
|
config := api.Config{}
|
||||||
configFile, err := os.Open(ConfigFilePath)
|
configFile, err := os.Open(ConfigFilePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
@@ -35,7 +30,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
configFile.Close()
|
configFile.Close()
|
||||||
|
|
||||||
api, err := api.NewAPI(config.APIConfig, config.TmpfsConfig)
|
api, err := api.NewAPI(config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
84
pkg/api/api.go
Normal file
84
pkg/api/api.go
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"msw-open-music/pkg/database"
|
||||||
|
"msw-open-music/pkg/tmpfs"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type API struct {
|
||||||
|
Db *database.Database
|
||||||
|
Server http.Server
|
||||||
|
token string
|
||||||
|
APIConfig APIConfig
|
||||||
|
Tmpfs *tmpfs.Tmpfs
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAPIConfig() APIConfig {
|
||||||
|
apiConfig := APIConfig{}
|
||||||
|
return apiConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
type APIConfig struct {
|
||||||
|
DatabaseName string `json:"database_name"`
|
||||||
|
Addr string `json:"addr"`
|
||||||
|
Token string `json:"token"`
|
||||||
|
FfmpegThreads int64 `json:"ffmpeg_threads"`
|
||||||
|
FfmpegConfigList []FfmpegConfig `json:"ffmpeg_config_list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
APIConfig APIConfig `json:"api"`
|
||||||
|
TmpfsConfig tmpfs.TmpfsConfig `json:"tmpfs"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAPI(config Config) (*API, error) {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
apiConfig := config.APIConfig
|
||||||
|
tmpfsConfig := config.TmpfsConfig
|
||||||
|
|
||||||
|
db, err := database.NewDatabase(apiConfig.DatabaseName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
apiMux := http.NewServeMux()
|
||||||
|
|
||||||
|
api := &API{
|
||||||
|
Db: db,
|
||||||
|
Server: http.Server{
|
||||||
|
Addr: apiConfig.Addr,
|
||||||
|
Handler: mux,
|
||||||
|
},
|
||||||
|
APIConfig: apiConfig,
|
||||||
|
}
|
||||||
|
api.Tmpfs = tmpfs.NewTmpfs(tmpfsConfig)
|
||||||
|
|
||||||
|
// mount api
|
||||||
|
apiMux.HandleFunc("/hello", api.HandleOK)
|
||||||
|
apiMux.HandleFunc("/get_file", api.HandleGetFile)
|
||||||
|
apiMux.HandleFunc("/get_file_direct", api.HandleGetFileDirect)
|
||||||
|
apiMux.HandleFunc("/search_files", api.HandleSearchFiles)
|
||||||
|
apiMux.HandleFunc("/search_folders", api.HandleSearchFolders)
|
||||||
|
apiMux.HandleFunc("/get_files_in_folder", api.HandleGetFilesInFolder)
|
||||||
|
apiMux.HandleFunc("/get_random_files", api.HandleGetRandomFiles)
|
||||||
|
apiMux.HandleFunc("/get_file_stream", api.HandleGetFileStream)
|
||||||
|
apiMux.HandleFunc("/get_ffmpeg_config_list", api.HandleGetFfmpegConfigs)
|
||||||
|
apiMux.HandleFunc("/feedback", api.HandleFeedback)
|
||||||
|
apiMux.HandleFunc("/get_file_info", api.HandleGetFileInfo)
|
||||||
|
apiMux.HandleFunc("/get_file_stream_direct", api.HandleGetFileStreamDirect)
|
||||||
|
apiMux.HandleFunc("/prepare_file_stream_direct", api.HandlePrepareFileStreamDirect)
|
||||||
|
// below needs token
|
||||||
|
apiMux.HandleFunc("/walk", api.HandleWalk)
|
||||||
|
apiMux.HandleFunc("/reset", api.HandleReset)
|
||||||
|
apiMux.HandleFunc("/add_ffmpeg_config", api.HandleAddFfmpegConfig)
|
||||||
|
|
||||||
|
mux.Handle("/api/v1/", http.StripPrefix("/api/v1", apiMux))
|
||||||
|
mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("web/build"))))
|
||||||
|
|
||||||
|
api.token = apiConfig.Token
|
||||||
|
|
||||||
|
return api, nil
|
||||||
|
}
|
||||||
17
pkg/api/check.go
Normal file
17
pkg/api/check.go
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (api *API) CheckLimit(w http.ResponseWriter, r *http.Request, limit int64) error {
|
||||||
|
if limit <= 0 || limit > 10 {
|
||||||
|
log.Println("[api] [Warning] Limit error", limit)
|
||||||
|
err := errors.New(`"limit" can't be zero or more than 10`)
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
26
pkg/api/handle_common.go
Normal file
26
pkg/api/handle_common.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status struct {
|
||||||
|
Status string `json:"status,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleStatus(w http.ResponseWriter, r *http.Request, status string) {
|
||||||
|
s := &Status{
|
||||||
|
Status: status,
|
||||||
|
}
|
||||||
|
|
||||||
|
json.NewEncoder(w).Encode(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
var ok Status = Status{
|
||||||
|
Status: "OK",
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleOK(w http.ResponseWriter, r *http.Request) {
|
||||||
|
json.NewEncoder(w).Encode(&ok)
|
||||||
|
}
|
||||||
81
pkg/api/handle_database_manage.go
Normal file
81
pkg/api/handle_database_manage.go
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WalkRequest struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
Root string `json:"root"`
|
||||||
|
Pattern []string `json:"pattern"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResetRequest struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleReset(w http.ResponseWriter, r *http.Request) {
|
||||||
|
resetRequest := &ResetRequest{}
|
||||||
|
err := json.NewDecoder(r.Body).Decode(resetRequest)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check token
|
||||||
|
err = api.CheckToken(w, r, resetRequest.Token)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// reset
|
||||||
|
err = api.Db.ResetFiles()
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = api.Db.ResetFolder()
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
api.HandleStatus(w, r, "Database reseted")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleWalk(w http.ResponseWriter, r *http.Request) {
|
||||||
|
walkRequest := &WalkRequest{}
|
||||||
|
err := json.NewDecoder(r.Body).Decode(walkRequest)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check token match
|
||||||
|
err = api.CheckToken(w, r, walkRequest.Token)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check root empty
|
||||||
|
if walkRequest.Root == "" {
|
||||||
|
api.HandleErrorString(w, r, `key "root" can't be empty`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check pattern empty
|
||||||
|
if len(walkRequest.Pattern) == 0 {
|
||||||
|
api.HandleErrorString(w, r, `"[]pattern" can't be empty`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// walk
|
||||||
|
err = api.Db.Walk(walkRequest.Root, walkRequest.Pattern)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
api.HandleStatus(w, r, "Database udpated")
|
||||||
|
}
|
||||||
28
pkg/api/handle_error.go
Normal file
28
pkg/api/handle_error.go
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (api *API) HandleError(w http.ResponseWriter, r *http.Request, err error) {
|
||||||
|
api.HandleErrorString(w, r, err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleErrorCode(w http.ResponseWriter, r *http.Request, err error, code int) {
|
||||||
|
api.HandleErrorStringCode(w, r, err.Error(), code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleErrorString(w http.ResponseWriter, r *http.Request, errorString string) {
|
||||||
|
api.HandleErrorStringCode(w, r, errorString, 500)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleErrorStringCode(w http.ResponseWriter, r *http.Request, errorString string, code int) {
|
||||||
|
log.Println("[api] [Error]", code, errorString)
|
||||||
|
errStatus := &Status{
|
||||||
|
Status: errorString,
|
||||||
|
}
|
||||||
|
w.WriteHeader(code)
|
||||||
|
json.NewEncoder(w).Encode(errStatus)
|
||||||
|
}
|
||||||
45
pkg/api/handle_feedback.go
Normal file
45
pkg/api/handle_feedback.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FeedbackRequest struct {
|
||||||
|
Feedback string `json:"feedback"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleFeedback(w http.ResponseWriter, r *http.Request) {
|
||||||
|
feedbackRequest := &FeedbackRequest{}
|
||||||
|
err := json.NewDecoder(r.Body).Decode(feedbackRequest)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check empty feedback
|
||||||
|
if feedbackRequest.Feedback == "" {
|
||||||
|
api.HandleErrorString(w, r, `"feedback" can't be empty`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("[api] Feedback", feedbackRequest.Feedback)
|
||||||
|
|
||||||
|
headerBuff := &bytes.Buffer{}
|
||||||
|
err = r.Header.Write(headerBuff)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
header := headerBuff.String()
|
||||||
|
|
||||||
|
err = api.Db.InsertFeedback(time.Now().Unix(), feedbackRequest.Feedback, header)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
api.HandleOK(w, r)
|
||||||
|
}
|
||||||
74
pkg/api/handle_ffmpeg_config.go
Normal file
74
pkg/api/handle_ffmpeg_config.go
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FfmpegConfig struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Args string `json:"args"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type FfmpegConfigList struct {
|
||||||
|
FfmpegConfigList []FfmpegConfig `json:"ffmpeg_config_list"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) GetFfmpegConfig(configName string) (FfmpegConfig, bool) {
|
||||||
|
ffmpegConfig := FfmpegConfig{}
|
||||||
|
for _, f := range api.APIConfig.FfmpegConfigList {
|
||||||
|
if f.Name == configName {
|
||||||
|
ffmpegConfig = f
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ffmpegConfig.Name == "" {
|
||||||
|
return ffmpegConfig, false
|
||||||
|
}
|
||||||
|
return ffmpegConfig, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleGetFfmpegConfigs(w http.ResponseWriter, r *http.Request) {
|
||||||
|
log.Println("[api] Get ffmpeg config list")
|
||||||
|
ffmpegConfigList := &FfmpegConfigList{
|
||||||
|
FfmpegConfigList: api.APIConfig.FfmpegConfigList,
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(&ffmpegConfigList)
|
||||||
|
}
|
||||||
|
|
||||||
|
type AddFfmpegConfigRequest struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
FfmpegConfig FfmpegConfig `json:"ffmpeg_config"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleAddFfmpegConfig(w http.ResponseWriter, r *http.Request) {
|
||||||
|
addFfmpegConfigRequest := AddFfmpegConfigRequest{}
|
||||||
|
err := json.NewDecoder(r.Body).Decode(&addFfmpegConfigRequest)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check token
|
||||||
|
err = api.CheckToken(w, r, addFfmpegConfigRequest.Token)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check name and args not null
|
||||||
|
if addFfmpegConfigRequest.Name == "" {
|
||||||
|
api.HandleErrorString(w, r, `"ffmpeg_config.name" can't be empty`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if addFfmpegConfigRequest.FfmpegConfig.Args == "" {
|
||||||
|
api.HandleErrorString(w, r, `"ffmpeg_config.args" can't be empty`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("[api] Add ffmpeg config")
|
||||||
|
|
||||||
|
api.APIConfig.FfmpegConfigList = append(api.APIConfig.FfmpegConfigList, addFfmpegConfigRequest.FfmpegConfig)
|
||||||
|
|
||||||
|
api.HandleOK(w, r)
|
||||||
|
}
|
||||||
117
pkg/api/handle_get_file_info.go
Normal file
117
pkg/api/handle_get_file_info.go
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GetFileRequest struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleGetFileInfo(w http.ResponseWriter, r *http.Request) {
|
||||||
|
getFileRequest := &GetFileRequest{
|
||||||
|
ID: -1,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := json.NewDecoder(r.Body).Decode(getFileRequest)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check empty
|
||||||
|
if getFileRequest.ID < 0 {
|
||||||
|
api.HandleErrorString(w, r, `"id" can't be none or negative`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := api.Db.GetFile(getFileRequest.ID)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = json.NewEncoder(w).Encode(file)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// /get_file
|
||||||
|
// get raw file with io.Copy method
|
||||||
|
func (api *API) HandleGetFile(w http.ResponseWriter, r *http.Request) {
|
||||||
|
getFileRequest := &GetFileRequest{
|
||||||
|
ID: -1,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := json.NewDecoder(r.Body).Decode(getFileRequest)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check empty
|
||||||
|
if getFileRequest.ID < 0 {
|
||||||
|
api.HandleErrorString(w, r, `"id" can't be none or negative`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := api.Db.GetFile(getFileRequest.ID)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
path, err := file.Path()
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("[api] Get pipe raw file", path)
|
||||||
|
|
||||||
|
src, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer src.Close()
|
||||||
|
io.Copy(w, src)
|
||||||
|
}
|
||||||
|
|
||||||
|
// /get_file_direct?id=1
|
||||||
|
// get raw file with http.ServeFile method
|
||||||
|
func (api *API) HandleGetFileDirect(w http.ResponseWriter, r *http.Request) {
|
||||||
|
q := r.URL.Query()
|
||||||
|
ids := q["id"]
|
||||||
|
if len(ids) == 0 {
|
||||||
|
api.HandleErrorString(w, r, `parameter "id" can't be empty`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, err := strconv.Atoi(ids[0])
|
||||||
|
if err != nil {
|
||||||
|
api.HandleErrorString(w, r, `parameter "id" should be an integer`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
file, err := api.Db.GetFile(int64(id))
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
path, err := file.Path()
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("[api] Get direct raw file", path)
|
||||||
|
|
||||||
|
http.ServeFile(w, r, path)
|
||||||
|
}
|
||||||
50
pkg/api/handle_get_files_in_folder.go
Normal file
50
pkg/api/handle_get_files_in_folder.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"msw-open-music/pkg/database"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GetFilesInFolderRequest struct {
|
||||||
|
Folder_id int64 `json:"folder_id"`
|
||||||
|
Limit int64 `json:"limit"`
|
||||||
|
Offset int64 `json:"offset"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetFilesInFolderResponse struct {
|
||||||
|
Files *[]database.File `json:"files"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleGetFilesInFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
getFilesInFolderRequest := &GetFilesInFolderRequest{
|
||||||
|
Folder_id: -1,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := json.NewDecoder(r.Body).Decode(getFilesInFolderRequest)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check empyt
|
||||||
|
if getFilesInFolderRequest.Folder_id < 0 {
|
||||||
|
api.HandleErrorString(w, r, `"folder_id" can't be none or negative`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
files, err := api.Db.GetFilesInFolder(getFilesInFolderRequest.Folder_id, getFilesInFolderRequest.Limit, getFilesInFolderRequest.Offset)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
getFilesInFolderResponse := &GetFilesInFolderResponse{
|
||||||
|
Files: &files,
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("[api] Get files in folder", getFilesInFolderRequest.Folder_id)
|
||||||
|
|
||||||
|
json.NewEncoder(w).Encode(getFilesInFolderResponse)
|
||||||
|
}
|
||||||
25
pkg/api/handle_get_random_files.go
Normal file
25
pkg/api/handle_get_random_files.go
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"msw-open-music/pkg/database"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GetRandomFilesResponse struct {
|
||||||
|
Files *[]database.File `json:"files"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleGetRandomFiles(w http.ResponseWriter, r *http.Request) {
|
||||||
|
files, err := api.Db.GetRandomFiles(10)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
getRandomFilesResponse := &GetRandomFilesResponse{
|
||||||
|
Files: &files,
|
||||||
|
}
|
||||||
|
log.Println("[api] Get random files")
|
||||||
|
json.NewEncoder(w).Encode(getRandomFilesResponse)
|
||||||
|
}
|
||||||
48
pkg/api/handle_search_files.go
Normal file
48
pkg/api/handle_search_files.go
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"msw-open-music/pkg/database"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SearchFilesRequest struct {
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
Limit int64 `json:"limit"`
|
||||||
|
Offset int64 `json:"offset"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SearchFilesResponse struct {
|
||||||
|
Files []database.File `json:"files"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleSearchFiles(w http.ResponseWriter, r *http.Request) {
|
||||||
|
searchFilesRequest := &SearchFilesRequest{}
|
||||||
|
err := json.NewDecoder(r.Body).Decode(searchFilesRequest)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check empty
|
||||||
|
if searchFilesRequest.Filename == "" {
|
||||||
|
api.HandleErrorString(w, r, `"filename" can't be empty`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if api.CheckLimit(w, r, searchFilesRequest.Limit) != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
searchFilesResponse := &SearchFilesResponse{}
|
||||||
|
|
||||||
|
searchFilesResponse.Files, err = api.Db.SearchFiles(searchFilesRequest.Filename, searchFilesRequest.Limit, searchFilesRequest.Offset)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("[api] Search files", searchFilesRequest.Filename, searchFilesRequest.Limit, searchFilesRequest.Offset)
|
||||||
|
|
||||||
|
json.NewEncoder(w).Encode(searchFilesResponse)
|
||||||
|
}
|
||||||
48
pkg/api/handle_search_folders.go
Normal file
48
pkg/api/handle_search_folders.go
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"msw-open-music/pkg/database"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SearchFoldersRequest struct {
|
||||||
|
Foldername string `json:"foldername"`
|
||||||
|
Limit int64 `json:"limit"`
|
||||||
|
Offset int64 `json:"offset"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SearchFoldersResponse struct {
|
||||||
|
Folders []database.Folder `json:"folders"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (api *API) HandleSearchFolders(w http.ResponseWriter, r *http.Request) {
|
||||||
|
searchFoldersRequest := &SearchFoldersRequest{}
|
||||||
|
err := json.NewDecoder(r.Body).Decode(searchFoldersRequest)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check empty
|
||||||
|
if searchFoldersRequest.Foldername == "" {
|
||||||
|
api.HandleErrorString(w, r, `"foldername" can't be empty`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if api.CheckLimit(w, r, searchFoldersRequest.Limit) != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
searchFoldersResponse := &SearchFoldersResponse{}
|
||||||
|
|
||||||
|
searchFoldersResponse.Folders, err = api.Db.SearchFolders(searchFoldersRequest.Foldername, searchFoldersRequest.Limit, searchFoldersRequest.Offset)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("[api] Search folders", searchFoldersRequest.Foldername, searchFoldersRequest.Limit, searchFoldersRequest.Offset)
|
||||||
|
|
||||||
|
json.NewEncoder(w).Encode(searchFoldersResponse)
|
||||||
|
}
|
||||||
191
pkg/api/handle_stream.go
Normal file
191
pkg/api/handle_stream.go
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (api *API) CheckGetFileStream(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
var err error
|
||||||
|
q := r.URL.Query()
|
||||||
|
ids := q["id"]
|
||||||
|
if len(ids) == 0 {
|
||||||
|
err = errors.New(`parameter "id" can't be empty`)
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = strconv.Atoi(ids[0])
|
||||||
|
if err != nil {
|
||||||
|
err = errors.New(`parameter "id" should be an integer`)
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
configs := q["config"]
|
||||||
|
if len(configs) == 0 {
|
||||||
|
err = errors.New(`parameter "config" can't be empty`)
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// /get_file_stream?id=1&config=ffmpeg_config_name
|
||||||
|
func (api *API) HandleGetFileStream(w http.ResponseWriter, r *http.Request) {
|
||||||
|
err := api.CheckGetFileStream(w, r)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
q := r.URL.Query()
|
||||||
|
ids := q["id"]
|
||||||
|
id, err := strconv.Atoi(ids[0])
|
||||||
|
configs := q["config"]
|
||||||
|
configName := configs[0]
|
||||||
|
file, err := api.Db.GetFile(int64(id))
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
path, err := file.Path()
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("[api] Stream file", path, configName)
|
||||||
|
|
||||||
|
ffmpegConfig, ok := api.GetFfmpegConfig(configName)
|
||||||
|
if !ok {
|
||||||
|
api.HandleErrorStringCode(w, r, `ffmpeg config not found`, 404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
args := strings.Split(ffmpegConfig.Args, " ")
|
||||||
|
startArgs := []string{"-threads", strconv.FormatInt(api.APIConfig.FfmpegThreads, 10), "-i", path}
|
||||||
|
endArgs := []string{"-vn", "-f", "ogg", "-"}
|
||||||
|
ffmpegArgs := append(startArgs, args...)
|
||||||
|
ffmpegArgs = append(ffmpegArgs, endArgs...)
|
||||||
|
cmd := exec.Command("ffmpeg", ffmpegArgs...)
|
||||||
|
cmd.Stdout = w
|
||||||
|
err = cmd.Run()
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type PrepareFileStreamDirectRequest struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
ConfigName string `json:"config_name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PrepareFileStreamDirectResponse struct {
|
||||||
|
Filesize int64 `json:"filesize"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// /prepare_file_stream_direct?id=1&config=ffmpeg_config_name
|
||||||
|
func (api *API) HandlePrepareFileStreamDirect(w http.ResponseWriter, r *http.Request) {
|
||||||
|
prepareFileStreamDirectRequst := &PrepareFileStreamDirectRequest{
|
||||||
|
ID: -1,
|
||||||
|
}
|
||||||
|
err := json.NewDecoder(r.Body).Decode(prepareFileStreamDirectRequst)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// check empty
|
||||||
|
if prepareFileStreamDirectRequst.ID < 0 {
|
||||||
|
api.HandleErrorString(w, r, `"id" can't be none or negative`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if prepareFileStreamDirectRequst.ConfigName == "" {
|
||||||
|
api.HandleErrorString(w, r, `"config_name" can't be empty`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := api.Db.GetFile(prepareFileStreamDirectRequst.ID)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
srcPath, err := file.Path()
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("[api] Prepare stream direct file", srcPath, prepareFileStreamDirectRequst.ConfigName)
|
||||||
|
ffmpegConfig, ok := api.GetFfmpegConfig(prepareFileStreamDirectRequst.ConfigName)
|
||||||
|
if !ok {
|
||||||
|
api.HandleErrorStringCode(w, r, `ffmpeg config not found`, 404)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
objPath := api.Tmpfs.GetObjFilePath(prepareFileStreamDirectRequst.ID, prepareFileStreamDirectRequst.ConfigName)
|
||||||
|
|
||||||
|
// check obj file exists
|
||||||
|
exists := api.Tmpfs.Exits(objPath)
|
||||||
|
if exists {
|
||||||
|
fileInfo, err := os.Stat(objPath)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
prepareFileStreamDirectResponse := &PrepareFileStreamDirectResponse{
|
||||||
|
Filesize: fileInfo.Size(),
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(prepareFileStreamDirectResponse)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
api.Tmpfs.Record(objPath)
|
||||||
|
args := strings.Split(ffmpegConfig.Args, " ")
|
||||||
|
startArgs := []string{"-threads", strconv.FormatInt(api.APIConfig.FfmpegThreads, 10), "-i", srcPath}
|
||||||
|
endArgs := []string{"-vn", "-y", objPath}
|
||||||
|
ffmpegArgs := append(startArgs, args...)
|
||||||
|
ffmpegArgs = append(ffmpegArgs, endArgs...)
|
||||||
|
cmd := exec.Command("ffmpeg", ffmpegArgs...)
|
||||||
|
err = cmd.Run()
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fileInfo, err := os.Stat(objPath)
|
||||||
|
if err != nil {
|
||||||
|
api.HandleError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
prepareFileStreamDirectResponse := &PrepareFileStreamDirectResponse{
|
||||||
|
Filesize: fileInfo.Size(),
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(prepareFileStreamDirectResponse)
|
||||||
|
}
|
||||||
|
|
||||||
|
// /get_file_stream_direct?id=1&config=ffmpeg_config_name
|
||||||
|
// return converted file with http.ServeFile method
|
||||||
|
func (api *API) HandleGetFileStreamDirect(w http.ResponseWriter, r *http.Request) {
|
||||||
|
err := api.CheckGetFileStream(w, r)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
q := r.URL.Query()
|
||||||
|
ids := q["id"]
|
||||||
|
id, err := strconv.Atoi(ids[0])
|
||||||
|
configs := q["config"]
|
||||||
|
configName := configs[0]
|
||||||
|
|
||||||
|
path := api.Tmpfs.GetObjFilePath(int64(id), configName)
|
||||||
|
if api.Tmpfs.Exits(path) {
|
||||||
|
api.Tmpfs.Record(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("[api] Get direct cached file", path)
|
||||||
|
|
||||||
|
http.ServeFile(w, r, path)
|
||||||
|
}
|
||||||
18
pkg/api/handle_token.go
Normal file
18
pkg/api/handle_token.go
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (api *API) CheckToken(w http.ResponseWriter, r *http.Request, token string) error {
|
||||||
|
if token != api.token {
|
||||||
|
err := errors.New("token not matched")
|
||||||
|
log.Println("[api] [Warning] Token not matched", token)
|
||||||
|
api.HandleErrorCode(w, r, err, 403)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
log.Println("[api] Token passed")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
36
pkg/database/database.go
Normal file
36
pkg/database/database.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
|
||||||
|
_ "github.com/mattn/go-sqlite3"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Database struct {
|
||||||
|
sqlConn *sql.DB
|
||||||
|
stmt *Stmt
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDatabase(dbName string) (*Database, error) {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
// open database
|
||||||
|
sqlConn, err := sql.Open("sqlite3", dbName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepare statement
|
||||||
|
stmt, err := NewPreparedStatement(sqlConn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// new database
|
||||||
|
database := &Database{
|
||||||
|
sqlConn: sqlConn,
|
||||||
|
stmt: stmt,
|
||||||
|
}
|
||||||
|
|
||||||
|
return database, nil
|
||||||
|
}
|
||||||
241
pkg/database/method.go
Normal file
241
pkg/database/method.go
Normal file
@@ -0,0 +1,241 @@
|
|||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (database *Database) InsertFeedback(time int64, feedback string, header string) error {
|
||||||
|
_, err := database.stmt.insertFeedback.Exec(time, feedback, header)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) GetRandomFiles(limit int64) ([]File, error) {
|
||||||
|
rows, err := database.stmt.getRandomFiles.Query(limit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
files := make([]File, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
file := File{
|
||||||
|
Db: database,
|
||||||
|
}
|
||||||
|
err = rows.Scan(&file.ID, &file.Folder_id, &file.Filename, &file.Foldername, &file.Filesize)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
files = append(files, file)
|
||||||
|
}
|
||||||
|
return files, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) GetFilesInFolder(folder_id int64, limit int64, offset int64) ([]File, error) {
|
||||||
|
rows, err := database.stmt.getFilesInFolder.Query(folder_id, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
files := make([]File, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
file := File{
|
||||||
|
Db: database,
|
||||||
|
Folder_id: folder_id,
|
||||||
|
}
|
||||||
|
err = rows.Scan(&file.ID, &file.Filename, &file.Filesize, &file.Foldername)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
files = append(files, file)
|
||||||
|
}
|
||||||
|
return files, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) SearchFolders(foldername string, limit int64, offset int64) ([]Folder, error) {
|
||||||
|
rows, err := database.stmt.searchFolders.Query("%"+foldername+"%", limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("Error searching folders at query " + err.Error())
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
folders := make([]Folder, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
folder := Folder{
|
||||||
|
Db: database,
|
||||||
|
}
|
||||||
|
err = rows.Scan(&folder.ID, &folder.Folder, &folder.Foldername)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("Error scanning SearchFolders" + err.Error())
|
||||||
|
}
|
||||||
|
folders = append(folders, folder)
|
||||||
|
}
|
||||||
|
return folders, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) GetFile(id int64) (*File, error) {
|
||||||
|
file := &File{
|
||||||
|
Db: database,
|
||||||
|
}
|
||||||
|
err := database.stmt.getFile.QueryRow(id).Scan(&file.ID, &file.Folder_id, &file.Filename, &file.Foldername, &file.Filesize)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return file, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) ResetFiles() error {
|
||||||
|
log.Println("[db] Reset files")
|
||||||
|
var err error
|
||||||
|
_, err = database.stmt.dropFiles.Exec()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = database.stmt.initFilesTable.Exec()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) ResetFolder() error {
|
||||||
|
log.Println("[db] Reset folders")
|
||||||
|
var err error
|
||||||
|
_, err = database.stmt.dropFolder.Exec()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = database.stmt.initFoldersTable.Exec()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) Walk(root string, pattern []string) error {
|
||||||
|
patternDict := make(map[string]bool)
|
||||||
|
for _, v := range pattern {
|
||||||
|
patternDict[v] = true
|
||||||
|
}
|
||||||
|
log.Println("[db] Walk", root, patternDict)
|
||||||
|
return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if info.IsDir() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// check pattern
|
||||||
|
ext := filepath.Ext(info.Name())
|
||||||
|
if _, ok := patternDict[ext]; !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// insert file, folder will aut created
|
||||||
|
err = database.Insert(path, info.Size())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) GetFolder(folderId int64) (*Folder, error) {
|
||||||
|
folder := &Folder{
|
||||||
|
Db: database,
|
||||||
|
}
|
||||||
|
err := database.stmt.getFolder.QueryRow(folderId).Scan(&folder.Folder)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return folder, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) SearchFiles(filename string, limit int64, offset int64) ([]File, error) {
|
||||||
|
rows, err := database.stmt.searchFiles.Query("%"+filename+"%", limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("Error searching files at query " + err.Error())
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
files := make([]File, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var file File = File{
|
||||||
|
Db: database,
|
||||||
|
}
|
||||||
|
err = rows.Scan(&file.ID, &file.Folder_id, &file.Filename, &file.Foldername, &file.Filesize)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("Error scanning SearchFiles " + err.Error())
|
||||||
|
}
|
||||||
|
files = append(files, file)
|
||||||
|
}
|
||||||
|
if err = rows.Err(); err != nil {
|
||||||
|
return nil, errors.New("Error scanning SearchFiles exit without full result" + err.Error())
|
||||||
|
}
|
||||||
|
return files, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) FindFolder(folder string) (int64, error) {
|
||||||
|
var id int64
|
||||||
|
err := database.stmt.findFolder.QueryRow(folder).Scan(&id)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) FindFile(folderId int64, filename string) (int64, error) {
|
||||||
|
var id int64
|
||||||
|
err := database.stmt.findFile.QueryRow(folderId, filename).Scan(&id)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) InsertFolder(folder string) (int64, error) {
|
||||||
|
result, err := database.stmt.insertFolder.Exec(folder, filepath.Base(folder))
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
lastInsertId, err := result.LastInsertId()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return lastInsertId, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) InsertFile(folderId int64, filename string, filesize int64) error {
|
||||||
|
_, err := database.stmt.insertFile.Exec(folderId, filename, filesize)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (database *Database) Insert(path string, filesize int64) error {
|
||||||
|
folder, filename := filepath.Split(path)
|
||||||
|
folderId, err := database.FindFolder(folder)
|
||||||
|
if err != nil {
|
||||||
|
folderId, err = database.InsertFolder(folder)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// if file exists, skip it
|
||||||
|
_, err = database.FindFile(folderId, filename)
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err = database.InsertFile(folderId, filename, filesize)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
215
pkg/database/sql_stmt.go
Normal file
215
pkg/database/sql_stmt.go
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
)
|
||||||
|
|
||||||
|
var initFilesTableQuery = `CREATE TABLE IF NOT EXISTS files (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
folder_id INTEGER NOT NULL,
|
||||||
|
filename TEXT NOT NULL,
|
||||||
|
filesize INTEGER NOT NULL
|
||||||
|
);`
|
||||||
|
|
||||||
|
var initFoldersTableQuery = `CREATE TABLE IF NOT EXISTS folders (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
folder TEXT NOT NULL,
|
||||||
|
foldername TEXT NOT NULL
|
||||||
|
);`
|
||||||
|
|
||||||
|
var initFeedbacksTableQuery = `CREATE TABLE IF NOT EXISTS feedbacks (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
time INTEGER NOT NULL,
|
||||||
|
feedback TEXT NOT NULL,
|
||||||
|
header TEXT NOT NULL
|
||||||
|
);`
|
||||||
|
|
||||||
|
var insertFolderQuery = `INSERT INTO folders (folder, foldername)
|
||||||
|
VALUES (?, ?);`
|
||||||
|
|
||||||
|
var findFolderQuery = `SELECT id FROM folders WHERE folder = ? LIMIT 1;`
|
||||||
|
|
||||||
|
var findFileQuery = `SELECT id FROM files WHERE folder_id = ? AND filename = ? LIMIT 1;`
|
||||||
|
|
||||||
|
var insertFileQuery = `INSERT INTO files (folder_id, filename, filesize)
|
||||||
|
VALUES (?, ?, ?);`
|
||||||
|
|
||||||
|
var searchFilesQuery = `SELECT
|
||||||
|
files.id, files.folder_id, files.filename, folders.foldername, files.filesize
|
||||||
|
FROM files
|
||||||
|
JOIN folders ON files.folder_id = folders.id
|
||||||
|
WHERE filename LIKE ?
|
||||||
|
LIMIT ? OFFSET ?;`
|
||||||
|
|
||||||
|
var getFolderQuery = `SELECT folder FROM folders WHERE id = ? LIMIT 1;`
|
||||||
|
|
||||||
|
var dropFilesQuery = `DROP TABLE files;`
|
||||||
|
|
||||||
|
var dropFolderQuery = `DROP TABLE folders;`
|
||||||
|
|
||||||
|
var getFileQuery = `SELECT
|
||||||
|
files.id, files.folder_id, files.filename, folders.foldername, files.filesize
|
||||||
|
FROM files
|
||||||
|
JOIN folders ON files.folder_id = folders.id
|
||||||
|
WHERE files.id = ?
|
||||||
|
LIMIT 1;`
|
||||||
|
|
||||||
|
var searchFoldersQuery = `SELECT
|
||||||
|
id, folder, foldername
|
||||||
|
FROM folders
|
||||||
|
WHERE foldername LIKE ?
|
||||||
|
LIMIT ? OFFSET ?;`
|
||||||
|
|
||||||
|
var getFilesInFolderQuery = `SELECT
|
||||||
|
files.id, files.filename, files.filesize, folders.foldername
|
||||||
|
FROM files
|
||||||
|
JOIN folders ON files.folder_id = folders.id
|
||||||
|
WHERE folder_id = ?
|
||||||
|
LIMIT ? OFFSET ?;`
|
||||||
|
|
||||||
|
var getRandomFilesQuery = `SELECT
|
||||||
|
files.id, files.folder_id, files.filename, folders.foldername, files.filesize
|
||||||
|
FROM files
|
||||||
|
JOIN folders ON files.folder_id = folders.id
|
||||||
|
ORDER BY RANDOM()
|
||||||
|
LIMIT ?;`
|
||||||
|
|
||||||
|
var insertFeedbackQuery = `INSERT INTO feedbacks (time, feedback, header)
|
||||||
|
VALUES (?, ?, ?);`
|
||||||
|
|
||||||
|
type Stmt struct {
|
||||||
|
initFilesTable *sql.Stmt
|
||||||
|
initFoldersTable *sql.Stmt
|
||||||
|
initFeedbacksTable *sql.Stmt
|
||||||
|
insertFolder *sql.Stmt
|
||||||
|
insertFile *sql.Stmt
|
||||||
|
findFolder *sql.Stmt
|
||||||
|
findFile *sql.Stmt
|
||||||
|
searchFiles *sql.Stmt
|
||||||
|
getFolder *sql.Stmt
|
||||||
|
dropFiles *sql.Stmt
|
||||||
|
dropFolder *sql.Stmt
|
||||||
|
getFile *sql.Stmt
|
||||||
|
searchFolders *sql.Stmt
|
||||||
|
getFilesInFolder *sql.Stmt
|
||||||
|
getRandomFiles *sql.Stmt
|
||||||
|
insertFeedback *sql.Stmt
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPreparedStatement(sqlConn *sql.DB) (*Stmt, error) {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
stmt := &Stmt{}
|
||||||
|
|
||||||
|
// init files table
|
||||||
|
stmt.initFilesTable, err = sqlConn.Prepare(initFilesTableQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init folders table
|
||||||
|
stmt.initFoldersTable, err = sqlConn.Prepare(initFoldersTableQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init feedbacks tables
|
||||||
|
stmt.initFeedbacksTable, err = sqlConn.Prepare(initFeedbacksTableQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// run init statement
|
||||||
|
_, err = stmt.initFilesTable.Exec()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
_, err = stmt.initFoldersTable.Exec()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
_, err = stmt.initFeedbacksTable.Exec()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init insert folder statement
|
||||||
|
stmt.insertFolder, err = sqlConn.Prepare(insertFolderQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init findFolder statement
|
||||||
|
stmt.findFolder, err = sqlConn.Prepare(findFolderQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init findFile statement
|
||||||
|
stmt.findFile, err = sqlConn.Prepare(findFileQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init insertFile stmt
|
||||||
|
stmt.insertFile, err = sqlConn.Prepare(insertFileQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init searchFile stmt
|
||||||
|
stmt.searchFiles, err = sqlConn.Prepare(searchFilesQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init getFolder stmt
|
||||||
|
stmt.getFolder, err = sqlConn.Prepare(getFolderQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init dropFolder stmt
|
||||||
|
stmt.dropFolder, err = sqlConn.Prepare(dropFolderQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init dropFiles stmt
|
||||||
|
stmt.dropFiles, err = sqlConn.Prepare(dropFilesQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init getFile stmt
|
||||||
|
stmt.getFile, err = sqlConn.Prepare(getFileQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init searchFolder stmt
|
||||||
|
stmt.searchFolders, err = sqlConn.Prepare(searchFoldersQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init getFilesInFolder stmt
|
||||||
|
stmt.getFilesInFolder, err = sqlConn.Prepare(getFilesInFolderQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init getRandomFiles
|
||||||
|
stmt.getRandomFiles, err = sqlConn.Prepare(getRandomFilesQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// init insertFeedback
|
||||||
|
stmt.insertFeedback, err = sqlConn.Prepare(insertFeedbackQuery)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return stmt, err
|
||||||
|
}
|
||||||
30
pkg/database/struct.go
Normal file
30
pkg/database/struct.go
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
type File struct {
|
||||||
|
Db *Database `json:"-"`
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Folder_id int64 `json:"folder_id"`
|
||||||
|
Foldername string `json:"foldername"`
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
Filesize int64 `json:"filesize"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Folder struct {
|
||||||
|
Db *Database `json:"-"`
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Folder string `json:"-"`
|
||||||
|
Foldername string `json:"foldername"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *File) Path() (string, error) {
|
||||||
|
folder, err := f.Db.GetFolder(f.Folder_id)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(folder.Folder, f.Filename), nil
|
||||||
|
}
|
||||||
|
|
||||||
23
web/.gitignore
vendored
Normal file
23
web/.gitignore
vendored
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||||
|
|
||||||
|
# dependencies
|
||||||
|
/node_modules
|
||||||
|
/.pnp
|
||||||
|
.pnp.js
|
||||||
|
|
||||||
|
# testing
|
||||||
|
/coverage
|
||||||
|
|
||||||
|
# production
|
||||||
|
/build
|
||||||
|
|
||||||
|
# misc
|
||||||
|
.DS_Store
|
||||||
|
.env.local
|
||||||
|
.env.development.local
|
||||||
|
.env.test.local
|
||||||
|
.env.production.local
|
||||||
|
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
4
web/Caddyfile
Normal file
4
web/Caddyfile
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
:8081 {
|
||||||
|
reverse_proxy /api/* localhost:8080
|
||||||
|
reverse_proxy * localhost:3000
|
||||||
|
}
|
||||||
70
web/README.md
Normal file
70
web/README.md
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
# Getting Started with Create React App
|
||||||
|
|
||||||
|
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||||
|
|
||||||
|
## Available Scripts
|
||||||
|
|
||||||
|
In the project directory, you can run:
|
||||||
|
|
||||||
|
### `npm start`
|
||||||
|
|
||||||
|
Runs the app in the development mode.\
|
||||||
|
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||||
|
|
||||||
|
The page will reload if you make edits.\
|
||||||
|
You will also see any lint errors in the console.
|
||||||
|
|
||||||
|
### `npm test`
|
||||||
|
|
||||||
|
Launches the test runner in the interactive watch mode.\
|
||||||
|
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||||
|
|
||||||
|
### `npm run build`
|
||||||
|
|
||||||
|
Builds the app for production to the `build` folder.\
|
||||||
|
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||||
|
|
||||||
|
The build is minified and the filenames include the hashes.\
|
||||||
|
Your app is ready to be deployed!
|
||||||
|
|
||||||
|
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||||
|
|
||||||
|
### `npm run eject`
|
||||||
|
|
||||||
|
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||||
|
|
||||||
|
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||||
|
|
||||||
|
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||||
|
|
||||||
|
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||||
|
|
||||||
|
## Learn More
|
||||||
|
|
||||||
|
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||||
|
|
||||||
|
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||||
|
|
||||||
|
### Code Splitting
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
|
||||||
|
|
||||||
|
### Analyzing the Bundle Size
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
|
||||||
|
|
||||||
|
### Making a Progressive Web App
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
|
||||||
|
|
||||||
|
### Advanced Configuration
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
|
||||||
|
|
||||||
|
### Deployment
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
|
||||||
|
|
||||||
|
### `npm run build` fails to minify
|
||||||
|
|
||||||
|
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
|
||||||
3
web/axios.min.js
vendored
3
web/axios.min.js
vendored
File diff suppressed because one or more lines are too long
@@ -1,41 +0,0 @@
|
|||||||
<html>
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<title>MSW Open Music Project</title>
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />
|
|
||||||
<link rel="stylesheet" href="water.css" />
|
|
||||||
<link rel="stylesheet" href="style.css" />
|
|
||||||
<!-- Add to homescreen for Chrome on Android -->
|
|
||||||
<meta name="mobile-web-app-capable" content="yes" />
|
|
||||||
<link rel="icon" href="favicon.png" />
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
<div id="app" class="base">
|
|
||||||
<header class="header">
|
|
||||||
<h3 class="title">
|
|
||||||
<img class="logo" src="favicon.png" />
|
|
||||||
<span class="title-text">MSW Open Music Project</span>
|
|
||||||
</h3>
|
|
||||||
<nav class="nav">
|
|
||||||
<router-link class="nav-link" to="/">I'm Feeling Lucky</router-link>
|
|
||||||
<router-link class="nav-link" to="/search_files">Files</router-link>
|
|
||||||
<router-link class="nav-link" to="/search_folders">Folders</router-link>
|
|
||||||
<router-link class="nav-link" to="/manage">Manage</router-link>
|
|
||||||
</nav>
|
|
||||||
</header>
|
|
||||||
<main>
|
|
||||||
<router-view :token="token" @set_token="set_token" @play_audio="play_audio"></router-view>
|
|
||||||
</main>
|
|
||||||
<footer>
|
|
||||||
<component-audio-player :token="token" @stop="stop" @play_audio="play_audio" :file=playing_audio_file></component-audio-player>
|
|
||||||
</footer>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
<script src="vue.js"></script>
|
|
||||||
<script src="vue-router.js"></script>
|
|
||||||
<script src="axios.min.js"></script>
|
|
||||||
<script src="index.js"></script>
|
|
||||||
|
|
||||||
</html>
|
|
||||||
942
web/index.js
942
web/index.js
@@ -1,942 +0,0 @@
|
|||||||
const component_share = {
|
|
||||||
emits: ['play_audio', 'set_token'],
|
|
||||||
props: ['token'],
|
|
||||||
template: `
|
|
||||||
<div class="page">
|
|
||||||
<h3>Share with others!</h3>
|
|
||||||
<p v-if="error_status">{{ error_status }}</p>
|
|
||||||
<p>Share link: <a :href="computed_share_link">{{ computed_share_link }}</a> , or share this page directly.</p>
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Filename</th>
|
|
||||||
<th>Folder Name</th>
|
|
||||||
<th>Size</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<tr>
|
|
||||||
<component-file :file=file @play_audio="$emit('play_audio', $event)"></component-file>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
computed: {
|
|
||||||
computed_share_link() {
|
|
||||||
return window.location.href
|
|
||||||
},
|
|
||||||
},
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
file: {},
|
|
||||||
error_status: "",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
mounted() {
|
|
||||||
if (this.$route.query.id) {
|
|
||||||
this.get_file_info()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
get_file_info() {
|
|
||||||
axios.post('/api/v1/get_file_info', {
|
|
||||||
id: parseInt(this.$route.query.id),
|
|
||||||
}).then((response) => {
|
|
||||||
this.file = response.data
|
|
||||||
}).catch((error) => {
|
|
||||||
if (error.response) {
|
|
||||||
this.error_status = error.response.data.status
|
|
||||||
} else {
|
|
||||||
this.error_status = 'Network error'
|
|
||||||
}
|
|
||||||
})
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const component_search_folders = {
|
|
||||||
emits: ['play_audio', 'set_token'],
|
|
||||||
props: ['token'],
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
search_foldernames: "",
|
|
||||||
folders: [],
|
|
||||||
folder: {},
|
|
||||||
offset: 0,
|
|
||||||
limit: 10,
|
|
||||||
folder_offset: 0,
|
|
||||||
folder_limit: 10,
|
|
||||||
files_in_folder: [],
|
|
||||||
playing_audio_file: {},
|
|
||||||
is_loading: false,
|
|
||||||
error_status: "",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
computed_folders_page() {
|
|
||||||
if (this.is_loading) {
|
|
||||||
return 'Loading...'
|
|
||||||
}
|
|
||||||
if (this.error_status) {
|
|
||||||
return this.error_status
|
|
||||||
}
|
|
||||||
return this.offset + ' ~ ' + (this.offset + this.folders.length)
|
|
||||||
},
|
|
||||||
computed_files_page() {
|
|
||||||
if (this.is_loading) {
|
|
||||||
return 'Loading...'
|
|
||||||
}
|
|
||||||
if (this.error_status) {
|
|
||||||
return this.error_status
|
|
||||||
}
|
|
||||||
return this.folder_offset + ' ~ ' + (this.folder_offset + this.files_in_folder.length)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
template: `
|
|
||||||
<div class="page">
|
|
||||||
<h3>Search Folders</h3>
|
|
||||||
<div class="search_toolbar">
|
|
||||||
<input type="text" @keyup.enter="first_search_folders" v-model="search_foldernames" placeholder="Enter folder name" />
|
|
||||||
<button @click="first_search_folders">Search Folders</Button>
|
|
||||||
<button @click="last_page">Last Page</button>
|
|
||||||
<button disabled>{{ computed_folders_page }}</button>
|
|
||||||
<button @click="next_page">Next Page</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<table v-if="folders.length">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Folder Name</th>
|
|
||||||
<th>Action</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<tr v-for="folder in folders">
|
|
||||||
<td class="clickable" @click="view_folder(folder)">{{ folder.foldername }}</td>
|
|
||||||
<td><button @click="view_folder(folder)">View</button></td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<h3>Files in folder</h3>
|
|
||||||
<div class="search_toolbar">
|
|
||||||
<button @click="folder_last_page">Last Page</button>
|
|
||||||
<button disabled>{{ computed_files_page }}</button>
|
|
||||||
<button @click="folder_next_page">Next Page</button>
|
|
||||||
</div>
|
|
||||||
<table v-if="files_in_folder.length">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Filename</th>
|
|
||||||
<th>Folder Name</th>
|
|
||||||
<th>Size</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<tr v-for="file in files_in_folder">
|
|
||||||
<component-file :file=file @play_audio="$emit('play_audio', $event)"></component-file>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
mounted() {
|
|
||||||
if (this.$route.query.folder_id) {
|
|
||||||
this.folder.id = parseInt(this.$route.query.folder_id)
|
|
||||||
this.get_files_in_folder()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
folder_last_page() {
|
|
||||||
this.folder_offset = this.folder_offset - this.folder_limit
|
|
||||||
if (this.folder_offset < 0) {
|
|
||||||
this.folder_offset = 0
|
|
||||||
return
|
|
||||||
}
|
|
||||||
this.get_files_in_folder()
|
|
||||||
},
|
|
||||||
folder_next_page() {
|
|
||||||
this.folder_offset = this.folder_offset + this.folder_limit
|
|
||||||
this.get_files_in_folder()
|
|
||||||
},
|
|
||||||
view_folder(folder) {
|
|
||||||
this.folder = folder
|
|
||||||
this.get_files_in_folder()
|
|
||||||
},
|
|
||||||
get_files_in_folder() {
|
|
||||||
this.is_loading = true
|
|
||||||
axios.post('/api/v1/get_files_in_folder', {
|
|
||||||
folder_id: this.folder.id,
|
|
||||||
limit: this.folder_limit,
|
|
||||||
offset: this.folder_offset,
|
|
||||||
}).then((response) => {
|
|
||||||
this.error_status = ""
|
|
||||||
this.files_in_folder = response.data.files
|
|
||||||
}).catch((error) => {
|
|
||||||
if (error.response) {
|
|
||||||
this.error_status = error.response.data.status
|
|
||||||
} else {
|
|
||||||
this.error_status = 'Network error'
|
|
||||||
}
|
|
||||||
}).finally(() => {
|
|
||||||
this.is_loading = false
|
|
||||||
})
|
|
||||||
},
|
|
||||||
last_page() {
|
|
||||||
this.offset = this.offset - this.limit
|
|
||||||
if (this.offset < 0) {
|
|
||||||
this.offset = 0
|
|
||||||
return
|
|
||||||
}
|
|
||||||
this.search_folders()
|
|
||||||
},
|
|
||||||
next_page() {
|
|
||||||
this.offset = this.offset + this.limit
|
|
||||||
this.search_folders()
|
|
||||||
},
|
|
||||||
first_search_folders() {
|
|
||||||
this.offset = 0
|
|
||||||
this.search_folders()
|
|
||||||
},
|
|
||||||
search_folders() {
|
|
||||||
this.is_loading = true
|
|
||||||
axios.post('/api/v1/search_folders', {
|
|
||||||
foldername: this.search_foldernames,
|
|
||||||
limit: this.limit,
|
|
||||||
offset: this.offset,
|
|
||||||
}).then((response) => {
|
|
||||||
this.error_status = ""
|
|
||||||
this.folders = response.data.folders
|
|
||||||
}).catch((error) => {
|
|
||||||
if (error.response) {
|
|
||||||
this.error_status = error.response.data.status
|
|
||||||
} else {
|
|
||||||
this.error_status = 'Network error'
|
|
||||||
}
|
|
||||||
}).finally(() => {
|
|
||||||
this.is_loading = false
|
|
||||||
})
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const component_token = {
|
|
||||||
progs: ['token'],
|
|
||||||
emits: ['set_token'],
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
token_tmp: "",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
template: `
|
|
||||||
<table><tbody><tr>
|
|
||||||
<td>Token</td>
|
|
||||||
<td><input type="text" v-model="token_tmp" @change="emit_set_token" placeholder="token" /></td>
|
|
||||||
</tr></tbody></table>
|
|
||||||
`,
|
|
||||||
methods: {
|
|
||||||
emit_set_token() {
|
|
||||||
this.$emit('set_token', this.token_tmp)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const component_manage= {
|
|
||||||
props: ['token'],
|
|
||||||
emits: ['set_token'],
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
feedback: "",
|
|
||||||
feedback_status: "Submit",
|
|
||||||
feedback_placeholder: "feedback...",
|
|
||||||
submit_disabled: false,
|
|
||||||
is_err: false,
|
|
||||||
err_msg: "",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
template: `
|
|
||||||
<div class="page">
|
|
||||||
<div class="description">
|
|
||||||
<h4>关于本站</h4>
|
|
||||||
<p>一只随处可见的 葱厨&车万人 想听 TA 屯在硬盘里的音乐。</p>
|
|
||||||
<p>一点点说明:下方播放器的 Raw 模式即不转码直接播放源文件,支持断点续传;Prepare 模式:勾选后播放的文件将提前在服务器端转码,然后以支持断点续传的方式提供,如果你的网络不稳定,经常播放到一半就中断,可以尝试勾选 Prepare。</p>
|
|
||||||
<p>站内音乐来自公开网络,仅供个人使用,如有侵权或建议请提交反馈</p>
|
|
||||||
<div class="feedback">
|
|
||||||
<input type="text" v-model="feedback" :disabled="submit_disabled" :placeholder="feedback_placeholder"/>
|
|
||||||
<button @click="submit_feedback" :disabled="submit_disabled">{{ feedback_status }}</button>
|
|
||||||
<label v-if="is_err">{{ err_msg }}</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<component-token :token="token" @set_token="$emit('set_token', $event)"></component-token>
|
|
||||||
<component-manage-database :token="token"></component-manage-database>
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
methods: {
|
|
||||||
submit_feedback() {
|
|
||||||
axios.post('/api/v1/feedback', {
|
|
||||||
feedback: this.feedback,
|
|
||||||
}).then((response) => {
|
|
||||||
this.submit_disabled = true
|
|
||||||
this.feedback = ""
|
|
||||||
this.feedback_status = "Success"
|
|
||||||
this.feedback_placeholder = "Thanks for your feedback!"
|
|
||||||
this.is_err = false
|
|
||||||
}).catch((err) => {
|
|
||||||
console.log(err)
|
|
||||||
this.is_err = true
|
|
||||||
this.err_msg = err.response.data.status
|
|
||||||
})
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const component_manage_database = {
|
|
||||||
props: ['token'],
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
root: "",
|
|
||||||
pattern: [".flac", ".mp3"],
|
|
||||||
pattern_tmp: "",
|
|
||||||
s: "",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
template: `
|
|
||||||
<div>
|
|
||||||
<table>
|
|
||||||
<tbody>
|
|
||||||
<tr>
|
|
||||||
<td>Root</td>
|
|
||||||
<td><input type="text" v-model="root" placeholder="/path/to/root" /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><button @click="add_pattern">Add Pattern</button></td>
|
|
||||||
<td><input type="text" v-model="pattern_tmp" placeholder=".wav" /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td colspan="2"><strong>Pattern List</strong></td>
|
|
||||||
</tr>
|
|
||||||
<tr v-for="p in pattern">
|
|
||||||
<td colspan="2">{{ p }}</td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><button @click="update_database">Update</button></td>
|
|
||||||
<td><button @click="reset_database">Reset</button></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td>Status</td>
|
|
||||||
<td>{{ s }}</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
methods: {
|
|
||||||
add_pattern() {
|
|
||||||
this.pattern.push(this.pattern_tmp)
|
|
||||||
this.pattern_tmp = ""
|
|
||||||
},
|
|
||||||
reset_database() {
|
|
||||||
axios.post('/api/v1/reset', {
|
|
||||||
token: this.token,
|
|
||||||
}).then((response) => {
|
|
||||||
this.s = response.data.status
|
|
||||||
}).catch((err) => {
|
|
||||||
this.s = err.response.data.status
|
|
||||||
})
|
|
||||||
},
|
|
||||||
update_database() {
|
|
||||||
this.s = "Updating..."
|
|
||||||
axios.post('/api/v1/walk', {
|
|
||||||
token: this.token,
|
|
||||||
root: this.root,
|
|
||||||
pattern: this.pattern,
|
|
||||||
}).then((response) => {
|
|
||||||
this.s = response.data.status
|
|
||||||
}).catch((err) => {
|
|
||||||
this.s = err.response.data.status
|
|
||||||
})
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const component_file_dialog = {
|
|
||||||
props: ['file', 'show_dialog'],
|
|
||||||
emits: ['play_audio', 'close_dialog'],
|
|
||||||
template: `
|
|
||||||
<dialog open v-if="show_dialog">
|
|
||||||
<p>{{ file.filename }}</p>
|
|
||||||
<p>
|
|
||||||
Download 使用 Axios 异步下载<br />
|
|
||||||
Play 调用网页播放器播放<br />
|
|
||||||
</p>
|
|
||||||
<button @click="download_file(file)" :disabled="disabled">{{ computed_download_status }}</button>
|
|
||||||
<button @click="emit_play_audio">Play</button>
|
|
||||||
<button @click="share">Share</button>
|
|
||||||
<button @click="emit_close_dialog">Close</button>
|
|
||||||
</dialog>
|
|
||||||
`,
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
download_loaded: 0,
|
|
||||||
disabled: false,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
share() {
|
|
||||||
this.$router.push({
|
|
||||||
path: '/share',
|
|
||||||
query: {
|
|
||||||
id: this.file.id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
this.emit_close_dialog()
|
|
||||||
},
|
|
||||||
emit_close_dialog() {
|
|
||||||
this.$emit('close_dialog')
|
|
||||||
},
|
|
||||||
emit_play_audio() {
|
|
||||||
console.log("pressed button")
|
|
||||||
this.$emit("play_audio", this.file)
|
|
||||||
this.emit_close_dialog()
|
|
||||||
},
|
|
||||||
download_file(file) {
|
|
||||||
this.disabled = true
|
|
||||||
axios({
|
|
||||||
url: '/api/v1/get_file',
|
|
||||||
method: 'POST',
|
|
||||||
responseType: 'blob', // important
|
|
||||||
data: {
|
|
||||||
id: file.id,
|
|
||||||
},
|
|
||||||
onDownloadProgress: ProgressEvent => {
|
|
||||||
this.download_loaded = ProgressEvent.loaded
|
|
||||||
}
|
|
||||||
}).then((response) => {
|
|
||||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
|
||||||
const link = document.createElement('a');
|
|
||||||
link.href = url;
|
|
||||||
link.setAttribute('download', file.filename);
|
|
||||||
document.body.appendChild(link);
|
|
||||||
link.click();
|
|
||||||
this.download_loaded = 0
|
|
||||||
this.disabled = false
|
|
||||||
this.emit_close_dialog()
|
|
||||||
})
|
|
||||||
},
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
computed_download_status() {
|
|
||||||
if (this.download_loaded === 0) {
|
|
||||||
return 'Download'
|
|
||||||
} else {
|
|
||||||
return Math.round(this.download_loaded / this.file.filesize * 100) + '%'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const component_file = {
|
|
||||||
props: ['file'],
|
|
||||||
emits: ['play_audio'],
|
|
||||||
template: `
|
|
||||||
<td class="clickable" @click="click_filename">{{ file.filename }}</td>
|
|
||||||
<td class="clickable" @click="show_folder">{{ file.foldername }}</td>
|
|
||||||
<td>{{ computed_readable_size }}
|
|
||||||
<component-file-dialog
|
|
||||||
@close_dialog="close_dialog"
|
|
||||||
@play_audio="$emit('play_audio', $event)"
|
|
||||||
:show_dialog="show_dialog"
|
|
||||||
:file="file"
|
|
||||||
></component-file-dialog>
|
|
||||||
</td>
|
|
||||||
`,
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
download_loaded: 0,
|
|
||||||
disabled: false,
|
|
||||||
show_dialog: false,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
click_filename() {
|
|
||||||
if (this.show_dialog) {
|
|
||||||
this.file.play_back_type = 'stream'
|
|
||||||
this.$emit('play_audio', this.file)
|
|
||||||
this.show_dialog = false
|
|
||||||
} else {
|
|
||||||
this.show_dialog = true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
show_folder() {
|
|
||||||
this.$router.push({
|
|
||||||
path: '/search_folders',
|
|
||||||
query: {
|
|
||||||
folder_id: this.file.folder_id,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
},
|
|
||||||
close_dialog() {
|
|
||||||
this.show_dialog = false
|
|
||||||
},
|
|
||||||
dialog() {
|
|
||||||
this.show_dialog = this.show_dialog ? false : true
|
|
||||||
},
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
computed_readable_size() {
|
|
||||||
let filesize = this.file.filesize
|
|
||||||
if (filesize < 1024) {
|
|
||||||
return filesize
|
|
||||||
}
|
|
||||||
if (filesize < 1024 * 1024) {
|
|
||||||
return Math.round(filesize / 1024) + 'K'
|
|
||||||
}
|
|
||||||
if (filesize < 1024 * 1024 * 1024) {
|
|
||||||
return Math.round(filesize / 1024 / 1024) + 'M'
|
|
||||||
}
|
|
||||||
if (filesize < 1024 * 1024 * 1024 * 1024) {
|
|
||||||
return Math.round(filesize / 1024 / 1024 / 1024) + 'G'
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const component_audio_player = {
|
|
||||||
emits: ['stop', 'play_audio'],
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
loop: true,
|
|
||||||
ffmpeg_config: {},
|
|
||||||
show_dialog: false,
|
|
||||||
is_preparing: false,
|
|
||||||
prepare: false,
|
|
||||||
raw: false,
|
|
||||||
playing_url: "",
|
|
||||||
prepared_filesize: 0,
|
|
||||||
playing_file: {},
|
|
||||||
error_status: "",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
props: ['file', 'token'],
|
|
||||||
template: `
|
|
||||||
<div>
|
|
||||||
<h5>Player Status</h5>
|
|
||||||
<component-file-dialog
|
|
||||||
@close_dialog="close_dialog"
|
|
||||||
@play_audio="$emit('play_audio', $event)"
|
|
||||||
:show_dialog="show_dialog"
|
|
||||||
:file="file"
|
|
||||||
></component-file-dialog>
|
|
||||||
<span v-if="computed_show">
|
|
||||||
<button @click="dialog">{{ file.filename }}</button>
|
|
||||||
<button @click="show_folder">{{ file.foldername }}</button>
|
|
||||||
<button disabled>{{ computed_readable_size }}</button>
|
|
||||||
<button v-if="error_status" @click="retry">Retry</button>
|
|
||||||
<button @click="emit_stop">Stop</button>
|
|
||||||
</span>
|
|
||||||
<br />
|
|
||||||
<input type="checkbox" v-model="loop" />
|
|
||||||
<label>Loop</label>
|
|
||||||
<input type="checkbox" v-model="raw" />
|
|
||||||
<label>Raw</label>
|
|
||||||
<input v-show="!raw" type="checkbox" v-model="prepare" />
|
|
||||||
<label v-show="!raw">Prepare</label><br />
|
|
||||||
<video v-if="computed_video_show" class="audio-player" :src="playing_url" controls autoplay :loop="loop">
|
|
||||||
</video>
|
|
||||||
<component-stream-config @set_ffmpeg_config="set_ffmpeg_config"></component-stream-config>
|
|
||||||
<p>{{ token }}</p>
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
methods: {
|
|
||||||
emit_stop() {
|
|
||||||
this.$emit('stop')
|
|
||||||
},
|
|
||||||
dialog() {
|
|
||||||
this.show_dialog = this.show_dialog ? false : true
|
|
||||||
},
|
|
||||||
close_dialog() {
|
|
||||||
this.show_dialog = false
|
|
||||||
},
|
|
||||||
show_folder() {
|
|
||||||
this.$router.push({
|
|
||||||
path: '/search_folders',
|
|
||||||
query: {
|
|
||||||
folder_id: this.file.folder_id,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
},
|
|
||||||
set_ffmpeg_config(ffmpeg_config) {
|
|
||||||
this.ffmpeg_config = ffmpeg_config
|
|
||||||
},
|
|
||||||
prepare_func() {
|
|
||||||
if (!this.file.id) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
this.playing_file = {}
|
|
||||||
this.is_preparing = true
|
|
||||||
axios.post('/api/v1/prepare_file_stream_direct', {
|
|
||||||
id: this.file.id,
|
|
||||||
config_name: this.ffmpeg_config.name,
|
|
||||||
}).then(response => {
|
|
||||||
console.log(response.data)
|
|
||||||
this.error_status = ''
|
|
||||||
this.prepared_filesize = response.data.filesize
|
|
||||||
var file = this.file
|
|
||||||
this.playing_file = file
|
|
||||||
this.set_playing_url()
|
|
||||||
console.log('axios done', this.playing_file)
|
|
||||||
}).catch((err) => {
|
|
||||||
if (err.response) {
|
|
||||||
this.error_status = err.response.data.status
|
|
||||||
} else {
|
|
||||||
this.error_status = "Network error"
|
|
||||||
}
|
|
||||||
}).finally(() => {
|
|
||||||
this.is_preparing = false
|
|
||||||
})
|
|
||||||
},
|
|
||||||
set_playing_url() {
|
|
||||||
if (this.raw) {
|
|
||||||
console.log('computed raw rul')
|
|
||||||
this.playing_url = '/api/v1/get_file_direct?id=' + this.playing_file.id
|
|
||||||
} else {
|
|
||||||
if (this.prepare) {
|
|
||||||
console.log('empty playing_file, start prepare')
|
|
||||||
this.playing_url = '/api/v1/get_file_stream_direct?id=' + this.playing_file.id + '&config=' + this.ffmpeg_config.name
|
|
||||||
} else {
|
|
||||||
console.log('computed stream url')
|
|
||||||
this.playing_url = '/api/v1/get_file_stream?id=' + this.playing_file.id + '&config=' + this.ffmpeg_config.name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
setup_player() {
|
|
||||||
// 如果没有勾选 prepare 则直接播放
|
|
||||||
// 否则进入 prepare 流程
|
|
||||||
this.playing_file = {}
|
|
||||||
if (this.prepare && !this.raw) {
|
|
||||||
this.prepare_func()
|
|
||||||
} else {
|
|
||||||
this.playing_file = this.file
|
|
||||||
this.set_playing_url()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
retry() {
|
|
||||||
this.setup_player()
|
|
||||||
},
|
|
||||||
},
|
|
||||||
watch: {
|
|
||||||
file() {
|
|
||||||
this.setup_player()
|
|
||||||
},
|
|
||||||
raw() {
|
|
||||||
if (this.prepare) {
|
|
||||||
this.prepare_func()
|
|
||||||
} else {
|
|
||||||
this.set_playing_url()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
prepare() {
|
|
||||||
this.playing_file = {}
|
|
||||||
this.prepare_func()
|
|
||||||
},
|
|
||||||
ffmpeg_config() {
|
|
||||||
this.setup_player()
|
|
||||||
},
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
computed_can_retry() {
|
|
||||||
return this.error_status ? true : false
|
|
||||||
},
|
|
||||||
computed_readable_size() {
|
|
||||||
if (this.is_preparing) {
|
|
||||||
return 'Preparing...'
|
|
||||||
}
|
|
||||||
if (this.error_status) {
|
|
||||||
return this.error_status
|
|
||||||
}
|
|
||||||
let filesize = this.playing_file.filesize
|
|
||||||
if (this.prepare) {
|
|
||||||
filesize = this.prepared_filesize
|
|
||||||
}
|
|
||||||
if (this.raw) {
|
|
||||||
filesize = this.playing_file.filesize
|
|
||||||
}
|
|
||||||
if (filesize < 1024 * 1024 * 1024) {
|
|
||||||
filesize = Math.round(filesize / 1024) + 'K'
|
|
||||||
}
|
|
||||||
if (filesize < 1024 * 1024 * 1024 * 1024) {
|
|
||||||
filesize = Math.round(filesize / 1024 / 1024) + 'M'
|
|
||||||
}
|
|
||||||
// add separater to number
|
|
||||||
return filesize.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
|
|
||||||
},
|
|
||||||
computed_video_show() {
|
|
||||||
if (this.playing_file.id && this.playing_url) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
},
|
|
||||||
computed_show() {
|
|
||||||
return this.file.id ? true : false
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const component_search_files = {
|
|
||||||
emits: ['play_audio'],
|
|
||||||
props: ['token'],
|
|
||||||
computed: {
|
|
||||||
computed_files_page() {
|
|
||||||
if (this.is_loading) {
|
|
||||||
return 'Loading...'
|
|
||||||
}
|
|
||||||
if (this.error_status) {
|
|
||||||
return this.error_status
|
|
||||||
}
|
|
||||||
return this.offset + ' ~ ' + (this.offset + this.files.length)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
template: `
|
|
||||||
<div class="page">
|
|
||||||
<h3>Search Files</h3>
|
|
||||||
<div class="search_toolbar">
|
|
||||||
<input type="text" name="filename" @keyup.enter="first_search_files" v-model="search_filenames" placeholder="Enter filename" />
|
|
||||||
<button @click="first_search_files">Search</button>
|
|
||||||
<button @click="last_page">Last Page</button>
|
|
||||||
<button disabled>{{ computed_files_page }}</button>
|
|
||||||
<button @click="next_page">Next Page</button>
|
|
||||||
</div>
|
|
||||||
<table v-if="files.length">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Filename</th>
|
|
||||||
<th>Folder Name</th>
|
|
||||||
<th>Size</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<tr v-for="file in files">
|
|
||||||
<component-file :file=file @play_audio="$emit('play_audio', $event)"></component-file>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
search_filenames: '',
|
|
||||||
files: [],
|
|
||||||
offset: 0,
|
|
||||||
limit: 10,
|
|
||||||
playing_audio_file: {},
|
|
||||||
is_loading: false,
|
|
||||||
error_status: "",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
first_search_files() {
|
|
||||||
this.offset = 0
|
|
||||||
this.search_files()
|
|
||||||
},
|
|
||||||
search_files() {
|
|
||||||
this.is_loading = true
|
|
||||||
axios.post('/api/v1/search_files', {
|
|
||||||
filename: this.search_filenames,
|
|
||||||
limit: this.limit,
|
|
||||||
offset: this.offset,
|
|
||||||
}).then((response) => {
|
|
||||||
this.error_status = ""
|
|
||||||
this.files = response.data.files
|
|
||||||
}).catch((error) => {
|
|
||||||
if (error.response) {
|
|
||||||
this.error_status = error.response.data.status
|
|
||||||
} else {
|
|
||||||
this.error_status = 'Network error'
|
|
||||||
}
|
|
||||||
}).finally(() => {
|
|
||||||
this.is_loading = false
|
|
||||||
})
|
|
||||||
},
|
|
||||||
last_page() {
|
|
||||||
this.offset = this.offset - this.limit
|
|
||||||
if (this.offset < 0) {
|
|
||||||
this.offset = 0
|
|
||||||
return
|
|
||||||
}
|
|
||||||
this.search_files()
|
|
||||||
},
|
|
||||||
next_page() {
|
|
||||||
this.offset = this.offset + this.limit
|
|
||||||
this.search_files()
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const component_get_random_files = {
|
|
||||||
emits: ['play_audio', 'set_token'],
|
|
||||||
props: ['token'],
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
files: [],
|
|
||||||
is_loading: false,
|
|
||||||
error_status: "",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
computed_refresh() {
|
|
||||||
if (this.error_status) {
|
|
||||||
return this.error_status
|
|
||||||
}
|
|
||||||
if (this.is_loading) {
|
|
||||||
return 'Loading...'
|
|
||||||
}
|
|
||||||
return 'Refresh'
|
|
||||||
},
|
|
||||||
},
|
|
||||||
template: `
|
|
||||||
<div class="page">
|
|
||||||
<div class="search_toolbar">
|
|
||||||
<button class="refresh" @click="get_random_files">{{ computed_refresh }}</button>
|
|
||||||
</div>
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Filename</th>
|
|
||||||
<th>Folder Name</th>
|
|
||||||
<th>Size</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<tr v-for="file in files">
|
|
||||||
<component-file :file=file @play_audio="$emit('play_audio', $event)"></component-file>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
mounted() {
|
|
||||||
this.get_random_files()
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
get_random_files() {
|
|
||||||
this.is_loading = true
|
|
||||||
axios.get('/api/v1/get_random_files'
|
|
||||||
).then(response => {
|
|
||||||
this.error_status = ""
|
|
||||||
this.files = response.data.files;
|
|
||||||
}).catch((error) => {
|
|
||||||
if (error.response) {
|
|
||||||
this.error_status = error.response.data.status
|
|
||||||
} else {
|
|
||||||
this.error_status = 'Network error'
|
|
||||||
}
|
|
||||||
}).finally(() => {
|
|
||||||
this.is_loading = false
|
|
||||||
})
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const component_stream_config = {
|
|
||||||
emits: ['set_ffmpeg_config'],
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
ffmpeg_config_list: [],
|
|
||||||
selected_ffmpeg_config: {},
|
|
||||||
}
|
|
||||||
},
|
|
||||||
template: `
|
|
||||||
<div>
|
|
||||||
<table>
|
|
||||||
<tbody>
|
|
||||||
<tr>
|
|
||||||
<td>
|
|
||||||
<select v-model="selected_ffmpeg_config">
|
|
||||||
<option v-for="ffmpeg_config in ffmpeg_config_list" :value="ffmpeg_config">
|
|
||||||
{{ ffmpeg_config.name }}
|
|
||||||
</option>
|
|
||||||
</select>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<span>{{ selected_ffmpeg_config.args }}</span>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
mounted() {
|
|
||||||
axios.get('/api/v1/get_ffmpeg_config_list',
|
|
||||||
).then(response => {
|
|
||||||
// 后端返回数据 ffmpeg_configs 是一个字典,name 作为 key,ffmpeg_config{} 作为 value
|
|
||||||
// 为方便前端,此处将 ffmpeg_configs 转为数组,并添加 name 到每个对象中
|
|
||||||
var ffmpeg_configs = response.data.ffmpeg_configs
|
|
||||||
var tmp_list = []
|
|
||||||
for (var key in ffmpeg_configs) {
|
|
||||||
var ffmpeg_config = ffmpeg_configs[key]
|
|
||||||
ffmpeg_config.name = key
|
|
||||||
tmp_list.push(ffmpeg_config)
|
|
||||||
}
|
|
||||||
tmp_list.sort()
|
|
||||||
this.ffmpeg_config_list = tmp_list
|
|
||||||
this.selected_ffmpeg_config = this.ffmpeg_config_list[0]
|
|
||||||
}).catch(err => {
|
|
||||||
this.ffmpeg_config_list = [{name: 'No avaliable config'}]
|
|
||||||
this.selected_ffmpeg_config = this.ffmpeg_config_list[0]
|
|
||||||
})
|
|
||||||
},
|
|
||||||
watch: {
|
|
||||||
selected_ffmpeg_config(n, o) {
|
|
||||||
this.$emit('set_ffmpeg_config', this.selected_ffmpeg_config)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const routes = [
|
|
||||||
{ path: '/', component: component_get_random_files},
|
|
||||||
{ path: '/search_files', component: component_search_files},
|
|
||||||
{ path: '/search_folders', component: component_search_folders},
|
|
||||||
{ path: '/manage', component: component_manage},
|
|
||||||
{ path: '/share', component: component_share},
|
|
||||||
]
|
|
||||||
const router = VueRouter.createRouter({
|
|
||||||
history: VueRouter.createWebHashHistory(),
|
|
||||||
routes,
|
|
||||||
})
|
|
||||||
|
|
||||||
const app = Vue.createApp({
|
|
||||||
data() {
|
|
||||||
return {
|
|
||||||
playing_audio_file: {},
|
|
||||||
token: "default token",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
stop() {
|
|
||||||
this.playing_audio_file = {}
|
|
||||||
},
|
|
||||||
set_token(token) {
|
|
||||||
this.token = token
|
|
||||||
},
|
|
||||||
play_audio(file) {
|
|
||||||
console.log(file)
|
|
||||||
this.playing_audio_file = file
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
app.component('component-search-folders', component_search_folders)
|
|
||||||
app.component('component-manage', component_manage)
|
|
||||||
app.component('component-file', component_file)
|
|
||||||
app.component('component-audio-player', component_audio_player)
|
|
||||||
app.component('component-search-files', component_search_files)
|
|
||||||
app.component('component-get-random-files', component_get_random_files)
|
|
||||||
app.component('component-file-dialog', component_file_dialog)
|
|
||||||
app.component('component-token', component_token)
|
|
||||||
app.component('component-stream-config', component_stream_config)
|
|
||||||
app.component('component-manage-database', component_manage_database)
|
|
||||||
app.component('component-share', component_share)
|
|
||||||
|
|
||||||
app.use(router)
|
|
||||||
|
|
||||||
app.mount('#app')
|
|
||||||
37510
web/package-lock.json
generated
Normal file
37510
web/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
44
web/package.json
Normal file
44
web/package.json
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"name": "msw-open-music-react",
|
||||||
|
"version": "1.1.0",
|
||||||
|
"private": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@testing-library/jest-dom": "^5.15.0",
|
||||||
|
"@testing-library/react": "^11.2.7",
|
||||||
|
"@testing-library/user-event": "^12.8.3",
|
||||||
|
"react": "^17.0.2",
|
||||||
|
"react-dom": "^17.0.2",
|
||||||
|
"react-router": "^6.0.2",
|
||||||
|
"react-router-dom": "^6.0.2",
|
||||||
|
"react-scripts": "4.0.3",
|
||||||
|
"water.css": "^2.1.1",
|
||||||
|
"web-vitals": "^1.1.2"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"start": "react-scripts start",
|
||||||
|
"build": "react-scripts build",
|
||||||
|
"test": "react-scripts test",
|
||||||
|
"eject": "react-scripts eject"
|
||||||
|
},
|
||||||
|
"eslintConfig": {
|
||||||
|
"extends": [
|
||||||
|
"react-app",
|
||||||
|
"react-app/jest"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"browserslist": {
|
||||||
|
"production": [
|
||||||
|
">0.2%",
|
||||||
|
"not dead",
|
||||||
|
"not op_mini all"
|
||||||
|
],
|
||||||
|
"development": [
|
||||||
|
"last 1 chrome version",
|
||||||
|
"last 1 firefox version",
|
||||||
|
"last 1 safari version"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/react": "^17.0.34"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Before Width: | Height: | Size: 4.6 KiB After Width: | Height: | Size: 4.6 KiB |
41
web/public/index.html
Normal file
41
web/public/index.html
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<link rel="icon" href="%PUBLIC_URL%/favicon.png" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="description" content="Personal music streaming platform" />
|
||||||
|
<link rel="apple-touch-icon" href="%PUBLIC_URL%/favicon.png" />
|
||||||
|
<!--
|
||||||
|
manifest.json provides metadata used when your web app is installed on a
|
||||||
|
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||||
|
-->
|
||||||
|
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||||
|
<!--
|
||||||
|
Notice the use of %PUBLIC_URL% in the tags above.
|
||||||
|
It will be replaced with the URL of the `public` folder during the build.
|
||||||
|
Only files inside the `public` folder can be referenced from the HTML.
|
||||||
|
|
||||||
|
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||||
|
work correctly both with client-side routing and a non-root public URL.
|
||||||
|
Learn how to configure a non-root public URL by running `npm run build`.
|
||||||
|
-->
|
||||||
|
<!-- Add to homescreen for Chrome on Android -->
|
||||||
|
<meta name="mobile-web-app-capable" content="yes" />
|
||||||
|
<title>MSW Open Music</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||||
|
<div id="root"></div>
|
||||||
|
<!--
|
||||||
|
This HTML file is a template.
|
||||||
|
If you open it directly in the browser, you will see an empty page.
|
||||||
|
|
||||||
|
You can add webfonts, meta tags, or analytics to this file.
|
||||||
|
The build step will place the bundled scripts into the <body> tag.
|
||||||
|
|
||||||
|
To begin the development, run `npm start` or `yarn start`.
|
||||||
|
To create a production bundle, use `npm run build` or `yarn build`.
|
||||||
|
-->
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
14
web/public/manifest.json
Normal file
14
web/public/manifest.json
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"short_name": "React App",
|
||||||
|
"name": "Create React App Sample",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"src": "favicon.png",
|
||||||
|
"type": "image/x-icon"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"start_url": ".",
|
||||||
|
"display": "standalone",
|
||||||
|
"theme_color": "#000000",
|
||||||
|
"background_color": "#ffffff"
|
||||||
|
}
|
||||||
3
web/public/robots.txt
Normal file
3
web/public/robots.txt
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# https://www.robotstxt.org/robotstxt.html
|
||||||
|
User-agent: *
|
||||||
|
Disallow:
|
||||||
3
web/src/.prettierrc.json
Normal file
3
web/src/.prettierrc.json
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"tabWidth": 2
|
||||||
|
}
|
||||||
94
web/src/App.css
Normal file
94
web/src/App.css
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
html {
|
||||||
|
font-size: 1em;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
margin: auto;
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
.base {
|
||||||
|
display: grid;
|
||||||
|
grid-row-gap: 1em;
|
||||||
|
}
|
||||||
|
.header {
|
||||||
|
color: white;
|
||||||
|
background-color: rgb(63, 81, 181);
|
||||||
|
box-shadow: 0 0 8px #393939;
|
||||||
|
border-radius: 6px 6px 0 0;
|
||||||
|
}
|
||||||
|
.title {
|
||||||
|
margin-left: 1em;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.title-text {
|
||||||
|
margin-left: 1em;
|
||||||
|
margin-right: 1em;
|
||||||
|
}
|
||||||
|
.logo {
|
||||||
|
width: 39px;
|
||||||
|
height: 39px;
|
||||||
|
border-radius: 6px;
|
||||||
|
}
|
||||||
|
.nav {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-evenly;
|
||||||
|
}
|
||||||
|
.nav-link {
|
||||||
|
color: rgb(229, 232, 245);
|
||||||
|
padding: 1em;
|
||||||
|
}
|
||||||
|
a.unset {
|
||||||
|
color: unset;
|
||||||
|
text-decoration: unset;
|
||||||
|
}
|
||||||
|
a.active {
|
||||||
|
color: deeppink;
|
||||||
|
background-color: lightgray;
|
||||||
|
border-radius: 0.39em 0.39em 0 0;
|
||||||
|
}
|
||||||
|
.audio-player {
|
||||||
|
height: 39px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
td.clickable {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
div.clickable {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
div.page {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
div.search_toolbar {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: flex-end;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
div.feedback {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
button.refresh {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
td,
|
||||||
|
th {
|
||||||
|
padding-bottom: 0.5em;
|
||||||
|
padding-top: 0.5em;
|
||||||
|
}
|
||||||
|
dialog {
|
||||||
|
border: solid;
|
||||||
|
}
|
||||||
|
.player-options {
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
.ffmpeg-config {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
}
|
||||||
80
web/src/App.js
Normal file
80
web/src/App.js
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import {
|
||||||
|
HashRouter as Router,
|
||||||
|
Routes,
|
||||||
|
Route,
|
||||||
|
NavLink,
|
||||||
|
} from "react-router-dom";
|
||||||
|
import "./App.css";
|
||||||
|
|
||||||
|
import GetRandomFiles from "./component/GetRandomFiles";
|
||||||
|
import SearchFiles from "./component/SearchFiles";
|
||||||
|
import SearchFolders from "./component/SearchFolders";
|
||||||
|
import FilesInFolder from "./component/FilesInFolder";
|
||||||
|
import Manage from "./component/Manage";
|
||||||
|
import Share from "./component/Share";
|
||||||
|
import AudioPlayer from "./component/AudioPlayer";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const [playingFile, setPlayingFile] = useState({});
|
||||||
|
return (
|
||||||
|
<div className="base">
|
||||||
|
<Router>
|
||||||
|
<header className="header">
|
||||||
|
<h3 className="title">
|
||||||
|
<img src="favicon.png" alt="logo" className="logo" />
|
||||||
|
<span className="title-text">MSW Open Music Project</span>
|
||||||
|
</h3>
|
||||||
|
<nav className="nav">
|
||||||
|
<NavLink to="/" className="nav-link">
|
||||||
|
Feeling luckly
|
||||||
|
</NavLink>
|
||||||
|
<NavLink to="/files" className="nav-link">
|
||||||
|
Files
|
||||||
|
</NavLink>
|
||||||
|
<NavLink to="/folders" className="nav-link">
|
||||||
|
Folders
|
||||||
|
</NavLink>
|
||||||
|
<NavLink to="/manage" className="nav-link">
|
||||||
|
Manage
|
||||||
|
</NavLink>
|
||||||
|
</nav>
|
||||||
|
</header>
|
||||||
|
<main>
|
||||||
|
<Routes>
|
||||||
|
<Route
|
||||||
|
index
|
||||||
|
path="/"
|
||||||
|
element={<GetRandomFiles setPlayingFile={setPlayingFile} />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/files"
|
||||||
|
element={<SearchFiles setPlayingFile={setPlayingFile} />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/folders"
|
||||||
|
element={<SearchFolders setPlayingFile={setPlayingFile} />}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/folders/:id"
|
||||||
|
element={<FilesInFolder setPlayingFile={setPlayingFile} />}
|
||||||
|
/>
|
||||||
|
<Route path="/manage" element={<Manage />} />
|
||||||
|
<Route
|
||||||
|
path="/files/:id/share"
|
||||||
|
element={<Share setPlayingFile={setPlayingFile} />}
|
||||||
|
/>
|
||||||
|
</Routes>
|
||||||
|
</main>
|
||||||
|
<footer>
|
||||||
|
<AudioPlayer
|
||||||
|
playingFile={playingFile}
|
||||||
|
setPlayingFile={setPlayingFile}
|
||||||
|
/>
|
||||||
|
</footer>
|
||||||
|
</Router>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
||||||
8
web/src/App.test.js
Normal file
8
web/src/App.test.js
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { render, screen } from '@testing-library/react';
|
||||||
|
import App from './App';
|
||||||
|
|
||||||
|
test('renders learn react link', () => {
|
||||||
|
render(<App />);
|
||||||
|
const linkElement = screen.getByText(/learn react/i);
|
||||||
|
expect(linkElement).toBeInTheDocument();
|
||||||
|
});
|
||||||
154
web/src/component/AudioPlayer.js
Normal file
154
web/src/component/AudioPlayer.js
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useNavigate } from "react-router";
|
||||||
|
import { CalcReadableFilesizeDetail } from "./Common";
|
||||||
|
import FfmpegConfig from "./FfmpegConfig";
|
||||||
|
import FileDialog from "./FileDialog";
|
||||||
|
|
||||||
|
function AudioPlayer(props) {
|
||||||
|
// props.playingFile
|
||||||
|
// props.setPlayingFile
|
||||||
|
|
||||||
|
const [fileDialogShowStatus, setFileDialogShowStatus] = useState(false);
|
||||||
|
const [loop, setLoop] = useState(true);
|
||||||
|
const [raw, setRaw] = useState(false);
|
||||||
|
const [prepare, setPrepare] = useState(false);
|
||||||
|
const [selectedFfmpegConfig, setSelectedFfmpegConfig] = useState({});
|
||||||
|
const [playingURL, setPlayingURL] = useState("");
|
||||||
|
const [isPreparing, setIsPreparing] = useState(false);
|
||||||
|
const [preparedFilesize, setPreparedFilesize] = useState(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// no playing file
|
||||||
|
if (props.playingFile.id === undefined) {
|
||||||
|
setPlayingURL("");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (raw) {
|
||||||
|
console.log("Play raw file");
|
||||||
|
setPlayingURL("/api/v1/get_file_direct?id=" + props.playingFile.id);
|
||||||
|
} else {
|
||||||
|
if (prepare) {
|
||||||
|
// prepare file
|
||||||
|
setIsPreparing(true);
|
||||||
|
fetch("/api/v1/prepare_file_stream_direct", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
id: props.playingFile.id,
|
||||||
|
config_name: selectedFfmpegConfig.name,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.then((response) => response.json())
|
||||||
|
.then((data) => {
|
||||||
|
setPreparedFilesize(data.filesize);
|
||||||
|
setIsPreparing(false);
|
||||||
|
setPlayingURL(
|
||||||
|
`/api/v1/get_file_stream_direct?id=${props.playingFile.id}&config=${selectedFfmpegConfig.name}`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setPlayingURL(
|
||||||
|
`/api/v1/get_file_stream?id=${props.playingFile.id}&config=${selectedFfmpegConfig.name}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [props.playingFile.id, raw, prepare, selectedFfmpegConfig]);
|
||||||
|
|
||||||
|
let navigate = useNavigate();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h5>Player status</h5>
|
||||||
|
{props.playingFile.id && (
|
||||||
|
<span>
|
||||||
|
<FileDialog
|
||||||
|
showStatus={fileDialogShowStatus}
|
||||||
|
setShowStatus={setFileDialogShowStatus}
|
||||||
|
file={props.playingFile}
|
||||||
|
setPlayingFile={() => {
|
||||||
|
return;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setFileDialogShowStatus(!fileDialogShowStatus);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{props.playingFile.filename}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
navigate(`/folders/${props.playingFile.folder_id}`)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{props.playingFile.foldername}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button disabled>
|
||||||
|
{prepare
|
||||||
|
? CalcReadableFilesizeDetail(preparedFilesize)
|
||||||
|
: CalcReadableFilesizeDetail(props.playingFile.filesize)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{isPreparing && <button disabled>Preparing...</button>}
|
||||||
|
|
||||||
|
{playingURL !== "" && (
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
props.setPlayingFile({});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Stop
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<input
|
||||||
|
checked={loop}
|
||||||
|
onChange={(event) => setLoop(event.target.checked)}
|
||||||
|
type="checkbox"
|
||||||
|
/>
|
||||||
|
<label>Loop</label>
|
||||||
|
|
||||||
|
<input
|
||||||
|
checked={raw}
|
||||||
|
onChange={(event) => setRaw(event.target.checked)}
|
||||||
|
type="checkbox"
|
||||||
|
/>
|
||||||
|
<label>Raw</label>
|
||||||
|
|
||||||
|
{!raw && (
|
||||||
|
<span>
|
||||||
|
<input
|
||||||
|
checked={prepare}
|
||||||
|
onChange={(event) => setPrepare(event.target.checked)}
|
||||||
|
type="checkbox"
|
||||||
|
/>
|
||||||
|
<label>Prepare</label>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{playingURL !== "" && (
|
||||||
|
<audio
|
||||||
|
controls
|
||||||
|
autoPlay
|
||||||
|
loop={loop}
|
||||||
|
className="audio-player"
|
||||||
|
src={playingURL}
|
||||||
|
></audio>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<FfmpegConfig
|
||||||
|
selectedFfmpegConfig={selectedFfmpegConfig}
|
||||||
|
setSelectedFfmpegConfig={setSelectedFfmpegConfig}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AudioPlayer;
|
||||||
40
web/src/component/Common.js
Normal file
40
web/src/component/Common.js
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
export function CalcReadableFilesize(filesize) {
|
||||||
|
if (filesize < 1024) {
|
||||||
|
return filesize;
|
||||||
|
}
|
||||||
|
if (filesize < 1024 * 1024) {
|
||||||
|
return Math.round(filesize / 1024) + "K";
|
||||||
|
}
|
||||||
|
if (filesize < 1024 * 1024 * 1024) {
|
||||||
|
return Math.round(filesize / 1024 / 1024) + "M";
|
||||||
|
}
|
||||||
|
if (filesize < 1024 * 1024 * 1024 * 1024) {
|
||||||
|
return Math.round(filesize / 1024 / 1024 / 1024) + "G";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CalcReadableFilesizeDetail(filesize) {
|
||||||
|
if (filesize < 1024 * 1024) {
|
||||||
|
return filesize;
|
||||||
|
}
|
||||||
|
if (filesize < 1024 * 1024 * 1024) {
|
||||||
|
return numberWithCommas(Math.round(filesize / 1024)) + "K";
|
||||||
|
}
|
||||||
|
if (filesize < 1024 * 1024 * 1024 * 1024) {
|
||||||
|
return numberWithCommas(Math.round(filesize / 1024 / 1024)) + "M";
|
||||||
|
}
|
||||||
|
if (filesize < 1024 * 1024 * 1024 * 1024 * 1024) {
|
||||||
|
return numberWithCommas(Math.round(filesize / 1024 / 1024 / 1024)) + "G";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function numberWithCommas(x) {
|
||||||
|
x = x.toString();
|
||||||
|
var pattern = /(-?\d+)(\d{3})/;
|
||||||
|
while (pattern.test(x)) x = x.replace(pattern, "$1,$2");
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SayHello() {
|
||||||
|
return "Hello";
|
||||||
|
}
|
||||||
41
web/src/component/FfmpegConfig.js
Normal file
41
web/src/component/FfmpegConfig.js
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
function FfmpegConfig(props) {
|
||||||
|
// props.setSelectedFfmpegConfig
|
||||||
|
// props.selectedFfmpegConfig
|
||||||
|
|
||||||
|
const [ffmpegConfigList, setFfmpegConfigList] = useState([]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetch("/api/v1/get_ffmpeg_config_list")
|
||||||
|
.then((response) => response.json())
|
||||||
|
.then((data) => {
|
||||||
|
setFfmpegConfigList(data.ffmpeg_config_list);
|
||||||
|
if (data.ffmpeg_config_list.length > 0) {
|
||||||
|
props.setSelectedFfmpegConfig(data.ffmpeg_config_list[0]);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert("get_ffmpeg_config_list error: " + error);
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ffmpeg-config">
|
||||||
|
<select
|
||||||
|
onChange={(event) => {
|
||||||
|
props.setSelectedFfmpegConfig(
|
||||||
|
ffmpegConfigList[event.target.selectedIndex]
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{ffmpegConfigList.map((ffmpegConfig) => (
|
||||||
|
<option key={ffmpegConfig.name}>{ffmpegConfig.name}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<span>{props.selectedFfmpegConfig.args}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default FfmpegConfig;
|
||||||
47
web/src/component/FileDialog.js
Normal file
47
web/src/component/FileDialog.js
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import { useNavigate } from "react-router";
|
||||||
|
|
||||||
|
function FileDialog(props) {
|
||||||
|
// props.showStatus
|
||||||
|
// props.setShowStatus
|
||||||
|
// props.playingFile
|
||||||
|
// props.setPlayingFile
|
||||||
|
// props.file
|
||||||
|
|
||||||
|
let navigate = useNavigate();
|
||||||
|
|
||||||
|
const downloadURL = "/api/v1/get_file_direct?id=" + props.file.id;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<dialog open={props.showStatus}>
|
||||||
|
<p>{props.file.filename}</p>
|
||||||
|
<p>
|
||||||
|
Download 使用浏览器下载原文件
|
||||||
|
<br />
|
||||||
|
Play 调用网页播放器播放
|
||||||
|
<br />
|
||||||
|
</p>
|
||||||
|
<a href={downloadURL} download>
|
||||||
|
<button>Download</button>
|
||||||
|
</a>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
props.setPlayingFile(props.file);
|
||||||
|
props.setShowStatus(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Play
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
navigate(`/files/${props.file.id}/share`);
|
||||||
|
props.setShowStatus(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Share
|
||||||
|
</button>
|
||||||
|
<button onClick={() => props.setShowStatus(false)}>Close</button>
|
||||||
|
</dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default FileDialog;
|
||||||
45
web/src/component/FileEntry.js
Normal file
45
web/src/component/FileEntry.js
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useNavigate } from "react-router";
|
||||||
|
import { CalcReadableFilesize } from "./Common";
|
||||||
|
import FileDialog from "./FileDialog";
|
||||||
|
|
||||||
|
function FileEntry(props) {
|
||||||
|
const [showStatus, setShowStatus] = useState(false);
|
||||||
|
let navigate = useNavigate();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<tr>
|
||||||
|
<td
|
||||||
|
className="clickable"
|
||||||
|
onClick={() => {
|
||||||
|
// double click to play file and close dialog
|
||||||
|
if (showStatus) {
|
||||||
|
props.setPlayingFile(props.file);
|
||||||
|
setShowStatus(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setShowStatus(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{props.file.filename}
|
||||||
|
</td>
|
||||||
|
<td
|
||||||
|
className="clickable"
|
||||||
|
onClick={() => navigate(`/folders/${props.file.folder_id}`)}
|
||||||
|
>
|
||||||
|
{props.file.foldername}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{CalcReadableFilesize(props.file.filesize)}
|
||||||
|
<FileDialog
|
||||||
|
setPlayingFile={props.setPlayingFile}
|
||||||
|
showStatus={showStatus}
|
||||||
|
setShowStatus={setShowStatus}
|
||||||
|
file={props.file}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default FileEntry;
|
||||||
60
web/src/component/FilesInFolder.js
Normal file
60
web/src/component/FilesInFolder.js
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import { useParams } from "react-router";
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import FilesTable from "./FilesTable";
|
||||||
|
|
||||||
|
function FilesInFolder(props) {
|
||||||
|
let params = useParams();
|
||||||
|
const [files, setFiles] = useState([]);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [offset, setOffset] = useState(0);
|
||||||
|
const limit = 10;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setIsLoading(true);
|
||||||
|
fetch("/api/v1/get_files_in_folder", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
folder_id: parseInt(params.id),
|
||||||
|
offset: offset,
|
||||||
|
limit: limit,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.then((response) => response.json())
|
||||||
|
.then((data) => {
|
||||||
|
setFiles(data.files ? data.files : []);
|
||||||
|
})
|
||||||
|
.catch((error) => alert(error))
|
||||||
|
.finally(() => {
|
||||||
|
setIsLoading(false);
|
||||||
|
});
|
||||||
|
}, [params.id, offset]);
|
||||||
|
|
||||||
|
function nextPage() {
|
||||||
|
setOffset(offset + limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
function lastPage() {
|
||||||
|
const offsetValue = offset - limit;
|
||||||
|
if (offsetValue < 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setOffset(offsetValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="page">
|
||||||
|
<h3>Files in Folder</h3>
|
||||||
|
<div className="search_toolbar">
|
||||||
|
<button onClick={lastPage}>Last page</button>
|
||||||
|
<button disabled>
|
||||||
|
{isLoading ? "Loading..." : `${offset} - ${offset + files.length}`}
|
||||||
|
</button>
|
||||||
|
<button onClick={nextPage}>Next page</button>
|
||||||
|
</div>
|
||||||
|
<FilesTable setPlayingFile={props.setPlayingFile} files={files} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default FilesInFolder;
|
||||||
29
web/src/component/FilesTable.js
Normal file
29
web/src/component/FilesTable.js
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import FileEntry from "./FileEntry";
|
||||||
|
|
||||||
|
function FilesTable(props) {
|
||||||
|
if (props.files.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Filename</th>
|
||||||
|
<th>Folder Name</th>
|
||||||
|
<th>Size</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{props.files.map((file) => (
|
||||||
|
<FileEntry
|
||||||
|
setPlayingFile={props.setPlayingFile}
|
||||||
|
key={file.id}
|
||||||
|
file={file}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default FilesTable;
|
||||||
35
web/src/component/FoldersTable.js
Normal file
35
web/src/component/FoldersTable.js
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { useNavigate } from "react-router";
|
||||||
|
|
||||||
|
function FoldersTable(props) {
|
||||||
|
let navigate = useNavigate();
|
||||||
|
if (props.folders.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Folder name</th>
|
||||||
|
<th>Action</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{props.folders.map((folder) => (
|
||||||
|
<tr key={folder.id}>
|
||||||
|
<td
|
||||||
|
onClick={() => navigate(`/folders/${folder.id}`)}
|
||||||
|
className="clickable"
|
||||||
|
>
|
||||||
|
{folder.foldername}
|
||||||
|
</td>
|
||||||
|
<td onClick={() => navigate(`/folders/${folder.id}`)}>
|
||||||
|
<button>View</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default FoldersTable;
|
||||||
38
web/src/component/GetRandomFiles.js
Normal file
38
web/src/component/GetRandomFiles.js
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import FilesTable from "./FilesTable";
|
||||||
|
|
||||||
|
function GetRandomFiles(props) {
|
||||||
|
const [files, setFiles] = useState([]);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
|
function refresh(setFiles) {
|
||||||
|
setIsLoading(true);
|
||||||
|
fetch("/api/v1/get_random_files")
|
||||||
|
.then((response) => response.json())
|
||||||
|
.then((data) => {
|
||||||
|
setFiles(data.files);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert("get_random_files error: " + error);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
setIsLoading(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
refresh(setFiles);
|
||||||
|
}, []);
|
||||||
|
return (
|
||||||
|
<div className="page">
|
||||||
|
<div className="search_toolbar">
|
||||||
|
<button className="refresh" onClick={() => refresh(setFiles)}>
|
||||||
|
{isLoading ? "Loading..." : "Refresh"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<FilesTable setPlayingFile={props.setPlayingFile} files={files} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default GetRandomFiles;
|
||||||
51
web/src/component/Manage.js
Normal file
51
web/src/component/Manage.js
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
function Manage() {
|
||||||
|
const [token, setToken] = useState("");
|
||||||
|
const [walkPath, setWalkPath] = useState("");
|
||||||
|
|
||||||
|
function updateDatabase() {
|
||||||
|
fetch("/api/v1/walk", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
token: token,
|
||||||
|
root: walkPath,
|
||||||
|
pattern: [".wav", ".mp3"],
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.then((res) => res.json())
|
||||||
|
.then((data) => {
|
||||||
|
console.log(data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h2>Manage</h2>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={token}
|
||||||
|
placeholder="token"
|
||||||
|
onChange={(e) => setToken(e.target.value)}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={walkPath}
|
||||||
|
placeholder="walk path"
|
||||||
|
onChange={(e) => setWalkPath(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
updateDatabase();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Update Database
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Manage;
|
||||||
81
web/src/component/SearchFiles.js
Normal file
81
web/src/component/SearchFiles.js
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import FilesTable from "./FilesTable";
|
||||||
|
|
||||||
|
function SearchFiles(props) {
|
||||||
|
const [files, setFiles] = useState([]);
|
||||||
|
const [filename, setFilename] = useState("");
|
||||||
|
const [offset, setOffset] = useState(0);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const limit = 10;
|
||||||
|
|
||||||
|
function searchFiles() {
|
||||||
|
setIsLoading(true);
|
||||||
|
fetch("/api/v1/search_files", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
filename: filename,
|
||||||
|
limit: limit,
|
||||||
|
offset: offset,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.then((response) => response.json())
|
||||||
|
.then((data) => {
|
||||||
|
const files = data.files ? data.files : [];
|
||||||
|
setFiles(files);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert("search_files error: " + error);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
setIsLoading(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function nextPage() {
|
||||||
|
setOffset(offset + limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
function lastPage() {
|
||||||
|
const offsetValue = offset - limit;
|
||||||
|
if (offsetValue < 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setOffset(offsetValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => searchFiles(), [offset]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="page">
|
||||||
|
<h3>Search Files</h3>
|
||||||
|
<div className="search_toolbar">
|
||||||
|
<input
|
||||||
|
onChange={(event) => setFilename(event.target.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "Enter") {
|
||||||
|
searchFiles();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
type="text"
|
||||||
|
placeholder="Enter filename"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
searchFiles();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isLoading ? "Loading..." : "Search"}
|
||||||
|
</button>
|
||||||
|
<button onClick={lastPage}>Last page</button>
|
||||||
|
<button disabled>
|
||||||
|
{offset} - {offset + files.length}
|
||||||
|
</button>
|
||||||
|
<button onClick={nextPage}>Next page</button>
|
||||||
|
</div>
|
||||||
|
<FilesTable setPlayingFile={props.setPlayingFile} files={files} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SearchFiles;
|
||||||
79
web/src/component/SearchFolders.js
Normal file
79
web/src/component/SearchFolders.js
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import FoldersTable from "./FoldersTable";
|
||||||
|
|
||||||
|
function SearchFolders() {
|
||||||
|
const [foldername, setFoldername] = useState("");
|
||||||
|
const [folders, setFolders] = useState([]);
|
||||||
|
const [offset, setOffset] = useState(0);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const limit = 10;
|
||||||
|
|
||||||
|
function searchFolder() {
|
||||||
|
if (foldername === "") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setIsLoading(true);
|
||||||
|
fetch("/api/v1/search_folders", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
foldername: foldername,
|
||||||
|
limit: limit,
|
||||||
|
offset: offset,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.then((response) => response.json())
|
||||||
|
.then((data) => {
|
||||||
|
setFolders(data.folders ? data.folders : []);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert("search_folders error: " + error);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
setIsLoading(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function nextPage() {
|
||||||
|
setOffset(offset + limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
function lastPage() {
|
||||||
|
const offsetValue = offset - limit;
|
||||||
|
if (offsetValue < 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setOffset(offsetValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => searchFolder(), [offset]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="page">
|
||||||
|
<h3>Search Folders</h3>
|
||||||
|
<div className="search_toolbar">
|
||||||
|
<input
|
||||||
|
onChange={(event) => setFoldername(event.target.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "Enter") {
|
||||||
|
searchFolder();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
type="text"
|
||||||
|
placeholder="Enter folder name"
|
||||||
|
/>
|
||||||
|
<button onClick={searchFolder}>
|
||||||
|
{isLoading ? "Loading..." : "Search"}
|
||||||
|
</button>
|
||||||
|
<button onClick={lastPage}>Last page</button>
|
||||||
|
<button disabled>
|
||||||
|
{offset} - {offset + limit}
|
||||||
|
</button>
|
||||||
|
<button onClick={nextPage}>Next page</button>
|
||||||
|
</div>
|
||||||
|
<FoldersTable folders={folders} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SearchFolders;
|
||||||
39
web/src/component/Share.js
Normal file
39
web/src/component/Share.js
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useParams } from "react-router";
|
||||||
|
import FilesTable from "./FilesTable";
|
||||||
|
|
||||||
|
function Share(props) {
|
||||||
|
let params = useParams();
|
||||||
|
const [file, setFile] = useState([]);
|
||||||
|
useEffect(() => {
|
||||||
|
fetch("/api/v1/get_file_info", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
id: parseInt(params.id),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.then((response) => response.json())
|
||||||
|
.then((data) => {
|
||||||
|
setFile([data]);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
alert("get_file_info error: " + error);
|
||||||
|
});
|
||||||
|
}, [params]);
|
||||||
|
return (
|
||||||
|
<div className="page">
|
||||||
|
<h3>Share with others!</h3>
|
||||||
|
<p>
|
||||||
|
👇 Click the filename below to enjoy music!
|
||||||
|
<br />
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Share link: <a href={window.location.href}>{window.location.href}</a>
|
||||||
|
</p>
|
||||||
|
<FilesTable setPlayingFile={props.setPlayingFile} files={file} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Share;
|
||||||
13
web/src/index.css
Normal file
13
web/src/index.css
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||||
|
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||||
|
sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
|
|
||||||
|
code {
|
||||||
|
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||||
|
monospace;
|
||||||
|
}
|
||||||
18
web/src/index.js
Normal file
18
web/src/index.js
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import ReactDOM from 'react-dom';
|
||||||
|
import './index.css';
|
||||||
|
import 'water.css';
|
||||||
|
import App from './App';
|
||||||
|
import reportWebVitals from './reportWebVitals';
|
||||||
|
|
||||||
|
ReactDOM.render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<App />
|
||||||
|
</React.StrictMode>,
|
||||||
|
document.getElementById('root')
|
||||||
|
);
|
||||||
|
|
||||||
|
// If you want to start measuring performance in your app, pass a function
|
||||||
|
// to log results (for example: reportWebVitals(console.log))
|
||||||
|
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
||||||
|
reportWebVitals();
|
||||||
13
web/src/reportWebVitals.js
Normal file
13
web/src/reportWebVitals.js
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
const reportWebVitals = onPerfEntry => {
|
||||||
|
if (onPerfEntry && onPerfEntry instanceof Function) {
|
||||||
|
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
|
||||||
|
getCLS(onPerfEntry);
|
||||||
|
getFID(onPerfEntry);
|
||||||
|
getFCP(onPerfEntry);
|
||||||
|
getLCP(onPerfEntry);
|
||||||
|
getTTFB(onPerfEntry);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export default reportWebVitals;
|
||||||
5
web/src/setupTests.js
Normal file
5
web/src/setupTests.js
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
// jest-dom adds custom jest matchers for asserting on DOM nodes.
|
||||||
|
// allows you to do things like:
|
||||||
|
// expect(element).toHaveTextContent(/react/i)
|
||||||
|
// learn more: https://github.com/testing-library/jest-dom
|
||||||
|
import '@testing-library/jest-dom';
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
html {
|
|
||||||
font-size: 1em;
|
|
||||||
}
|
|
||||||
.base {
|
|
||||||
display: grid;
|
|
||||||
grid-row-gap: 1em;
|
|
||||||
}
|
|
||||||
.header {
|
|
||||||
color: white;
|
|
||||||
background-color: rgb(63, 81, 181);
|
|
||||||
box-shadow: 0 0 8px #393939;
|
|
||||||
}
|
|
||||||
.title {
|
|
||||||
margin-left: 1em;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
.title-text {
|
|
||||||
margin-left: 1em;
|
|
||||||
margin-right: 1em;
|
|
||||||
}
|
|
||||||
.logo {
|
|
||||||
width: 39px;
|
|
||||||
height: 39px;
|
|
||||||
border-radius: 6px;
|
|
||||||
}
|
|
||||||
.nav {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-evenly;
|
|
||||||
}
|
|
||||||
.nav-link {
|
|
||||||
color: rgb(229, 232, 245);
|
|
||||||
padding: 1em;
|
|
||||||
}
|
|
||||||
a.router-link-active {
|
|
||||||
color: deeppink;
|
|
||||||
background-color: lightgray;
|
|
||||||
border-radius: 0.39em 0.39em 0 0;
|
|
||||||
}
|
|
||||||
.audio-player {
|
|
||||||
height: 39px;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
td.clickable {
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
div.clickable {
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
div.page {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
}
|
|
||||||
div.search_toolbar {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: row;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
justify-content: flex-end;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
div.feedback {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: row;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
}
|
|
||||||
button.refresh {
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
td, th {
|
|
||||||
padding-bottom: 0.5em;
|
|
||||||
padding-top: 0.5em;
|
|
||||||
}
|
|
||||||
File diff suppressed because one or more lines are too long
3375
web/vue-router.js
3375
web/vue-router.js
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
13931
web/vue.js
13931
web/vue.js
File diff suppressed because it is too large
Load Diff
1506
web/water.css
1506
web/water.css
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user