Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(hook): Add customize Netease Cookie #1342

Merged
merged 3 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ node app.js -o bilibili ytdlp
| SIGN_CERT | path | 自定义证书文件 | `SIGN_CERT="./server.crt"` |
| SIGN_KEY | path | 自定义密钥文件 | `SIGN_KEY="./server.key"` |
| SEARCH_ALBUM | bool | 在其他音源搜索歌曲时携带专辑名称(默认搜索条件 `歌曲名 - 歌手`,启用后搜索条件 `歌曲名 - 歌手 专辑名`) | `SEARCH_ALBUM=true` |
| NETEASE_COOKIE | str | 网易云 Cookie | `MUSIC_U=007554xxx` |

#### 日志等级 (`LOG_LEVEL`)

Expand Down
15 changes: 14 additions & 1 deletion src/hook.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const crypto = require('./crypto');
const request = require('./request');
const match = require('./provider/match');
const querystring = require('querystring');
const { isHost } = require('./utilities');
const { isHost, cookieToMap, mapToCookie } = require('./utilities');
const { getManagedCacheStorage } = require('./cache');
const { logScope } = require('./logger');

Expand Down Expand Up @@ -128,6 +128,19 @@ hook.request.before = (ctx) => {
)
)
ctx.decision = 'proxy';

if (process.env.NETEASE_COOKIE && url.path.includes('url')) {
var cookies = cookieToMap(req.headers.cookie);
var new_cookies = cookieToMap(process.env.NETEASE_COOKIE);

Object.entries(new_cookies).forEach(([key, value]) => {
cookies[key] = value;
});

req.headers.cookie = mapToCookie(cookies);
logger.debug('Replace netease cookie');
}

if (
[url.hostname, req.headers.host].some((host) =>
hook.target.host.has(host)
Expand Down
15 changes: 15 additions & 0 deletions src/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,22 @@ const isHost = (url, host) => {
*/
const isHostWrapper = (url) => (host) => isHost(url, host);

const cookieToMap = (cookie) => {
return cookie
.split(';')
.map((cookie) => cookie.trim().split('='))
.reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});
};

const mapToCookie = (map) => {
return Object.entries(map)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
};

module.exports = {
isHost,
isHostWrapper,
cookieToMap,
mapToCookie,
};