Skip to content

Commit

Permalink
MusicFree 0.0.6
Browse files Browse the repository at this point in the history
Next version
maotoumao authored Dec 25, 2024
2 parents bafe820 + fbe7de6 commit 7c8bd0a
Showing 268 changed files with 10,730 additions and 11,088 deletions.
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -95,4 +95,8 @@ tmp

plugins

.VSCodeCounter
.VSCodeCounter

.idea/

undefinedelectron-log-preload.js
147 changes: 67 additions & 80 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007

Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

Preamble

The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
software for all its users.

When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
@@ -26,44 +24,34 @@ them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.

Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

The precise terms and conditions for copying, distribution and
modification follow.
@@ -72,7 +60,7 @@ modification follow.

0. Definitions.

"This License" refers to version 3 of the GNU General Public License.
"This License" refers to version 3 of the GNU Affero General Public License.

"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
@@ -549,35 +537,45 @@ to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

13. Use with the GNU Affero General Public License.
13. Remote Network Interaction; Use with the GNU General Public License.

Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

14. Revised Versions of this License.

The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

@@ -635,40 +633,29 @@ the "copyright" line and a pointer to where the full notice is found.
Copyright (C) <year> <name of author>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
GNU Affero General Public License for more details.

You should have received a copy of the GNU General Public License
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
21 changes: 10 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
# MusicFree 桌面版

## 本项目基于 GPL 3.0 协议开源,不禁止二次分发,但使用代码时请遵守如下规则:

1. 二次分发版必须同样遵循 GPL 3.0 协议,**开源且免费**
2. **合法合规使用代码,禁止用于商业用途; 修改后的软件造成的任何问题由使用此代码的开发者承担**
3. 打包、二次分发 **请保留代码出处**https://github.com/maotoumao/MusicFree
4. 如果使用此代码的开发者不同意以上三条,则视为 **二次分发版遵守 CC0 协议**
5. 如果开源协议变更,将在此 Github 仓库更新,不另行通知
## 项目使用约定:
本项目基于 AGPL 3.0 协议开源,使用此项目时请遵守开源协议。
除此外,希望你在使用代码时已经了解以下额外说明:

1. 打包、二次分发 **请保留代码出处**https://github.com/maotoumao/MusicFree
2. 请不要用于商业用途,合法合规使用代码;
3. 如果开源协议变更,将在此 Github 仓库更新,不另行通知。
---

## 简介
@@ -20,7 +19,7 @@

### 下载地址

[蓝奏云下载地址](https://wwzb.lanzoue.com/b042da1xe)
[飞书云文档](https://r0rvr854dd1.feishu.cn/drive/folder/IrVEfD67KlWZGkdqwjecLHFNnBb?from=from_copylink)

## 特性

@@ -30,15 +29,15 @@

- 定制化:本软件可以通过主题包定义软件外观及背景,详见下方主题包一节。

- 无广告:基于 GPL3.0 协议开源,将会保持免费。
- 无广告:基于 AGPL3.0 协议开源,将会保持免费。

- 隐私:软件所有数据存储在本地,本软件不会上传你的个人信息。

## 插件

插件协议和安卓版完全相同。

[示例插件仓库](https://github.com/maotoumao/MusicFreePlugins),你可以根据[插件开发文档](http://musicfree.upup.fun/docs/tutorial-plugin/intro/) 开发适配于任意音源的插件。
[示例插件仓库](https://github.com/maotoumao/MusicFreePlugins),你可以根据[插件开发文档](https://musicfree.catcat.work/plugin/introduction.html) 开发适配于任意音源的插件。

## 主题包

@@ -88,7 +87,7 @@ config.json 是一个配置文件。
"preview": "#000000", // 预览图,支持颜色或图片;
"description": "描述文本",
"iframes": {
"app": "http://musicfree.upup.fun", // 整个软件的背景
"app": "http://musicfree.catcat.work", // 整个软件的背景
"header": "", // 头部区域的背景
"body": "", // 侧边栏+主页面区域的背景
"side-bar": "", // 侧边栏区域的背景
11 changes: 11 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
`2024-12-25 v0.0.6`
1. 【优化】大量代码重构
2. 【功能】新增播放失败时不寻找其他音质版本的配置
3. 【功能】歌单内支持通过 ctrl 键盘多选歌曲批量操作
4. 【功能】支持自定义主窗口大小
5. 【功能】支持自定义歌词窗口大小
6. 【功能】调整播放详情页面的样式
7. 【功能】支持了评论功能(需要插件支持)
8. 【修复】修复了歌单id无法带特殊字符的问题
9. 【修复】修复了音源太多时布局异常的问题

`2024-06.25 v0.0.5`
【修复】修复重启软件后歌单丢失的问题;如果未出现上述问题可忽略此版本更新

2 changes: 1 addition & 1 deletion forge.config.ts
Original file line number Diff line number Diff line change
@@ -91,7 +91,7 @@ const config: ForgeConfig = {
js: "./src/webworkers/db-worker.ts",
name: "db",
nodeIntegration: true,
},
}
],
},
}),
31 changes: 21 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "musicfree-desktop",
"productName": "MusicFree",
"version": "0.0.5",
"version": "0.0.6",
"description": "一个插件化的音乐播放器",
"main": ".webpack/main",
"scripts": {
@@ -78,11 +78,12 @@
"cheerio": "^1.0.0-rc.12",
"chokidar": "^3.6.0",
"color": "^4.2.3",
"comlink": "^4.4.1",
"comlink": "^4.4.2",
"compare-versions": "^6.1.0",
"crypto-js": "^4.2.0",
"dayjs": "^1.11.11",
"dexie": "^3.2.4",
"electron-log": "^5.2.0",
"eventemitter3": "^5.0.1",
"he": "^1.2.0",
"hls.js": "^1.5.8",
@@ -91,7 +92,7 @@
"i18next": "^22.5.1",
"iconv-lite": "^0.6.3",
"immer": "^10.1.1",
"jschardet": "^3.1.2",
"jschardet": "^3.1.3",
"lodash.shuffle": "^4.2.0",
"lodash.throttle": "^4.1.1",
"lru-cache": "^10.2.2",
2 changes: 1 addition & 1 deletion release/build-windows.iss
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@
#define MyAppVersion "0.0.0-alpha.0"
#endif
#define MyAppPublisher "maotoumao"
#define MyAppURL "https://musicfree.upup.fun"
#define MyAppURL "https://musicfree.catcat.work"
#define MyAppExeName "MusicFree.exe"
#ifndef MyAppId
#define MyAppId
26 changes: 12 additions & 14 deletions release/version.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
{
"version": "0.0.5",
"version": "0.0.6",
"changeLog": [
"【修复】修复重启软件后歌单丢失的问题;如果未出现上述问题可忽略此版本更新",
"--- 以下为 0.0.4 更新 ---",
"1. 【功能】播放列表支持拖拽排序",
"2. 【功能】支持多语言。本次支持简体中文、繁体中文、英文、西班牙语",
"3. 【功能】支持歌词翻译功能(需要插件实现getLyric方法)",
"4. 【功能】新增最近播放,默认保存最近播放的 500 首歌",
"5. 【功能】新增小窗模式",
"6. 【功能】新增音频设备移除时的行为设置,现在可以让拔掉耳机的时候停止播放了",
"7. 【功能】新增单独的主题页,可以在主题市场中直接使用主题;本地.mftheme主题可以直接拖拽到播放器安装",
"8. 【优化】本地音乐会尝试读取本地路径下的同名 .lrc 文件作为歌词;同时会读取同名 -tr.lrc 文件作为翻译",
"9. 【修复】修复部分情况下本地歌词无法读取的问题",
"10. 【修复】修复 linux 托盘点击无效的问题"
"⚠ 此版本有大量代码重构,小伙伴们谨慎更新",
"1. 【优化】大量代码重构",
"2. 【功能】新增播放失败时不寻找其他音质版本的配置",
"3. 【功能】歌单内支持通过 ctrl 键盘多选歌曲批量操作",
"4. 【功能】支持自定义主窗口大小",
"5. 【功能】支持自定义歌词窗口大小",
"6. 【功能】调整播放详情页面的样式",
"7. 【功能】支持了评论功能(需要插件支持)",
"8. 【修复】修复了歌单id无法带特殊字符的问题",
"9. 【修复】修复了音源太多时布局异常的问题"
],
"download": ["https://www.123pan.com/s/grz2jv-CjmAA.html"]
"download": ["https://r0rvr854dd1.feishu.cn/drive/folder/IrVEfD67KlWZGkdqwjecLHFNnBb?from=from_copylink"]
}
105 changes: 105 additions & 0 deletions res/.service/request-forwarder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
const http = require("http");
const https = require("https");


const defaultPort = 52735;
const maxRetries = 20;

let retryCount = 0;

function forwardRequest(clientRes, url, method, headers) {
const options = {
method: method,
headers: headers,
};

const protocol = url.startsWith("https") ? https : http;

const req = protocol.request(url, options, (targetRes) => {
// 将目标响应的状态码和头部转发到客户端
clientRes.writeHead(targetRes.statusCode, targetRes.headers);

// 将目标响应的数据流转发到客户端
targetRes.pipe(clientRes, {
end: true,
});
});

req.on("error", (error) => {
console.error("Error forwarding request:", error);
clientRes.writeHead(500, {"Content-Type": "text/plain"});
clientRes.end("Internal Server Error");
});

// 结束目标请求
req.end();
}


function safeParse(data) {
try {
return JSON.parse(data) || {};
} catch (e) {
return {};
}
}


function startServer(port) {

// 创建一个 HTTP 服务器
const server = http.createServer((req, res) => {
if (req.method !== "GET") {
res.writeHead(405, {"Content-Type": "text/plain"});
return res.end("Only GET requests are allowed");
}

if (req.url === "/heartbeat") {
res.writeHead(200, {"Content-Type": "text/plain"});
return res.end("OK");
}

const query = new URLSearchParams(req.url.slice(1));


const url = query.get("url");
const method = query.get("method") || "GET"; // 默认使用 GET 方法
const headers = safeParse(query.get("headers"));

res.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有源
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); // 允许的方法

if (!url) {
res.writeHead(400, {"Content-Type": "text/plain"});
return res.end("Bad Request: Missing URL");
}

forwardRequest(res, url, method, {
...(req.headers || {}),
...(headers || {})
});
});

server.listen(port, () => {
process.send?.({
type: "port",
port
});
console.log(`Proxy server is running on http://localhost:${port}`);
});

server.on("error", (err) => {
console.error("Server error:", err);
if (retryCount < maxRetries) {
retryCount++;
const newPort = port + 1; // 尝试下一个端口
console.log(`Retrying on port: ${newPort} (attempt ${retryCount})`);
startServer(newPort);
} else {
process.send?.({type: "error", error: "Max retries reached"});
}
})
}


