appcenter-cli
Version:
Command line tool for Visual Studio App Center
185 lines (184 loc) • 10.2 kB
JavaScript
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const commandline_1 = require("../../util/commandline");
const interaction_1 = require("../../util/interaction");
const util_1 = require("util");
const _ = require("lodash");
const date_parsing_helper_1 = require("./lib/date-parsing-helper");
const percent_change_helper_1 = require("./lib/percent-change-helper");
const analytics_constants_1 = require("./lib/analytics-constants");
const debug = require("debug")("appcenter-cli:commands:analytics:sessions");
const IsoDuration = require("iso8601-duration");
let SessionCommand = class SessionCommand extends commandline_1.AppCommand {
constructor(args) {
super(args);
interaction_1.supportsCsv(this.additionalSupportedOutputFormats);
}
run(client) {
return __awaiter(this, void 0, void 0, function* () {
const app = this.app;
const appVersion = this.getAppVersion();
const startDate = date_parsing_helper_1.parseDate(this.startDate, new Date(new Date().setHours(0, 0, 0, 0)), `start date value ${this.startDate} is not a valid date string`);
const endDate = date_parsing_helper_1.parseDate(this.endDate, new Date(), `end date value ${this.endDate} is not a valid date string`);
if (!this.duration && !this.statistics) {
// when no switches are specified, all the data should be shown
this.duration = this.statistics = true;
}
const promises = [];
const requestResult = {};
// durations statistics required for both "duration" and "statistics" switches
promises.push(this.loadSessionDurationsStatistics(client, app, startDate, endDate, appVersion).then((distributions) => (requestResult.sessionDurationsDistribution = distributions)));
if (this.statistics) {
promises.push(this.loadSessionCountsStatistics(client, app, startDate, endDate, appVersion).then((counts) => (requestResult.sessionCounts = counts)));
// get session counts for the previous interval of the same length
const previousEndDate = startDate;
const previousStartDate = new Date(previousEndDate.valueOf() - (endDate.valueOf() - startDate.valueOf()));
promises.push(this.loadSessionCountsStatistics(client, app, previousStartDate, previousEndDate, appVersion).then((counts) => (requestResult.previousSessionCounts = counts)));
}
yield interaction_1.out.progress("Loading statistics...", Promise.all(promises));
const outputObject = this.toJsonOutput(requestResult);
this.outputStatistics(outputObject);
return commandline_1.success();
});
}
getAppVersion() {
return !_.isNil(this.appVersion) ? [this.appVersion] : undefined;
}
loadSessionDurationsStatistics(client, app, startDate, endDate, appVersion) {
return __awaiter(this, void 0, void 0, function* () {
try {
return yield client.analytics.sessionDurationsDistribution(startDate, app.ownerName, app.appName, {
end: endDate,
versions: appVersion,
});
}
catch (error) {
debug(`Failed to get sessions duration distributions - ${util_1.inspect(error)}`);
throw commandline_1.failure(commandline_1.ErrorCodes.Exception, "failed to get sessions duration distributions");
}
});
}
loadSessionCountsStatistics(client, app, startDate, endDate, appVersion) {
return __awaiter(this, void 0, void 0, function* () {
try {
return yield client.analytics.sessionCounts(startDate, "P1D", app.ownerName, app.appName, {
end: endDate,
versions: appVersion,
});
}
catch (error) {
debug(`Failed to get session counts - ${util_1.inspect(error)}`);
throw commandline_1.failure(commandline_1.ErrorCodes.Exception, "failed to get session counts");
}
});
}
toJsonOutput(requestsResult) {
const jsonOutput = {};
if (this.duration) {
jsonOutput.sessions = requestsResult.sessionDurationsDistribution.distribution;
}
if (this.statistics) {
const totalSessionsCount = _.sumBy(requestsResult.sessionCounts, (dateTimeCounts) => dateTimeCounts.count);
const previousTotalSessionsCount = _.sumBy(requestsResult.previousSessionCounts, (dateTimeCounts) => dateTimeCounts.count);
const averageSessionsPerDay = totalSessionsCount / requestsResult.sessionCounts.length;
const previousAverageSessionsPerDay = previousTotalSessionsCount / requestsResult.previousSessionCounts.length;
const averageSessionDuration = IsoDuration.toSeconds(IsoDuration.parse(requestsResult.sessionDurationsDistribution.averageDuration));
const previousAverageSessionDuration = IsoDuration.toSeconds(IsoDuration.parse(requestsResult.sessionDurationsDistribution.previousAverageDuration));
jsonOutput.statistics = {
totalSessions: {
count: totalSessionsCount,
percentage: percent_change_helper_1.calculatePercentChange(totalSessionsCount, previousTotalSessionsCount),
},
averageSessionsPerDay: {
count: averageSessionsPerDay,
percentage: percent_change_helper_1.calculatePercentChange(averageSessionsPerDay, previousAverageSessionsPerDay),
},
averageSessionsLength: {
seconds: averageSessionDuration,
percentage: percent_change_helper_1.calculatePercentChange(averageSessionDuration, previousAverageSessionDuration),
},
};
}
return jsonOutput;
}
outputStatistics(statisticsObject) {
interaction_1.out.reportObjectAsTitledTables((stats, numberFormatter, dateFormatter, percentageFormatter) => {
const tableArray = [];
if (stats.sessions) {
tableArray.push({
name: "Session Durations",
content: [["", "Count"]].concat(stats.sessions.map((group) => [group.bucket, numberFormatter(group.count)])),
});
}
if (stats.statistics) {
tableArray.push({
name: "Session Statistics",
content: [
["", "Count", "Change"],
["Total Sessions"].concat(toArray(stats.statistics.totalSessions, numberFormatter, percentageFormatter)),
["Average Sessions Per Day"].concat(toArray(stats.statistics.averageSessionsPerDay, numberFormatter, percentageFormatter)),
[
"Average Session Length (sec)",
numberFormatter(stats.statistics.averageSessionsLength.seconds),
percentageFormatter(stats.statistics.averageSessionsLength.percentage),
],
],
});
}
return tableArray;
}, statisticsObject);
}
};
__decorate([
commandline_1.help(analytics_constants_1.startDateHelpMessage),
commandline_1.shortName("s"),
commandline_1.longName("start"),
commandline_1.hasArg
], SessionCommand.prototype, "startDate", void 0);
__decorate([
commandline_1.help(analytics_constants_1.endDateHelpMessage),
commandline_1.shortName("e"),
commandline_1.longName("end"),
commandline_1.hasArg
], SessionCommand.prototype, "endDate", void 0);
__decorate([
commandline_1.help("Specify app version to show statistics for"),
commandline_1.shortName("V"),
commandline_1.longName("app-version"),
commandline_1.hasArg
], SessionCommand.prototype, "appVersion", void 0);
__decorate([
commandline_1.help("Show session durations"),
commandline_1.longName("durations")
], SessionCommand.prototype, "duration", void 0);
__decorate([
commandline_1.help("Show session statistics"),
commandline_1.longName("statistics")
], SessionCommand.prototype, "statistics", void 0);
__decorate([
commandline_1.longName("output"),
commandline_1.help("Format of output for this command: json, csv"),
commandline_1.hasArg
], SessionCommand.prototype, "format", void 0);
SessionCommand = __decorate([
commandline_1.help("Show statistics for sessions")
], SessionCommand);
exports.default = SessionCommand;
function toArray(changingCount, numberFormatter, percentageFormatter) {
return [numberFormatter(changingCount.count), percentageFormatter(changingCount.percentage)];
}