import { Injectable } from '@angular/core'; import { Platform } from 'ionic-angular'; import { AppVersion } from '@ionic-native/app-version'; import { Device } from '@ionic-native/device'; import { utils } from '../utils' import { Store } from './store' import { Log } from "../utils/log"; const log = new Log('Env'); @Injectable() export class Env { is: any version: any ip clientId isInApp // 是否启动并处于应用内环境 readyResolve ipApi baseApi testVersion = '2.2.0' config constructor( public store:Store, public device:Device, public appVersion:AppVersion, public platform: Platform ) { const isIos = platform.is('ios'); const isAndroid = platform.is('android'); const isWindows = platform.is('windows'); const isMobile = platform.is('mobile'); const isDesktop = platform.is('core'); const OSVersion = platform.version().num; this.is = { ios: isIos, android: isAndroid, windows: isWindows, mobile: isMobile, desktop: isDesktop, oldOS: (isAndroid && OSVersion < 5.2) || (isIos && OSVersion < 6) || (isWindows && OSVersion < 8) } this.version= { OS: OSVersion } } setConfig = (config) => { this.config = config || {}; } // 初始化app版本号和设备id init = (baseApi,ipApi) => { this.baseApi = baseApi; this.ipApi = ipApi; this.setInApp(true); // 设置isInApp为true return this.getClientId().then((id)=>{ log.info('client Id',id,true); this.clientId = id; return this.getAppVersion(); }).then((version)=>{ log.info('version', version, true); this.version.app = version; return this.setIp(); }).then((ip)=>{ if(this.readyResolve) this.readyResolve(); return ip; }); } // 标题添加环境标识 getEnvTitle = (title) => { const envNames = { dev: '(开发)', test:'(测试)', uat: '(内测)', testin:'', prod:'', deploy:'' }; return title + envNames[this.config.env]; } setInApp = (isInApp) => { this.isInApp = isInApp; } // 环境初始化 ready = () => { return new Promise((resolve)=>{ this.readyResolve = resolve; }); } // 获取ip getIp = () => { if(this.ip){ return new Promise((resolve)=>{ resolve(this.ip); }); }else{ return this.setIp(); } } // 设置ip setIp = () => { return this.baseApi.fetch(this.ipApi).then((res)=>{ this.ip = res ? res.ip : '';// 获取环境ip log.info('ip',this.ip); return this.ip; }); } // 异步获取version getAppVersion = () => { if(this.platform.is('cordova')){ try{ return this.appVersion.getVersionNumber().then((version)=>{ return version || ''; }); }catch(err){ log.info('getAppVersion err',err,true); return new Promise((resolve)=>{ resolve('2.0.0'); }); } }else{ return new Promise((resolve)=>{ resolve(this.config.isDev ? this.testVersion : ''); }); } } // 获取客户端id getClientId = () => { if(this.device.uuid){ return new Promise((resolve)=>{ resolve(this.device.uuid); }) }else{ return this.store.get('clientId',true).then((clientId)=>{ if(!clientId) { clientId = utils.uuid(); return this.store.set('clientId',clientId,true).then(()=>{ return clientId; }); }else{ return clientId; } }); } } }