startServer(defaultPort);
7 changes: 5 additions & 2 deletions res/lang/en-US.json
Original file line number Diff line number Diff line change
@@ -45,6 +45,7 @@
"media_type_artist": "Artist",
"media_type_sheet": "Playlist",
"media_type_lyric": "Lyric",
"media_type_comment": "Comment",

"media_title": "Title",
"media_platform": "Source",
@@ -281,6 +282,7 @@
"when_quality_missing": "When playback quality is missing",
"play_lower_quality_version": "Play lower quality version",
"play_higher_quality_version": "Play higher quality version",
"play_skip_quality_version": "Do not look for other quality versions",
"when_play_error": "When playback error occurs",
"pause": "Pause",
"skip_to_next": "Automatically play next song",
@@ -325,7 +327,8 @@
"volume-down": "Volume Down",
"toggle-desktop-lyric": "Toggle Desktop Lyric",
"like/dislike": "Like/Dislike Current Song",
"no_short_cut": "None"
"no_short_cut": "None",
"toggle-main-window-visible": "Show/Hide Main Window"
},
"network": {
"host": "Host",
@@ -360,7 +363,7 @@
"already_latest": "Already up to date!",
"check_update": "Check for Update",
"software_author": "Software Author: ",
"open_source_declaration": "Source Code: Software is open-source under GPL3.0 license. <Github>Github Link</Github> <Gitee>Gitee Link</Gitee>",
"open_source_declaration": "Source Code: Software is open-source under AGPL3.0 license. <Github>Github Link</Github> <Gitee>Gitee Link</Gitee>",
"official_site": "Official Website",
"mobile_version": "Mobile Version"
}
395 changes: 0 additions & 395 deletions res/lang/es-ES.json

This file was deleted.

395 changes: 0 additions & 395 deletions res/lang/ru-RU.json

This file was deleted.

7 changes: 5 additions & 2 deletions res/lang/zh-CN.json
Original file line number Diff line number Diff line change
@@ -45,6 +45,7 @@
"media_type_artist": "作者",
"media_type_sheet": "歌单",
"media_type_lyric": "歌词",
"media_type_comment": "评论",

