appInit.js 13.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
import uniStarterConfig from '@/uni-starter.config.js';
import store from '@/store'
//应用初始化页
// #ifdef APP-PLUS
import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update';
import callCheckVersion from '@/uni_modules/uni-upgrade-center-app/utils/call-check-version';
import interceptorChooseImage from '@/uni_modules/json-interceptor-chooseImage/js_sdk/main.js';
// #endif
const db = uniCloud.database()
export default async function() {
11 12
	let loginConfig = uniStarterConfig.router.login;
	const debug = uniStarterConfig.debug;
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
	//清除有配置但设备环境不支持的登录项
	// #ifdef APP-PLUS
	await new Promise((callBack) => {
		plus.oauth.getServices(oauthServices => {
			loginConfig = loginConfig.filter(item => {
				if (["univerify", "weixin", "apple"].includes(item)) {
					let index = oauthServices.findIndex(e => e.id == item)
					if (index == -1) {
						return false
					} else {
						return oauthServices[index].nativeClient
					}
				} else {
					return true
				}
			})
			if (loginConfig.includes('univerify')) { //一键登录 功能预登录
				uni.preLogin({
					provider: 'univerify',
					complete: e => {
						console.log(e);
					}
				})
			}
			callBack()
		}, err => {
			console.error('获取服务供应商失败:' + JSON.stringify(err));
		})
	})
	// #endif

	//非app移除:一键登录、苹果登录;h5移除微信登录,如果你做微信公众号登录需要将此行移除
	// #ifndef APP-PLUS
	loginConfig = loginConfig.filter(item => {
		return ![
			'univerify',
			'apple',
			// #ifdef H5
			'weixin'
			// #endif
		].includes(item)
	})
	// #endif

	uniStarterConfig.router.login = loginConfig

	// uniStarterConfig挂载到getApp().globalData.config
	setTimeout(() => {
		getApp({
			allowDefault: true
		}).globalData.config = uniStarterConfig;
	}, 1)


	// 初始化appVersion(仅app生效)
	initAppVersion();

	// #ifdef APP-PLUS
	// 实现,路由拦截。当应用无访问摄像头/相册权限,引导跳到设置界面
	interceptorChooseImage()
	// #endif


	//clientDB的错误提示
	function onDBError({
		code, // 错误码详见https://uniapp.dcloud.net.cn/uniCloud/clientdb?id=returnvalue
		message
	}) {
		console.log('onDBError', {
			code,
			message
		});
		// 处理错误
		console.error(code, message);
		if ([
				'TOKEN_INVALID_INVALID_CLIENTID',
				'TOKEN_INVALID',
				'TOKEN_INVALID_TOKEN_EXPIRED',
				'TOKEN_INVALID_WRONG_TOKEN',
92
				'TOKEN_INVALID_ANONYMOUS_USER'
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
			].includes(code)) {
			uni.navigateTo({
				url: '/pages/ucenter/login-page/index/index'
			})
		}
	}
	// 绑定clientDB错误事件
	db.on('error', onDBError)

	// 解绑clientDB错误事件
	//db.off('error', onDBError)
	db.on('refreshToken', function({
		token,
		tokenExpired
	}) {
		console.log('监听到clientDB的refreshToken', {
			token,
			tokenExpired
		});
		store.commit('user/login', {
			token,
			tokenExpired
		})
	})
117 118 119 120 121 122
	
	uni.addInterceptor('setStorage', {
		invoke(args) {
			if (args.data && args.key == 'uni_id_token') {
				let oldToken = uni.getStorageSync('uni_id_token')
				if(oldToken.length){
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
					console.log('监听到token更新,就刷新push_clientid的有效期');
					// #ifdef APP-PLUS
					let push_clientid;
					try {
						push_clientid = plus.push.getClientInfo().clientid
					} catch (e) {
						uni.showModal({
							content: '获取推送标识失败。如果你的应用不需要推送功能,请注释掉本代码块',
							showCancel: false,
							confirmText: "好的"
						});
						console.log(e)
					}
					uniCloud.callFunction({
						name:'uni-id-cf',
						data:{
							"action": "renewDeviceTokenExpiredxpired",
							"params": {push_clientid}
						},
						complete: (e) => {
							console.log(e);
						}
					})
146
					// #endif
147 148 149 150 151 152 153 154
				}
			}
			// console.log('interceptor-complete', args)
		},
		complete(e) {
			// console.log(e);
		}
	})
155 156 157 158 159 160

	//拦截器封装callFunction
	let callFunctionOption;
	uniCloud.addInterceptor('callFunction', {
		async invoke(option) {
			// 判断如果是执行登录(无论是哪种登录方式),就记录用户的相关设备id
161
			// 注意:注册可能不仅仅走register接口,还有登录并注册的接口
162 163 164
			if (option.name == 'uni-id-cf' &&
				(option.data.action == 'register' || option.data.action.slice(0, 5) == 'login')
			) {
165 166
				option.data.deviceInfo = await getDeviceInfo()
				console.log("重新登录/注册,获取设备id", option.data.deviceInfo);
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
				option.data.inviteCode = await new Promise((callBack) => {
					uni.getClipboardData({
						success: function(res) {
							if (res.data.slice(0, 18) == 'uniInvitationCode:') {
								let uniInvitationCode = res.data.slice(18, 38)
								console.log('当前用户是其他用户推荐下载的,推荐者的code是:' +
									uniInvitationCode);
								// uni.showModal({
								// 	content: '当前用户是其他用户推荐下载的,推荐者的code是:'+uniInvitationCode,
								// 	showCancel: false
								// });
								callBack(uniInvitationCode)
								//当前用户是其他用户推荐下载的。这里登记他的推荐者id 为当前用户的myInviteCode。判断如果是注册
							} else {
								callBack(false)
							}
						},
						fail() {
							callBack(false)
186 187 188 189 190
						},
						complete(){
							// #ifdef MP-WEIXIN
							uni.hideToast()
							// #endif
191 192 193 194 195 196 197 198 199 200
						}
					});
				})
			}
			// console.log(JSON.stringify(option));
			callFunctionOption = option
		},
		complete(e) {
			// console.log(JSON.stringify(e));
		},
201
		fail(e) { // 失败回调拦截
study夏羽's avatar
update  
study夏羽 已提交
202
			console.error('网络请求错误码:',JSON.stringify(e));
203
			if (debug) {
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
				uni.showModal({
					content: JSON.stringify(e),
					showCancel: false
				});
				console.error(e);
			} else {
				uni.showModal({
					content: "系统错误请稍后再试!",
					showCancel: false,
					confirmText: "知道了"
				});
			}
			//如果执行错误,检查是否断网
			uni.getNetworkType({
				complete: res => {
					// console.log(res);
					if (res.networkType == 'none') {
						uni.showToast({
							title: '手机网络异常',
							icon: 'none'
						});
						console.log('手机网络异常');
						let callBack = res => {
							console.log(res);
							if (res.isConnected) {
								uni.showToast({
									title: '恢复联网自动重新执行',
									icon: 'none'
								});
								console.log(res.networkType, "恢复联网自动重新执行");
								uni.offNetworkStatusChange(e => {
									console.log("移除监听成功", e);
								})
								//恢复联网自动重新执行
								uniCloud.callFunction(callFunctionOption)
								uni.offNetworkStatusChange(callBack);
							}
						}
						uni.onNetworkStatusChange(callBack);
					}
				}
			});
		},
		success: (e) => {
			const {
				token,
				tokenExpired
			} = e.result
			if (token && tokenExpired) {
				store.commit('user/login', {
					token,
					tokenExpired
				})
			}
			switch (e.result.code) {
				case 403:
					uni.navigateTo({
						url: "/pages/ucenter/login-page/index/index"
					})
					break;
				case 30203:
					uni.navigateTo({
						url: "/pages/ucenter/login-page/index/index"
					})
					break;
				case 50101:
					uni.showToast({
						title: e.result.msg,
						icon: 'none',
						duration: 2000
					});
					break;
				default:
					console.log('code的值是:' + e.result.code, '可以在上面添加case,自动处理响应体');
					break;
			}

			switch (e.result.errCode) {
				case 'uni-id-token-not-exist':
					uni.showToast({
						title: '登录信息失效',
						icon: 'none'
					});
					uni.navigateTo({
						url: "/pages/ucenter/login-page/index/index"
					})
					break;
				default:
					break;
			}
		}
	})

	//自定义路由拦截
	const {
		"router": {
			needLogin,
			visitor,
			login
		}
	} = uniStarterConfig //需要登录的页面

	let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
	list.forEach(item => { //用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
		uni.addInterceptor(item, {
			invoke(e) { // 调用前拦截
				//获取用户的token
				const token = uni.getStorageSync('uni_id_token'),
					//token是否已失效
					tokenExpired = uni.getStorageSync('uni_id_token_expired') < Date.now(),
					//获取要跳转的页面路径(url去掉"?"和"?"后的参数)
					url = e.url.split('?')[0];
				//获取要前往的页面路径(即url去掉"?"和"?"后的参数)
				const pages = getCurrentPages();
				if (!pages.length) {
					console.log("首页启动调用了");
					return e
				}
				const fromUrl = pages[pages.length - 1].route;

				let inLoginPage = fromUrl.split('/')[2] == 'login-page'

				//控制登录优先级
				if ( //判断当前窗口是否为登录页面,如果是则不重定向路由
					url == '/pages/ucenter/login-page/index/index' &&
					!inLoginPage
				) {
					//一键登录(univerify)、账号(username)、验证码登录(短信smsCode)
					if (login[0] == 'username') {
						e.url = "/pages/ucenter/login-page/pwd-login/pwd-login"
					} else {
						if (e.url == url) {
							e.url += '?'
						} //添加参数之前判断是否带了`?`号如果没有就补上,因为当开发场景本身有参数的情况下是已经带了`?`号
						e.url += "type=" + login[0]
					}
				} else {
					//拦截强制登录页面
					let pass = true
					//pattern
					if (needLogin) {
						pass = needLogin.every((item) => {
							if (typeof(item) == 'object' && item.pattern) {
								return !item.pattern.test(url)
							}
							return url != item
						})
						// console.log({pass})
					}
					if (visitor) {
						pass = visitor.some((item) => {
							if (typeof(item) == 'object' && item.pattern) {
								return item.pattern.test(url)
							}
							return url == item
						})
						// console.log({pass})
					}

					if (!pass && (token == '' || tokenExpired)) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						uni.navigateTo({
							url: "/pages/ucenter/login-page/index/index"
						})
						return false
					}
				}
				return e
			},
			fail(err) { // 失败回调拦截 
				console.log(err);
study夏羽's avatar
update  
study夏羽 已提交
378
				if (debug) {
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
					console.log(err);
					uni.showModal({
						content: JSON.stringify(err),
						showCancel: false
					});
				}
			}
		})
	})

	// #ifdef APP-PLUS
	// 监听并提示设备网络状态变化
	uni.onNetworkStatusChange(res => {
		console.log(res.isConnected);
		console.log(res.networkType);
		if (res.networkType != 'none') {
			uni.showToast({
				title: '当前网络类型:' + res.networkType,
				icon: 'none',
				duration: 3000
			})
		} else {
			uni.showToast({
				title: '网络类型:' + res.networkType,
				icon: 'none',
				duration: 3000
			})
		}
	});
	// #endif

}
/**
 * // 初始化appVersion
 */
