Compare commits
160 Commits
v2.0.2
...
v2.2.0-beta.2
| Author | SHA1 | Date | |
|---|---|---|---|
| a6d4f8cf98 | |||
| d19b2394e8 | |||
| 036a99d84d | |||
| b022335af7 | |||
| a66c20c9d5 | |||
| f9fc135647 | |||
| fbbee9c114 | |||
| a65fbcbaf8 | |||
| 39b68b71d4 | |||
| 4d12a0a937 | |||
| 960973302e | |||
| 1a68b00bdd | |||
| dba73fc473 | |||
| 211f7314ce | |||
| 64d719a63a | |||
| 0304e6b569 | |||
| 190447a0bd | |||
| 497d1265f0 | |||
| 6d459e0692 | |||
| 45cde40cea | |||
| e9deb4c7f7 | |||
| 1abfc763dc | |||
| b84ddcc88d | |||
| 33f7951901 | |||
| d3354f9109 | |||
| d252816cc3 | |||
| 6e31904e95 | |||
| 2825d1f4c7 | |||
| fcb10c6137 | |||
| f564739578 | |||
| 40faf4b383 | |||
| affff353bd | |||
| f410fabff7 | |||
| 7d4b201b6e | |||
| a9ac0aa16b | |||
| 5419970080 | |||
| 506a573180 | |||
| 17b2450b43 | |||
| 2942e65a54 | |||
| 913a7bd9e5 | |||
| c5f2edd9de | |||
| 24d511e6b6 | |||
| 47f3336f9a | |||
| e0e6e5dbed | |||
| aa7f3e7bf7 | |||
| 065a6c45f7 | |||
| b13174dda1 | |||
| 9e6a931a41 | |||
| cdabdfd2f8 | |||
| b4cdbd7547 | |||
| 75fe603919 | |||
| 16ef9ae642 | |||
| 7db3162748 | |||
| 3f0e6d9856 | |||
| d87fc4a400 | |||
| ec6241b79e | |||
| 9b37398e9f | |||
| 3fca8694ee | |||
| 78efffa29b | |||
| 737ecbdadd | |||
| fa6ce22ea7 | |||
| 315c55c844 | |||
| d9ba60e1a5 | |||
| 7503322d01 | |||
| 2e5f2dc687 | |||
| e4afd27908 | |||
| 6fe5d5523e | |||
| 7335946ec2 | |||
| eb4576de9b | |||
| 1e41a9ee99 | |||
| dd5226ab47 | |||
| 989e5535eb | |||
| 65efeed692 | |||
| fcddb2d382 | |||
| bbc892ec81 | |||
| ca1c2821a7 | |||
| c8d4f763fd | |||
| a3d587af44 | |||
| ce2146cc89 | |||
| 8455f17517 | |||
| c075bdd4f9 | |||
| 65d88d0896 | |||
| 1c62640301 | |||
| dd6684c550 | |||
| 2e1a753583 | |||
| cbf6e4ecfb | |||
| 5af471fe1a | |||
| 0deb205faa | |||
| 73eaf0ecaa | |||
| 4791defbdd | |||
| 926249184b | |||
| 659b2755ef | |||
| e9d36edaa4 | |||
| fdcdbf27eb | |||
| 2f5cc2eb80 | |||
| c087fa4956 | |||
| ed33ec6532 | |||
| 2d96c2730c | |||
| 5bcec10be3 | |||
| 207bd15b14 | |||
| 00f0bfc84b | |||
| 7bc3f83c88 | |||
| 1af2803c22 | |||
| fd6a81abfd | |||
| a383093914 | |||
| 13656429af | |||
| bc34881b38 | |||
| e3b11cb087 | |||
| 8df78ca377 | |||
| f12919c6bc | |||
| 00df324ae7 | |||
| f14f9ffc1b | |||
| a388b725bc | |||
| e64eaeefef | |||
| 6830d69b62 | |||
| 8f609a8e93 | |||
| 99c23f47c5 | |||
| 95f9e20f39 | |||
| df1e664bc9 | |||
| fec30a6453 | |||
| a048211486 | |||
| 465e9b2988 | |||
| af1ff19cb2 | |||
| eae470f2ec | |||
| 1933799e32 | |||
| c7977bf7b4 | |||
| ce8407ce46 | |||
| 5d313df190 | |||
| c560a09904 | |||
| df66a92989 | |||
| 52c9611e49 | |||
| 4018112a1d | |||
| 633a257e65 | |||
| 0666d41226 | |||
| c2cfe55e24 | |||
| cb7fbddd7a | |||
| 135d9fed1b | |||
| 267aedc594 | |||
| 325d0da930 | |||
| 615bc74d15 | |||
| 1ca6935d36 | |||
| 3bfb7139d3 | |||
| 14d44765e5 | |||
| 807dd2d920 | |||
| c9a0a7f7c2 | |||
| a3eea6d501 | |||
| 4ce7dcac1b | |||
| 096762f24c | |||
| baf358d223 | |||
| e72973346b | |||
| 41258ecee8 | |||
| b6a5be152a | |||
| d5d45c4935 | |||
| 81eb4ecf09 | |||
| 5a4cc8c449 | |||
| e7ab664310 | |||
| 3cb2fa27b9 | |||
| e29e41aa4c | |||
| cc62613640 | |||
| 2720bcc685 |
@@ -0,0 +1,38 @@
|
||||
behaviour
|
||||
commitlint
|
||||
conventionalcommits
|
||||
optimizelegibility
|
||||
pinia
|
||||
tiptap
|
||||
vuedraggable
|
||||
vuejs
|
||||
TDAPP
|
||||
reduxjs
|
||||
bilibili
|
||||
localforage
|
||||
ahooks
|
||||
antd
|
||||
languagedetector
|
||||
redownload
|
||||
Redownload
|
||||
watting
|
||||
Watting
|
||||
cancle
|
||||
Sider
|
||||
inversify
|
||||
datetime
|
||||
typeorm
|
||||
bili
|
||||
mediago
|
||||
nocheck
|
||||
metas
|
||||
DDTHH
|
||||
Conpty
|
||||
execa
|
||||
bodys
|
||||
cliqz
|
||||
adblocker
|
||||
acodec
|
||||
KHTML
|
||||
svgz
|
||||
stylelint
|
||||
@@ -1,6 +1,6 @@
|
||||
APP_NAME=media-downloader
|
||||
APP_NAME=mediago
|
||||
APP_ID=mediago.ziying.site
|
||||
APP_COPYRIGHT=caorushizi
|
||||
APP_VERSION=2.0.2
|
||||
APP_VERSION=2.2.0-beta.2
|
||||
|
||||
APP_SERVER_PORT=8433
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
APP_TD_APPID=
|
||||
APP_DOWNLOAD_DEBUG=true
|
||||
APP_CLARITY_APPID=
|
||||
|
||||
GH_TOKEN=
|
||||
LOAD_DEVTOOLS=
|
||||
DEBUG_PLUGINS=true
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
APP_TD_APPID=
|
||||
APP_DOWNLOAD_DEBUG=
|
||||
APP_CLARITY_APPID=
|
||||
|
||||
GH_TOKEN=
|
||||
DEBUG_PLUGINS=false
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/* eslint-env node */
|
||||
module.exports = {
|
||||
env: {
|
||||
browser: true,
|
||||
es2021: true,
|
||||
},
|
||||
extends: [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"plugin:prettier/recommended",
|
||||
],
|
||||
overrides: [],
|
||||
parser: "@typescript-eslint/parser",
|
||||
parserOptions: {
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
},
|
||||
plugins: ["@typescript-eslint"],
|
||||
rules: {},
|
||||
};
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "" # See documentation for possible values
|
||||
- package-ecosystem: "npm" # See documentation for possible values
|
||||
directory: "/" # Location of package manifests
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
@@ -23,21 +23,28 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-latest, macos-latest]
|
||||
os: [windows-latest, macos-12]
|
||||
|
||||
# create steps
|
||||
steps:
|
||||
# step1: check out repository
|
||||
- name: Check out git repository
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# step2: install node env
|
||||
- name: Install Node.js
|
||||
uses: actions/setup-node@v3
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "16.x"
|
||||
node-version: 20
|
||||
|
||||
- uses: pnpm/action-setup@v2
|
||||
# step4: install python env
|
||||
- name: Install Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.10"
|
||||
|
||||
# step5: install pnpm env
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: latest
|
||||
run_install: true
|
||||
@@ -47,8 +54,9 @@ jobs:
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
APP_TD_APPID: ${{ secrets.APP_TD_APPID }}
|
||||
APP_CLARITY_APPID: ${{ secrets.APP_CLARITY_APPID}}
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: artifact
|
||||
path: packages/main/release/media-downloader-setup-*
|
||||
name: mediago-${{ matrix.os }}
|
||||
path: packages/main/release/mediago-setup-*
|
||||
|
||||
+13
-10
@@ -16,7 +16,6 @@ concurrency:
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
BUILD_PATH: "."
|
||||
BUCKET: downloader-docs
|
||||
ENDPOINT: oss-cn-beijing.aliyuncs.com
|
||||
ACCESS_KEY: LTAI5tLckcUrBtj7bCiUYwWz
|
||||
@@ -28,22 +27,26 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v3
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "16"
|
||||
- name: Install PNPM
|
||||
run: npm i -g pnpm
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
working-directory: ${{ env.BUILD_PATH }}
|
||||
node-version: 20
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: latest
|
||||
run_install: true
|
||||
|
||||
- name: Build with Vitepress
|
||||
run: pnpm run docs:build
|
||||
working-directory: ${{ env.BUILD_PATH }}
|
||||
|
||||
- name: Install Alibaba Cloud OSSUTIL
|
||||
run: wget http://gosspublic.alicdn.com/ossutil/1.6.10/ossutil64 && chmod +x ossutil64
|
||||
|
||||
- name: Configure Alibaba Cloud OSSUTIL
|
||||
run: ./ossutil64 config -i ${ACCESS_KEY} -k ${ACCESS_KEY_SECRET} -e ${ENDPOINT} -c .ossutilconfig
|
||||
|
||||
- name: Upload the web folder to the chosen OSS bucket
|
||||
run: ./ossutil64 --config-file .ossutilconfig cp ${{ github.workspace }}/docs/.vitepress/dist oss://${BUCKET} -r -f
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
node_modules
|
||||
.vscode
|
||||
*.local
|
||||
.idea
|
||||
.parcel-cache
|
||||
.vitepress
|
||||
*.tsno.mjs
|
||||
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname -- "$0")/_/husky.sh"
|
||||
|
||||
npx --no -- commitlint --edit ${1}
|
||||
npm run commitlint ${1}
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
npx tsx ./scripts/pre-commit.ts
|
||||
@@ -0,0 +1,3 @@
|
||||
# Ignore artifacts:
|
||||
build
|
||||
coverage
|
||||
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Launch dev",
|
||||
"runtimeExecutable": "npm",
|
||||
"runtimeArgs": ["run-script", "dev"],
|
||||
"skipFiles": ["<node_internals>/**"]
|
||||
},
|
||||
{
|
||||
"name": "Attach to Electron",
|
||||
"type": "node",
|
||||
"request": "attach",
|
||||
"address": "localhost",
|
||||
"restart": true,
|
||||
"timeout": 10000,
|
||||
"localRoot": "${workspaceFolder}",
|
||||
"remoteRoot": "${workspaceFolder}"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,30 +1,59 @@
|
||||
# media-downloader
|
||||
<img src="https://socialify.git.ci/caorushizi/mediago/image?font=Inter&forks=1&issues=1&language=1&name=1&owner=1&pattern=Circuit%20Board&pulls=1&stargazers=1&theme=Auto" alt="MediaDownloader"/>
|
||||
|
||||
m3u8 视频在线提取工具 流媒体下载 m3u8 下载 桌面客户端 windows mac。
|
||||
可以直接在线获取 m3u8 链接地址,无需使用使用网络抓包,无需安装浏览器插件,可以直接带出请求标头……详情请参考[使用帮助](https://downloader.caorushizi.cn/guides.html?form=github)
|
||||
<div align="center">
|
||||
<h1>MediaGo</h1>
|
||||
<a href="https://downloader.caorushizi.cn/guides.html?form=github">快速开始</a>
|
||||
<span> • </span>
|
||||
<a href="https://downloader.caorushizi.cn?form=github">官网</a>
|
||||
<span> • </span>
|
||||
<a href="https://downloader.caorushizi.cn/documents.html?form=github">文档</a>
|
||||
<span> • </span>
|
||||
<a href="https://github.com/caorushizi/mediago/discussions">Discussions</a>
|
||||
<br>
|
||||
<br>
|
||||
|
||||
## 上手指南
|
||||
<img alt="GitHub Downloads (all assets, all releases)" src="https://img.shields.io/github/downloads/caorushizi/mediago/total">
|
||||
<img alt="GitHub Downloads (all assets, latest release)" src="https://img.shields.io/github/downloads/caorushizi/mediago/latest/total">
|
||||
<img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/caorushizi/mediago">
|
||||
<img alt="GitHub forks" src="https://img.shields.io/github/forks/caorushizi/mediago">
|
||||
|
||||
以下指南将帮助你在本地机器上安装和运行该项目,进行开发和测试。关于如何将该项目部署到在线环境,请参考部署小节。
|
||||
<hr />
|
||||
</div>
|
||||
|
||||
## 安装要求
|
||||
## Intro
|
||||
|
||||
运行代码需要 node 和 pnpm,node 需要在官网下载安装,pnpm 可以通过`npm i -g pnpm`安装。
|
||||
本项目支持 m3u8 视频在线提取工具 流媒体下载 m3u8 下载。
|
||||
|
||||
- **✅ 无需抓包**: 使用软件自带浏览器可以轻松嗅探网页中的视频资源,通过嗅探到的资源列表选择自己想要下载的资源,简单快速。
|
||||
- **📱 移动播放**: 可以轻松无缝的在PC和移动设备之前切换,下载完成后即可使用手机观看视频。
|
||||
- **⚡️ 批量下载**: 支持同时下载多个视频和直播资源,高速带宽不闲置。
|
||||
|
||||
## Quickstart
|
||||
|
||||
运行代码需要 node 、 pnpm 和 go,node、go 需要在官网下载安装,pnpm 可以通过`npm i -g pnpm`安装。
|
||||
|
||||
## 运行代码
|
||||
|
||||
安装依赖 `pnpm i`
|
||||
```shell
|
||||
# 代码下载
|
||||
git clone https://github.com/caorushizi/mediago.git
|
||||
|
||||
开发环境 `pnpm run dev`
|
||||
# 安装依赖
|
||||
pnpm i
|
||||
|
||||
打包运行 `pnpm run release`
|
||||
# 开发环境
|
||||
pnpm dev
|
||||
|
||||
## 下载链接
|
||||
# 打包运行
|
||||
pnpm release
|
||||
```
|
||||
|
||||
**v2.0.1(2023.7.1 发布)**
|
||||
## Releases
|
||||
|
||||
- [windows media-downloader v2.0.1](https://github.com/caorushizi/m3u8-downloader/releases/download/v2.0.1/media-downloader-setup-2.0.1.exe)
|
||||
- [macos media-downloader v2.0.1](https://github.com/caorushizi/m3u8-downloader/releases/download/v2.0.1/media-downloader-setup-2.0.1.dmg)
|
||||
**v2.0.2(2023.7.9 发布)**
|
||||
|
||||
- [windows mediago v2.0.2](https://github.com/caorushizi/mediago/releases/download/v2.0.2/media-downloader-setup-2.0.2.exe)
|
||||
- [macos mediago v2.0.2](https://github.com/caorushizi/mediago/releases/download/v2.0.2/media-downloader-setup-2.0.2.dmg)
|
||||
|
||||
**更新日志**
|
||||
|
||||
@@ -39,17 +68,17 @@ m3u8 视频在线提取工具 流媒体下载 m3u8 下载 桌面客户端 window
|
||||
|
||||
**v1.1.5(2022.2.5 发布)**
|
||||
|
||||
- [windows media-downloader v1.1.5](https://github.com/caorushizi/m3u8-downloader/releases/download/1.1.5/media-downloader-setup-1.1.4.exe)
|
||||
- [windows mediago v1.1.5](https://github.com/caorushizi/mediago/releases/download/1.1.5/media-downloader-setup-1.1.4.exe)
|
||||
|
||||
**更新日志**
|
||||
|
||||
## 软件截图
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
## 技术栈
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
export default {
|
||||
extends: ["@commitlint/config-conventional"], // extends can be nested
|
||||
parserPreset: "conventional-changelog-conventionalcommits",
|
||||
prompt: {
|
||||
settings: {},
|
||||
messages: {
|
||||
skip: ":skip",
|
||||
max: "upper %d chars",
|
||||
min: "%d chars at least",
|
||||
emptyWarning: "can not be empty",
|
||||
upperLimitWarning: "over limit",
|
||||
lowerLimitWarning: "below limit",
|
||||
},
|
||||
types: [
|
||||
{ value: "feat", name: "feat: ✨ A new feature", emoji: "✨ " },
|
||||
{ value: "fix", name: "fix: 🐛 A bug fix", emoji: "🐛 " },
|
||||
{
|
||||
value: "docs",
|
||||
name: "docs: 📝 Documentation only changes",
|
||||
emoji: "📝 ",
|
||||
},
|
||||
{
|
||||
value: "style",
|
||||
name: "style: 💄 Changes that do not affect the meaning of the code",
|
||||
emoji: "💄 ",
|
||||
},
|
||||
{
|
||||
value: "refactor",
|
||||
name: "refactor: 📦️ A code change that neither fixes a bug nor adds a feature",
|
||||
emoji: "📦️ ",
|
||||
},
|
||||
{
|
||||
value: "perf",
|
||||
name: "perf: 🚀 A code change that improves performance",
|
||||
emoji: "🚀 ",
|
||||
},
|
||||
{
|
||||
value: "test",
|
||||
name: "test: 🚨 Adding missing tests or correcting existing tests",
|
||||
emoji: "🚨 ",
|
||||
},
|
||||
{
|
||||
value: "build",
|
||||
name: "build: 🛠 Changes that affect the build system or external dependencies",
|
||||
emoji: "🛠 ",
|
||||
},
|
||||
{
|
||||
value: "ci",
|
||||
name: "ci: 🎡 Changes to our CI configuration files and scripts",
|
||||
emoji: "🎡 ",
|
||||
},
|
||||
{
|
||||
value: "chore",
|
||||
name: "chore: 🔨 Other changes that don't modify src or test files",
|
||||
emoji: "🔨 ",
|
||||
},
|
||||
{
|
||||
value: "revert",
|
||||
name: "revert: ⏪️ Reverts a previous commit",
|
||||
emoji: ":rewind:",
|
||||
},
|
||||
],
|
||||
useEmoji: true,
|
||||
confirmColorize: true,
|
||||
emojiAlign: "center",
|
||||
questions: {
|
||||
scope: {
|
||||
description:
|
||||
"What is the scope of this change (e.g. component or file name)",
|
||||
},
|
||||
subject: {
|
||||
description:
|
||||
"Write a short, imperative tense description of the change",
|
||||
},
|
||||
body: {
|
||||
description: "Provide a longer description of the change",
|
||||
},
|
||||
isBreaking: {
|
||||
description: "Are there any breaking changes?",
|
||||
},
|
||||
breakingBody: {
|
||||
description:
|
||||
"A BREAKING CHANGE commit requires a body. Please enter a longer description of the commit itself",
|
||||
},
|
||||
breaking: {
|
||||
description: "Describe the breaking changes",
|
||||
},
|
||||
isIssueAffected: {
|
||||
description: "Does this change affect any open issues?",
|
||||
},
|
||||
issuesBody: {
|
||||
description:
|
||||
"If issues are closed, the commit requires a body. Please enter a longer description of the commit itself",
|
||||
},
|
||||
issues: {
|
||||
description: 'Add issue references (e.g. "fix #123", "re #123".)',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"import": [
|
||||
"@cspell/dict-lorem-ipsum/cspell-ext.json"
|
||||
],
|
||||
"caseSensitive": false,
|
||||
"dictionaries": [
|
||||
"custom-words"
|
||||
],
|
||||
"dictionaryDefinitions": [
|
||||
{
|
||||
"name": "custom-words",
|
||||
"path": "./.cspell/custom-words.txt",
|
||||
"addWords": true
|
||||
}
|
||||
],
|
||||
"ignorePaths": [
|
||||
"**/node_modules/**",
|
||||
"**/dist/**",
|
||||
"**/lib/**",
|
||||
"**/docs/**",
|
||||
"**/stats.html"
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { HeadConfig } from "vitepress";
|
||||
import { defineConfig } from "vitepress";
|
||||
import { HeadConfig, defineConfig } from "vitepress";
|
||||
|
||||
const isDev = process.env.NODE_ENV === "development";
|
||||
|
||||
@@ -22,7 +21,7 @@ if (!isDev) {
|
||||
|
||||
// https://vitepress.dev/reference/site-config
|
||||
export default defineConfig({
|
||||
title: "media-downloader",
|
||||
title: "MediaGo",
|
||||
description: "简单易用,快速下载",
|
||||
lastUpdated: true,
|
||||
head,
|
||||
@@ -57,7 +56,7 @@ export default defineConfig({
|
||||
|
||||
footer: {
|
||||
message: '<a href="https://beian.miit.gov.cn">豫ICP备20012967号-2</a>',
|
||||
copyright: "Copyright © 2019-present caorushizi",
|
||||
copyright: "Copyright © 2021-present caorushizi",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -29,7 +29,6 @@ function initWaline() {
|
||||
serverURL: "https://comments.ziying.site",
|
||||
dark: isDark.value,
|
||||
lang: "zh-CN",
|
||||
reaction: true,
|
||||
pageview: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -20,11 +20,13 @@
|
||||
--vp-button-brand-text: #f2f7fd;
|
||||
--vp-button-brand-bg: #2a82f6;
|
||||
|
||||
--vp-button-brand-active-border: #5e9ef3;
|
||||
--vp-button-brand-active-text: #fff;
|
||||
--vp-button-brand-active-bg: #409eff;
|
||||
|
||||
--vp-button-brand-hover-border: #5e9ef3;
|
||||
--vp-button-brand-hover-text: #fff;
|
||||
--vp-button-brand-hover-bg: #2a82f6;
|
||||
|
||||
--vp-button-brand-active-border: #f6ceec;
|
||||
|
||||
--vp-c-brand: #2a82f6;
|
||||
}
|
||||
|
||||
+3
-3
@@ -15,8 +15,8 @@ outline: deep
|
||||
|
||||
**v2.0.1(2023.7.1 发布)**
|
||||
|
||||
- [windows media-downloader v2.0.1](https://github.com/caorushizi/m3u8-downloader/releases/download/v2.0.1/media-downloader-setup-2.0.1.exe)
|
||||
- [macos media-downloader v2.0.1](https://github.com/caorushizi/m3u8-downloader/releases/download/v2.0.1/media-downloader-setup-2.0.1.dmg)
|
||||
- [windows mediago v2.0.1](https://github.com/caorushizi/mediago/releases/download/v2.0.1/media-downloader-setup-2.0.1.exe)
|
||||
- [macos mediago v2.0.1](https://github.com/caorushizi/mediago/releases/download/v2.0.1/media-downloader-setup-2.0.1.dmg)
|
||||
|
||||
**更新日志**
|
||||
|
||||
@@ -31,7 +31,7 @@ outline: deep
|
||||
|
||||
**v1.1.5(2022.2.5 发布)**
|
||||
|
||||
- [windows media-downloader v1.1.5](https://github.com/caorushizi/m3u8-downloader/releases/download/1.1.5/media-downloader-setup-1.1.4.exe)
|
||||
- [windows mediago v1.1.5](https://github.com/caorushizi/mediago/releases/download/1.1.5/media-downloader-setup-1.1.4.exe)
|
||||
|
||||
**更新日志**
|
||||
|
||||
|
||||
+2
-2
@@ -13,8 +13,8 @@ outline: deep
|
||||
|
||||
**v1.1.5(2022.2.5 发布)**
|
||||
|
||||
- [windows media-downloader v1.1.5](https://github.com/caorushizi/m3u8-downloader/releases/download/1.1.5/media-downloader-setup-1.1.4.exe)
|
||||
- ~~macos media-downloader v1.1.5 无~~
|
||||
- [windows mediago v1.1.5](https://github.com/caorushizi/mediago/releases/download/1.1.5/media-downloader-setup-1.1.4.exe)
|
||||
- ~~macos mediago v1.1.5 无~~
|
||||
|
||||
**更新日志**
|
||||
|
||||
|
||||
+1
-1
@@ -26,5 +26,5 @@ features:
|
||||
details: 可以轻松无缝的在PC和移动设备之前切换,下载完成后即可使用手机观看视频。
|
||||
- icon: ⚡️
|
||||
title: 支持批量下载
|
||||
details: 支持同时最多下载10个视频和直播资源,高速带宽不闲置。
|
||||
details: 支持同时下载多个视频和直播资源,高速带宽不闲置。
|
||||
---
|
||||
|
||||
+43
-14
@@ -1,31 +1,60 @@
|
||||
{
|
||||
"name": "electron-template",
|
||||
"name": "mediago",
|
||||
"version": "0.1.0",
|
||||
"description": "electron-template",
|
||||
"main": "index.js",
|
||||
"description": "mediago",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "pnpm run build:mobile && pnpm --parallel -F \"./packages/*\" run dev",
|
||||
"build": "pnpm run build:mobile && pnpm run build:main && pnpm run build:renderer",
|
||||
"build:mobile": "pnpm -F mobile run build",
|
||||
"dev": "tsx scripts/dev.ts && pnpm --parallel -F \"./packages/*\" run dev",
|
||||
"build": "tsx scripts/build.ts",
|
||||
"build:plugin": "pnpm -F plugin run build",
|
||||
"build:main": "pnpm -F main run build",
|
||||
"build:renderer": "pnpm -F renderer run build",
|
||||
"pack": "pnpm -F media-downloader run pack",
|
||||
"prerelease": "pnpm run build && pnpm -F mediago run pack",
|
||||
"release": "pnpm run build && pnpm -F main run release",
|
||||
"docs:dev": "vitepress dev docs",
|
||||
"docs:build": "vitepress build docs",
|
||||
"docs:preview": "vitepress preview docs"
|
||||
"docs:preview": "vitepress preview docs",
|
||||
"types": "pnpm -F main run types",
|
||||
"types:watch": "pnpm -F main run types:watch",
|
||||
"prepare": "husky",
|
||||
"commit": "git-cz",
|
||||
"commitlint": "commitlint --edit",
|
||||
"spellcheck": "cspell \"packages/**/src/**/*.{ts,tsx}\"",
|
||||
"lint-staged": "pnpm --recursive -F \"./packages/*\" run lint-staged"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"pnpm": {
|
||||
"patchedDependencies": {
|
||||
"@cliqz/adblocker@1.26.6": "patches/@cliqz__adblocker@1.26.6.patch"
|
||||
"config": {
|
||||
"commitizen": {
|
||||
"path": "node_modules/cz-git"
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@waline/client": "^2.15.5",
|
||||
"vitepress": "1.0.0-beta.3",
|
||||
"vue": "^3.3.4"
|
||||
"@commitlint/cli": "^18.6.0",
|
||||
"@commitlint/config-conventional": "^18.6.0",
|
||||
"@commitlint/cz-commitlint": "^18.6.0",
|
||||
"@typescript-eslint/eslint-plugin": "^6.21.0",
|
||||
"@typescript-eslint/parser": "^6.21.0",
|
||||
"@waline/client": "^3.1.3",
|
||||
"commitizen": "^4.3.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"cspell": "^8.3.2",
|
||||
"cz-git": "^1.8.0",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-plugin-prettier": "^5.1.3",
|
||||
"husky": "^9.0.10",
|
||||
"prettier": "3.2.5",
|
||||
"tsx": "^4.7.1",
|
||||
"vitepress": "1.0.1",
|
||||
"vue": "^3.4.15",
|
||||
"zx": "^7.2.3"
|
||||
},
|
||||
"pnpm": {
|
||||
"patchedDependencies": {
|
||||
"@cliqz/adblocker@1.27.3": "patches/@cliqz__adblocker@1.27.3.patch"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
./types
|
||||
|
||||
@@ -6,16 +6,18 @@ module.exports = {
|
||||
extends: [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"prettier",
|
||||
"plugin:prettier/recommended",
|
||||
],
|
||||
overrides: [],
|
||||
ignorePatterns: ["app"],
|
||||
parser: "@typescript-eslint/parser",
|
||||
parserOptions: {
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
},
|
||||
plugins: ["@typescript-eslint", "prettier"],
|
||||
plugins: ["@typescript-eslint"],
|
||||
rules: {
|
||||
"prettier/prettier": "warn",
|
||||
"@typescript-eslint/no-explicit-any": "warn",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4,3 +4,4 @@ build
|
||||
dist
|
||||
bin/Logs
|
||||
release
|
||||
types
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
types/
|
||||
@@ -1 +1 @@
|
||||
{}
|
||||
{}
|
||||
|
||||
@@ -2,3 +2,4 @@ node_modules
|
||||
output
|
||||
bin
|
||||
mobile
|
||||
plugin
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
{
|
||||
"name": "media-downloader",
|
||||
"version": "2.0.2",
|
||||
"name": "mediago",
|
||||
"version": "2.2.0-beta.2",
|
||||
"description": "在线视频下载器",
|
||||
"main": "main/index.js",
|
||||
"scripts": {},
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cliqz/adblocker-electron": "^1.26.6",
|
||||
"@cliqz/adblocker-electron-preload": "^1.26.6"
|
||||
"@cliqz/adblocker-electron": "^1.27.3",
|
||||
"@cliqz/adblocker-electron-preload": "^1.27.3",
|
||||
"node-pty": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"electron": "^28.2.6"
|
||||
}
|
||||
}
|
||||
|
||||
+55
-53
@@ -4,71 +4,73 @@
|
||||
"description": "在线视频下载器",
|
||||
"main": "main/index.js",
|
||||
"scripts": {
|
||||
"rebuild": "electron-rebuild -f -w better-sqlite3",
|
||||
"dev": "cross-env NODE_ENV=development node script/dev.mjs",
|
||||
"build": "cross-env NODE_ENV=production node script/build.mjs",
|
||||
"pack": "cross-env NODE_ENV=development node script/release.mjs",
|
||||
"release": "cross-env NODE_ENV=production node script/release.mjs"
|
||||
"postinstall": "electron-rebuild -f -w",
|
||||
"dev": "cross-env NODE_ENV=development VITE_CJS_IGNORE_WARNING=true tsx scripts/dev.ts",
|
||||
"build": "cross-env NODE_ENV=production tsx scripts/build.ts",
|
||||
"pack": "cross-env NODE_ENV=development tsx scripts/release.ts",
|
||||
"types": "tsc",
|
||||
"types:watch": "tsc -w",
|
||||
"release": "cross-env NODE_ENV=production tsx scripts/release.ts",
|
||||
"lint-staged": "lint-staged"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{js,jsx,ts,tsx}": "eslint"
|
||||
},
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@electron/rebuild": "^3.2.13",
|
||||
"@rushstack/eslint-patch": "^1.3.2",
|
||||
"@types/fs-extra": "^11.0.1",
|
||||
"@types/koa": "^2.13.6",
|
||||
"@types/koa-range": "^0.3.2",
|
||||
"@types/koa-send": "^4.1.3",
|
||||
"@types/koa__cors": "^4.0.0",
|
||||
"@types/koa__router": "^12.0.0",
|
||||
"@types/lodash": "^4.14.195",
|
||||
"@types/node": "^20.3.1",
|
||||
"@typescript-eslint/eslint-plugin": "5.60.0",
|
||||
"@typescript-eslint/parser": "5.60.0",
|
||||
"@electron/rebuild": "^3.5.0",
|
||||
"@rushstack/eslint-patch": "^1.7.0",
|
||||
"@types/fs-extra": "^11.0.4",
|
||||
"@types/lodash": "^4.14.202",
|
||||
"@types/mime-types": "^2.1.4",
|
||||
"@types/node": "^20.11.5",
|
||||
"@types/node-fetch": "^2.6.11",
|
||||
"@types/semver": "^7.5.6",
|
||||
"@typescript-eslint/eslint-plugin": "6.21.0",
|
||||
"@typescript-eslint/parser": "6.21.0",
|
||||
"chokidar": "^3.5.3",
|
||||
"cross-env": "^7.0.3",
|
||||
"dotenv": "^16.3.1",
|
||||
"electron": "^25.2.0",
|
||||
"electron-builder": "^24.4.0",
|
||||
"electron-updater": "^6.1.1",
|
||||
"esbuild": "^0.18.6",
|
||||
"eslint": "^8.43.0",
|
||||
"eslint-config-prettier": "^8.8.0",
|
||||
"eslint-config-standard-with-typescript": "^35.0.0",
|
||||
"eslint-plugin-import": "2.27.5",
|
||||
"eslint-plugin-n": "15.0.0",
|
||||
"eslint-plugin-prettier": "^4.2.1",
|
||||
"dotenv": "^16.3.2",
|
||||
"electron": "^28.2.6",
|
||||
"electron-builder": "^24.9.1",
|
||||
"electron-updater": "^6.1.7",
|
||||
"esbuild": "^0.19.11",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-config-standard-with-typescript": "^43.0.1",
|
||||
"eslint-plugin-import": "2.29.1",
|
||||
"eslint-plugin-n": "16.6.2",
|
||||
"eslint-plugin-prettier": "^5.1.3",
|
||||
"eslint-plugin-promise": "6.1.1",
|
||||
"prebuild-install": "^7.1.1",
|
||||
"prettier": "2.8.8",
|
||||
"semver": "^7.5.2",
|
||||
"typescript": "^5.1.3"
|
||||
"prettier": "3.2.5",
|
||||
"semver": "^7.5.4",
|
||||
"tsx": "^4.7.1",
|
||||
"typescript": "^5.3.3",
|
||||
"vite": "^5.0.12"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cliqz/adblocker-electron": "^1.26.6",
|
||||
"@cliqz/adblocker-electron-preload": "^1.26.6",
|
||||
"@koa/cors": "^4.0.0",
|
||||
"@koa/router": "^12.0.0",
|
||||
"@types/koa-static": "^4.0.2",
|
||||
"axios": "^1.4.0",
|
||||
"better-sqlite3": "^8.4.0",
|
||||
"cross-fetch": "^3.1.6",
|
||||
"dayjs": "^1.11.8",
|
||||
"@cliqz/adblocker-electron": "^1.27.3",
|
||||
"@cliqz/adblocker-electron-preload": "^1.27.3",
|
||||
"axios": "^1.6.5",
|
||||
"better-sqlite3": "^9.3.0",
|
||||
"cheerio": "1.0.0-rc.12",
|
||||
"dayjs": "^1.11.10",
|
||||
"electron-devtools-installer": "^3.2.0",
|
||||
"electron-is-dev": "^2.0.0",
|
||||
"electron-log": "^4.4.8",
|
||||
"electron-is-dev": "^3.0.1",
|
||||
"electron-log": "^5.0.3",
|
||||
"electron-store": "^8.1.0",
|
||||
"execa": "^7.1.1",
|
||||
"fs-extra": "^11.1.1",
|
||||
"glob": "^10.3.0",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"inversify": "^6.0.1",
|
||||
"koa": "^2.14.2",
|
||||
"koa-range": "^0.3.0",
|
||||
"koa-send": "^5.0.1",
|
||||
"koa-static": "^5.0.0",
|
||||
"execa": "^8.0.1",
|
||||
"fs-extra": "^11.2.0",
|
||||
"inversify": "^6.0.2",
|
||||
"lint-staged": "^15.2.2",
|
||||
"lodash": "^4.17.21",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"typeorm": "^0.3.17"
|
||||
"mime-types": "^2.1.35",
|
||||
"node-fetch": "^3.3.2",
|
||||
"node-pty": "^1.0.0",
|
||||
"reflect-metadata": "^0.2.1",
|
||||
"strip-ansi": "^7.1.0",
|
||||
"typeorm": "^0.3.19"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,11 +4,13 @@ import {
|
||||
loadDotEnvDefined,
|
||||
copyResource,
|
||||
removeResource,
|
||||
} from "./utils.mjs";
|
||||
} from "./utils";
|
||||
import { external } from "./config";
|
||||
|
||||
const mainDefined = loadDotEnvDefined();
|
||||
|
||||
removeResource([mainResolve("app/build")]);
|
||||
removeResource([mainResolve("app/bin")]);
|
||||
|
||||
const path = "build/Release/better_sqlite3.node";
|
||||
|
||||
@@ -17,25 +19,36 @@ copyResource([
|
||||
from: mainResolve("node_modules/better-sqlite3", path),
|
||||
to: mainResolve("app", path),
|
||||
},
|
||||
{
|
||||
from: mainResolve("bin"),
|
||||
to: mainResolve("app/bin"),
|
||||
},
|
||||
]);
|
||||
|
||||
esbuild.build({
|
||||
entryPoints: [
|
||||
mainResolve("src/index.ts"),
|
||||
mainResolve("src/preload.ts"),
|
||||
mainResolve("src/webview.ts"),
|
||||
],
|
||||
entryPoints: [mainResolve("src/index.ts")],
|
||||
bundle: true,
|
||||
platform: "node",
|
||||
sourcemap: false,
|
||||
target: ["node16.13"],
|
||||
external: [
|
||||
"electron",
|
||||
"nock",
|
||||
"aws-sdk",
|
||||
"mock-aws-s3",
|
||||
"@cliqz/adblocker-electron-preload",
|
||||
],
|
||||
external,
|
||||
define: {
|
||||
"process.env.NODE_ENV": '"production"',
|
||||
...mainDefined,
|
||||
},
|
||||
outdir: mainResolve("app/build/main"),
|
||||
loader: { ".png": "file" },
|
||||
minify: true,
|
||||
plugins: [],
|
||||
});
|
||||
|
||||
esbuild.build({
|
||||
entryPoints: [mainResolve("src/preload.ts")],
|
||||
bundle: true,
|
||||
platform: "browser",
|
||||
target: ["chrome89"],
|
||||
sourcemap: false,
|
||||
external,
|
||||
define: {
|
||||
"process.env.NODE_ENV": '"production"',
|
||||
...mainDefined,
|
||||
@@ -0,0 +1,8 @@
|
||||
export const external = [
|
||||
"electron",
|
||||
"nock",
|
||||
"aws-sdk",
|
||||
"mock-aws-s3",
|
||||
"@cliqz/adblocker-electron-preload",
|
||||
"node-pty",
|
||||
];
|
||||
@@ -1,10 +1,11 @@
|
||||
import { spawn } from "child_process";
|
||||
import { ChildProcessWithoutNullStreams, spawn } from "child_process";
|
||||
import electron from "electron";
|
||||
import * as esbuild from "esbuild";
|
||||
import chokidar from "chokidar";
|
||||
import { loadDotEnvRuntime, mainResolve, log, copyResource } from "./utils.mjs";
|
||||
import { loadDotEnvRuntime, mainResolve, log, copyResource } from "./utils";
|
||||
import { external } from "./config";
|
||||
|
||||
let electronProcess = null;
|
||||
let electronProcess: ChildProcessWithoutNullStreams | null = null;
|
||||
|
||||
process.env.NODE_ENV = "development";
|
||||
loadDotEnvRuntime();
|
||||
@@ -24,23 +25,12 @@ async function copySource() {
|
||||
]);
|
||||
}
|
||||
|
||||
const ctx = await esbuild.context({
|
||||
entryPoints: [
|
||||
mainResolve("src/index.ts"),
|
||||
mainResolve("src/preload.ts"),
|
||||
mainResolve("src/webview.ts"),
|
||||
],
|
||||
const buildConfig: esbuild.BuildOptions = {
|
||||
bundle: true,
|
||||
platform: "node",
|
||||
sourcemap: true,
|
||||
target: ["node16.13"],
|
||||
external: [
|
||||
"electron",
|
||||
"mock-aws-s3",
|
||||
"aws-sdk",
|
||||
"nock",
|
||||
"@cliqz/adblocker-electron-preload",
|
||||
],
|
||||
target: ["node20.9"],
|
||||
external,
|
||||
define: {
|
||||
// 开发环境中二进制可执行文件的路径
|
||||
__bin__: `"${mainResolve("bin", process.platform).replace(/\\/g, "\\\\")}"`,
|
||||
@@ -48,23 +38,7 @@ const ctx = await esbuild.context({
|
||||
plugins: [],
|
||||
outdir: mainResolve("app/build/main"),
|
||||
loader: { ".png": "file" },
|
||||
});
|
||||
|
||||
const watcher = chokidar.watch("./src");
|
||||
|
||||
watcher.on("change", async () => {
|
||||
await ctx.rebuild();
|
||||
log("watch build succeed.");
|
||||
if (electronProcess && electronProcess.kill) {
|
||||
if (process.platform === "darwin") {
|
||||
spawn("kill", ["-9", electronProcess.pid]);
|
||||
} else {
|
||||
process.kill(electronProcess.pid);
|
||||
}
|
||||
electronProcess = null;
|
||||
startElectron();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
function startElectron() {
|
||||
const args = ["--inspect=5858", mainResolve("app/build/main/index.js")];
|
||||
@@ -80,11 +54,47 @@ function startElectron() {
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await ctx.rebuild();
|
||||
await copySource();
|
||||
await startElectron();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
process.exit();
|
||||
function restartElectron() {
|
||||
if (electronProcess && electronProcess.pid) {
|
||||
if (process.platform === "darwin") {
|
||||
spawn("kill", ["-9", String(electronProcess.pid)]);
|
||||
} else {
|
||||
process.kill(electronProcess.pid);
|
||||
}
|
||||
electronProcess = null;
|
||||
startElectron();
|
||||
}
|
||||
}
|
||||
|
||||
async function start() {
|
||||
const mainContext = await esbuild.context({
|
||||
...buildConfig,
|
||||
entryPoints: [mainResolve("src/index.ts")],
|
||||
});
|
||||
|
||||
const preloadContext = await esbuild.context({
|
||||
...buildConfig,
|
||||
entryPoints: [mainResolve("src/preload.ts")],
|
||||
platform: "browser",
|
||||
});
|
||||
|
||||
const watcher = chokidar.watch("./src");
|
||||
watcher.on("change", async () => {
|
||||
await mainContext.rebuild();
|
||||
await preloadContext.rebuild();
|
||||
log("watch build succeed.");
|
||||
restartElectron();
|
||||
});
|
||||
|
||||
try {
|
||||
await mainContext.rebuild();
|
||||
await preloadContext.rebuild();
|
||||
await copySource();
|
||||
await startElectron();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
process.exit();
|
||||
}
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,34 +1,25 @@
|
||||
import builder from "electron-builder";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { loadDotEnvRuntime, log, mainResolve, removeResource } from "./utils";
|
||||
import * as builder from "electron-builder";
|
||||
import semver from "semver";
|
||||
import {
|
||||
mainResolve,
|
||||
loadDotEnvRuntime,
|
||||
log,
|
||||
removeResource,
|
||||
} from "./utils.mjs";
|
||||
import pkg from "../app/package.json";
|
||||
|
||||
removeResource([mainResolve("release")]);
|
||||
|
||||
const packageJson = JSON.parse(readFileSync(mainResolve("./app/package.json")));
|
||||
loadDotEnvRuntime();
|
||||
|
||||
if (semver.neq(process.env.APP_VERSION, packageJson.version)) {
|
||||
if (semver.neq(process.env.APP_VERSION || "", pkg.version)) {
|
||||
log("请先同步构建版本和发布版本");
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Let's get that intellisense working
|
||||
/**
|
||||
* @type {import('electron-builder').Configuration}
|
||||
* @see https://www.electron.build/configuration/configuration
|
||||
*/
|
||||
const options = {
|
||||
const options: builder.Configuration = {
|
||||
productName: process.env.APP_NAME,
|
||||
buildVersion: process.env.APP_VERSION,
|
||||
appId: process.env.APP_ID,
|
||||
copyright: process.env.APP_COPYRIGHT,
|
||||
artifactName: "${productName}-setup-${buildVersion}.${ext}",
|
||||
// FIXME: 这里屏蔽 node-pty 自动重构,因为会导致打包失败
|
||||
npmRebuild: false,
|
||||
directories: {
|
||||
output: "./release",
|
||||
},
|
||||
@@ -41,8 +32,8 @@ const options = {
|
||||
],
|
||||
extraResources: [
|
||||
{
|
||||
from: "./app/mobile",
|
||||
to: "mobile",
|
||||
from: "./app/plugin",
|
||||
to: "plugin",
|
||||
},
|
||||
{
|
||||
from: "./app/bin/${platform}/",
|
||||
@@ -95,25 +86,29 @@ const options = {
|
||||
},
|
||||
publish: {
|
||||
provider: "github",
|
||||
repo: "m3u8-downloader",
|
||||
repo: "mediago",
|
||||
owner: "caorushizi",
|
||||
releaseType: "prerelease",
|
||||
},
|
||||
};
|
||||
|
||||
const target =
|
||||
process.env.NODE_ENV === "development"
|
||||
? builder.DIR_TARGET
|
||||
: builder.DEFAULT_TARGET;
|
||||
try {
|
||||
const targets =
|
||||
process.platform === "win32"
|
||||
? builder.Platform.WINDOWS.createTarget(target)
|
||||
: builder.Platform.MAC.createTarget(target);
|
||||
await builder.build({
|
||||
targets,
|
||||
config: options,
|
||||
});
|
||||
} catch (e) {
|
||||
log(e);
|
||||
async function start() {
|
||||
const target =
|
||||
process.env.NODE_ENV === "development"
|
||||
? builder.DIR_TARGET
|
||||
: builder.DEFAULT_TARGET;
|
||||
try {
|
||||
const targets =
|
||||
process.platform === "win32"
|
||||
? builder.Platform.WINDOWS.createTarget(target)
|
||||
: builder.Platform.MAC.createTarget(target);
|
||||
await builder.build({
|
||||
targets,
|
||||
config: options,
|
||||
});
|
||||
} catch (e) {
|
||||
log(e);
|
||||
}
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -1,28 +1,27 @@
|
||||
import { existsSync, cpSync, rmSync } from "node:fs";
|
||||
import { existsSync, cpSync, rmSync } from "fs";
|
||||
import dotenv from "dotenv";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { resolve } from "path";
|
||||
|
||||
// FIXME: 有没有什么办法可以不用这么写?
|
||||
const con = console;
|
||||
export const log = con.log;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const mainResolve = (...r) => resolve(__dirname, "..", ...r);
|
||||
export const rootResolve = (...r) => resolve(__dirname, "../../..", ...r);
|
||||
export const mainResolve = (...r: any[]) => resolve(__dirname, "..", ...r);
|
||||
export const rootResolve = (...r: any[]) =>
|
||||
resolve(__dirname, "../../..", ...r);
|
||||
const nodeEnv = process.env.NODE_ENV;
|
||||
log("当前的环境是: ", nodeEnv);
|
||||
|
||||
function loadEnv(path) {
|
||||
const result = {};
|
||||
function loadEnv(path: string) {
|
||||
const result: Record<string, string> = {};
|
||||
|
||||
const _loadEnv = (path) => {
|
||||
const _loadEnv = (path: string) => {
|
||||
if (!existsSync(path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { error, parsed } = dotenv.config({ path });
|
||||
if (error != null) {
|
||||
if (error != null || !parsed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -57,14 +56,14 @@ export function loadDotEnvRuntime() {
|
||||
export function loadDotEnvDefined() {
|
||||
const env = loadDotEnv();
|
||||
|
||||
return Object.keys(env).reduce((prev, cur) => {
|
||||
return Object.keys(env).reduce<Record<string, string>>((prev, cur) => {
|
||||
if (!cur.startsWith("APP_")) return prev;
|
||||
prev[`process.env.${[cur]}`] = JSON.stringify(env[cur]);
|
||||
return prev;
|
||||
}, {});
|
||||
}
|
||||
|
||||
export function copyResource(resource) {
|
||||
export function copyResource(resource: { from: string; to: string }[]) {
|
||||
resource.forEach((r) => {
|
||||
const { from, to } = r;
|
||||
cpSync(from, to, {
|
||||
@@ -73,7 +72,7 @@ export function copyResource(resource) {
|
||||
});
|
||||
}
|
||||
|
||||
export function removeResource(resource) {
|
||||
export function removeResource(resource: string[]) {
|
||||
resource.forEach((r) => {
|
||||
rmSync(r, { recursive: true, force: true });
|
||||
});
|
||||
+40
-39
@@ -1,60 +1,61 @@
|
||||
import { inject, injectable } from "inversify";
|
||||
import {
|
||||
DatabaseService,
|
||||
DownloadStatus,
|
||||
IpcHandlerService,
|
||||
MainWindowService,
|
||||
ProtocolService,
|
||||
UpdateService,
|
||||
VideoRepository,
|
||||
WebviewService,
|
||||
type App,
|
||||
WebService,
|
||||
DevToolsService,
|
||||
StoreService,
|
||||
} from "./interfaces";
|
||||
import { DownloadStatus } from "./interfaces";
|
||||
import { TYPES } from "./types";
|
||||
import { Menu, Tray, app, nativeImage, nativeTheme } from "electron";
|
||||
import TrayIcon from "./tray-icon.png";
|
||||
import path from "path";
|
||||
import MainWindow from "./windows/MainWindow";
|
||||
import WebviewService from "./services/WebviewService";
|
||||
import VideoRepository from "./repository/VideoRepository";
|
||||
import ElectronDevtools from "./vendor/ElectronDevtools";
|
||||
import ElectronStore from "./vendor/ElectronStore";
|
||||
import ElectronUpdater from "./vendor/ElectronUpdater";
|
||||
import TypeORM from "./vendor/TypeORM";
|
||||
import ProtocolService from "./core/protocol";
|
||||
import IpcHandlerService from "./core/ipc";
|
||||
|
||||
@injectable()
|
||||
export default class ElectronApp implements App {
|
||||
export default class ElectronApp {
|
||||
constructor(
|
||||
@inject(TYPES.MainWindowService)
|
||||
private readonly mainWindow: MainWindowService,
|
||||
@inject(TYPES.MainWindow)
|
||||
private readonly mainWindow: MainWindow,
|
||||
@inject(TYPES.ProtocolService)
|
||||
private readonly protocolService: ProtocolService,
|
||||
@inject(TYPES.UpdateService)
|
||||
private readonly updateService: UpdateService,
|
||||
private readonly protocol: ProtocolService,
|
||||
@inject(TYPES.ElectronUpdater)
|
||||
private readonly updater: ElectronUpdater,
|
||||
@inject(TYPES.IpcHandlerService)
|
||||
private readonly ipcHandler: IpcHandlerService,
|
||||
@inject(TYPES.DatabaseService)
|
||||
private readonly dataService: DatabaseService,
|
||||
private readonly ipc: IpcHandlerService,
|
||||
@inject(TYPES.TypeORM)
|
||||
private readonly db: TypeORM,
|
||||
@inject(TYPES.WebviewService)
|
||||
private readonly webview: WebviewService,
|
||||
@inject(TYPES.VideoRepository)
|
||||
private readonly videoRepository: VideoRepository,
|
||||
@inject(TYPES.DevToolsService)
|
||||
private readonly devTools: DevToolsService,
|
||||
@inject(TYPES.WebService)
|
||||
private readonly webService: WebService,
|
||||
@inject(TYPES.StoreService)
|
||||
private readonly storeService: StoreService
|
||||
@inject(TYPES.ElectronDevtools)
|
||||
private readonly devTools: ElectronDevtools,
|
||||
@inject(TYPES.ElectronStore)
|
||||
private readonly store: ElectronStore,
|
||||
) {}
|
||||
|
||||
private async seriveInit(): Promise<void> {
|
||||
this.protocolService.create();
|
||||
await this.dataService.init();
|
||||
private async serviceInit(): Promise<void> {
|
||||
this.mainWindow.init();
|
||||
this.ipcHandler.init();
|
||||
this.updateService.init();
|
||||
this.webview.init(), this.devTools.init();
|
||||
this.webService.init();
|
||||
this.webview.init();
|
||||
}
|
||||
|
||||
private async vendorInit() {
|
||||
await this.db.init();
|
||||
this.updater.init();
|
||||
this.devTools.init();
|
||||
}
|
||||
|
||||
async init(): Promise<void> {
|
||||
await this.seriveInit();
|
||||
this.protocol.create();
|
||||
this.ipc.init();
|
||||
|
||||
// vendor
|
||||
await this.vendorInit();
|
||||
// service
|
||||
await this.serviceInit();
|
||||
|
||||
app.on("activate", () => {
|
||||
this.mainWindow.init();
|
||||
@@ -67,7 +68,7 @@ export default class ElectronApp implements App {
|
||||
}
|
||||
|
||||
initAppTheme(): void {
|
||||
const theme = this.storeService.get("theme");
|
||||
const theme = this.store.get("theme");
|
||||
nativeTheme.themeSource = theme;
|
||||
}
|
||||
|
||||
@@ -93,7 +94,7 @@ export default class ElectronApp implements App {
|
||||
const videoIds = videos.map((video) => video.id);
|
||||
await this.videoRepository.changeVideoStatus(
|
||||
videoIds,
|
||||
DownloadStatus.Failed
|
||||
DownloadStatus.Failed,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +1,37 @@
|
||||
import { IpcMainEvent } from "electron/main";
|
||||
import { inject, injectable } from "inversify";
|
||||
import { handle } from "../helper/decorator";
|
||||
import { handle } from "../helper";
|
||||
import {
|
||||
StoreService,
|
||||
type Controller,
|
||||
VideoRepository,
|
||||
DownloadItem,
|
||||
DownloadItemPagination,
|
||||
DownloadService,
|
||||
Task,
|
||||
DownloadStatus,
|
||||
} from "../interfaces";
|
||||
import { TYPES } from "../types";
|
||||
import { spawnDownload } from "helper";
|
||||
import MainWindowServiceImpl from "windows/Main";
|
||||
import MainWindow from "../windows/MainWindow";
|
||||
import ElectronStore from "../vendor/ElectronStore";
|
||||
import DownloadService from "../services/DownloadService";
|
||||
import VideoRepository from "../repository/VideoRepository";
|
||||
|
||||
@injectable()
|
||||
export default class DownloadController implements Controller {
|
||||
constructor(
|
||||
@inject(TYPES.StoreService)
|
||||
private readonly storeService: StoreService,
|
||||
@inject(TYPES.ElectronStore)
|
||||
private readonly store: ElectronStore,
|
||||
@inject(TYPES.VideoRepository)
|
||||
private readonly videoRepository: VideoRepository,
|
||||
@inject(TYPES.DownloadService)
|
||||
private readonly downloadService: DownloadService,
|
||||
@inject(TYPES.MainWindowService)
|
||||
private readonly mainWindow: MainWindowServiceImpl
|
||||
@inject(TYPES.MainWindow)
|
||||
private readonly mainWindow: MainWindow,
|
||||
) {}
|
||||
|
||||
@handle("show-download-dialog")
|
||||
async showDownloadDialog(e: IpcMainEvent, data: DownloadItem) {
|
||||
this.mainWindow.window?.webContents.send("show-download-dialog", data);
|
||||
}
|
||||
|
||||
@handle("add-download-item")
|
||||
async addDownloadItem(e: IpcMainEvent, video: DownloadItem) {
|
||||
const item = await this.videoRepository.addVideo(video);
|
||||
@@ -36,6 +40,14 @@ export default class DownloadController implements Controller {
|
||||
return item;
|
||||
}
|
||||
|
||||
@handle("add-download-items")
|
||||
async addDownloadItems(e: IpcMainEvent, videos: DownloadItem[]) {
|
||||
const items = await this.videoRepository.addVideos(videos);
|
||||
// 这里向页面发送消息,通知页面更新
|
||||
this.mainWindow.window?.webContents.send("download-item-notifier", items);
|
||||
return items;
|
||||
}
|
||||
|
||||
@handle("edit-download-item")
|
||||
async editDownloadItem(e: IpcMainEvent, video: DownloadItem) {
|
||||
const item = await this.videoRepository.editVideo(video);
|
||||
@@ -53,7 +65,8 @@ export default class DownloadController implements Controller {
|
||||
|
||||
@handle("get-download-items")
|
||||
async getDownloadItems(e: IpcMainEvent, pagination: DownloadItemPagination) {
|
||||
return await this.videoRepository.findVideos(pagination);
|
||||
const videos = await this.videoRepository.findVideos(pagination);
|
||||
return videos;
|
||||
}
|
||||
|
||||
@handle("start-download")
|
||||
@@ -63,22 +76,22 @@ export default class DownloadController implements Controller {
|
||||
if (!video) {
|
||||
return Promise.reject("没有找到该视频");
|
||||
}
|
||||
const { name, url, headers } = video;
|
||||
const local = this.storeService.get("local");
|
||||
const { name, url, headers, type } = video;
|
||||
const local = this.store.get("local");
|
||||
|
||||
// 从配置中添加参数
|
||||
const deleteSegments = this.storeService.get("deleteSegments");
|
||||
const deleteSegments = this.store.get("deleteSegments");
|
||||
|
||||
const task: Task = {
|
||||
id: vid,
|
||||
params: {
|
||||
url,
|
||||
type,
|
||||
local,
|
||||
name,
|
||||
headers,
|
||||
deleteSegments,
|
||||
},
|
||||
process: spawnDownload,
|
||||
};
|
||||
await this.videoRepository.changeVideoStatus(vid, DownloadStatus.Watting);
|
||||
this.downloadService.addTask(task);
|
||||
|
||||
@@ -8,45 +8,39 @@ import {
|
||||
shell,
|
||||
clipboard,
|
||||
} from "electron";
|
||||
import { Favorite } from "entity/Favorite";
|
||||
import { convertToAudio } from "helper";
|
||||
import { db, workspace } from "helper/variables";
|
||||
import { Favorite } from "../entity/Favorite";
|
||||
import { convertToAudio, db, workspace } from "../helper";
|
||||
import { inject, injectable } from "inversify";
|
||||
import { AppStore, EnvPath } from "main";
|
||||
import { AppStore, EnvPath } from "../main";
|
||||
import path from "path";
|
||||
import { handle, getLocalIP } from "../helper";
|
||||
import {
|
||||
StoreService,
|
||||
type Controller,
|
||||
FavoriteRepository,
|
||||
MainWindowService,
|
||||
VideoRepository,
|
||||
BrowserWindowService,
|
||||
PlayerWindowService,
|
||||
WebviewService,
|
||||
} from "../interfaces";
|
||||
import { type Controller } from "../interfaces";
|
||||
import { TYPES } from "../types";
|
||||
import fs from "fs-extra";
|
||||
import MainWindow from "../windows/MainWindow";
|
||||
import BrowserWindow from "../windows/BrowserWindow";
|
||||
import ElectronStore from "../vendor/ElectronStore";
|
||||
import WebviewService from "../services/WebviewService";
|
||||
import FavoriteRepository from "../repository/FavoriteRepository";
|
||||
import VideoRepository from "../repository/VideoRepository";
|
||||
|
||||
@injectable()
|
||||
export default class HomeController implements Controller {
|
||||
private sharedState: Record<string, any> = {};
|
||||
|
||||
constructor(
|
||||
@inject(TYPES.StoreService)
|
||||
private readonly storeService: StoreService,
|
||||
@inject(TYPES.ElectronStore)
|
||||
private readonly store: ElectronStore,
|
||||
@inject(TYPES.FavoriteRepository)
|
||||
private readonly favoriteRepository: FavoriteRepository,
|
||||
@inject(TYPES.MainWindowService)
|
||||
private readonly mainWindow: MainWindowService,
|
||||
@inject(TYPES.MainWindow)
|
||||
private readonly mainWindow: MainWindow,
|
||||
@inject(TYPES.VideoRepository)
|
||||
private readonly videoRepository: VideoRepository,
|
||||
@inject(TYPES.BrowserWindowService)
|
||||
private readonly browserWindow: BrowserWindowService,
|
||||
@inject(TYPES.PlayerWindowService)
|
||||
private readonly playerWindow: PlayerWindowService,
|
||||
@inject(TYPES.BrowserWindow)
|
||||
private readonly browserWindow: BrowserWindow,
|
||||
@inject(TYPES.WebviewService)
|
||||
private readonly webviewService: WebviewService
|
||||
private readonly webviewService: WebviewService,
|
||||
) {}
|
||||
|
||||
@handle("get-env-path")
|
||||
@@ -56,7 +50,7 @@ export default class HomeController implements Controller {
|
||||
dbPath: db,
|
||||
workspace: workspace,
|
||||
platform: process.platform,
|
||||
local: this.storeService.get("local"),
|
||||
local: this.store.get("local"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -77,7 +71,7 @@ export default class HomeController implements Controller {
|
||||
|
||||
@handle("get-app-store")
|
||||
getAppStore() {
|
||||
return this.storeService.store;
|
||||
return this.store.store;
|
||||
}
|
||||
|
||||
@handle("on-favorite-item-context-menu")
|
||||
@@ -121,7 +115,7 @@ export default class HomeController implements Controller {
|
||||
|
||||
if (!result.canceled) {
|
||||
const dir = result.filePaths[0];
|
||||
this.storeService.set("local", dir);
|
||||
this.store.set("local", dir);
|
||||
return dir;
|
||||
}
|
||||
return "";
|
||||
@@ -131,12 +125,12 @@ export default class HomeController implements Controller {
|
||||
async setAppStore(e: IpcMainEvent, key: keyof AppStore, val: any) {
|
||||
// useProxy
|
||||
if (key === "useProxy") {
|
||||
const proxy = this.storeService.get("proxy");
|
||||
const proxy = this.store.get("proxy");
|
||||
this.webviewService.setProxy(val, proxy);
|
||||
}
|
||||
// proxy
|
||||
if (key === "proxy") {
|
||||
const useProxy = this.storeService.get("useProxy");
|
||||
const useProxy = this.store.get("useProxy");
|
||||
useProxy && this.webviewService.setProxy(true, val);
|
||||
}
|
||||
// block
|
||||
@@ -152,7 +146,7 @@ export default class HomeController implements Controller {
|
||||
this.webviewService.setUserAgent(val);
|
||||
}
|
||||
|
||||
this.storeService.set(key, val);
|
||||
this.store.set(key, val);
|
||||
}
|
||||
|
||||
@handle("open-dir")
|
||||
@@ -218,7 +212,7 @@ export default class HomeController implements Controller {
|
||||
@handle("convert-to-audio")
|
||||
async convertToAudio(e: IpcMainEvent, id: number) {
|
||||
const video = await this.videoRepository.findVideo(id);
|
||||
const local = this.storeService.get("local");
|
||||
const local = this.store.get("local");
|
||||
const input = path.join(local, `${video?.name}.mp4`);
|
||||
const output = path.join(local, `${video?.name}.mp3`);
|
||||
|
||||
@@ -240,13 +234,7 @@ export default class HomeController implements Controller {
|
||||
// 关闭浏览器窗口
|
||||
this.browserWindow.hideWindow();
|
||||
// 修改设置中的属性
|
||||
this.storeService.set("openInNewWindow", false);
|
||||
}
|
||||
|
||||
@handle("open-player-window")
|
||||
async openPlayerWindow(event: IpcMainEvent, id: number) {
|
||||
// 打开播放器窗口
|
||||
this.playerWindow.openWindow(id);
|
||||
this.store.set("openInNewWindow", false);
|
||||
}
|
||||
|
||||
@handle("get-local-ip")
|
||||
@@ -263,4 +251,10 @@ export default class HomeController implements Controller {
|
||||
async setSharedState(event: IpcMainEvent, state: any) {
|
||||
this.sharedState = state;
|
||||
}
|
||||
|
||||
@handle("get-download-log")
|
||||
async getDownloadLog(event: IpcMainEvent, id: number) {
|
||||
const video = await this.videoRepository.findVideo(id);
|
||||
return video?.log || "";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,26 @@
|
||||
import { IpcMainEvent } from "electron";
|
||||
import {
|
||||
IpcMainEvent,
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuItemConstructorOptions,
|
||||
} from "electron";
|
||||
import { inject, injectable } from "inversify";
|
||||
import { handle } from "../helper/decorator";
|
||||
import { type Controller, WebviewService, StoreService } from "../interfaces";
|
||||
import { handle } from "../helper";
|
||||
import { type Controller } from "../interfaces";
|
||||
import { TYPES } from "../types";
|
||||
import WebviewService from "../services/WebviewService";
|
||||
import ElectronStore from "../vendor/ElectronStore";
|
||||
import { SniffingHelper } from "../services/SniffingHelperService";
|
||||
|
||||
@injectable()
|
||||
export default class WebviewController implements Controller {
|
||||
constructor(
|
||||
@inject(TYPES.WebviewService)
|
||||
private readonly webview: WebviewService,
|
||||
@inject(TYPES.StoreService)
|
||||
private readonly storeService: StoreService
|
||||
@inject(TYPES.ElectronStore)
|
||||
private readonly store: ElectronStore,
|
||||
@inject(TYPES.SniffingHelper)
|
||||
private readonly sniffingHelper: SniffingHelper,
|
||||
) {}
|
||||
|
||||
@handle("set-webview-bounds")
|
||||
@@ -23,6 +33,23 @@ export default class WebviewController implements Controller {
|
||||
await this.webview.loadURL(url);
|
||||
}
|
||||
|
||||
@handle("webview-url-contextmenu")
|
||||
async webviewUrlContextMenu() {
|
||||
const template: Array<MenuItemConstructorOptions | MenuItem> = [
|
||||
{
|
||||
label: "复制",
|
||||
role: "copy",
|
||||
},
|
||||
{
|
||||
label: "粘贴",
|
||||
role: "paste",
|
||||
},
|
||||
];
|
||||
|
||||
const menu = Menu.buildFromTemplate(template);
|
||||
menu.popup();
|
||||
}
|
||||
|
||||
@handle("webview-go-back")
|
||||
async webviewGoBack(): Promise<boolean> {
|
||||
return this.webview.goBack();
|
||||
@@ -51,6 +78,11 @@ export default class WebviewController implements Controller {
|
||||
@handle("webview-change-user-agent")
|
||||
async webviewChangeUserAgent(e: IpcMainEvent, isMobile: boolean) {
|
||||
this.webview.setUserAgent(isMobile);
|
||||
this.storeService.set("isMobile", isMobile);
|
||||
this.store.set("isMobile", isMobile);
|
||||
}
|
||||
|
||||
@handle("plugin-ready")
|
||||
async pluginReady() {
|
||||
this.sniffingHelper.pluginReady();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { ipcMain } from "electron";
|
||||
import { inject, injectable, multiInject } from "inversify";
|
||||
import { Controller } from "../interfaces";
|
||||
import { TYPES } from "../types";
|
||||
import ElectronLogger from "../vendor/ElectronLogger";
|
||||
import { error, success } from "../helper/utils";
|
||||
|
||||
@injectable()
|
||||
export default class IpcHandlerService {
|
||||
constructor(
|
||||
@multiInject(TYPES.Controller)
|
||||
private readonly controllers: Controller[],
|
||||
@inject(TYPES.ElectronLogger)
|
||||
private readonly logger: ElectronLogger,
|
||||
) {}
|
||||
|
||||
private registerIpc(
|
||||
controller: Controller,
|
||||
propertyKey: string | symbol,
|
||||
): void {
|
||||
const property = controller[propertyKey];
|
||||
if (typeof property !== "function") return;
|
||||
|
||||
const channel: string = Reflect.getMetadata(
|
||||
"ipc-channel",
|
||||
controller,
|
||||
propertyKey,
|
||||
);
|
||||
if (!channel) return;
|
||||
|
||||
const ipcMethod: "on" | "handle" = Reflect.getMetadata(
|
||||
"ipc-method",
|
||||
controller,
|
||||
propertyKey,
|
||||
);
|
||||
if (!ipcMethod) return;
|
||||
|
||||
ipcMain[ipcMethod](channel, async (...args: unknown[]) => {
|
||||
try {
|
||||
let res = property.call(controller, ...args);
|
||||
if (res.then) {
|
||||
res = await res;
|
||||
}
|
||||
return success(res);
|
||||
} catch (e: unknown) {
|
||||
this.logger.error("处理 ipc 事件时异常: ", e);
|
||||
if (e instanceof Error) {
|
||||
return error(e.message);
|
||||
} else {
|
||||
return error(String(e));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
init(): void {
|
||||
for (const controller of this.controllers) {
|
||||
const Class = Object.getPrototypeOf(controller);
|
||||
Object.getOwnPropertyNames(Class).forEach((propertyKey) =>
|
||||
this.registerIpc(controller, propertyKey),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { protocol } from "electron";
|
||||
import isDev from "electron-is-dev";
|
||||
import { pathExists, readFile } from "fs-extra";
|
||||
import { injectable } from "inversify";
|
||||
import { join } from "path";
|
||||
import { URL } from "url";
|
||||
import { defaultScheme } from "../helper";
|
||||
import mime from "mime-types";
|
||||
|
||||
@injectable()
|
||||
export default class ProtocolService {
|
||||
create(): void {
|
||||
if (isDev) return;
|
||||
|
||||
protocol.handle(defaultScheme, async (req) => {
|
||||
const pathName = new URL(req.url).pathname;
|
||||
let filePath = join(__dirname, "../renderer", pathName);
|
||||
const fileExist = await pathExists(filePath);
|
||||
if (!fileExist) {
|
||||
// 如果没有找到文件,直接返回 index.html , react history 模式
|
||||
filePath = join(__dirname, "../renderer/index.html");
|
||||
}
|
||||
const mimeType = mime.lookup(filePath);
|
||||
const data = await readFile(filePath);
|
||||
return new Response(data, {
|
||||
headers: { "Content-Type": mimeType || "text/html" },
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export interface Vendor {
|
||||
init(): Promise<void>;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DownloadStatus } from "interfaces";
|
||||
import { DownloadStatus, DownloadType } from "../interfaces";
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
@@ -17,9 +17,17 @@ export class Video {
|
||||
@Column({
|
||||
type: "text",
|
||||
nullable: true,
|
||||
unique: true,
|
||||
})
|
||||
name: string;
|
||||
|
||||
@Column({
|
||||
type: "text",
|
||||
nullable: false,
|
||||
default: DownloadType.m3u8,
|
||||
})
|
||||
type: DownloadType;
|
||||
|
||||
@Column({
|
||||
type: "text",
|
||||
nullable: false,
|
||||
@@ -46,6 +54,12 @@ export class Video {
|
||||
})
|
||||
status: DownloadStatus;
|
||||
|
||||
@Column({
|
||||
type: "text",
|
||||
default: "",
|
||||
})
|
||||
log: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdDate: Date;
|
||||
|
||||
|
||||
@@ -1,205 +0,0 @@
|
||||
import { execa } from "execa";
|
||||
import { macDownloaderPath, winDownloaderPath } from "./variables";
|
||||
import iconv from "iconv-lite";
|
||||
import { formatHeaders, stripColors } from "./utils";
|
||||
import { DownloadParams, DownloadProgress } from "interfaces";
|
||||
|
||||
export const spawnDownload = (params: DownloadParams): Promise<void> => {
|
||||
if (process.platform === "win32") {
|
||||
return winSpawnDownload(params);
|
||||
} else {
|
||||
return macSpawnDownload(params);
|
||||
}
|
||||
};
|
||||
|
||||
const winSpawnDownload = async (params: DownloadParams): Promise<void> => {
|
||||
const {
|
||||
id,
|
||||
abortSignal,
|
||||
url,
|
||||
local,
|
||||
name,
|
||||
deleteSegments,
|
||||
headers,
|
||||
callback,
|
||||
} = params;
|
||||
const progressReg = /Progress:\s(\d+)\/(\d+)\s\(.+?\).+?\((.+?\/s).*?\)/g;
|
||||
const isLiveReg = /识别为直播流, 开始录制/g;
|
||||
const startDownloadReg = /开始下载文件/g;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const spawnParams = [url, "--workDir", local, "--saveName", name];
|
||||
|
||||
if (headers) {
|
||||
spawnParams.push("--headers", formatHeaders(headers));
|
||||
}
|
||||
|
||||
if (deleteSegments) {
|
||||
spawnParams.push("--enableDelAfterDone");
|
||||
}
|
||||
|
||||
const downloader = execa(winDownloaderPath, spawnParams, {
|
||||
signal: abortSignal.signal,
|
||||
});
|
||||
|
||||
let isLive = false;
|
||||
downloader.stdout?.on("data", (data) => {
|
||||
const str = iconv.decode(Buffer.from(data), "gbk");
|
||||
str.split("\n").forEach((item) => {
|
||||
if (item.trim() == "") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isLiveReg.test(item) || startDownloadReg.test(item)) {
|
||||
callback({
|
||||
id,
|
||||
type: "ready",
|
||||
isLive,
|
||||
cur: "",
|
||||
total: "",
|
||||
speed: "",
|
||||
});
|
||||
isLive = true;
|
||||
}
|
||||
|
||||
const result = progressReg.exec(item);
|
||||
if (!result) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [, cur, total, speed] = result;
|
||||
const progress: DownloadProgress = {
|
||||
id,
|
||||
type: "progress",
|
||||
cur,
|
||||
total,
|
||||
speed,
|
||||
isLive,
|
||||
};
|
||||
callback(progress);
|
||||
});
|
||||
});
|
||||
|
||||
downloader.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
|
||||
downloader.on("close", (code) => {
|
||||
if (code === 0) {
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error("未知错误"));
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const macSpawnDownload = (params: DownloadParams): Promise<void> => {
|
||||
const {
|
||||
id,
|
||||
abortSignal,
|
||||
url,
|
||||
local,
|
||||
name,
|
||||
deleteSegments,
|
||||
headers,
|
||||
callback,
|
||||
} = params;
|
||||
// const progressReg = /([\d.]+)% .*? ([\d.\w]+?) /g;
|
||||
const progressReg = /([\d.]+)%/g;
|
||||
const errorReg = /ERROR/g;
|
||||
const startDownloadReg = /保存文件名:/g;
|
||||
const isLiveReg = /检测到直播流/g;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const spawnParams = [
|
||||
url,
|
||||
"--tmp-dir",
|
||||
local,
|
||||
"--save-dir",
|
||||
local,
|
||||
"--save-name",
|
||||
name,
|
||||
"--auto-select",
|
||||
];
|
||||
|
||||
if (headers) {
|
||||
const h: Record<string, unknown> = JSON.parse(headers);
|
||||
Object.entries(h).forEach(([k, v]) => {
|
||||
spawnParams.push("-H", `${k}: ${v}`);
|
||||
});
|
||||
}
|
||||
|
||||
if (deleteSegments) {
|
||||
spawnParams.push("--del-after-done");
|
||||
}
|
||||
|
||||
const downloader = execa(macDownloaderPath, spawnParams, {
|
||||
signal: abortSignal.signal,
|
||||
});
|
||||
|
||||
let isLive = false;
|
||||
downloader.stdout?.on("data", (data) => {
|
||||
const str = String(Buffer.from(data));
|
||||
str.split("\n").forEach((item) => {
|
||||
if (item.trim() == "") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isLiveReg.test(item) || startDownloadReg.test(item)) {
|
||||
callback({
|
||||
id,
|
||||
type: "ready",
|
||||
isLive,
|
||||
cur: "",
|
||||
total: "",
|
||||
speed: "",
|
||||
});
|
||||
isLive = true;
|
||||
}
|
||||
|
||||
const log = stripColors(item);
|
||||
|
||||
if (errorReg.test(log)) {
|
||||
reject(new Error(log));
|
||||
return;
|
||||
}
|
||||
|
||||
const result = progressReg.exec(log);
|
||||
if (!result) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [, precentage, speed] = result;
|
||||
const cur = String(Number(precentage) * 10);
|
||||
if (cur === "0") {
|
||||
return;
|
||||
}
|
||||
|
||||
const total = "1000";
|
||||
// FIXME: 无法获取是否为直播流
|
||||
const progress: DownloadProgress = {
|
||||
id,
|
||||
type: "progress",
|
||||
cur,
|
||||
total,
|
||||
speed,
|
||||
isLive,
|
||||
};
|
||||
callback(progress);
|
||||
});
|
||||
});
|
||||
|
||||
downloader.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
|
||||
downloader.on("close", (code) => {
|
||||
if (code === 0) {
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error("未知错误"));
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -3,7 +3,7 @@ import { ffmpegPath } from "./variables";
|
||||
|
||||
export const convertToAudio = async (
|
||||
input: string,
|
||||
output: string
|
||||
output: string,
|
||||
): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const ffmpeg = spawn(ffmpegPath, [
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
import axios from "axios";
|
||||
import https from "https";
|
||||
|
||||
const agent = new https.Agent({
|
||||
rejectUnauthorized: false,
|
||||
});
|
||||
|
||||
// 创建 axios 实例,并指定自定义的 HTTPS Agent
|
||||
const instance = axios.create({
|
||||
httpsAgent: agent,
|
||||
});
|
||||
|
||||
export default instance;
|
||||
@@ -1,4 +1,6 @@
|
||||
import os from "os";
|
||||
import fetch from "node-fetch";
|
||||
import https from "https";
|
||||
|
||||
export function getLocalIP() {
|
||||
const interfaces = os.networkInterfaces();
|
||||
@@ -11,7 +13,7 @@ export function getLocalIP() {
|
||||
|
||||
// 过滤出 IPv4 地址且非回环地址
|
||||
const filteredIface = iface.filter(
|
||||
(details) => details.family === "IPv4" && !details.internal
|
||||
(details) => details.family === "IPv4" && !details.internal,
|
||||
);
|
||||
|
||||
if (filteredIface.length > 0) {
|
||||
@@ -23,9 +25,17 @@ export function getLocalIP() {
|
||||
return localIP;
|
||||
}
|
||||
|
||||
export { sleep } from "./utils";
|
||||
function fetchWrapper(url: string) {
|
||||
const options = {
|
||||
agent: new https.Agent({
|
||||
rejectUnauthorized: false,
|
||||
}),
|
||||
};
|
||||
return fetch(url, options);
|
||||
}
|
||||
|
||||
export { sleep, formatHeaders } from "./utils";
|
||||
export * from "./variables";
|
||||
export { on, handle } from "./decorator";
|
||||
export { spawnDownload } from "./download";
|
||||
export { convertToAudio } from "./ffmpeg";
|
||||
export { default as http } from "./http";
|
||||
export { fetchWrapper as fetch };
|
||||
|
||||
@@ -4,14 +4,6 @@ export async function sleep(second = 1): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, second * 1000));
|
||||
}
|
||||
|
||||
export function stripColors(str: string) {
|
||||
// 匹配控制台颜色字符的正则表达式
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const colorRegex = /\x1b\[(\d+)(;\d+)*m/g;
|
||||
// 将所有颜色字符替换为空字符串
|
||||
return str.replace(colorRegex, "");
|
||||
}
|
||||
|
||||
export function formatHeaders(headersStr: string): string {
|
||||
const headers: Record<string, any> | null = JSON.parse(headersStr);
|
||||
if (!headers) return "";
|
||||
@@ -22,3 +14,25 @@ export function formatHeaders(headersStr: string): string {
|
||||
}
|
||||
|
||||
export const event = new EventEmitter();
|
||||
|
||||
export interface IpcResponse {
|
||||
code: number;
|
||||
message: string;
|
||||
data: Record<string, any> | null;
|
||||
}
|
||||
|
||||
export function success(data: Record<string, any>): IpcResponse {
|
||||
return {
|
||||
code: 0,
|
||||
message: "success",
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
export function error(message = "fail"): IpcResponse {
|
||||
return {
|
||||
code: -1,
|
||||
message,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,28 +1,45 @@
|
||||
import { app } from "electron";
|
||||
import isDev from "electron-is-dev";
|
||||
import path from "path";
|
||||
import { resolve } from "path";
|
||||
|
||||
const appPath = app.getAppPath();
|
||||
export const appData = app.getPath("appData");
|
||||
export const download = app.getPath("downloads");
|
||||
|
||||
export const isMac = process.platform === "darwin";
|
||||
export const isWin = process.platform === "win32";
|
||||
|
||||
if (!isDev) {
|
||||
global.__bin__ = path.resolve(app.getAppPath(), "../bin");
|
||||
global.__bin__ = resolve(appPath, "../bin");
|
||||
}
|
||||
|
||||
export const appData = app.getPath("appData");
|
||||
export const appName = process.env.APP_NAME || "electron-template";
|
||||
export const workspace = path.resolve(appData, appName);
|
||||
export function resolveStatic(path: string) {
|
||||
const relativePath = isDev ? "../.." : "..";
|
||||
return resolve(appPath, relativePath, path);
|
||||
}
|
||||
export function resolveBin(path: string) {
|
||||
if (isWin) {
|
||||
path += ".exe";
|
||||
}
|
||||
return resolve(__bin__, path);
|
||||
}
|
||||
|
||||
export const appName = process.env.APP_NAME || "mediago";
|
||||
export const workspace = resolve(appData, appName);
|
||||
export const defaultScheme = "mediago";
|
||||
export const download = app.getPath("downloads");
|
||||
export const PERSIST_MEDIAGO = "persist:mediago";
|
||||
export const PERSIST_WEBVIEW = "persist:webview";
|
||||
export const db = path.resolve(workspace, "app.db");
|
||||
export const macDownloaderPath = path.resolve(__bin__, "N_m3u8DL-RE");
|
||||
export const winDownloaderPath = path.resolve(__bin__, "N_m3u8DL-CLI.exe");
|
||||
export const ffmpegPath =
|
||||
process.platform === "win32"
|
||||
? path.resolve(__bin__, "ffmpeg.exe")
|
||||
: path.resolve(__bin__, "ffmpeg");
|
||||
export const mobilePath = isDev
|
||||
? path.resolve(app.getAppPath(), "../../mobile")
|
||||
: path.resolve(app.getAppPath(), "../mobile");
|
||||
export const db = resolve(workspace, "app.db");
|
||||
|
||||
// bin path
|
||||
const downloaderBinName = isWin ? "N_m3u8DL-CLI" : "N_m3u8DL-RE";
|
||||
export const ffmpegPath = resolveBin("ffmpeg");
|
||||
export const biliDownloaderBin = resolveBin("BBDown");
|
||||
export const m3u8DownloaderBin = resolveBin(downloaderBinName);
|
||||
export const videoServerBin = resolveBin("server");
|
||||
|
||||
// plugin path
|
||||
export const pluginPath = resolveStatic("plugin/index.js");
|
||||
|
||||
// user agent
|
||||
export const pcUA =
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import "reflect-metadata";
|
||||
import { app, protocol } from "electron";
|
||||
import { defaultScheme } from "./helper/variables";
|
||||
import { type App } from "./interfaces";
|
||||
import { defaultScheme } from "./helper";
|
||||
import { container } from "./inversify.config";
|
||||
import { TYPES } from "./types";
|
||||
import ElectronApp from "./app";
|
||||
|
||||
const gotTheLock = app.requestSingleInstanceLock();
|
||||
const start = async (): Promise<void> => {
|
||||
@@ -21,7 +21,7 @@ const start = async (): Promise<void> => {
|
||||
},
|
||||
]);
|
||||
await app.whenReady();
|
||||
const mediago = container.get<App>(TYPES.App);
|
||||
const mediago = container.get<ElectronApp>(TYPES.ElectronApp);
|
||||
mediago.init();
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
|
||||
+14
-121
@@ -1,68 +1,13 @@
|
||||
import { type BrowserWindow, BrowserView } from "electron";
|
||||
import { ElectronLog } from "electron-log";
|
||||
import Store from "electron-store";
|
||||
import { Favorite } from "entity/Favorite";
|
||||
import { Video } from "entity/Video";
|
||||
import EventEmitter from "events";
|
||||
import { AppStore } from "main";
|
||||
import { DataSource, EntityManager, UpdateResult, DeleteResult } from "typeorm";
|
||||
|
||||
export interface MainWindowService {
|
||||
window: BrowserWindow | null;
|
||||
init: () => void;
|
||||
}
|
||||
|
||||
export interface PlayerWindowService {
|
||||
openWindow: (id: number) => void;
|
||||
}
|
||||
|
||||
export interface BrowserWindowService {
|
||||
window: BrowserWindow | null;
|
||||
showWindow: () => void;
|
||||
hideWindow: () => void;
|
||||
}
|
||||
|
||||
export interface App {
|
||||
init: () => void;
|
||||
}
|
||||
|
||||
export interface IpcHandlerService {
|
||||
init: () => void;
|
||||
}
|
||||
|
||||
export interface ProtocolService {
|
||||
create: () => void;
|
||||
}
|
||||
|
||||
export interface UpdateService {
|
||||
init: () => void;
|
||||
}
|
||||
|
||||
export interface DatabaseService {
|
||||
manager: EntityManager;
|
||||
appDataSource: DataSource;
|
||||
init: () => void;
|
||||
}
|
||||
|
||||
export type Controller = Record<string | symbol, any>;
|
||||
|
||||
export interface LoggerService {
|
||||
logger: ElectronLog;
|
||||
info: (...args: any[]) => void;
|
||||
error: (...args: any[]) => void;
|
||||
warn: (...args: any[]) => void;
|
||||
debug: (...args: any[]) => void;
|
||||
}
|
||||
|
||||
export interface StoreService extends Store<AppStore> {
|
||||
init: () => void;
|
||||
}
|
||||
|
||||
export interface DownloadItem {
|
||||
id?: number;
|
||||
id: number;
|
||||
type: DownloadType;
|
||||
name: string;
|
||||
url: string;
|
||||
headers: string;
|
||||
headers?: string;
|
||||
status?: DownloadStatus;
|
||||
isLive?: boolean;
|
||||
}
|
||||
|
||||
export enum DownloadFilter {
|
||||
@@ -81,53 +26,6 @@ export interface VideoResponse {
|
||||
list: DownloadItem[];
|
||||
}
|
||||
|
||||
export interface VideoRepository {
|
||||
addVideo: (video: DownloadItem) => Promise<Video>;
|
||||
editVideo: (video: DownloadItem) => Promise<Video>;
|
||||
findVideos: (pagiantion: DownloadItemPagination) => Promise<VideoResponse>;
|
||||
findVideo: (id: number) => Promise<Video | null>;
|
||||
changeVideoStatus: (
|
||||
id: number | number[],
|
||||
status: DownloadStatus
|
||||
) => Promise<UpdateResult>;
|
||||
findWattingAndDownloadingVideos: () => Promise<Video[]>;
|
||||
deleteDownloadItem: (id: number) => Promise<DeleteResult>;
|
||||
findAllVideos(): Promise<Video[]>;
|
||||
changeVideoIsLive: (
|
||||
id: number | number[],
|
||||
isLive: boolean
|
||||
) => Promise<UpdateResult>;
|
||||
findVideoByUrl: (url: string) => Promise<Video | null>;
|
||||
}
|
||||
|
||||
export interface FavoriteRepository {
|
||||
findFavorites: () => Promise<Favorite[]>;
|
||||
addFavorite: (favorite: Favorite) => Promise<Favorite>;
|
||||
removeFavorite: (id: number) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface WebviewService {
|
||||
view: BrowserView;
|
||||
init: () => void;
|
||||
getBounds: () => Electron.Rectangle;
|
||||
setAutoResize: (options: Electron.AutoResizeOptions) => void;
|
||||
setBackgroundColor: (color: string) => void;
|
||||
setBounds: (bounds: Electron.Rectangle) => void;
|
||||
loadURL: (url?: string) => Promise<void>;
|
||||
goBack: () => Promise<boolean>;
|
||||
reload: () => Promise<void>;
|
||||
goHome: () => Promise<void>;
|
||||
hide: () => void;
|
||||
show: () => void;
|
||||
setProxy: (useProxy: boolean, proxy: string) => void;
|
||||
setBlocking: (enableBlocking: boolean) => void;
|
||||
setUserAgent: (isMobile: boolean) => void;
|
||||
}
|
||||
|
||||
export interface WebService {
|
||||
init: () => void;
|
||||
}
|
||||
|
||||
export enum DownloadStatus {
|
||||
Ready = "ready",
|
||||
Watting = "watting",
|
||||
@@ -137,37 +35,32 @@ export enum DownloadStatus {
|
||||
Failed = "failed",
|
||||
}
|
||||
|
||||
export interface DownloadService extends EventEmitter {
|
||||
addTask: (task: Task) => Promise<void>;
|
||||
stopTask: (id: number) => Promise<void>;
|
||||
}
|
||||
|
||||
export type Task = {
|
||||
id: number;
|
||||
params: Omit<DownloadParams, "id" | "abortSignal">;
|
||||
process: (params: DownloadParams) => Promise<void>;
|
||||
params: Omit<DownloadParams, "id" | "abortSignal" | "callback">;
|
||||
};
|
||||
|
||||
export interface DownloadProgress {
|
||||
id: number;
|
||||
type: string;
|
||||
cur: string;
|
||||
total: string;
|
||||
percent: string;
|
||||
speed: string;
|
||||
isLive: boolean;
|
||||
}
|
||||
|
||||
export enum DownloadType {
|
||||
m3u8 = "m3u8",
|
||||
bilibili = "bilibili",
|
||||
}
|
||||
export interface DownloadParams {
|
||||
id: number;
|
||||
type: DownloadType;
|
||||
url: string;
|
||||
local: string;
|
||||
name: string;
|
||||
headers: string;
|
||||
headers?: string;
|
||||
abortSignal: AbortController;
|
||||
proxy?: string;
|
||||
deleteSegments?: boolean;
|
||||
callback: (progress: DownloadProgress) => void;
|
||||
}
|
||||
|
||||
export interface DevToolsService {
|
||||
init: () => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -1,42 +1,24 @@
|
||||
import DownloadController from "controller/DownloadController";
|
||||
import HomeController from "controller/HomeController";
|
||||
import WebviewController from "controller/WebviewController";
|
||||
import DownloadController from "./controller/DownloadController";
|
||||
import HomeController from "./controller/HomeController";
|
||||
import WebviewController from "./controller/WebviewController";
|
||||
import { Container } from "inversify";
|
||||
import FavoriteRepositoryImpl from "repository/favoriteRepositoryImpl";
|
||||
import VideoRepositoryImpl from "repository/videoRepositoryImpl";
|
||||
import DatabaseServiceImpl from "services/DatabaseServiceImpl";
|
||||
import DevToolsServiceImpl from "services/DevToolsServiceImpl";
|
||||
import DownloadServiceImpl from "services/DownloadServiceImpl";
|
||||
import StoreServiceImpl from "services/StoreServiceImpl";
|
||||
import WebviewServiceImpl from "services/WebviewServiceImpl";
|
||||
import FavoriteRepository from "./repository/FavoriteRepository";
|
||||
import VideoRepository from "./repository/VideoRepository";
|
||||
import WebviewService from "./services/WebviewService";
|
||||
import ElectronApp from "./app";
|
||||
import {
|
||||
App,
|
||||
StoreService,
|
||||
Controller,
|
||||
IpcHandlerService,
|
||||
LoggerService,
|
||||
MainWindowService,
|
||||
ProtocolService,
|
||||
UpdateService,
|
||||
VideoRepository,
|
||||
DatabaseService,
|
||||
FavoriteRepository,
|
||||
WebviewService,
|
||||
BrowserWindowService,
|
||||
DevToolsService,
|
||||
WebService,
|
||||
PlayerWindowService,
|
||||
} from "./interfaces";
|
||||
import IpcHandlerServiceImpl from "./services/IpcHandlerServiceImpl";
|
||||
import LoggerServiceImpl from "./services/LoggerServiceImpl";
|
||||
import ProtocolServiceImpl from "./services/ProtocolServiceImpl";
|
||||
import UpdateServiceImpl from "./services/UpdateServiceImpl";
|
||||
import { Controller } from "./interfaces";
|
||||
import { TYPES } from "./types";
|
||||
import WebServiceImpl from "services/WebServiceImpl";
|
||||
import MainWindow from "./windows/Main";
|
||||
import PlayerWindow from "windows/Player";
|
||||
import BrowserWin from "windows/Browser";
|
||||
import MainWindow from "./windows/MainWindow";
|
||||
import BrowserWindow from "./windows/BrowserWindow";
|
||||
import { SniffingHelper } from "./services/SniffingHelperService";
|
||||
import DownloadService from "./services/DownloadService";
|
||||
import ElectronLogger from "./vendor/ElectronLogger";
|
||||
import ElectronUpdater from "./vendor/ElectronUpdater";
|
||||
import TypeORM from "./vendor/TypeORM";
|
||||
import ElectronDevtools from "./vendor/ElectronDevtools";
|
||||
import ElectronStore from "./vendor/ElectronStore";
|
||||
import IpcHandler from "./core/ipc";
|
||||
import ProtocolService from "./core/protocol";
|
||||
|
||||
const container = new Container({
|
||||
skipBaseClassChecks: true,
|
||||
@@ -44,36 +26,37 @@ const container = new Container({
|
||||
autoBindInjectable: true,
|
||||
});
|
||||
|
||||
container.bind<App>(TYPES.App).to(ElectronApp);
|
||||
container
|
||||
.bind<IpcHandlerService>(TYPES.IpcHandlerService)
|
||||
.to(IpcHandlerServiceImpl);
|
||||
container.bind<ProtocolService>(TYPES.ProtocolService).to(ProtocolServiceImpl);
|
||||
container.bind<UpdateService>(TYPES.UpdateService).to(UpdateServiceImpl);
|
||||
container.bind<LoggerService>(TYPES.LoggerService).to(LoggerServiceImpl);
|
||||
container.bind<StoreService>(TYPES.StoreService).to(StoreServiceImpl);
|
||||
container.bind<DatabaseService>(TYPES.DatabaseService).to(DatabaseServiceImpl);
|
||||
container.bind<WebviewService>(TYPES.WebviewService).to(WebviewServiceImpl);
|
||||
container
|
||||
.bind<DownloadServiceImpl>(TYPES.DownloadService)
|
||||
.to(DownloadServiceImpl);
|
||||
container.bind<DevToolsService>(TYPES.DevToolsService).to(DevToolsServiceImpl);
|
||||
container.bind<WebService>(TYPES.WebService).to(WebServiceImpl);
|
||||
container.bind<ElectronApp>(TYPES.ElectronApp).to(ElectronApp);
|
||||
|
||||
// services
|
||||
container.bind<WebviewService>(TYPES.WebviewService).to(WebviewService);
|
||||
container.bind<DownloadService>(TYPES.DownloadService).to(DownloadService);
|
||||
container.bind<SniffingHelper>(TYPES.SniffingHelper).to(SniffingHelper);
|
||||
|
||||
// windows
|
||||
container.bind<MainWindowService>(TYPES.MainWindowService).to(MainWindow);
|
||||
container.bind<BrowserWindowService>(TYPES.BrowserWindowService).to(BrowserWin);
|
||||
container.bind<PlayerWindowService>(TYPES.PlayerWindowService).to(PlayerWindow);
|
||||
container.bind<MainWindow>(TYPES.MainWindow).to(MainWindow);
|
||||
container.bind<BrowserWindow>(TYPES.BrowserWindow).to(BrowserWindow);
|
||||
|
||||
// === controller
|
||||
// controller
|
||||
container.bind<Controller>(TYPES.Controller).to(HomeController);
|
||||
container.bind<Controller>(TYPES.Controller).to(WebviewController);
|
||||
container.bind<Controller>(TYPES.Controller).to(DownloadController);
|
||||
|
||||
// === repository
|
||||
container.bind<VideoRepository>(TYPES.VideoRepository).to(VideoRepositoryImpl);
|
||||
// repository
|
||||
container.bind<VideoRepository>(TYPES.VideoRepository).to(VideoRepository);
|
||||
container
|
||||
.bind<FavoriteRepository>(TYPES.FavoriteRepository)
|
||||
.to(FavoriteRepositoryImpl);
|
||||
.to(FavoriteRepository);
|
||||
|
||||
// vendor
|
||||
container.bind<ElectronDevtools>(TYPES.ElectronDevtools).to(ElectronDevtools);
|
||||
container.bind<TypeORM>(TYPES.TypeORM).to(TypeORM);
|
||||
container.bind<ElectronUpdater>(TYPES.ElectronUpdater).to(ElectronUpdater);
|
||||
container.bind<ElectronLogger>(TYPES.ElectronLogger).to(ElectronLogger);
|
||||
container.bind<ElectronStore>(TYPES.ElectronStore).to(ElectronStore);
|
||||
|
||||
// core
|
||||
container.bind<ProtocolService>(TYPES.ProtocolService).to(ProtocolService);
|
||||
container.bind<IpcHandler>(TYPES.IpcHandlerService).to(IpcHandler);
|
||||
|
||||
export { container };
|
||||
|
||||
Vendored
+12
-50
@@ -1,10 +1,6 @@
|
||||
import { Video, Rectangle } from "electron";
|
||||
import { type Favorite } from "entity/Favorite";
|
||||
import {
|
||||
DownloadItem,
|
||||
DownloadItemPagination,
|
||||
VideoResponse,
|
||||
} from "interfaces";
|
||||
import { Rectangle } from "electron";
|
||||
import { type DownloadType } from "interfaces";
|
||||
import { AppLanguage, AppTheme } from "./types";
|
||||
|
||||
declare interface EnvPath {
|
||||
binPath: string;
|
||||
@@ -19,51 +15,11 @@ declare interface BrowserWindowInitialVal {
|
||||
sourceList?: WebSource[];
|
||||
}
|
||||
|
||||
declare interface ElectronAPI {
|
||||
getEnvPath: () => Promise<EnvPath>;
|
||||
getFavorites: () => Promise<Favorite>;
|
||||
addFavorite: (favorite: Favorite) => Promise<Favorite>;
|
||||
removeFavorite: (id: number) => Promise<void>;
|
||||
setWebviewBounds: (rect: Electron.Rectangle) => Promise<void>;
|
||||
webviewLoadURL: (url?: string) => Promise<void>;
|
||||
webviewGoBack: () => Promise<boolean>;
|
||||
webviewReload: () => Promise<void>;
|
||||
webwiewGoHome: () => Promise<void>;
|
||||
getAppStore: () => Promise<AppStore>;
|
||||
onSelectDownloadDir: () => Promise<string>;
|
||||
setAppStore: (key: keyof AppStore, val: any) => Promise<void>;
|
||||
openDir: (dir: string) => Promise<void>;
|
||||
addDownloadItem: (video: DownloadItem) => Promise<Video>;
|
||||
getDownloadItems: (
|
||||
pagiantion: DownloadItemPagination
|
||||
) => Promise<VideoResponse>;
|
||||
startDownload: (vid: number) => Promise<void>;
|
||||
openUrl: (url: string) => Promise<void>;
|
||||
stopDownload: (id: number) => Promise<void>;
|
||||
onDownloadListContextMenu: (id: number) => Promise<void>;
|
||||
onFavoriteItemContextMenu: (id: number) => Promise<void>;
|
||||
deleteDownloadItem: (id: number) => Promise<void>;
|
||||
convertToAudio: (id: number) => Promise<void>;
|
||||
rendererEvent: (channel: string, funcId: string, listener: any) => void;
|
||||
removeEventListener: (channel: string, funcId: string) => void;
|
||||
showBrowserWindow: () => Promise<void>;
|
||||
webviewHide: () => Promise<void>;
|
||||
webviewShow: () => Promise<void>;
|
||||
downloadNow: (video: DownloadItem) => Promise<void>;
|
||||
combineToHomePage: (initialVal: BrowserStore) => Promise<void>;
|
||||
editDownloadItem: (video: DownloadItem) => Promise<void>;
|
||||
openPlayerWindow: (videoId: number) => Promise<void>;
|
||||
getLocalIP: () => Promise<string>;
|
||||
openBrowser: (url: string) => Promise<void>;
|
||||
getSharedState: () => Promise<any>;
|
||||
setSharedState: (state: any) => Promise<void>;
|
||||
setUserAgent: (isMobile: boolean) => Promise<void>;
|
||||
}
|
||||
|
||||
declare interface WebSource {
|
||||
url: string;
|
||||
type: DownloadType;
|
||||
name: string;
|
||||
headers: string;
|
||||
headers?: string;
|
||||
}
|
||||
|
||||
declare interface AppStore {
|
||||
@@ -83,13 +39,19 @@ declare interface AppStore {
|
||||
browserBounds?: Rectangle;
|
||||
blockAds: boolean;
|
||||
// 主题
|
||||
theme: "system" | "light" | "dark";
|
||||
theme: AppTheme;
|
||||
// 使用浏览器插件
|
||||
useExtension: boolean;
|
||||
// 是否使用手机UA
|
||||
isMobile: boolean;
|
||||
// 最大同时下载数
|
||||
maxRunner: number;
|
||||
// 语言
|
||||
language: AppLanguage;
|
||||
// 是否显示终端
|
||||
showTerminal: boolean;
|
||||
// 隐私模式
|
||||
privacy: boolean;
|
||||
}
|
||||
|
||||
declare interface BrowserStore {
|
||||
|
||||
+139
-45
@@ -1,60 +1,154 @@
|
||||
import { contextBridge, ipcRenderer, shell } from "electron";
|
||||
import { ElectronAPI } from "./main";
|
||||
import { contextBridge, ipcRenderer } from "electron/renderer";
|
||||
import { shell } from "electron/common";
|
||||
import { AppStore, BrowserStore, EnvPath } from "./main";
|
||||
import { type Favorite } from "./entity/Favorite";
|
||||
import {
|
||||
VideoResponse,
|
||||
type DownloadItem,
|
||||
type DownloadItemPagination,
|
||||
} from "./interfaces";
|
||||
import { Video } from "./entity/Video";
|
||||
|
||||
const apiFunctions: Record<string, any> = {};
|
||||
|
||||
const apiKey = "electron";
|
||||
const handleApi: ElectronAPI = {
|
||||
getEnvPath: () => ipcRenderer.invoke("get-env-path"),
|
||||
getFavorites: () => ipcRenderer.invoke("get-favorites"),
|
||||
addFavorite: (favorite) => ipcRenderer.invoke("add-favorite", favorite),
|
||||
removeFavorite: (id) => ipcRenderer.invoke("remove-favorite", id),
|
||||
setWebviewBounds: (rect) => ipcRenderer.invoke("set-webview-bounds", rect),
|
||||
webviewGoBack: () => ipcRenderer.invoke("webview-go-back"),
|
||||
webviewReload: () => ipcRenderer.invoke("webview-reload"),
|
||||
webviewLoadURL: (url?: string) => ipcRenderer.invoke("webview-load-url", url),
|
||||
webwiewGoHome: () => ipcRenderer.invoke("webview-go-home"),
|
||||
getAppStore: () => ipcRenderer.invoke("get-app-store"),
|
||||
onSelectDownloadDir: () => ipcRenderer.invoke("select-download-dir"),
|
||||
setAppStore: (key, val) => ipcRenderer.invoke("set-app-store", key, val),
|
||||
openDir: (dir) => ipcRenderer.invoke("open-dir", dir),
|
||||
addDownloadItem: (video) => ipcRenderer.invoke("add-download-item", video),
|
||||
getDownloadItems: (p) => ipcRenderer.invoke("get-download-items", p),
|
||||
startDownload: (vid) => ipcRenderer.invoke("start-download", vid),
|
||||
openUrl: (url: string) => ipcRenderer.invoke("open-url", url),
|
||||
stopDownload: (id) => ipcRenderer.invoke("stop-download", id),
|
||||
onDownloadListContextMenu: (id) =>
|
||||
ipcRenderer.invoke("on-download-list-context-menu", id),
|
||||
onFavoriteItemContextMenu: (id) =>
|
||||
ipcRenderer.invoke("on-favorite-item-context-menu", id),
|
||||
deleteDownloadItem: (id) => ipcRenderer.invoke("delete-download-item", id),
|
||||
convertToAudio: (id) => ipcRenderer.invoke("convert-to-audio", id),
|
||||
rendererEvent: (channel, funcId, listener) => {
|
||||
|
||||
export type ElectronApi = typeof electronApi;
|
||||
|
||||
const electronApi = {
|
||||
getEnvPath(): Promise<EnvPath> {
|
||||
return ipcRenderer.invoke("get-env-path");
|
||||
},
|
||||
getFavorites(): Promise<Favorite[]> {
|
||||
return ipcRenderer.invoke("get-favorites");
|
||||
},
|
||||
addFavorite(
|
||||
favorite: Omit<Favorite, "id" | "createdDate" | "updatedDate">,
|
||||
): Promise<Favorite> {
|
||||
return ipcRenderer.invoke("add-favorite", favorite);
|
||||
},
|
||||
removeFavorite(id: number): Promise<void> {
|
||||
return ipcRenderer.invoke("remove-favorite", id);
|
||||
},
|
||||
setWebviewBounds(rect: Electron.Rectangle): Promise<void> {
|
||||
return ipcRenderer.invoke("set-webview-bounds", rect);
|
||||
},
|
||||
webviewGoBack(): Promise<boolean> {
|
||||
return ipcRenderer.invoke("webview-go-back");
|
||||
},
|
||||
webviewReload(): Promise<void> {
|
||||
return ipcRenderer.invoke("webview-reload");
|
||||
},
|
||||
webviewLoadURL(url?: string): Promise<void> {
|
||||
return ipcRenderer.invoke("webview-load-url", url);
|
||||
},
|
||||
webviewGoHome(): Promise<void> {
|
||||
return ipcRenderer.invoke("webview-go-home");
|
||||
},
|
||||
getAppStore(): Promise<AppStore> {
|
||||
return ipcRenderer.invoke("get-app-store");
|
||||
},
|
||||
onSelectDownloadDir(): Promise<string> {
|
||||
return ipcRenderer.invoke("select-download-dir");
|
||||
},
|
||||
setAppStore(
|
||||
key: keyof AppStore,
|
||||
val: AppStore[keyof AppStore],
|
||||
): Promise<void> {
|
||||
return ipcRenderer.invoke("set-app-store", key, val);
|
||||
},
|
||||
openDir(dir: string): Promise<void> {
|
||||
return ipcRenderer.invoke("open-dir", dir);
|
||||
},
|
||||
addDownloadItem(video: Omit<DownloadItem, "id">): Promise<Video> {
|
||||
return ipcRenderer.invoke("add-download-item", video);
|
||||
},
|
||||
addDownloadItems(videos: DownloadItem[]): Promise<Video[]> {
|
||||
return ipcRenderer.invoke("add-download-items", videos);
|
||||
},
|
||||
getDownloadItems(p: DownloadItemPagination): Promise<VideoResponse> {
|
||||
return ipcRenderer.invoke("get-download-items", p);
|
||||
},
|
||||
startDownload(vid: number): Promise<void> {
|
||||
return ipcRenderer.invoke("start-download", vid);
|
||||
},
|
||||
openUrl(url: string): Promise<void> {
|
||||
return ipcRenderer.invoke("open-url", url);
|
||||
},
|
||||
stopDownload(id: number): Promise<void> {
|
||||
return ipcRenderer.invoke("stop-download", id);
|
||||
},
|
||||
onDownloadListContextMenu(id: number): Promise<void> {
|
||||
return ipcRenderer.invoke("on-download-list-context-menu", id);
|
||||
},
|
||||
onFavoriteItemContextMenu(id: number): Promise<void> {
|
||||
return ipcRenderer.invoke("on-favorite-item-context-menu", id);
|
||||
},
|
||||
deleteDownloadItem(id: number): Promise<void> {
|
||||
return ipcRenderer.invoke("delete-download-item", id);
|
||||
},
|
||||
convertToAudio(id: number): Promise<void> {
|
||||
return ipcRenderer.invoke("convert-to-audio", id);
|
||||
},
|
||||
rendererEvent(channel: string, funcId: string, listener: any): void {
|
||||
const key = `${channel}-${funcId}`;
|
||||
apiFunctions[key] = listener;
|
||||
ipcRenderer.on(channel, listener);
|
||||
},
|
||||
removeEventListener: (channel, funcId) => {
|
||||
removeEventListener(channel: string, funcId: string): void {
|
||||
const key = `${channel}-${funcId}`;
|
||||
const fun = apiFunctions[key];
|
||||
ipcRenderer.removeListener(channel, fun);
|
||||
delete apiFunctions[key];
|
||||
},
|
||||
showBrowserWindow: () => ipcRenderer.invoke("show-browser-window"),
|
||||
webviewHide: () => ipcRenderer.invoke("webview-hide"),
|
||||
webviewShow: () => ipcRenderer.invoke("webview-show"),
|
||||
downloadNow: (video) => ipcRenderer.invoke("download-now", video),
|
||||
combineToHomePage: (store) =>
|
||||
ipcRenderer.invoke("combine-to-home-page", store),
|
||||
editDownloadItem: (video) => ipcRenderer.invoke("edit-download-item", video),
|
||||
openPlayerWindow: (videoId) =>
|
||||
ipcRenderer.invoke("open-player-window", videoId),
|
||||
getLocalIP: () => ipcRenderer.invoke("get-local-ip"),
|
||||
openBrowser: (url: string) => shell.openExternal(url),
|
||||
getSharedState: () => ipcRenderer.invoke("get-shared-state"),
|
||||
setSharedState: (state) => ipcRenderer.invoke("set-shared-state", state),
|
||||
setUserAgent: (isMobile: boolean) =>
|
||||
ipcRenderer.invoke("webview-change-user-agent", isMobile),
|
||||
showBrowserWindow(): Promise<void> {
|
||||
return ipcRenderer.invoke("show-browser-window");
|
||||
},
|
||||
webviewHide(): Promise<void> {
|
||||
return ipcRenderer.invoke("webview-hide");
|
||||
},
|
||||
webviewShow(): Promise<void> {
|
||||
return ipcRenderer.invoke("webview-show");
|
||||
},
|
||||
webviewUrlContextMenu(): Promise<void> {
|
||||
return ipcRenderer.invoke("webview-url-contextmenu");
|
||||
},
|
||||
downloadNow(video: Omit<DownloadItem, "id">): Promise<void> {
|
||||
return ipcRenderer.invoke("download-now", video);
|
||||
},
|
||||
combineToHomePage(store: BrowserStore): Promise<void> {
|
||||
return ipcRenderer.invoke("combine-to-home-page", store);
|
||||
},
|
||||
editDownloadItem(video: DownloadItem): Promise<void> {
|
||||
return ipcRenderer.invoke("edit-download-item", video);
|
||||
},
|
||||
getLocalIP(): Promise<string> {
|
||||
return ipcRenderer.invoke("get-local-ip");
|
||||
},
|
||||
openBrowser(url: string): Promise<void> {
|
||||
return shell.openExternal(url);
|
||||
},
|
||||
getSharedState(): Promise<any> {
|
||||
return ipcRenderer.invoke("get-shared-state");
|
||||
},
|
||||
setSharedState(state: any): Promise<void> {
|
||||
return ipcRenderer.invoke("set-shared-state", state);
|
||||
},
|
||||
setUserAgent(isMobile: boolean): Promise<void> {
|
||||
return ipcRenderer.invoke("webview-change-user-agent", isMobile);
|
||||
},
|
||||
downloadItem(data: Omit<DownloadItem, "id">) {
|
||||
return ipcRenderer.invoke("add-download-item", data);
|
||||
},
|
||||
getDownloadLog(id: number): Promise<string> {
|
||||
return ipcRenderer.invoke("get-download-log", id);
|
||||
},
|
||||
showDownloadDialog(data: Omit<DownloadItem, "id">[]) {
|
||||
return ipcRenderer.invoke("show-download-dialog", data);
|
||||
},
|
||||
pluginReady() {
|
||||
return ipcRenderer.invoke("plugin-ready");
|
||||
},
|
||||
};
|
||||
|
||||
contextBridge.exposeInMainWorld(apiKey, handleApi);
|
||||
contextBridge.exposeInMainWorld(apiKey, electronApi);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { inject, injectable } from "inversify";
|
||||
import { TYPES } from "../types";
|
||||
import { Favorite } from "../entity/Favorite";
|
||||
import TypeORM from "../vendor/TypeORM";
|
||||
|
||||
@injectable()
|
||||
export default class FavoriteRepository {
|
||||
constructor(
|
||||
@inject(TYPES.TypeORM)
|
||||
private readonly db: TypeORM,
|
||||
) {}
|
||||
|
||||
async findFavorites(): Promise<Favorite[]> {
|
||||
return await this.db.manager.find(Favorite, {
|
||||
order: {
|
||||
createdDate: "desc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async addFavorite(favorite: Favorite): Promise<Favorite> {
|
||||
const exist = await this.db.manager.findOne(Favorite, {
|
||||
where: {
|
||||
url: favorite.url,
|
||||
},
|
||||
});
|
||||
|
||||
if (exist) {
|
||||
throw new Error("网址已经存在");
|
||||
}
|
||||
|
||||
const item = new Favorite();
|
||||
item.title = favorite.title;
|
||||
item.url = favorite.url;
|
||||
item.icon = favorite.icon;
|
||||
return await this.db.manager.save(item);
|
||||
}
|
||||
|
||||
async removeFavorite(id: number): Promise<void> {
|
||||
await this.db.manager.getRepository(Favorite).delete(id);
|
||||
}
|
||||
}
|
||||
+60
-22
@@ -1,37 +1,51 @@
|
||||
import { Video } from "../entity/Video";
|
||||
import { inject, injectable } from "inversify";
|
||||
import {
|
||||
DatabaseService,
|
||||
DownloadFilter,
|
||||
DownloadItem,
|
||||
DownloadItemPagination,
|
||||
DownloadStatus,
|
||||
LoggerService,
|
||||
VideoRepository,
|
||||
} from "../interfaces";
|
||||
import { TYPES } from "../types";
|
||||
import { In, Not } from "typeorm";
|
||||
import TypeORM from "../vendor/TypeORM";
|
||||
|
||||
@injectable()
|
||||
export default class VideoRepositoryImpl implements VideoRepository {
|
||||
export default class VideoRepository {
|
||||
constructor(
|
||||
@inject(TYPES.DatabaseService)
|
||||
private readonly dataService: DatabaseService,
|
||||
@inject(TYPES.LoggerService)
|
||||
private readonly logger: LoggerService
|
||||
@inject(TYPES.TypeORM)
|
||||
private readonly db: TypeORM,
|
||||
) {}
|
||||
|
||||
async addVideo(video: DownloadItem) {
|
||||
async addVideo(video: Omit<DownloadItem, "id">) {
|
||||
// 先判断有没有同名的视频
|
||||
const exist = await this.findVideoByName(video.name);
|
||||
if (exist) {
|
||||
throw new Error("视频名称已存在,请更换视频名称");
|
||||
}
|
||||
const item = new Video();
|
||||
item.name = video.name;
|
||||
item.url = video.url;
|
||||
item.headers = video.headers;
|
||||
return await this.dataService.manager.save(item);
|
||||
item.type = video.type;
|
||||
video.headers && (item.headers = video.headers);
|
||||
return await this.db.manager.save(item);
|
||||
}
|
||||
|
||||
async addVideos(videos: DownloadItem[]) {
|
||||
const items = videos.map((video) => {
|
||||
const item = new Video();
|
||||
item.name = video.name;
|
||||
item.url = video.url;
|
||||
item.type = video.type;
|
||||
video.headers && (item.headers = video.headers);
|
||||
return item;
|
||||
});
|
||||
return await this.db.manager.save(items);
|
||||
}
|
||||
|
||||
// 编辑视频
|
||||
async editVideo(video: DownloadItem) {
|
||||
const item = await this.dataService.appDataSource
|
||||
const item = await this.db.appDataSource
|
||||
.getRepository(Video)
|
||||
.findOneBy({ id: video.id });
|
||||
if (!item) {
|
||||
@@ -39,12 +53,13 @@ export default class VideoRepositoryImpl implements VideoRepository {
|
||||
}
|
||||
item.name = video.name;
|
||||
item.url = video.url;
|
||||
return await this.dataService.manager.save(item);
|
||||
video.headers && (item.headers = video.headers);
|
||||
return await this.db.manager.save(item);
|
||||
}
|
||||
|
||||
// 查找所有视频
|
||||
async findAllVideos() {
|
||||
return await this.dataService.appDataSource.getRepository(Video).find({
|
||||
return await this.db.appDataSource.getRepository(Video).find({
|
||||
order: {
|
||||
createdDate: "DESC",
|
||||
},
|
||||
@@ -62,14 +77,14 @@ export default class VideoRepositoryImpl implements VideoRepository {
|
||||
? DownloadStatus.Success
|
||||
: Not(DownloadStatus.Success);
|
||||
|
||||
const [items, count] = await this.dataService.appDataSource
|
||||
const [items, count] = await this.db.appDataSource
|
||||
.getRepository(Video)
|
||||
.findAndCount({
|
||||
where: {
|
||||
status: filterCondition,
|
||||
},
|
||||
order: {
|
||||
createdDate: "DESC",
|
||||
createdDate: "ASC",
|
||||
},
|
||||
skip: (current - 1) * pageSize,
|
||||
take: pageSize,
|
||||
@@ -81,14 +96,20 @@ export default class VideoRepositoryImpl implements VideoRepository {
|
||||
}
|
||||
|
||||
async findVideo(id: number) {
|
||||
return this.dataService.appDataSource.getRepository(Video).findOneBy({
|
||||
return this.db.appDataSource.getRepository(Video).findOneBy({
|
||||
id,
|
||||
});
|
||||
}
|
||||
|
||||
async findVideoByName(name: string) {
|
||||
return this.db.appDataSource.getRepository(Video).findOneBy({
|
||||
name,
|
||||
});
|
||||
}
|
||||
|
||||
async changeVideoStatus(id: number | number[], status: DownloadStatus) {
|
||||
const ids = !Array.isArray(id) ? [id] : id;
|
||||
return this.dataService.appDataSource
|
||||
return this.db.appDataSource
|
||||
.createQueryBuilder()
|
||||
.update(Video)
|
||||
.set({ status })
|
||||
@@ -98,7 +119,7 @@ export default class VideoRepositoryImpl implements VideoRepository {
|
||||
|
||||
async changeVideoIsLive(id: number | number[], isLive: boolean) {
|
||||
const ids = !Array.isArray(id) ? [id] : id;
|
||||
return this.dataService.appDataSource
|
||||
return this.db.appDataSource
|
||||
.createQueryBuilder()
|
||||
.update(Video)
|
||||
.set({ isLive })
|
||||
@@ -107,7 +128,7 @@ export default class VideoRepositoryImpl implements VideoRepository {
|
||||
}
|
||||
|
||||
async findWattingAndDownloadingVideos() {
|
||||
return await this.dataService.appDataSource.getRepository(Video).find({
|
||||
return await this.db.appDataSource.getRepository(Video).find({
|
||||
where: {
|
||||
status: In([DownloadStatus.Downloading, DownloadStatus.Watting]),
|
||||
},
|
||||
@@ -115,12 +136,29 @@ export default class VideoRepositoryImpl implements VideoRepository {
|
||||
}
|
||||
|
||||
async deleteDownloadItem(id: number) {
|
||||
return await this.dataService.appDataSource.getRepository(Video).delete(id);
|
||||
return await this.db.appDataSource.getRepository(Video).delete(id);
|
||||
}
|
||||
|
||||
async findVideoByUrl(url: string) {
|
||||
return this.dataService.appDataSource.getRepository(Video).findOneBy({
|
||||
return this.db.appDataSource.getRepository(Video).findOneBy({
|
||||
url,
|
||||
});
|
||||
}
|
||||
|
||||
async appendDownloadLog(id: number, message: string) {
|
||||
const video = await this.findVideo(id);
|
||||
if (!video) {
|
||||
throw new Error("视频不存在");
|
||||
}
|
||||
video.log = video.log ? `${video.log}\n${message}` : message;
|
||||
return await this.db.manager.save(video);
|
||||
}
|
||||
|
||||
async getDownloadLog(id: number) {
|
||||
const video = await this.findVideo(id);
|
||||
if (!video) {
|
||||
throw new Error("视频不存在");
|
||||
}
|
||||
return video.log;
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { inject, injectable } from "inversify";
|
||||
import {
|
||||
DatabaseService,
|
||||
FavoriteRepository,
|
||||
LoggerService,
|
||||
} from "../interfaces";
|
||||
import { TYPES } from "../types";
|
||||
import { Favorite } from "entity/Favorite";
|
||||
|
||||
@injectable()
|
||||
export default class FavoriteRepositoryImpl implements FavoriteRepository {
|
||||
constructor(
|
||||
@inject(TYPES.DatabaseService)
|
||||
private readonly dataService: DatabaseService,
|
||||
@inject(TYPES.LoggerService)
|
||||
private readonly logger: LoggerService
|
||||
) {}
|
||||
|
||||
async findFavorites(): Promise<Favorite[]> {
|
||||
return await this.dataService.manager.find(Favorite, {
|
||||
order: {
|
||||
createdDate: "desc",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async addFavorite(favorite: Favorite): Promise<Favorite> {
|
||||
const exist = await this.dataService.manager.findOne(Favorite, {
|
||||
where: {
|
||||
url: favorite.url,
|
||||
},
|
||||
});
|
||||
|
||||
if (exist) {
|
||||
throw new Error("网址已经存在");
|
||||
}
|
||||
|
||||
const item = new Favorite();
|
||||
item.title = favorite.title;
|
||||
item.url = favorite.url;
|
||||
item.icon = favorite.icon;
|
||||
return await this.dataService.manager.save(item);
|
||||
}
|
||||
|
||||
async removeFavorite(id: number): Promise<void> {
|
||||
await this.dataService.manager.getRepository(Favorite).delete(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
import EventEmitter from "events";
|
||||
import { inject, injectable } from "inversify";
|
||||
import {
|
||||
DownloadParams,
|
||||
DownloadProgress,
|
||||
DownloadStatus,
|
||||
Task,
|
||||
} from "../interfaces";
|
||||
import { TYPES } from "../types";
|
||||
import ElectronLogger from "../vendor/ElectronLogger";
|
||||
import ElectronStore from "../vendor/ElectronStore";
|
||||
import VideoRepository from "../repository/VideoRepository";
|
||||
import { biliDownloaderBin, m3u8DownloaderBin } from "../helper";
|
||||
import * as pty from "node-pty";
|
||||
import stripAnsi from "strip-ansi";
|
||||
|
||||
export interface DownloadOptions {
|
||||
abortSignal: AbortController;
|
||||
encoding?: string;
|
||||
onMessage?: (ctx: any, message: string) => void;
|
||||
id: number;
|
||||
}
|
||||
|
||||
interface Schema {
|
||||
args: Record<string, { argsName: string[] | null }>;
|
||||
consoleReg: {
|
||||
percent: string;
|
||||
speed: string;
|
||||
error: string;
|
||||
start: string;
|
||||
isLive: string;
|
||||
};
|
||||
bin: string;
|
||||
platform: string[];
|
||||
type: string;
|
||||
}
|
||||
|
||||
const processList: Schema[] = [
|
||||
{
|
||||
type: "m3u8",
|
||||
platform: ["win32"],
|
||||
bin: m3u8DownloaderBin,
|
||||
args: {
|
||||
url: {
|
||||
argsName: null,
|
||||
},
|
||||
localDir: {
|
||||
argsName: ["--workDir"],
|
||||
},
|
||||
name: {
|
||||
argsName: ["--saveName"],
|
||||
},
|
||||
// headers: {
|
||||
// argsName: ["--headers"],
|
||||
// },
|
||||
deleteSegments: {
|
||||
argsName: ["--enableDelAfterDone"],
|
||||
},
|
||||
proxy: {
|
||||
argsName: ["--proxyAddress"],
|
||||
},
|
||||
},
|
||||
consoleReg: {
|
||||
percent: "([\\d.]+)%",
|
||||
speed: "([\\d.]+\\s[GMK]B/s)",
|
||||
error: "ERROR",
|
||||
start: "开始下载文件",
|
||||
isLive: "识别为直播流, 开始录制",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "m3u8",
|
||||
platform: ["darwin"],
|
||||
bin: m3u8DownloaderBin,
|
||||
args: {
|
||||
url: {
|
||||
argsName: null,
|
||||
},
|
||||
localDir: {
|
||||
argsName: ["--tmp-dir", "--save-dir"],
|
||||
},
|
||||
name: {
|
||||
argsName: ["--save-name"],
|
||||
},
|
||||
// headers: {
|
||||
// argsName: ["--headers"],
|
||||
// },
|
||||
deleteSegments: {
|
||||
argsName: ["--del-after-done"],
|
||||
},
|
||||
proxy: {
|
||||
argsName: ["--custom-proxy"],
|
||||
},
|
||||
},
|
||||
consoleReg: {
|
||||
percent: "([\\d.]+)%",
|
||||
speed: "([\\d.]+[GMK]Bps)",
|
||||
error: "ERROR",
|
||||
start: "保存文件名:",
|
||||
isLive: "检测到直播流",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "bilibili",
|
||||
platform: ["win32", "darwin"],
|
||||
bin: biliDownloaderBin,
|
||||
args: {
|
||||
url: {
|
||||
argsName: null,
|
||||
},
|
||||
localDir: {
|
||||
argsName: ["--work-dir"],
|
||||
},
|
||||
},
|
||||
consoleReg: {
|
||||
speed: "([\\d.]+\\s[GMK]B/s)",
|
||||
percent: "([\\d.]+)%",
|
||||
error: "ERROR",
|
||||
start: "保存文件名:",
|
||||
isLive: "检测到直播流",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@injectable()
|
||||
export default class DownloadService extends EventEmitter {
|
||||
private queue: Task[] = [];
|
||||
|
||||
private active: Task[] = [];
|
||||
|
||||
private limit: number;
|
||||
|
||||
private signal: Record<number, AbortController> = {};
|
||||
|
||||
constructor(
|
||||
@inject(TYPES.ElectronLogger)
|
||||
private readonly logger: ElectronLogger,
|
||||
@inject(TYPES.VideoRepository)
|
||||
private readonly videoRepository: VideoRepository,
|
||||
@inject(TYPES.ElectronStore)
|
||||
private readonly storeService: ElectronStore,
|
||||
) {
|
||||
super();
|
||||
|
||||
const maxRunner = this.storeService.get("maxRunner");
|
||||
this.limit = maxRunner;
|
||||
|
||||
this.storeService.onDidChange("maxRunner", (maxRunner) => {
|
||||
maxRunner && (this.limit = maxRunner);
|
||||
});
|
||||
}
|
||||
|
||||
async addTask(task: Task) {
|
||||
this.queue.push(task);
|
||||
this.runTask();
|
||||
}
|
||||
|
||||
async stopTask(id: number) {
|
||||
if (this.signal[id]) {
|
||||
this.logger.info(`taskId: ${id} stop`);
|
||||
this.signal[id].abort();
|
||||
}
|
||||
}
|
||||
|
||||
async execute(task: Task) {
|
||||
try {
|
||||
await this.videoRepository.changeVideoStatus(
|
||||
task.id,
|
||||
DownloadStatus.Downloading,
|
||||
);
|
||||
this.emit("download-start", task.id);
|
||||
|
||||
this.logger.info(`taskId: ${task.id} start`);
|
||||
const controller = new AbortController();
|
||||
this.signal[task.id] = controller;
|
||||
|
||||
const callback = (progress: DownloadProgress) => {
|
||||
if (progress.type === "progress") {
|
||||
this.emit("download-progress", progress);
|
||||
} else if (progress.type === "ready") {
|
||||
this.emit("download-ready-start", progress);
|
||||
if (progress.isLive) {
|
||||
this.removeTask(progress.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const params: DownloadParams = {
|
||||
...task.params,
|
||||
id: task.id,
|
||||
abortSignal: controller,
|
||||
callback,
|
||||
};
|
||||
|
||||
const { proxy, useProxy } = this.storeService.store;
|
||||
if (useProxy) {
|
||||
params.proxy = proxy;
|
||||
}
|
||||
|
||||
await this.process(params);
|
||||
delete this.signal[task.id];
|
||||
this.logger.info(`taskId: ${task.id} success`);
|
||||
|
||||
await this.videoRepository.changeVideoStatus(
|
||||
task.id,
|
||||
DownloadStatus.Success,
|
||||
);
|
||||
this.emit("download-success", task.id);
|
||||
} catch (err: any) {
|
||||
this.logger.info(`taskId: ${task.id} failed`);
|
||||
if (err.message === "AbortError") {
|
||||
// 下载暂停
|
||||
await this.videoRepository.changeVideoStatus(
|
||||
task.id,
|
||||
DownloadStatus.Stopped,
|
||||
);
|
||||
this.emit("download-stop", task.id);
|
||||
} else {
|
||||
// 下载失败
|
||||
await this.videoRepository.changeVideoStatus(
|
||||
task.id,
|
||||
DownloadStatus.Failed,
|
||||
);
|
||||
this.emit("download-failed", task.id, err);
|
||||
}
|
||||
} finally {
|
||||
this.removeTask(task.id);
|
||||
|
||||
// 传输完成
|
||||
if (this.queue.length === 0 && this.active.length === 0) {
|
||||
// this.emit("download-finish");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
removeTask(id: number) {
|
||||
// 处理当前正在活动的任务
|
||||
const doneId = this.active.findIndex((i) => i.id === id);
|
||||
this.active.splice(doneId, 1);
|
||||
// 处理完成的任务
|
||||
if (this.active.length < this.limit) {
|
||||
this.runTask();
|
||||
}
|
||||
}
|
||||
|
||||
runTask() {
|
||||
while (this.active.length < this.limit && this.queue.length > 0) {
|
||||
const task = this.queue.shift();
|
||||
if (task) {
|
||||
this.active.push(task);
|
||||
this.execute(task);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _execa(
|
||||
binPath: string,
|
||||
args: string[],
|
||||
params: DownloadOptions,
|
||||
): Promise<void> {
|
||||
const { abortSignal, onMessage, id } = params;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const ptyProcess = pty.spawn(binPath, args, {
|
||||
name: "xterm-color",
|
||||
cols: 500,
|
||||
rows: 500,
|
||||
useConpty: false,
|
||||
});
|
||||
|
||||
if (onMessage) {
|
||||
const ctx = {};
|
||||
ptyProcess.onData((data) => {
|
||||
try {
|
||||
this.emit("download-message", id, data);
|
||||
onMessage(ctx, stripAnsi(data));
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
abortSignal.signal.addEventListener("abort", () => {
|
||||
ptyProcess.kill();
|
||||
reject(new Error("AbortError"));
|
||||
});
|
||||
|
||||
ptyProcess.onExit(({ exitCode }) => {
|
||||
if (exitCode === 0) {
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error("未知错误"));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async downloader(params: DownloadParams, schema: Schema): Promise<void> {
|
||||
const {
|
||||
id,
|
||||
abortSignal,
|
||||
url,
|
||||
local,
|
||||
name,
|
||||
deleteSegments,
|
||||
headers,
|
||||
callback,
|
||||
proxy,
|
||||
} = params;
|
||||
|
||||
const spawnParams = [];
|
||||
for (const key of Object.keys(schema.args)) {
|
||||
const { argsName } = schema.args[key];
|
||||
if (key === "url") {
|
||||
argsName && spawnParams.push(...argsName);
|
||||
spawnParams.push(url);
|
||||
}
|
||||
if (key === "localDir") {
|
||||
argsName && argsName.forEach((i) => spawnParams.push(i, local));
|
||||
}
|
||||
if (key === "name") {
|
||||
argsName && argsName.forEach((i) => spawnParams.push(i, name));
|
||||
}
|
||||
|
||||
if (key === "headers") {
|
||||
if (headers) {
|
||||
const h: Record<string, unknown> = JSON.parse(headers);
|
||||
Object.entries(h).forEach(([k, v]) => {
|
||||
spawnParams.push("--header", `${k}: ${v}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (key === "deleteSegments" && deleteSegments) {
|
||||
argsName && spawnParams.push(...argsName);
|
||||
}
|
||||
|
||||
if (key === "proxy" && proxy) {
|
||||
argsName && argsName.forEach((i) => spawnParams.push(i, proxy));
|
||||
}
|
||||
}
|
||||
|
||||
const { consoleReg } = schema;
|
||||
const isLiveReg = RegExp(consoleReg.isLive, "g");
|
||||
const startDownloadReg = RegExp(consoleReg.start, "g");
|
||||
const errorReg = RegExp(consoleReg.error, "g");
|
||||
const speedReg = RegExp(consoleReg.speed, "g");
|
||||
const percentReg = RegExp(consoleReg.percent, "g");
|
||||
|
||||
const onMessage = (ctx: any, message: string) => {
|
||||
// 解析是否为直播资源
|
||||
if (isLiveReg.test(message)) {
|
||||
ctx.isLive = true;
|
||||
}
|
||||
// 解析下载进度
|
||||
const [, percent] = percentReg.exec(message) || [];
|
||||
if (percent && Number(ctx.percent || 0) < Number(percent)) {
|
||||
ctx.percent = percent;
|
||||
}
|
||||
// 解析下载速度
|
||||
const [, speed] = speedReg.exec(message) || [];
|
||||
if (speed) {
|
||||
ctx.speed = speed;
|
||||
}
|
||||
|
||||
if (startDownloadReg.test(message)) {
|
||||
callback({
|
||||
id,
|
||||
type: "ready",
|
||||
isLive: !!ctx.isLive,
|
||||
speed: "",
|
||||
percent: "",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (errorReg.test(message)) {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
// FIXME: 无法获取是否为直播流
|
||||
callback({
|
||||
id,
|
||||
type: "progress",
|
||||
percent: ctx.percent || "",
|
||||
speed: ctx.speed || "",
|
||||
isLive: !!ctx.isLive,
|
||||
});
|
||||
};
|
||||
|
||||
this.logger.debug("download params: ", spawnParams);
|
||||
await this._execa(schema.bin, spawnParams, {
|
||||
id,
|
||||
abortSignal,
|
||||
onMessage,
|
||||
});
|
||||
}
|
||||
|
||||
async process(params: DownloadParams): Promise<void> {
|
||||
const program = processList
|
||||
.filter((i) => i.platform.includes(process.platform))
|
||||
.filter((i) => i.type === params.type);
|
||||
|
||||
if (program.length === 0) {
|
||||
return Promise.reject(new Error("不支持的下载类型"));
|
||||
}
|
||||
|
||||
const schema = program[0];
|
||||
await this.downloader(params, schema);
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
import EventEmitter from "events";
|
||||
import { inject, injectable } from "inversify";
|
||||
import {
|
||||
DownloadService,
|
||||
DownloadStatus,
|
||||
StoreService,
|
||||
Task,
|
||||
VideoRepository,
|
||||
} from "../interfaces";
|
||||
import { TYPES } from "../types";
|
||||
import LoggerServiceImpl from "./LoggerServiceImpl";
|
||||
|
||||
@injectable()
|
||||
export default class DownloadServiceImpl
|
||||
extends EventEmitter
|
||||
implements DownloadService
|
||||
{
|
||||
private queue: Task[] = [];
|
||||
|
||||
private active: Task[] = [];
|
||||
|
||||
private limit: number;
|
||||
|
||||
private debug = process.env.APP_DOWNLOAD_DEBUG;
|
||||
|
||||
private signal: Record<number, AbortController> = {};
|
||||
|
||||
constructor(
|
||||
@inject(TYPES.LoggerService)
|
||||
private readonly logger: LoggerServiceImpl,
|
||||
@inject(TYPES.VideoRepository)
|
||||
private readonly videoRepository: VideoRepository,
|
||||
@inject(TYPES.StoreService)
|
||||
private readonly storeService: StoreService
|
||||
) {
|
||||
super();
|
||||
|
||||
const maxRunner = this.storeService.get("maxRunner");
|
||||
this.limit = maxRunner;
|
||||
|
||||
this.storeService.onDidChange("maxRunner", (maxRunner) => {
|
||||
maxRunner && (this.limit = maxRunner);
|
||||
});
|
||||
}
|
||||
|
||||
async addTask(task: Task) {
|
||||
this.queue.push(task);
|
||||
this.runTask();
|
||||
}
|
||||
|
||||
async stopTask(id: number) {
|
||||
if (this.signal[id]) {
|
||||
this.log(`taskId: ${id} stop`);
|
||||
this.signal[id].abort();
|
||||
}
|
||||
}
|
||||
|
||||
async execute(task: Task) {
|
||||
try {
|
||||
await this.videoRepository.changeVideoStatus(
|
||||
task.id,
|
||||
DownloadStatus.Downloading
|
||||
);
|
||||
this.emit("download-start", task.id);
|
||||
|
||||
this.log(`taskId: ${task.id} start`);
|
||||
const controller = new AbortController();
|
||||
this.signal[task.id] = controller;
|
||||
await task.process({
|
||||
...task.params,
|
||||
id: task.id,
|
||||
abortSignal: controller,
|
||||
callback: (progress) => {
|
||||
if (progress.type === "progress") {
|
||||
this.emit("download-progress", progress);
|
||||
} else if (progress.type === "ready") {
|
||||
this.emit("download-ready-start", progress);
|
||||
if (progress.isLive) {
|
||||
this.removeTask(progress.id);
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
delete this.signal[task.id];
|
||||
this.log(`taskId: ${task.id} success`);
|
||||
|
||||
await this.videoRepository.changeVideoStatus(
|
||||
task.id,
|
||||
DownloadStatus.Success
|
||||
);
|
||||
this.emit("download-success", task.id);
|
||||
} catch (err: any) {
|
||||
this.log(`taskId: ${task.id} failed`);
|
||||
if (err.name === "AbortError") {
|
||||
// 下载暂停
|
||||
await this.videoRepository.changeVideoStatus(
|
||||
task.id,
|
||||
DownloadStatus.Stopped
|
||||
);
|
||||
this.emit("download-stop", task.id);
|
||||
} else {
|
||||
// 下载失败
|
||||
await this.videoRepository.changeVideoStatus(
|
||||
task.id,
|
||||
DownloadStatus.Failed
|
||||
);
|
||||
this.emit("download-failed", task.id, err);
|
||||
}
|
||||
} finally {
|
||||
this.removeTask(task.id);
|
||||
|
||||
// 传输完成
|
||||
if (this.queue.length === 0 && this.active.length === 0) {
|
||||
// this.emit("download-finish");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
removeTask(id: number) {
|
||||
// 处理当前正在活动的任务
|
||||
const doneId = this.active.findIndex((i) => i.id === id);
|
||||
this.active.splice(doneId, 1);
|
||||
// 处理完成的任务
|
||||
if (this.active.length < this.limit) {
|
||||
this.runTask();
|
||||
}
|
||||
}
|
||||
|
||||
runTask() {
|
||||
while (this.active.length < this.limit && this.queue.length > 0) {
|
||||
const task = this.queue.shift();
|
||||
if (task) {
|
||||
this.active.push(task);
|
||||
this.execute(task);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log(...args: any[]) {
|
||||
if (this.debug) {
|
||||
this.logger.info(`[DownloadService] `, ...args);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import { ipcMain } from "electron";
|
||||
import { inject, injectable, multiInject } from "inversify";
|
||||
import { Controller, IpcHandlerService, LoggerService } from "../interfaces";
|
||||
import { TYPES } from "../types";
|
||||
|
||||
@injectable()
|
||||
export default class IpcHandlerServiceImpl implements IpcHandlerService {
|
||||
constructor(
|
||||
@multiInject(TYPES.Controller)
|
||||
private readonly controllers: Controller[],
|
||||
@inject(TYPES.LoggerService)
|
||||
private readonly logger: LoggerService
|
||||
) {}
|
||||
|
||||
private registerIpc(controller: Controller, property: string | symbol): void {
|
||||
const fun = controller[property];
|
||||
const channel: string = Reflect.getMetadata(
|
||||
"ipc-channel",
|
||||
controller,
|
||||
property
|
||||
);
|
||||
const method: "on" | "handle" = Reflect.getMetadata(
|
||||
"ipc-method",
|
||||
controller,
|
||||
property
|
||||
);
|
||||
if (typeof fun === "function" && method && channel) {
|
||||
ipcMain[method](channel, async (...args: any[]) => {
|
||||
try {
|
||||
const handler = fun.bind(controller);
|
||||
let res = handler(...args);
|
||||
if (res.then) {
|
||||
res = await res;
|
||||
}
|
||||
return this.success(res);
|
||||
} catch (e: any) {
|
||||
this.logger.error("处理 ipc 事件时异常: ", e);
|
||||
if (e instanceof Error) {
|
||||
return this.error(e.message);
|
||||
} else if (typeof e === "string") {
|
||||
return this.error(e);
|
||||
} else {
|
||||
return this.error(String(e));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
success(data: any) {
|
||||
return {
|
||||
code: 0,
|
||||
message: "success",
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
error(message = "fail") {
|
||||
return {
|
||||
code: -1,
|
||||
message,
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
private bindIpcMethods(controller: Controller): void {
|
||||
const Class = Object.getPrototypeOf(controller);
|
||||
Object.getOwnPropertyNames(Class).forEach((property) =>
|
||||
this.registerIpc(controller, property as never)
|
||||
);
|
||||
}
|
||||
|
||||
init(): void {
|
||||
this.controllers.forEach((controller) => this.bindIpcMethods(controller));
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { protocol } from "electron";
|
||||
import isDev from "electron-is-dev";
|
||||
import { pathExists, readFile } from "fs-extra";
|
||||
import { injectable } from "inversify";
|
||||
import { extname, join } from "path";
|
||||
import { URL } from "url";
|
||||
import { defaultScheme } from "../helper/variables";
|
||||
import { ProtocolService } from "../interfaces";
|
||||
|
||||
@injectable()
|
||||
export default class ProtocolServiceImpl implements ProtocolService {
|
||||
create(): void {
|
||||
if (isDev) return;
|
||||
|
||||
protocol.registerBufferProtocol(
|
||||
defaultScheme,
|
||||
async (request, callback) => {
|
||||
let pathName = new URL(request.url).pathname;
|
||||
pathName = decodeURI(pathName);
|
||||
|
||||
const filePath = join(__dirname, "../renderer", pathName);
|
||||
const fileExist = await pathExists(filePath);
|
||||
|
||||
if (fileExist) {
|
||||
const data = await readFile(filePath);
|
||||
const extension = extname(pathName).toLowerCase();
|
||||
let mimeType = "";
|
||||
|
||||
if (extension === ".js") {
|
||||
mimeType = "text/javascript";
|
||||
} else if (extension === ".html") {
|
||||
mimeType = "text/html";
|
||||
} else if (extension === ".css") {
|
||||
mimeType = "text/css";
|
||||
} else if (extension === ".svg" || extension === ".svgz") {
|
||||
mimeType = "image/svg+xml";
|
||||
} else if (extension === ".json") {
|
||||
mimeType = "application/json";
|
||||
}
|
||||
|
||||
callback({ mimeType, data });
|
||||
} else {
|
||||
// 如果没有找到文件,直接返回 index.html , react history 模式
|
||||
const filePath = join(__dirname, "../renderer/index.html");
|
||||
const data = await readFile(filePath);
|
||||
callback({ mimeType: "text/html", data });
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { inject, injectable } from "inversify";
|
||||
import { DownloadType } from "../interfaces";
|
||||
import { TYPES } from "../types";
|
||||
import ElectronLogger from "../vendor/ElectronLogger";
|
||||
import EventEmitter from "events";
|
||||
import { session } from "electron";
|
||||
import { PERSIST_WEBVIEW } from "../helper";
|
||||
import {
|
||||
CallbackResponse,
|
||||
OnBeforeRequestListenerDetails,
|
||||
} from "electron/main";
|
||||
|
||||
export interface SourceParams {
|
||||
id: number;
|
||||
url: string;
|
||||
filter: SourceFilter;
|
||||
documentURL: string;
|
||||
name: string;
|
||||
type: DownloadType;
|
||||
}
|
||||
|
||||
export interface SourceFilter {
|
||||
matches: RegExp[];
|
||||
type: DownloadType;
|
||||
schema?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface PageInfo {
|
||||
title: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
const filterList: SourceFilter[] = [
|
||||
{
|
||||
matches: [/\.m3u8/],
|
||||
type: DownloadType.m3u8,
|
||||
},
|
||||
{
|
||||
// TODO: 合集、列表、收藏夹
|
||||
matches: [/^https?:\/\/(www\.)?bilibili.com\/video/],
|
||||
type: DownloadType.bilibili,
|
||||
schema: {
|
||||
name: "title",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@injectable()
|
||||
export class SniffingHelper extends EventEmitter {
|
||||
private pageInfo: PageInfo = { title: "", url: "" };
|
||||
private ready = false;
|
||||
private queue: SourceParams[] = [];
|
||||
|
||||
constructor(
|
||||
@inject(TYPES.ElectronLogger)
|
||||
private readonly logger: ElectronLogger,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
pluginReady() {
|
||||
this.ready = true;
|
||||
this.queue.forEach((item) => {
|
||||
this.emit("source", item);
|
||||
});
|
||||
}
|
||||
|
||||
reset(pageInfo: PageInfo) {
|
||||
this.pageInfo = pageInfo;
|
||||
this.ready = false;
|
||||
this.queue = [];
|
||||
}
|
||||
|
||||
start() {
|
||||
const viewSession = session.fromPartition(PERSIST_WEBVIEW);
|
||||
viewSession.webRequest.onBeforeRequest(this.requestWillBeSent.bind(this));
|
||||
}
|
||||
|
||||
private requestWillBeSent(
|
||||
details: OnBeforeRequestListenerDetails,
|
||||
callback: (response: CallbackResponse) => void,
|
||||
): void {
|
||||
const { id, webContents, url } = details;
|
||||
const { title } = this.pageInfo;
|
||||
|
||||
const documentURL = webContents?.getURL() || "";
|
||||
|
||||
for (const filter of filterList) {
|
||||
for (const match of filter.matches) {
|
||||
const u = new URL(url);
|
||||
if (!match.test(u.pathname)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const item: SourceParams = {
|
||||
id,
|
||||
url,
|
||||
filter,
|
||||
documentURL,
|
||||
name: title,
|
||||
type: filter.type,
|
||||
};
|
||||
|
||||
this.logger.info(`在窗口中捕获视频链接: ${url}`);
|
||||
// 等待 DOM 中浮窗加载完成
|
||||
if (this.ready) {
|
||||
this.emit("source", item);
|
||||
} else {
|
||||
this.queue.push(item);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
callback({});
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
import {
|
||||
LoggerService,
|
||||
StoreService,
|
||||
VideoRepository,
|
||||
WebService,
|
||||
} from "../interfaces";
|
||||
import { inject, injectable } from "inversify";
|
||||
import Koa, { Context } from "koa";
|
||||
import Router from "@koa/router";
|
||||
import serve from "koa-static";
|
||||
import range from "koa-range";
|
||||
import { TYPES } from "types";
|
||||
import { glob } from "glob";
|
||||
import send from "koa-send";
|
||||
import cors from "@koa/cors";
|
||||
import { getLocalIP, mobilePath } from "helper";
|
||||
|
||||
@injectable()
|
||||
export default class WebServiceImpl implements WebService {
|
||||
private readonly app: Koa;
|
||||
private readonly router: Router;
|
||||
private readonly baseUrl: string;
|
||||
|
||||
constructor(
|
||||
@inject(TYPES.StoreService)
|
||||
private readonly storeService: StoreService,
|
||||
@inject(TYPES.VideoRepository)
|
||||
private readonly videoRepository: VideoRepository,
|
||||
@inject(TYPES.LoggerService)
|
||||
private readonly logger: LoggerService
|
||||
) {
|
||||
this.app = new Koa();
|
||||
this.router = new Router();
|
||||
this.baseUrl = `http://${getLocalIP()}:${
|
||||
process.env.APP_SERVER_PORT
|
||||
}/video/`;
|
||||
}
|
||||
|
||||
async init(): Promise<void> {
|
||||
this.router.get("/api/video-list", this.videoList);
|
||||
this.router.get("/video/:filename", this.serveVideo);
|
||||
const local = this.storeService.get("local");
|
||||
|
||||
this.app.use(cors());
|
||||
this.app.use(range);
|
||||
this.app.use(serve(local));
|
||||
this.app.use(
|
||||
serve(mobilePath, {
|
||||
extensions: ["html", "js", "css"],
|
||||
index: "index.html",
|
||||
})
|
||||
);
|
||||
this.app.use(this.router.routes());
|
||||
this.app.use(this.router.allowedMethods());
|
||||
|
||||
this.app
|
||||
.listen(process.env.APP_SERVER_PORT, () => {
|
||||
this.logger.info("web server init success.");
|
||||
})
|
||||
.on("error", (err: unknown) => {
|
||||
this.logger.error("server error", err);
|
||||
});
|
||||
}
|
||||
|
||||
private videoList = async (ctx: Context) => {
|
||||
const local = this.storeService.get("local");
|
||||
const mp4Files = await glob("*.mp4", {
|
||||
cwd: local,
|
||||
});
|
||||
const videoList = await this.videoRepository.findAllVideos();
|
||||
|
||||
const res = mp4Files
|
||||
.map((file) => {
|
||||
const name = file.split(".").shift();
|
||||
|
||||
const video = videoList.find((video) => video.name === name);
|
||||
if (!video) return null;
|
||||
|
||||
return {
|
||||
id: video.id,
|
||||
name: video.name,
|
||||
url: `${this.baseUrl}${file}`,
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
ctx.body = res;
|
||||
};
|
||||
|
||||
private serveVideo = async (ctx: Context) => {
|
||||
const { filename } = ctx.params;
|
||||
const local = this.storeService.get("local");
|
||||
const file = filename;
|
||||
await send(ctx, file, { root: local, index: false });
|
||||
};
|
||||
}
|
||||
+90
-108
@@ -1,44 +1,36 @@
|
||||
import {
|
||||
BrowserView,
|
||||
CallbackResponse,
|
||||
OnBeforeSendHeadersListenerDetails,
|
||||
session,
|
||||
} from "electron";
|
||||
import {
|
||||
BrowserWindowService,
|
||||
LoggerService,
|
||||
MainWindowService,
|
||||
StoreService,
|
||||
VideoRepository,
|
||||
WebviewService,
|
||||
} from "../interfaces";
|
||||
import { BrowserView, session } from "electron";
|
||||
import { inject, injectable } from "inversify";
|
||||
import { TYPES } from "../types";
|
||||
import isDev from "electron-is-dev";
|
||||
import { PERSIST_WEBVIEW, mobileUA, pcUA } from "helper/variables";
|
||||
import { PERSIST_WEBVIEW, fetch, mobileUA, pcUA, pluginPath } from "../helper";
|
||||
import { ElectronBlocker } from "@cliqz/adblocker-electron";
|
||||
import fetch from "cross-fetch";
|
||||
import path from "path";
|
||||
import { WebSource } from "main";
|
||||
import ElectronLogger from "../vendor/ElectronLogger";
|
||||
import ElectronStore from "../vendor/ElectronStore";
|
||||
import MainWindow from "../windows/MainWindow";
|
||||
import BrowserWindow from "../windows/BrowserWindow";
|
||||
import VideoRepository from "../repository/VideoRepository";
|
||||
import { SniffingHelper } from "./SniffingHelperService";
|
||||
import { resolve } from "path";
|
||||
import { readFileSync } from "fs";
|
||||
|
||||
// FIXME: 需要重构
|
||||
@injectable()
|
||||
export default class WebviewServiceImpl implements WebviewService {
|
||||
export default class WebviewService {
|
||||
public view: BrowserView;
|
||||
private blocker?: ElectronBlocker;
|
||||
private sources = new Set();
|
||||
|
||||
constructor(
|
||||
@inject(TYPES.MainWindowService)
|
||||
private readonly mainWindow: MainWindowService,
|
||||
@inject(TYPES.LoggerService)
|
||||
private readonly logger: LoggerService,
|
||||
@inject(TYPES.BrowserWindowService)
|
||||
private readonly browserWindow: BrowserWindowService,
|
||||
@inject(TYPES.StoreService)
|
||||
private readonly storeService: StoreService,
|
||||
@inject(TYPES.MainWindow)
|
||||
private readonly mainWindow: MainWindow,
|
||||
@inject(TYPES.ElectronLogger)
|
||||
private readonly logger: ElectronLogger,
|
||||
@inject(TYPES.BrowserWindow)
|
||||
private readonly browserWindow: BrowserWindow,
|
||||
@inject(TYPES.ElectronStore)
|
||||
private readonly store: ElectronStore,
|
||||
@inject(TYPES.VideoRepository)
|
||||
private readonly videoRepository: VideoRepository
|
||||
private readonly videoRepository: VideoRepository,
|
||||
@inject(TYPES.SniffingHelper)
|
||||
private readonly sniffingHelper: SniffingHelper,
|
||||
) {
|
||||
// 初始化 blocker
|
||||
this.initBlocker();
|
||||
@@ -48,26 +40,43 @@ export default class WebviewServiceImpl implements WebviewService {
|
||||
this.view = new BrowserView({
|
||||
webPreferences: {
|
||||
partition: PERSIST_WEBVIEW,
|
||||
preload: path.resolve(__dirname, "./webview.js"),
|
||||
preload: resolve(__dirname, "./preload.js"),
|
||||
},
|
||||
});
|
||||
this.view.setBackgroundColor("#fff");
|
||||
this.view.webContents.setAudioMuted(true);
|
||||
this.webContents.setAudioMuted(true);
|
||||
|
||||
const { useProxy, proxy, isMobile } = this.storeService.store;
|
||||
const { useProxy, proxy, isMobile } = this.store.store;
|
||||
this.setProxy(useProxy, proxy);
|
||||
this.setUserAgent(isMobile);
|
||||
|
||||
this.view.webContents.on("dom-ready", () => {
|
||||
this.sources.clear();
|
||||
const title = this.view.webContents.getTitle();
|
||||
const url = this.view.webContents.getURL();
|
||||
this.curWindow?.webContents.send("webview-dom-ready", { title, url });
|
||||
this.webContents.on("dom-ready", async () => {
|
||||
const baseInfo = {
|
||||
title: this.webContents.getTitle(),
|
||||
url: this.webContents.getURL(),
|
||||
};
|
||||
this.sniffingHelper.reset(baseInfo);
|
||||
this.curWindow?.webContents.send("webview-dom-ready", baseInfo);
|
||||
|
||||
try {
|
||||
if (isDev && process.env.DEBUG_PLUGINS === "true") {
|
||||
const content =
|
||||
'function addScript(src){const script=document.createElement("script");script.src=src;script.type="module";document.body.appendChild(script)}addScript("http://localhost:8080/src/main.ts");';
|
||||
await this.webContents.executeJavaScript(content);
|
||||
} else {
|
||||
const content = readFileSync(pluginPath, "utf-8");
|
||||
await this.webContents.executeJavaScript(content);
|
||||
}
|
||||
} catch (err) {
|
||||
// empty
|
||||
}
|
||||
});
|
||||
this.view.webContents.setWindowOpenHandler(({ url }) => {
|
||||
|
||||
// 兼容网站在当前页面中打开
|
||||
this.webContents.setWindowOpenHandler(({ url }) => {
|
||||
if (url === "about:blank") {
|
||||
// 兼容一些网站跳转到 about:blank
|
||||
this.view.webContents.once("will-redirect", async (event, url) => {
|
||||
this.webContents.once("will-redirect", async (event, url) => {
|
||||
this.loadURL(url, true);
|
||||
});
|
||||
} else {
|
||||
@@ -77,8 +86,24 @@ export default class WebviewServiceImpl implements WebviewService {
|
||||
return { action: "deny" };
|
||||
});
|
||||
|
||||
const urls = ["<all_urls>"];
|
||||
this.session.webRequest.onBeforeSendHeaders({ urls }, this.before);
|
||||
this.sniffingHelper.start();
|
||||
this.sniffingHelper.on("source", async (item) => {
|
||||
// 这里需要判断是否使用浏览器插件
|
||||
const useExtension = this.store.get("useExtension");
|
||||
if (useExtension) {
|
||||
this.webContents.send("webview-link-message", item);
|
||||
} else {
|
||||
const video = await this.videoRepository.findVideoByName(item.name);
|
||||
if (video) {
|
||||
item.name = `${item.name}-${Date.now()}`;
|
||||
}
|
||||
const res = await this.videoRepository.addVideo(item);
|
||||
const mainWebContents = this.mainWindow.window?.webContents;
|
||||
if (!mainWebContents) return;
|
||||
// 这里向页面发送消息,通知页面更新
|
||||
mainWebContents.send("download-item-notifier", res);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
getBounds(): Electron.Rectangle {
|
||||
@@ -95,38 +120,37 @@ export default class WebviewServiceImpl implements WebviewService {
|
||||
|
||||
show() {
|
||||
this.curWindow?.setBrowserView(this.view);
|
||||
isDev && this.view.webContents.openDevTools();
|
||||
isDev && this.webContents.openDevTools();
|
||||
}
|
||||
|
||||
hide() {
|
||||
this.curWindow?.setBrowserView(null);
|
||||
isDev && this.view.webContents.closeDevTools();
|
||||
isDev && this.webContents.closeDevTools();
|
||||
}
|
||||
|
||||
setBounds(bounds: Electron.Rectangle): void {
|
||||
if (process.platform === "darwin") {
|
||||
bounds.y = bounds.y + 30;
|
||||
}
|
||||
this.view.setBounds(bounds);
|
||||
}
|
||||
|
||||
async loadURL(url?: string, isNewWindow?: boolean) {
|
||||
const canGoBack = this.view.webContents.canGoBack();
|
||||
const canGoBack = this.webContents.canGoBack();
|
||||
|
||||
try {
|
||||
await this.view.webContents.loadURL(url || "");
|
||||
this.webContents.stop();
|
||||
await this.webContents.loadURL(url || "");
|
||||
} catch (err: unknown) {
|
||||
this.logger.error("加载 url 时出现错误: ", err);
|
||||
throw err;
|
||||
} finally {
|
||||
if (!canGoBack && !isNewWindow) {
|
||||
this.view.webContents.clearHistory();
|
||||
this.webContents.clearHistory();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async goBack() {
|
||||
if (this.view.webContents.canGoBack()) {
|
||||
this.view.webContents.goBack();
|
||||
if (this.webContents.canGoBack()) {
|
||||
this.webContents.goBack();
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
@@ -134,11 +158,12 @@ export default class WebviewServiceImpl implements WebviewService {
|
||||
}
|
||||
|
||||
async reload() {
|
||||
this.view.webContents.reload();
|
||||
this.webContents.reload();
|
||||
}
|
||||
|
||||
async goHome() {
|
||||
this.view.webContents.clearHistory();
|
||||
this.webContents.stop();
|
||||
this.webContents.clearHistory();
|
||||
}
|
||||
|
||||
get curWindow() {
|
||||
@@ -190,7 +215,7 @@ export default class WebviewServiceImpl implements WebviewService {
|
||||
async initBlocker() {
|
||||
this.blocker = await ElectronBlocker.fromPrebuiltAdsAndTracking(fetch);
|
||||
|
||||
const enableBlocking = this.storeService.get("blockAds");
|
||||
const enableBlocking = this.store.get("blockAds");
|
||||
this.setBlocking(enableBlocking);
|
||||
}
|
||||
|
||||
@@ -215,63 +240,20 @@ export default class WebviewServiceImpl implements WebviewService {
|
||||
this.logger.info("关闭 blocker 成功");
|
||||
}
|
||||
|
||||
before = (
|
||||
details: OnBeforeSendHeadersListenerDetails,
|
||||
callback: (response: CallbackResponse) => void
|
||||
): void => {
|
||||
const { url } = details;
|
||||
|
||||
const sourceReg = /\.m3u8$/;
|
||||
const detailsUrl = new URL(url);
|
||||
|
||||
if (sourceReg.test(detailsUrl.pathname)) {
|
||||
try {
|
||||
this.handleM3u8(details);
|
||||
} catch (e) {
|
||||
// empty
|
||||
}
|
||||
}
|
||||
|
||||
callback({});
|
||||
};
|
||||
|
||||
handleM3u8 = async (
|
||||
details: OnBeforeSendHeadersListenerDetails
|
||||
): Promise<void> => {
|
||||
const { id, url } = details;
|
||||
|
||||
this.logger.info(`在窗口中捕获 m3u8 链接: ${url} id: ${id}`);
|
||||
const webContents = details.webContents;
|
||||
|
||||
const source: WebSource = {
|
||||
url,
|
||||
name: webContents?.getTitle() || "没有获取到名称",
|
||||
headers: JSON.stringify(details.requestHeaders),
|
||||
};
|
||||
// 这里需要判断是否使用浏览器插件
|
||||
const useExtension = this.storeService.get("useExtension");
|
||||
|
||||
if (!this.sources.has(source.url)) {
|
||||
this.sources.add(source.url);
|
||||
if (useExtension) {
|
||||
this.view.webContents.send("webview-link-message", source);
|
||||
} else {
|
||||
const item = await this.videoRepository.addVideo(source);
|
||||
// 这里向页面发送消息,通知页面更新
|
||||
this.mainWindow.window?.webContents.send(
|
||||
"download-item-notifier",
|
||||
item
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
setUserAgent(isMobile?: boolean) {
|
||||
if (isMobile) {
|
||||
this.view.webContents.setUserAgent(mobileUA);
|
||||
this.webContents.setUserAgent(mobileUA);
|
||||
} else {
|
||||
this.view.webContents.setUserAgent(pcUA);
|
||||
this.webContents.setUserAgent(pcUA);
|
||||
}
|
||||
this.logger.info("设置 user-agent 成功", isMobile);
|
||||
}
|
||||
|
||||
get debugger() {
|
||||
return this.webContents.debugger;
|
||||
}
|
||||
|
||||
get webContents() {
|
||||
return this.view.webContents;
|
||||
}
|
||||
}
|
||||
+21
-12
@@ -1,22 +1,25 @@
|
||||
export const TYPES = {
|
||||
App: Symbol.for("App"),
|
||||
MainWindowService: Symbol.for("MainWindowService"),
|
||||
StoreService: Symbol.for("StoreService"),
|
||||
SessionService: Symbol.for("SessionService"),
|
||||
DatabaseService: Symbol.for("DatabaseService"),
|
||||
ProtocolService: Symbol.for("ProtocolService"),
|
||||
UpdateService: Symbol.for("UpdateService"),
|
||||
LoggerService: Symbol.for("LoggerService"),
|
||||
ElectronApp: Symbol.for("ElectronApp"),
|
||||
IpcHandlerService: Symbol.for("IpcHandlerService"),
|
||||
Controller: Symbol.for("Controller"),
|
||||
// repository
|
||||
VideoRepository: Symbol.for("VideoRepository"),
|
||||
FavoriteRepository: Symbol.for("FavoriteRepository"),
|
||||
// windows
|
||||
BrowserWindow: Symbol.for("BrowserWindow"),
|
||||
MainWindow: Symbol.for("MainWindow"),
|
||||
// services
|
||||
WebviewService: Symbol.for("WebviewService"),
|
||||
DownloadService: Symbol.for("DownloadService"),
|
||||
BrowserWindowService: Symbol.for("BrowserWindowService"),
|
||||
DevToolsService: Symbol.for("DevToolsService"),
|
||||
WebService: Symbol.for("WebService"),
|
||||
PlayerWindowService: Symbol.for("PlayerWindowService"),
|
||||
SessionService: Symbol.for("SessionService"),
|
||||
ProtocolService: Symbol.for("ProtocolService"),
|
||||
SniffingHelper: Symbol.for("SniffingHelper"),
|
||||
// vendor
|
||||
ElectronLogger: Symbol.for("ElectronLogger"),
|
||||
ElectronUpdater: Symbol.for("ElectronUpdater"),
|
||||
ElectronStore: Symbol.for("ElectronStore"),
|
||||
ElectronDevtools: Symbol.for("ElectronDevtools"),
|
||||
TypeORM: Symbol.for("TypeORM"),
|
||||
};
|
||||
|
||||
export enum AppTheme {
|
||||
@@ -24,3 +27,9 @@ export enum AppTheme {
|
||||
Light = "light",
|
||||
Dark = "dark",
|
||||
}
|
||||
|
||||
export enum AppLanguage {
|
||||
System = "system",
|
||||
ZH = "zh",
|
||||
EN = "en",
|
||||
}
|
||||
|
||||
Vendored
+7
-6
@@ -1,4 +1,3 @@
|
||||
import { DevToolsService, LoggerService } from "../interfaces";
|
||||
import { inject, injectable } from "inversify";
|
||||
import { TYPES } from "../types";
|
||||
import isDev from "electron-is-dev";
|
||||
@@ -6,15 +5,17 @@ import installExtension, {
|
||||
REDUX_DEVTOOLS,
|
||||
REACT_DEVELOPER_TOOLS,
|
||||
} from "electron-devtools-installer";
|
||||
import ElectronLogger from "./ElectronLogger";
|
||||
import { Vendor } from "../core/vendor";
|
||||
|
||||
@injectable()
|
||||
export default class DevToolsServiceImpl implements DevToolsService {
|
||||
export default class DevToolsService implements Vendor {
|
||||
constructor(
|
||||
@inject(TYPES.LoggerService)
|
||||
private readonly logger: LoggerService
|
||||
@inject(TYPES.ElectronLogger)
|
||||
private readonly logger: ElectronLogger,
|
||||
) {}
|
||||
|
||||
async init(): Promise<void> {
|
||||
async init() {
|
||||
if (!isDev) {
|
||||
return;
|
||||
}
|
||||
@@ -27,7 +28,7 @@ export default class DevToolsServiceImpl implements DevToolsService {
|
||||
this.logger.debug("当前环境为开发环境,开始加载开发者工具");
|
||||
await installExtension([REDUX_DEVTOOLS, REACT_DEVELOPER_TOOLS]);
|
||||
this.logger.debug("加载开发者工具成功");
|
||||
} catch (err: any) {
|
||||
} catch (err: unknown) {
|
||||
this.logger.error("加载开发者工具失败", err);
|
||||
}
|
||||
}
|
||||
Vendored
+11
-9
@@ -1,36 +1,38 @@
|
||||
import logger, { ElectronLog } from "electron-log";
|
||||
import logger, { Logger } from "electron-log";
|
||||
import { injectable } from "inversify";
|
||||
import dayjs from "dayjs";
|
||||
import path from "path";
|
||||
import { appName, workspace } from "../helper";
|
||||
import { LoggerService } from "../interfaces";
|
||||
import { Vendor } from "../core/vendor";
|
||||
|
||||
@injectable()
|
||||
export default class LoggerServiceImpl implements LoggerService {
|
||||
logger: ElectronLog;
|
||||
export default class ElectronLogger implements Vendor {
|
||||
logger: Logger;
|
||||
|
||||
constructor() {
|
||||
const datetime = dayjs().format("YYYY-MM-DD");
|
||||
const logPath = path.resolve(workspace, `logs/${datetime}-${appName}.log`);
|
||||
logger.transports.console.format = "{h}:{i}:{s} {text}";
|
||||
logger.transports.file.getFile();
|
||||
logger.transports.file.resolvePath = () => logPath;
|
||||
logger.transports.file.resolvePathFn = () => logPath;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
info(...args: any[]) {
|
||||
info(...args: unknown[]) {
|
||||
return this.logger.info(...args);
|
||||
}
|
||||
|
||||
warn(...args: any[]) {
|
||||
warn(...args: unknown[]) {
|
||||
return this.logger.warn(...args);
|
||||
}
|
||||
|
||||
error(...args: any[]) {
|
||||
error(...args: unknown[]) {
|
||||
return this.logger.error(...args);
|
||||
}
|
||||
|
||||
debug(...args: any[]) {
|
||||
debug(...args: unknown[]) {
|
||||
return this.logger.debug(...args);
|
||||
}
|
||||
|
||||
async init() {}
|
||||
}
|
||||
+9
-11
@@ -1,15 +1,12 @@
|
||||
import Store from "electron-store";
|
||||
import { injectable } from "inversify";
|
||||
import { AppStore } from "main";
|
||||
import { download, workspace } from "../helper/variables";
|
||||
import { StoreService } from "../interfaces";
|
||||
import { AppTheme } from "types";
|
||||
import { AppStore } from "../main";
|
||||
import { download, workspace } from "../helper";
|
||||
import { AppLanguage, AppTheme } from "../types";
|
||||
import { Vendor } from "../core/vendor";
|
||||
|
||||
@injectable()
|
||||
export default class StoreServiceImpl
|
||||
extends Store<AppStore>
|
||||
implements StoreService
|
||||
{
|
||||
export default class StoreService extends Store<AppStore> implements Vendor {
|
||||
constructor() {
|
||||
super({
|
||||
name: "config",
|
||||
@@ -28,11 +25,12 @@ export default class StoreServiceImpl
|
||||
useExtension: false,
|
||||
isMobile: false,
|
||||
maxRunner: 2,
|
||||
language: AppLanguage.System,
|
||||
showTerminal: false,
|
||||
privacy: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
init(): void {
|
||||
// empty
|
||||
}
|
||||
async init() {}
|
||||
}
|
||||
Vendored
+5
-4
@@ -1,16 +1,17 @@
|
||||
import { autoUpdater } from "electron-updater";
|
||||
import { inject, injectable } from "inversify";
|
||||
import { LoggerService, type UpdateService } from "../interfaces";
|
||||
import { TYPES } from "../types";
|
||||
import isDev from "electron-is-dev";
|
||||
import ElectronLogger from "./ElectronLogger";
|
||||
import { Vendor } from "../core/vendor";
|
||||
|
||||
@injectable()
|
||||
export default class UpdateServiceImpl implements UpdateService {
|
||||
export default class UpdateService implements Vendor {
|
||||
constructor(
|
||||
@inject(TYPES.LoggerService) private readonly logger: LoggerService
|
||||
@inject(TYPES.ElectronLogger) private readonly logger: ElectronLogger,
|
||||
) {}
|
||||
|
||||
async init(): Promise<void> {
|
||||
async init() {
|
||||
if (isDev) return;
|
||||
|
||||
try {
|
||||
+8
-7
@@ -1,18 +1,19 @@
|
||||
import { db } from "../helper/variables";
|
||||
import { db } from "../helper";
|
||||
import { inject, injectable } from "inversify";
|
||||
import { DataSource, EntityManager } from "typeorm";
|
||||
import { TYPES } from "../types";
|
||||
import { DatabaseService, LoggerService } from "../interfaces";
|
||||
import { Video } from "../entity/Video";
|
||||
import { Favorite } from "entity/Favorite";
|
||||
import { Favorite } from "../entity/Favorite";
|
||||
import ElectronLogger from "./ElectronLogger";
|
||||
import { Vendor } from "../core/vendor";
|
||||
|
||||
@injectable()
|
||||
export default class DatabaseServiceImpl implements DatabaseService {
|
||||
export default class DatabaseService implements Vendor {
|
||||
appDataSource: DataSource;
|
||||
|
||||
constructor(
|
||||
@inject(TYPES.LoggerService)
|
||||
private readonly logger: LoggerService
|
||||
@inject(TYPES.ElectronLogger)
|
||||
private readonly logger: ElectronLogger,
|
||||
) {
|
||||
this.appDataSource = new DataSource({
|
||||
type: "better-sqlite3",
|
||||
@@ -25,7 +26,7 @@ export default class DatabaseServiceImpl implements DatabaseService {
|
||||
});
|
||||
}
|
||||
|
||||
async init(): Promise<void> {
|
||||
async init() {
|
||||
this.logger.info("数据库地址是: ", db);
|
||||
await this.appDataSource.initialize();
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import { WebSource } from "main";
|
||||
import { IpcRendererEvent, ipcRenderer } from "electron/renderer";
|
||||
|
||||
// 创建浮窗容器元素
|
||||
const floatingContainer = document.createElement("div");
|
||||
floatingContainer.style.cssText = `
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: 200px;
|
||||
z-index: 10000;
|
||||
display: none;
|
||||
font-size: 16px;
|
||||
`;
|
||||
|
||||
// 创建浮窗按钮元素
|
||||
const floatingButton = document.createElement("div");
|
||||
floatingButton.textContent = "检测到视频资源……";
|
||||
floatingButton.style.cssText = `
|
||||
background-color: #000;
|
||||
color: #fff;
|
||||
padding: 10px;
|
||||
cursor: pointer;
|
||||
opacity: 0.8;
|
||||
`;
|
||||
|
||||
// 创建浮窗列表元素
|
||||
const floatingList = document.createElement("ul");
|
||||
floatingList.style.cssText = `
|
||||
display: none;
|
||||
background-color: #000;
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
`;
|
||||
|
||||
const itemStyle = `
|
||||
padding: 10px;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
`;
|
||||
|
||||
const items: WebSource[] = [];
|
||||
ipcRenderer.on(
|
||||
"webview-link-message",
|
||||
(e: IpcRendererEvent, data: WebSource) => {
|
||||
floatingContainer.style.display = "block";
|
||||
|
||||
items.push(data);
|
||||
|
||||
// 清空列表
|
||||
while (floatingList?.firstChild) {
|
||||
floatingList.removeChild(floatingList.firstChild);
|
||||
}
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
// 创建列表项元素
|
||||
const elItem = document.createElement("li");
|
||||
elItem.textContent = item.name;
|
||||
elItem.title = item.name;
|
||||
elItem.style.cssText = itemStyle;
|
||||
elItem.addEventListener("click", () => {
|
||||
ipcRenderer.invoke("add-download-item", {
|
||||
name: data.name,
|
||||
url: data.url,
|
||||
});
|
||||
});
|
||||
elItem.addEventListener("mouseenter", () => {
|
||||
elItem.style.backgroundColor = "#fff";
|
||||
elItem.style.color = "#000";
|
||||
});
|
||||
elItem.addEventListener("mouseleave", () => {
|
||||
elItem.style.backgroundColor = "#000";
|
||||
elItem.style.color = "#fff";
|
||||
});
|
||||
|
||||
// 将列表项添加到浮窗列表
|
||||
floatingList.appendChild(elItem);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// 将按钮和列表添加到浮窗容器
|
||||
floatingContainer.appendChild(floatingList);
|
||||
floatingContainer.appendChild(floatingButton);
|
||||
|
||||
// 鼠标进入浮窗按钮时的处理函数
|
||||
floatingContainer.addEventListener("mouseenter", () => {
|
||||
floatingButton.style.opacity = "1";
|
||||
floatingList.style.display = "block";
|
||||
});
|
||||
|
||||
// 鼠标离开浮窗按钮时的处理函数
|
||||
floatingContainer.addEventListener("mouseleave", () => {
|
||||
floatingButton.style.opacity = "0.8";
|
||||
floatingList.style.display = "none";
|
||||
});
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
// 将浮窗容器添加到body元素
|
||||
document.body.appendChild(floatingContainer);
|
||||
});
|
||||
@@ -2,22 +2,19 @@ import isDev from "electron-is-dev";
|
||||
import { inject, injectable } from "inversify";
|
||||
import { resolve } from "path";
|
||||
import { TYPES } from "../types";
|
||||
import { BrowserWindowService, StoreService } from "../interfaces";
|
||||
import _ from "lodash";
|
||||
import Window from "./window";
|
||||
import Window from "../core/window";
|
||||
import ElectronStore from "../vendor/ElectronStore";
|
||||
|
||||
@injectable()
|
||||
export default class BrowserWindowServiceImpl
|
||||
extends Window
|
||||
implements BrowserWindowService
|
||||
{
|
||||
export default class BrowserWindow extends Window {
|
||||
url = isDev
|
||||
? "http://localhost:8555/browser"
|
||||
: "mediago://index.html/browser";
|
||||
|
||||
constructor(
|
||||
@inject(TYPES.StoreService)
|
||||
private readonly storeService: StoreService
|
||||
@inject(TYPES.ElectronStore)
|
||||
private readonly store: ElectronStore,
|
||||
) {
|
||||
super({
|
||||
width: 1100,
|
||||
@@ -31,8 +28,8 @@ export default class BrowserWindowServiceImpl
|
||||
},
|
||||
});
|
||||
|
||||
this.storeService.onDidChange("openInNewWindow", this.handleNewWindowsVal);
|
||||
this.storeService.onDidAnyChange(this.storeChange);
|
||||
this.store.onDidChange("openInNewWindow", this.handleNewWindowsVal);
|
||||
this.store.onDidAnyChange(this.storeChange);
|
||||
}
|
||||
|
||||
storeChange = (store: any) => {
|
||||
@@ -56,7 +53,7 @@ export default class BrowserWindowServiceImpl
|
||||
if (!this.window) return;
|
||||
|
||||
const bounds = this.window.getBounds();
|
||||
this.storeService.set("browserBounds", _.omit(bounds, ["x", "y"]));
|
||||
this.store.set("browserBounds", _.omit(bounds, ["x", "y"]));
|
||||
};
|
||||
|
||||
showWindow = () => {
|
||||
@@ -68,7 +65,7 @@ export default class BrowserWindowServiceImpl
|
||||
this.window.show();
|
||||
isDev && this.window.webContents.openDevTools();
|
||||
|
||||
const browserBounds = this.storeService.get("browserBounds");
|
||||
const browserBounds = this.store.get("browserBounds");
|
||||
if (browserBounds) {
|
||||
this.window.setBounds(browserBounds);
|
||||
}
|
||||
@@ -3,33 +3,27 @@ import isDev from "electron-is-dev";
|
||||
import { inject, injectable } from "inversify";
|
||||
import { resolve } from "path";
|
||||
import { TYPES } from "../types";
|
||||
import {
|
||||
DownloadProgress,
|
||||
DownloadService,
|
||||
LoggerService,
|
||||
MainWindowService,
|
||||
StoreService,
|
||||
VideoRepository,
|
||||
} from "../interfaces";
|
||||
import { event } from "helper/utils";
|
||||
import { DownloadProgress } from "../interfaces";
|
||||
import _ from "lodash";
|
||||
import Window from "./window";
|
||||
import Window from "../core/window";
|
||||
import ElectronLogger from "../vendor/ElectronLogger";
|
||||
import DownloadService from "../services/DownloadService";
|
||||
import ElectronStore from "../vendor/ElectronStore";
|
||||
import VideoRepository from "../repository/VideoRepository";
|
||||
import { isWin } from "../helper";
|
||||
|
||||
@injectable()
|
||||
export default class MainWindowServiceImpl
|
||||
extends Window
|
||||
implements MainWindowService
|
||||
{
|
||||
export default class MainWindow extends Window {
|
||||
url = isDev ? "http://localhost:8555/" : "mediago://index.html/";
|
||||
constructor(
|
||||
@inject(TYPES.LoggerService)
|
||||
private readonly logger: LoggerService,
|
||||
@inject(TYPES.ElectronLogger)
|
||||
private readonly logger: ElectronLogger,
|
||||
@inject(TYPES.DownloadService)
|
||||
private readonly downloadService: DownloadService,
|
||||
@inject(TYPES.VideoRepository)
|
||||
private readonly videoRepository: VideoRepository,
|
||||
@inject(TYPES.StoreService)
|
||||
private readonly storeService: StoreService
|
||||
@inject(TYPES.ElectronStore)
|
||||
private readonly store: ElectronStore,
|
||||
) {
|
||||
super({
|
||||
width: 1100,
|
||||
@@ -48,8 +42,9 @@ export default class MainWindowServiceImpl
|
||||
this.downloadService.on("download-success", this.onDownloadSuccess);
|
||||
this.downloadService.on("download-failed", this.onDownloadFailed);
|
||||
this.downloadService.on("download-start", this.onDownloadStart);
|
||||
this.downloadService.on("download-stop", this.onDownloadStart);
|
||||
this.storeService.onDidAnyChange(this.storeChange);
|
||||
this.downloadService.on("download-stop", this.onDownloadStop);
|
||||
this.downloadService.on("download-message", this.receiveMessage);
|
||||
this.store.onDidAnyChange(this.storeChange);
|
||||
app.on("second-instance", this.secondInstance);
|
||||
}
|
||||
|
||||
@@ -69,7 +64,7 @@ export default class MainWindowServiceImpl
|
||||
|
||||
this.window = this.create();
|
||||
|
||||
const mainBounds = this.storeService.get("mainBounds");
|
||||
const mainBounds = this.store.get("mainBounds");
|
||||
if (mainBounds) {
|
||||
this.window.setBounds(mainBounds);
|
||||
}
|
||||
@@ -82,12 +77,12 @@ export default class MainWindowServiceImpl
|
||||
if (!this.window) return;
|
||||
|
||||
const bounds = this.window.getBounds();
|
||||
this.storeService.set("mainBounds", _.omit(bounds, ["x", "y"]));
|
||||
this.store.set("mainBounds", _.omit(bounds, ["x", "y"]));
|
||||
};
|
||||
|
||||
secondInstance = () => {
|
||||
if (!this.window) return;
|
||||
if (process.platform === "win32") {
|
||||
if (isWin) {
|
||||
if (this.window) {
|
||||
if (this.window.isMinimized()) {
|
||||
this.window.restore();
|
||||
@@ -111,7 +106,7 @@ export default class MainWindowServiceImpl
|
||||
};
|
||||
|
||||
onDownloadSuccess = async (id: number) => {
|
||||
const promptTone = this.storeService.get("promptTone");
|
||||
const promptTone = this.store.get("promptTone");
|
||||
if (promptTone) {
|
||||
const video = await this.videoRepository.findVideo(id);
|
||||
|
||||
@@ -125,7 +120,7 @@ export default class MainWindowServiceImpl
|
||||
};
|
||||
|
||||
onDownloadFailed = async (id: number, err: any) => {
|
||||
const promptTone = this.storeService.get("promptTone");
|
||||
const promptTone = this.store.get("promptTone");
|
||||
if (promptTone) {
|
||||
const video = await this.videoRepository.findVideo(id);
|
||||
|
||||
@@ -146,6 +141,15 @@ export default class MainWindowServiceImpl
|
||||
this.send("download-stop", id);
|
||||
};
|
||||
|
||||
receiveMessage = async (id: number, message: string) => {
|
||||
// 将日志写入数据库中
|
||||
await this.videoRepository.appendDownloadLog(id, message);
|
||||
const showTerminal = this.store.get("showTerminal");
|
||||
if (showTerminal) {
|
||||
this.send("download-message", id, message);
|
||||
}
|
||||
};
|
||||
|
||||
send(channel: string, ...args: any[]) {
|
||||
if (!this.window) return;
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import isDev from "electron-is-dev";
|
||||
import { inject, injectable } from "inversify";
|
||||
import { resolve } from "path";
|
||||
import { PlayerWindowService, VideoRepository } from "../interfaces";
|
||||
import { TYPES } from "types";
|
||||
import Window from "./window";
|
||||
|
||||
@injectable()
|
||||
export default class PlayerWindowServiceImpl
|
||||
extends Window
|
||||
implements PlayerWindowService
|
||||
{
|
||||
url = isDev ? "http://localhost:8555/player" : "mediago://index.html/player";
|
||||
|
||||
constructor(
|
||||
@inject(TYPES.VideoRepository)
|
||||
private readonly videoRepository: VideoRepository
|
||||
) {
|
||||
super({
|
||||
width: 1100,
|
||||
minWidth: 1100,
|
||||
height: 680,
|
||||
minHeight: 680,
|
||||
show: false,
|
||||
frame: true,
|
||||
webPreferences: {
|
||||
preload: resolve(__dirname, "./preload.js"),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
openWindow = async (id: number) => {
|
||||
if (!this.window) {
|
||||
this.window = this.create();
|
||||
}
|
||||
|
||||
const video = await this.videoRepository.findVideo(id);
|
||||
if (!video) throw new Error("video not found");
|
||||
|
||||
isDev && this.window.webContents.openDevTools();
|
||||
this.window.webContents.send("open-player-window", video.id);
|
||||
this.window.show();
|
||||
};
|
||||
}
|
||||
@@ -6,14 +6,21 @@
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"baseUrl": "./src",
|
||||
"resolveJsonModule": true,
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"moduleResolution": "Node",
|
||||
"strictPropertyInitialization": false,
|
||||
"typeRoots": ["node_modules/@types"],
|
||||
"declaration": true,
|
||||
"emitDeclarationOnly": true,
|
||||
"declarationDir": "./types",
|
||||
"outDir": "app/output/build/main"
|
||||
},
|
||||
"include": ["./src/**/*"]
|
||||
"include": ["src"],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"composite": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "ES2015",
|
||||
"moduleResolution": "Node",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["script", "app/package.json"]
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
/* eslint-env node */
|
||||
require("@rushstack/eslint-patch/modern-module-resolution");
|
||||
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: [
|
||||
"plugin:vue/vue3-essential",
|
||||
"eslint:recommended",
|
||||
"@vue/eslint-config-typescript",
|
||||
"@vue/eslint-config-prettier/skip-formatting",
|
||||
],
|
||||
parserOptions: {
|
||||
ecmaVersion: "latest",
|
||||
},
|
||||
rules: {
|
||||
"prettier/prettier": "error",
|
||||
},
|
||||
};
|
||||
@@ -1,71 +0,0 @@
|
||||
# mobile-player
|
||||
|
||||
This template should help get you started developing with Vue 3 in Vite.
|
||||
|
||||
## Recommended IDE Setup
|
||||
|
||||
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).
|
||||
|
||||
## Type Support for `.vue` Imports in TS
|
||||
|
||||
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin) to make the TypeScript language service aware of `.vue` types.
|
||||
|
||||
If the standalone TypeScript plugin doesn't feel fast enough to you, Volar has also implemented a [Take Over Mode](https://github.com/johnsoncodehk/volar/discussions/471#discussioncomment-1361669) that is more performant. You can enable it by the following steps:
|
||||
|
||||
1. Disable the built-in TypeScript Extension
|
||||
1. Run `Extensions: Show Built-in Extensions` from VSCode's command palette
|
||||
2. Find `TypeScript and JavaScript Language Features`, right click and select `Disable (Workspace)`
|
||||
2. Reload the VSCode window by running `Developer: Reload Window` from the command palette.
|
||||
|
||||
## Customize configuration
|
||||
|
||||
See [Vite Configuration Reference](https://vitejs.dev/config/).
|
||||
|
||||
## Project Setup
|
||||
|
||||
```sh
|
||||
npm install
|
||||
```
|
||||
|
||||
### Compile and Hot-Reload for Development
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Type-Check, Compile and Minify for Production
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
```
|
||||
|
||||
### Run Unit Tests with [Vitest](https://vitest.dev/)
|
||||
|
||||
```sh
|
||||
npm run test:unit
|
||||
```
|
||||
|
||||
### Run End-to-End Tests with [Playwright](https://playwright.dev)
|
||||
|
||||
```sh
|
||||
# Install browsers for the first run
|
||||
npx playwright install
|
||||
|
||||
# When testing on CI, must build the project first
|
||||
npm run build
|
||||
|
||||
# Runs the end-to-end tests
|
||||
npm run test:e2e
|
||||
# Runs the tests only on Chromium
|
||||
npm run test:e2e -- --project=chromium
|
||||
# Runs the tests of a specific file
|
||||
npm run test:e2e -- tests/example.spec.ts
|
||||
# Runs the tests in debug mode
|
||||
npm run test:e2e -- --debug
|
||||
```
|
||||
|
||||
### Lint with [ESLint](https://eslint.org/)
|
||||
|
||||
```sh
|
||||
npm run lint
|
||||
```
|
||||
Vendored
-17
@@ -1,17 +0,0 @@
|
||||
/* eslint-disable */
|
||||
/* prettier-ignore */
|
||||
// @ts-nocheck
|
||||
// Generated by unplugin-vue-components
|
||||
// Read more: https://github.com/vuejs/core/pull/3399
|
||||
export {}
|
||||
|
||||
declare module 'vue' {
|
||||
export interface GlobalComponents {
|
||||
RouterLink: typeof import('vue-router')['RouterLink']
|
||||
RouterView: typeof import('vue-router')['RouterView']
|
||||
VanCell: typeof import('vant/es')['Cell']
|
||||
VanEmpty: typeof import('vant/es')['Empty']
|
||||
VanList: typeof import('vant/es')['List']
|
||||
VanNavBar: typeof import('vant/es')['NavBar']
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"extends": "@tsconfig/node18/tsconfig.json",
|
||||
"include": ["./**/*"]
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
|
||||
// See here how to get started:
|
||||
// https://playwright.dev/docs/intro
|
||||
test("visits the app root url", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
await expect(page.locator("div.greetings > h1")).toHaveText("You did it!");
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Vite App</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,47 +0,0 @@
|
||||
{
|
||||
"name": "mobile",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev:mobile": "vite",
|
||||
"build": "run-p type-check build-only",
|
||||
"preview": "vite preview",
|
||||
"test:unit": "vitest",
|
||||
"test:e2e": "playwright test",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --noEmit -p tsconfig.vitest.json --composite false",
|
||||
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
|
||||
"format": "prettier --write src/"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.4.0",
|
||||
"pinia": "^2.1.4",
|
||||
"vant": "^4.5.0",
|
||||
"vue": "^3.3.4",
|
||||
"vue-router": "^4.2.2",
|
||||
"xgplayer": "^3.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.35.1",
|
||||
"@rushstack/eslint-patch": "^1.3.2",
|
||||
"@tsconfig/node18": "^2.0.1",
|
||||
"@types/jsdom": "^21.1.1",
|
||||
"@types/node": "^20.3.1",
|
||||
"@vitejs/plugin-vue": "^4.2.3",
|
||||
"@vitejs/plugin-vue-jsx": "^3.0.1",
|
||||
"@vue/eslint-config-prettier": "^7.1.0",
|
||||
"@vue/eslint-config-typescript": "^11.0.3",
|
||||
"@vue/test-utils": "^2.4.0",
|
||||
"@vue/tsconfig": "^0.4.0",
|
||||
"eslint": "^8.43.0",
|
||||
"eslint-plugin-vue": "^9.15.0",
|
||||
"jsdom": "^22.1.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"prettier": "^2.8.8",
|
||||
"typescript": "~5.1.3",
|
||||
"unplugin-vue-components": "^0.25.1",
|
||||
"vite": "^4.3.9",
|
||||
"vitest": "^0.32.2",
|
||||
"vue-tsc": "^1.8.1"
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
import type { PlaywrightTestConfig } from "@playwright/test";
|
||||
import { devices } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* Read environment variables from file.
|
||||
* https://github.com/motdotla/dotenv
|
||||
*/
|
||||
// require('dotenv').config();
|
||||
|
||||
/**
|
||||
* See https://playwright.dev/docs/test-configuration.
|
||||
*/
|
||||
const config: PlaywrightTestConfig = {
|
||||
testDir: "./e2e",
|
||||
/* Maximum time one test can run for. */
|
||||
timeout: 30 * 1000,
|
||||
expect: {
|
||||
/**
|
||||
* Maximum time expect() should wait for the condition to be met.
|
||||
* For example in `await expect(locator).toHaveText();`
|
||||
*/
|
||||
timeout: 5000,
|
||||
},
|
||||
/* Fail the build on CI if you accidentally left test.only in the source code. */
|
||||
forbidOnly: !!process.env.CI,
|
||||
/* Retry on CI only */
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
/* Opt out of parallel tests on CI. */
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
|
||||
reporter: "html",
|
||||
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
|
||||
use: {
|
||||
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
|
||||
actionTimeout: 0,
|
||||
/* Base URL to use in actions like `await page.goto('/')`. */
|
||||
baseURL: "http://localhost:5173",
|
||||
|
||||
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||
trace: "on-first-retry",
|
||||
|
||||
/* Only on CI systems run the tests headless */
|
||||
headless: !!process.env.CI,
|
||||
},
|
||||
|
||||
/* Configure projects for major browsers */
|
||||
projects: [
|
||||
{
|
||||
name: "chromium",
|
||||
use: {
|
||||
...devices["Desktop Chrome"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "firefox",
|
||||
use: {
|
||||
...devices["Desktop Firefox"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "webkit",
|
||||
use: {
|
||||
...devices["Desktop Safari"],
|
||||
},
|
||||
},
|
||||
|
||||
/* Test against mobile viewports. */
|
||||
// {
|
||||
// name: 'Mobile Chrome',
|
||||
// use: {
|
||||
// ...devices['Pixel 5'],
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// name: 'Mobile Safari',
|
||||
// use: {
|
||||
// ...devices['iPhone 12'],
|
||||
// },
|
||||
// },
|
||||
|
||||
/* Test against branded browsers. */
|
||||
// {
|
||||
// name: 'Microsoft Edge',
|
||||
// use: {
|
||||
// channel: 'msedge',
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// name: 'Google Chrome',
|
||||
// use: {
|
||||
// channel: 'chrome',
|
||||
// },
|
||||
// },
|
||||
],
|
||||
|
||||
/* Folder for test artifacts such as screenshots, videos, traces, etc. */
|
||||
// outputDir: 'test-results/',
|
||||
|
||||
/* Run your local dev server before starting the tests */
|
||||
webServer: {
|
||||
/**
|
||||
* Use the dev server by default for faster feedback loop.
|
||||
* Use the preview server on CI for more realistic testing.
|
||||
Playwright will re-use the local server if there is already a dev-server running.
|
||||
*/
|
||||
command: process.env.CI ? "vite preview --port 5173" : "vite dev",
|
||||
port: 5173,
|
||||
reuseExistingServer: !process.env.CI,
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 4.2 KiB |
@@ -1,10 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { RouterView } from "vue-router";
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<van-nav-bar title="视频播放" />
|
||||
<RouterView />
|
||||
</template>
|
||||
|
||||
<style scoped></style>
|
||||
@@ -1,14 +0,0 @@
|
||||
import "./assets/main.css";
|
||||
|
||||
import { createApp } from "vue";
|
||||
import { createPinia } from "pinia";
|
||||
|
||||
import App from "./App.vue";
|
||||
import router from "./router";
|
||||
|
||||
const app = createApp(App);
|
||||
|
||||
app.use(createPinia());
|
||||
app.use(router);
|
||||
|
||||
app.mount("#app");
|
||||
@@ -1,14 +0,0 @@
|
||||
import { createRouter, createWebHistory } from "vue-router";
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(import.meta.env.BASE_URL),
|
||||
routes: [
|
||||
{
|
||||
path: "/",
|
||||
name: "home",
|
||||
component: () => import("../views/HomeView.vue"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -1,12 +0,0 @@
|
||||
import { ref, computed } from "vue";
|
||||
import { defineStore } from "pinia";
|
||||
|
||||
export const useCounterStore = defineStore("counter", () => {
|
||||
const count = ref(0);
|
||||
const doubleCount = computed(() => count.value * 2);
|
||||
function increment() {
|
||||
count.value++;
|
||||
}
|
||||
|
||||
return { count, doubleCount, increment };
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
import Player, { type IPlayerOptions } from "xgplayer";
|
||||
import "xgplayer/dist/index.min.css";
|
||||
import axios from "axios";
|
||||
|
||||
interface VideoData {
|
||||
id: number;
|
||||
name: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
const videoRef = ref(null);
|
||||
const player = ref<Player | null>(null);
|
||||
const list = ref<VideoData[]>([]);
|
||||
|
||||
onMounted(async () => {
|
||||
const res = await axios.get(`/api/video-list`);
|
||||
if (videoRef.value) {
|
||||
const options: IPlayerOptions = {
|
||||
el: videoRef.value,
|
||||
fluid: true,
|
||||
videoInit: true,
|
||||
};
|
||||
if (Array.isArray(res.data) && res.data.length > 0) {
|
||||
list.value = res.data;
|
||||
options.src = list.value[0].url;
|
||||
}
|
||||
player.value = new Player(options);
|
||||
}
|
||||
});
|
||||
|
||||
function itemClick(item: VideoData) {
|
||||
if (!player.value) return;
|
||||
|
||||
player.value.src = item.url;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main>
|
||||
<div v-show="list.length" ref="videoRef"></div>
|
||||
<div v-if="list.length">
|
||||
<van-list finished-text="没有更多了">
|
||||
<van-cell
|
||||
v-for="item in list"
|
||||
:key="item.id"
|
||||
:title="item.name"
|
||||
@click="itemClick(item)"
|
||||
/>
|
||||
</van-list>
|
||||
</div>
|
||||
<van-empty v-else description="暂无视频" />
|
||||
</main>
|
||||
</template>
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
|
||||
"exclude": ["src/**/__tests__/*"],
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.vitest.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"extends": "@tsconfig/node18/tsconfig.json",
|
||||
"include": [
|
||||
"vite.config.*",
|
||||
"vitest.config.*",
|
||||
"cypress.config.*",
|
||||
"playwright.config.*"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"module": "ESNext",
|
||||
"types": ["node"]
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"extends": "./tsconfig.app.json",
|
||||
"exclude": [],
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"lib": [],
|
||||
"types": ["node", "jsdom"]
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user