"media_title": "标题",
"media_platform": "来源",
@@ -281,6 +282,7 @@
"when_quality_missing": "播放音质缺失时",
"play_lower_quality_version": "播放更低音质",
"play_higher_quality_version": "播放更高音质",
"play_skip_quality_version": "不寻找其他音质版本",
"when_play_error": "播放失败时",
"pause": "暂停播放",
"skip_to_next": "自动播放下一首",
@@ -325,7 +327,8 @@
"volume-down": "降低音量",
"toggle-desktop-lyric": "打开/关闭桌面歌词",
"like/dislike": "喜欢/不喜欢当前歌曲",
"no_short_cut": ""
"no_short_cut": "",
"toggle-main-window-visible": "显示/隐藏主窗口"
},
"network": {
"host": "主机",
@@ -360,7 +363,7 @@
"already_latest": "当前已是最新版本!",
"check_update": "检查更新",
"software_author": "软件作者: ",
"open_source_declaration": "源代码: 软件基于 GPL3.0 协议开源. <Github>Github地址</Github> <Gitee>Gitee地址</Gitee>",
"open_source_declaration": "源代码: 软件基于 AGPL3.0 协议开源. <Github>Github地址</Github> <Gitee>Gitee地址</Gitee>",
"official_site": "软件官网",
"mobile_version": "移动版"
}
7 changes: 5 additions & 2 deletions res/lang/zh-TW.json
Original file line number Diff line number Diff line change
@@ -45,6 +45,7 @@
"media_type_artist": "藝術家",
"media_type_sheet": "歌單",
"media_type_lyric": "歌詞",
"media_type_comment": "評論",

"media_title": "標題",
"media_platform": "來源",
@@ -281,6 +282,7 @@
"when_quality_missing": "當播放音質缺失時",
"play_lower_quality_version": "播放低音質版本",
"play_higher_quality_version": "播放高音質版本",
"play_skip_quality_version": "不尋找其他音質版本",
"when_play_error": "播放錯誤時",
"pause": "暫停",
"skip_to_next": "跳至下一首",
@@ -325,7 +327,8 @@
"volume-down": "音量減少",
"toggle-desktop-lyric": "開啟/關閉桌面歌詞",
"like/dislike": "喜歡/不喜歡當前歌曲",
"no_short_cut": ""
"no_short_cut": "",
"toggle-main-window-visible": "顯示/隱藏主窗口"
},
"network": {
"host": "主機",
@@ -360,7 +363,7 @@
"already_latest": "已是最新版本!",
"check_update": "檢查更新",
"software_author": "軟件作者:",
"open_source_declaration": "源碼:軟件是基於 GPL3.0 授權的開源軟件。<Github>Github 地址</Github> <Gitee>Gitee 地址</Gitee>",
"open_source_declaration": "源碼:軟件是基於 AGPL3.0 授權的開源軟件。<Github>Github 地址</Github> <Gitee>Gitee 地址</Gitee>",
"official_site": "官方網站",
"mobile_version": "移動版"
}
Binary file modified res/logo.icns
Binary file not shown.
Binary file modified res/logo.ico
Binary file not shown.
Binary file modified res/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions src/assets/icons/chat-bubble-left-ellipsis.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions src/assets/icons/hand-thumb-up.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions src/assets/icons/square.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 3 additions & 2 deletions src/common/cache-fn.ts → src/common/async-memoize.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export function asyncCacheFn<R, T extends (...args: any[]) => Promise<R>>(callback: T): T{

export default function asyncMemoize<R, T extends (...args: any[]) => Promise<R>>(callback: T): T{
let val: R

return (async (...args: any[]) => {
@@ -8,4 +9,4 @@ export function asyncCacheFn<R, T extends (...args: any[]) => Promise<R>>(callba

return val;
}) as T;
}
}
216 changes: 135 additions & 81 deletions src/common/constant.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { IAppConfig } from "../shared/app-config/type";
import {IAppConfig} from "@/types/app-config";
import {ICommand} from "@shared/message-bus/type";

export const internalDataKey = "$";
export const internalDataSymbol = Symbol.for("internal");
@@ -18,120 +19,173 @@ export const localPluginName = "本地";
export const localPluginHash = "本地";

export const supportedMediaType = [
"music",
"album",
"artist",
"sheet",
"music",
"album",
"artist",
"sheet",
] as const;

export const rem = 13;

export enum RequestStateCode {
/** 空闲 */
IDLE = 0b00000000,
PENDING_FIRST_PAGE = 0b00000010,
LOADING = 0b00000010,
/** 检索中 */
PENDING_REST_PAGE = 0b00000011,
/** 部分结束 */
PARTLY_DONE = 0b00000100,
/** 全部结束 */
FINISHED = 0b0001000,
/** 出错了 */
ERROR = 0b10000000,
/** 空闲 */
IDLE = 0b00000000,
PENDING_FIRST_PAGE = 0b00000010,
LOADING = 0b00000010,
/** 检索中 */
PENDING_REST_PAGE = 0b00000011,
/** 部分结束 */
PARTLY_DONE = 0b00000100,
/** 全部结束 */
FINISHED = 0b0001000,
/** 出错了 */
ERROR = 0b10000000,
}

/** 音质列表 */
export const qualityKeys: IMusic.IQualityKey[] = [
"low",
"standard",
"high",
"super",
"low",
"standard",
"high",
"super",
];

export const supportLocalMediaType = [
".mp3",
".mp4",
".m4s",
".flac",
".wma",
".wav",
".m4a",
".ogg",
".acc",
".aac",
// ".ape",
".opus",
".mp3",
".mp4",
".m4s",
".flac",
".wma",
".wav",
".m4a",
".ogg",
".acc",
".aac",
// ".ape",
".opus",
];

export const toastDuration = {
short: 1000,
long: 2500,
short: 1000,
long: 2500,
};

export const defaultFont = {
fullName: "默认",
family: "",
postscriptName: "",
style: "",
fullName: "默认",
family: "",
postscriptName: "",
style: "",
};

type IShortCutKeys = keyof IAppConfig["shortCut"]["shortcuts"];
type IShortCutKeys = keyof IAppConfig["shortCut.shortcuts"];
export const shortCutKeys: IShortCutKeys[] = [
"play/pause",
"skip-next",
"skip-previous",
"volume-up",
"volume-down",
"toggle-desktop-lyric",
"like/dislike",
"play/pause",
"skip-next",
"skip-previous",
"volume-up",
"volume-down",
"toggle-desktop-lyric",
"like/dislike",
"toggle-main-window-visible"
];

// 快捷键列表对应的事件
export const shortCutKeysEvts: Record<IShortCutKeys, keyof IEventType.IEvents> =
{
"play/pause": "TOGGLE_PLAYER_STATE",
"skip-next": "SKIP_NEXT",
"skip-previous": "SKIP_PREVIOUS",
"volume-down": "VOLUME_DOWN",
"volume-up": "VOLUME_UP",
"toggle-desktop-lyric": "TOGGLE_DESKTOP_LYRIC",
"like/dislike": "TOGGLE_LIKE",
};
// 快捷键列表对应的指令
export const shortCutKeysCommands: Record<IShortCutKeys, keyof ICommand> =
{
"play/pause": "TogglePlayerState",
"skip-next": "SkipToNext",
"skip-previous": "SkipToPrevious",
"volume-down": "VolumeDown",
"volume-up": "VolumeUp",
"toggle-desktop-lyric": "ToggleDesktopLyric",
"like/dislike": "ToggleFavorite",
"toggle-main-window-visible": "ToggleMainWindowVisible"
};

// 主进程的Resource
export enum ResourceName {
SKIP_LEFT_ICON = "skip-left.png",
SKIP_RIGHT_ICON = "skip-right.png",
PAUSE_ICON = "pause.png",
PLAY_ICON = "play.png",
DEFAULT_ALBUM_COVER_IMAGE = "album-cover.jpeg",
LOGO_IMAGE = "logo.png"

}

/** 下载状态 */
export enum DownloadState {
/** 空闲状态 */
NONE = "NONE",
/** 排队等待中 */
WAITING = "WAITING",
/** 下载中 */
DOWNLOADING = "DOWNLOADING",
/** 失败 */
ERROR = "ERROR",
/** 下载完成 */
DONE = "DONE",
/** 空闲状态 */
NONE = "NONE",
/** 排队等待中 */
WAITING = "WAITING",
/** 下载中 */
DOWNLOADING = "DOWNLOADING",
/** 失败 */
ERROR = "ERROR",
/** 下载完成 */
DONE = "DONE",
}

// 主题更新链接
export const themePackStoreBaseUrl = [
"https://raw.githubusercontent.com/maotoumao/MusicFreeThemePacks/master/", //github
"https://cdn.jsdelivr.net/gh/maotoumao/MusicFreeThemePacks@master/",
"https://gitee.com/maotoumao/MusicFreeThemePacks/raw/master/", // gitee
"https://raw.githubusercontent.com/maotoumao/MusicFreeThemePacks/master/", //github
"https://cdn.jsdelivr.net/gh/maotoumao/MusicFreeThemePacks@master/",
"https://dev.azure.com/maotoumao/MusicFree/_apis/git/repositories/MusicFreeThemePacks/items?scopePath=/.publish/publish.json&api-version=6.0", // azure
];

export const appUpdateSources = [
"https://gitee.com/maotoumao/MusicFreeDesktop/raw/master/release/version.json",
"https://raw.githubusercontent.com/maotoumao/MusicFreeDesktop/master/release/version.json",
"https://cdn.jsdelivr.net/gh/maotoumao/MusicFreeDesktop@master/release/version.json",
"https://gitee.com/maotoumao/MusicFreeDesktop/raw/master/release/version.json",
"https://raw.githubusercontent.com/maotoumao/MusicFreeDesktop/master/release/version.json",
"https://cdn.jsdelivr.net/gh/maotoumao/MusicFreeDesktop@master/release/version.json",
];

export enum TrackPlayerSyncType {
SyncPlayerState = "SyncPlayerState",
MusicChanged = "MusicChanged",
PlayerStateChanged = "PlayerStateChanged",
RepeatModeChanged = "RepeatModeChanged",
LyricChanged = "LyricChanged",
CurrentLyricChanged = "CurrentLyricChanged",
ProgressChanged = "ProgressChanged",
SyncPlayerState = "SyncPlayerState",
MusicChanged = "MusicChanged",
PlayerStateChanged = "PlayerStateChanged",
RepeatModeChanged = "RepeatModeChanged",
LyricChanged = "LyricChanged",
CurrentLyricChanged = "CurrentLyricChanged",
ProgressChanged = "ProgressChanged",
}

/** 播放器状态 */
export enum PlayerState {
/** 无音频 */
None,
/** 播放中 */
Playing,
/** 暂停 */
Paused,
/** 缓冲中 */
Buffering,
}

/** 播放模式 */
export enum RepeatMode {
/** 随机 */
Shuffle = "shuffle",
/** 播放队列 */
Queue = "queue-repeat",
/** 单曲循环 */
Loop = "loop",
}


/** 窗口类型 */
export enum WindowType {
MAIN = "MAIN",
LYRIC = "LYRIC",
MINIMODE = "MINIMODE",
}

export enum WindowRole {
MAIN = "MAIN",
SLAVE = "SLAVE",
}

export const CommonConst = {
/** 新建歌单名称长度限制 */
NEW_SHEET_NAME_LENGTH_LIMIT: 120,
}
9 changes: 9 additions & 0 deletions src/common/index-map.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export interface IIndexMap {
indexOf: (mediaItem?: IMedia.IMediaBase | null) => number;
has: (mediaItem?: IMedia.IMediaBase | null) => boolean;
update: (mediaItems?: IMedia.IMediaBase[]) => void;
}

@@ -31,8 +32,16 @@ export function createIndexMap(mediaItems?: IMedia.IMediaBase[]): IIndexMap {
return indexMap.get(mediaItem?.platform)?.get(mediaItem?.id) ?? -1;
}

function has(mediaItem?: IMedia.IMediaBase | null) {
if (!mediaItem) {
return false;
}
return indexMap.get(mediaItem?.platform)?.has(mediaItem?.id)?? false;
}

return {
update,
indexOf,
has
};
}
11 changes: 11 additions & 0 deletions src/common/main/get-resource-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { app } from "electron";
import path from "path";

