更新cookie管理,文件保存

This commit is contained in:
whyour 2021-03-17 20:43:03 +08:00
parent 8526a57caf
commit 361963711e
6 changed files with 156 additions and 89 deletions

View File

@ -3,6 +3,8 @@ import { Router, Request, Response, NextFunction } from 'express';
import { Container } from 'typedi'; import { Container } from 'typedi';
import { Logger } from 'winston'; import { Logger } from 'winston';
import config from '../config'; import config from '../config';
import * as fs from 'fs';
import { celebrate, Joi } from 'celebrate';
const route = Router(); const route = Router();
export default (app: Router) => { export default (app: Router) => {
@ -40,4 +42,26 @@ export default (app: Router) => {
} }
}, },
); );
route.post(
'/save',
celebrate({
body: Joi.object({
name: Joi.string().required(),
content: Joi.string().required(),
}),
}),
async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
try {
const { name, content } = req.body;
const path = (config.fileMap as any)[name];
fs.writeFileSync(path, content);
res.send({ code: 200, msg: '保存成功' });
} catch (e) {
logger.error('🔥 error: %o', e);
return next(e);
}
},
);
}; };

View File

@ -1,10 +1,7 @@
import { Router, Request, Response, NextFunction } from 'express'; import { Router, Request, Response, NextFunction } from 'express';
import { Container } from 'typedi'; import { Container } from 'typedi';
import CookieService from '../services/cookie'; import CookieService from '../services/cookie';
import { celebrate, Joi } from 'celebrate';
import { Logger } from 'winston'; import { Logger } from 'winston';
import { getFileContentByName } from '../config/util';
import config from '../config';
const route = Router(); const route = Router();
export default (app: Router) => { export default (app: Router) => {
@ -49,7 +46,23 @@ export default (app: Router) => {
const logger: Logger = Container.get('logger'); const logger: Logger = Container.get('logger');
try { try {
const cookieService = Container.get(CookieService); const cookieService = Container.get(CookieService);
const data = await cookieService.addCookie(); const data = await cookieService.addCookie(req.query.cookie as string);
return res.send({ code: 200, data });
} catch (e) {
logger.error('🔥 error: %o', e);
return next(e);
}
},
);
route.post(
'/cookie/refresh',
async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
try {
const cookieService = Container.get(CookieService);
console.log(req);
const data = await cookieService.refreshCookie(req.body);
return res.send({ code: 200, data }); return res.send({ code: 200, data });
} catch (e) { } catch (e) {
logger.error('🔥 error: %o', e); logger.error('🔥 error: %o', e);

View File

@ -41,4 +41,9 @@ export default {
crontabFile, crontabFile,
sampleFile, sampleFile,
confFile, confFile,
fileMap: {
'config.sh': confFile,
'crontab.list': crontabFile,
'diy.sh': diyFile,
},
}; };

View File

@ -159,13 +159,13 @@ export default class CookieService {
return userCookie; return userCookie;
} }
public async addCookie() { public async addCookie(oldCookie: string) {
const res: any = await this.checkLogin(); const res: any = await this.checkLogin();
if (res.body.errcode === 0) { if (res.body.errcode === 0) {
let ucookie = this.getCookie(res); let ucookie = this.getCookie(res);
let content = getFileContentByName(config.confFile); let content = getFileContentByName(config.confFile);
const regx = /.*Cookie[0-9]{1}\=\"(.+?)\"/g; const regx = /.*Cookie[0-9]{1}\=\"(.+?)\"/g;
const lastCookie = (content.match(regx) as any[]).pop(); const lastCookie = oldCookie || (content.match(regx) as any[]).pop();
const cookieRegx = /Cookie([0-9]+)\=.+?/.exec(lastCookie); const cookieRegx = /Cookie([0-9]+)\=.+?/.exec(lastCookie);
if (cookieRegx) { if (cookieRegx) {
const num = parseInt(cookieRegx[1]) + 1; const num = parseInt(cookieRegx[1]) + 1;
@ -246,6 +246,17 @@ export default class CookieService {
return result; return result;
} }
public async refreshCookie(body: any) {
const { cookie } = body;
const { nickname, status } = await this.getJdInfo(cookie);
return {
pin: cookie.match(/pt_pin=(.+?);/)[1],
cookie,
status,
nickname: nickname,
};
}
private getJdInfo(cookie: string) { private getJdInfo(cookie: string) {
return fetch( return fetch(
`https://me-api.jd.com/user_new/info/GetJDUserInfoUnion?orgFlag=JD_PinGou_New&callSource=mainorder&channel=4&isHomewhite=0&sceneval=2&_=${Date.now()}&sceneval=2&g_login_type=1&g_ty=ls`, `https://me-api.jd.com/user_new/info/GetJDUserInfoUnion?orgFlag=JD_PinGou_New&callSource=mainorder&channel=4&isHomewhite=0&sceneval=2&_=${Date.now()}&sceneval=2&g_login_type=1&g_ty=ls`,
@ -266,7 +277,6 @@ export default class CookieService {
) )
.then((x) => x.json()) .then((x) => x.json())
.then((x) => { .then((x) => {
console.log(x.data.userInfo);
if (x.retcode === '0' && x.data && x.data.userInfo) { if (x.retcode === '0' && x.data && x.data.userInfo) {
return { nickname: x.data.userInfo.baseInfo.nickname, status: 0 }; return { nickname: x.data.userInfo.baseInfo.nickname, status: 0 };
} else if (x.retcode === 13) { } else if (x.retcode === 13) {

View File

@ -22,18 +22,6 @@ const Crontab = () => {
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}; };
const updateConfig = () => {
request
.post(`${config.apiPrefix}save`, {
data: { content: value, name: 'diy.sh' },
})
.then((data) => {
notification.success({
message: data.msg,
});
});
};
useEffect(() => { useEffect(() => {
if (document.body.clientWidth < 768) { if (document.body.clientWidth < 768) {
setWdith('auto'); setWdith('auto');
@ -52,11 +40,6 @@ const Crontab = () => {
className="code-mirror-wrapper" className="code-mirror-wrapper"
title="互助码" title="互助码"
loading={loading} loading={loading}
extra={[
<Button key="1" type="primary" onClick={updateConfig}>
</Button>,
]}
header={{ header={{
style: { style: {
padding: '4px 16px 4px 15px', padding: '4px 16px 4px 15px',

View File

@ -16,67 +16,75 @@ enum StatusColor {
'warning', 'warning',
} }
const columns = [
{
title: '用户名',
dataIndex: 'pin',
key: 'pin',
align: 'center' as const,
render: (text: string, record: any) => {
return <span>{decodeURIComponent(text)}</span>;
},
},
{
title: '昵称',
dataIndex: 'nickname',
key: 'nickname',
align: 'center' as const,
},
{
title: '值',
dataIndex: 'cookie',
key: 'cookie',
align: 'center' as const,
render: (text: string, record: any) => {
return (
<span
style={{
textAlign: 'left',
display: 'inline-block',
wordBreak: 'break-all',
}}
>
{text}
</span>
);
},
},
{
title: '状态',
key: 'status',
dataIndex: 'status',
align: 'center' as const,
render: (text: string, record: any) => {
return (
<Space size="middle">
<Tag color={StatusColor[record.status]}>{Status[record.status]}</Tag>
</Space>
);
},
},
{
title: '操作',
key: 'action',
render: (text: string, record: any) => (
<Space size="middle">
<a>Invite {record.name}</a>
<a>Delete</a>
</Space>
),
},
];
const Config = () => { const Config = () => {
const columns = [
{
title: '用户名',
dataIndex: 'pin',
key: 'pin',
align: 'center' as const,
render: (text: string, record: any) => {
return <span>{decodeURIComponent(text)}</span>;
},
},
{
title: '昵称',
dataIndex: 'nickname',
key: 'nickname',
align: 'center' as const,
},
{
title: '值',
dataIndex: 'cookie',
key: 'cookie',
align: 'center' as const,
width: '50%',
render: (text: string, record: any) => {
return (
<span
style={{
textAlign: 'left',
display: 'inline-block',
wordBreak: 'break-all',
}}
>
{text}
</span>
);
},
},
{
title: '状态',
key: 'status',
dataIndex: 'status',
align: 'center' as const,
render: (text: string, record: any) => {
return (
<Space size="middle">
<Tag color={StatusColor[record.status]}>
{Status[record.status]}
</Tag>
</Space>
);
},
},
{
title: '操作',
key: 'action',
align: 'center' as const,
render: (text: string, record: any, index: number) => (
<Space size="middle">
{record.status === 0 && <span>-</span>}
{record.status === 1 && (
<a onClick={() => reacquire(record)}></a>
)}
{record.status === 2 && (
<a onClick={() => refreshStatus(record, index)}></a>
)}
</Space>
),
},
];
const [width, setWdith] = useState('100%'); const [width, setWdith] = useState('100%');
const [marginLeft, setMarginLeft] = useState(0); const [marginLeft, setMarginLeft] = useState(0);
const [marginTop, setMarginTop] = useState(-72); const [marginTop, setMarginTop] = useState(-72);
@ -109,7 +117,7 @@ const Config = () => {
return new Promise((resolve) => setTimeout(resolve, time)); return new Promise((resolve) => setTimeout(resolve, time));
} }
const showQrCode = () => { const showQrCode = (oldCookie?: string) => {
request.get(`${config.apiPrefix}qrcode`).then(async (data) => { request.get(`${config.apiPrefix}qrcode`).then(async (data) => {
if (data.qrcode) { if (data.qrcode) {
const modal = Modal.info({ const modal = Modal.info({
@ -135,18 +143,21 @@ const Config = () => {
</div> </div>
), ),
}); });
getCookie(modal); getCookie(modal, oldCookie);
} else { } else {
notification.error({ message: '获取二维码失败' }); notification.error({ message: '获取二维码失败' });
} }
}); });
}; };
const getCookie = async (modal: { destroy: () => void }) => { const getCookie = async (
modal: { destroy: () => void },
oldCookie: string = '',
) => {
for (let i = 0; i < 50; i++) { for (let i = 0; i < 50; i++) {
const { const {
data: { cookie, errcode, message }, data: { cookie, errcode, message },
} = await request.get(`${config.apiPrefix}cookie`); } = await request.get(`${config.apiPrefix}cookie?cookie=${oldCookie}`);
if (cookie) { if (cookie) {
notification.success({ notification.success({
message: 'Cookie获取成功', message: 'Cookie获取成功',
@ -166,6 +177,26 @@ const Config = () => {
} }
}; };
const reacquire = async (record: any) => {
await showQrCode(record.cookie);
};
const refreshStatus = (record: any, index: number) => {
request
.post(`${config.apiPrefix}cookie/refresh`, {
data: { cookie: record.cookie },
})
.then(async (data: any) => {
if (data.data && data.data.cookie) {
(value as any).splice(index, 1, data.data);
setValue([...(value as any)] as any);
notification.success({ message: '更新状态成功' });
} else {
notification.error({ message: '更新状态失败' });
}
});
};
useEffect(() => { useEffect(() => {
if (document.body.clientWidth < 768) { if (document.body.clientWidth < 768) {
setWdith('auto'); setWdith('auto');
@ -185,7 +216,7 @@ const Config = () => {
title="Cookie管理" title="Cookie管理"
loading={loading} loading={loading}
extra={[ extra={[
<Button key="2" type="primary" onClick={showQrCode}> <Button key="2" type="primary" onClick={() => showQrCode()}>
Cookie Cookie
</Button>, </Button>,
]} ]}
@ -212,6 +243,7 @@ const Config = () => {
rowKey="pin" rowKey="pin"
size="middle" size="middle"
bordered bordered
scroll={{ x: '100%' }}
/> />
</PageContainer> </PageContainer>
); );