liveroom.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const { ObjectId } = require('mongoose').Types;
  5. const { CrudService } = require('naf-framework-mongoose/lib/service');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. class LiveroomService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'liveroom');
  10. this.model = this.ctx.model.Liveroom;
  11. }
  12. async create(data) {
  13. const { subid, teacherid } = data;
  14. assert(subid, '缺少科目信息');
  15. assert(teacherid, '缺少教师信息');
  16. const list = await this.model.find();
  17. const last = _.last(list);
  18. let number = '000001';
  19. if (last) {
  20. number = last.number * 1 + 1;
  21. }
  22. data.number = number;
  23. const res = await this.model.create(data);
  24. return res;
  25. }
  26. async personcount(data) {
  27. const { number, name, userid, type } = data;
  28. // 取出已经进入直播的用户列表
  29. let list = await this.app.redis.get(`liveroom${number}`);
  30. console.log(_.cloneDeep(list));
  31. if (list) {
  32. // 已经开始直播,并且有人观看
  33. list = JSON.parse(list);
  34. if (!type) {
  35. list = _.uniqBy(list.push({ name, userid }), 'userid');
  36. } else {
  37. list = list.filter(f => f.userid !== userid);
  38. }
  39. list = JSON.stringify(list);
  40. } else {
  41. // 还没有人进直播
  42. list = JSON.stringify([{ name, userid }]);
  43. }
  44. await this.app.redis.set(`liveroom${number}`, list);
  45. const { mq } = this.ctx;
  46. if (mq) {
  47. const exchange = 'liveroom-personcount';
  48. const parm = {
  49. durable: true,
  50. headers: {
  51. userid: 1,
  52. },
  53. };
  54. await mq.fanout(exchange, number, list, parm);
  55. }
  56. }
  57. }
  58. module.exports = LiveroomService;