const resPath = app.isPackaged
? path.resolve(process.resourcesPath, "res")
: path.resolve(__dirname, "../../res");

export default (resourceName: string) => {
return path.resolve(resPath, resourceName);
};

140 changes: 140 additions & 0 deletions src/common/main/thumb-bar-util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import {BrowserWindow, nativeImage} from "electron";
import getResourcePath from "@/common/main/get-resource-path";
import {t} from "@shared/i18n/main";
import {ResourceName} from "@/common/constant";
import asyncMemoize from "@/common/async-memoize";
import fs from "fs/promises";
import logger from "@shared/logger/main";
import axios from "axios";
import messageBus from "@shared/message-bus/main";

/**
* 设置缩略图按钮
* @param window 当前窗口
* @param isPlaying 当前是否正在播放音乐
*/
function setThumbBarButtons(window: BrowserWindow, isPlaying?: boolean) {
if (!window) {
return;
}

window.setThumbarButtons([
{
icon: nativeImage.createFromPath(getResourcePath(ResourceName.SKIP_LEFT_ICON)),
tooltip: t("main.previous_music"),
click() {
messageBus.sendCommand("SkipToPrevious");
},
},
{
icon: nativeImage.createFromPath(
getResourcePath(isPlaying ? ResourceName.PAUSE_ICON : ResourceName.PLAY_ICON)
),
tooltip: isPlaying
? t("media.music_state_pause")
: t("media.music_state_play"),
click() {
messageBus.sendCommand(
"TogglePlayerState"
);
},
},
{
icon: nativeImage.createFromPath(getResourcePath(ResourceName.SKIP_RIGHT_ICON)),
tooltip: t("main.next_music"),
click() {
messageBus.sendCommand("SkipToNext");
},
},
]);

}


