actions.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. import NP from 'number-precision'
  2. import API from '@/api'
  3. import { showError, Cookie, getUserOpt, setUserOpt } from '@/util/util.js'
  4. import { getNetwork } from '@/util/contract.js'
  5. import Eos from 'eosjs'
  6. export const actions = {
  7. setScatter: ({ commit }, scatter) => commit('setScatter', scatter),
  8. setEos: ({ commit }, eosjs) => commit('setEos', eosjs),
  9. setAccount: ({ commit }, account) => commit('setAccount', account),
  10. /**
  11. * 调起授权登录
  12. * @param {Object} store
  13. * @param {Object} params
  14. */
  15. async doScatterLogin ({ dispatch, commit, state }, h5Router) {
  16. if (!state.scatter) {
  17. showError('Please install the scatter', 'Scatter')
  18. } else {
  19. if (getUserOpt('isChangeIndentity') == 1) {
  20. await actions.doScatterLogout(...arguments)
  21. localStorage.setItem('accounts', '')
  22. setUserOpt('isChangeIndentity', 0)
  23. }
  24. // 获取最快主网
  25. let networkConfig = await getNetwork()
  26. // 调用getIdentity方法获取用户名
  27. try {
  28. var identity = await state.scatter.getIdentity({
  29. accounts: [networkConfig]
  30. })
  31. } catch (error) {
  32. if (error.type !== 'identity_rejected') {
  33. showError(error.message)
  34. }
  35. return Promise.reject(error)
  36. }
  37. let accounts = identity.accounts.find(x => x.blockchain === 'eos')
  38. let lastAccounts = localStorage.getItem('accounts')
  39. if (lastAccounts && JSON.parse(lastAccounts).name !== accounts.name) {
  40. await actions.doScatterLogout(...arguments)
  41. h5Router.push({ path: '/login' })
  42. commit('setUserInfo', null)
  43. commit('initChatData')
  44. commit('initGroupData')
  45. commit('chatAppLogin', false)
  46. commit('toApp', false)
  47. }
  48. commit('setAccount', accounts)
  49. localStorage.setItem('accounts', JSON.stringify(accounts))
  50. // 如果当前登录的用户名和cookie中保存的account不一致
  51. // 则删除cookie中保存的account
  52. // 避免某些用户在移动端钱包中切换账号时跳过注销流程导致账号不一致的问题
  53. // if (Cookie.getCookie('account') !== accounts.name) {
  54. // Cookie.delCookie('account')
  55. // }
  56. // 设置全局EOS对象
  57. window.EOS = state.scatter.eos(networkConfig, Eos, {})
  58. // 调用scatter登录成功后获取用户EOS、GT
  59. // dispatch('getUserEOS')
  60. // dispatch('getUserGT')
  61. await dispatch('getAccount')
  62. // 每分钟刷新一次
  63. // this.limitTimer = setInterval(() => {
  64. // dispatch('getAccount')
  65. // }, 60000)
  66. return Promise.resolve(true)
  67. }
  68. },
  69. /**
  70. * eos账号绑定
  71. * @param {*} param0
  72. */
  73. async doScatterBind ({ dispatch, commit, state }) {
  74. let eosType = getUserOpt('eosType') || 'eos'// eos操作类型meetone,eos,默认eos
  75. let eosExtInfo = {
  76. contract: eosType == 'meetone' ? 'meechat.m' : 'meechatadmin', // 合约
  77. net_id: eosType == 'meetone' ? 2 : 1 // 网络类型,1:EOS, 2:MeetOne
  78. }
  79. if (!state.scatter) {
  80. showError('Please install the scatter', 'Scatter')
  81. } else {
  82. // 获取最快主网
  83. let networkConfig = await getNetwork()
  84. await (state.scatter && state.scatter.forgetIdentity && state.scatter.forgetIdentity())
  85. setUserOpt('isChangeIndentity', 1)
  86. // 调用getIdentity方法获取用户名
  87. try {
  88. var identity = await state.scatter.getIdentity({
  89. accounts: [networkConfig]
  90. })
  91. } catch (error) {
  92. if (error.type !== 'identity_rejected') {
  93. showError(error.message)
  94. }
  95. return Promise.reject(error)
  96. }
  97. let accounts = identity.accounts.find(x => x.blockchain === 'eos')
  98. console.log('identity', identity)
  99. // 合约登录
  100. let { data } = await API.user.getRandom2({ account: accounts.name })
  101. let random = data.data.random
  102. let accessToken = data.data.accessToken
  103. let trx = null
  104. let eos = state.scatter.eos(networkConfig, Eos, {})
  105. let contract = await eos.contract(eosExtInfo.contract)
  106. console.log('contract', contract)
  107. trx = await contract.login(accounts.name, random, { authorization: [`${accounts.name}@${accounts.authority}`] })
  108. let param = {
  109. account: accounts.name,
  110. access_token: accessToken,
  111. trx_id: trx.transaction_id || trx.transaction.transaction_id,
  112. net_id: eosExtInfo.net_id
  113. }
  114. return API.user.eosBind2(param)
  115. }
  116. },
  117. /**
  118. * 注销当前scatter账号
  119. * @param {Object} store
  120. * @param {Object} params
  121. */
  122. doScatterLogout ({ commit, state }, params) {
  123. Cookie.delCookie('user_id')
  124. Cookie.delCookie('token')
  125. localStorage.removeItem('user_id')
  126. localStorage.removeItem('token')
  127. localStorage.removeItem('accounts')
  128. commit('setUserId', null)
  129. commit('setToken', null)
  130. // sessionStorage.removeItem('vuex')
  131. commit('setAccount', '')
  132. setUserOpt('isChangeIndentity', 0)
  133. return state.scatter && state.scatter.forgetIdentity && state.scatter.forgetIdentity()
  134. },
  135. /**
  136. * 更新用户EOS币数量
  137. * @param {Object} store
  138. * @param {Object} params
  139. */
  140. getUserEOS ({ dispatch, commit, state }, params) {
  141. return new Promise((resolve, reject) => {
  142. window.EOS.getCurrencyBalance('eosio.token', state.account.name, 'EOS').then(([ balance ]) => {
  143. let balanceNum = Number(balance.replace(/\sEOS/, '')).toFixed(4)
  144. balanceNum = NP.times(balanceNum, 10000)
  145. commit('setBalance', balanceNum)
  146. commit('setEOSError', 0)
  147. resolve()
  148. }).catch(error => {
  149. // 失败重新尝试,最大尝试5次
  150. commit('setEOSError', state.eosErrorCount + 1)
  151. if (state.eosErrorCount <= 5) {
  152. setTimeout(() => {
  153. dispatch('getUserEOS')
  154. }, 1000 * state.eosErrorCount)
  155. }
  156. reject(error)
  157. })
  158. })
  159. },
  160. /**
  161. * 获取用户信息
  162. * @param {Object} store
  163. * @param {Object} params
  164. */
  165. getAccount ({ commit, state }, params) {
  166. return new Promise((resolve, reject) => {
  167. window.EOS.getAccount(state.account.name).then(data => {
  168. // 设置公钥
  169. const perms = JSON.parse(JSON.stringify(data.permissions))
  170. perms.forEach(v => {
  171. if (v.perm_name === 'active') {
  172. let publicKey = v.required_auth.keys[0].key
  173. commit('setPublicKey', publicKey)
  174. }
  175. })
  176. resolve(data)
  177. }).catch(error => {
  178. reject(error)
  179. })
  180. })
  181. },
  182. /**
  183. * 进行验证身份登录,生成业务登录态token
  184. * @param {Object} store
  185. * @param {Object} params
  186. */
  187. async doGameLogin ({ dispatch, commit, state }, params) {
  188. let userId = localStorage.getItem('user_id')
  189. let token = localStorage.getItem('token')
  190. if (userId && token) {
  191. commit('setUserId', userId)
  192. commit('setToken', token)
  193. return Promise.resolve({
  194. user_id: userId,
  195. token: token
  196. })
  197. } else {
  198. let rData = await API.user.getRandom({ account: state.account.name })
  199. let random = rData.data.data
  200. let pubkey = state.publicKey
  201. return new Promise((resolve, reject) => {
  202. state.scatter.getArbitrarySignature(pubkey, random, 'Need Login').then(sign => {
  203. let param = {
  204. account: state.account.name,
  205. sign,
  206. pubkey,
  207. data: random
  208. }
  209. API.user.eosLogin(param).then(({ data }) => {
  210. if (data.result === 1) {
  211. let userId = data.data.user_id
  212. let token = data.data.token
  213. localStorage.setItem('user_id', userId)
  214. localStorage.setItem('token', token)
  215. commit('setUserId', userId)
  216. commit('setToken', token)
  217. resolve(data)
  218. } else {
  219. reject(new Error(data.msg))
  220. }
  221. })
  222. }).catch(error => {
  223. reject(error)
  224. })
  225. })
  226. }
  227. },
  228. /**
  229. * 登录态过期,清除当前登录态相关数据,重新调起登录
  230. * @param {Object} store
  231. * @param {Object} params
  232. */
  233. async resetGameLogin ({ dispatch, commit, state }, params) {
  234. localStorage.removeItem('user_id')
  235. localStorage.removeItem('token')
  236. await dispatch('doContractLogin')
  237. if (self !== top) {
  238. location.replace(location.href.replace('show=false', 'show=true'))
  239. } else {
  240. location.reload()
  241. }
  242. },
  243. /**
  244. * 合约登录, 生成业务登录态token
  245. * @param {Array} params
  246. */
  247. async doContractLogin ({ commit, state }, params) {
  248. let eosType = getUserOpt('eosType') || 'eos'// eos操作类型meetone,eos,默认eos
  249. let eosExtInfo = {
  250. contract: eosType == 'meetone' ? 'meechat.m' : 'meechatadmin', // 合约
  251. net_id: eosType == 'meetone' ? 2 : 1 // 网络类型,1:EOS, 2:MeetOne
  252. }
  253. let userId = localStorage.getItem('user_id')
  254. let token = localStorage.getItem('token')
  255. if (userId && token) {
  256. commit('setUserId', userId)
  257. commit('setToken', token)
  258. return Promise.resolve({
  259. user_id: userId,
  260. token: token
  261. })
  262. } else {
  263. try {
  264. // 合约登录
  265. let { data } = await API.user.getRandom2({ account: state.account.name })
  266. let random = data.data.random
  267. let accessToken = data.data.accessToken
  268. let identity = { authorization: [`${state.account.name}@${state.account.authority}`] }
  269. let trx = null
  270. if (self !== top) {
  271. trx = await window.postMessager.send({
  272. action: 'meechat:eosAction',
  273. data: {
  274. contract: eosExtInfo.contract,
  275. action: 'login',
  276. param: [state.account.name, random, identity]
  277. }
  278. })
  279. } else {
  280. let eos = window.EOS || state.scatter.eos
  281. let contract = await eos.contract(eosExtInfo.contract)
  282. trx = await contract.login(state.account.name, random, identity)
  283. }
  284. let param = {
  285. account: state.account.name,
  286. access_token: accessToken,
  287. trx_id: trx.transaction_id || trx.transaction.transaction_id,
  288. group_id: state.group.groupId || null,
  289. net_id: eosExtInfo.net_id
  290. }
  291. let res = await API.user.eosLogin2(param)
  292. if (res.data.result === 1) {
  293. let userId = res.data.data.user_id
  294. let token = res.data.data.token
  295. localStorage.setItem('user_id', userId)
  296. localStorage.setItem('token', token)
  297. commit('setUserId', userId)
  298. commit('setToken', token)
  299. return Promise.resolve(res.data)
  300. }
  301. } catch (error) {
  302. return Promise.reject(error)
  303. }
  304. }
  305. },
  306. /**
  307. * @des 获取热门群组
  308. */
  309. getHotList ({ state }, params) {
  310. if (state.hotList.length > 0) return
  311. API.group.getHotList().then(({ data }) => {
  312. state.hotList = data.data
  313. })
  314. },
  315. /**
  316. * @des 获取发现
  317. */
  318. getDiscovery ({ state }, params) {
  319. if (state.hotGame.length > 0 && state.hotList.length > 0) return
  320. API.base.discovery().then(({ data }) => {
  321. state.hotGame = data.data.hotGame
  322. state.hotList = data.data.hotGroup
  323. })
  324. }
  325. }