Message.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import TableHelper from './lib/TableHelper'
  2. import User from './User'
  3. import { decryptoMsg } from '@/util/util.js'
  4. class Message extends TableHelper {
  5. constructor () {
  6. super('message')
  7. }
  8. async getMsg (sessionId, limit = 30) {
  9. if (!sessionId) return null
  10. let objTable = await this.getObjTable()
  11. if (!objTable) return
  12. var lowerBound = [sessionId, 0]
  13. var upperBound = [sessionId, 999999999999999]
  14. let keyRangeValue = IDBKeyRange.bound(lowerBound, upperBound)
  15. let cursor = await objTable.index('session_id').openCursor(keyRangeValue, 'prev')
  16. let list = []
  17. let userIds = {}
  18. // let list2 = []
  19. while (cursor && cursor.value) {
  20. let value = cursor.value
  21. if (list.length < limit && value['session_id'] === sessionId) {
  22. if (value.msg_type == 4) {
  23. // 针对红包类型
  24. try {
  25. if (typeof value.msg === 'string') {
  26. value.msg = JSON.parse(decryptoMsg(value.msg))
  27. }
  28. } catch (ex) {
  29. console.error(ex)
  30. }
  31. } else {
  32. value.msg = decryptoMsg(value.msg)
  33. }
  34. list.unshift(value)
  35. userIds[value.from] = value.from
  36. if (value.to) {
  37. userIds[value.to] = value.to
  38. }
  39. cursor = await cursor.continue()
  40. } else {
  41. break
  42. }
  43. }
  44. let objUser = new User()
  45. let userMap = await objUser.getUserMap(userIds)
  46. return { list, userMap }
  47. }
  48. async updatePackInfo (hash, type, value) {
  49. let objTable = await this.getObjTable()
  50. if (!objTable) return
  51. let obj = await objTable.get(hash)
  52. if (obj) {
  53. obj.ext[type] = value
  54. objTable.put(obj)
  55. } else {
  56. console.log('can not find redpack:' + hash)
  57. }
  58. }
  59. async saveMsg (sessionId, data) {
  60. const objMessage = new Message()
  61. // 数据保存到indexDB
  62. let objTable = await objMessage.getObjTable()
  63. if (!objTable) return
  64. for (let key in data.list) {
  65. let value = Object.assign({ 'session_id': sessionId }, data.list[key])
  66. await objTable.put(value)
  67. }
  68. let objUser = new User()
  69. objUser.replaceObjects(data.userMap)
  70. }
  71. async removeMsg (sessionId, hash) {
  72. const objMessage = new Message()
  73. // 数据保存到indexDB
  74. let objTable = await objMessage.getObjTable()
  75. if (!objTable) return
  76. objTable.delete(hash)
  77. }
  78. }
  79. export default Message