// 获取默认的图片
const getDefaultAlbumCoverImage = asyncMemoize(async () => {
return await fs.readFile((getResourcePath(ResourceName.DEFAULT_ALBUM_COVER_IMAGE)));
})

let hookedFlag = false;

/**
* 设置缩略图
* @param window 窗口
* @param src 图片url
*/
async function setThumbImage(window: BrowserWindow, src: string) {
if (!window) {
return;
}

// only support windows
if (process.platform !== "win32") {
return;
}

try {
const hwnd = window.getNativeWindowHandle().readBigUInt64LE(0);

const taskBarThumbManager = (await import("@native/TaskbarThumbnailManager/TaskbarThumbnailManager.node")).default;

if (!hookedFlag) {
taskBarThumbManager.config(hwnd);
hookedFlag = true;
}

let buffer: Buffer;
if (!src) {
buffer = await getDefaultAlbumCoverImage();
} else if (src.startsWith("http")) {
try {
buffer = (
await axios.get(src, {
responseType: "arraybuffer",
})
).data;
} catch {
buffer = await getDefaultAlbumCoverImage();
}
} else if (src.startsWith("data:image")) {
buffer = Buffer.from(src.split(";base64,").pop(), "base64");
} else {
buffer = await getDefaultAlbumCoverImage();
}

const size = 106;

const sharp = (await import("sharp")).default;
const result = await sharp(buffer)
.resize(size, size, {
fit: "cover",
})
.png()
.ensureAlpha(1)
.raw()
.toBuffer({
resolveWithObject: true,
});

taskBarThumbManager.sendIconicRepresentation(
hwnd,
{
width: size,
height: size,
},
result.data
);
} catch (ex) {
logger.logError("Fail to setThumbImage", ex);
}


}


const ThumbBarManager = {
setThumbBarButtons,
setThumbImage
};

