accounts.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import { Router } from 'express';
  2. import { body, param, query } from 'express-validator';
  3. import { AccountService } from '../services/AccountService.js';
  4. import { browserLoginService } from '../services/BrowserLoginService.js';
  5. import { authenticate } from '../middleware/auth.js';
  6. import { asyncHandler } from '../middleware/error.js';
  7. import { validateRequest } from '../middleware/validate.js';
  8. import type { PlatformType } from '@media-manager/shared';
  9. const router = Router();
  10. const accountService = new AccountService();
  11. // 所有路由需要认证
  12. router.use(authenticate);
  13. // ============ 账号分组 ============
  14. // 获取分组列表
  15. router.get(
  16. '/groups',
  17. asyncHandler(async (req, res) => {
  18. const groups = await accountService.getGroups(req.user!.userId);
  19. res.json({ success: true, data: groups });
  20. })
  21. );
  22. // 创建分组
  23. router.post(
  24. '/groups',
  25. [
  26. body('name').notEmpty().withMessage('分组名称不能为空'),
  27. validateRequest,
  28. ],
  29. asyncHandler(async (req, res) => {
  30. const group = await accountService.createGroup(req.user!.userId, req.body);
  31. res.status(201).json({ success: true, data: group });
  32. })
  33. );
  34. // 更新分组
  35. router.put(
  36. '/groups/:id',
  37. [
  38. param('id').isInt().withMessage('分组ID无效'),
  39. validateRequest,
  40. ],
  41. asyncHandler(async (req, res) => {
  42. const group = await accountService.updateGroup(
  43. req.user!.userId,
  44. Number(req.params.id),
  45. req.body
  46. );
  47. res.json({ success: true, data: group });
  48. })
  49. );
  50. // 删除分组
  51. router.delete(
  52. '/groups/:id',
  53. [
  54. param('id').isInt().withMessage('分组ID无效'),
  55. validateRequest,
  56. ],
  57. asyncHandler(async (req, res) => {
  58. await accountService.deleteGroup(req.user!.userId, Number(req.params.id));
  59. res.json({ success: true, message: '分组已删除' });
  60. })
  61. );
  62. // ============ 平台账号 ============
  63. // 获取账号列表
  64. router.get(
  65. '/',
  66. asyncHandler(async (req, res) => {
  67. const { platform, groupId, status } = req.query;
  68. const accounts = await accountService.getAccounts(req.user!.userId, {
  69. platform: platform as string,
  70. groupId: groupId ? Number(groupId) : undefined,
  71. status: status as string,
  72. });
  73. res.json({ success: true, data: accounts });
  74. })
  75. );
  76. // 获取单个账号
  77. router.get(
  78. '/:id',
  79. [
  80. param('id').isInt().withMessage('账号ID无效'),
  81. validateRequest,
  82. ],
  83. asyncHandler(async (req, res) => {
  84. const account = await accountService.getAccountById(
  85. req.user!.userId,
  86. Number(req.params.id)
  87. );
  88. res.json({ success: true, data: account });
  89. })
  90. );
  91. // 添加账号(通过 Cookie)
  92. router.post(
  93. '/',
  94. [
  95. body('platform').notEmpty().withMessage('平台不能为空'),
  96. body('cookieData').notEmpty().withMessage('Cookie不能为空'),
  97. validateRequest,
  98. ],
  99. asyncHandler(async (req, res) => {
  100. const account = await accountService.addAccount(req.user!.userId, req.body);
  101. res.status(201).json({ success: true, data: account });
  102. })
  103. );
  104. // 更新账号
  105. router.put(
  106. '/:id',
  107. [
  108. param('id').isInt().withMessage('账号ID无效'),
  109. validateRequest,
  110. ],
  111. asyncHandler(async (req, res) => {
  112. const account = await accountService.updateAccount(
  113. req.user!.userId,
  114. Number(req.params.id),
  115. req.body
  116. );
  117. res.json({ success: true, data: account });
  118. })
  119. );
  120. // 删除账号
  121. router.delete(
  122. '/:id',
  123. [
  124. param('id').isInt().withMessage('账号ID无效'),
  125. validateRequest,
  126. ],
  127. asyncHandler(async (req, res) => {
  128. await accountService.deleteAccount(req.user!.userId, Number(req.params.id));
  129. res.json({ success: true, message: '账号已删除' });
  130. })
  131. );
  132. // 刷新账号状态
  133. router.post(
  134. '/:id/refresh',
  135. [
  136. param('id').isInt().withMessage('账号ID无效'),
  137. validateRequest,
  138. ],
  139. asyncHandler(async (req, res) => {
  140. const result = await accountService.refreshAccount(
  141. req.user!.userId,
  142. Number(req.params.id)
  143. );
  144. const { needReLogin, ...account } = result;
  145. res.json({
  146. success: true,
  147. data: account,
  148. needReLogin: needReLogin || false,
  149. });
  150. })
  151. );
  152. // 检查账号 Cookie 是否有效
  153. router.get(
  154. '/:id/check-status',
  155. [
  156. param('id').isInt().withMessage('账号ID无效'),
  157. validateRequest,
  158. ],
  159. asyncHandler(async (req, res) => {
  160. const result = await accountService.checkAccountStatus(
  161. req.user!.userId,
  162. Number(req.params.id)
  163. );
  164. res.json({
  165. success: true,
  166. data: {
  167. isValid: result.isValid,
  168. needReLogin: !result.isValid,
  169. }
  170. });
  171. })
  172. );
  173. // 批量刷新所有账号状态
  174. router.post(
  175. '/refresh-all',
  176. asyncHandler(async (req, res) => {
  177. const result = await accountService.refreshAllAccounts(req.user!.userId);
  178. res.json({
  179. success: true,
  180. data: result,
  181. });
  182. })
  183. );
  184. // 获取扫码登录二维码
  185. router.post(
  186. '/qrcode',
  187. [
  188. body('platform').notEmpty().withMessage('平台不能为空'),
  189. validateRequest,
  190. ],
  191. asyncHandler(async (req, res) => {
  192. const qrcode = await accountService.getQRCode(req.body.platform);
  193. res.json({ success: true, data: qrcode });
  194. })
  195. );
  196. // 检查扫码状态
  197. router.get(
  198. '/qrcode/status',
  199. [
  200. query('platform').notEmpty().withMessage('平台不能为空'),
  201. query('qrcodeKey').notEmpty().withMessage('二维码Key不能为空'),
  202. validateRequest,
  203. ],
  204. asyncHandler(async (req, res) => {
  205. const { platform, qrcodeKey } = req.query;
  206. const status = await accountService.checkQRCodeStatus(
  207. platform as string,
  208. qrcodeKey as string
  209. );
  210. res.json({ success: true, data: status });
  211. })
  212. );
  213. // ============ 浏览器登录 ============
  214. // 开始浏览器登录会话
  215. router.post(
  216. '/browser-login',
  217. [
  218. body('platform').notEmpty().withMessage('平台不能为空'),
  219. validateRequest,
  220. ],
  221. asyncHandler(async (req, res) => {
  222. const { platform } = req.body;
  223. const result = await browserLoginService.startLoginSession(platform as PlatformType);
  224. res.json({ success: true, data: result });
  225. })
  226. );
  227. // 获取浏览器登录状态
  228. router.get(
  229. '/browser-login/:sessionId',
  230. [
  231. param('sessionId').notEmpty().withMessage('会话ID不能为空'),
  232. validateRequest,
  233. ],
  234. asyncHandler(async (req, res) => {
  235. const { sessionId } = req.params;
  236. const status = browserLoginService.getSessionStatus(sessionId);
  237. if (!status) {
  238. res.status(404).json({ success: false, error: { message: '会话不存在或已过期' } });
  239. return;
  240. }
  241. res.json({ success: true, data: status });
  242. })
  243. );
  244. // 取消浏览器登录会话
  245. router.delete(
  246. '/browser-login/:sessionId',
  247. [
  248. param('sessionId').notEmpty().withMessage('会话ID不能为空'),
  249. validateRequest,
  250. ],
  251. asyncHandler(async (req, res) => {
  252. const { sessionId } = req.params;
  253. await browserLoginService.cancelSession(sessionId);
  254. res.json({ success: true, message: '会话已取消' });
  255. })
  256. );
  257. // 确认浏览器登录并保存账号
  258. router.post(
  259. '/browser-login/:sessionId/confirm',
  260. [
  261. param('sessionId').notEmpty().withMessage('会话ID不能为空'),
  262. body('platform').notEmpty().withMessage('平台不能为空'),
  263. validateRequest,
  264. ],
  265. asyncHandler(async (req, res) => {
  266. const { sessionId } = req.params;
  267. const { platform, groupId } = req.body;
  268. const status = browserLoginService.getSessionStatus(sessionId);
  269. if (!status || status.status !== 'success' || !status.cookies) {
  270. res.status(400).json({
  271. success: false,
  272. error: { message: '登录未完成或会话已失效' }
  273. });
  274. return;
  275. }
  276. // 使用获取到的 Cookie 和账号信息创建账号
  277. const account = await accountService.addAccount(req.user!.userId, {
  278. platform,
  279. cookieData: status.cookies,
  280. groupId,
  281. // 传递从浏览器会话中获取的账号信息
  282. accountInfo: status.accountInfo,
  283. });
  284. res.status(201).json({ success: true, data: account });
  285. })
  286. );
  287. // ============ 内嵌浏览器登录 Cookie 验证 ============
  288. // 验证 Cookie 登录状态(用于 Electron 内嵌浏览器)
  289. router.post(
  290. '/verify-cookie',
  291. [
  292. body('platform').notEmpty().withMessage('平台不能为空'),
  293. body('cookieData').notEmpty().withMessage('Cookie不能为空'),
  294. validateRequest,
  295. ],
  296. asyncHandler(async (req, res) => {
  297. const { platform, cookieData } = req.body;
  298. try {
  299. // 使用服务验证 cookie 并获取账号信息
  300. const result = await accountService.verifyCookieAndGetInfo(
  301. platform as PlatformType,
  302. cookieData
  303. );
  304. res.json({
  305. success: true,
  306. data: {
  307. success: result.success,
  308. message: result.message,
  309. accountInfo: result.accountInfo,
  310. }
  311. });
  312. } catch (error) {
  313. res.json({
  314. success: true,
  315. data: {
  316. success: false,
  317. message: error instanceof Error ? error.message : '验证失败',
  318. }
  319. });
  320. }
  321. })
  322. );
  323. export default router;