18 Commits

Author SHA1 Message Date
b6013ba1e3 DBMS add web/README.md demo website and group info 2021-11-28 23:07:54 +08:00
3457fde522 DBMS Submit static webpage
Removed all fetch function
2021-11-28 18:56:33 +08:00
be2515231c Update: docs/problem_description add extra description 2021-11-25 23:57:54 +08:00
2358335d4e Add: README.md DBMS TODO 2021-11-25 23:57:42 +08:00
1bef4d0272 Add: docs/problem_description.md 2021-11-25 23:55:43 +08:00
546385a484 Update: Share instruction 2021-11-25 23:48:09 +08:00
d8470d0f4b Update: FileDialog download method 2021-11-25 23:48:09 +08:00
85a6c2b859 fix bug recursive FileDialog 2021-11-25 23:48:06 +08:00
057e21285b Change README.md to english 2021-11-25 16:12:55 +08:00
e485d1a8c5 Update: documents and Makefile 2021-11-24 11:39:40 +08:00
e3de41fe07 add web handle fetch error 2021-11-24 11:09:21 +08:00
8a2c8dd8b2 add coc .prettierrc.json for web 2021-11-24 11:08:40 +08:00
abc0096ade fix: web package version number 2021-11-24 10:48:43 +08:00
e170c8b842 Rewrite web front-end using React
This is a big commit, some font-end function are still working,
including manage, error handle, as others.
2021-11-21 17:30:43 +08:00
d556bbe0c8 Break: change ffmpeg_configs to ffmpeg_config_list structure 2021-11-14 23:18:09 +08:00
b1fb8b0866 Update README.md for release v1.0.0 2021-05-30 11:14:56 +08:00
b0d903a096 delete test.html 2021-05-30 11:11:55 +08:00
3c6552e480 Merge branch 'no-dialog' 2021-05-30 02:53:04 +08:00
59 changed files with 39329 additions and 20075 deletions

View File

