@signiant/media-shuttle-sdk-base
Version:
The base parent sdk behind other media shuttle sdks (e.g. media-shuttle-sdk)
452 lines (451 loc) • 22.4 kB
JavaScript
/* eslint-disable import/first */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
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());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var _a;
import { MessageContext } from '../common';
import { LogManager, messageService } from '../system';
import { signiant_private } from '../../index';
import { v4 as uuid } from 'uuid';
import MessageStatus from '../common/channelproviders/MessageStatus';
import { mapToAppEventType } from '../common/utils';
import { CodedError, ErrorCode } from '../../external';
import ErrorMessages from '../../external/common/ErrorMessages';
import TransferClientEventType from '../enums/TransferClientEventType';
import MessageServiceState from '../enums/MessageServiceState';
import TransferClientState from '../enums/TransferClientState';
import MessageServiceEventType from '../enums/MessageServiceEventType';
import EventEmitter from 'events';
import { transferConfigKeyJsId } from '../common/constants';
import { get as getIn } from 'lodash';
/**
* This mapping admittedly looks a little pointless but we really shouldn't be exposing the various messageService
* states in events emitted from a TransferClient. Among other reasons the Appless client may not use
* the messageService in the future.
*/
var messageServiceToTransferClientMap = (_a = {},
_a[MessageServiceState.UNINITIALIZED] = TransferClientState.UNINITIALIZED,
_a[MessageServiceState.INITIALIZING] = TransferClientState.INITIALIZING,
_a[MessageServiceState.INITIALIZED] = TransferClientState.INITIALIZED,
_a);
var FolderSelectResultCode;
(function (FolderSelectResultCode) {
FolderSelectResultCode["OK"] = "ok";
FolderSelectResultCode["CANCEL"] = "cancel";
})(FolderSelectResultCode || (FolderSelectResultCode = {}));
var createInitError = function () {
return new CodedError({
message: ErrorMessages.staticErrorMessages[ErrorCode.APP_CONNECTION_UNINITIALIZED],
code: ErrorCode.APP_CONNECTION_UNINITIALIZED,
});
};
var DEFAULT_MAX_REQUEST_TIMEOUT_MILLISECONDS = 10 * 1000;
var UNRESPONSIVE_COMMANDS = [MessageContext.FILES_DELETED_EVENT, MessageContext.CANCEL_TRANSFER];
var AppClient = /** @class */ (function (_super) {
__extends(AppClient, _super);
function AppClient(_a) {
var messageServiceUrl = _a.messageServiceUrl, _b = _a.messageTimeoutMillis, messageTimeoutMillis = _b === void 0 ? DEFAULT_MAX_REQUEST_TIMEOUT_MILLISECONDS : _b;
var _this = _super.call(this) || this;
_this._originatorId = uuid();
_this._messageServiceUrl = messageServiceUrl;
_this._messageTimeoutMillis = messageTimeoutMillis;
return _this;
}
AppClient.prototype.cancelTransfer = function (originator) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.initialized) {
throw createInitError();
}
return [4 /*yield*/, this.sendMessageRequest({
originator: originator,
context: MessageContext.CANCEL_TRANSFER,
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
AppClient.prototype.initialize = function (options) {
if (options === void 0) { options = {}; }
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!!this.initialized) return [3 /*break*/, 3];
this._transferClientInitializationOptions = options;
this._messageServiceStateChangeListenerBoundInstance = this.listenToMessageServiceStateChange.bind(this);
return [4 /*yield*/, messageService.initializeApplication({
force: options.force,
messageServiceUrl: this._messageServiceUrl,
})];
case 1:
_b.sent();
this._messageChannel = messageService.messageChannel;
messageService.on(MessageServiceEventType.STATE_CHANGED, this._messageServiceStateChangeListenerBoundInstance);
_a = this;
return [4 /*yield*/, this.getClientInfo()];
case 2:
_a._clientInfo = _b.sent();
_b.label = 3;
case 3: return [2 /*return*/];
}
});
});
};
AppClient.prototype.listenToMessageServiceStateChange = function (newState) {
var newTransferClientState = messageServiceToTransferClientMap[newState];
this.emit(TransferClientEventType.STATE_CHANGED, newTransferClientState);
};
AppClient.prototype.reinitialize = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
LogManager.info('Reinitializing the App Client');
messageService.off(MessageServiceEventType.STATE_CHANGED, this._messageServiceStateChangeListenerBoundInstance);
this._messageServiceStateChangeListenerBoundInstance = null;
this._messageChannel = null;
return [4 /*yield*/, this.initialize(this._transferClientInitializationOptions)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
Object.defineProperty(AppClient.prototype, "clientInfo", {
get: function () {
return this._clientInfo;
},
enumerable: false,
configurable: true
});
AppClient.prototype.getClientInfo = function () {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var autodeliveryinfo;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (!!this._clientId) return [3 /*break*/, 2];
return [4 /*yield*/, this.sendMessageRequest({
originator: this._originatorId,
context: MessageContext.GET_AUTODELIVERY_INFO,
})];
case 1:
autodeliveryinfo = (_c.sent()).autodeliveryinfo;
this._clientId = autodeliveryinfo.machineid;
_c.label = 2;
case 2: return [2 /*return*/, {
appVersion: (_b = (_a = this._messageChannel) === null || _a === void 0 ? void 0 : _a.clientInfo) === null || _b === void 0 ? void 0 : _b.app_version,
clientId: this._clientId,
}];
}
});
});
};
Object.defineProperty(AppClient.prototype, "initialized", {
get: function () {
/**
* We can't rely on the message service state here because we can have multiple app clients but
* messageService is singleton.
*/
return !!this._messageChannel;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AppClient.prototype, "state", {
get: function () {
return messageServiceToTransferClientMap[messageService.state];
},
enumerable: false,
configurable: true
});
AppClient.prototype.openFolder = function (path, originator) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.initialized) {
throw createInitError();
}
if (!path) {
throw new CodedError({
message: ErrorMessages.staticErrorMessages[ErrorCode.FOLDER_NOT_SELECTED],
code: ErrorCode.FOLDER_NOT_SELECTED,
});
}
return [4 /*yield*/, this.sendMessageRequest({
originator: originator,
context: signiant_private.MessageContext.OPEN_FOLDER,
content: { path: path },
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
AppClient.prototype.selectDestinationFolder = function (originator) {
if (originator === void 0) { originator = this._originatorId; }
return __awaiter(this, void 0, void 0, function () {
var results, userResponse;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.initialized) {
throw createInitError();
}
LogManager.debug('Prompting user for destination folder');
return [4 /*yield*/, Promise.all([
new Promise(function (resolve) {
_this._messageChannel.setEventHandler(originator, MessageContext.FOLDER_SELECT, resolve);
}),
this.sendMessageRequest({
originator: originator,
context: MessageContext.OPEN_FOLDER_SELECT,
}),
])];
case 1:
results = _a.sent();
userResponse = results.shift();
if (userResponse.resultCode === FolderSelectResultCode.OK) {
return [2 /*return*/, getIn(userResponse, 'folderlist[0].path')];
}
else if (userResponse.resultCode === FolderSelectResultCode.CANCEL) {
throw new CodedError({
message: ErrorMessages.staticErrorMessages[ErrorCode.FOLDER_SELECTION_CANCELED],
code: ErrorCode.FOLDER_SELECTION_CANCELED,
});
}
throw new CodedError({
message: ErrorMessages.staticErrorMessages[ErrorCode.FOLDER_SELECTION_ERROR],
code: ErrorCode.FOLDER_SELECTION_ERROR,
});
}
});
});
};
AppClient.prototype.selectFiles = function (originator) {
return __awaiter(this, void 0, void 0, function () {
var results, userResponse;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.initialized) {
throw createInitError();
}
LogManager.debug('Prompting user for file selection');
return [4 /*yield*/, Promise.all([
new Promise(function (resolve) {
_this._messageChannel.setEventHandler(originator, MessageContext.FILE_SELECTED, resolve);
}),
this.sendMessageRequest({
originator: originator,
context: MessageContext.OPEN_FILE_SELECT,
}),
])];
case 1:
results = _a.sent();
userResponse = results[0];
if (userResponse.resultCode === FolderSelectResultCode.OK) {
return [2 /*return*/, userResponse.filelist];
}
else if (userResponse.resultCode === FolderSelectResultCode.CANCEL) {
throw new CodedError({
message: ErrorMessages.staticErrorMessages[ErrorCode.FILE_SELECTION_CANCELLED],
code: ErrorCode.FILE_SELECTION_CANCELLED,
});
}
throw new CodedError({
message: ErrorMessages.staticErrorMessages[ErrorCode.FILE_SELECTION_ERROR],
code: ErrorCode.FILE_SELECTION_ERROR,
});
}
});
});
};
AppClient.prototype.removeSelectedFiles = function (paths, originator) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.initialized) {
throw createInitError();
}
LogManager.debug('Sending message to indicate that some selected files were deleted');
return [4 /*yield*/, this.sendMessageRequest({
originator: originator,
context: MessageContext.FILES_DELETED_EVENT,
content: {
filelist: paths.map(function (path) { return ({ path: path }); }),
},
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
AppClient.prototype.startDownload = function (originator, transferConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.initialized) {
throw createInitError();
}
LogManager.debug("Starting download transfer [".concat(transferConfig[transferConfigKeyJsId], "] with transferConfig"), transferConfig);
return [4 /*yield*/, this.sendMessageRequest({
originator: originator,
context: MessageContext.DOWNLOAD,
content: transferConfig,
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
AppClient.prototype.startUpload = function (originator, transferConfig) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.initialized) {
throw createInitError();
}
LogManager.debug("Starting upload transfer [".concat(transferConfig[transferConfigKeyJsId], "] with transferConfig"), transferConfig);
return [4 /*yield*/, this.sendMessageRequest({
originator: originator,
context: MessageContext.UPLOAD,
content: transferConfig,
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
AppClient.prototype.sendMessageRequest = function (_a) {
var _this = this;
var _b = _a.originator, originator = _b === void 0 ? this._originatorId : _b, context = _a.context, _c = _a.content, content = _c === void 0 ? null : _c;
return Promise.race([
new Promise(function (resolve, reject) {
if (!UNRESPONSIVE_COMMANDS.includes(context)) {
setTimeout(function () {
reject(new CodedError({
message: ErrorMessages.generatedErrorMessages[ErrorCode.REQUEST_TIMEOUT](_this._messageTimeoutMillis),
code: ErrorCode.REQUEST_TIMEOUT,
}));
}, _this._messageTimeoutMillis);
}
else {
resolve({});
}
}),
new Promise(function (resolve, reject) {
_this._messageChannel.sendMessageRequest(originator, context, function (response) {
if (response.status === MessageStatus.FAIL) {
return reject(new Error(response.error.message));
}
resolve(response.content || response);
}, content);
}),
]);
};
AppClient.prototype.setEventHandler = function (originator, eventType, callback) {
if (eventType instanceof RegExp) {
this._messageChannel.setEventHandler(originator, eventType, callback);
}
else {
var mappedAppEventType = mapToAppEventType(eventType);
this.validateEventType(mappedAppEventType, eventType);
this._messageChannel.setEventHandler(originator, mappedAppEventType, callback);
}
};
AppClient.prototype.validateEventType = function (mappedAppEventType, eventType) {
if (!mappedAppEventType) {
throw new CodedError({
message: ErrorMessages.generatedErrorMessages[ErrorCode.UNKNOWN_EVENT_TYPE](eventType),
code: ErrorCode.UNKNOWN_EVENT_TYPE,
});
}
};
AppClient.prototype.removeEventHandler = function (originator, eventType) {
if (eventType instanceof RegExp) {
return this._messageChannel.removeEventHandler(originator, eventType);
}
else {
var mappedAppEventType = mapToAppEventType(eventType);
this.validateEventType(mappedAppEventType, eventType);
return this._messageChannel.removeEventHandler(originator, mappedAppEventType);
}
};
AppClient.prototype.removeAllEventHandlers = function (originator) {
return this._messageChannel.removeEventHandlers(originator);
};
return AppClient;
}(EventEmitter));
export default AppClient;