Skip to content

Fix asking for user's emails on postinstall and starting of emualtor on tns debug #2919

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 26, 2017
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ node_js:
- '6'
git:
submodules: true
install:
- npm install --ignore-scripts
before_script:
- gem install xcodeproj
- gem install cocoapods
Expand Down
1 change: 1 addition & 0 deletions lib/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,4 @@ $injector.requireCommand("extension|uninstall", "./commands/extensibility/uninst
$injector.requirePublic("extensibilityService", "./services/extensibility-service");

$injector.require("nodeModulesDependenciesBuilder", "./tools/node-modules/node-modules-dependencies-builder");
$injector.require("subscriptionService", "./services/subscription-service");
6 changes: 1 addition & 5 deletions lib/commands/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@

this.$config.debugLivesync = true;

await this.$devicesService.initialize({

});
await this.$devicesService.detectCurrentlyAttachedDevices();

const devices = this.$devicesService.getDeviceInstances();
Expand Down Expand Up @@ -86,8 +83,7 @@
platform: this.platform,
deviceId: this.$options.device,
emulator: this.$options.emulator,
skipDeviceDetectionInterval: true,
skipInferPlatform: true
skipDeviceDetectionInterval: true
});
// Start emulator if --emulator is selected or no devices found.
if (this.$options.emulator || this.$devicesService.deviceCount === 0) {
Expand Down
62 changes: 2 additions & 60 deletions lib/commands/post-install.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
import { PostInstallCommand } from "../common/commands/post-install";
import * as emailValidator from "email-validator";
import * as queryString from "querystring";
import * as helpers from "../common/helpers";

export class PostInstallCliCommand extends PostInstallCommand {
private logger: ILogger;

constructor($fs: IFileSystem,
private $httpClient: Server.IHttpClient,
private $prompter: IPrompter,
private $userSettingsService: IUserSettingsService,
private $subscriptionService: ISubscriptionService,
$staticConfig: Config.IStaticConfig,
$commandsService: ICommandsService,
$htmlHelpService: IHtmlHelpService,
Expand All @@ -18,63 +11,12 @@ export class PostInstallCliCommand extends PostInstallCommand {
$analyticsService: IAnalyticsService,
$logger: ILogger) {
super($fs, $staticConfig, $commandsService, $htmlHelpService, $options, $doctorService, $analyticsService, $logger);
this.logger = $logger;
}

public async execute(args: string[]): Promise<void> {
await super.execute(args);

if (await this.shouldAskForEmail()) {
this.logger.out("Leave your e-mail address here to subscribe for NativeScript newsletter and product updates, tips and tricks:");
let email = await this.getEmail("(press Enter for blank)");
await this.$userSettingsService.saveSetting("EMAIL_REGISTERED", true);
await this.sendEmail(email);
}
}

private async shouldAskForEmail(): Promise<boolean> {
return helpers.isInteractive() && await process.env.CLI_NOPROMPT !== "1" && !this.$userSettingsService.getSettingValue("EMAIL_REGISTERED");
}

private async getEmail(prompt: string, options?: IPrompterOptions): Promise<string> {
let schema: IPromptSchema = {
message: prompt,
type: "input",
name: "inputEmail",
validate: (value: any) => {
if (value === "" || emailValidator.validate(value)) {
return true;
}
return "Please provide a valid e-mail or simply leave it blank.";
},
default: options && options.defaultAction
};

let result = await this.$prompter.get([schema]);
return result.inputEmail;
}

private async sendEmail(email: string): Promise<void> {
if (email) {
let postData = queryString.stringify({
'elqFormName': "dev_uins_cli",
'elqSiteID': '1325',
'emailAddress': email,
'elqCookieWrite': '0'
});

let options = {
url: 'https://s1325.t.eloqua.com/e/f2',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
},
body: postData
};

await this.$httpClient.httpRequest(options);
}
await this.$subscriptionService.subscribeForNewsletter();
}
}

Expand Down
1 change: 1 addition & 0 deletions lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,4 @@ export const BUILD_OUTPUT_EVENT_NAME = "buildOutput";
export const CONNECTION_ERROR_EVENT_NAME = "connectionError";
export const VERSION_STRING = "version";
export const INSPECTOR_CACHE_DIRNAME = "ios-inspector";
export const POST_INSTALL_COMMAND_NAME = "post-install-cli";
11 changes: 11 additions & 0 deletions lib/definitions/subscription-service.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* Describes methods for subscribing to different NativeScript campaigns.
*/
interface ISubscriptionService {
/**
* Subscribes users for NativeScript's newsletter by asking them for their email.
* In case we've already asked the user for his email, this method will do nothing.
* @returns {Promise<void>}
*/
subscribeForNewsletter(): Promise<void>;
}
2 changes: 1 addition & 1 deletion lib/services/ios-project-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ export class IOSProjectService extends projectServiceBaseLib.PlatformProjectServ
if (!buildConfig.release && !buildConfig.architectures) {
await this.$devicesService.initialize({
platform: this.$devicePlatformsConstants.iOS.toLowerCase(), deviceId: buildConfig.device,
isBuildForDevice: true
skipEmulatorStart: true
});
let instances = this.$devicesService.getDeviceInstances();
let devicesArchitectures = _(instances)
Expand Down
73 changes: 73 additions & 0 deletions lib/services/subscription-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import * as emailValidator from "email-validator";
import * as queryString from "querystring";
import * as helpers from "../common/helpers";

export class SubscriptionService implements ISubscriptionService {
constructor(private $httpClient: Server.IHttpClient,
private $prompter: IPrompter,
private $userSettingsService: IUserSettingsService,
private $logger: ILogger) {
}

public async subscribeForNewsletter(): Promise<void> {
if (await this.shouldAskForEmail()) {
this.$logger.out("Leave your e-mail address here to subscribe for NativeScript newsletter and product updates, tips and tricks:");
let email = await this.getEmail("(press Enter for blank)");
await this.$userSettingsService.saveSetting("EMAIL_REGISTERED", true);
await this.sendEmail(email);
}
}

/**
* Checks whether we should ask the current user if they want to subscribe to NativeScript newsletter.
* NOTE: This method is protected, not private, only because of our unit tests.
* @returns {Promise<boolean>}
*/
protected async shouldAskForEmail(): Promise<boolean> {
return helpers.isInteractive() && process.env.CLI_NOPROMPT !== "1" && !(await this.$userSettingsService.getSettingValue("EMAIL_REGISTERED"));
}

private async getEmail(prompt: string, options?: IPrompterOptions): Promise<string> {
let schema: IPromptSchema = {
message: prompt,
type: "input",
name: "inputEmail",
validate: (value: any) => {
if (value === "" || emailValidator.validate(value)) {
return true;
}

return "Please provide a valid e-mail or simply leave it blank.";
}
};

let result = await this.$prompter.get([schema]);
return result.inputEmail;
}

private async sendEmail(email: string): Promise<void> {
if (email) {
let postData = queryString.stringify({
'elqFormName': "dev_uins_cli",
'elqSiteID': '1325',
'emailAddress': email,
'elqCookieWrite': '0'
});

let options = {
url: 'https://s1325.t.eloqua.com/e/f2',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
},
body: postData
};

await this.$httpClient.httpRequest(options);
}
}

}

$injector.register("subscriptionService", SubscriptionService);
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"glob": "^7.0.3",
"iconv-lite": "0.4.11",
"inquirer": "0.9.0",
"ios-device-lib": "0.4.6",
"ios-device-lib": "0.4.7",
"ios-mobileprovision-finder": "1.0.9",
"ios-sim-portable": "~3.0.0",
"lockfile": "1.0.1",
Expand Down
5 changes: 3 additions & 2 deletions postinstall.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"use strict";

var child_process = require("child_process");
var commandArgs = ["bin/tns", "post-install-cli"];
var path = require("path");
var constants = require(path.join(__dirname, "lib", "constants"));
var commandArgs = [path.join(__dirname, "bin", "tns"), constants.POST_INSTALL_COMMAND_NAME];
var nodeArgs = require(path.join(__dirname, "lib", "common", "scripts", "node-args")).getNodeArgs();

child_process.spawn(process.argv[0], nodeArgs.concat(commandArgs), {stdio: "inherit"});
child_process.spawn(process.argv[0], nodeArgs.concat(commandArgs), { stdio: "inherit" });
59 changes: 59 additions & 0 deletions test/commands/post-install.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Yok } from "../../lib/common/yok";
import { assert } from "chai";
import { PostInstallCliCommand } from "../../lib/commands/post-install";