function initAppVersion() {
	// #ifdef APP-PLUS
	let appid = plus.runtime.appid;
	plus.runtime.getProperty(appid, (wgtInfo) => {
		let appVersion = plus.runtime;
		let currentVersion = appVersion.versionCode > wgtInfo.versionCode ? appVersion : wgtInfo;
		getApp({
			allowDefault: true
		}).appVersion = {
			...currentVersion,
			appid,
			hasNew: false
		}
		// 检查更新小红点
		callCheckVersion().then(res => {
			// console.log('检查是否有可以更新的版本', res);
			if (res.result.code > 0) {
				// 有新版本
				getApp({
					allowDefault: true
				}).appVersion.hasNew = true;
			}
		})
	});
	// 检查更新
	// #endif
}
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496

async function getDeviceInfo() {
	let deviceInfo = {
		"uuid": '',
		"vendor": '',
		"push_clientid": '',
		"imei": '',
		"oaid": '',
		"idfa": '',
		"model": '',
		"platform": '',
	}
	const {
		model,
		platform,
	} = uni.getSystemInfoSync();
	Object.assign(deviceInfo, {
		model,
		platform
	});

	// #ifdef APP-PLUS
	const oaid = await new Promise((callBack, fail) => {
			if (deviceInfo.platform == "android") {
				plus.device.getOAID({
					success: function(e) {
						callBack(e.oaid)
						// console.log('getOAID success: '+JSON.stringify(e));
					},
					fail: function(e) {
						callBack()
						console.log('getOAID failed: ' + JSON.stringify(e));
					}
				});
			} else {
				callBack()
			}
		}),
		{
			imei,
			uuid
		} = await new Promise((callBack, fail) => {
			plus.device.getInfo({
				success: function(e) {
					callBack(e)
					// console.log('getOAID success: '+JSON.stringify(e));
				},
				fail: function(e) {
					callBack()
					console.log('getOAID failed: ' + JSON.stringify(e));
				}
			});
		}),
		idfa = plus.storage.getItem('idfa') || '', //idfa有需要的用户在应用首次启动时自己获取存储到storage中
		vendor = plus.device.vendor;
	try {
497
		deviceInfo.push_clientid = plus.push.getClientInfo().clientid
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
	} catch (e) {
		uni.showModal({
			content: '获取推送标识失败。如果你的应用不需要推送功能,请注释掉本代码块',
			showCancel: false,
			confirmText: "好的"
		});
		console.log(e)
	}
	Object.assign(deviceInfo, {
		imei,
		uuid,
		idfa,
		vendor
	});
	// #endif
	return deviceInfo
}