This commit is contained in:
Vasil Trifonov 2018-09-28 18:08:43 +03:00
Родитель 48c81b3d50 984a978635
Коммит 7df4c34a48
7 изменённых файлов: 791 добавлений и 696 удалений

1262
package-lock.json сгенерированный

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,34 +1,36 @@
{
"name": "nativescript-preview-sdk",
"version": "0.2.8",
"description": "Handles the communication to the NativeScript Preview Apps",
"main": "src/nativescript-preview-sdk",
"typings": "src/nativescript-preview-sdk.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/telerik/nativescript-preview-sdk.git"
},
"keywords": [
"nativescript",
"preview",
"sdk",
"play",
"playground"
],
"author": "NativeScript Team",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/telerik/nativescript-preview-sdk/issues"
},
"homepage": "https://github.com/telerik/nativescript-preview-sdk#readme",
"dependencies": {
"@types/pubnub": "4.0.2",
"@types/shortid": "0.0.29",
"btoa": "1.2.1",
"pubnub": "4.21.2",
"shortid": "2.2.12"
},
"devDependencies": {
"typescript": "^3.0.3"
}
"name": "nativescript-preview-sdk",
"version": "0.2.12",
"description": "Handles the communication to the NativeScript Preview Apps",
"main": "src/nativescript-preview-sdk",
"typings": "src/nativescript-preview-sdk.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/telerik/nativescript-preview-sdk.git"
},
"keywords": [
"nativescript",
"preview",
"sdk",
"play",
"playground"
],
"author": "NativeScript Team",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/telerik/nativescript-preview-sdk/issues"
},
"homepage": "https://github.com/telerik/nativescript-preview-sdk#readme",
"dependencies": {
"@types/axios": "0.14.0",
"@types/pubnub": "4.0.2",
"@types/shortid": "0.0.29",
"axios": "0.18.0",
"btoa": "1.2.1",
"pubnub": "4.21.2",
"shortid": "2.2.12"
},
"devDependencies": {
"typescript": "3.0.3"
}
}

Просмотреть файл

@ -1,8 +1,6 @@
export class Constants {
public static PreviewAppStoreId = "1264484702";
public static PreviewGooglePlayId = "org.nativescript.preview";
public static PreviewGooglePlayId = "org.nativescript.preview";
public static PlaygroundAppStoreLink = "https://itunes.apple.com/us/app/nativescript-playground/id1263543946?mt=8&ls=1";
public static PlaygroundGooglePlayLink = "https://play.google.com/store/apps/details?id=org.nativescript.play";
public static MsvAndroid = 26;
public static МsviOS = 16;
}

Просмотреть файл

