dm.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "html"
  8. "sort"
  9. "go-common/app/interface/main/dm2/model"
  10. arcMdl "go-common/app/service/main/archive/model/archive"
  11. "go-common/library/ecode"
  12. "go-common/library/log"
  13. )
  14. func (s *Service) dmsCache(c context.Context, tp int32, oid, maxlimit int64, needTrim bool) (dms []*model.DM, err error) {
  15. ok, err := s.dao.ExpireDMCache(c, tp, oid)
  16. if err != nil || !ok {
  17. return
  18. }
  19. values, err := s.dao.DMCache(c, tp, oid)
  20. if err != nil || len(values) == 0 {
  21. return
  22. }
  23. var (
  24. start, trimCnt int
  25. normal, protect, special []*model.DM
  26. )
  27. for _, value := range values {
  28. dm := &model.DM{}
  29. if err = dm.Unmarshal(value); err != nil {
  30. log.Error("proto.Unmarshal(%s) error(%v)", value, err)
  31. return
  32. }
  33. if dm.Pool == model.PoolNormal {
  34. if dm.AttrVal(model.AttrProtect) == model.AttrYes {
  35. protect = append(protect, dm)
  36. } else {
  37. normal = append(normal, dm)
  38. }
  39. } else {
  40. special = append(special, dm)
  41. }
  42. }
  43. // 保护弹幕
  44. if start = len(protect) - int(maxlimit); start > 0 { // 只保留maxlimit条保护弹幕
  45. trimCnt += start
  46. protect = protect[start:]
  47. }
  48. dms = append(dms, protect...)
  49. // 普通弹幕
  50. if start = len(normal) + len(protect) - int(maxlimit); start > 0 { // 保护弹幕+普通弹幕=maxlimit
  51. trimCnt += start
  52. normal = normal[start:]
  53. }
  54. dms = append(dms, normal...)
  55. // 追加字幕弹幕和特殊弹幕
  56. dms = append(dms, special...)
  57. if trimCnt > 0 && needTrim {
  58. err = s.dao.TrimDMCache(c, tp, oid, int64(trimCnt))
  59. }
  60. return
  61. }
  62. // 返回所有每个弹幕池对应的弹幕列表
  63. func (s *Service) dms(c context.Context, tp int32, oid, maxlimit int64, childpool int32) (dms []*model.DM, err error) {
  64. var (
  65. key string
  66. count int
  67. keyprotect = "kp"
  68. dmMap = make(map[string][]*model.DM)
  69. contentSpeMap = make(map[int64]*model.ContentSpecial)
  70. )
  71. idxMap, dmids, spedmids, err := s.dao.Indexs(c, tp, oid)
  72. if err != nil {
  73. return
  74. }
  75. if len(dmids) == 0 {
  76. return
  77. }
  78. contents, err := s.dao.Contents(c, oid, dmids)
  79. if err != nil {
  80. return
  81. }
  82. if len(spedmids) > 0 {
  83. if contentSpeMap, err = s.dao.ContentsSpecial(c, spedmids); err != nil {
  84. return
  85. }
  86. }
  87. for _, content := range contents {
  88. if dm, ok := idxMap[content.ID]; ok {
  89. key = fmt.Sprint(dm.Pool)
  90. dm.Content = content
  91. if dm.Pool == model.PoolNormal {
  92. if dm.AttrVal(model.AttrProtect) == model.AttrYes {
  93. key = keyprotect
  94. }
  95. }
  96. if dm.Pool == model.PoolSpecial {
  97. contentSpe, ok := contentSpeMap[dm.ID]
  98. if ok {
  99. dm.ContentSpe = contentSpe
  100. }
  101. }
  102. dmMap[key] = append(dmMap[key], dm)
  103. }
  104. }
  105. // dm sort
  106. for _, dmsTmp := range dmMap {
  107. sort.Sort(model.DMSlice(dmsTmp))
  108. }
  109. // pool = 0 保护弹幕和普通弹幕总和为maxlimit
  110. if protect, ok := dmMap[keyprotect]; ok {
  111. if start := len(protect) - int(maxlimit); start > 0 { // 只保留maxlimit条保护弹幕
  112. protect = protect[start:]
  113. }
  114. dms = append(dms, protect...)
  115. count = len(protect)
  116. }
  117. key = fmt.Sprint(model.PoolNormal)
  118. if normal, ok := dmMap[key]; ok {
  119. start := len(normal) + count - int(maxlimit)
  120. if start > 0 {
  121. normal = normal[start:]
  122. }
  123. dms = append(dms, normal...)
  124. }
  125. if childpool > 0 {
  126. // pool = 1 字幕弹幕
  127. if _, ok := dmMap[fmt.Sprint(model.PoolSubtitle)]; ok {
  128. dms = append(dms, dmMap[fmt.Sprint(model.PoolSubtitle)]...)
  129. }
  130. // pool =2 特殊弹幕
  131. key = fmt.Sprint(model.PoolSpecial)
  132. if _, ok := dmMap[key]; ok {
  133. dms = append(dms, dmMap[key]...)
  134. }
  135. }
  136. return
  137. }
  138. func (s *Service) genXML(c context.Context, sub *model.Subject) (xml []byte, err error) {
  139. buf := new(bytes.Buffer)
  140. buf.WriteString(`<?xml version="1.0" encoding="UTF-8"?><i>`)
  141. buf.WriteString(`<chatserver>chat.bilibili.com</chatserver><chatid>`)
  142. buf.WriteString(fmt.Sprint(sub.Oid))
  143. buf.WriteString(`</chatid><mission>`)
  144. buf.WriteString(fmt.Sprint(sub.AttrVal(model.AttrSubMission)))
  145. buf.WriteString(`</mission><maxlimit>`)
  146. buf.WriteString(fmt.Sprint(sub.Maxlimit))
  147. buf.WriteString(`</maxlimit>`)
  148. buf.WriteString(fmt.Sprintf(`<state>%d</state>`, sub.State))
  149. realname := s.isRealname(c, sub.Pid, sub.Oid)
  150. if realname {
  151. buf.WriteString(`<real_name>1</real_name>`)
  152. } else {
  153. buf.WriteString(`<real_name>0</real_name>`)
  154. }
  155. if sub.State == model.SubStateClosed {
  156. buf.WriteString(`</i>`)
  157. xml = buf.Bytes()
  158. return
  159. }
  160. dms, err := s.dmsCache(c, sub.Type, sub.Oid, sub.Maxlimit, true)
  161. if err != nil {
  162. return
  163. }
  164. if len(dms) > 0 {
  165. buf.WriteString(`<source>k-v</source>`)
  166. } else {
  167. buf.WriteString(`<source>e-r</source>`)
  168. if dms, err = s.dms(c, sub.Type, sub.Oid, sub.Maxlimit, sub.Childpool); err != nil {
  169. return
  170. }
  171. flush := &model.Flush{Type: sub.Type, Oid: sub.Oid, Force: false}
  172. data, err := json.Marshal(flush)
  173. if err != nil {
  174. log.Error("json.Marshal(%v) error(%v)", flush, err)
  175. return nil, err
  176. }
  177. s.dao.SendAction(context.TODO(), fmt.Sprint(sub.Oid), &model.Action{Action: model.ActionFlush, Data: data})
  178. }
  179. for _, dm := range dms {
  180. buf.WriteString(dm.ToXML(realname))
  181. }
  182. buf.WriteString("</i>")
  183. return buf.Bytes(), nil
  184. }
  185. // DMXML return dm xml.
  186. func (s *Service) DMXML(c context.Context, tp int32, oid int64) (data []byte, err error) {
  187. // get from local cache
  188. var ok bool
  189. if data, ok = s.localCache[keyXML(tp, oid)]; ok {
  190. return
  191. }
  192. data, err = s.singleGenXML(c, tp, oid)
  193. return
  194. }
  195. func (s *Service) singleGenXML(c context.Context, tp int32, oid int64) (data []byte, err error) {
  196. v, err, _ := s.singleGroup.Do(keyXML(tp, oid), func() (res interface{}, err error) {
  197. // 从memcache获取
  198. if data, err = s.dao.XMLCache(c, oid); err != nil {
  199. return
  200. }
  201. if len(data) > 0 {
  202. res = data
  203. return
  204. }
  205. sub, err := s.subject(c, tp, oid)
  206. if err != nil {
  207. return
  208. }
  209. if data, err = s.genXML(c, sub); err != nil {
  210. return
  211. }
  212. if len(data) == 0 {
  213. err = ecode.NothingFound
  214. return
  215. }
  216. if data, err = s.gzflate(data); err != nil {
  217. log.Error("s.gzflate(oid:%d) error(%v)", oid, err)
  218. return
  219. }
  220. s.cache.Do(c, func(ctx context.Context) {
  221. s.dao.AddXMLCache(ctx, oid, data)
  222. })
  223. res = data
  224. return
  225. })
  226. if err != nil {
  227. return
  228. }
  229. data = v.([]byte)
  230. return
  231. }
  232. // AjaxDM 返回首页弹幕列表
  233. func (s *Service) AjaxDM(c context.Context, aid int64) (msgs []string, err error) {
  234. msgs = make([]string, 0)
  235. res, err := s.arcRPC.Archive3(c, &arcMdl.ArgAid2{Aid: aid})
  236. if err != nil {
  237. log.Error("arcRPC.Archive3(%d) error(%v)", aid, err)
  238. return
  239. }
  240. oid := res.FirstCid
  241. if msgs, err = s.dao.AjaxDMCache(c, oid); err != nil {
  242. return
  243. }
  244. if len(msgs) > 0 {
  245. return
  246. }
  247. dms, err := s.dmsCache(c, model.SubTypeVideo, oid, 20, false)
  248. if err != nil {
  249. log.Error("s.dmsCache(%d %d) error(%v)", aid, oid, err)
  250. return
  251. }
  252. for _, dm := range dms {
  253. if dm.Pool == model.PoolNormal && dm.Content.Mode != model.ModeSpecial {
  254. msgs = append(msgs, html.EscapeString(dm.Content.Msg))
  255. }
  256. }
  257. s.cache.Do(c, func(ctx context.Context) {
  258. s.dao.AddAjaxDMCache(ctx, oid, msgs)
  259. })
  260. return
  261. }
  262. // JudgeDms get fengjiwei dm list
  263. func (s *Service) JudgeDms(c context.Context, tp int8, oid int64, dmid int64) (judgeDMList *model.JudgeDMList, err error) {
  264. var (
  265. start, end, dmidIn int
  266. length = 100
  267. dms = make([]*model.JDM, 0)
  268. dmids []int64
  269. contentSpec = make(map[int64]*model.ContentSpecial)
  270. )
  271. judgeDMList, err = s.dao.DMJudgeCache(c, tp, oid, dmid)
  272. if err != nil {
  273. log.Error("DMJudge:s.dmDao.DMJudgeCache(tp:%d,oid:%d,dmid:%d) error(%v)", tp, oid, dmid, err)
  274. return
  275. }
  276. if judgeDMList != nil {
  277. return
  278. }
  279. judgeDMList = new(model.JudgeDMList)
  280. judgeDMList.List = make([]*model.JDM, 0)
  281. judgeDMList.Index = make([]int64, 0)
  282. idx, err := s.dao.IndexByid(c, tp, oid, dmid)
  283. if err != nil {
  284. log.Error("DMJudge:s.dmDao.Index2(type:%d,oid:%d, dmid:%d) error (%v)", tp, oid, dmid, err)
  285. return
  286. }
  287. if idx == nil {
  288. s.cache.Do(c, func(ctx context.Context) {
  289. s.dao.SetDMJudgeCache(ctx, tp, oid, dmid, judgeDMList)
  290. })
  291. return
  292. }
  293. part, spart, err := s.dao.JudgeIndex(c, tp, oid, idx.Ctime-86400, idx.Ctime+86400, idx.Progress-5000, idx.Progress+5000)
  294. if err != nil {
  295. log.Error("DMJudge:s.dmDao.JudgeIndex (type:%d,oid:%d) error (%v)", tp, oid, err)
  296. return
  297. }
  298. sort.Sort(model.JudgeSlice(part))
  299. for k, d := range part {
  300. if d.ID == dmid {
  301. dmidIn = k + 1
  302. break
  303. }
  304. }
  305. if dmidIn == 0 {
  306. log.Error("DMJudge: cid:%d dmid:%d dm too much", oid, dmid)
  307. return
  308. }
  309. start = dmidIn - length/2
  310. end = dmidIn + length/2
  311. if start < 0 {
  312. start = 0
  313. }
  314. if end > len(part) {
  315. end = len(part)
  316. }
  317. part = part[start:end]
  318. for k, i := range part {
  319. if i.Mid == idx.Mid {
  320. judgeDMList.Index = append(judgeDMList.Index, int64(k))
  321. }
  322. dmids = append(dmids, i.ID)
  323. }
  324. ctsMap, err := s.dao.Contents(c, oid, dmids)
  325. if err != nil {
  326. log.Error("DMJudge:s.dmDao.Contents(type:%d,oid:%d dmids:%v) error (%v)", tp, oid, dmids, err)
  327. return
  328. }
  329. if len(spart) > 0 {
  330. if contentSpec, err = s.dao.ContentsSpecial(c, spart); err != nil {
  331. log.Error("DMJudge:s.dmDao.ContentsSpecial(type:%d,oid:%d) error (%v)", tp, oid, err)
  332. return
  333. }
  334. }
  335. for _, i := range part {
  336. ct, ok := ctsMap[i.ID]
  337. if !ok {
  338. continue
  339. }
  340. dm := &model.JDM{
  341. ID: i.ID,
  342. Progress: timeStr(int64(i.Progress)),
  343. Msg: ct.Msg,
  344. Mid: i.Mid,
  345. CTime: i.Ctime,
  346. }
  347. if i.Pool == model.PoolSpecial {
  348. if _, ok = contentSpec[dm.ID]; ok {
  349. dm.Msg = contentSpec[dm.ID].Msg
  350. }
  351. }
  352. dms = append(dms, dm)
  353. }
  354. judgeDMList.List = dms
  355. s.cache.Do(c, func(ctx context.Context) {
  356. s.dao.SetDMJudgeCache(ctx, tp, oid, dmid, judgeDMList)
  357. })
  358. return
  359. }
  360. // timeStr microTime to string.
  361. func timeStr(t int64) string {
  362. sec := t / 1000 % 60
  363. min := t / 1000 / 60 % 60
  364. hour := t / 1000 / 60 / 60
  365. return fmt.Sprintf("%02d:%02d:%02d", hour, min, sec)
  366. }
  367. func (s *Service) isRealname(c context.Context, aid, oid int64) (realname bool) {
  368. for _, v := range s.conf.Realname.Whitelist {
  369. if oid == v {
  370. realname = true
  371. return
  372. }
  373. }
  374. if !s.conf.Realname.SwitchOn {
  375. return
  376. }
  377. arg := &arcMdl.ArgAid2{Aid: aid}
  378. archive, err := s.arcRPC.Archive3(c, arg)
  379. if err != nil {
  380. log.Error("arcRPC.Archive3(%v) error(%v)", arg, err)
  381. return
  382. }
  383. if v, ok := s.realname[int64(archive.TypeID)]; ok && oid >= v {
  384. realname = true
  385. } else {
  386. realname = false
  387. }
  388. return
  389. }
  390. // DMDistribution get dm distribution from dm list.
  391. func (s *Service) DMDistribution(c context.Context, typ int32, oid int64, interval int32) (res map[int64]int64, err error) {
  392. res = make(map[int64]int64)
  393. sub, err := s.subject(c, typ, oid)
  394. if err != nil {
  395. return
  396. }
  397. dms, err := s.dmsCache(c, sub.Type, sub.Oid, sub.Maxlimit, true)
  398. if err != nil {
  399. return
  400. }
  401. if len(dms) == 0 {
  402. if dms, err = s.dms(c, sub.Type, sub.Oid, sub.Maxlimit, sub.Childpool); err != nil {
  403. return
  404. }
  405. flush := &model.Flush{Type: sub.Type, Oid: sub.Oid, Force: false}
  406. data, err := json.Marshal(flush)
  407. if err != nil {
  408. log.Error("json.Marshal(%v) error(%v)", flush, err)
  409. return nil, err
  410. }
  411. s.dao.SendAction(context.TODO(), fmt.Sprint(sub.Oid), &model.Action{Action: model.ActionFlush, Data: data})
  412. }
  413. for _, dm := range dms {
  414. x := int64(dm.Progress/1000.0/interval) + 1
  415. if _, ok := res[x]; !ok {
  416. res[x] = 1
  417. } else {
  418. res[x]++
  419. }
  420. }
  421. return
  422. }
  423. func (s *Service) loadLocalcache(oids []int64) {
  424. var (
  425. err error
  426. duration int64
  427. sub *model.Subject
  428. tp = model.SubTypeVideo
  429. c = context.Background()
  430. tmp = make(map[string][]byte)
  431. bs []byte
  432. )
  433. for _, oid := range oids {
  434. if sub, err = s.dao.Subject(c, tp, oid); err != nil || sub == nil {
  435. continue
  436. }
  437. if bs, err = json.Marshal(sub); err != nil {
  438. continue
  439. }
  440. tmp[keySubject(sub.Type, sub.Oid)] = bs
  441. // local cache video duration
  442. if duration, err = s.videoDuration(c, sub.Pid, oid); err != nil {
  443. continue
  444. }
  445. tmp[keyDuration(tp, oid)] = []byte(fmt.Sprint(duration))
  446. // local cache segment dm xml
  447. seg := model.SegmentInfo(0, duration)
  448. for i := int64(1); i <= seg.Cnt; i++ { // flush every segment cache
  449. seg.Num = i
  450. var xml []byte
  451. if xml, err = s.singleGenSegXML(c, sub.Pid, sub, seg); err != nil {
  452. continue
  453. }
  454. tmp[keySeg(tp, oid, seg.Cnt, seg.Num)] = xml
  455. }
  456. // local cache dm xml
  457. data, err := s.singleGenXML(c, tp, oid)
  458. if err != nil {
  459. continue
  460. }
  461. tmp[keyXML(tp, oid)] = []byte(data)
  462. }
  463. if len(tmp) > 0 {
  464. s.localCache = tmp
  465. }
  466. }
  467. // dmList get dm list from database.
  468. func (s *Service) dmList(c context.Context, tp int32, oid int64, dmids []int64) (dms []*model.DM, err error) {
  469. if len(dmids) == 0 {
  470. return
  471. }
  472. dms = make([]*model.DM, 0, len(dmids))
  473. contentSpe := make(map[int64]*model.ContentSpecial)
  474. idxMap, special, err := s.dao.IndexsByid(c, tp, oid, dmids)
  475. if err != nil || len(idxMap) == 0 {
  476. return
  477. }
  478. ctsMap, err := s.dao.Contents(c, oid, dmids)
  479. if err != nil {
  480. return
  481. }
  482. if len(special) > 0 {
  483. if contentSpe, err = s.dao.ContentsSpecial(c, special); err != nil {
  484. return
  485. }
  486. }
  487. for _, dmid := range dmids {
  488. if dm, ok := idxMap[dmid]; ok {
  489. var content *model.Content
  490. if content, ok = ctsMap[dmid]; ok {
  491. dm.Content = content
  492. } else {
  493. log.Error("dm content not exist,tp:%d,oid:%d,dmid:%d", tp, oid, dmid)
  494. continue
  495. }
  496. if dm.Pool == model.PoolSpecial {
  497. if _, ok = contentSpe[dmid]; ok {
  498. dm.ContentSpe = contentSpe[dmid]
  499. } else {
  500. log.Error("dm special content not exist,tp:%d,oid:%d,dmid:%d", tp, oid, dmid)
  501. continue
  502. }
  503. }
  504. dms = append(dms, dm)
  505. }
  506. }
  507. return
  508. }