actions.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. * 调起授权登录
  71. * @param {Object} store
  72. * @param {Object} params
  73. */
  74. async doScatterLoginCopy ({ dispatch, commit, state }, h5Router) {
  75. if (!state.scatter) {
  76. showError('Please install the scatter', 'Scatter')
  77. } else {
  78. if (getUserOpt('isChangeIndentity') == 1) {
  79. await actions.doScatterLogout(...arguments)
  80. localStorage.setItem('accounts', '')
  81. setUserOpt('isChangeIndentity', 0)
  82. }
  83. alert('networkConfig before')
  84. // 获取最快主网
  85. let networkConfig = await getNetwork()
  86. alert('networkConfig next')
  87. // 调用getIdentity方法获取用户名
  88. try {
  89. var identity = await state.scatter.login({
  90. accounts: [networkConfig]
  91. })
  92. } catch (error) {
  93. if (error.type !== 'identity_rejected') {
  94. showError(error.message)
  95. }
  96. return Promise.reject(error)
  97. }
  98. let accounts = identity.accounts.find(x => x.blockchain === 'eos')
  99. let lastAccounts = localStorage.getItem('accounts')
  100. if (lastAccounts && JSON.parse(lastAccounts).name !== accounts.name) {
  101. await actions.doScatterLogout(...arguments)
  102. h5Router.push({ path: '/login' })
  103. commit('setUserInfo', null)
  104. commit('initChatData')
  105. commit('initGroupData')
  106. commit('chatAppLogin', false)
  107. commit('toApp', false)
  108. }
  109. commit('setAccount', accounts)
  110. localStorage.setItem('accounts', JSON.stringify(accounts))
  111. // 如果当前登录的用户名和cookie中保存的account不一致
  112. // 则删除cookie中保存的account
  113. // 避免某些用户在移动端钱包中切换账号时跳过注销流程导致账号不一致的问题
  114. // if (Cookie.getCookie('account') !== accounts.name) {
  115. // Cookie.delCookie('account')
  116. // }
  117. // 设置全局EOS对象
  118. window.EOS = state.scatter.eos(networkConfig, Eos, {})
  119. // 调用scatter登录成功后获取用户EOS、GT
  120. // dispatch('getUserEOS')
  121. // dispatch('getUserGT')
  122. await dispatch('getAccount')
  123. // 每分钟刷新一次
  124. // this.limitTimer = setInterval(() => {
  125. // dispatch('getAccount')
  126. // }, 60000)
  127. return Promise.resolve(true)
  128. }
  129. },
  130. /**
  131. * eos账号绑定
  132. * @param {*} param0
  133. */
  134. async doScatterBind ({ dispatch, commit, state }) {
  135. let eosType = getUserOpt('eosType') || 'eos'// eos操作类型meetone,eos,默认eos
  136. let eosExtInfo = {
  137. contract: eosType == 'meetone' ? 'meechat.m' : 'meechatadmin', // 合约
  138. net_id: eosType == 'meetone' ? 2 : 1 // 网络类型,1:EOS, 2:MeetOne
  139. }
  140. if (!state.scatter) {
  141. showError('Please install the scatter', 'Scatter')
  142. } else {
  143. // 获取最快主网
  144. let networkConfig = await getNetwork()
  145. if (state.scatter.identity) {
  146. await (state.scatter && state.scatter.logout && state.scatter.logout())
  147. }
  148. setUserOpt('isChangeIndentity', 1)
  149. // 调用getIdentity方法获取用户名
  150. try {
  151. var identity = await state.scatter.login({
  152. accounts: [networkConfig]
  153. })
  154. } catch (error) {
  155. if (error.type !== 'identity_rejected') {
  156. showError(error.message)
  157. }
  158. return Promise.reject(error)
  159. }
  160. let accounts = identity.accounts.find(x => x.blockchain === 'eos')
  161. // 合约登录
  162. let { data } = await API.user.getRandom2({ account: accounts.name })
  163. let random = data.data.random
  164. let accessToken = data.data.accessToken
  165. let trx = null
  166. let eos = state.scatter.eos(networkConfig, Eos, {})
  167. let contract = await eos.contract(eosExtInfo.contract)
  168. trx = await contract.login(accounts.name, random, { authorization: [`${accounts.name}@${accounts.authority}`] })
  169. let param = {
  170. account: accounts.name,
  171. access_token: accessToken,
  172. trx_id: trx.transaction_id || trx.transaction.transaction_id,
  173. net_id: eosExtInfo.net_id
  174. }
  175. return new Promise((resolve, reject) => {
  176. API.user.eosBind2(param).then(() => {
  177. resolve(param)
  178. }).catch((e) => {
  179. reject(e)
  180. })
  181. })
  182. }
  183. },
  184. /**
  185. * 注销当前scatter账号
  186. * @param {Object} store
  187. * @param {Object} params
  188. */
  189. doScatterLogout ({ commit, state }, params) {
  190. Cookie.delCookie('user_id')
  191. Cookie.delCookie('token')
  192. localStorage.removeItem('user_id')
  193. localStorage.removeItem('token')
  194. localStorage.removeItem('accounts')
  195. commit('setUserId', null)
  196. commit('setToken', null)
  197. // sessionStorage.removeItem('vuex')
  198. commit('setAccount', '')
  199. setUserOpt('isChangeIndentity', 0)
  200. // return state.scatter && state.scatter.identity ? state.scatter.logout && state.scatter.logout() : true
  201. return (state.scatter && state.scatter.identity && state.scatter.logout && state.scatter.logout()) || true
  202. },
  203. /**
  204. * 更新用户EOS币数量
  205. * @param {Object} store
  206. * @param {Object} params
  207. */
  208. getUserEOS ({ dispatch, commit, state }, params) {
  209. return new Promise((resolve, reject) => {
  210. window.EOS.getCurrencyBalance('eosio.token', state.account.name, 'EOS').then(([ balance ]) => {
  211. let balanceNum = Number(balance.replace(/\sEOS/, '')).toFixed(4)
  212. balanceNum = NP.times(balanceNum, 10000)
  213. commit('setBalance', balanceNum)
  214. commit('setEOSError', 0)
  215. resolve()
  216. }).catch(error => {
  217. // 失败重新尝试,最大尝试5次
  218. commit('setEOSError', state.eosErrorCount + 1)
  219. if (state.eosErrorCount <= 5) {
  220. setTimeout(() => {
  221. dispatch('getUserEOS')
  222. }, 1000 * state.eosErrorCount)
  223. }
  224. reject(error)
  225. })
  226. })
  227. },
  228. /**
  229. * 获取用户信息
  230. * @param {Object} store
  231. * @param {Object} params
  232. */
  233. getAccount ({ commit, state }, params) {
  234. return new Promise((resolve, reject) => {
  235. window.EOS.getAccount(state.account.name).then(data => {
  236. // 设置公钥
  237. const perms = JSON.parse(JSON.stringify(data.permissions))
  238. perms.forEach(v => {
  239. if (v.perm_name === 'active') {
  240. let publicKey = v.required_auth.keys[0].key
  241. commit('setPublicKey', publicKey)
  242. }
  243. })
  244. resolve(data)
  245. }).catch(error => {
  246. reject(error)
  247. })
  248. })
  249. },
  250. /**
  251. * 进行验证身份登录,生成业务登录态token
  252. * @param {Object} store
  253. * @param {Object} params
  254. */
  255. async doGameLogin ({ dispatch, commit, state }, params) {
  256. let userId = localStorage.getItem('user_id')
  257. let token = localStorage.getItem('token')
  258. if (userId && token) {
  259. commit('setUserId', userId)
  260. commit('setToken', token)
  261. return Promise.resolve({
  262. user_id: userId,
  263. token: token
  264. })
  265. } else {
  266. let rData = await API.user.getRandom({ account: state.account.name })
  267. let random = rData.data.data
  268. let pubkey = state.publicKey
  269. return new Promise((resolve, reject) => {
  270. state.scatter.getArbitrarySignature(pubkey, random, 'Need Login').then(sign => {
  271. let param = {
  272. account: state.account.name,
  273. sign,
  274. pubkey,
  275. data: random
  276. }
  277. API.user.eosLogin(param).then(({ data }) => {
  278. if (data.result === 1) {
  279. let userId = data.data.user_id
  280. let token = data.data.token
  281. localStorage.setItem('user_id', userId)
  282. localStorage.setItem('token', token)
  283. commit('setUserId', userId)
  284. commit('setToken', token)
  285. resolve(data)
  286. } else {
  287. reject(new Error(data.msg))
  288. }
  289. })
  290. }).catch(error => {
  291. reject(error)
  292. })
  293. })
  294. }
  295. },
  296. /**
  297. * 登录态过期,清除当前登录态相关数据,重新调起登录
  298. * @param {Object} store
  299. * @param {Object} params
  300. */
  301. async resetGameLogin ({ dispatch, commit, state }, params) {
  302. localStorage.removeItem('user_id')
  303. localStorage.removeItem('token')
  304. await dispatch('doContractLogin')
  305. if (self !== top) {
  306. location.replace(location.href.replace('show=false', 'show=true'))
  307. } else {
  308. location.reload()
  309. }
  310. },
  311. /**
  312. * 合约登录, 生成业务登录态token
  313. * @param {Array} params
  314. */
  315. async doContractLogin ({ commit, state }, params) {
  316. let eosType = getUserOpt('eosType') || 'eos'// eos操作类型meetone,eos,默认eos
  317. let eosExtInfo = {
  318. contract: eosType == 'meetone' ? 'meechat.m' : 'meechatadmin', // 合约
  319. net_id: eosType == 'meetone' ? 2 : 1 // 网络类型,1:EOS, 2:MeetOne
  320. }
  321. let userId = localStorage.getItem('user_id')
  322. let token = localStorage.getItem('token')
  323. if (userId && token) {
  324. commit('setUserId', userId)
  325. commit('setToken', token)
  326. return Promise.resolve({
  327. user_id: userId,
  328. token: token
  329. })
  330. } else {
  331. try {
  332. // 合约登录
  333. let { data } = await API.user.getRandom2({ account: state.account.name })
  334. let random = data.data.random
  335. let accessToken = data.data.accessToken
  336. let identity = { authorization: [`${state.account.name}@${state.account.authority}`] }
  337. let trx = null
  338. let networkConfig = await getNetwork()
  339. if (self !== top) {
  340. trx = await window.postMessager.send({
  341. action: 'meechat:eosAction',
  342. data: {
  343. contract: eosExtInfo.contract,
  344. action: 'login',
  345. param: [state.account.name, random, identity],
  346. network: networkConfig
  347. }
  348. })
  349. } else {
  350. let eos = window.EOS || state.scatter.eos
  351. let contract = await eos.contract(eosExtInfo.contract)
  352. trx = await contract.login(state.account.name, random, identity)
  353. }
  354. let param = {
  355. account: state.account.name,
  356. access_token: accessToken,
  357. trx_id: trx.transaction_id || trx.transaction.transaction_id,
  358. group_id: state.group.groupId || null,
  359. net_id: eosExtInfo.net_id
  360. }
  361. let res = await API.user.eosLogin2(param)
  362. if (res.data.result === 1) {
  363. return Promise.resolve(res.data)
  364. }
  365. } catch (error) {
  366. return Promise.reject(error)
  367. }
  368. }
  369. },
  370. /**
  371. * @des 获取热门群组
  372. */
  373. getHotList ({ state }, params) {
  374. if (state.hotList.length > 0) return
  375. API.group.getHotList().then(({ data }) => {
  376. state.hotList = data.data
  377. })
  378. },
  379. /**
  380. * @des 获取发现
  381. */
  382. getDiscovery ({ state }, params) {
  383. if (state.hotGame.length > 0 && state.hotList.length > 0) return
  384. API.base.discovery().then(({ data }) => {
  385. state.hotGame = data.data.hotGame
  386. state.hotList = data.data.hotGroup
  387. })
  388. }
  389. }