1
0

token-store.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package channel
  2. import (
  3. "message-pusher/common"
  4. "message-pusher/model"
  5. "sync"
  6. "time"
  7. )
  8. type TokenStoreItem interface {
  9. Key() string
  10. Token() string
  11. Refresh()
  12. IsFilled() bool
  13. IsShared() bool
  14. }
  15. type tokenStore struct {
  16. Map map[string]*TokenStoreItem
  17. Mutex sync.RWMutex
  18. ExpirationSeconds int
  19. }
  20. var s tokenStore
  21. func channel2item(channel_ *model.Channel) TokenStoreItem {
  22. switch channel_.Type {
  23. case model.TypeWeChatTestAccount:
  24. item := &WeChatTestAccountTokenStoreItem{
  25. AppID: channel_.AppId,
  26. AppSecret: channel_.Secret,
  27. }
  28. return item
  29. case model.TypeWeChatCorpAccount:
  30. corpId, agentId, err := parseWechatCorpAccountAppId(channel_.AppId)
  31. if err != nil {
  32. common.SysError(err.Error())
  33. return nil
  34. }
  35. item := &WeChatCorpAccountTokenStoreItem{
  36. CorpId: corpId,
  37. AgentSecret: channel_.Secret,
  38. AgentId: agentId,
  39. }
  40. return item
  41. case model.TypeLarkApp:
  42. item := &LarkAppTokenStoreItem{
  43. AppID: channel_.AppId,
  44. AppSecret: channel_.Secret,
  45. }
  46. return item
  47. }
  48. return nil
  49. }
  50. func channels2items(channels []*model.Channel) []TokenStoreItem {
  51. var items []TokenStoreItem
  52. for _, channel_ := range channels {
  53. item := channel2item(channel_)
  54. if item != nil {
  55. items = append(items, item)
  56. }
  57. }
  58. return items
  59. }
  60. func TokenStoreInit() {
  61. s.Map = make(map[string]*TokenStoreItem)
  62. // https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
  63. // https://developer.work.weixin.qq.com/document/path/91039
  64. s.ExpirationSeconds = 2 * 55 * 60 // 2 hours - 5 minutes
  65. go func() {
  66. channels, err := model.GetTokenStoreChannels()
  67. if err != nil {
  68. common.FatalLog(err.Error())
  69. }
  70. items := channels2items(channels)
  71. s.Mutex.RLock()
  72. for i := range items {
  73. // s.Map[item.Key()] = &item // This is wrong, you are getting the address of a local variable!
  74. s.Map[items[i].Key()] = &items[i]
  75. }
  76. s.Mutex.RUnlock()
  77. for {
  78. s.Mutex.RLock()
  79. var tmpMap = make(map[string]*TokenStoreItem)
  80. for k, v := range s.Map {
  81. tmpMap[k] = v
  82. }
  83. s.Mutex.RUnlock()
  84. for k := range tmpMap {
  85. (*tmpMap[k]).Refresh()
  86. }
  87. s.Mutex.RLock()
  88. // we shouldn't directly replace the old map with the new map, cause the old map's keys may already change
  89. for k := range s.Map {
  90. v, okay := tmpMap[k]
  91. if okay {
  92. s.Map[k] = v
  93. }
  94. }
  95. sleepDuration := common.Max(s.ExpirationSeconds, 60)
  96. s.Mutex.RUnlock()
  97. time.Sleep(time.Duration(sleepDuration) * time.Second)
  98. }
  99. }()
  100. }
  101. // TokenStoreAddItem It's okay to add an incomplete item.
  102. func TokenStoreAddItem(item TokenStoreItem) {
  103. if !item.IsFilled() {
  104. return
  105. }
  106. item.Refresh()
  107. s.Mutex.RLock()
  108. s.Map[item.Key()] = &item
  109. s.Mutex.RUnlock()
  110. }
  111. func TokenStoreRemoveItem(item TokenStoreItem) {
  112. s.Mutex.RLock()
  113. delete(s.Map, item.Key())
  114. s.Mutex.RUnlock()
  115. }
  116. func TokenStoreAddUser(user *model.User) {
  117. channels, err := model.GetTokenStoreChannelsByUserId(user.Id)
  118. if err != nil {
  119. common.SysError(err.Error())
  120. return
  121. }
  122. items := channels2items(channels)
  123. for i := range items {
  124. TokenStoreAddItem(items[i])
  125. }
  126. }
  127. // TokenStoreRemoveUser
  128. // user must be filled.
  129. // It's okay to delete a user that don't have an item here.
  130. func TokenStoreRemoveUser(user *model.User) {
  131. channels, err := model.GetTokenStoreChannelsByUserId(user.Id)
  132. if err != nil {
  133. common.SysError(err.Error())
  134. return
  135. }
  136. items := channels2items(channels)
  137. for i := range items {
  138. if items[i].IsShared() {
  139. continue
  140. }
  141. TokenStoreRemoveItem(items[i])
  142. }
  143. }
  144. func checkTokenStoreChannelType(channelType string) bool {
  145. return channelType == model.TypeWeChatTestAccount || channelType == model.TypeWeChatCorpAccount || channelType == model.TypeLarkApp
  146. }
  147. func TokenStoreAddChannel(channel *model.Channel) {
  148. if !checkTokenStoreChannelType(channel.Type) {
  149. return
  150. }
  151. item := channel2item(channel)
  152. if item != nil {
  153. // Do not check IsShared here, cause its useless
  154. TokenStoreAddItem(item)
  155. }
  156. }
  157. func TokenStoreRemoveChannel(channel *model.Channel) {
  158. if !checkTokenStoreChannelType(channel.Type) {
  159. return
  160. }
  161. item := channel2item(channel)
  162. if item != nil && !item.IsShared() {
  163. TokenStoreRemoveItem(item)
  164. }
  165. }
  166. func TokenStoreUpdateChannel(newChannel *model.Channel, oldChannel *model.Channel) {
  167. if oldChannel.Type != model.TypeWeChatTestAccount && oldChannel.Type != model.TypeWeChatCorpAccount {
  168. return
  169. }
  170. // Why so complicated? Because the given channel maybe incomplete.
  171. if oldChannel.Type == model.TypeWeChatTestAccount {
  172. // Only keep changed parts
  173. if newChannel.AppId == oldChannel.AppId {
  174. newChannel.AppId = ""
  175. }
  176. if newChannel.Secret == oldChannel.Secret {
  177. newChannel.Secret = ""
  178. }
  179. oldItem := WeChatTestAccountTokenStoreItem{
  180. AppID: oldChannel.AppId,
  181. AppSecret: oldChannel.Secret,
  182. }
  183. // Yeah, it's a deep copy.
  184. newItem := oldItem
  185. // This means the user updated those fields.
  186. if newChannel.AppId != "" {
  187. newItem.AppID = newChannel.AppId
  188. }
  189. if newChannel.Secret != "" {
  190. newItem.AppSecret = newChannel.Secret
  191. }
  192. if !oldItem.IsShared() {
  193. TokenStoreRemoveItem(&oldItem)
  194. }
  195. TokenStoreAddItem(&newItem)
  196. return
  197. }
  198. if oldChannel.Type == model.TypeWeChatCorpAccount {
  199. // Only keep changed parts
  200. if newChannel.AppId == oldChannel.AppId {
  201. newChannel.AppId = ""
  202. }
  203. if newChannel.Secret == oldChannel.Secret {
  204. newChannel.Secret = ""
  205. }
  206. corpId, agentId, err := parseWechatCorpAccountAppId(oldChannel.AppId)
  207. if err != nil {
  208. common.SysError(err.Error())
  209. return
  210. }
  211. oldItem := WeChatCorpAccountTokenStoreItem{
  212. CorpId: corpId,
  213. AgentSecret: oldChannel.Secret,
  214. AgentId: agentId,
  215. }
  216. // Yeah, it's a deep copy.
  217. newItem := oldItem
  218. // This means the user updated those fields.
  219. if newChannel.AppId != "" {
  220. corpId, agentId, err := parseWechatCorpAccountAppId(oldChannel.AppId)
  221. if err != nil {
  222. common.SysError(err.Error())
  223. return
  224. }
  225. newItem.CorpId = corpId
  226. newItem.AgentId = agentId
  227. }
  228. if newChannel.Secret != "" {
  229. newItem.AgentSecret = newChannel.Secret
  230. }
  231. if !oldItem.IsShared() {
  232. TokenStoreRemoveItem(&oldItem)
  233. }
  234. TokenStoreAddItem(&newItem)
  235. return
  236. }
  237. }
  238. func TokenStoreGetToken(key string) string {
  239. s.Mutex.RLock()
  240. defer s.Mutex.RUnlock()
  241. item, ok := s.Map[key]
  242. if ok {
  243. return (*item).Token()
  244. }
  245. common.SysError("token for " + key + " is blank!")
  246. return ""
  247. }