player.controller.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. import Router from '@koa/router';
  2. import { Context } from 'koa';
  3. import * as PlayerService from './player.service';
  4. import { BadRequestError } from '../../middleware/errorHandler';
  5. import { optionalAuth } from '../../middleware/auth';
  6. import { prisma } from '../../models';
  7. // 测试用户ID(开发环境使用)
  8. const TEST_USER_ID = '1';
  9. const router = new Router();
  10. // 获取播放进度列表
  11. router.get('/progress', optionalAuth, async (ctx: Context) => {
  12. // 开发环境使用测试用户ID
  13. const userId = ctx.state.user?.userId || TEST_USER_ID;
  14. const { audioId } = ctx.query as { audioId?: string };
  15. const records = await PlayerService.getPlayProgress(
  16. userId,
  17. audioId ? parseInt(audioId) : undefined
  18. );
  19. ctx.body = {
  20. code: 0,
  21. message: 'success',
  22. data: records,
  23. };
  24. });
  25. // 保存播放进度
  26. router.post('/progress', optionalAuth, async (ctx: Context) => {
  27. // 开发环境使用测试用户ID
  28. const userId = ctx.state.user?.userId || TEST_USER_ID;
  29. const body = ctx.request.body as {
  30. audioId: number;
  31. progress: number;
  32. duration: number;
  33. };
  34. const { audioId, progress, duration } = body;
  35. if (!audioId || typeof progress !== 'number' || typeof duration !== 'number') {
  36. throw new BadRequestError('参数错误');
  37. }
  38. const record = await PlayerService.savePlayProgress(userId, audioId, progress, duration);
  39. ctx.body = {
  40. code: 0,
  41. message: 'success',
  42. data: record,
  43. };
  44. });
  45. // 更新播放进度 (在 DELETE 路由之前定义)
  46. router.put('/progress/:audioId', optionalAuth, async (ctx: Context) => {
  47. // 开发环境使用测试用户ID
  48. const userId = ctx.state.user?.userId || TEST_USER_ID;
  49. const audioId = parseInt(ctx.params.audioId as string);
  50. const body = ctx.request.body as { progress: number; duration?: number };
  51. const { progress, duration } = body;
  52. if (typeof progress !== 'number') {
  53. throw new BadRequestError('进度参数错误');
  54. }
  55. const record = await PlayerService.updatePlayProgress(userId, audioId, progress, duration);
  56. ctx.body = {
  57. code: 0,
  58. message: 'success',
  59. data: record,
  60. };
  61. });
  62. // 删除播放记录
  63. router.delete('/progress/:audioId', optionalAuth, async (ctx: Context) => {
  64. // 开发环境使用测试用户ID
  65. const userId = ctx.state.user?.userId || TEST_USER_ID;
  66. const audioId = parseInt(ctx.params.audioId as string);
  67. await PlayerService.deletePlayRecord(userId, audioId);
  68. ctx.body = {
  69. code: 0,
  70. message: '删除成功',
  71. };
  72. });
  73. // 批量删除播放记录
  74. router.delete('/progress/batch', optionalAuth, async (ctx: Context) => {
  75. const userId = ctx.state.user?.userId || TEST_USER_ID;
  76. const { audioIds } = ctx.request.body as { audioIds: number[] };
  77. if (!audioIds || !Array.isArray(audioIds)) {
  78. throw new BadRequestError('参数错误');
  79. }
  80. for (const audioId of audioIds) {
  81. await PlayerService.deletePlayRecord(userId, audioId);
  82. }
  83. ctx.body = {
  84. code: 0,
  85. message: '批量删除成功',
  86. };
  87. });
  88. // ============ OPT-03: 首页最近收听 ============
  89. // 获取用户最近播放记录
  90. router.get('/recent', optionalAuth, async (ctx: Context) => {
  91. const userId = ctx.state.user?.userId;
  92. // 未登录用户返回空列表
  93. if (!userId) {
  94. ctx.body = {
  95. code: 0,
  96. message: 'success',
  97. data: { list: [] },
  98. };
  99. return;
  100. }
  101. const records = await PlayerService.getRecentPlayRecords(userId, 10);
  102. ctx.body = {
  103. code: 0,
  104. message: 'success',
  105. data: { list: records },
  106. };
  107. });
  108. // ============ 临时 API:为播放器页面适配书籍章节音频 ============
  109. // 获取播放列表(兼容前端 /api/player/playlist)
  110. router.get('/playlist', optionalAuth, async (ctx: Context) => {
  111. const { page = '1', pageSize = '100' } = ctx.query as { page?: string; pageSize?: string };
  112. // 开发环境使用测试用户ID
  113. const userId = ctx.state.user?.userId || TEST_USER_ID;
  114. // 获取所有有音频的章节:公开的 + 当前用户自己的
  115. const chapters = await prisma.bookChapter.findMany({
  116. where: {
  117. audioUrl: {
  118. not: null,
  119. },
  120. AND: [
  121. { audioUrl: { not: '' } },
  122. {
  123. OR: [
  124. { isPublic: true },
  125. { book: { userId: parseInt(userId) } },
  126. { book: { userId: null } },
  127. ]
  128. }
  129. ]
  130. },
  131. include: { book: true },
  132. orderBy: [
  133. { bookId: 'asc' },
  134. { number: 'asc' },
  135. ],
  136. skip: (parseInt(page) - 1) * parseInt(pageSize),
  137. take: parseInt(pageSize),
  138. });
  139. const total = await prisma.bookChapter.count({
  140. where: {
  141. audioUrl: {
  142. not: null,
  143. },
  144. AND: [
  145. { audioUrl: { not: '' } },
  146. {
  147. OR: [
  148. { isPublic: true },
  149. { book: { userId: parseInt(userId) } },
  150. ]
  151. }
  152. ]
  153. },
  154. });
  155. const list = await Promise.all(chapters.map(async (chapter) => {
  156. const urlParts = (chapter.audioUrl || '').match(/\/uploads\/([^\/]+)\//);
  157. const audioId = urlParts ? urlParts[1] : null;
  158. let finalAudioUrl = chapter.audioUrl || '';
  159. if (chapter.level === 1) {
  160. const mergedUrl = await PlayerService.getChapterAudioUrl(chapter.id);
  161. if (mergedUrl) {
  162. finalAudioUrl = mergedUrl;
  163. }
  164. }
  165. return {
  166. id: chapter.id,
  167. _id: chapter.id,
  168. audioId,
  169. title: chapter.title,
  170. summary: chapter.summary || '',
  171. text: chapter.content || '',
  172. audioUrl: finalAudioUrl,
  173. audioDuration: chapter.audioDuration || 0,
  174. wordCount: chapter.wordCount || 0,
  175. albumId: chapter.bookId,
  176. albumName: chapter.book?.title || '默认专辑',
  177. isFavorite: false,
  178. isPublic: chapter.isPublic,
  179. isOwner: chapter.book?.userId === parseInt(userId),
  180. level: chapter.level,
  181. lrcLyrics: chapter.lrcLyrics || '',
  182. };
  183. }));
  184. ctx.body = {
  185. code: 0,
  186. message: 'success',
  187. data: { list, total, page: parseInt(page), pageSize: parseInt(pageSize) },
  188. };
  189. });
  190. // 获取播放列表(适配旧播放器)- 必须放在 /:id 之前
  191. // 过滤规则:公开的音频 + 当前用户自己的音频
  192. router.get('/audio/list', optionalAuth, async (ctx: Context) => {
  193. const { page = '1', pageSize = '100' } = ctx.query as { page?: string; pageSize?: string };
  194. // 开发环境使用测试用户ID
  195. const userId = ctx.state.user?.userId || TEST_USER_ID;
  196. // 获取所有有音频的章节:公开的 + 当前用户自己的
  197. const chapters = await prisma.bookChapter.findMany({
  198. where: {
  199. audioUrl: {
  200. not: null,
  201. },
  202. AND: [
  203. { audioUrl: { not: '' } },
  204. {
  205. OR: [
  206. { isPublic: true }, // 公开的音频
  207. { book: { userId: parseInt(userId) } }, // 当前用户自己的
  208. { book: { userId: null } }, // 匿名用户创建的音频(无归属用户)
  209. ]
  210. }
  211. ]
  212. },
  213. include: { book: true },
  214. orderBy: [
  215. { bookId: 'asc' },
  216. { number: 'asc' },
  217. ],
  218. skip: (parseInt(page) - 1) * parseInt(pageSize),
  219. take: parseInt(pageSize),
  220. });
  221. const total = await prisma.bookChapter.count({
  222. where: {
  223. audioUrl: {
  224. not: null,
  225. },
  226. AND: [
  227. { audioUrl: { not: '' } },
  228. {
  229. OR: [
  230. { isPublic: true },
  231. { book: { userId: parseInt(userId) } },
  232. ]
  233. }
  234. ]
  235. },
  236. });
  237. const list = await Promise.all(chapters.map(async (chapter) => {
  238. // 从 audioUrl 中提取 audioId (UUID)
  239. // 格式: /uploads/{audioId}/output.mp3
  240. const urlParts = (chapter.audioUrl || '').match(/\/uploads\/([^\/]+)\//);
  241. const audioId = urlParts ? urlParts[1] : null;
  242. // 如果是章(level=1),自动合并小节音频
  243. let finalAudioUrl = chapter.audioUrl || '';
  244. if (chapter.level === 1) {
  245. const mergedUrl = await PlayerService.getChapterAudioUrl(chapter.id);
  246. if (mergedUrl) {
  247. finalAudioUrl = mergedUrl;
  248. }
  249. }
  250. return {
  251. id: chapter.id,
  252. _id: chapter.id,
  253. audioId,
  254. title: chapter.title,
  255. summary: chapter.summary || '',
  256. text: chapter.content || '',
  257. audioUrl: finalAudioUrl,
  258. audioDuration: chapter.audioDuration || 0,
  259. wordCount: chapter.wordCount || 0,
  260. albumId: chapter.bookId,
  261. albumName: chapter.book?.title || '默认专辑',
  262. isFavorite: false,
  263. isPublic: chapter.isPublic,
  264. isOwner: chapter.book?.userId === parseInt(userId),
  265. level: chapter.level,
  266. lrcLyrics: chapter.lrcLyrics || '', // OPT-17: LRC 歌词时间轴
  267. };
  268. }));
  269. ctx.body = {
  270. code: 0,
  271. message: 'success',
  272. data: { list, total, page: parseInt(page), pageSize: parseInt(pageSize) },
  273. };
  274. });
  275. // 获取章节音频详情(适配旧播放器)
  276. router.get('/audio/:id', optionalAuth, async (ctx: Context) => {
  277. const chapterId = parseInt(ctx.params.id as string);
  278. if (isNaN(chapterId)) {
  279. ctx.status = 400;
  280. ctx.body = { code: 1, message: '无效的音频ID' };
  281. return;
  282. }
  283. // 开发环境使用测试用户ID
  284. const userId = ctx.state.user?.userId || TEST_USER_ID;
  285. const chapter = await prisma.bookChapter.findUnique({
  286. where: { id: chapterId },
  287. include: { book: true },
  288. });
  289. if (!chapter) {
  290. ctx.status = 404;
  291. ctx.body = { code: 1, message: '音频不存在' };
  292. return;
  293. }
  294. // 如果音频未公开且不是所有者(且不是null userId的记录),拒绝访问
  295. const isNullOwner = chapter.book?.userId === null;
  296. if (!chapter.isPublic && chapter.book?.userId !== parseInt(userId) && !isNullOwner) {
  297. ctx.status = 403;
  298. ctx.body = { code: 1, message: '该音频未公开,无法访问' };
  299. return;
  300. }
  301. // 如果章节是章(level=1),自动合并小节音频
  302. let finalAudioUrl = chapter.audioUrl || '';
  303. if (chapter.level === 1) {
  304. const mergedUrl = await PlayerService.getChapterAudioUrl(chapterId);
  305. if (mergedUrl) {
  306. finalAudioUrl = mergedUrl;
  307. }
  308. }
  309. // 适配旧的 AudioItem 格式
  310. const audioItem = {
  311. id: chapter.id,
  312. _id: chapter.id,
  313. title: chapter.title,
  314. summary: chapter.summary || '',
  315. text: chapter.content || '',
  316. audioUrl: finalAudioUrl,
  317. audioDuration: chapter.audioDuration || 0,
  318. wordCount: chapter.wordCount || 0,
  319. albumId: chapter.bookId,
  320. albumName: chapter.book?.title || '默认专辑',
  321. isFavorite: false,
  322. isPublic: chapter.isPublic,
  323. isOwner: chapter.book?.userId === parseInt(userId),
  324. level: chapter.level,
  325. lrcLyrics: chapter.lrcLyrics || '', // OPT-17: LRC 歌词时间轴
  326. };
  327. ctx.body = {
  328. code: 0,
  329. message: 'success',
  330. data: audioItem,
  331. };
  332. });
  333. // 更新章节公开状态
  334. router.put('/audio/:id/public', optionalAuth, async (ctx: Context) => {
  335. const chapterId = parseInt(ctx.params.id as string);
  336. if (isNaN(chapterId)) {
  337. ctx.status = 400;
  338. ctx.body = { code: 1, message: '无效的音频ID' };
  339. return;
  340. }
  341. // 开发环境使用测试用户ID
  342. const userId = ctx.state.user?.userId || TEST_USER_ID;
  343. const { isPublic } = ctx.request.body as { isPublic: boolean };
  344. // 获取章节信息,验证所有权
  345. const chapter = await prisma.bookChapter.findUnique({
  346. where: { id: chapterId },
  347. include: { book: true },
  348. });
  349. if (!chapter) {
  350. ctx.status = 404;
  351. ctx.body = { code: 1, message: '章节不存在' };
  352. return;
  353. }
  354. // 验证是否是所有者
  355. if (chapter.book?.userId !== parseInt(userId)) {
  356. ctx.status = 403;
  357. ctx.body = { code: 1, message: '无权限操作' };
  358. return;
  359. }
  360. // 更新公开状态
  361. const updated = await prisma.bookChapter.update({
  362. where: { id: chapterId },
  363. data: { isPublic },
  364. });
  365. ctx.body = {
  366. code: 0,
  367. message: isPublic ? '已公开到首页' : '已取消公开',
  368. data: { isPublic: updated.isPublic },
  369. };
  370. });
  371. export default router;