export default ThumbBarManager;
12 changes: 11 additions & 1 deletion src/common/media-util.ts
Original file line number Diff line number Diff line change
@@ -65,10 +65,16 @@ export function addSortProperty(
const now = Date.now();
if (Array.isArray(mediaItems)) {
mediaItems.forEach((item, index) => {
if (!item) {
return;
}
item[timeStampSymbol] = now;
item[sortIndexSymbol] = index;
});
} else {
if (!mediaItems) {
return;
}
mediaItems[timeStampSymbol] = now;
mediaItems[sortIndexSymbol] = 0;
}
@@ -111,8 +117,12 @@ export function removeInternalProperties<T extends IMedia.IMediaBase>(
*/
export function getQualityOrder(
qualityKey: IMusic.IQualityKey,
sort: "higher" | "lower"
sort: "higher" | "lower" | "skip"
) {
if (sort === "skip") {
return [qualityKey];
}

const idx = qualityKeys.indexOf(qualityKey);
const left = qualityKeys.slice(0, idx);
const right = qualityKeys.slice(idx + 1);
2 changes: 2 additions & 0 deletions src/common/void-callback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// eslint-disable-next-line @typescript-eslint/no-empty-function
export default () => {};
25 changes: 25 additions & 0 deletions src/hooks/useAppConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import AppConfig from "@shared/app-config/renderer";
import {IAppConfig} from "@/types/app-config";
import {useEffect, useState} from "react";


export default function useAppConfig<K extends keyof IAppConfig>(configKey: K): IAppConfig[K] {
const [state, setState] = useState<IAppConfig[K]>(AppConfig.getConfig(configKey));

useEffect(() => {
const callback = (patch: IAppConfig, fullConfig: IAppConfig) => {
if (configKey in patch) {
setState(fullConfig[configKey]);
}
};

AppConfig.onConfigUpdate(callback);

return () => {
AppConfig.offConfigUpdate(callback);
};
}, []);


return state;
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ interface IVirtualListProps<T> {
/** 滚动容器的query */
scrollElementQuery?: string;
/** 元素高度和列表高度 */
estimizeItemHeight: number;
estimateItemHeight: number;

/** 数据 */
data: T[];
@@ -36,7 +36,7 @@ interface IVirtualItem<T> {

export default function useVirtualList<T>(props: IVirtualListProps<T>) {
const {
estimizeItemHeight,
estimateItemHeight,
data,
renderCount = 40,
fallbackRenderCount = -1,
@@ -49,7 +49,7 @@ export default function useVirtualList<T>(props: IVirtualListProps<T>) {

const [virtualItems, setVirtualItems] = useState<IVirtualItem<T>[]>([]);
const [totalHeight, setTotalHeight] = useState<number>(
data.length * estimizeItemHeight
data.length * estimateItemHeight
);

const scrollElementRef = useRef<HTMLElement>();
@@ -61,7 +61,7 @@ export default function useVirtualList<T>(props: IVirtualListProps<T>) {
(scrollElementRef.current?.scrollTop ?? 0) -
(typeof offsetHeight === "number" ? offsetHeight : offsetHeight());
const realData = dataRef.current;
const estimizeStartIndex = Math.floor(scrollTop / estimizeItemHeight);
const estimizeStartIndex = Math.floor(scrollTop / estimateItemHeight);
const startIndex = Math.max(
estimizeStartIndex - (estimizeStartIndex % 2 === 1 ? 3 : 2),
0
@@ -81,7 +81,7 @@ export default function useVirtualList<T>(props: IVirtualListProps<T>) {
.map((item, index) => ({
rowIndex: startIndex + index,
dataItem: item,
top: (startIndex + index) * estimizeItemHeight,
top: (startIndex + index) * estimateItemHeight,
}))
);
},
@@ -95,7 +95,7 @@ export default function useVirtualList<T>(props: IVirtualListProps<T>) {
);

useEffect(() => {
setTotalHeight(data.length * estimizeItemHeight);
setTotalHeight(data.length * estimateItemHeight);
scrollHandler();
}, [data]);

@@ -128,7 +128,7 @@ export default function useVirtualList<T>(props: IVirtualListProps<T>) {
scrollElementRef.current.scrollTo({
top:
(typeof offsetHeight === "number" ? offsetHeight : offsetHeight()) +
estimizeItemHeight * index,
estimateItemHeight * index,
behavior,
});
}
60 changes: 0 additions & 60 deletions src/main/core/global-short-cut/index.ts

This file was deleted.

282 changes: 0 additions & 282 deletions src/main/core/plugin-manager/index.ts

This file was deleted.

31 changes: 0 additions & 31 deletions src/main/core/plugin-manager/local-plugin.ts

This file was deleted.

184 changes: 0 additions & 184 deletions src/main/core/plugin-manager/plugin.ts

This file was deleted.

49 changes: 49 additions & 0 deletions src/main/deep-link/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import {supportLocalMediaType} from "@/common/constant";
import {parseLocalMusicItem, safeStat} from "@/common/file-util";
import PluginManager from "@shared/plugin-manager/main";
import voidCallback from "@/common/void-callback";
import messageBus from "@shared/message-bus/main";

export function handleDeepLink(url: string) {
if (!url) {
return;
}

try {
const urlObj = new URL(url);
if (urlObj.protocol === "musicfree:") {
handleMusicFreeScheme(urlObj);
}
} catch {
// pass
}
}

async function handleMusicFreeScheme(url: URL) {
const hostname = url.hostname;
if (hostname === "install") {
try {
const pluginUrlStr =
url.pathname.slice(1) || url.searchParams.get("plugin");
const pluginUrls = pluginUrlStr.split(",").map(decodeURIComponent);
await Promise.all(
pluginUrls.map((it) => PluginManager.installPluginFromRemoteUrl(it).catch(voidCallback))
);
} catch {
// pass
}
}
}

async function handleBareUrl(url: string) {
try {
if (
(await safeStat(url)).isFile() &&
supportLocalMediaType.some((postfix) => url.endsWith(postfix))
) {
const musicItem = await parseLocalMusicItem(url);
messageBus.sendCommand("PlayMusic", musicItem);
}
} catch {
}
}
348 changes: 231 additions & 117 deletions src/main/index.ts
Original file line number Diff line number Diff line change
@@ -1,165 +1,279 @@
import { app, BrowserWindow, globalShortcut } from "electron";
import {
createLyricWindow,
createMainWindow,
getLyricWindow,
getMainWindow,
showMainWindow,
} from "./window";
import setupIpcMain, { handleProxy } from "./ipc";
import { setupPluginManager } from "./core/plugin-manager";
import { setupTray, setupTrayMenu } from "./tray";
import { setupGlobalShortCut } from "./core/global-short-cut";
import {app, BrowserWindow, globalShortcut} from "electron";
import fs from "fs";
import path from "path";
import { setAutoFreeze } from "immer";
import setThumbbarBtns from "./utils/set-thumbbar-btns";
import { currentMusicInfoStore } from "./store/current-music";
// TODO: Main process should not depends on files in renderer process
import { PlayerState } from "@/renderer/core/track-player/enum";

import {
getAppConfigPath,
getAppConfigPathSync,
setAppConfigPath,
setupMainAppConfig,
} from "@/shared/app-config/main";
import { setupGlobalContext } from "@/shared/global-context/main";
import { setupI18n } from "@/shared/i18n/main";
import {
createMiniModeWindow,
getMinimodeWindow,
showMinimodeWindow,
} from "./window/minimode-window";
import { handleDeepLink } from "./utils/deep-link";

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
// if (require("electron-squirrel-startup")) {
// app.quit();
// }
import {setAutoFreeze} from "immer";
import {setupGlobalContext} from "@/shared/global-context/main";
import {setupI18n} from "@/shared/i18n/main";
import {handleDeepLink} from "./deep-link";
import logger from "@shared/logger/main";
import {PlayerState} from "@/common/constant";
import ThumbBarUtil from "@/common/main/thumb-bar-util";
import windowManager from "@main/window-manager";
import AppConfig from "@shared/app-config/main";
import TrayManager from "@main/tray-manager";
import WindowDrag from "@shared/window-drag/main";
import {IAppConfig} from "@/types/app-config";
import axios from "axios";
import {HttpsProxyAgent} from "https-proxy-agent";
import PluginManager from "@shared/plugin-manager/main";
import ServiceManager from "@shared/service-manager/main";
import utils from "@shared/utils/main";
import messageBus from "@shared/message-bus/main";
import shortCut from "@shared/short-cut/main";
import voidCallback from "@/common/void-callback";

// portable
if (process.platform === "win32") {
try {
const appPath = app.getPath("exe");
const portablePath = path.resolve(appPath, "../portable");
const portableFolderStat = fs.statSync(portablePath);
if (portableFolderStat.isDirectory()) {
const appPathNames = ["appData", "userData"];
appPathNames.forEach((it) => {
app.setPath(it, path.resolve(portablePath, it));
});
try {
const appPath = app.getPath("exe");
const portablePath = path.resolve(appPath, "../portable");
const portableFolderStat = fs.statSync(portablePath);
if (portableFolderStat.isDirectory()) {
const appPathNames = ["appData", "userData"];
appPathNames.forEach((it) => {
app.setPath(it, path.resolve(portablePath, it));
});
}
} catch (e) {
// pass
}
} catch (e) {
// console.log(e)
}
}

setAutoFreeze(false);


if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient("musicfree", process.execPath, [
path.resolve(process.argv[1]),
]);
}
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient("musicfree", process.execPath, [
path.resolve(process.argv[1]),
]);
}
} else {
app.setAsDefaultProtocolClient("musicfree");
app.setAsDefaultProtocolClient("musicfree");
}

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
if (process.platform !== "darwin") {
app.quit();
}
});

app.on("activate", () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createMainWindow();
}
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
windowManager.showMainWindow();
}
});

if (!app.requestSingleInstanceLock()) {
app.exit(0);
app.exit(0);
}

app.on("second-instance", (_evt, commandLine) => {
if (getMainWindow()) {
showMainWindow();
}
if (windowManager.mainWindow) {
windowManager.showMainWindow();
}

if (process.platform !== "darwin") {
handleDeepLink(commandLine.pop());
}
if (process.platform !== "darwin") {
handleDeepLink(commandLine.pop());
}
});

app.on("open-url", (_evt, url) => {
handleDeepLink(url);
handleDeepLink(url);
});

app.on("will-quit", () => {
globalShortcut.unregisterAll();
globalShortcut.unregisterAll();
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
app.whenReady().then(async () => {
await Promise.allSettled([setupGlobalContext(), setupMainAppConfig()]);
setupI18n({
getDefaultLang() {
return getAppConfigPathSync("normal.language");
},
onLanguageChanged(lang) {
setAppConfigPath("normal.language", lang);
setupTrayMenu();
if (process.platform === "win32") {
setThumbbarBtns(
currentMusicInfoStore.getValue().currentPlayerState ===
PlayerState.Playing
);
}
},
});
setupIpcMain();
setupPluginManager();
setupTray();
bootstrap();
setupGlobalShortCut();
createMainWindow();
logger.logPerf("App Ready");
setupGlobalContext();
await AppConfig.setup(windowManager);

await setupI18n({
getDefaultLang() {
return AppConfig.getConfig("normal.language");
},
onLanguageChanged(lang) {
AppConfig.setConfig({
"normal.language": lang
});
if (process.platform === "win32") {

ThumbBarUtil.setThumbBarButtons(windowManager.mainWindow, messageBus.getAppState().playerState === PlayerState.Playing)
}
},
});
utils.setup(windowManager);
PluginManager.setup(windowManager);
TrayManager.setup(windowManager);
WindowDrag.setup();
shortCut.setup().then(voidCallback);
logger.logPerf("Create Main Window");
// Setup message bus & app state
messageBus.onAppStateChange((_, patch) => {
if ("musicItem" in patch) {
TrayManager.buildTrayMenu();
const musicItem = patch.musicItem;
const mainWindow = windowManager.mainWindow;

if (mainWindow) {
const thumbStyle = AppConfig.getConfig("normal.taskbarThumb");
if (process.platform === "win32" && thumbStyle === "artwork") {
ThumbBarUtil.setThumbImage(mainWindow, musicItem?.artwork);
}
if (musicItem) {
mainWindow.setTitle(
musicItem.title + (musicItem.artist ? ` - ${musicItem.artist}` : "")
);
} else {
mainWindow.setTitle(app.name);
}
}
} else if ("playerState" in patch) {
TrayManager.buildTrayMenu();
const playerState = patch.playerState;

if (process.platform === "win32") {
ThumbBarUtil.setThumbBarButtons(windowManager.mainWindow, playerState === PlayerState.Playing)
}
} else if ("repeatMode" in patch) {
TrayManager.buildTrayMenu();
} else if ("lyricText" in patch && process.platform === "darwin") {
if (AppConfig.getConfig("lyric.enableStatusBarLyric")) {
TrayManager.setTitle(patch.lyricText);
} else {
TrayManager.setTitle("");
}
}
})

messageBus.setup(windowManager);

windowManager.showMainWindow();

bootstrap();

});

async function bootstrap() {
const downloadPath = await getAppConfigPath("download.path");
if (!downloadPath) {
setAppConfigPath("download.path", app.getPath("downloads"));
}

/** 一些初始化设置 */
// 初始化桌面歌词
getAppConfigPath("lyric.enableDesktopLyric").then((result) => {
if (result) {
if (!getLyricWindow()) {
createLyricWindow();
}
ServiceManager.setup(windowManager);

const downloadPath = AppConfig.getConfig("download.path");
if (!downloadPath) {
AppConfig.setConfig({
"download.path": app.getPath("downloads")
});
}
});

getAppConfigPath("private.minimode").then((enabled) => {
if (enabled) {
if (!getMinimodeWindow()) {
showMinimodeWindow();
}
const minimodeEnabled = AppConfig.getConfig("private.minimode");

if (minimodeEnabled) {
windowManager.showMiniModeWindow();
}
});

getAppConfigPath("network.proxy").then((result) => {
if (result) {
handleProxy(result);
/** 一些初始化设置 */
// 初始化桌面歌词
const desktopLyricEnabled = AppConfig.getConfig("lyric.enableDesktopLyric");

if (desktopLyricEnabled) {
windowManager.showLyricWindow();
}

AppConfig.onConfigUpdated((patch) => {
// 桌面歌词锁定状态
if ("lyric.lockLyric" in patch) {
const lyricWindow = windowManager.lyricWindow;
const lockState = patch["lyric.lockLyric"];

if (!lyricWindow) {
return;
}
if (lockState) {
lyricWindow.setIgnoreMouseEvents(true, {
forward: true,
});
} else {
lyricWindow.setIgnoreMouseEvents(false);
}
}
if ("shortCut.enableGlobal" in patch) {
const enableGlobal = patch["shortCut.enableGlobal"];
if (enableGlobal) {
shortCut.registerAllGlobalShortCuts();
} else {
shortCut.unregisterAllGlobalShortCuts();
}
}
})


// 初始化代理
const proxyConfigKeys: Array<keyof IAppConfig> = [
"network.proxy.enabled",
"network.proxy.host",
"network.proxy.port",
"network.proxy.username",
"network.proxy.password"
];

AppConfig.onConfigUpdated((patch, config) => {
let proxyUpdated = false;
for (const proxyConfigKey of proxyConfigKeys) {
if (proxyConfigKey in patch) {
proxyUpdated = true;
break;
}
}

if (proxyUpdated) {
if (config["network.proxy.enabled"]) {
handleProxy(true, config["network.proxy.host"], config["network.proxy.port"], config["network.proxy.username"], config["network.proxy.password"]);
} else {
handleProxy(false);
}
}
});

handleProxy(
AppConfig.getConfig("network.proxy.enabled"),
AppConfig.getConfig("network.proxy.host"),
AppConfig.getConfig("network.proxy.port"),
AppConfig.getConfig("network.proxy.username"),
AppConfig.getConfig("network.proxy.password")
);


}


function handleProxy(enabled: boolean, host?: string | null, port?: string | null, username?: string | null, password?: string | null) {
try {
if (!enabled) {
axios.defaults.httpAgent = undefined;
axios.defaults.httpsAgent = undefined;
} else if (host) {
const proxyUrl = new URL(host);
proxyUrl.port = port;
proxyUrl.username = username;
proxyUrl.password = password;
const agent = new HttpsProxyAgent(proxyUrl);

axios.defaults.httpAgent = agent;
axios.defaults.httpsAgent = agent;
} else {
throw new Error("Unknown Host");
}
} catch (e) {
axios.defaults.httpAgent = undefined;
axios.defaults.httpsAgent = undefined;
}
});
}
288 changes: 0 additions & 288 deletions src/main/ipc/index.ts

This file was deleted.

12 changes: 0 additions & 12 deletions src/main/store/current-music.ts

This file was deleted.

288 changes: 288 additions & 0 deletions src/main/tray-manager/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,288 @@
import {app, Menu, MenuItem, MenuItemConstructorOptions, nativeImage, Tray} from "electron";
import {t} from "@shared/i18n/main";
import {IWindowManager} from "@/types/main/window-manager";
import getResourcePath from "@/common/main/get-resource-path";
import {PlayerState, RepeatMode, ResourceName} from "@/common/constant";
import AppConfig from "@shared/app-config/main";
import windowManager from "@main/window-manager";
import {IAppConfig} from "@/types/app-config";
import messageBus from "@shared/message-bus/main";

if (process.platform === "darwin") {
Menu.setApplicationMenu(
Menu.buildFromTemplate([
{
label: app.getName(),
submenu: [
{
label: t("common.about"),
role: "about",
},
{
label: t("common.exit"),
click() {
app.quit();
},
},
],
},
{
label: t("common.edit"),
submenu: [
{
label: t("common.undo"),
accelerator: "Command+Z",
role: "undo",
},
{
label: t("common.redo"),
accelerator: "Shift+Command+Z",
role: "redo",
},
{type: "separator"},
{label: t("common.cut"), accelerator: "Command+X", role: "cut"},
{label: t("common.copy"), accelerator: "Command+C", role: "copy"},
{label: t("common.cut"), accelerator: "Command+V", role: "paste"},
{type: "separator"},
{
label: t("common.select_all"),
accelerator: "Command+A",
role: "selectAll",
},
],
},
])
);
} else {
Menu.setApplicationMenu(null);
}

class TrayManager {
private static trayInstance: Tray | null = null;
private windowManager: IWindowManager;

private observedKey: Array<keyof IAppConfig> = [
"lyric.lockLyric",
"lyric.enableDesktopLyric",
"normal.language"
]

public setup(windowManager: IWindowManager) {
this.windowManager = windowManager;
const tray = new Tray(
nativeImage.createFromPath(getResourcePath(ResourceName.LOGO_IMAGE)).resize({
width: 32,
height: 32,
})
);

if (process.platform === "linux") {
tray.on("click", () => {
windowManager.showMainWindow();
});
} else {
tray.on("double-click", () => {
windowManager.showMainWindow();
});
}

// 配置变化时更新菜单
AppConfig.onConfigUpdated((changedConfig) => {
for (const k of this.observedKey) {
if (k in changedConfig) {
this.buildTrayMenu();
return;
}
}
})

TrayManager.trayInstance = tray;
this.buildTrayMenu();
}

private openMusicDetail() {
this.windowManager.showMainWindow();
messageBus.sendCommand("OpenMusicDetailPage");
}

public async buildTrayMenu() {
if (!TrayManager.trayInstance) {
return;
}
const ctxMenu: Array<MenuItemConstructorOptions | MenuItem> = [];

const tray = TrayManager.trayInstance;

/********* 音乐信息 **********/
const {musicItem, playerState, repeatMode} =
messageBus.getAppState();
// 更新一下tooltip
if (musicItem) {
tray.setToolTip(
`${musicItem.title ?? t("media.unknown_title")}${
musicItem.artist ? ` - ${musicItem.artist}` : ""
}`
);
} else {
tray.setToolTip("MusicFree");
}
if (musicItem) {
const fullName = `${musicItem.title ?? t("media.unknown_title")}${
musicItem.artist ? ` - ${musicItem.artist}` : ""
}`;
ctxMenu.push(
{
label: fullName.length > 12 ? fullName.slice(0, 12) + "..." : fullName,
click: this.openMusicDetail.bind(this),
},
{
label: `${t("media.media_platform")}: ${musicItem.platform}`,
click: this.openMusicDetail.bind(this),
}
);
} else {
ctxMenu.push({
label: t("main.no_playing_music"),
enabled: false,
});
}

ctxMenu.push(
{
label: musicItem
? playerState === PlayerState.Playing
? t("media.music_state_pause")
: t("media.music_state_play")
: t("media.music_state_play_or_pause"),
enabled: !!musicItem,
click() {
if (!musicItem) {
return;
}
messageBus.sendCommand("TogglePlayerState");
},
},
{
label: t("main.previous_music"),
enabled: !!musicItem,
click() {
messageBus.sendCommand("SkipToPrevious");
},
},
{
label: t("main.next_music"),
enabled: !!musicItem,
click() {
messageBus.sendCommand("SkipToNext");
},
}
);

ctxMenu.push({
label: t("media.music_repeat_mode"),
type: "submenu",
submenu: Menu.buildFromTemplate([
{
label: t("media.music_repeat_mode_loop"),
id: RepeatMode.Loop,
type: "radio",
checked: repeatMode === RepeatMode.Loop,
click() {
messageBus.sendCommand("SetRepeatMode", RepeatMode.Loop);
},
},
{
label: t("media.music_repeat_mode_queue"),
id: RepeatMode.Queue,
type: "radio",
checked: repeatMode === RepeatMode.Queue,
click() {
messageBus.sendCommand("SetRepeatMode", RepeatMode.Queue);
},
},
{
label: t("media.music_repeat_mode_shuffle"),
id: RepeatMode.Shuffle,
type: "radio",
checked: repeatMode === RepeatMode.Shuffle,
click() {
messageBus.sendCommand("SetRepeatMode", RepeatMode.Shuffle);
},
},
]),
});

ctxMenu.push({
type: "separator",
});
/** TODO: 桌面歌词 */
// const lyricConfig = await getAppConfigPath("lyric");
// if (lyricConfig?.enableDesktopLyric) {
// ctxMenu.push({
// label: t("main.close_desktop_lyric"),
// click() {
// setLyricWindow(false);
// },
// });
// } else {
// ctxMenu.push({
// label: t("main.open_desktop_lyric"),
// click() {
// setLyricWindow(true);
// },
// });
// }
//
// if (lyricConfig?.lockLyric) {
// ctxMenu.push({
// label: t("main.unlock_desktop_lyric"),
// click() {
// setDesktopLyricLock(false);
// },
// });
// } else {
// ctxMenu.push({
// label: t("main.lock_desktop_lyric"),
// click() {
// setDesktopLyricLock(true);
// },
// });
// }

ctxMenu.push({
type: "separator",
});
/********* 其他操作 **********/
ctxMenu.push({
label: t("app_header.settings"),
click() {
windowManager.showMainWindow();
messageBus.sendCommand("Navigate", "/main/setting");
},
});
ctxMenu.push({
label: t("common.exit"),
role: "quit",
click() {
app.exit(0);
},
});

TrayManager.trayInstance.setContextMenu(Menu.buildFromTemplate(ctxMenu));
}

public setTitle(title: string) {
if (!title || !title.length) {
TrayManager.trayInstance?.setTitle("");
return;
}
if (title.length > 7) {
TrayManager.trayInstance?.setTitle(" " + title.slice(0) + "...");
} else {
TrayManager.trayInstance?.setTitle(" " + title);
}
}

}

export default new TrayManager();
276 changes: 0 additions & 276 deletions src/main/tray/index.ts

This file was deleted.

50 changes: 0 additions & 50 deletions src/main/utils/deep-link.ts

This file was deleted.

11 changes: 0 additions & 11 deletions src/main/utils/get-res-path.ts

This file was deleted.

67 changes: 0 additions & 67 deletions src/main/utils/set-thumb-img.ts

This file was deleted.

45 changes: 0 additions & 45 deletions src/main/utils/set-thumbbar-btns.ts

This file was deleted.

Loading

0 comments on commit 7c8bd0a

Please sign in to comment.