@@ -1,10 +1,6 @@
dist:
mkdir -p dist
minify web/index.js web/*.html web/*.css -o dist/
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
cd web && npm install
cd web && npm run build
linux:
go build

297
README.md
View File

@@ -1,62 +1,123 @@
# MSW Open Music Project
## 简介
## Introduction
Fork from `msw-file`,目前是一个音乐播放器。
A light weight personal music streaming platform.
![demo1](demo1.jpg)
[toc]
## TODO
- Restructure为多人协作做好准备
### 前端部分更改
- 修复页面 CSS 溢出问题
- 显示操作执行世界
页面数量至少 10 个(目前 5 个),预计添加如下页面
- 文件详情页,可以修改单个文件的信息
- 文件评论页,可对文件进行评论
- 最新动态页,查看最近播放的曲目、最近的评论
- 登录/注册页,取代现有的 token 逻辑
- FfmpegConfigs 配置页面
- 意见反馈的查看页面
### 后端部分更改
- 返回操作执行时间
- 修复 Prepare 模式转码不完整但仍然被 tmpfs 记录为成功转码的问题
- FfmpegConfigs 由目前的字典格式改为列表格式
- 为 sqlite3 添加数据库单线程锁
- 添加外键约束
- Update 功能自动检查重复的项目并忽略,只添加新的项目
- Token 验证方法改为 暱称 + 密码 的方法,管理员使用 admin 保留关键字作为暱称。
需要 8 个 entities 和 6 个 relationship目前有 3 个 entities和 1 个 relationship
目前有
- files 文件表,数量 50,000
- folders 文件夹表,数量 3,000
- feedbacks 反馈留言表
计划添加
- users 用户表
- comments 管理表
- playbacks 播放记录表
- likes 点赞记录表
## 编译 & 构建
### 编译后端
## How to build
`go build`
### Build the back-end server
如无任何输出,说明构建成功,可执行程序位于 `msw-open-music`
`make linux` or `make windows`
### 构建前端
The executable file is named `msw-open-music` or `msw-open-music.exe`
`make`
### Build the font-end web pages
说明:`Makefile` 脚本中的代码会在 `dist` 目录生成用于生产环境的前端 web 文件。这个脚本做的事情是简单地将 `vue` `vue-router` 等 js 文件替换成生产版本。并使用 `minify` 工具处理 `css``html` 文件。
To build production web page `make web`
## 使用
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`
初次使用请配置 `config.json` **最重要的是配置 `token`**
## Usage
默认 ffmpeg 线程 `ffmpeg_threads` 为 1 ,大于 1 以上的值似乎对编码音频没有效果。
Start back-end server. Server will listen on 8080 port.
#### config.json 说明
Build the font-end web page, then go to <http://127.0.0.1:8080>
- `database_name` 字符串类型,指定 sqlite3 单文件数据库的位置,如果不存在则会自动创建。
- `addr` api 服务监听端口,该参数会被传入 `http.Serve.Addr`
- `token` 字符串,作为管理密码
- `ffmpeg_configs`,字典,其键是 ffmpeg 配置的名称,其值是放入 `ffmpeg -i input.mp3 -vn [此处] -f matroska -` 的参数,类型是字符串。 **注意:** 前端会按键名来排序配置列表,并以列表中的第一项作为默认配置。
- `file_life_time` 临时文件生存时间超过该时间没有访问该临时文件tmpfs 将删除此文件。
- `cleaner_internal` 清理器的检查间隔。
- `root` 存放该临时文件目录, **Windows 用户请替换成合适的目录。**
By default:
### 前端使用
- URL matched `/api/*` will process by back-end server.
- Others URL matched `/*` will be served files under `web/build/`
前端文件引用均使用相对路径,将前端文件放到同一目录下即可。
### Run back-end server
前端在调用后端 api 时使用的是绝对路径,例如 `/api/v1/hello`。如需更改,可以修改后端 `api.go` 中的 `apiMux``mux` 的相关属性
Configuration file is `config.json` **Please modify your `token`**
## 关于临时文件夹的说明
Default `ffmpeg_threads` is 1. Seems value larger than 1 will not increase the audio encode speed.
前端播放器中勾选了 `Prepare` ,后端将转码文件到临时文件夹,然后直链提供文件。这有助于修复网路不稳定时 TCP 链接断开stream 模式下 ffmpeg 中断输出并且不能断点续传的问题。
#### config.json description
临时文件夹管理器位于 `internal/pkg/tmpfs` 中,默认删除时间是 10 分钟。10分钟内如果没有对该临时文件的访问则会删除此临时文件。
- `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.**
## 后端 API 文档
### Run font-end web page
说明中带有 `stream``流` 相关字样的,说明该 API 以 `io.Copy` 方式传输文件,不支持断点续传
Open your web browser to <http://127.0.0.1:8080> you will see the web pages.
无需返回数据的 API 将返回 OK某些 API 可能会在 `status` 字段中返回详细的执行信息。
## 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
- `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`).
## Back-end API references
API named `stream` means it transfer data using `io.Copy`, which **DO NOT** support continue getting a partially-downloaded audio.
API does not need to respond any data will return the following JSON object.
```json
{
@@ -64,13 +125,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
{
@@ -78,15 +141,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/search_files` 搜索文件
- `/api/v1/search_files` Search files by filename.
- 请求示例
- Request example
```json
{
@@ -96,13 +159,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
{
@@ -115,29 +178,29 @@ Fork from `msw-file`,目前是一个音乐播放器。
"filesize": 1048576
},
{
"id": 30,
"id": 31,
"folder_id": 100,
"folder_name": "wonderful",
"filename": "memories.flac",
"filesize": 1048576
"filename": "memories (instrunment).flac",
"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
{
@@ -147,13 +210,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
{
@@ -163,20 +226,20 @@ Fork from `msw-file`,目前是一个音乐播放器。
"foldername": "folder name"
},
{
"id": 100,
"foldername": "folder name"
"id": 101,
"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
{
@@ -186,52 +249,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.
- 返回示例
同 `/api/v1/search_files`
Same with `/api/v1/search_files`
- `/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`
获取 ffmpeg 配置列表
Get ffmpeg config list
- 请求示例
- Request example
GET `/api/v1/get_ffmpeg_config_list`
- 返回示例
- Respond example
```json
{
"ffmpeg_configs": {
"OPUS 256k": {"args": "-c:a libopus -ab 256k"},
"WAV": {"args": "-c:a wav"}
}
"ffmpeg_config_list": [
{"name": "OPUS 256k", "args": "-c:a libopus -ab 256k"},
{"name": "WAV", "args": "-c:a wav"}
]
}
```
- `/api/v1/feedback` 反馈
- `/api/v1/feedback` Send a feedback.
- 请求示例
- Request example
```json
{
@@ -239,11 +300,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
{
@@ -251,7 +312,7 @@ Fork from `msw-file`,目前是一个音乐播放器。
}
```
- 返回示例
- Respond example.
```json
{
@@ -263,15 +324,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
{
@@ -280,7 +341,7 @@ Fork from `msw-file`,目前是一个音乐播放器。
}
```
- 返回示例
- Respond example
```json
{
@@ -288,13 +349,11 @@ Fork from `msw-file`,目前是一个音乐播放器。
}
```
### API needs token
### 需要 token 的 API
- `/api/v1/walk` Walk directory, add all files and folders to database.
- `/api/v1/walk` 遍历目录,并将文件和文件夹添加到数据库中
- 请求示例
- Request example
```json
{
@@ -304,17 +363,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
{
@@ -322,13 +381,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
{
@@ -340,26 +399,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 文档
- `/#/share/39`
前端只有少量 API ,允许用户直接打开链接就执行某些功能
Share a specific file.
- `/web/#/share?id=39`
- `/#/search-folders/2614`
分享文件id 是文件的唯一标识。
- `/web/#/search_folders?folder_id=2614`
显示该文件夹中的文件, folder_id 是文件夹的唯一标识。
Show files in a specific folder.

View File

@@ -4,16 +4,16 @@
"addr": ":8080",
"token": "!! config your very strong token here !!",
"ffmpeg_threads": 1,
"ffmpeg_configs": {
"0. OPUS 128k": {"args": "-c:a libopus -ab 128k"},
"1. OPUS 96k": {"args": "-c:a libopus -ab 96k"},
"2. OPUS 256k": {"args": "-c:a libopus -ab 256k"},
"3. OPUS 320k": {"args": "-c:a libopus -ab 320k"},
"4. OPUS 512k": {"args": "-c:a libopus -ab 512k"},
"5. AAC 128k": {"args": "-c:a aac -ab 128k"},
"6. AAC 256k": {"args": "-c:a aac -ab 256k"},
"7. 全损音质 32k": {"args": "-c:a libopus -ab 32k"}
}
"ffmpeg_config_list": [
{"name": "OPUS 128k", "args": "-c:a libopus -ab 128k"},
{"name": "OPUS 96k", "args": "-c:a libopus -ab 96k"},
{"name": "OPUS 256k", "args": "-c:a libopus -ab 256k"},
{"name": "OPUS 320k", "args": "-c:a libopus -ab 320k"},
{"name": "OPUS 512k", "args": "-c:a libopus -ab 512k"},
{"name": "AAC 128k", "args": "-c:a aac -ab 128k"},
{"name": "AAC 256k", "args": "-c:a aac -ab 256k"},
{"name": "全损音质 32k", "args": "-c:a libopus -ab 32k"}
]
},
"tmpfs": {
"file_life_time": 600,

BIN
demo1.jpg

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 46 KiB

View File

@@ -0,0 +1,36 @@
# DBMS Group Project Problem Description
- Group 1
The Internet infrastructure construction has made the network speed development faster. With the fast Internet, people are gradually migrating various data and services to the cloud. For example, NetEase Cloud Music, Spotify, and Apple Music, we call them streaming media platforms. The definition of streaming media platform is that users purchase the digital copyright of music and then play the music online on the platform.
Generally speaking, users cannot buy music that is not available on the platform. The user cannot download the digital file of the music (the user purchases the right to play instead of the right to copy). Users cannot upload their music to the platform.
However, in the era of digital copyright, there are still many advantages to getting original music files, such as no need to install a dedicated player; free copying to other devices (without violating copyright); no risk of music unavailable from the platform; no play records and privacy will be tracked by the platform.
Some people don't like streaming platforms. They like to collect music (download or buy CDs) and save it on their computers. But as more and more music is collected (over 70,000 songs and in total size of 800GB), it becomes very difficult to manage files. It is difficult for them to find where the songs they want to listen to are saved. Also, lossless music files are large and difficult to play online.
As long as there no such "Self-hosted music streaming platform" software available, we decided to develop a project based on database knowledge to help people who have collected a lot of music to enjoy their music simply.
We will handle various relevant types of data in our database. Including song name, album name, file size, update date, rating, comment, user information, etc. They are highly relevant, so using a relational database will be a good choice.
The features of the project we designed are as follows:
- Open. Independent front-end (GUI) and back-end (server program), using API to communicate.
- Easy to use. Minimize dependencies, allowing users to configure quickly and simply.
- Lightweight. The program is small in size and quick to install.
- High performance. Only do what should be done, no features that will lead to poor performance.
- Cross-platform. The project can run on computers, mobile phones, Linux, Windows, macOS, and X86 and ARM processor architectures.
- Extensibility. Access to cloud OSS (Object Storage Service), reverse proxy, or other external software.
Our project has the following functions:
- Index file. Index local files into the database.
- Search. Search for music based on name/album/tag/comment, sorted by rating or other columns.
- Play. Play music online, play music randomly and play music at a low bit rate on a bad network.
- User management. Users can register and log in.
- Comment. Users can give a like or comment on the music.
- Management. The administrator can upload music, update or delete the database.
- Share. Generate a link to share the music with others.
After research and discussion, in order to meet the above requirements, we decided to use the Golang programming language on the backend. SQLite as a database program. Vue as the front-end GUI interface.

View File

@@ -24,8 +24,8 @@ type API struct {
Tmpfs *tmpfs.Tmpfs
}
type FfmpegConfigs struct {
FfmpegConfigs map[string]*FfmpegConfig `json:"ffmpeg_configs"`
type FfmpegConfigList struct {
FfmpegConfigList []FfmpegConfig `json:"ffmpeg_config_list"`
}
type AddFfmpegConfigRequest struct {
@@ -35,6 +35,7 @@ type AddFfmpegConfigRequest struct {
}
type FfmpegConfig struct {
Name string `json:"name"`
Args string `json:"args"`
}
@@ -371,6 +372,19 @@ func (api *API) CheckGetFileStream(w http.ResponseWriter, r *http.Request) (erro
return nil
}
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) HandleGetFileStream(w http.ResponseWriter, r *http.Request) {
err := api.CheckGetFileStream(w, r)
if err != nil {
@@ -395,7 +409,7 @@ func (api *API) HandleGetFileStream(w http.ResponseWriter, r *http.Request) {
log.Println("[api] Stream file", path, configName)
ffmpegConfig, ok := api.APIConfig.FfmpegConfigs[configName]
ffmpegConfig, ok := api.GetFfmpegConfig(configName)
if !ok {
api.HandleErrorStringCode(w, r, `ffmpeg config not found`, 404)
return
@@ -455,7 +469,7 @@ func (api *API) HandlePrepareFileStreamDirect(w http.ResponseWriter, r *http.Req
}
log.Println("[api] Prepare stream direct file", srcPath, prepareFileStreamDirectRequst.ConfigName)
ffmpegConfig, ok := api.APIConfig.FfmpegConfigs[prepareFileStreamDirectRequst.ConfigName]
ffmpegConfig, ok := api.GetFfmpegConfig(prepareFileStreamDirectRequst.ConfigName)
if !ok {
api.HandleErrorStringCode(w, r, `ffmpeg config not found`, 404)
return
@@ -593,10 +607,10 @@ func (api *API) HandleGetFile(w http.ResponseWriter, r *http.Request) {
func (api *API) HandleGetFfmpegConfigs(w http.ResponseWriter, r *http.Request) {
log.Println("[api] Get ffmpeg config list")
ffmpegConfigs:= &FfmpegConfigs{
FfmpegConfigs: api.APIConfig.FfmpegConfigs,
ffmpegConfigList:= &FfmpegConfigList{
FfmpegConfigList: api.APIConfig.FfmpegConfigList,
}
json.NewEncoder(w).Encode(&ffmpegConfigs)
json.NewEncoder(w).Encode(&ffmpegConfigList)
}
func (api *API) HandleAddFfmpegConfig(w http.ResponseWriter, r *http.Request) {
@@ -625,7 +639,8 @@ func (api *API) HandleAddFfmpegConfig(w http.ResponseWriter, r *http.Request) {
log.Println("[api] Add ffmpeg config")
api.APIConfig.FfmpegConfigs[addFfmpegConfigRequest.Name] = &addFfmpegConfigRequest.FfmpegConfig
api.APIConfig.FfmpegConfigList = append(api.APIConfig.FfmpegConfigList, addFfmpegConfigRequest.FfmpegConfig)
api.HandleOK(w, r)
}
@@ -666,9 +681,7 @@ func (api *API) HandleFeedback(w http.ResponseWriter, r *http.Request) {
}
func NewAPIConfig() (APIConfig) {
apiConfig := APIConfig{
FfmpegConfigs: make(map[string]*FfmpegConfig),
}
apiConfig := APIConfig{}
return apiConfig
}
@@ -677,12 +690,20 @@ type APIConfig struct {
Addr string `json:"addr"`
Token string `json:"token"`
FfmpegThreads int64 `json:"ffmpeg_threads"`
FfmpegConfigs map[string]*FfmpegConfig `json:"ffmpeg_configs"`
FfmpegConfigList []FfmpegConfig `json:"ffmpeg_config_list"`
}
func NewAPI(apiConfig APIConfig, tmpfsConfig tmpfs.TmpfsConfig) (*API, error) {
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
@@ -721,7 +742,7 @@ func NewAPI(apiConfig APIConfig, tmpfsConfig tmpfs.TmpfsConfig) (*API, error) {
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"))))
mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("web/build"))))
api.token = apiConfig.Token

View File

@@ -5,7 +5,6 @@ import (
"flag"
"log"
"msw-open-music/internal/pkg/api"
"msw-open-music/internal/pkg/tmpfs"
"os"
)
@@ -15,16 +14,12 @@ func init() {
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() {
var err error
flag.Parse()
config := Config{}
config := api.Config{}
configFile, err := os.Open(ConfigFilePath)
if err != nil {
log.Fatal(err)
@@ -35,7 +30,7 @@ func main() {
}
configFile.Close()
api, err := api.NewAPI(config.APIConfig, config.TmpfsConfig)
api, err := api.NewAPI(config)
if err != nil {
log.Fatal(err)
}

23
web/.gitignore vendored Normal file
View 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
View File

@@ -0,0 +1,4 @@
:8081 {
reverse_proxy /api/* localhost:8080
reverse_proxy * localhost:3000
}

58
web/README.md Normal file
View File

@@ -0,0 +1,58 @@
# msw-open-music web font-end
This msw-open-music project was bootstrapped with `Create React App`
## Group 9 information
| Name | Name (EN) | No |
| ------ | ------------- | ---------- |
| 陈永源 | CHEN Yongyuan | 1930006025 |
| 鲁雷 | Lu Lei | 2030026101 |
| 张滨玮 | Zhang Binwei | 2030026197 |
| 丁俊超 | Ding Junchao | 2030026258 |
| 邱星越 | Qiu Xingyue | 2030026119 |
| 李真晔 | Li Zhenye | 2030006104 |
## URL References
- `/#/` Default home page. Generate random files.
- `/#/search-files` Search files
- `/#/search-folders` Search folders
- `/#/folder/:id` Show files in the folder
- `/#/file/:id` Show file's information
- `/#/file/:id/share` Share a specific file
- `/#/file/:id/review` Review a file
- `/#/manage` Manage system setting and status
- `/#/login` Login
- `/#/register/` Register
- `/#/profile/:id` Profile of a user
## HOW TO DEPLOY?
Welcome to visit the demo <https://demo.uicbbs.com>
Put the files under `build` folder to your HTTP server (Apache, nginx, caddy, etc.) root folder.
## 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 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.

3
web/axios.min.js vendored

File diff suppressed because one or more lines are too long

View File

@@ -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>

View File

@@ -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 作为 keyffmpeg_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

File diff suppressed because it is too large Load Diff

44
web/package.json Normal file
View 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"
}
}

View File

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

41
web/public/index.html Normal file
View 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
View 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
View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

3
web/src/.prettierrc.json Normal file
View File

@@ -0,0 +1,3 @@
{
"tabWidth": 2
}

102
web/src/App.css Normal file
View File

@@ -0,0 +1,102 @@
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;
}
.avatar {
border-radius: 50%;
background-color: lightpink;
padding: 0.39rem;
}
.title {
margin-left: 1em;
margin-right: 1em;
display: flex;
align-items: center;
vertical-align: middle;
justify-content: space-between;
}
.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;
}

91
web/src/App.js Normal file
View File

@@ -0,0 +1,91 @@
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 Manage from "./component/Manage";
import Share from "./component/Share";
import AudioPlayer from "./component/AudioPlayer";
import FilesInFolder from "./component/FilesInFolder";
import FileInfo from "./component/FileInfo";
import Review from "./component/Review";
import Profile from "./component/Profile";
import User from "./component/User";
import Login from "./component/Login";
import Register from "./component/Register";
import { useState } from "react";
function App() {
const [playingFile, setPlayingFile] = useState({});
const [user, setUser] = useState(null);
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>
<User user={user} setUser={setUser} />
</h3>
<nav className="nav">
<NavLink to="/" className="nav-link">
Feeling luckly
</NavLink>
<NavLink to="/search-files" className="nav-link">
Files
</NavLink>
<NavLink to="/search-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="/search-files"
element={<SearchFiles setPlayingFile={setPlayingFile} />}
/>
<Route
path="/search-folders"
element={<SearchFolders setPlayingFile={setPlayingFile} />}
/>
<Route
path="/folder/:id"
element={<FilesInFolder setPlayingFile={setPlayingFile} />}
/>
<Route path="/manage" element={<Manage />} />
<Route
path="/file/:id/share"
element={<Share setPlayingFile={setPlayingFile} />}
/>
<Route path="/file/:id/review" element={<Review />} />
<Route
path="/profile/:id"
element={<Profile user={user} setUser={setUser} />}
/>
<Route path="/login" element={<Login setUser={setUser} />} />
<Route path="/register" element={<Register setUser={setUser} />} />
<Route path="/file/:id" element={<FileInfo />} />
</Routes>
</main>
<footer>
<AudioPlayer
playingFile={playingFile}
setPlayingFile={setPlayingFile}
/>
</footer>
</Router>
</div>
);
}
export default App;

8
web/src/App.test.js Normal file
View 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();
});

View 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(`search-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;

View 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";
}

View File

@@ -0,0 +1,33 @@
import { useEffect, useState } from "react";
import getFfmpegConfigListRespondExample from "../example-respond/get_ffmpeg_config_list.json"
function FfmpegConfig(props) {
// props.setSelectedFfmpegConfig
// props.selectedFfmpegConfig
const [ffmpegConfigList, setFfmpegConfigList] = useState([]);
useEffect(() => {
setFfmpegConfigList(getFfmpegConfigListRespondExample.ffmpeg_config_list);
props.setSelectedFfmpegConfig(getFfmpegConfigListRespondExample.ffmpeg_config_list[0]);
}, []);
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;

View File

@@ -0,0 +1,43 @@
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 using browser
<br />
Play on the web page
<br />
</p>
<button
onClick={() => {
props.setPlayingFile(props.file);
props.setShowStatus(false);
}}
>
Play
</button>
<button
onClick={() => {
navigate(`/file/${props.file.id}`);
}}
>
Info
</button>
<button onClick={() => props.setShowStatus(false)}>Close</button>
</dialog>
);
}
export default FileDialog;

View 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(`/folder/${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;

View File

@@ -0,0 +1,69 @@
import { useParams, Link, useNavigate } from "react-router-dom";
function FileInfo() {
let params = useParams();
let navigate = useNavigate();
return (
<div className="page">
<h3>File Information</h3>
<span>
<button>Download</button>
<button
onClick={() => {
navigate("/file/" + params.id + '/share');
}}
>
Share
</button>
<button
onClick={() => {
navigate("/file/" + params.id + '/review');
}}
>Review</button>
</span>
<table>
<thead>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>File Name</td>
<td>{params.id}</td>
</tr>
<tr>
<td>File Size</td>
<td>123456</td>
</tr>
<tr>
<td>File Type</td>
<td>media/aac</td>
</tr>
<tr>
<td>Last Modified</td>
<td>2020-01-01</td>
</tr>
<tr>
<td>Import by</td>
<td>
<Link to="/profile/3">@admin</Link>
</td>
</tr>
<tr>
<td>Import Date</td>
<td>2020-01-01</td>
</tr>
<tr>
<td>Location</td>
<td>/data/media/aac</td>
</tr>
</tbody>
</table>
<button>Update</button>
</div>
);
}
export default FileInfo;

View File

@@ -0,0 +1,15 @@
import FilesTable from "./FilesTable";
import searchFilesRespondExample from "../example-respond/search_files.json"
import {useParams} from "react-router";
function FilesInFolder(props) {
let params = useParams();
return (
<div>
<h3>Files in folder id {params.id}</h3>
<FilesTable setPlayingFile={props.setPlayingFile} files={searchFilesRespondExample.files} />
</div>
);
}
export default FilesInFolder;

View File

@@ -0,0 +1,26 @@
import FileEntry from "./FileEntry";
function FilesTable(props) {
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;

View File

@@ -0,0 +1,32 @@
import { useNavigate } from "react-router";
function FoldersTable(props) {
let navigate = useNavigate();
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(`/folder/${folder.id}`)}
className="clickable"
>
{folder.foldername}
</td>
<td onClick={() => navigate(`/folder/${folder.id}`)}>
<button>View</button>
</td>
</tr>
))}
</tbody>
</table>
);
}
export default FoldersTable;

View File

@@ -0,0 +1,28 @@
import { useEffect, useState } from "react";
import FilesTable from "./FilesTable";
import getRandomFilesRespondExample from "../example-respond/get_random_files.json"
function GetRandomFiles(props) {
const [files, setFiles] = useState([]);
const [isLoading, setIsLoading] = useState(false);
function refresh(setFiles) {
setFiles(getRandomFilesRespondExample.files);
}
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;

View File

@@ -0,0 +1,48 @@
import { useNavigate } from "react-router-dom";
import { useState } from "react";
function Login(props) {
let navigate = useNavigate();
let [username, setUsername] = useState("");
let [password, setPassword] = useState("");
return (
<div>
<h1>Login</h1>
<label htmlFor="username"></label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<span>
<button
onClick={() => {
if (!username || !password) {
alert("Please enter username and password");
return;
}
props.setUser({ id: 123, username: username, password: password });
navigate("/");
}}
>
Login
</button>
<button
onClick={() => {
navigate("/register");
}}
>Register</button>
</span>
</div>
);
}
export default Login;

104
web/src/component/Manage.js Normal file
View File

@@ -0,0 +1,104 @@
import getFfmpegConfigListRespondExample from "../example-respond/get_ffmpeg_config_list.json";
function Manage() {
return (
<div className="page">
<h2>Manage</h2>
<h3>Server status</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Server status</td>
<td>
<span className="status-ok">OK</span>
</td>
</tr>
<tr>
<td>Server uptime</td>
<td>
<span>1 day, 23 hours, 59 minutes and 59 seconds</span>
</td>
</tr>
<tr>
<td>Server load</td>
<td>
<span>0.00 / 0.00 / 0.00</span>
</td>
</tr>
<tr>
<td>Server memory usage</td>
<td>
<span>0.00 MB</span>
</td>
</tr>
<tr>
<td>Server disk usage</td>
<td>
<span>0.00 MB</span>
</td>
</tr>
<tr>
<td>Server uptime</td>
<td>
<span>1 day, 23 hours, 59 minutes and 59 seconds</span>
</td>
</tr>
<tr>
<td>Server load</td>
<td>
<span>0.00 / 0.00 / 0.00</span>
</td>
</tr>
<tr>
<td>Server memory usage</td>
<td>
<span>0.00 MB</span>
</td>
</tr>
<tr>
<td>Server disk usage</td>
<td>
<span>0.00 MB</span>
</td>
</tr>
</tbody>
</table>
<h3>Database opeartions</h3>
<ul>
<li>.mp3</li>
<li>.flac</li>
<li>.wav</li>
<li>.ogg</li>
<li>.aac</li>
<li>.m4a</li>
</ul>
<input type="text" placeholder=".mp3" />
<button>Add Pattern</button>
<input type="text" placeholder="/path/to/root" />
<button>Import</button>
<h3>Ffmpeg Settings</h3>
<ol>
{getFfmpegConfigListRespondExample.ffmpeg_config_list.map(
(item, index) => (
<li>
{item.name} {item.args}
</li>
)
)}
</ol>
<span>
<input type="text" placeholder="name" />
<input type="text" placeholder="args" />
<button>Add</button>
</span>
</div>
);
}
export default Manage;

View File

@@ -0,0 +1,37 @@
import { useParams, useNavigate } from "react-router-dom";
import ReviewEntry from "./ReviewEntry";
import SearchFiles from "./SearchFiles";
import getRandomFilesRespondExample from "../example-respond/get_random_files.json";
function Profile(props) {
let params = useParams();
let navigate = useNavigate();
return (
<div>
<h1>Profile of user {params.id}</h1>
{props.user && props.user.id === parseInt(params.id) && (
<button
onClick={() => {
props.setUser(null);
navigate("/");
}}
>
Logout
</button>
)}
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
doloremque, quidem quisquam, quisquam quisquam quisquam quisquam
dignissimos.
</p>
<h3>Reviews</h3>
<ReviewEntry />
<ReviewEntry />
<h3>Liked music</h3>
<SearchFiles folder={{}} />
</div>
);
}
export default Profile;

View File

@@ -0,0 +1,51 @@
import { useNavigate } from "react-router-dom";
import { useState } from "react";
function Register(props) {
let navigate = useNavigate();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [password2, setPassword2] = useState("");
return (
<div>
<h1>Register</h1>
<label htmlFor="username">Username:</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<label htmlFor="password2">Confirm Password:</label>
<input
type="password"
id="password2"
value={password2}
onChange={(e) => setPassword2(e.target.value)}
/>
<button
onClick={() => {
if (!username || !password || !password2) {
alert("Please fill out all fields");
} else if (password !== password2) {
alert("Passwords do not match");
} else {
props.setUser({ id: 39, username: username, password: password });
navigate("/");
}
}}
>
Register
</button>
</div>
);
}
export default Register;

View File

@@ -0,0 +1,35 @@
import { useParams } from "react-router";
import { Link } from "react-router-dom";
import ReviewEntry from "./ReviewEntry";
function Review() {
let params = useParams();
return (
<div className="page">
<h3>Review on music ID {params.id}</h3>
<textarea
className="review-text"
placeholder="Write your review here"
></textarea>
<span>
<button>Submit</button>
<button>Add to fav</button>
</span>
<details open>
<summary>Liked by</summary>
<p>
<Link to="/profile/1">@User 1</Link>&nbsp;
<Link to="/profile/2">@User 2</Link>&nbsp;
<Link to="/profile/3">@User 3</Link>&nbsp;
<Link to="/profile/4">@User 4</Link>&nbsp;
</p>
</details>
<ReviewEntry />
<ReviewEntry />
<ReviewEntry />
</div>
);
}
export default Review;

View File

@@ -0,0 +1,18 @@
import { Link} from "react-router-dom";
function ReviewEntry() {
return (
<p>
<h5>
<Link to="/profile/2">@rin</Link> comment music ID 39 at
2019-01-01 12:23:45
</h5>
Agree with <Link to="/profile/1">@hmsy</Link>. I also like how well the
musician plays the guitar. They are all very good. They really make the
song sound better. I like the way the bass plays and the way the guitar
sounds. I like the way the drums sound.
</p>
);
}
export default ReviewEntry;

View File

@@ -0,0 +1,68 @@
import { useState, useEffect } from "react";
import FilesTable from "./FilesTable";
import searchFilesRespondExample from "../example-respond/search_files.json"
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() {
setFiles(searchFilesRespondExample.files);
}
function nextPage() {
setOffset(offset + limit);
}
function lastPage() {
const offsetValue = offset - limit;
if (offsetValue < 0) {
return;
}
setOffset(offsetValue);
}
useEffect(() => searchFiles(), [offset, props.folder]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<div className="page">
<h3>Search Files</h3>
<div className="search_toolbar">
{!props.folder && (
<input
onChange={(event) => setFilename(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") {
searchFiles();
}
}}
type="text"
placeholder="Enter filename"
/>
)}
<button
disabled={!!props.folder}
onClick={() => {
searchFiles();
}}
>
{isLoading ? "Loading..." : "Search"}
</button>
{props.folder && props.folder.foldername && (
<button onClick={searchFiles}>{props.folder.foldername}</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;

View File

@@ -0,0 +1,72 @@
import { useEffect, useState } from "react";
import { useParams } from "react-router";
import FoldersTable from "./FoldersTable";
import SearchFiles from "./SearchFiles";
import searchFoldersRespondExample from "../example-respond/search_folders.json";
function SearchFolders(props) {
const [foldername, setFoldername] = useState("");
const [folders, setFolders] = useState([]);
const [folder, setFolder] = useState({});
const [offset, setOffset] = useState(0);
const [isLoading, setIsLoading] = useState(false);
const limit = 10;
function searchFolder() {
setFolders(searchFoldersRespondExample.folders);
}
function nextPage() {
setOffset(offset + limit);
}
function lastPage() {
const offsetValue = offset - limit;
if (offsetValue < 0) {
return;
}
setOffset(offsetValue);
}
function viewFolder(folder) {
setFolder(folder);
}
let params = useParams();
useEffect(() => searchFolder(), [offset]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (params.id !== undefined) {
setFolder({ id: parseInt(params.id) });
}
}, [params.id]);
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 viewFolder={viewFolder} folders={folders} />
<SearchFiles setPlayingFile={props.setPlayingFile} folder={folder} />
</div>
);
}
export default SearchFolders;

View File

@@ -0,0 +1,27 @@
import { useEffect, useState } from "react";
import { useParams } from "react-router";
import FilesTable from "./FilesTable";
import GetFileInfoRespondExample from "../example-respond/get_file_info.json";
function Share(props) {
let params = useParams();
const [file, setFile] = useState([]);
useEffect(() => {
setFile([GetFileInfoRespondExample]);
}, [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;

23
web/src/component/User.js Normal file
View File

@@ -0,0 +1,23 @@
import { useNavigate } from "react-router";
function User(props) {
// props.user
// props.setUser
let navigate = useNavigate();
return (
<div
className="avatar"
onClick={() => {
if (props.user) {
navigate("/profile/" + props.user.id);
} else {
navigate("/login");
}
}}
>
{props.user ? props.user.username : "Login"}
</div>
);
}
export default User;

View File

@@ -0,0 +1,12 @@
{
"ffmpeg_config_list": [
{ "name": "OPUS 128k", "args": "-c:a libopus -ab 128k" },
{ "name": "OPUS 96k", "args": "-c:a libopus -ab 96k" },
{ "name": "OPUS 256k", "args": "-c:a libopus -ab 256k" },
{ "name": "OPUS 320k", "args": "-c:a libopus -ab 320k" },
{ "name": "OPUS 512k", "args": "-c:a libopus -ab 512k" },
{ "name": "AAC 128k", "args": "-c:a aac -ab 128k" },
{ "name": "AAC 256k", "args": "-c:a aac -ab 256k" },
{ "name": "全损音质 32k", "args": "-c:a libopus -ab 32k" }
]
}

View File

@@ -0,0 +1,7 @@
{
"id": 9856,
"folder_id": 898,
"foldername": "[2021.05.12] TVアニメ「シャドーハウス」EDテーマ「ないない」ReoNa [スペシャルエディション] [FLAC 96kHz24bit]",
"filename": "03. 生きてるだけでえらいよ.flac",
"filesize": 122761032
}

View File

@@ -0,0 +1,74 @@
{
"files": [
{
"id": 9727,
"folder_id": 958,
"foldername": "garnet (narry) — emerald [GARN-0002] (flac)",
"filename": "06. narry — malachite.flac",
"filesize": 28228112
},
{
"id": 4785,
"folder_id": 457,
"foldername": "Winter (FLAC)",
"filename": "08 - 恋.flac",
"filesize": 33576086
},
{
"id": 13943,
"folder_id": 1368,
"foldername": "[mikudb] 融合YELLOWS",
"filename": "10. カレーライスのうた.mp3",
"filesize": 2524925
},
{
"id": 21743,
"folder_id": 2207,
"foldername": "Tsumanne(^o^)",
"filename": "08.スーパートルコ行進曲 - オワタ\(^o^).mp3",
"filesize": 7677985
},
{
"id": 35918,
"folder_id": 3758,
"foldername": "2008 - Higurashi 2 - Ano hi, Ano Basho, Subete ni ' Arigatou",
"filename": "06 - Thanks (Bashee Arenge Version).flac",
"filesize": 39545977
},
{
"id": 32394,
"folder_id": 3341,
"foldername": "[彩音 xi-on] Eyes",
"filename": "08 - 少女さとり ~ 3rd Eye.mp3",
"filesize": 7538525
},
{
"id": 16934,
"folder_id": 1671,
"foldername": "Explorism",
"filename": "14.Please, My Producer (feat. SAK).mp3",
"filesize": 6099717
},
{
"id": 1381,
"folder_id": 131,
"foldername": "Garakuta Live (FLAC)",
"filename": "(09) [しけもく] 愛染エピローグ.flac",
"filesize": 25173829
},
{
"id": 18066,
"folder_id": 1791,
"foldername": "Jailbreak from the Sunday Morning!!",
"filename": "05. Good bye!! Melancory Sunday Morning!!.mp3",
"filesize": 10197778
},
{
"id": 41261,
"folder_id": 4305,
"foldername": "[KSLA-0124~6] Modification of Key Sounds Label [CD-FLAC]",
"filename": "3-01. Trigger (MUZIK SERVANT vs Freezer Remix).flac",
"filesize": 42772516
}
]
}

View File

@@ -0,0 +1,25 @@
{
"files": [
{
"id": 26555,
"folder_id": 2579,
"foldername": "[mikudb] SEB presents SUPER HATSUNE BEAT Vol. 1",
"filename": "02. White Letter (ゆうゆP Euro Arrange).mp3",
"filesize": 4252006
},
{
"id": 40891,
"folder_id": 4121,
"foldername": "初音ミクベスト memories",
"filename": "10.White letter.mp3",
"filesize": 6723982
},
{
"id": 43289,
"folder_id": 4384,
"foldername": "Hatsune Miku Best ~memories~",
"filename": "10.White Letter.flac",
"filesize": 20817678
}
]
}

View File

@@ -0,0 +1,32 @@
{
"folders": [
{
"id": 2037,
"foldername": "P∴Rhythmatiq — 七色リミックス [OSLA-0005] (flac+scans)"
},
{
"id": 2130,
"foldername": " P∴Rhythmatiq — P∴Rhythmatiq act09 [PRTQ-0017] (flac+scans)"
},
{
"id": 2176,
"foldername": "P∴Rhythmatiq — P∴Rhythmatiq act02 [PRTQ-0002] (flac)"
},
{
"id": 2184,
"foldername": "P∴Rhythmatiq — P∴Rhythmatiq act04 [PRTQ-0005] (flac)"
},
{
"id": 2190,
"foldername": "P∴Rhythmatiq — P∴Rhythmatiq Rock!! [PQPC-0001] (flac)"
},
{
"id": 2360,
"foldername": "P∴Rhythmatiq — P∴Rhythmatiq act11 [PRTQ-0025] (flac)"
},
{ "id": 3443, "foldername": "P∴Rhythmatiq EXTRA" },
{ "id": 3444, "foldername": "P∴Rhythmatiq Hearts" },
{ "id": 3445, "foldername": "P∴Rhythmatiq Re act" },
{ "id": 3446, "foldername": "P∴Rhythmatiq Rock!!" }
]
}

13
web/src/index.css Normal file
View 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
View 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();

View 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
View 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';

View File

@@ -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;
}

View File

@@ -1,38 +0,0 @@
<html>
<body>
<h1>title</h1>
<audio id="player" autoplay controls></audio>
</body>
</html>
<script>
var video = document.getElementById("player")
var url = "/api/v1/get_file_stream?id=38508&config=0. OPUS 128k"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "arraybuffer";
xhr.onload = function (oEvent) {
var blob = new Blob([oEvent.target.response]);
video.src = URL.createObjectURL(blob);
//video.play() if you want it to play on load
};
xhr.onprogress = function (oEvent) {
console.log(oEvent.loaded)
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
// do something with this
console.log(percentComplete);
}
}
xhr.send();
</script>

File diff suppressed because one or more lines are too long

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff