@aurigma/design-atoms
Version:
Design Atoms is a part of Customer's Canvas SDK which allows for manipulating individual design elements through your code.
307 lines • 12.3 kB
JavaScript
import * as Ajax from "./../Utils/Ajax";
import * as Utils from "@aurigma/design-atoms-model/Utils/Utils";
import { ImageMetaData } from "@aurigma/design-atoms-model/Product/Items/ImageMetaData";
import { Exception } from "@aurigma/design-atoms-model/Exception";
import { RectangleF } from "@aurigma/design-atoms-model/Math";
import { EventWithSenderArg } from "@aurigma/design-atoms-model";
import { Deferred } from "../Utils/Deferred";
import { JsonColorParser } from "../Serialization/JsonColorParser";
export class ServiceError {
constructor(_timeout, _message, _stacktrace, _type, _data) {
this._timeout = _timeout;
this._message = _message;
this._stacktrace = _stacktrace;
this._type = _type;
this._data = _data;
}
}
const loadingImageDefaultUrl = "/resource?image=waitclock";
const authHeader = "Authorization";
export class DesignAtomsApiClient {
constructor(timeout = 60000) {
this._setBackendUrl = new Deferred();
this._backendUrl = "";
this._timeout = 60000;
this._loadingImageUrl = null;
this._authorizationToken = null;
this._timeout = timeout;
this._loadingImageUrlChanged = new EventWithSenderArg();
this._authorizationToken = null;
}
set backendUrl(value) {
this._backendUrl = value;
}
get backendUrl() {
return this._backendUrl;
}
get loadingImageUrl() {
var _a;
return (_a = this._loadingImageUrl) !== null && _a !== void 0 ? _a : Utils.urlCombine(this._backendUrl, "api/ccviewer", loadingImageDefaultUrl);
}
set loadingImageUrl(value) {
if (typeof value === "string" && this._loadingImageUrl !== value) {
this._loadingImageUrl = value;
this._loadingImageUrlChanged.notify(this, {});
}
}
get loadingImageUrlChanged() {
return this._loadingImageUrlChanged;
}
get serviceEndpoint() {
return Utils.urlCombine(this._backendUrl, "api/ccviewer");
}
setAuthorizationToken(authorizationToken) {
this._authorizationToken = authorizationToken;
}
async getColorPreviews(colors, colorSettings) {
const request = { colorData: colors.map(x => x.getData()), colorSettings: colorSettings };
try {
const response = await Ajax.request({
url: Utils.urlCombine(this.backendUrl, `/api/ccviewer/GetColorPreviews`),
type: Ajax.RequestType.post,
headers: this._getHeaders(),
data: JSON.stringify(request)
});
const colorJsonArray = JSON.parse(response.value).previews;
const result = colorJsonArray.map(x => JsonColorParser.parseRgbColor(x));
return result;
}
catch (ex) {
console.error(`Unable to get ColorPreview. Reason: ${ex}`);
throw ex;
}
}
async getColorPreview(color, colorSettings) {
const request = { colorData: color.getData(), colorSettings: colorSettings };
try {
const response = await Ajax.request({
url: Utils.urlCombine(this.backendUrl, `/api/ccviewer/GetColorPreview`),
type: Ajax.RequestType.post,
headers: this._getHeaders(),
data: JSON.stringify(request)
});
return JsonColorParser.parseRgbColor(JSON.parse(response.value).preview);
}
catch (ex) {
console.error(`Unable to get ColorPreview. Reason: ${ex}`);
return ex;
}
}
async getFontsCSS(requestedFonts, advancedMode) {
try {
const data = await Ajax.request({
url: Utils.urlCombine(this.backendUrl, `/api/ccviewer/cssFonts`),
type: Ajax.RequestType.post,
headers: this._getHeaders(),
data: JSON.stringify({
requestedFontsByPsName: requestedFonts,
advancedMode: advancedMode,
baseUrl: `${this.backendUrl}/api/ccviewer`,
})
});
return Utils.createCssDataUri(data.value);
}
catch (ex) {
console.error(`Unable to get FontsCss. Reason: ${ex}`);
return ex;
}
}
async getFallbackFonts() {
await this._setBackendUrl.promise;
try {
const data = await Ajax.request({
url: Utils.urlCombine(this.backendUrl, `/api/ccviewer/GetFallbackFonts`),
type: Ajax.RequestType.get,
headers: this._getHeaders(),
data: JSON.stringify({
baseUrl: `${this.backendUrl}/api/ccviewer`
})
});
return JSON.parse(data.value);
}
catch (ex) {
console.error(`Unable to get FallbackFonts. Reason: ${ex}`);
return ex;
}
}
async getFontsByteArray(psName) {
try {
const data = await Ajax.request({
type: Ajax.RequestType.get,
url: Utils.urlCombine(this.backendUrl, `/api/ccviewer/fonts/${psName}`),
responseType: "arraybuffer",
headers: this._getHeaders(false)
});
const arrayBuffer = data.xhr.response;
if (arrayBuffer) {
return new Uint8Array(arrayBuffer);
}
}
catch (ex) {
console.error(`Unable to get FontsCss. Reason: ${ex}`);
return ex;
}
}
async getContentPath(originalPathId) {
try {
const data = await Ajax.request({
type: Ajax.RequestType.get,
url: Utils.urlCombine(this.backendUrl, `/api/ccviewer/pth?f=${originalPathId}`),
headers: this._getHeaders()
});
return data.value;
}
catch (ex) {
console.error(`Unable to get content path. Reason: ${ex}`);
return ex;
}
}
async getImageMetaDataFromRemoteUrl(remoteUrl, appDomainUrl = this._backendUrl) {
try {
const imageData = await Ajax.request({
url: Utils.urlCombine(appDomainUrl, "/api/ImagePicker/GetWebImageMeta"),
type: Ajax.RequestType.post,
headers: this._getHeaders(),
data: JSON.stringify({ "url": remoteUrl })
});
return this._parseImageMetadata(imageData.value);
}
catch (ex) {
console.error(`Unable to get Image From Remote Url. Reason: ${ex}`);
return ex;
}
}
async getImageMetaDataFromFile(filePath, userId = null) {
const requestData = { filePath: filePath, userId: userId };
try {
const response = await Ajax.request({
url: Utils.urlCombine(this._backendUrl, "/api/ImagePicker/GetFileMetadata"),
type: Ajax.RequestType.post,
headers: this._getHeaders(),
data: JSON.stringify(requestData)
});
return this._parseImageMetadata(response.value);
}
catch (error) {
throw new Exception(JSON.parse(error.toJSON().message).ExceptionMessage);
}
}
async getImageMetaDataFromDesignImage(designImageName) {
const requestData = { "designImageName": designImageName };
let response;
try {
response = await Ajax.request({
url: Utils.urlCombine(this._backendUrl, "/api/ImagePicker/GetDesignImageMeta"),
type: Ajax.RequestType.post,
headers: this._getHeaders(),
data: JSON.stringify(requestData)
});
}
catch (error) {
throw new Exception(JSON.parse(error.toJSON().message).ExceptionMessage);
}
return this._parseImageMetadata(response.value);
}
async getImageMetadataFromRemoteFile(url) {
const request = { url: url };
let response;
try {
response = await Ajax.request({
url: Utils.urlCombine(this._backendUrl, "/api/ImagePicker/GetWebImageMeta"),
type: Ajax.RequestType.post,
headers: this._getHeaders(),
data: JSON.stringify(request)
});
}
catch (error) {
throw new Exception(JSON.parse(error.toJSON().message).ExceptionMessage);
}
return this._parseImageMetadata(response.value);
}
async getLicenseAsync() {
const response = await Ajax.getJson(Utils.urlCombine(this._backendUrl, "api/ccviewer/license"));
if (response.status !== Ajax.StatusCode.Ok)
throw new Exception("Cannot get license from server");
const raw = JSON.parse(response.value);
const license = {
isDeveloper: raw.isDeveloper,
isTrial: raw.isTrial,
isDesktopOnly: raw.isDesktopOnly,
isEnterprise: raw.isEnterprise,
expirationDate: new Date(raw.expirationDate)
};
return license;
}
async getPathBoundsFromServer(path) {
try {
const result = await Ajax.request({
type: Ajax.RequestType.post,
url: `${this.backendUrl}/api/ccviewer/GetShapeBounds`,
headers: this._getHeaders(),
data: JSON.stringify({ path: path.toString() }),
});
return RectangleF.FromObject(JSON.parse(result.value));
}
catch (ex) {
console.error(`Unable to load shape bounds. Reason: ${ex}`);
}
}
sendRequest(methodName, data, resolve, failure, returnRawResponse = false) {
const xmlhttp = new XMLHttpRequest();
let serviceEndpoint = Utils.urlCombine(this.backendUrl, `/api/ccviewer`);
xmlhttp.open("POST", serviceEndpoint + "/" + methodName);
if (returnRawResponse)
xmlhttp.responseType = "arraybuffer";
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
if (this._isAuthHeaderRequired())
xmlhttp.setRequestHeader(authHeader, this._getAuthHeaderValue());
xmlhttp.timeout = this._timeout;
xmlhttp.onload = (ev) => {
if (xmlhttp.status === 200) {
if (returnRawResponse) {
resolve(xmlhttp.response, xmlhttp);
}
else
resolve(JSON.parse(xmlhttp.response));
}
else {
const error = new ServiceError(false, xmlhttp.statusText, xmlhttp.response);
failure(error, null, methodName);
}
};
xmlhttp.onerror = (ev) => {
failure("error", null, methodName);
};
xmlhttp.ontimeout = (ev) => {
const error = new ServiceError(true, xmlhttp.statusText, xmlhttp.response);
failure(error, null, methodName);
};
const stringData = JSON.stringify(data);
xmlhttp.send(stringData);
}
_parseImageMetadata(json) {
const data = JSON.parse(json);
const result = new ImageMetaData();
result.storageId = data["storageId"];
result.name = data["name"];
result.size.width = data["width"];
result.size.height = data["height"];
result.isVector = data["isVector"];
return result;
}
_getHeaders(includeContentTypeJson = true) {
const result = [];
if (includeContentTypeJson)
result.push(Ajax.ContentType.json);
if (this._isAuthHeaderRequired())
result.push({ name: authHeader, value: this._getAuthHeaderValue() });
return result;
}
_getAuthHeaderValue() {
return `Bearer ${this._authorizationToken}`;
}
_isAuthHeaderRequired() {
return this._authorizationToken != null;
}
}
//# sourceMappingURL=DesignAtomsApiClient.js.map