const createTestInjector = (): IInjector => {
const testInjector = new Yok();
testInjector.register("fs", {
setCurrentUserAsOwner: async (path: string, owner: string): Promise<void> => undefined
});

testInjector.register("subscriptionService", {
subscribeForNewsletter: async (): Promise<void> => undefined
});

testInjector.register("staticConfig", {});

testInjector.register("commandsService", {
tryExecuteCommand: async (commandName: string, commandArguments: string[]): Promise<void> => undefined
});

testInjector.register("htmlHelpService", {
generateHtmlPages: async (): Promise<void> => undefined
});

testInjector.register("options", {});

testInjector.register("doctorService", {
printWarnings: async (configOptions?: { trackResult: boolean }): Promise<boolean> => undefined
});

testInjector.register("analyticsService", {
checkConsent: async (): Promise<void> => undefined,
track: async (featureName: string, featureValue: string): Promise<void> => undefined
});

testInjector.register("logger", {
out: (formatStr?: any, ...args: any[]): void => undefined,
printMarkdown: (...args: any[]): void => undefined
});

testInjector.registerCommand("post-install-cli", PostInstallCliCommand);

return testInjector;
};

describe("post-install command", () => {
it("calls subscriptionService.subscribeForNewsletter method", async () => {
const testInjector = createTestInjector();
const subscriptionService = testInjector.resolve<ISubscriptionService>("subscriptionService");
let isSubscribeForNewsletterCalled = false;
subscriptionService.subscribeForNewsletter = async (): Promise<void> => {
isSubscribeForNewsletterCalled = true;
};
const postInstallCommand = testInjector.resolveCommand("post-install-cli");

await postInstallCommand.execute([]);
assert.isTrue(isSubscribeForNewsletterCalled, "post-install-cli command must call subscriptionService.subscribeForNewsletter");
});
});
35 changes: 35 additions & 0 deletions test/post-install.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { assert } from "chai";

