fixing race conditions

This commit is contained in:
Ondřej Samohel 2020-04-21 19:21:28 +02:00
parent 67e5ff10ff
commit 45feed021a
8 changed files with 840 additions and 672 deletions

View file

@ -39,7 +39,7 @@ class PremierePrelaunch(PypeHook):
else:
# Premiere Setup integration
importlib.reload(prlib)
# importlib.reload(prlib)
prlib.setup(env)
return True

View file

@ -84,7 +84,7 @@ $.batchrenamer = {
// count += 1;
var newName = episode + sequenceName + shotPref + (shotNum).pad(padding);
$.writeln(newName);
$.pype.log(newName);
selected[c].clip.name = newName;
parents.push({

View file

@ -11,9 +11,14 @@ if (ExternalObject.AdobeXMPScript === undefined) {
ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');
}
// this is needed for CSXSEvent to work
if (ExternalObject.PlugPlugExternalObject === undefined) {
ExternalObject.PlugPlugExternalObject = new ExternalObject( "lib:PlugPlugExternalObject");
}
// variable pype is defined in pypeAvalon.jsx
$.pype = {
presets: null,
expectedJobs: [],
addNewTrack: function (numTracks) {
app.enableQE();
var sequence = app.project.activeSequence;
@ -579,28 +584,28 @@ $.pype = {
var successfullyAdded = app.project.addPropertyToProjectMetadataSchema(pypeData, pypeDataN, 2);
var pypeDataValue = xmp.getProperty(kPProPrivateProjectMetadataURI, pypeData);
$.writeln('__ pypeDataValue: ' + pypeDataValue);
$.writeln('__ firstTimeRun: ' + firstTimeRun);
$.writeln('__ successfullyAdded: ' + successfullyAdded);
$.pype.log('__ pypeDataValue: ' + pypeDataValue);
$.pype.log('__ firstTimeRun: ' + firstTimeRun);
$.pype.log('__ successfullyAdded: ' + successfullyAdded);
if ((pypeDataValue === undefined) && (firstTimeRun !== undefined)) {
var pyMeta = {
clips: {},
tags: {}
};
$.writeln('__ pyMeta: ' + pyMeta);
$.pype.log('__ pyMeta: ' + pyMeta);
$.pype.setSequencePypeMetadata(sequence, pyMeta);
pypeDataValue = xmp.getProperty(kPProPrivateProjectMetadataURI, pypeData);
return $.pype.getSequencePypeMetadata(sequence);
} else {
if (successfullyAdded === true) {
$.writeln('__ adding {}');
$.pype.log('__ adding {}');
$.pype.setSequencePypeMetadata(sequence, {});
}
if ((pypeDataValue === undefined) || (!Object.prototype.hasOwnProperty.call(JSON.parse(pypeDataValue), 'clips'))) {
$.writeln('__ getSequencePypeMetadata: returning null');
$.pype.log('__ getSequencePypeMetadata: returning null');
return null;
} else {
$.writeln('__ getSequencePypeMetadata: returning data');
$.pype.log('__ getSequencePypeMetadata: returning data');
return JSON.parse(pypeDataValue);
}
}
@ -612,6 +617,7 @@ $.pype = {
*/
setProjectPreset: function (inPresets) {
// validating the incoming data are having `plugins` key
$.pype.log(inPresets.plugins);
if (Object.prototype.hasOwnProperty.call(inPresets, 'plugins')) {
$.pype.presets = inPresets;
return true;
@ -800,53 +806,59 @@ $.pype = {
return instances;
},
/**
* Return request json data object with instances for pyblish
* @param stagingDir {string} - path to temp directory
* @return {json string}
*/
getPyblishRequest: function (stagingDir, audioOnly) {
var sequence = app.project.activeSequence;
var settings = sequence.getSettings();
$.pype.log('__ stagingDir: ' + stagingDir)
$.pype.log('__ audioOnly: ' + audioOnly)
$.pype.log('__ sequence: ' + sequence)
$.pype.log('__ settings: ' + settings)
var request = {
stagingDir: stagingDir,
currentFile: $.pype.convertPathString(app.project.path),
framerate: (1 / settings.videoFrameRate.seconds),
host: $.getenv('AVALON_APP'),
hostVersion: $.getenv('AVALON_APP_NAME').split('_')[1],
cwd: $.pype.convertPathString(app.project.path).split('\\').slice(0, -1).join('\\')
};
$.pype.log('__ request: ' + request)
var sendInstances = [];
var instances = $.pype.getSelectedClipsAsInstances();
try {
var sequence = app.project.activeSequence;
var settings = sequence.getSettings();
$.pype.log('__ stagingDir: ' + stagingDir)
$.pype.log('__ audioOnly: ' + audioOnly)
$.pype.log('__ sequence: ' + sequence)
$.pype.log('__ settings: ' + settings)
var request = {
stagingDir: stagingDir,
currentFile: $.pype.convertPathString(app.project.path),
framerate: (1 / settings.videoFrameRate.seconds),
host: $.getenv('AVALON_APP'),
hostVersion: $.getenv('AVALON_APP_NAME').split('_')[1],
cwd: $.pype.convertPathString(app.project.path).split('\\').slice(0, -1).join('\\')
};
$.pype.log('__ request: ' + request)
var sendInstances = [];
var instances = $.pype.getSelectedClipsAsInstances();
// make sure the process will end if no instancess are returned
if (instances === null) {
return null;
}
if (audioOnly) {
for (var i = 0; i < instances.length; i++) {
var representations = instances[i].representations;
var newRepr = {};
for (var key in representations) {
var _include = ['audio', 'thumbnail', 'projectfile'];
if (include(_include, key)) {
newRepr[key] = representations[key];
}
}
instances[i].representations = newRepr;
sendInstances.push(instances[i]);
// make sure the process will end if no instancess are returned
if (instances === null) {
return null;
}
} else {
sendInstances = instances;
if (audioOnly) {
for (var i = 0; i < instances.length; i++) {
var representations = instances[i].representations;
var newRepr = {};
for (var key in representations) {
var _include = ['audio', 'thumbnail', 'projectfile'];
if (include(_include, key)) {
newRepr[key] = representations[key];
}
}
instances[i].representations = newRepr;
sendInstances.push(instances[i]);
}
} else {
sendInstances = instances;
}
request['instances'] = sendInstances;
return JSON.stringify(request);
} catch (error) {
$.pype.log('error: ' + error);
return error;
}
request['instances'] = sendInstances;
return JSON.stringify(request);
},
convertSecToTimecode: function (timeSec, fps) {
@ -937,11 +949,19 @@ $.pype = {
},
onEncoderJobComplete: function(jobID, outputFilePath) {
// this will dispatch event to js
var eventObj = new CSXSEvent();
eventObj.type = 'pype.EncoderJobComplete';
eventObj.data = {"jobID": jobID, "outputFilePath": outputFilePath};
eventObj.dispatch();
// remove job from expected jobs list
const index = $.pype.expectedJobs.indexOf(jobID);
if (index > -1) {
$.pype.expectedJobs.splice(index, 1);
}
// test if expected job list is empty. If so, emit event for JS
if (len($.pype.expectedJobs) == 0) {
var eventObj = new CSXSEvent();
eventObj.type = 'pype.EncoderJobsComplete';
eventObj.data = {"jobID": jobID, "outputFilePath": outputFilePath};
eventObj.dispatch();
}
},
render: function (outputPath, family, representation, clipName, version, inPoint, outPoint) {
@ -989,7 +1009,7 @@ $.pype = {
app.encoder.setEmbeddedXMPEnabled(0);
var jobID = app.encoder.encodeSequence(app.project.activeSequence, fullPathToFile, outPreset.fsName, app.encoder.ENCODE_IN_TO_OUT, 1); // Remove from queue upon successful completion?
$.pype.expectedJobs.push(jobID);
$._PPP_.updateEventPanel('jobID = ' + jobID);
outPreset.close();
return file;

View file

@ -1,17 +1,4 @@
/* global $, File, Folder, alert */
/*************************************************************************
* ADOBE CONFIDENTIAL
* ___________________
*
* Copyright 2014 Adobe
* All Rights Reserved.
*
* NOTICE: Adobe permits you to use, modify, and distribute this file in
* accordance with the terms of the Adobe license agreement accompanying
* it. If you have received this file from a source other than Adobe,
* then your use, modification, or distribution of it requires the prior
* written permission of Adobe.
**************************************************************************/
if (typeof ($) === 'undefined') {
var $ = {};
@ -26,89 +13,3 @@ function keepExtention () {
}
keepExtention();
var jsFilesList = ['json2.js'];
$._ext = {
evalJSFiles: function (extensionFolder) {
var libDir = new File(extensionFolder + '/lib');
// adding JS from lib
for (var jsi = 0; jsi < jsFilesList.length; jsi++) {
var js = libDir + '/' + jsFilesList[jsi];
try {
$.evalFile(js);
$.writeln(js);
} catch (e) {
$.writeln(e);
alert('Exception:' + e);
}
}
},
// Evaluate a file and catch the exception.
evalFile: function (path) {
try {
$.evalFile(path);
$.writeln(path);
} catch (e) {
$.writeln(e);
alert('Exception:' + e);
}
},
// Evaluate all the files in the given folder
evalJSXFiles: function (extensionFolder, appShortName) {
// adding all jsx files
var folderJsx = new Folder(extensionFolder + '/jsx/');
var folderPpro = new Folder(folderJsx + '/' + appShortName);
var foldersToImport = [folderPpro, folderJsx];
for (var fi = 0; fi < foldersToImport.length; fi++) {
if (foldersToImport[fi].exists) {
var jsxFiles = foldersToImport[fi].getFiles('*.jsx');
for (var i = 0; i < jsxFiles.length; i++) {
var jsxFile = jsxFiles[i];
$._ext.evalFile(jsxFile);
}
}
}
},
// entry-point function to call scripts more easily & reliably
callScript: function (dataStr) {
try {
var dataObj = JSON.parse(decodeURIComponent(dataStr));
if (
!dataObj ||
!dataObj.namespace ||
!dataObj.scriptName ||
!dataObj.args
) {
throw new Error('Did not provide all needed info to callScript!');
}
// call the specified jsx-function
var result = $[dataObj.namespace][dataObj.scriptName].apply(
null,
dataObj.args
);
// build the payload-object to return
var payload = {
err: 0,
result: result
};
return encodeURIComponent(JSON.stringify(payload));
} catch (err) {
payload = {
err: err
};
return encodeURIComponent(JSON.stringify(payload));
}
}
};
// var extensionFolder = new Folder(
// 'C:/Users/jezsc/CODE/pype-setup/repos/pype/pype/premiere/extensions/com.pype');
// $.writeln(extensionFolder);
// var mainJsx = extensionFolder + '/pypeApp.jsx';
// var appName = 'PPRO';
// $.writeln(mainJsx);
// $.evalFile(mainJsx);
// $._ext.evalJSXFiles(extensionFolder, appName);
// $._ext.evalJSFiles(extensionFolder);

View file

@ -0,0 +1,69 @@
{
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "script",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
"constructor-super": 2,
"for-direction": 2,
"getter-return": 2,
"no-async-promise-executor": 2,
"no-case-declarations": 2,
"no-class-assign": 2,
"no-compare-neg-zero": 2,
"no-cond-assign": 2,
"no-const-assign": 2,
"no-constant-condition": 2,
"no-control-regex": 2,
"no-debugger": 2,
"no-delete-var": 2,
"no-dupe-args": 2,
"no-dupe-class-members": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-empty": 2,
"no-empty-character-class": 2,
"no-empty-pattern": 2,
"no-ex-assign": 2,
"no-extra-boolean-cast": 2,
"no-extra-semi": 2,
"no-fallthrough": 2,
"no-func-assign": 2,
"no-global-assign": 2,
"no-inner-declarations": 2,
"no-invalid-regexp": 2,
"no-irregular-whitespace": 2,
"no-misleading-character-class": 2,
"no-mixed-spaces-and-tabs": 2,
"no-new-symbol": 2,
"no-obj-calls": 2,
"no-octal": 2,
"no-prototype-builtins": 2,
"no-redeclare": 2,
"no-regex-spaces": 2,
"no-self-assign": 2,
"no-shadow-restricted-names": 2,
"no-sparse-arrays": 2,
"no-this-before-super": 2,
"no-undef": 2,
"no-unexpected-multiline": 2,
"no-unreachable": 2,
"no-unsafe-finally": 2,
"no-unsafe-negation": 2,
"no-unused-labels": 2,
"no-unused-vars": 2,
"no-useless-catch": 2,
"no-useless-escape": 2,
"no-with": 2,
"require-yield": 2,
"use-isnan": 2,
"valid-typeof": 2
},
"env": {
"es2017": false,
"node": true
}
}

View file

@ -1,427 +1,233 @@
/* esversion:6, global CSInterface, $, cep_node, querySelector, pras, SystemPath, displayResult */
/*global CSInterface, $, PypeRestApiClient, SystemPath, document */
/* eslint-env node, es2017 */
var csi = new CSInterface();
var output = document.getElementById('output');
var process = require('process');
var timecodes = require('node-timecodes');
class Pype {
constructor() {
var self = this;
this.csi = new CSInterface();
this.rootFolderPath = this.csi.getSystemPath(SystemPath.EXTENSION);
var extensionRoot = this.rootFolderPath + "/jsx/";
console.info("Loading pype.jsx");
this.csi.evalScript('$.evalFile("' + extensionRoot + 'pype.jsx")');
console.info("Loading batchRenamer.jsx");
this.csi.evalScript('$.evalFile("' + extensionRoot + 'batchRenamer.jsx")');
function displayResult (r) {
console.log(r);
_pype.csi.evalScript('$.writeln( ' + JSON.stringify(r) + ' );');
output.classList.remove('error');
output.innerText = r;
_pype.csi.evalScript('$.pype.log( ' + JSON.stringify(r) + ' );');
}
function displayError (e) {
_pype.csi.evalScript('$.pype.alert_message( ' + JSON.stringify(e) + ' )');
output.classList.add('error');
output.innerText = e;
}
var _pype = {
csi: csi,
rootFolderPath: csi.getSystemPath(SystemPath.EXTENSION),
displayResult: displayResult,
displayError: displayError,
getEnv: function () {
_pype.csi.evalScript('$.pype.getProjectFileData();', function (result) {
process.env.EXTENSION_PATH = _pype.rootFolderPath;
_pype.ENV = process.env;
console.log(result);
console.log(_pype.rootFolderPath);
var resultData = JSON.parse(result);
for (var key in resultData) {
_pype.ENV[key] = resultData[key];
}
csi.evalScript('$.pype.setEnvs(' + JSON.stringify(_pype.ENV) + ')');
});
}
};
// function renderClips () {
// _pype.csi.evalScript('$.pype.transcodeExternal(' + pras.rootFolderPath + ');', function (result) {
// displayResult(result);
// });
// }
function loadExtensionDependencies () {
// get extension path
var extensionPath = _pype.csi.getSystemPath(SystemPath.EXTENSION);
// get the appName of the currently used app. For Premiere Pro it's "PPRO"
var appName = _pype.csi.hostEnvironment.appName;
console.log('App name: ' + appName);
// load general JS scripts from `extensionPath/lib/`
_pype.csi.evalScript(
'$._ext.evalJSFiles("' + extensionPath + '" )');
console.log('js load done');
// load all available JSX scripts from `extensionPath/jsx/*` with subfolders
_pype.csi.evalScript(
'$._ext.evalJSXFiles("' + extensionPath + '", "' + appName + '")');
console.log('jsx load done');
_pype.csi.evalScript('$._PPP_.updateEventPanel( "' + 'all plugins are loaded' + '" )');
}
// run all at loading
loadExtensionDependencies();
function querySelector (elementId) {
return document.querySelector(elementId);
}
function loadAnimationRendersToTimeline () {
// it will get type of asset and extension from input
// and start loading script from jsx
var $ = querySelector('#load');
var data = {};
data.subset = $.querySelector('input[name=type]').value;
data.subsetExt = $.querySelector('input[name=ext]').value;
var requestList = [];
// get all selected clips
_pype.csi.evalScript('$.pype.getClipsForLoadingSubsets( "' + data.subset + '" )', function (result) {
// TODO: need to check if the clips are already created and this is just updating to last versions
var resultObj = JSON.parse(result);
var instances = resultObj[0];
var numTracks = resultObj[1];
var key = '';
// creating requesting list of dictionaries
for (key in instances) {
var clipData = {};
clipData.parentClip = instances[key];
clipData.asset = key;
clipData.subset = data.subset;
clipData.representation = data.subsetExt;
requestList.push(clipData);
// get environment
this.csi.evalScript('$.pype.getProjectFileData();', (result) => {
process.env.EXTENSION_PATH = this.rootFolderPath;
this.env = process.env;
var resultData = JSON.parse(result);
for (var key in resultData) {
this.env[key] = resultData[key];
}
this.csi.evalScript('$.pype.setEnvs(' + JSON.stringify(self.env) + ')');
this.pras = new PypeRestApiClient(this.env);
console.info(`Getting presets for ${this.env.AVALON_PROJECT}`);
this.presets = this.pras.get_presets(this.env.AVALON_PROJECT);
console.info("transferring presets to jsx")
this.csi.evalScript('$.pype.setProjectPreset(' + JSON.stringify(result) + ');', () => {
console.log("done");
// bind encoding jobs event listener
this.csi.addEventListener("pype.EncoderJobsComplete", this._encodingDone);
// Bind Interface buttons
this._bindButtons();
});
});
}
if (requestList.length < 1) {
_pype.csi.evalScript(
'$.pype.alert_message("' + 'Need to select at least one clip' + '")');
return;
}
// gets data from mongodb
pras.load_representations(_pype.ENV.AVALON_PROJECT, requestList).then(
function (avalonData) {
// creates or updates data on timeline
var makeData = {};
makeData.binHierarchy = data.subset + '/' + data.subsetExt;
makeData.clips = avalonData;
makeData.numTracks = numTracks;
_pype.csi.evalScript('$.pype.importFiles( ' + JSON.stringify(makeData) + ' )');
}
);
});
}
function evalScript (script) {
var callback = function (result) {
displayResult(result);
};
_pype.csi.evalScript(script, callback);
}
function deregister () {
pras.deregister_plugin_path().then(displayResult);
}
function register () {
var $ = querySelector('#register');
var path = $.querySelector('input[name=path]').value;
pras.register_plugin_path(path).then(displayResult);
}
function getStagingDir () {
const mkdirp = require('mkdirp');
const os = require('os');
const path = require('path');
const UUID = require('pure-uuid');
// create stagingDir
var id = new UUID(4).format();
var stagingDir = path.join(os.tmpdir(), id);
mkdirp(stagingDir);
return stagingDir;
}
function convertPathString (path) {
return path.replace(
new RegExp('\\\\', 'g'), '/').replace(new RegExp('//\\?/', 'g'), '');
}
function _publish () {
var publish_id = querySelector('#publish');
// var gui = $.querySelector('input[name=gui]').checked;
var gui = true;
var versionUp = publish_id.querySelector('input[name=version-up]').checked;
var audioOnly = publish_id.querySelector('input[name=audio-only]').checked;
var jsonSendPath = publish_id.querySelector('input[name=send-path]').value;
var jsonGetPath = publish_id.querySelector('input[name=get-path]').value;
if (jsonSendPath === '') {
// create temp staging directory on local
var stagingDir = convertPathString(getStagingDir());
// copy project file to stagingDir
_pype.csi.evalScript('$.pype.getProjectFileData();', function (result) {
const path = require('path');
const fs = require('fs');
displayResult(result);
var data = JSON.parse(result);
displayResult(stagingDir);
displayResult(data.projectfile);
var destination = convertPathString(path.join(stagingDir, data.projectfile));
displayResult('copy project file');
displayResult(data.projectfile);
displayResult(destination);
fs.copyFile(data.projectpath, destination, displayResult);
displayResult('project file copied!');
});
// set presets to jsx
pras.get_presets(_pype.ENV.AVALON_PROJECT, function (presetResult) {
displayResult('result from get_presets: ' + presetResult);
// publishing file
_pype.csi.evalScript('$.pype.getPyblishRequest("' + stagingDir + '", ' + audioOnly + ');', function (r) {
displayResult(r);
// make sure the process will end if no instancess are returned
if (r === 'null') {
displayError('Publish cannot be finished. Please fix the previously pointed problems');
return null;
rename () {
let renameId = document.querySelector('#rename');
let data = {};
data.ep = renameId.querySelector('input[name=episode]').value;
data.epSuffix = renameId.querySelector('input[name=ep_suffix]').value;
if (!data.ep) {
this.csi.evalScript('$.pype.alert_message("' + 'Need to fill episode code' + '")');
return;
}
var request = JSON.parse(r);
displayResult(JSON.stringify(request));
if (!data.epSuffix) {
this.csi.evalScript('$.pype.alert_message("' + 'Need to fill episode longer suffix' + '")');
return;
}
this.csi.evalScript(
'$.batchrenamer.renameTargetedTextLayer( ' + JSON.stringify(
data) + ' );', function (result) {
console.info(result);
});
}
_pype.csi.evalScript('$.pype.encodeRepresentation(' + JSON.stringify(request) + ');', function (result) {
// create json for pyblish
const jsonfile = require('jsonfile');
const fs = require('fs');
var jsonSendPath = stagingDir + '_send.json';
var jsonGetPath = stagingDir + '_get.json';
_bindButtons() {
var self = this;
$('#btn-publish').click(function () {
self.publish();
});
var publish_id = querySelector('#publish');
publish_id.querySelector('input[name=send-path]').value = jsonSendPath;
publish_id.querySelector('input[name=get-path]').value = jsonGetPath;
$('#btn-rename').click(function () {
self.rename();
});
}
var jsonContent = JSON.parse(result);
jsonfile.writeFile(jsonSendPath, jsonContent);
var checkingFile = function (path) {
var timeout = 10;
setTimeout(function () {
if (fs.existsSync(path)) {
displayResult('path were rendered: ' + path);
// send json to pyblish
var dataToPublish = {
"adobePublishJsonPathSend": jsonSendPath,
"adobePublishJsonPathGet": jsonGetPath,
"gui": gui,
"publishPath": convertPathString(_pype.ENV.PUBLISH_PATH),
"project": _pype.ENV.AVALON_PROJECT,
"asset": _pype.ENV.AVALON_ASSET,
"task": _pype.ENV.AVALON_TASK,
"workdir": convertPathString(_pype.ENV.AVALON_WORKDIR),
"host": _pype.ENV.AVALON_APP
/**
* Normalize slashes in path string
* @param {String} path
*/
static convertPathString (path) {
return path.replace(
new RegExp('\\\\', 'g'), '/').replace(new RegExp('//\\?/', 'g'), '');
}
/**
* Gather all user UI options for publishing
*/
_gatherPublishUI() {
var publishId = document.querySelector('#publish');
var publishUI = {
"publishId": publishId,
"versionUp": publishId.querySelector('input[name=version-up]').checked,
"audioOnly": publishId.querySelector('input[name=audio-only]').checked,
"jsonSendPath": publishId.querySelector('input[name=send-path]').value,
"jsonGetPath": publishId.querySelector('input[name=get-path]').value
}
this.publishUI = publishUI;
return publishUI;
}
_getStagingDir() {
const path = require('path');
const UUID = require('pure-uuid');
const os = require('os');
const id = new UUID(4).format();
return path.join(os.tmpdir(), id);
}
/**
* Create staging directories and copy project files
* @param {object} projectData Project JSON data
*/
_copyProjectFiles(projectData) {
const path = require('path');
const fs = require('fs');
const mkdirp = require('mkdirp');
this.stagingDir = this._getStagingDir();
console.info(`Creating directory [ ${this.stagingDir} ]`);
mkdirp.sync(this.stagingDir)
let stagingDir = Pype.convertPathString(this.stagingDir);
const destination = Pype.convertPathString(
path.join(stagingDir, projectData.projectfile));
console.info(`Copying files from [ ${projectData.projectpath} ] -> [ ${destination} ]`);
fs.copyFileSync(projectData.projectpath, destination);
console.info("Project files copied.")
}
_encodeRepresentation(repre) {
var self = this;
return new Promise(function(resolve, reject) {
self.csi.evalScript('$.pype.encodeRepresentation(' + JSON.stringify(repre) + ');', (result) => {
if (result == "EvalScript error.") {
reject(result);
}
displayResult('dataToPublish: ' + JSON.stringify(dataToPublish));
pras.publish(dataToPublish).then(function (result) {
displayResult(
'pype.js:publish < pras.publish: ' + JSON.stringify(result));
// check if resulted path exists as file
if (fs.existsSync(result.return_data_path)) {
// read json data from resulted path
displayResult('Updating metadata of clips after publishing');
resolve(result);
});
});
}
// jsonfile.readFile(result.return_data_path, function (json) {
// _pype.csi.evalScript('$.pype.dumpPublishedInstancesToMetadata(' + JSON.stringify(json) + ');');
// });
_getPyblishRequest(stagingDir) {
var self = this;
return new Promise(function(resolve, reject) {
console.log(`Called with ${stagingDir} and ${self.publishUI.audioOnly}`);
self.csi.evalScript("$.pype.getPyblishRequest('" + stagingDir + "', '" + self.publishUI.audioOnly + "');", (result) => {
if (result === "null" || result === "EvalScript error.") {
console.error(`cannot create publish request data ${result}`);
reject("cannot create publish request data");
} else {
console.log(`Request generated: ${result}`);
resolve(result);
}
});
});
}
// version up project
if (versionUp) {
displayResult('Saving new version of the project file');
_pype.csi.evalScript('$.pype.versionUpWorkFile();');
}
} else {
// if resulted path file not existing
displayResult('Publish has not been finished correctly. Hit Publish again to publish from already rendered data, or Reset to render all again.');
}
publish() {
this._gatherPublishUI();
if (this.publishUI.jsonSendPath === "") {
// path is empty, so we first prepare data for publishing
// and create json
console.log("Gathering project data ...")
this.csi.evalScript('$.pype.getProjectFileData();', (result) => {
this._copyProjectFiles(JSON.parse(result))
// create request and start encoding
// after that is done, we should recieve event and continue in
// _encodingDone()
console.log("Creating request ...")
this._getPyblishRequest(Pype.convertPathString(this.stagingDir))
.then(result => {
console.log("Encoding ...");
this._encodeRepresentation(JSON.parse(result))
}, error => {
console.error(`failed to publish: ${error}`);
});
} else {
displayResult('waiting');
checkingFile(path);
}
}, timeout);
};
checkingFile(jsonContent.waitingFor);
});
});
});
} else {
// send json to pyblish
pras.publish(jsonSendPath, jsonGetPath, gui).then(function (result) {
const jsonfile = require('jsonfile');
const fs = require('fs');
// check if resulted path exists as file
if (fs.existsSync(result.get_json_path)) {
// read json data from resulted path
displayResult('Updating metadata of clips after publishing');
jsonfile.readFile(result.get_json_path, function (json) {
_pype.csi.evalScript('$.pype.dumpPublishedInstancesToMetadata(' + JSON.stringify(json) + ');');
});
// version up project
if (versionUp) {
displayResult('Saving new version of the project file');
_pype.csi.evalScript('$.pype.versionUpWorkFile();');
});
} else {
// load request
var request = require(this.publishUI.jsonSendPath);
this.pras.publish(request)
.then((result) => {
const fs = require('fs');
if (fs.existsSync(result.return_data_path)) {
this.csi.evalScript('$.pype.dumpPublishedInstancesToMetadata(' + JSON.stringify(result) + ');');
if (this.publishUI.versionUp) {
console.log('Saving new version of the project file');
this.csi.evalScript('$.pype.versionUpWorkFile();');
}
} else {
console.error("Publish has not finished correctly")
throw "Publish has not finished correctly";
}
});
}
} else {
// if resulted path file not existing
displayResult('Publish has not been finished correctly. Hit Publish again to publish from already rendered data, or Reset to render all again.');
}
});
}
}
_encodingDone(event) {
var dataToPublish = {
"adobePublishJsonPathSend": this.publishUI.jsonSendPath,
"adobePublishJsonPathGet": this.publishUI.jsonGetPath,
"gui": true,
"publishPath": Pype.convertPathString(this.env.PUBLISH_PATH),
"project": this.env.AVALON_PROJECT,
"asset": this.env.AVALON_ASSET,
"task": this.env.AVALON_TASK,
"workdir": Pype.convertPathString(this.env.ENV.AVALON_WORKDIR),
"host": this.env.ENV.AVALON_APP
}
this.pras.publish(dataToPublish)
.then((result) => {
const fs = require('fs');
if (fs.existsSync(result.return_data_path)) {
if (this.publishUI.versionUp) {
console.log('Saving new version of the project file');
this.csi.evalScript('$.pype.versionUpWorkFile();');
}
} else {
console.error("Publish has not finished correctly")
throw "Publish has not finished correctly";
}
});
}
}
function context () {
var $ = querySelector('#context');
var project = $.querySelector('input[name=project]').value;
var asset = $.querySelector('input[name=asset]').value;
var task = $.querySelector('input[name=task]').value;
var app = $.querySelector('input[name=app]').value;
pras.context(project, asset, task, app).then(displayResult);
}
function tc (timecode) {
var seconds = timecodes.toSeconds(timecode);
var timec = timecodes.fromSeconds(seconds);
displayResult(seconds);
displayResult(timec);
}
function rename () {
var $ = querySelector('#rename');
var data = {};
data.ep = $.querySelector('input[name=episode]').value;
data.epSuffix = $.querySelector('input[name=ep_suffix]').value;
if (!data.ep) {
_pype.csi.evalScript('$.pype.alert_message("' + 'Need to fill episode code' + '")');
return;
}
if (!data.epSuffix) {
_pype.csi.evalScript('$.pype.alert_message("' + 'Need to fill episode longer suffix' + '")');
return;
}
_pype.csi.evalScript(
'$.batchrenamer.renameTargetedTextLayer( ' + JSON.stringify(
data) + ' );', function (result) {
displayResult(result);
});
}
// bind buttons
$('#btn-getRernderAnimation').click(function () {
loadAnimationRendersToTimeline();
$(document).ready(function() {
new Pype();
});
// -------------------------------------------------------
$('#btn-rename').click(function () {
rename();
});
$('#btn-set-context').click(function () {
context();
});
$('#btn-register').click(function () {
register();
});
$('#btn-deregister').click(function () {
deregister();
});
$('#btn-publish').click(function () {
_publish();
});
$('#btn-send-reset').click(function () {
var $ = querySelector('#publish');
$.querySelector('input[name=send-path]').value = '';
});
$('#btn-get-reset').click(function () {
var $ = querySelector('#publish');
$.querySelector('input[name=get-path]').value = '';
});
$('#btn-get-active-sequence').click(function () {
evalScript('$.pype.getActiveSequence();');
});
$('#btn-get-selected').click(function () {
$.querySelector('#output').html('getting selected clips info ...');
evalScript('$.pype.getSelectedItems();');
});
$('#btn-get-env').click(function () {
displayResult(window.ENV);
});
$('#btn-get-projectitems').click(function () {
evalScript('$.pype.getProjectItems();');
});
$('#btn-metadata').click(function () {
var $ = querySelector('#publish');
var path = $.querySelector('input[name=get-path]').value;
const jsonfile = require('jsonfile');
displayResult(path);
jsonfile.readFile(path, function (json) {
_pype.csi.evalScript(
'$.pype.dumpPublishedInstancesToMetadata(' + JSON.stringify(json) + ');');
displayResult('Metadata of clips after publishing were updated');
});
});
$('#btn-get-frame').click(function () {
_pype.csi.evalScript('$._PPP_.exportCurrentFrameAsPNG();', function (result) {
displayResult(result);
});
});
$('#btn-tc').click(function () {
tc('00:23:47:10');
});
$('#btn-generateRequest').click(function () {
evalScript('$.pype.getPyblishRequest();');
});
$('#btn-newWorkfileVersion').click(function () {
displayResult('Saving new version of the project file');
_pype.csi.evalScript('$.pype.versionUpWorkFile();');
});
$('#btn-testing').click(function () {
var data = {
"adobePublishJsonPathSend": "C:/Users/jezsc/_PYPE_testing/testing_data/premiere/95478408-91ee-4522-81f6-f1689060664f_send.json",
"adobePublishJsonPathGet": "C:/Users/jezsc/_PYPE_testing/testing_data/premiere/95478408-91ee-4522-81f6-f1689060664f_get.json",
"gui": true,
"project": "J01_jakub_test",
"asset": "editorial",
"task": "conforming",
"workdir": "C:/Users/jezsc/_PYPE_testing/projects/J01_jakub_test/editorial/work/conforming",
"publishPath": "C:/Users/jezsc/CODE/pype-setup/repos/pype/pype/plugins/premiere/publish",
"host": "premiere"
}
// var data = {"adobePublishJsonPathSend":"C:/Users/jezsc/AppData/Local/Temp/887ed0c3-d772-4105-b285-847ef53083cd_send.json","adobePublishJsonPathGet":"C:/Users/jezsc/AppData/Local/Temp/887ed0c3-d772-4105-b285-847ef53083cd_get.json","gui":true,"publishPath":"C:/Users/jezsc/CODE/pype-setup/repos/pype/pype/plugins/premiere/publish","project":"J01_jakub_test","asset":"editorial","task":"conforming","workdir":"C:/Users/jezsc/_PYPE_testing/projects/J01_jakub_test/editorial/work/conforming","host":"premiere"}
pras.publish(data);
});
_pype.getEnv();

View file

@ -0,0 +1,429 @@
/* esversion:6, global CSInterface, $, cep_node, querySelector, pras, SystemPath, displayResult */
var csi = new CSInterface();
var output = document.getElementById('output');
var process = require('process');
var timecodes = require('node-timecodes');
function displayResult (r) {
console.log(r);
_pype.csi.evalScript('$.writeln( ' + JSON.stringify(r) + ' );');
output.classList.remove('error');
output.innerText = r;
_pype.csi.evalScript('$.pype.log( ' + JSON.stringify(r) + ' );');
}
function displayError (e) {
_pype.csi.evalScript('$.pype.alert_message( ' + JSON.stringify(e) + ' )');
output.classList.add('error');
output.innerText = e;
}
var _pype = {
csi: csi,
rootFolderPath: csi.getSystemPath(SystemPath.EXTENSION),
displayResult: displayResult,
displayError: displayError,
getEnv: function () {
_pype.csi.evalScript('$.pype.getProjectFileData();', function (result) {
process.env.EXTENSION_PATH = _pype.rootFolderPath;
_pype.ENV = process.env;
console.log(result);
console.log(_pype.rootFolderPath);
var resultData = JSON.parse(result);
for (var key in resultData) {
_pype.ENV[key] = resultData[key];
}
csi.evalScript('$.pype.setEnvs(' + JSON.stringify(_pype.ENV) + ')');
});
}
};
// function renderClips () {
// _pype.csi.evalScript('$.pype.transcodeExternal(' + pras.rootFolderPath + ');', function (result) {
// displayResult(result);
// });
// }
function loadExtensionDependencies () {
// get extension path
var extensionPath = _pype.csi.getSystemPath(SystemPath.EXTENSION);
// get the appName of the currently used app. For Premiere Pro it's "PPRO"
var appName = _pype.csi.hostEnvironment.appName;
console.log('App name: ' + appName);
// load general JS scripts from `extensionPath/lib/`
_pype.csi.evalScript(
'$._ext.evalJSFiles("' + extensionPath + '" )');
console.log('js load done');
// load all available JSX scripts from `extensionPath/jsx/*` with subfolders
_pype.csi.evalScript(
'$._ext.evalJSXFiles("' + extensionPath + '", "' + appName + '")');
console.log('jsx load done');
_pype.csi.evalScript('$._PPP_.updateEventPanel( "' + 'all plugins are loaded' + '" )');
}
// run all at loading
loadExtensionDependencies();
function querySelector (elementId) {
return document.querySelector(elementId);
}
function loadAnimationRendersToTimeline () {
// it will get type of asset and extension from input
// and start loading script from jsx
var $ = querySelector('#load');
var data = {};
data.subset = $.querySelector('input[name=type]').value;
data.subsetExt = $.querySelector('input[name=ext]').value;
var requestList = [];
// get all selected clips
_pype.csi.evalScript('$.pype.getClipsForLoadingSubsets( "' + data.subset + '" )', function (result) {
// TODO: need to check if the clips are already created and this is just updating to last versions
var resultObj = JSON.parse(result);
var instances = resultObj[0];
var numTracks = resultObj[1];
var key = '';
// creating requesting list of dictionaries
for (key in instances) {
var clipData = {};
clipData.parentClip = instances[key];
clipData.asset = key;
clipData.subset = data.subset;
clipData.representation = data.subsetExt;
requestList.push(clipData);
}
if (requestList.length < 1) {
_pype.csi.evalScript(
'$.pype.alert_message("' + 'Need to select at least one clip' + '")');
return;
}
// gets data from mongodb
pras.load_representations(_pype.ENV.AVALON_PROJECT, requestList).then(
function (avalonData) {
// creates or updates data on timeline
var makeData = {};
makeData.binHierarchy = data.subset + '/' + data.subsetExt;
makeData.clips = avalonData;
makeData.numTracks = numTracks;
_pype.csi.evalScript('$.pype.importFiles( ' + JSON.stringify(makeData) + ' )');
}
);
});
}
function evalScript (script) {
var callback = function (result) {
displayResult(result);
};
_pype.csi.evalScript(script, callback);
}
function deregister () {
pras.deregister_plugin_path().then(displayResult);
}
function register () {
var $ = querySelector('#register');
var path = $.querySelector('input[name=path]').value;
pras.register_plugin_path(path).then(displayResult);
}
function getStagingDir () {
const mkdirp = require('mkdirp');
const os = require('os');
const path = require('path');
const UUID = require('pure-uuid');
// create stagingDir
var id = new UUID(4).format();
var stagingDir = path.join(os.tmpdir(), id);
mkdirp(stagingDir);
return stagingDir;
}
function convertPathString (path) {
return path.replace(
new RegExp('\\\\', 'g'), '/').replace(new RegExp('//\\?/', 'g'), '');
}
function _publish () {
var publish_id = querySelector('#publish');
// var gui = $.querySelector('input[name=gui]').checked;
var gui = true;
var versionUp = publish_id.querySelector('input[name=version-up]').checked;
var audioOnly = publish_id.querySelector('input[name=audio-only]').checked;
var jsonSendPath = publish_id.querySelector('input[name=send-path]').value;
var jsonGetPath = publish_id.querySelector('input[name=get-path]').value;
if (jsonSendPath === '') {
// create temp staging directory on local
var stagingDir = convertPathString(getStagingDir());
// copy project file to stagingDir
_pype.csi.evalScript('$.pype.getProjectFileData();', function (result) {
const path = require('path');
const fs = require('fs');
displayResult(result);
var data = JSON.parse(result);
displayResult(stagingDir);
displayResult(data.projectfile);
var destination = convertPathString(path.join(stagingDir, data.projectfile));
displayResult('copy project file');
displayResult(data.projectfile);
displayResult(destination);
fs.copyFile(data.projectpath, destination, displayResult);
displayResult('project file copied!');
});
displayResult("getting presets ...")
// set presets to jsx
pras.get_presets(_pype.ENV.AVALON_PROJECT, function (presetResult) {
displayResult('result from get_presets: ' + presetResult);
// publishing file
_pype.csi.evalScript('$.pype.getPyblishRequest("' + stagingDir + '", ' + audioOnly + ');', function (r) {
displayResult(r);
// make sure the process will end if no instancess are returned
if (r === 'null') {
displayError('Publish cannot be finished. Please fix the previously pointed problems');
return null;
}
var request = JSON.parse(r);
displayResult(JSON.stringify(request));
displayResult("------------------------------------")
_pype.csi.evalScript('$.pype.encodeRepresentation(' + JSON.stringify(request) + ');', function (result) {
// create json for pyblish
displayResult(result)
const jsonfile = require('jsonfile');
const fs = require('fs');
var publish_id = querySelector('#publish');
publish_id.querySelector('input[name=send-path]').value = jsonSendPath;
publish_id.querySelector('input[name=get-path]').value = jsonGetPath;
var jsonContent = JSON.parse(result);
jsonfile.writeFile(jsonSendPath, jsonContent);
var checkingFile = function (path) {
var timeout = 10;
setTimeout(function () {
if (fs.existsSync(path)) {
displayResult('path were rendered: ' + path);
// send json to pyblish
var dataToPublish = {
"adobePublishJsonPathSend": jsonSendPath,
"adobePublishJsonPathGet": jsonGetPath,
"gui": gui,
"publishPath": convertPathString(_pype.ENV.PUBLISH_PATH),
"project": _pype.ENV.AVALON_PROJECT,
"asset": _pype.ENV.AVALON_ASSET,
"task": _pype.ENV.AVALON_TASK,
"workdir": convertPathString(_pype.ENV.AVALON_WORKDIR),
"host": _pype.ENV.AVALON_APP
}
displayResult('dataToPublish: ' + JSON.stringify(dataToPublish));
pras.publish(dataToPublish).then(function (result) {
displayResult(
'pype.js:publish < pras.publish: ' + JSON.stringify(result));
// check if resulted path exists as file
if (fs.existsSync(result.return_data_path)) {
// read json data from resulted path
displayResult('Updating metadata of clips after publishing');
// jsonfile.readFile(result.return_data_path, function (json) {
// _pype.csi.evalScript('$.pype.dumpPublishedInstancesToMetadata(' + JSON.stringify(json) + ');');
// });
// version up project
if (versionUp) {
displayResult('Saving new version of the project file');
_pype.csi.evalScript('$.pype.versionUpWorkFile();');
}
} else {
// if resulted path file not existing
displayResult('Publish has not been finished correctly. Hit Publish again to publish from already rendered data, or Reset to render all again.');
}
});
} else {
displayResult('waiting');
checkingFile(path);
}
}, timeout);
};
checkingFile(jsonContent.waitingFor);
});
});
});
} else {
// send json to pyblish
pras.publish(jsonSendPath, jsonGetPath, gui).then(function (result) {
const jsonfile = require('jsonfile');
const fs = require('fs');
// check if resulted path exists as file
if (fs.existsSync(result.get_json_path)) {
// read json data from resulted path
displayResult('Updating metadata of clips after publishing');
jsonfile.readFile(result.get_json_path, function (json) {
_pype.csi.evalScript('$.pype.dumpPublishedInstancesToMetadata(' + JSON.stringify(json) + ');');
});
// version up project
if (versionUp) {
displayResult('Saving new version of the project file');
_pype.csi.evalScript('$.pype.versionUpWorkFile();');
}
} else {
// if resulted path file not existing
displayResult('Publish has not been finished correctly. Hit Publish again to publish from already rendered data, or Reset to render all again.');
}
});
}
}
function context () {
var $ = querySelector('#context');
var project = $.querySelector('input[name=project]').value;
var asset = $.querySelector('input[name=asset]').value;
var task = $.querySelector('input[name=task]').value;
var app = $.querySelector('input[name=app]').value;
pras.context(project, asset, task, app).then(displayResult);
}
function tc (timecode) {
var seconds = timecodes.toSeconds(timecode);
var timec = timecodes.fromSeconds(seconds);
displayResult(seconds);
displayResult(timec);
}
function rename () {
var $ = querySelector('#rename');
var data = {};
data.ep = $.querySelector('input[name=episode]').value;
data.epSuffix = $.querySelector('input[name=ep_suffix]').value;
if (!data.ep) {
_pype.csi.evalScript('$.pype.alert_message("' + 'Need to fill episode code' + '")');
return;
}
if (!data.epSuffix) {
_pype.csi.evalScript('$.pype.alert_message("' + 'Need to fill episode longer suffix' + '")');
return;
}
_pype.csi.evalScript(
'$.batchrenamer.renameTargetedTextLayer( ' + JSON.stringify(
data) + ' );', function (result) {
displayResult(result);
});
}
// bind buttons
$('#btn-getRernderAnimation').click(function () {
loadAnimationRendersToTimeline();
});
$('#btn-rename').click(function () {
rename();
});
$('#btn-set-context').click(function () {
context();
});
$('#btn-register').click(function () {
register();
});
$('#btn-deregister').click(function () {
deregister();
});
$('#btn-publish').click(function () {
_publish();
});
$('#btn-send-reset').click(function () {
var $ = querySelector('#publish');
$.querySelector('input[name=send-path]').value = '';
});
$('#btn-get-reset').click(function () {
var $ = querySelector('#publish');
$.querySelector('input[name=get-path]').value = '';
});
$('#btn-get-active-sequence').click(function () {
evalScript('$.pype.getActiveSequence();');
});
$('#btn-get-selected').click(function () {
$.querySelector('#output').html('getting selected clips info ...');
evalScript('$.pype.getSelectedItems();');
});
$('#btn-get-env').click(function () {
displayResult(window.ENV);
});
$('#btn-get-projectitems').click(function () {
evalScript('$.pype.getProjectItems();');
});
$('#btn-metadata').click(function () {
var $ = querySelector('#publish');
var path = $.querySelector('input[name=get-path]').value;
const jsonfile = require('jsonfile');
displayResult(path);
jsonfile.readFile(path, function (json) {
_pype.csi.evalScript(
'$.pype.dumpPublishedInstancesToMetadata(' + JSON.stringify(json) + ');');
displayResult('Metadata of clips after publishing were updated');
});
});
$('#btn-get-frame').click(function () {
_pype.csi.evalScript('$._PPP_.exportCurrentFrameAsPNG();', function (result) {
displayResult(result);
});
});
$('#btn-tc').click(function () {
tc('00:23:47:10');
});
$('#btn-generateRequest').click(function () {
evalScript('$.pype.getPyblishRequest();');
});
$('#btn-newWorkfileVersion').click(function () {
displayResult('Saving new version of the project file');
_pype.csi.evalScript('$.pype.versionUpWorkFile();');
});
$('#btn-testing').click(function () {
var data = {
"adobePublishJsonPathSend": "C:/Users/jezsc/_PYPE_testing/testing_data/premiere/95478408-91ee-4522-81f6-f1689060664f_send.json",
"adobePublishJsonPathGet": "C:/Users/jezsc/_PYPE_testing/testing_data/premiere/95478408-91ee-4522-81f6-f1689060664f_get.json",
"gui": true,
"project": "J01_jakub_test",
"asset": "editorial",
"task": "conforming",
"workdir": "C:/Users/jezsc/_PYPE_testing/projects/J01_jakub_test/editorial/work/conforming",
"publishPath": "C:/Users/jezsc/CODE/pype-setup/repos/pype/pype/plugins/premiere/publish",
"host": "premiere"
}
// var data = {"adobePublishJsonPathSend":"C:/Users/jezsc/AppData/Local/Temp/887ed0c3-d772-4105-b285-847ef53083cd_send.json","adobePublishJsonPathGet":"C:/Users/jezsc/AppData/Local/Temp/887ed0c3-d772-4105-b285-847ef53083cd_get.json","gui":true,"publishPath":"C:/Users/jezsc/CODE/pype-setup/repos/pype/pype/plugins/premiere/publish","project":"J01_jakub_test","asset":"editorial","task":"conforming","workdir":"C:/Users/jezsc/_PYPE_testing/projects/J01_jakub_test/editorial/work/conforming","host":"premiere"}
pras.publish(data);
});
_pype.getEnv();

View file

@ -1,124 +1,67 @@
/* global _pype */
// connecting pype module pype rest api server (pras)
const fetch = require('node-fetch');
/* eslint-env node, es2018 */
// connecting pype module pype rest api server (pras)
class PypeRestApiClient {
constructor(env) {
this.env = env;
}
var pras = {
/**
* Return url for pype rest api server service
* @return {url string}
*/
getApiServerUrl: function () {
var url = _pype.ENV.PYPE_REST_API_URL;
_getApiServerUrl() {
var url = this.env.PYPE_REST_API_URL;
return url
},
getRequestFromRestApiServer: async function(url, options, callback) {
_pype.displayResult('url: ' + url);
}
// define options in case there is null comming
if (options === null) {
options = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
}
_pype.displayResult('options: ' + JSON.stringify(options));
// send post request to rest api server
try {
const res = await fetch(url);
const json = await res.json();
if (isPypeData(json)) {
_pype.displayResult(json.data);
callback(json.data);
} else {
_pype.displayError('Data comming from `{url}` are not correct'.format({url: url}));
callback(null);
}
} catch (error) {
_pype.displayError('Data comming from `{url}` are not correct.\n\nError: {error}'.format({url: url, error: error}));
}
},
load_representations: function (projectName, requestList) {
// preparation for getting representations from api server
console.log('Load Represention:projectName: ' + projectName);
console.log('Load Represention:requestList: ' + requestList);
},
get_presets: function (projectName, callback) {
var template = '{serverUrl}/adobe/presets/{projectName}';
var url = template.format({serverUrl: pras.getApiServerUrl(), projectName: projectName});
_pype.displayResult(url);
// send request to server
pras.getRequestFromRestApiServer(url, options = null, function (result) {
if (result === null) {
_pype.displayError('No data for `{projectName}` project in database'.format({projectName: projectName}));
return null
} else {
// send the data into jsx and write to module's global variable
_pype.csi.evalScript('$.pype.setProjectPreset(' + JSON.stringify(result) + ');', function (resultBack) {
_pype.displayResult('$.pype.setProjectPreset(): ' + resultBack);
callback(resultBack);
// test the returning presets data from jsx if they are there
// _pype.csi.evalScript(
// '$.pype.getProjectPreset();',
// function (resultedPresets) {
// _pype.displayResult(
// '$.pype.getProjectPreset(): ' + resultedPresets);
// });
});
}
});
},
publish: function (data) {
var template = '{serverUrl}/adobe/publish';
var url = template.format({serverUrl: pras.getApiServerUrl()});
var _options = {
method: 'POST',
body: JSON.stringify(data),
/**
* Return JSON from server. This will wait for result.
* @todo handle status codes and non-json data
* @param {String} url server url
* @param {object} options request options
*/
async getResponseFromRestApiServer(url, options = {}) {
const fetch = require('node-fetch');
let defaults = {
method: "GET",
headers: {
'Content-Type': 'application/json'
"Content-Type": "application/json"
}
};
_pype.displayResult('__ publish:url ' + url);
_pype.displayResult('__ publish:_options ' + JSON.stringify(_options));
// publish data with rest api server
pras.getRequestFromRestApiServer(url, _options, function (result) {
if (result === null) {
_pype.displayError('No data for `{projectName}` project in database'.format({projectName: projectName}));
return null
} else {
_pype.displayResult('pras.publish.getRequestFromRestApiServer: ' + JSON.stringify(result));
return result
}
// preparation for publishing with rest api server
});
},
context: function (project, asset, task, app) {
// getting context of project
}
};
String.prototype.format = function (arguments) {
var this_string = '';
for (var char_pos = 0; char_pos < this.length; char_pos++) {
this_string = this_string + this[char_pos];
}
let settings = {...defaults, ...options}
const res = await fetch(url, settings);
return await res.json();
}
for (var key in arguments) {
var string_key = '{' + key + '}'
this_string = this_string.replace(new RegExp(string_key, 'g'), arguments[key]);
}
return this_string;
};
function isPypeData(v) {
try {
return Object.prototype.hasOwnProperty.call(v, 'success');
} catch (e) {
/* console.error("not a dict",e); */
return false;
/**
* Return presets for project from server
* @param {String} projectName
*/
async get_presets(projectName) {
let server = this._getApiServerUrl();
let url = `${server}/adobe/presets/${projectName}`;
console.log("connecting ...");
let response = await this.getResponseFromRestApiServer(url)
console.log("got presets:");
console.log(response.data);
return response.data;
}
async publish(data) {
let server = this._getApiServerUrl();
let url = `${server}/adobe/publish`;
let headers = {
"Content-Type": "application/json"
}
let response = await this.getResponseFromRestApiServer(
url, {method: 'POST', headers: headers, body: data});
return response.data;
}
}