friendStore.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { defineStore } from 'pinia';
  2. import http from '../common/request'
  3. import { TERMINAL_TYPE } from '../common/enums.js'
  4. export default defineStore('friendStore', {
  5. state: () => {
  6. return {
  7. friends: [],
  8. timer: null
  9. }
  10. },
  11. actions: {
  12. setFriends(friends) {
  13. friends.forEach((f) => {
  14. f.online = false;
  15. f.onlineWeb = false;
  16. f.onlineApp = false;
  17. })
  18. this.friends = friends;
  19. },
  20. updateFriend(friend) {
  21. let f = this.findFriend(friend.id);
  22. let copy = JSON.parse(JSON.stringify(f));
  23. Object.assign(f, friend);
  24. f.online = copy.online;
  25. f.onlineWeb = copy.onlineWeb;
  26. f.onlineApp = copy.onlineApp;
  27. },
  28. removeFriend(id) {
  29. this.friends.filter(f => f.id == id).forEach(f => f.deleted = true);
  30. },
  31. addFriend(friend) {
  32. if (this.friends.some((f) => f.id == friend.id)) {
  33. this.updateFriend(friend)
  34. } else {
  35. this.friends.unshift(friend);
  36. }
  37. },
  38. setOnlineStatus(onlineTerminals) {
  39. this.friends.forEach((f) => {
  40. let userTerminal = onlineTerminals.find((o) => f.id == o.userId);
  41. if (userTerminal) {
  42. f.online = true;
  43. f.onlineWeb = userTerminal.terminals.indexOf(TERMINAL_TYPE.WEB) >= 0
  44. f.onlineApp = userTerminal.terminals.indexOf(TERMINAL_TYPE.APP) >= 0
  45. } else {
  46. f.online = false;
  47. f.onlineWeb = false;
  48. f.onlineApp = false;
  49. }
  50. });
  51. },
  52. refreshOnlineStatus() {
  53. let userIds = this.friends.filter((f) => !f.deleted).map((f) => f.id);
  54. if (userIds.length == 0) {
  55. return;
  56. }
  57. http({
  58. url: '/user/terminal/online?userIds=' + userIds.join(','),
  59. method: 'GET'
  60. }).then((onlineTerminals) => {
  61. this.setOnlineStatus(onlineTerminals);
  62. })
  63. // 30s后重新拉取
  64. clearTimeout(this.timer);
  65. this.timer = setTimeout(() => {
  66. this.refreshOnlineStatus();
  67. }, 30000)
  68. },
  69. clear() {
  70. clearTimeout(this.timer);
  71. this.friends = [];
  72. this.timer = null;
  73. },
  74. loadFriend() {
  75. return new Promise((resolve, reject) => {
  76. http({
  77. url: '/friend/list',
  78. method: 'GET'
  79. }).then((friends) => {
  80. this.setFriends(friends);
  81. this.refreshOnlineStatus();
  82. resolve()
  83. }).catch((res) => {
  84. reject();
  85. })
  86. });
  87. }
  88. },
  89. getters: {
  90. isFriend: (state) => (userId) => {
  91. return state.friends.filter((f) => !f.deleted).some((f) => f.id == userId);
  92. },
  93. findFriend: (state) => (id) => {
  94. return state.friends.find((f) => f.id == id);
  95. }
  96. }
  97. })