@mentaport/certificates
Version:
Mentaport certificates SDK.
849 lines (838 loc) • 32.6 kB
JavaScript
import { Environment, Base, applyCombination } from '@mentaport/common';
export { Base, BlockchainTypes, ContentSource, ContractEnvironment, ContractStatus, Environment, MentaportUtils } from '@mentaport/common';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(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());
});
}
/**
* Function to check if current client is running on
* web or mobile
*/
function checkIsMobile() {
if (!navigator) {
return false;
}
const isMobile = {
Android: function () {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function () {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function () {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function () {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function () {
return navigator.userAgent.match(/IEMobile/i);
},
any: function () {
return (isMobile.Android() || isMobile.iOS() || isMobile.Windows());
}
};
if (isMobile.any()) {
return true;
}
return false;
}
const developer = "https://public.api.mentaport.xyz/dev";
const staging = "https://public.api.mentaport.xyz/staging";
const production = "https://public.api.mentaport.xyz/prod/v1";
// export const developer_upload = "https://watermarks.api.mentaport.xyz/dev"
// export const staging_upload = "https://watermarks.api.mentaport.xyz/staging"
// export const production_upload = "https://watermarks.api.mentaport.xyz/v1"
function GetBaseURLs(environment) {
let baseIp = developer;
let uploadIp = developer;
if (environment === Environment.STAGING) {
baseIp = staging;
uploadIp = staging;
}
else if (environment === Environment.PRODUCTION) {
baseIp = production;
uploadIp = production;
}
return [baseIp, uploadIp];
}
var UploadProgress;
(function (UploadProgress) {
UploadProgress["NA"] = "Nothing is Uploading";
UploadProgress["UPLOAD"] = "Uploading Content";
UploadProgress["COMPLETE"] = "Upload Complete";
})(UploadProgress || (UploadProgress = {}));
var ContentTypes;
(function (ContentTypes) {
ContentTypes["Image"] = "image";
ContentTypes["Audio"] = "audio";
ContentTypes["Video"] = "video";
})(ContentTypes || (ContentTypes = {}));
var ContentFormat;
(function (ContentFormat) {
ContentFormat["mp3"] = "mp3";
ContentFormat["wav"] = "wav";
ContentFormat["png"] = "png";
ContentFormat["jpg"] = "jpg";
ContentFormat["mp4"] = "mp4";
})(ContentFormat || (ContentFormat = {}));
var CertificateStatus;
(function (CertificateStatus) {
CertificateStatus["NonActive"] = "NonActive";
CertificateStatus["Initiating"] = "Initiating";
CertificateStatus["Processing"] = "Processing";
CertificateStatus["Pending"] = "Pending";
CertificateStatus["Active"] = "Active";
})(CertificateStatus || (CertificateStatus = {}));
var VerificationStatus;
(function (VerificationStatus) {
VerificationStatus["Initiating"] = "Initiating";
VerificationStatus["Processing"] = "Processing";
VerificationStatus["NoCertificate"] = "NoCertificate";
VerificationStatus["Certified"] = "Certified";
})(VerificationStatus || (VerificationStatus = {}));
var CopyrightInfo;
(function (CopyrightInfo) {
CopyrightInfo["NoCopyright"] = "no_copyright";
CopyrightInfo["Registered"] = "copyright_registered";
CopyrightInfo["Registering"] = "copyright_registering";
})(CopyrightInfo || (CopyrightInfo = {}));
var AITrainingMiningInfo;
(function (AITrainingMiningInfo) {
AITrainingMiningInfo["NotAllowed"] = "not_allowed";
AITrainingMiningInfo["Allow"] = "allow";
})(AITrainingMiningInfo || (AITrainingMiningInfo = {}));
class Core extends Base {
constructor(apiKey) {
super(apiKey);
this._uploadUrl = "";
// this._apiKey = apiKey
this._uploadProgress = UploadProgress.NA;
}
/**
* Function to check if app running in mobile
*
* @returns {boolean}
*/
isMobile() {
return checkIsMobile();
}
getApi() {
return super._apiKey;
}
getUploadProgress() {
return this._uploadProgress;
}
//------
resetUploadProgress() {
this._uploadProgress = UploadProgress.NA;
}
startUploadProgress() {
this._uploadProgress = UploadProgress.UPLOAD;
}
completeUploadProgress() {
this._uploadProgress = UploadProgress.COMPLETE;
}
}
// lambda limit of 4.0MB
const _maxSizeInBytes = 4.0 * 1000000; // 4.0MB limit
class CertificatesNFTs extends Core {
//-------------------------------------------------------------------------------------------------
// CREATE + APPROVE
//-------------------------------------------------------------------------------------------------
/**
* Function to create a watermark certificate
*
* @param {certificate} ICertificateArg
* @param {blobContent} Content
*
* @returns {IResults<ICertificate>} Returns create certificate
*/
createCertificate(certificate, blobContent) {
return __awaiter(this, void 0, void 0, function* () {
try {
this.startUploadProgress();
// return await this.createCertificatePresignURL(projectId, certId, contentFormat, blobContent)
if (blobContent.size > _maxSizeInBytes) {
//console.log("presign cert")
return yield this.createCertificatePresignURL(certificate, blobContent);
}
//console.log("normal cert", blobContent.size)
return yield this.createCertificateSmall(certificate, blobContent);
}
catch (error) {
this.resetUploadProgress();
return Promise.reject(error);
}
});
}
createCertificatePresignURL(certificate, blobContent) {
const _super = Object.create(null, {
request: { get: () => super.request },
upload: { get: () => super.upload }
});
return __awaiter(this, void 0, void 0, function* () {
try {
// To upload content over 10mb we are now using presigned URLs
// 1. Get presiged url
const emp = {};
const params_pre = { action: 'upload', projectId: certificate.projectId, contentFormat: certificate.contentFormat };
// console.log(params_pre)
const presigned = yield _super.request.call(this, {
url: `/presigned`,
method: "GET",
params: params_pre
});
let certId = '';
let fail_messaga = presigned.message;
//2. Upload content to url provided
if (presigned.status && presigned.data != null) {
// construct call with new parameters:
certId = presigned.data.id;
const formData = new FormData();
const url = presigned.data.signedUrl.url;
const fields = presigned.data.signedUrl.fields;
Object.entries(fields).forEach(([key, val]) => {
formData.append(key, val);
});
const nameType = "upload." + certificate.contentFormat;
formData.append('file', blobContent, nameType);
const uploadRes = yield _super.upload.call(this, {
url: ``,
method: "POST",
data: formData,
}, url);
if (uploadRes < 300) {
//3. Generate watermark
certificate.certId = certId;
const res = yield _super.request.call(this, {
url: `/certificates/create/presigned`,
method: "POST",
params: certificate
});
this.completeUploadProgress();
return res;
}
fail_messaga = 'Error uploading content.';
}
this.completeUploadProgress();
return { status: false, statusCode: 400, message: fail_messaga, data: emp };
}
catch (error) {
return Promise.reject(error);
}
});
}
createCertificateSmall(certificate, blobContent) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
const formData = new FormData();
if (certificate.certId) {
certificate.certId = undefined;
}
const nameType = "upload." + certificate.contentFormat;
formData.append('content', blobContent, nameType);
const res = yield _super.request.call(this, {
url: `/certificates/create`,
method: "POST",
data: formData,
params: certificate
});
this.completeUploadProgress();
return res;
}
catch (error) {
return Promise.reject(error);
}
});
}
/**
* Function to update a certificate that is NonActive or Pending
*
* @param {certificate} ICertificateUpdateArg
* @param {blobContent} Content
*
* @returns {IResults<ICertificate>} Returns create certificate
*/
updateCertificate(certificate, blobContent) {
return __awaiter(this, void 0, void 0, function* () {
try {
this.startUploadProgress();
if (blobContent.size > _maxSizeInBytes) {
return yield this.updateCertificatePresignURL(certificate, blobContent);
}
return yield this.updateCertificateSmall(certificate, blobContent);
}
catch (error) {
this.resetUploadProgress();
return Promise.reject(error);
}
});
}
updateCertificatePresignURL(certificate, blobContent) {
const _super = Object.create(null, {
request: { get: () => super.request },
upload: { get: () => super.upload }
});
return __awaiter(this, void 0, void 0, function* () {
try {
// To upload content over 10mb we are now using presigned URLs
// 1. Get presiged url
const emp = {};
const params_pre = { action: 'upload', projectId: certificate.projectId, contentFormat: certificate.contentFormat, certId: certificate.certId };
// console.log(params_pre)
const presigned = yield _super.request.call(this, {
url: `/presigned`,
method: "GET",
params: params_pre
});
let certId = '';
let fail_messaga = presigned.message;
//2. Upload content to url provided
if (presigned.status && presigned.data != null) {
// construct call with new parameters:
certId = presigned.data.id;
const formData = new FormData();
const url = presigned.data.signedUrl.url;
const fields = presigned.data.signedUrl.fields;
Object.entries(fields).forEach(([key, val]) => {
formData.append(key, val);
});
const nameType = "upload." + certificate.contentFormat;
formData.append('file', blobContent, nameType);
const uploadRes = yield _super.upload.call(this, {
url: ``,
method: "POST",
data: formData,
}, url);
if (uploadRes < 300) {
//3. Generate watermark
certificate.certId = certId;
const params = Object.assign(Object.assign({}, certificate), { presign: true });
const res = yield _super.request.call(this, {
url: `/certificates/update`,
method: "POST",
params: params
});
this.completeUploadProgress();
return res;
}
fail_messaga = 'Error uploading content.';
}
this.completeUploadProgress();
return { status: false, statusCode: 400, message: fail_messaga, data: emp };
}
catch (error) {
return Promise.reject(error);
}
});
}
updateCertificateSmall(certificate, blobContent) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
const formData = new FormData();
const nameType = "upload." + certificate.contentFormat;
formData.append('content', blobContent, nameType);
const params = Object.assign(Object.assign({}, certificate), { presign: false });
const res = yield _super.request.call(this, {
url: `/certificates/update`,
method: "POST",
data: formData,
params: params
});
this.completeUploadProgress();
return res;
}
catch (error) {
return Promise.reject(error);
}
});
}
/**
* Function to approve / non-approve a certificate before it generates NFT
*
* @param {projectId} ProjectId
* @param {certId} CertId from init content call
* @param {approve} Approve boolean
*
* @returns {IResults<ICertificate>} Returns certificate
*/
approveCertificate(projectId, certId, approved) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
this.resetUploadProgress();
const params = { certId, projectId, approved };
return yield _super.request.call(this, {
url: `/certificates/approve`,
method: "POST",
params
});
}
catch (error) {
return Promise.reject(error);
}
});
}
/**
* Function to delete a NonActive or Pending certificate
*
* @param {projectId} ProjectId
* @param {certId} CertId from init content call
*
* @returns {IResults<null>} Returns status of deletion
*/
deleteCertificate(projectId, certId) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
this.resetUploadProgress();
const params = { certId, projectId };
return yield _super.request.call(this, {
url: `/certificates/delete`,
method: "POST",
params
});
}
catch (error) {
return Promise.reject(error);
}
});
}
//-------------------------------------------------------------------------------------------------
// GETTERS
//-------------------------------------------------------------------------------------------------
/**
* Get certificates based on specified criteria.
* @param {GetCertificatesOptions} options - The options for fetching certificates
* - ProjectId: Filter certificates by project ID
* - CertId: Get a specific certificate by ID (requires projectId)
* - Cursor: Pagination cursor for fetching next page of results
* - Limit: Maximum number of certificates to return
* @returns {Promise<IResults<ICertificatesQuery>>} Returns paginated certificates matching the criteria
*/
getCertificates(options) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
return yield _super.request.call(this, {
url: `/certificates`,
method: "GET",
params: options,
});
}
catch (error) {
return Promise.reject(error);
}
});
}
/**
* Get certificates count based on specified criteria.
* @param {projectId} projectId - The options for fetching certificates count
* - ProjectId: Filter certificates by project ID
* @returns {Promise<IResults<ICertificatesCount>>} Returns certificates count matching the criteria
*/
getTotalCertificates(projectId) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
return yield _super.request.call(this, {
url: `/certificates/count`,
method: "GET",
params: { projectId },
});
}
catch (error) {
return Promise.reject(error);
}
});
}
/**
* Function to get download url of certificate
* @param {projectId} ProjectId
* @param {certId} certId
*
* @returns {url} Returns url
*/
getDownloadUrl(projectId, certId) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
const params = { projectId, certId };
return yield _super.request.call(this, {
url: `/download`,
method: "GET",
params,
});
}
catch (error) {
return Promise.reject(error);
}
});
}
/**
* Function to check certificate status
* @param {projectId} ProjectId
* @param {certId} certId
*
* @returns {ICertStatusResult} Returns certificate and status information.
*/
getCertificateStatus(projectId, certId) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
const params = { projectId, certId };
const res = yield _super.request.call(this, {
url: `/certificates/status`,
method: "GET",
params,
});
return res;
}
catch (error) {
return Promise.reject(error);
}
});
}
//-------------------------------------------------------------------------------------------------
/**
* Function to get active projects of a user.
* All projects will be return if all is true (active and non active)
* @param {allProjects} Boolean to get all projects, not just active
*
* @returns {ICertificateProject[]} Returns projects of user
*/
getProjects(all) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
const params = { allProjects: all || false };
return yield _super.request.call(this, {
url: '/certificates/projects',
method: "GET",
params
});
}
catch (error) {
return Promise.reject(error);
}
});
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// VERIFY
//-------------------------------------------------------------------------------------------------
/**
* Function to verify if a piece of content has a certificate calling from a server
* @param {contentFormat} contentFormat
* @param {urlFound} URL of where it was found
* @param {blobContent} content blob
*
* @returns {IResults<IVerify>} Returns a certificate if found
*
*/
verifyContent(contentFormat, urlFound, blobContent) {
return __awaiter(this, void 0, void 0, function* () {
try {
this.startUploadProgress();
if (blobContent.size > _maxSizeInBytes) {
return yield this.verifyContentPresignURL(contentFormat, urlFound, blobContent);
}
return yield this.verifyContentSmall(contentFormat, urlFound, blobContent);
}
catch (error) {
this.completeUploadProgress();
return Promise.reject(error);
}
});
}
verifyContentSmall(contentFormat, urlFound, blobContent) {
const _super = Object.create(null, {
upload: { get: () => super.upload }
});
return __awaiter(this, void 0, void 0, function* () {
try {
const params = { contentFormat, url: urlFound, verifyType: "upload_sdk" };
const formData = new FormData();
const nameType = "verify." + contentFormat;
formData.append('content', blobContent, nameType);
const res = yield _super.upload.call(this, {
url: `/verify`,
method: "POST",
data: formData,
params: params,
}, this._uploadUrl);
this.completeUploadProgress();
return res;
}
catch (error) {
return Promise.reject(error);
}
});
}
verifyContentPresignURL(contentFormat, urlFound, blobContent) {
const _super = Object.create(null, {
request: { get: () => super.request },
upload: { get: () => super.upload }
});
return __awaiter(this, void 0, void 0, function* () {
try {
// To upload content over 10mb we are now using presigned URLs
// 1. Get presiged url
const emp = {};
const params_pre = { action: 'verify', contentFormat };
// console.log('params_pre',params_pre)
const presigned = yield _super.request.call(this, {
url: `/verify/presigned`,
method: "GET",
params: params_pre
});
//2. Upload content to url provided
if (presigned.status && presigned.data != null) {
// construct call with new parameters:
const formData = new FormData();
const url = presigned.data.signedUrl.url;
const verId = presigned.data.id;
const fields = presigned.data.signedUrl.fields;
Object.entries(fields).forEach(([key, val]) => {
formData.append(key, val);
});
const nameType = "verify." + contentFormat;
formData.append('file', blobContent, nameType);
const uploadRes = yield _super.upload.call(this, {
url: ``,
method: "POST",
data: formData,
}, url);
if (uploadRes < 300) {
//3. Generate watermark
const params1 = { contentFormat, url: urlFound, verId: verId, verifyType: "upload_sdk" };
const res = yield _super.upload.call(this, {
url: `/verify/presigned`,
method: "POST",
params: params1
}, this._uploadUrl);
this.completeUploadProgress();
return res;
}
}
this.completeUploadProgress();
return { status: false, statusCode: 400, message: "Error verifying content (presigned).", data: emp };
}
catch (error) {
return Promise.reject(error);
}
});
}
/**
* Function to get verification progress status
* @param {verId} string
*
* @returns {IVerify} Returns IVerify
*/
getVerificationStatus(verId) {
const _super = Object.create(null, {
upload: { get: () => super.upload }
});
return __awaiter(this, void 0, void 0, function* () {
try {
const params = { verId };
const res = yield _super.upload.call(this, {
url: `/verify/status`,
method: "GET",
params,
}, this._uploadUrl);
return res;
}
catch (error) {
return Promise.reject(error);
}
});
}
//-------------------------------------------------------------------------------------------------
// REPORTING
//-------------------------------------------------------------------------------------------------
/**
* Function to report a content
*
* @param {isOk} Status of report
* @param {certIds} certIds list to report
* @param {timestamp} timestamp of verification record
* @param {count} Number of verification in url to report
* @param {url} URL link (optional)
*
*/
reportContent(reportContent) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
this.resetUploadProgress();
return yield _super.request.call(this, {
url: `/report`,
method: "POST",
data: JSON.stringify(reportContent)
});
}
catch (error) {
return Promise.reject(error);
}
});
}
/**
* Function to report a content
*
* @param {id} id returned in verifyContent
* @param {source} Source (optional)
* @param {url} URL link (optional)
*
*/
reportNewContent(reportContent) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
this.resetUploadProgress();
return yield _super.request.call(this, {
url: `/verify/report/new`,
method: "POST",
data: JSON.stringify(reportContent)
});
}
catch (error) {
return Promise.reject(error);
}
});
}
//-------------------------------------------------------------------------------------------------
// ANALYTICS
//-------------------------------------------------------------------------------------------------
/**
* Function to get certificates analytics
* @param {queryDateStart} Query start date
* @param {queryDateEnd} Query end date
* @param {projectId} ProjectId
* @param {certId} CertId
*
* @returns {ICertificatesQuery} Returns all certificates per project.
* Each project certificate will be in its own array
*/
getCertificatesAnalytics(analytics) {
const _super = Object.create(null, {
request: { get: () => super.request }
});
return __awaiter(this, void 0, void 0, function* () {
try {
return yield _super.request.call(this, {
url: `/certificates/analytics`,
method: "GET",
params: analytics,
});
}
catch (error) {
return Promise.reject(error);
}
});
}
}
class CertificateSDK extends Core {
/**
* Constructor for Core SDK
*
* @param {apiKey} APIKey
*
* @returns {}
*/
constructor(apiKey) {
super(apiKey);
}
//--------------------------------------------------------------------
//------------------- PUBLIC FUNCTION -------------------------------
//--------------------------------------------------------------------
/**
* Function to set the client with default env Production
* All users have to call this function
*
* @param {url} urlPath (optional)
*
* @returns {void}
*/
setClient() {
const urls = GetBaseURLs(Environment.PRODUCTION);
super.setClientSide(urls[0]);
this._uploadUrl = urls[1];
}
/**
* Function to set the client environment.
* All users have to call this function
*
* @param {environment} Environment to run sdk in
* @param {url} urlPath (optional-only for testing)
*
* @returns {void}
*/
setClientEnv(environment, url, upload_url) {
const urls = GetBaseURLs(environment);
// if we pass an overload url, use that
if (url || upload_url) {
if (url) {
super.setClientSide(url);
}
else {
super.setClientSide(urls[0]);
}
if (upload_url) {
this._uploadUrl = upload_url;
}
else {
this._uploadUrl = urls[1];
}
}
else {
super.setClientSide(urls[0]);
this._uploadUrl = urls[1];
}
}
}
applyCombination(CertificateSDK, [CertificatesNFTs]);
export { AITrainingMiningInfo, CertificateSDK, CertificateStatus, ContentFormat, ContentTypes, CopyrightInfo, UploadProgress, VerificationStatus };
//# sourceMappingURL=index.js.map