// Use require instead of import in order to replace the `spawn` method of child_process
let childProcess = require("child_process");

import { SpawnOptions, ChildProcess } from "child_process";
import * as path from "path";
import { POST_INSTALL_COMMAND_NAME } from "../lib/constants";

describe("postinstall.js", () => {
it("calls post-install-cli command of CLI", () => {
const originalSpawn = childProcess.spawn;
let isSpawnCalled = false;
let argsPassedToSpawn: string[] = [];
childProcess.spawn = (command: string, args?: string[], options?: SpawnOptions): ChildProcess => {
isSpawnCalled = true;
argsPassedToSpawn = args;

return null;
};

require(path.join(__dirname, "..", "postinstall"));

childProcess.spawn = originalSpawn;

assert.isTrue(isSpawnCalled, "child_process.spawn must be called from postinstall.js");

const expectedPathToCliExecutable = path.join(__dirname, "..", "bin", "tns");

assert.isTrue(argsPassedToSpawn.indexOf(expectedPathToCliExecutable) !== -1, `The spawned args must contain path to TNS.
Expected path is: ${expectedPathToCliExecutable}, current args are: ${argsPassedToSpawn}.`);
assert.isTrue(argsPassedToSpawn.indexOf(POST_INSTALL_COMMAND_NAME) !== -1, `The spawned args must contain the name of the post-install command.
Expected path is: ${expectedPathToCliExecutable}, current args are: ${argsPassedToSpawn}.`);
});
});
Loading