actions.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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.login({
  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.logout && state.scatter.logout())
  86. }
  87. setUserOpt('isChangeIndentity', 1)
  88. // 调用getIdentity方法获取用户名
  89. try {
  90. var identity = await state.scatter.login({
  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.logout && state.scatter.logout() : true
  140. return state.scatter && state.scatter.logout && state.scatter.logout()
  141. },
  142. /**
  143. * 更新用户EOS币数量
  144. * @param {Object} store
  145. * @param {Object} params
  146. */
  147. getUserEOS ({ dispatch, commit, state }, params) {
  148. return new Promise((resolve, reject) => {
  149. window.EOS.getCurrencyBalance('eosio.token', state.account.name, 'EOS').then(([ balance ]) => {
  150. let balanceNum = Number(balance.replace(/\sEOS/, '')).toFixed(4)
  151. balanceNum = NP.times(balanceNum, 10000)
  152. commit('setBalance', balanceNum)
  153. commit('setEOSError', 0)
  154. resolve()
  155. }).catch(error => {
  156. // 失败重新尝试,最大尝试5次
  157. commit('setEOSError', state.eosErrorCount + 1)
  158. if (state.eosErrorCount <= 5) {
  159. setTimeout(() => {
  160. dispatch('getUserEOS')
  161. }, 1000 * state.eosErrorCount)
  162. }
  163. reject(error)
  164. })
  165. })
  166. },
  167. /**
  168. * 获取用户信息
  169. * @param {Object} store
  170. * @param {Object} params
  171. */
  172. getAccount ({ commit, state }, params) {
  173. return new Promise((resolve, reject) => {
  174. window.EOS.getAccount(state.account.name).then(data => {
  175. // 设置公钥
  176. const perms = JSON.parse(JSON.stringify(data.permissions))
  177. perms.forEach(v => {
  178. if (v.perm_name === 'active') {
  179. let publicKey = v.required_auth.keys[0].key
  180. commit('setPublicKey', publicKey)
  181. }
  182. })
  183. resolve(data)
  184. }).catch(error => {
  185. reject(error)
  186. })
  187. })
  188. },
  189. /**
  190. * 进行验证身份登录,生成业务登录态token
  191. * @param {Object} store
  192. * @param {Object} params
  193. */
  194. async doGameLogin ({ dispatch, commit, state }, params) {
  195. let userId = localStorage.getItem('user_id')
  196. let token = localStorage.getItem('token')
  197. if (userId && token) {
  198. commit('setUserId', userId)
  199. commit('setToken', token)
  200. return Promise.resolve({
  201. user_id: userId,
  202. token: token
  203. })
  204. } else {
  205. let rData = await API.user.getRandom({ account: state.account.name })
  206. let random = rData.data.data
  207. let pubkey = state.publicKey
  208. return new Promise((resolve, reject) => {
  209. state.scatter.getArbitrarySignature(pubkey, random, 'Need Login').then(sign => {
  210. let param = {
  211. account: state.account.name,
  212. sign,
  213. pubkey,
  214. data: random
  215. }
  216. API.user.eosLogin(param).then(({ data }) => {
  217. if (data.result === 1) {
  218. let userId = data.data.user_id
  219. let token = data.data.token
  220. localStorage.setItem('user_id', userId)
  221. localStorage.setItem('token', token)
  222. commit('setUserId', userId)
  223. commit('setToken', token)
  224. resolve(data)
  225. } else {
  226. reject(new Error(data.msg))
  227. }
  228. })
  229. }).catch(error => {
  230. reject(error)
  231. })
  232. })
  233. }
  234. },
  235. /**
  236. * 登录态过期,清除当前登录态相关数据,重新调起登录
  237. * @param {Object} store
  238. * @param {Object} params
  239. */
  240. async resetGameLogin ({ dispatch, commit, state }, params) {
  241. localStorage.removeItem('user_id')
  242. localStorage.removeItem('token')
  243. await dispatch('doContractLogin')
  244. if (self !== top) {
  245. location.replace(location.href.replace('show=false', 'show=true'))
  246. } else {
  247. location.reload()
  248. }
  249. },
  250. /**
  251. * 合约登录, 生成业务登录态token
  252. * @param {Array} params
  253. */
  254. async doContractLogin ({ commit, state }, params) {
  255. let eosType = getUserOpt('eosType') || 'eos'// eos操作类型meetone,eos,默认eos
  256. let eosExtInfo = {
  257. contract: eosType == 'meetone' ? 'meechat.m' : 'meechatadmin', // 合约
  258. net_id: eosType == 'meetone' ? 2 : 1 // 网络类型,1:EOS, 2:MeetOne
  259. }
  260. let userId = localStorage.getItem('user_id')
  261. let token = localStorage.getItem('token')
  262. if (userId && token) {
  263. commit('setUserId', userId)
  264. commit('setToken', token)
  265. return Promise.resolve({
  266. user_id: userId,
  267. token: token
  268. })
  269. } else {
  270. try {
  271. // 合约登录
  272. let { data } = await API.user.getRandom2({ account: state.account.name })
  273. let random = data.data.random
  274. let accessToken = data.data.accessToken
  275. let identity = { authorization: [`${state.account.name}@${state.account.authority}`] }
  276. let trx = null
  277. let networkConfig = await getNetwork()
  278. if (self !== top) {
  279. trx = await window.postMessager.send({
  280. action: 'meechat:eosAction',
  281. data: {
  282. contract: eosExtInfo.contract,
  283. action: 'login',
  284. param: [state.account.name, random, identity],
  285. network: networkConfig
  286. }
  287. })
  288. } else {
  289. let eos = window.EOS || state.scatter.eos
  290. let contract = await eos.contract(eosExtInfo.contract)
  291. trx = await contract.login(state.account.name, random, identity)
  292. }
  293. let param = {
  294. account: state.account.name,
  295. access_token: accessToken,
  296. trx_id: trx.transaction_id || trx.transaction.transaction_id,
  297. group_id: state.group.groupId || null,
  298. net_id: eosExtInfo.net_id
  299. }
  300. let res = await API.user.eosLogin2(param)
  301. if (res.data.result === 1) {
  302. return Promise.resolve(res.data)
  303. }
  304. } catch (error) {
  305. return Promise.reject(error)
  306. }
  307. }
  308. },
  309. /**
  310. * @des 获取热门群组
  311. */
  312. getHotList ({ state }, params) {
  313. if (state.hotList.length > 0) return
  314. API.group.getHotList().then(({ data }) => {
  315. state.hotList = data.data
  316. })
  317. },
  318. /**
  319. * @des 获取发现
  320. */
  321. getDiscovery ({ state }, params) {
  322. if (state.hotGame.length > 0 && state.hotList.length > 0) return
  323. API.base.discovery().then(({ data }) => {
  324. state.hotGame = data.data.hotGame
  325. state.hotList = data.data.hotGroup
  326. })
  327. }
  328. }