@ -6,6 +6,14 @@ import { Device } from "./device";
export class Config {
pubnubPublishKey: string;
pubnubSubscribeKey: string;
/**
* Can be playground or cli
*/
msvKey: string;
/**
* Can be staging, uat or live
*/
msvEnv: string;
callbacks: SdkCallbacks;
getInitialFiles: (device?: Device) => Promise<FilesPayload>;
instanceId?: string;

Просмотреть файл

@ -1,35 +1,32 @@
const data = {
exports.fallbackPreviewVersions = {
"staging": {
"playground": {
"android": 30,
"ios": 19
"android": 31,
"ios": 20
},
"cli": {
"android": 30,
"ios": 19
"android": 31,
"ios": 20
}
},
"uat": {
"playground": {
"android": 30,
"ios": 19
"android": 31,
"ios": 20
},
"cli": {
"android": 30,
"ios": 19
"android": 31,
"ios": 20
}
},
"live": {
"playground": {
"android": 27,
"ios": 19
"android": 31,
"ios": 20
},
"cli": {
"android": 27,
"ios": 19
"android": 31,
"ios": 20
}
}
};
export {
data
};

Просмотреть файл

@ -12,6 +12,7 @@ import { FilesPayload } from "../models/files-payload";
import * as PubNub from "pubnub";
import { SdkCallbacks } from "../models/sdk-callbacks";
import { SendFilesStatus } from "../models/send-files-status";
import { PreviewAppVersionsService } from "./preview-app-versions-service";
export class MessagingService {
private static PubNubInitialized = false;
@ -19,18 +20,21 @@ export class MessagingService {
private pubNub: PubNub;
private pubNubListenerParams: PubNub.ListenerParameters;
private pubNubSubscribeParams: PubNub.SubscribeParameters;
private connectedDevicesTimeouts: {[id: string]: number};
private connectedDevicesTimeouts: { [id: string]: number };
private config: Config;
private helpersService: HelpersService;
private devicesService: DevicesService;
private previewAppVersionsService: PreviewAppVersionsService;
private minSupportedVersions: { android: number, ios: number };
constructor() {
this.helpersService = new HelpersService();
this.devicesService = new DevicesService(this.helpersService);
this.previewAppVersionsService = new PreviewAppVersionsService();
this.connectedDevicesTimeouts = {};
}
public initialize(config: Config): string {
public async initialize(config: Config): Promise<string> {
this.config = config;
this.ensureValidConfig();
@ -38,6 +42,8 @@ export class MessagingService {
return;
}
this.minSupportedVersions = await this.previewAppVersionsService.getMinSupportedVersions(this.config.msvKey, this.config.msvEnv);
this.pubNub = new PubNub({
publishKey: this.config.pubnubPublishKey,
subscribeKey: this.config.pubnubSubscribeKey,
@ -120,7 +126,7 @@ export class MessagingService {
private ensureValidConfig() {
this.config.instanceId = this.config.instanceId || this.helpersService.shortId();
this.config.connectedDevices = this.config.connectedDevices || {};
this.config.getInitialFiles = this.config.getInitialFiles || (() => new Promise<FilesPayload>((resolve) => { resolve({ files: [], platform: ""}); }));
this.config.getInitialFiles = this.config.getInitialFiles || (() => new Promise<FilesPayload>((resolve) => { resolve({ files: [], platform: "" }); }));
this.config.callbacks = this.config.callbacks || <SdkCallbacks>{};
this.config.callbacks.onConnectedDevicesChange = this.config.callbacks.onConnectedDevicesChange || (() => { });
this.config.callbacks.onDeviceConnectedMessage = this.config.callbacks.onDeviceConnectedMessage || (() => { });
@ -142,6 +148,22 @@ export class MessagingService {
if (!this.config.callbacks.onBiggerFilesUpload) {
throw new Error("onBiggerFilesUpload callback is required when creating a messaging service.");
}
if (!this.config.msvKey) {
throw new Error(`msvKey is required when getting min supported versions of preview apps. Valid values are: ${this.previewAppVersionsService.validMsvEnvs.join(", ")}.`);
}
if (!this.config.msvEnv) {
throw new Error(`msvEnv is required when getting min supported versions of preview apps. Valid values are: ${this.previewAppVersionsService.validMsvEnvs.join(", ")}.`);
}
if (!this.previewAppVersionsService.validMsvKeys.find(msvKey => this.helpersService.areCaseInsensitiveEqual(msvKey, this.config.msvKey))) {
throw new Error(`Invalid msvKey ${this.config.msvKey}. Valid values are: ${this.previewAppVersionsService.validMsvEnvs.join(", ")}.`);
}
if (!this.previewAppVersionsService.validMsvEnvs.find(env => this.helpersService.areCaseInsensitiveEqual(env, this.config.msvEnv))) {
throw new Error(`Invalid msvEnv ${this.config.msvEnv}. Valid values are: ${this.previewAppVersionsService.validMsvEnvs.join(", ")}.`);
}
}
sendInitialFiles(instanceId: string, hmrMode?: number) {
@ -151,7 +173,7 @@ export class MessagingService {
getConnectedDevices(instanceId: string): Promise<Device[]> {
let devicesChannel = this.getDevicesChannel(instanceId);
return new Promise((resolve, reject) => {
let request = {
let request = {
channels: [devicesChannel],
includeUUIDs: true,
includeState: true
@ -213,7 +235,8 @@ export class MessagingService {
}
private sendFilesInChunks(channel: string, messageType: string, filesPayload: FilesPayload, deviceIdMeta?: string): Promise<SendFilesStatus> {
let chunks = this.getChunks(filesPayload.files);
let finalFilesPayload = this.getFinalFilesPayload(filesPayload);
let chunks = this.getChunks(finalFilesPayload);
this.config.callbacks.onSendingChange(true);
return new Promise((resolve, reject) => {
this.getPublishPromise(channel, messageType, chunks, deviceIdMeta, filesPayload.platform, filesPayload.hmrMode)
@ -228,6 +251,19 @@ export class MessagingService {
});
}
private getFinalFilesPayload(filesPayload: FilesPayload) {
let finalFiles = filesPayload.files;
var appPackageJson = finalFiles.find((filePayload) => filePayload.file === "package.json");
if (appPackageJson) {
const jsonContent = JSON.parse(appPackageJson.fileContents);
jsonContent.android = jsonContent.android || {};
jsonContent.android.forceLog = true;
appPackageJson.fileContents = JSON.stringify(jsonContent);
}
return finalFiles;
}
private getPublishPromise(channel: string, messageType: string, chunks: FileChunk[], deviceIdMeta: string, platform: string, hmrMode?: number): Promise<void> {
return new Promise((resolve, reject) => {
if (!chunks.length) {
@ -291,18 +327,18 @@ export class MessagingService {
let meta: any = {
msvi: Constants.МsviOS,
msva: Constants.MsvAndroid,
platform: targetPlatform,
platform: targetPlatform,
};
if (deviceIdMeta) {
meta = {
msvi: Number.MAX_SAFE_INTEGER,
msva: Number.MAX_SAFE_INTEGER,
di: deviceIdMeta,
di: deviceIdMeta,
}
}
if(hmrMode === 0 || hmrMode === 1) {
meta.hmrMode = hmrMode;
}
}
if(hmrMode === 0 || hmrMode === 1) {
meta.hmrMode = hmrMode;
}
return meta;
}
@ -342,7 +378,8 @@ export class MessagingService {
device = this.devicesService.get(deviceConnectedMessage);
let isAndroid = this.helpersService.areCaseInsensitiveEqual(device.platform, "android");
let minimumSupportedVersion = isAndroid ? Constants.MsvAndroid : Constants.МsviOS;
let minimumSupportedVersion = isAndroid ? this.minSupportedVersions.android : this.minSupportedVersions.ios;
if (!deviceConnectedMessage.version || !deviceConnectedMessage.platform || deviceConnectedMessage.version < minimumSupportedVersion) {
let deprecatedAppFiles = this.getDeprecatedAppContent();
this.sendFilesInChunks(this.getDevicesChannel(instanceId), "initial sync chunk", { files: deprecatedAppFiles, hmrMode }, data.publisher).then(() => { });
@ -354,23 +391,23 @@ export class MessagingService {
this.config.getInitialFiles(device)
.then((initialPayload) => {
if (initialPayload.files && initialPayload.files.length) {
if (initialPayload && initialPayload.files && initialPayload.files.length) {
if (!initialPayload.deviceId && device) {
initialPayload.deviceId = device.id;
}
initialPayload.hmrMode = hmrMode;
initialPayload.hmrMode = hmrMode;
this.sendFilesInChunks(this.getDevicesChannel(instanceId), "initial sync chunk", initialPayload);
}
});
}
private getConnectedDevicesDelayed(presenceEvent: any, delay: number, retryCount: number): void {
this.connectedDevicesTimeouts[presenceEvent.uuid] = setTimeout(() => {
if(!this.helpersService.isBrowserTabActive()) {
console.log("Page not visible, retrying in 2 seconds");
return this.getConnectedDevicesDelayed(presenceEvent, 2000, retryCount);
}
this.connectedDevicesTimeouts[presenceEvent.uuid] = setTimeout(() => {
if (!this.helpersService.isBrowserTabActive()) {
//Page not visible, retrying in 2 seconds
return this.getConnectedDevicesDelayed(presenceEvent, 2000, retryCount);
}
this.getConnectedDevices(this.config.instanceId).then(devices => {
let shouldRetry =

Просмотреть файл

@ -0,0 +1,43 @@
import * as axios from "axios";
import { fallbackPreviewVersions } from "../preview-app-versions";
export class PreviewAppVersionsService {
private static GET_VERSIONS_DATA_URL = "https://raw.githubusercontent.com/telerik/nativescript-preview-sdk/master/src/preview-app-versions.js";
public validMsvKeys = ["cli", "playground"];
public validMsvEnvs = ["staging", "uat", "live"];
public async getMinSupportedVersions(key: string, env: string): Promise<{ android: number, ios: number }> {
const response = await this.get();
const result = this.parseResponseSafe(response) || fallbackPreviewVersions;
return result[env][key];
}
private async get(): Promise<any> {
return new Promise(resolve => {
(<any>axios).get(PreviewAppVersionsService.GET_VERSIONS_DATA_URL)
.then(response => resolve(response))
.catch(err => resolve(null));
});
}
private parseResponseSafe(response: any) {
try {
const parsedResponse = this.parseResponse(response.data);
return JSON.parse(parsedResponse);
} catch (err) { }
return null;
}
private parseResponse(response: any): string {
const parts = response.split("\n");
// Replace first row with {
parts[0] = "{ ";
let result = parts.join("\n");
// Remove last symbol - ;
result = result.substr(0, result.length - 1);
return result;
}
}