appInit.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. import uniStarterConfig from '@/uni-starter.config.js';
  2. import store from '@/store'
  3. //应用初始化页
  4. // #ifdef APP-PLUS
  5. import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update';
  6. import callCheckVersion from '@/uni_modules/uni-upgrade-center-app/utils/call-check-version';
  7. import interceptorChooseImage from '@/uni_modules/json-interceptor-chooseImage/js_sdk/main.js';
  8. // #endif
  9. // const db = uniCloud.database()
  10. export default async function() {
  11. let loginConfig = uniStarterConfig.router.login;
  12. const debug = uniStarterConfig.debug;
  13. //清除有配置但设备环境不支持的登录项
  14. // #ifdef APP-PLUS
  15. await new Promise((callBack) => {
  16. plus.oauth.getServices(oauthServices => {
  17. loginConfig = loginConfig.filter(item => {
  18. if (["univerify", "weixin", "apple"].includes(item)) {
  19. let index = oauthServices.findIndex(e => e.id == item)
  20. if (index == -1) {
  21. return false
  22. } else {
  23. return oauthServices[index].nativeClient
  24. }
  25. } else {
  26. return true
  27. }
  28. })
  29. if (loginConfig.includes('univerify')) { //一键登录 功能预登录
  30. uni.preLogin({
  31. provider: 'univerify',
  32. complete: e => {
  33. console.log(e);
  34. }
  35. })
  36. }
  37. callBack()
  38. }, err => {
  39. console.error('获取服务供应商失败:' + JSON.stringify(err));
  40. })
  41. })
  42. // #endif
  43. //非app移除:一键登录、苹果登录;h5移除微信登录,如果你做微信公众号登录需要将此行移除
  44. // #ifndef APP-PLUS
  45. loginConfig = loginConfig.filter(item => {
  46. return ![
  47. 'univerify',
  48. 'apple',
  49. // #ifdef H5
  50. 'weixin'
  51. // #endif
  52. ].includes(item)
  53. })
  54. // #endif
  55. uniStarterConfig.router.login = loginConfig
  56. // uniStarterConfig挂载到getApp().globalData.config
  57. setTimeout(() => {
  58. getApp({
  59. allowDefault: true
  60. }).globalData.config = uniStarterConfig;
  61. }, 1)
  62. // 初始化appVersion(仅app生效)
  63. initAppVersion();
  64. // #ifdef APP-PLUS
  65. // 实现,路由拦截。当应用无访问摄像头/相册权限,引导跳到设置界面
  66. interceptorChooseImage()
  67. // #endif
  68. //clientDB的错误提示
  69. function onDBError({
  70. code, // 错误码详见https://uniapp.dcloud.net.cn/uniCloud/clientdb?id=returnvalue
  71. message
  72. }) {
  73. console.log('onDBError', {
  74. code,
  75. message
  76. });
  77. // 处理错误
  78. console.error(code, message);
  79. if ([
  80. 'TOKEN_INVALID_INVALID_CLIENTID',
  81. 'TOKEN_INVALID',
  82. 'TOKEN_INVALID_TOKEN_EXPIRED',
  83. 'TOKEN_INVALID_WRONG_TOKEN',
  84. 'TOKEN_INVALID_ANONYMOUS_USER'
  85. ].includes(code)) {
  86. uni.navigateTo({
  87. url: '/subpages/ucenter/login-page/index/index'
  88. })
  89. }
  90. }
  91. // 绑定clientDB错误事件
  92. // db.on('error', onDBError)
  93. // 解绑clientDB错误事件
  94. //db.off('error', onDBError)
  95. // db.on('refreshToken', function({
  96. // token,
  97. // tokenExpired
  98. // }) {
  99. // console.log('监听到clientDB的refreshToken', {
  100. // token,
  101. // tokenExpired
  102. // });
  103. // store.commit('user/login', {
  104. // token,
  105. // tokenExpired
  106. // })
  107. // })
  108. uni.addInterceptor('setStorage', {
  109. invoke(args) {
  110. if (args.data && args.key == 'uni_id_token') {
  111. let oldToken = uni.getStorageSync('uni_id_token')
  112. if (oldToken.length) {
  113. console.log('监听到token更新,就刷新push_clientid的有效期');
  114. // #ifdef APP-PLUS
  115. let push_clientid;
  116. try {
  117. push_clientid = plus.push.getClientInfo().clientid
  118. } catch (e) {
  119. uni.showModal({
  120. content: '获取推送标识失败。如果你的应用不需要推送功能,请注释掉本代码块',
  121. showCancel: false,
  122. confirmText: "好的"
  123. });
  124. console.log(e)
  125. }
  126. uniCloud.callFunction({
  127. name: 'uni-id-cf',
  128. data: {
  129. "action": "renewDeviceTokenExpiredxpired",
  130. "params": {
  131. push_clientid
  132. }
  133. },
  134. complete: (e) => {
  135. console.log(e);
  136. }
  137. })
  138. // #endif
  139. }
  140. }
  141. // console.log('interceptor-complete', args)
  142. },
  143. complete(e) {
  144. // console.log(e);
  145. }
  146. })
  147. //拦截器封装callFunction
  148. // let callFunctionOption;
  149. // uniCloud.addInterceptor('callFunction', {
  150. // async invoke(option) {
  151. // // 判断如果是执行登录(无论是哪种登录方式),就记录用户的相关设备id
  152. // // 注意:注册可能不仅仅走register接口,还有登录并注册的接口
  153. // if (option.name == 'uni-id-cf' &&
  154. // (option.data.action == 'register' || option.data.action.slice(0, 5) == 'login')
  155. // ) {
  156. // option.data.deviceInfo = await getDeviceInfo()
  157. // console.log("重新登录/注册,获取设备id", option.data.deviceInfo);
  158. // option.data.inviteCode = await new Promise((callBack) => {
  159. // uni.getClipboardData({
  160. // success: function(res) {
  161. // if (res.data.slice(0, 18) == 'uniInvitationCode:') {
  162. // let uniInvitationCode = res.data.slice(18, 38)
  163. // console.log('当前用户是其他用户推荐下载的,推荐者的code是:' +
  164. // uniInvitationCode);
  165. // // uni.showModal({
  166. // // content: '当前用户是其他用户推荐下载的,推荐者的code是:'+uniInvitationCode,
  167. // // showCancel: false
  168. // // });
  169. // callBack(uniInvitationCode)
  170. // //当前用户是其他用户推荐下载的。这里登记他的推荐者id 为当前用户的myInviteCode。判断如果是注册
  171. // } else {
  172. // callBack(false)
  173. // }
  174. // },
  175. // fail() {
  176. // callBack(false)
  177. // },
  178. // complete(){
  179. // // #ifdef MP-WEIXIN
  180. // uni.hideToast()
  181. // // #endif
  182. // }
  183. // });
  184. // })
  185. // }
  186. // // console.log(JSON.stringify(option));
  187. // callFunctionOption = option
  188. // },
  189. // complete(e) {
  190. // // console.log(JSON.stringify(e));
  191. // },
  192. // fail(e) { // 失败回调拦截
  193. // console.error('网络请求错误码:',JSON.stringify(e));
  194. // if (debug) {
  195. // uni.showModal({
  196. // content: JSON.stringify(e),
  197. // showCancel: false
  198. // });
  199. // console.error(e);
  200. // } else {
  201. // uni.showModal({
  202. // content: "系统错误请稍后再试!",
  203. // showCancel: false,
  204. // confirmText: "知道了"
  205. // });
  206. // }
  207. // //如果执行错误,检查是否断网
  208. // uni.getNetworkType({
  209. // complete: res => {
  210. // // console.log(res);
  211. // if (res.networkType == 'none') {
  212. // uni.showToast({
  213. // title: '手机网络异常',
  214. // icon: 'none'
  215. // });
  216. // console.log('手机网络异常');
  217. // let callBack = res => {
  218. // console.log(res);
  219. // if (res.isConnected) {
  220. // uni.showToast({
  221. // title: '恢复联网自动重新执行',
  222. // icon: 'none'
  223. // });
  224. // console.log(res.networkType, "恢复联网自动重新执行");
  225. // uni.offNetworkStatusChange(e => {
  226. // console.log("移除监听成功", e);
  227. // })
  228. // //恢复联网自动重新执行
  229. // uniCloud.callFunction(callFunctionOption)
  230. // uni.offNetworkStatusChange(callBack);
  231. // }
  232. // }
  233. // uni.onNetworkStatusChange(callBack);
  234. // }
  235. // }
  236. // });
  237. // },
  238. // success: (e) => {
  239. // const {
  240. // token,
  241. // tokenExpired
  242. // } = e.result
  243. // if (token && tokenExpired) {
  244. // store.commit('user/login', {
  245. // token,
  246. // tokenExpired
  247. // })
  248. // }
  249. // switch (e.result.code) {
  250. // case 403:
  251. // uni.navigateTo({
  252. // url: "/pages/ucenter/login-page/index/index"
  253. // })
  254. // break;
  255. // case 30203:
  256. // uni.navigateTo({
  257. // url: "/pages/ucenter/login-page/index/index"
  258. // })
  259. // break;
  260. // case 50101:
  261. // uni.showToast({
  262. // title: e.result.msg,
  263. // icon: 'none',
  264. // duration: 2000
  265. // });
  266. // break;
  267. // default:
  268. // console.log('code的值是:' + e.result.code, '可以在上面添加case,自动处理响应体');
  269. // break;
  270. // }
  271. // switch (e.result.errCode) {
  272. // case 'uni-id-token-not-exist':
  273. // uni.showToast({
  274. // title: '登录信息失效',
  275. // icon: 'none'
  276. // });
  277. // uni.navigateTo({
  278. // url: "/pages/ucenter/login-page/index/index"
  279. // })
  280. // break;
  281. // default:
  282. // break;
  283. // }
  284. // }
  285. // })
  286. //自定义路由拦截
  287. // const {
  288. // "router": {
  289. // needLogin,
  290. // visitor,
  291. // login
  292. // }
  293. // } = uniStarterConfig //需要登录的页面
  294. // let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
  295. // list.forEach(item => { //用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
  296. // uni.addInterceptor(item, {
  297. // invoke(e) { // 调用前拦截
  298. // //获取用户的token
  299. // const token = uni.getStorageSync('uni_id_token'),
  300. // //token是否已失效
  301. // tokenExpired = uni.getStorageSync('uni_id_token_expired') < Date.now(),
  302. // //获取要跳转的页面路径(url去掉"?"和"?"后的参数)
  303. // url = e.url.split('?')[0];
  304. // //获取要前往的页面路径(即url去掉"?"和"?"后的参数)
  305. // const pages = getCurrentPages();
  306. // if (!pages.length) {
  307. // console.log("首页启动调用了");
  308. // return e
  309. // }
  310. // const fromUrl = pages[pages.length - 1].route;
  311. // let inLoginPage = fromUrl.split('/')[2] == 'login-page'
  312. // //控制登录优先级
  313. // if ( //判断当前窗口是否为登录页面,如果是则不重定向路由
  314. // url == '/pages/ucenter/login-page/index/index' &&
  315. // !inLoginPage
  316. // ) {
  317. // //一键登录(univerify)、账号(username)、验证码登录(短信smsCode)
  318. // if (login[0] == 'username') {
  319. // e.url = "/pages/ucenter/login-page/pwd-login/pwd-login"
  320. // } else {
  321. // if (e.url == url) {
  322. // e.url += '?'
  323. // } //添加参数之前判断是否带了`?`号如果没有就补上,因为当开发场景本身有参数的情况下是已经带了`?`号
  324. // e.url += "type=" + login[0]
  325. // }
  326. // } else {
  327. // //拦截强制登录页面
  328. // let pass = true
  329. // //pattern
  330. // if (needLogin) {
  331. // pass = needLogin.every((item) => {
  332. // if (typeof(item) == 'object' && item.pattern) {
  333. // return !item.pattern.test(url)
  334. // }
  335. // return url != item
  336. // })
  337. // // console.log({pass})
  338. // }
  339. // if (visitor) {
  340. // pass = visitor.some((item) => {
  341. // if (typeof(item) == 'object' && item.pattern) {
  342. // return item.pattern.test(url)
  343. // }
  344. // return url == item
  345. // })
  346. // // console.log({pass})
  347. // }
  348. // if (!pass && (token == '' || tokenExpired)) {
  349. // uni.showToast({
  350. // title: '请先登录',
  351. // icon: 'none'
  352. // })
  353. // uni.navigateTo({
  354. // url: "/pages/ucenter/login-page/index/index"
  355. // })
  356. // return false
  357. // }
  358. // }
  359. // return e
  360. // },
  361. // fail(err) { // 失败回调拦截
  362. // console.log(err);
  363. // if (debug) {
  364. // console.log(err);
  365. // uni.showModal({
  366. // content: JSON.stringify(err),
  367. // showCancel: false
  368. // });
  369. // }
  370. // }
  371. // })
  372. // })
  373. // #ifdef APP-PLUS
  374. // 监听并提示设备网络状态变化
  375. uni.onNetworkStatusChange(res => {
  376. console.log(res.isConnected);
  377. console.log(res.networkType);
  378. if (res.networkType != 'none') {
  379. uni.showToast({
  380. title: '当前网络类型:' + res.networkType,
  381. icon: 'none',
  382. duration: 3000
  383. })
  384. } else {
  385. uni.showToast({
  386. title: '网络类型:' + res.networkType,
  387. icon: 'none',
  388. duration: 3000
  389. })
  390. }
  391. });
  392. // #endif
  393. }
  394. /**
  395. * // 初始化appVersion
  396. */
  397. function initAppVersion() {
  398. // #ifdef APP-PLUS
  399. let appid = plus.runtime.appid;
  400. plus.runtime.getProperty(appid, (wgtInfo) => {
  401. let appVersion = plus.runtime;
  402. let currentVersion = appVersion.versionCode > wgtInfo.versionCode ? appVersion : wgtInfo;
  403. getApp({
  404. allowDefault: true
  405. }).appVersion = {
  406. ...currentVersion,
  407. appid,
  408. hasNew: false
  409. }
  410. // 检查更新小红点
  411. callCheckVersion().then(res => {
  412. // console.log('检查是否有可以更新的版本', res);
  413. if (res.result.code > 0) {
  414. // 有新版本
  415. getApp({
  416. allowDefault: true
  417. }).appVersion.hasNew = true;
  418. }
  419. })
  420. });
  421. // 检查更新
  422. // #endif
  423. }
  424. async function getDeviceInfo() {
  425. let deviceInfo = {
  426. "uuid": '',
  427. "vendor": '',
  428. "push_clientid": '',
  429. "imei": '',
  430. "oaid": '',
  431. "idfa": '',
  432. "model": '',
  433. "platform": '',
  434. }
  435. const {
  436. model,
  437. platform,
  438. } = uni.getSystemInfoSync();
  439. Object.assign(deviceInfo, {
  440. model,
  441. platform
  442. });
  443. // #ifdef APP-PLUS
  444. const oaid = await new Promise((callBack, fail) => {
  445. if (deviceInfo.platform == "android") {
  446. plus.device.getOAID({
  447. success: function(e) {
  448. callBack(e.oaid)
  449. // console.log('getOAID success: '+JSON.stringify(e));
  450. },
  451. fail: function(e) {
  452. callBack()
  453. console.log('getOAID failed: ' + JSON.stringify(e));
  454. }
  455. });
  456. } else {
  457. callBack()
  458. }
  459. }),
  460. {
  461. imei,
  462. uuid
  463. } = await new Promise((callBack, fail) => {
  464. plus.device.getInfo({
  465. success: function(e) {
  466. callBack(e)
  467. // console.log('getOAID success: '+JSON.stringify(e));
  468. },
  469. fail: function(e) {
  470. callBack()
  471. console.log('getOAID failed: ' + JSON.stringify(e));
  472. }
  473. });
  474. }),
  475. idfa = plus.storage.getItem('idfa') || '', //idfa有需要的用户在应用首次启动时自己获取存储到storage中
  476. vendor = plus.device.vendor;
  477. try {
  478. deviceInfo.push_clientid = plus.push.getClientInfo().clientid
  479. } catch (e) {
  480. uni.showModal({
  481. content: '获取推送标识失败。如果你的应用不需要推送功能,请注释掉本代码块',
  482. showCancel: false,
  483. confirmText: "好的"
  484. });
  485. console.log(e)
  486. }
  487. Object.assign(deviceInfo, {
  488. imei,
  489. uuid,
  490. idfa,
  491. vendor
  492. });
  493. // #endif
  494. return deviceInfo
  495. }