actions.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. if (state.scatter.identity) {
  85. await (state.scatter && state.scatter.forgetIdentity && state.scatter.forgetIdentity())
  86. }
  87. setUserOpt('isChangeIndentity', 1)
  88. // 调用getIdentity方法获取用户名
  89. try {
  90. var identity = await state.scatter.getIdentity({
  91. accounts: [networkConfig]
  92. })
  93. } catch (error) {
  94. if (error.type !== 'identity_rejected') {
  95. showError(error.message)
  96. }
  97. return Promise.reject(error)
  98. }
  99. let accounts = identity.accounts.find(x => x.blockchain === 'eos')
  100. // 合约登录
  101. let { data } = await API.user.getRandom2({ account: accounts.name })
  102. let random = data.data.random
  103. let accessToken = data.data.accessToken
  104. let trx = null
  105. let eos = state.scatter.eos(networkConfig, Eos, {})
  106. let contract = await eos.contract(eosExtInfo.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 new Promise((resolve, reject) => {
  115. API.user.eosBind2(param).then(() => {
  116. resolve(param)
  117. }).catch((e) => {
  118. reject(e)
  119. })
  120. })
  121. }
  122. },
  123. /**
  124. * 注销当前scatter账号
  125. * @param {Object} store
  126. * @param {Object} params
  127. */
  128. doScatterLogout ({ commit, state }, params) {
  129. Cookie.delCookie('user_id')
  130. Cookie.delCookie('token')
  131. localStorage.removeItem('user_id')
  132. localStorage.removeItem('token')
  133. localStorage.removeItem('accounts')
  134. commit('setUserId', null)
  135. commit('setToken', null)
  136. // sessionStorage.removeItem('vuex')
  137. commit('setAccount', '')
  138. setUserOpt('isChangeIndentity', 0)
  139. return state.scatter && state.scatter.identity ? state.scatter.forgetIdentity && state.scatter.forgetIdentity() : true
  140. },
  141. /**
  142. * 更新用户EOS币数量
  143. * @param {Object} store
  144. * @param {Object} params
  145. */
  146. getUserEOS ({ dispatch, commit, state }, params) {
  147. return new Promise((resolve, reject) => {
  148. window.EOS.getCurrencyBalance('eosio.token', state.account.name, 'EOS').then(([ balance ]) => {
  149. let balanceNum = Number(balance.replace(/\sEOS/, '')).toFixed(4)
  150. balanceNum = NP.times(balanceNum, 10000)
  151. commit('setBalance', balanceNum)
  152. commit('setEOSError', 0)
  153. resolve()
  154. }).catch(error => {
  155. // 失败重新尝试,最大尝试5次
  156. commit('setEOSError', state.eosErrorCount + 1)
  157. if (state.eosErrorCount <= 5) {
  158. setTimeout(() => {
  159. dispatch('getUserEOS')
  160. }, 1000 * state.eosErrorCount)
  161. }
  162. reject(error)
  163. })
  164. })
  165. },
  166. /**
  167. * 获取用户信息
  168. * @param {Object} store
  169. * @param {Object} params
  170. */
  171. getAccount ({ commit, state }, params) {
  172. return new Promise((resolve, reject) => {
  173. window.EOS.getAccount(state.account.name).then(data => {
  174. // 设置公钥
  175. const perms = JSON.parse(JSON.stringify(data.permissions))
  176. perms.forEach(v => {
  177. if (v.perm_name === 'active') {
  178. let publicKey = v.required_auth.keys[0].key
  179. commit('setPublicKey', publicKey)
  180. }
  181. })
  182. resolve(data)
  183. }).catch(error => {
  184. reject(error)
  185. })
  186. })
  187. },
  188. /**
  189. * 进行验证身份登录,生成业务登录态token
  190. * @param {Object} store
  191. * @param {Object} params
  192. */
  193. async doGameLogin ({ dispatch, commit, state }, params) {
  194. let userId = localStorage.getItem('user_id')
  195. let token = localStorage.getItem('token')
  196. if (userId && token) {
  197. commit('setUserId', userId)
  198. commit('setToken', token)
  199. return Promise.resolve({
  200. user_id: userId,
  201. token: token
  202. })
  203. } else {
  204. let rData = await API.user.getRandom({ account: state.account.name })
  205. let random = rData.data.data
  206. let pubkey = state.publicKey
  207. return new Promise((resolve, reject) => {
  208. state.scatter.getArbitrarySignature(pubkey, random, 'Need Login').then(sign => {
  209. let param = {
  210. account: state.account.name,
  211. sign,
  212. pubkey,
  213. data: random
  214. }
  215. API.user.eosLogin(param).then(({ data }) => {
  216. if (data.result === 1) {
  217. let userId = data.data.user_id
  218. let token = data.data.token
  219. localStorage.setItem('user_id', userId)
  220. localStorage.setItem('token', token)
  221. commit('setUserId', userId)
  222. commit('setToken', token)
  223. resolve(data)
  224. } else {
  225. reject(new Error(data.msg))
  226. }
  227. })
  228. }).catch(error => {
  229. reject(error)
  230. })
  231. })
  232. }
  233. },
  234. /**
  235. * 登录态过期,清除当前登录态相关数据,重新调起登录
  236. * @param {Object} store
  237. * @param {Object} params
  238. */
  239. async resetGameLogin ({ dispatch, commit, state }, params) {
  240. localStorage.removeItem('user_id')
  241. localStorage.removeItem('token')
  242. await dispatch('doContractLogin')
  243. if (self !== top) {
  244. location.replace(location.href.replace('show=false', 'show=true'))
  245. } else {
  246. location.reload()
  247. }
  248. },
  249. /**
  250. * 合约登录, 生成业务登录态token
  251. * @param {Array} params
  252. */
  253. async doContractLogin ({ commit, state }, params) {
  254. let eosType = getUserOpt('eosType') || 'eos'// eos操作类型meetone,eos,默认eos
  255. let eosExtInfo = {
  256. contract: eosType == 'meetone' ? 'meechat.m' : 'meechatadmin', // 合约
  257. net_id: eosType == 'meetone' ? 2 : 1 // 网络类型,1:EOS, 2:MeetOne
  258. }
  259. let userId = localStorage.getItem('user_id')
  260. let token = localStorage.getItem('token')
  261. if (userId && token) {
  262. commit('setUserId', userId)
  263. commit('setToken', token)
  264. return Promise.resolve({
  265. user_id: userId,
  266. token: token
  267. })
  268. } else {
  269. try {
  270. // 合约登录
  271. let { data } = await API.user.getRandom2({ account: state.account.name })
  272. let random = data.data.random
  273. let accessToken = data.data.accessToken
  274. let identity = { authorization: [`${state.account.name}@${state.account.authority}`] }
  275. let trx = null
  276. if (self !== top) {
  277. trx = await window.postMessager.send({
  278. action: 'meechat:eosAction',
  279. data: {
  280. contract: eosExtInfo.contract,
  281. action: 'login',
  282. param: [state.account.name, random, identity]
  283. }
  284. })
  285. } else {
  286. let eos = window.EOS || state.scatter.eos
  287. let contract = await eos.contract(eosExtInfo.contract)
  288. trx = await contract.login(state.account.name, random, identity)
  289. }
  290. let param = {
  291. account: state.account.name,
  292. access_token: accessToken,
  293. trx_id: trx.transaction_id || trx.transaction.transaction_id,
  294. group_id: state.group.groupId || null,
  295. net_id: eosExtInfo.net_id
  296. }
  297. let res = await API.user.eosLogin2(param)
  298. if (res.data.result === 1) {
  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. }