From ba9524d06f93aa7a7ecfa630b6a441e56ddbc88f Mon Sep 17 00:00:00 2001 From: Jakub Jezek Date: Mon, 13 Apr 2020 19:17:03 +0200 Subject: [PATCH] feat(ppro): wip on extension --- .../premiere/extensions/com.pype/jsx/pype.jsx | 270 ++++++++---------- .../extensions/com.pype/jsx/testingCode._jsx | 11 + pype/premiere/lib.py | 11 +- pype/premiere/ppro/js/pype.js | 130 +++++---- pype/premiere/ppro/js/pype_restapi_client.js | 83 ++++-- 5 files changed, 258 insertions(+), 247 deletions(-) create mode 100644 pype/premiere/extensions/com.pype/jsx/testingCode._jsx diff --git a/pype/premiere/extensions/com.pype/jsx/pype.jsx b/pype/premiere/extensions/com.pype/jsx/pype.jsx index 90b6ce326c..85dcc912a3 100644 --- a/pype/premiere/extensions/com.pype/jsx/pype.jsx +++ b/pype/premiere/extensions/com.pype/jsx/pype.jsx @@ -13,11 +13,12 @@ if (ExternalObject.AdobeXMPScript === undefined) { // variable pype is defined in pypeAvalon.jsx $.pype = { + presets: null, addNewTrack: function (numTracks) { app.enableQE(); var sequence = app.project.activeSequence; var activeSequence = qe.project.getActiveSequence(); - activeSequence.addTracks(numTracks, sequence.videoTracks.numTracks, 0) + activeSequence.addTracks(numTracks, sequence.videoTracks.numTracks, 0); for (var t = 0; t < sequence.videoTracks.numTracks; t++) { var videoTrack = sequence.videoTracks[t]; @@ -30,7 +31,6 @@ $.pype = { // $.writeln(videoTrack); } }, - searchForBinWithName: function (nameToFind, folderObject) { // deep-search a folder by name in project var deepSearchBin = function (inFolder) { @@ -40,9 +40,10 @@ $.pype = { for (var i = 0; i < inFolder.children.numItems; i++) { if (inFolder.children[i] && inFolder.children[i].type === 2) { var foundBin = deepSearchBin(inFolder.children[i]); - if (foundBin) return foundBin; + if (foundBin) + return foundBin; + } } - } } return undefined; }; @@ -52,7 +53,6 @@ $.pype = { return deepSearchBin(folderObject); } }, - createDeepBinStructure: function (hierarchyString) { var parents = hierarchyString.split('/'); @@ -77,7 +77,8 @@ $.pype = { var seq = app.project.activeSequence; var numVTracks = seq.videoTracks.numTracks; - var addInTrack = (numTracks === 1) ? (origNumTracks) + var addInTrack = (numTracks === 1) + ? (origNumTracks) : (numVTracks - numTracks + trackOrder); $.writeln('\n___name: ' + binClip.name); $.writeln('numVTracks: ' + numVTracks + ', trackOrder: ' + trackOrder + ', numTracks: ' + numTracks + ', origNumTracks: ' + origNumTracks + ', addInTrack: ' + addInTrack); @@ -138,10 +139,8 @@ $.pype = { for (var p = 0; p < namesToSetToClips.length; p++) { // check if the clip is not in bin items alrady if (!include(binItemNames, namesToSetToClips[p])) { - app.project.importFiles([pathsToImport[p]], - 1, // suppress warnings - parent, - 0); // import as numbered stills + app.project.importFiles([pathsToImport[p]], 1, // suppress warnings + parent, 0); // import as numbered stills for (var pi = 0; pi < parent.children.numItems; pi++) { if (namesToGetFromBin[p] === parent.children[pi].name) { @@ -163,10 +162,8 @@ $.pype = { } } } else { - app.project.importFiles(pathsToImport, - 1, // suppress warnings - parent, - 0); // import as numbered stills + app.project.importFiles(pathsToImport, 1, // suppress warnings + parent, 0); // import as numbered stills for (var pi = 0; pi < parent.children.numItems; pi++) { parent.children[pi].name = namesToSetToClips[i]; start = data.clips[namesToSetToClips[i]]['parentClip']['start'] @@ -186,7 +183,6 @@ $.pype = { }, setEnvs: function (env) { for (var key in env) { - $.writeln((key + ': ' + env[key])); $.setenv(key, env[key]); } }, @@ -197,9 +193,7 @@ $.pype = { }, convertPathString: function (path) { - return path.replace( - new RegExp('\\\\', 'g'), '/').replace(new RegExp('//\\?/', 'g'), '').replace( - new RegExp('/', 'g'), '\\').replace('UNC', '\\'); + return path.replace(new RegExp('\\\\', 'g'), '/').replace(new RegExp('//\\?/', 'g'), '').replace(new RegExp('/', 'g'), '\\').replace('UNC', '\\'); }, getProjectFileData: function () { @@ -255,7 +249,7 @@ $.pype = { var seq = qe.project.getSequenceAt(rootSeqCounter); // $.pype.log('\nSequence in root, guid: ' + seq ); for (var property in seq) { - if (seq.hasOwnProperty(property)) { + if (Object.prototype.hasOwnProperty.call(seq, property)) { $.pype.log('\nSequence in root: ' + seq); $.pype.log('qe sequence prop: ' + property); } @@ -265,7 +259,7 @@ $.pype = { } } - function objectIsSequence () { + function objectIsSequence() { var isSequence = false; for (var s = 0; s < app.project.sequences.numSequences; s++) { @@ -278,7 +272,7 @@ $.pype = { } // walk through bins recursively - function walkBins (item, source, rootBinCounter) { + function walkBins(item, source, rootBinCounter) { app.enableQE(); // $.pype.log('\nget clips for bin ' + item.name ); @@ -304,7 +298,7 @@ $.pype = { } // walk through sequences and video & audiotracks to find clip names in sequences - function getClipNames (seq, sequences) { + function getClipNames(seq, sequences) { for (var k = 0; k < sequences.length; k++) { // $.pype.log('getClipNames seq.guid ' + seq.guid ); // $.pype.log(' getClipNames sequences[k].id ' + sequences[k].sequenceID ); @@ -321,12 +315,12 @@ $.pype = { // $.pype.log('\n' + bin.name + ' ' + seq.name + ' ' + videoTrack.name + ' has ' + numOfClips + ' clips'); for (var m = 0; m < numOfClips; m++) { // var clip = app.project.sequences[k].videoTracks[l].clips[m]; - // $.pype.log('clips in video tracks: ' + m + ' - ' + clip); //TrackItem, doesn't have name property + // $.pype.log('clips in video tracks: ' + m + ' - ' + clip); TrackItem, doesn't have name property // if a clip was deleted and another one added, the index of the new one is one or more higher while (clipCounter < numOfClips) { // undefined because of old clips if (videoTrack.getItemAt(m).name) { clipCounter++; - // $.pype.log('getClipNames ' + seq.name + ' ' + videoTrack.name + ' has ' + videoTrack.getItemAt(m).name); //Object + // $.pype.log('getClipNames ' + seq.name + ' ' + videoTrack.name + ' has ' + videoTrack.getItemAt(m).name); Object for (var s = 0; s < sequences.length; s++) { if (seq.guid === sequences[s].sequenceID) { @@ -402,7 +396,7 @@ $.pype = { } // walk through bins recursively - function walkBins (bin) { // eslint-disable-line no-unused-vars + function walkBins(bin) { // eslint-disable-line no-unused-vars app.enableQE(); // $.writeln('bin.name + ' has ' + bin.children.numItems); @@ -455,10 +449,7 @@ $.pype = { }, getImageSize: function () { - return { - h: app.project.activeSequence.frameSizeHorizontal, - v: app.project.activeSequence.frameSizeVertical - }; + return {h: app.project.activeSequence.frameSizeHorizontal, v: app.project.activeSequence.frameSizeVertical}; }, getInOutOfAll: function () { var seq = app.project.activeSequence; @@ -496,12 +487,7 @@ $.pype = { for (var m = 0; m < numOfClips; m++) { var clip = seq.videoTracks[l].clips[m]; if (clip.isSelected()) { - selected.push({ - clip: clip, - sequence: seq, - videoTrack: seq.videoTracks[l], - trackOrder: l - }); + selected.push({clip: clip, sequence: seq, videoTrack: seq.videoTracks[l], trackOrder: l}); } } } @@ -523,9 +509,7 @@ $.pype = { data.template = instances[i].template; data.version = instances[i].version; data.ftrackTaskID = instances[i].ftrackTask.substring(6, (instances[i].ftrackTask.length - 2)); - data.representation = instances[i].jsonData.representations[ - instances[i].families.families[0] - ]; + data.representation = instances[i].jsonData.representations[instances[i].families.families[0]]; // getting published path from transfers var transfers = instances[i].transfers.transfers; for (var t = 0; t < transfers.length; t++) { @@ -592,8 +576,7 @@ $.pype = { var pypeData = 'pypeData'; var pypeDataN = 'Pype Data'; var xmp = new XMPMeta(metadata); - var successfullyAdded = app.project.addPropertyToProjectMetadataSchema( - pypeData, pypeDataN, 2); + var successfullyAdded = app.project.addPropertyToProjectMetadataSchema(pypeData, pypeDataN, 2); var pypeDataValue = xmp.getProperty(kPProPrivateProjectMetadataURI, pypeData); $.writeln('__ pypeDataValue: ' + pypeDataValue); @@ -613,7 +596,7 @@ $.pype = { $.writeln('__ adding {}'); $.pype.setSequencePypeMetadata(sequence, {}); } - if ((pypeDataValue === undefined) || (!JSON.parse(pypeDataValue).hasOwnProperty ('clips'))) { + if ((pypeDataValue === undefined) || (!Object.prototype.hasOwnProperty.call(JSON.parse(pypeDataValue), 'clips'))) { $.writeln('__ getSequencePypeMetadata: returning null'); return null; } else { @@ -622,6 +605,33 @@ $.pype = { } } }, + /** + * Sets project presets into module's variable for other functions to use. + * @param inPresets {object} - dictionary object comming from js + * @return {bool}: true is success, false if not + */ + setProjectPreset: function (inPresets) { + // validating the incoming data are having `plugins` key + if (Object.prototype.hasOwnProperty.call(inPresets, 'plugins')) { + $.pype.presets = inPresets; + return true; + } else { + $.pype.alert_message('Presets are missing `plugins` key!'); + return false; + } + }, + /** + * Gets project presets from module's variable for other functions to use. + * @return {Object}: JSON string with presets dictionary or false if unsuccess + */ + getProjectPreset: function () { + if ($.pype.presets === null) { + $.pype.alert_message('Presets needs to be set before they could be required!'); + return false; + } else { + return JSON.stringify($.pype.presets); + } + }, /** * Return instance representation of clip * @param clip {object} - index of clip on videoTrack @@ -629,16 +639,16 @@ $.pype = { * @param videoTrack {object VideoTrack} - VideoTrack clip is in * @return {Object} */ - getClipAsInstance: function (clip, sequence, videoTrack, pypeData, presets) { + getClipAsInstance: function (clip, sequence, videoTrack, pypeData) { + var presets = JSON.parse($.pype.getProjectPreset()); // var clip = sequence.videoTracks.clips[clipIdx] - if ((clip.projectItem.type !== ProjectItemType.CLIP) && - (clip.mediaType !== 'Video')) { + if ((clip.projectItem.type !== ProjectItemType.CLIP) && (clip.mediaType !== 'Video')) { return false; } var pdClips = pypeData.clips; var hierarchy; var parents; - $.writeln('>> getClipAsInstance:clip.name ' + clip.name) + $.pype.log('>> getClipAsInstance:clip.name ' + clip.name) if (pdClips[clip.name]) { parents = pdClips[clip.name].parents; hierarchy = pdClips[clip.name].hierarchy; @@ -650,14 +660,14 @@ $.pype = { } var interpretation = clip.projectItem.getFootageInterpretation(); - $.writeln('>> getClipAsInstance:interpretation ' + interpretation) + $.pype.log('>> getClipAsInstance:interpretation ' + interpretation) var instance = {}; instance.publish = true; instance.family = 'clip'; instance.name = clip.name; instance.hierarchy = hierarchy; instance.parents = parents; - instance.representations = presets.rules_tasks.representations; + instance.representations = presets.premiere.rules_tasks.representations; // metadata var metadata = {}; // TODO: how to get colorspace clip info @@ -694,7 +704,7 @@ $.pype = { orders.push(selected[s].trackOrder); } var orderStart = Math.min.apply(null, orders); - $.writeln("__orderStart__: " + orderStart) + $.writeln('__orderStart__: ' + orderStart); for (var s = 0; s < selected.length; s++) { var selClipName = selected[s].clip.name; @@ -752,8 +762,8 @@ $.pype = { $.writeln('__ getSelectedClipsAsInstances:version: ' + version); var pypeData = $.pype.getSequencePypeMetadata(app.project.activeSequence); - $.writeln('__ getSelectedClipsAsInstances:typeof(pypeData): ' + typeof (pypeData)); - $.writeln('__ getSelectedClipsAsInstances:pypeData: ' + JSON.stringify(pypeData)); + $.pype.log('__ getSelectedClipsAsInstances:typeof(pypeData): ' + typeof(pypeData)); + $.pype.log('__ getSelectedClipsAsInstances:pypeData: ' + JSON.stringify(pypeData)); // check if the pype data are available and if not alert the user // we need to have avalable metadata for correct hierarchy @@ -766,15 +776,8 @@ $.pype = { var instances = []; var selected = $.pype.getSelectedItems(); for (var s = 0; s < selected.length; s++) { - $.writeln( - '__ getSelectedClipsAsInstances:selected[s].clip: ' + selected[s].clip); - var instance = $.pype.getClipAsInstance( - selected[s].clip, - selected[s].sequence, - selected[s].videoTrack, - pypeData, - presets - ); + $.pype.log('__ getSelectedClipsAsInstances:selected[s].clip: ' + selected[s].clip); + var instance = $.pype.getClipAsInstance(selected[s].clip, selected[s].sequence, selected[s].videoTrack, pypeData); if (instance !== false) { instance.version = version; instances.push(instance); @@ -805,10 +808,10 @@ $.pype = { getPyblishRequest: function (stagingDir, audioOnly) { var sequence = app.project.activeSequence; var settings = sequence.getSettings(); - $.writeln('__ stagingDir: ' + stagingDir) - $.writeln('__ audioOnly: ' + audioOnly) - $.writeln('__ sequence: ' + sequence) - $.writeln('__ settings: ' + settings) + $.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), @@ -817,7 +820,7 @@ $.pype = { hostVersion: $.getenv('AVALON_APP_NAME').split('_')[1], cwd: $.pype.convertPathString(app.project.path).split('\\').slice(0, -1).join('\\') }; - $.writeln('__ request: ' + request) + $.pype.log('__ request: ' + request) var sendInstances = []; var instances = $.pype.getSelectedClipsAsInstances(); @@ -852,38 +855,34 @@ $.pype = { var dec = Number(parts[1]); var main = Number(parts[0]); var sec; - var frames = (Number(('' + ((dec * fps) / 100)).split('.')[0])).pad(2); + var frames = (Number(('' + ( + (dec * fps) / 100)).split('.')[0])).pad(2); if (main > 59) { - sec = (Math.round(((Number(('' + (Math.round((main / 60) * 100) / 100).toFixed(2)).split('.')[1]) / 100) * 60))).pad(2); + sec = (Math.round(((Number(('' + ( + Math.round((main / 60) * 100) / 100).toFixed(2)).split('.')[1]) / 100) * 60))).pad(2); if (sec === 'NaN') { sec = '00'; }; } else { sec = main; }; - var min = (Number(('' + (main / 60)).split('.')[0])).pad(2); - var hov = (Number(('' + (main / 3600)).split('.')[0])).pad(2); + var min = (Number(('' + ( + main / 60)).split('.')[0])).pad(2); + var hov = (Number(('' + ( + main / 3600)).split('.')[0])).pad(2); return hov + ':' + min + ':' + sec + ':' + frames; }, exportThumbnail: function (name, family, version, outputPath, time, fps) { app.enableQE(); var activeSequence = qe.project.getActiveSequence(); // note: make sure a sequence is active in PPro UI - var file = name + '_' + - family + - '_v' + version + - '.jpg'; - var fullPathToFile = outputPath + - $._PPP_.getSep() + - file; - var expJPEG = activeSequence.exportFrameJPEG( - $.pype.convertSecToTimecode(time, fps), - $.pype.convertPathString(fullPathToFile).split('/').join($._PPP_.getSep()) - ); + var file = name + '_' + family + '_v' + version + '.jpg'; + var fullPathToFile = outputPath + $._PPP_.getSep() + file; + var expJPEG = activeSequence.exportFrameJPEG($.pype.convertSecToTimecode(time, fps), $.pype.convertPathString(fullPathToFile).split('/').join($._PPP_.getSep())); return file; }, encodeRepresentation: function (request) { - $.writeln('__ request: ' + request); + $.pype.log('__ request: ' + request); var waitFile = ''; var sequence = app.project.activeSequence // get original timeline in out points @@ -895,44 +894,29 @@ $.pype = { origInPoint = allInOut[0]; origOutPoint = allInOut[1]; }; - $.writeln('__ origInPoint: ' + origInPoint); - $.writeln('__ origOutPoint: ' + origOutPoint); + $.pype.log('__ origInPoint: ' + origInPoint); + $.pype.log('__ origOutPoint: ' + origOutPoint); // instances var instances = request.instances; - $.writeln('__ instances: ' + instances); + $.pype.log('__ instances: ' + instances); for (var i = 0; i < instances.length; i++) { // generate data for instance's representations // loop representations of instance and sent job to encoder var representations = instances[i].representations; - $.writeln('__ representations: ' + representations); + $.pype.log('__ representations: ' + representations); instances[i].files = []; for (var key in representations) { // send render jobs to encoder var exclude = ['projectfile', 'thumbnail']; if (!include(exclude, key)) { - instances[i].files.push($.pype.render( - request.stagingDir, - key, - representations[key], - instances[i].name, - instances[i].version, - instances[i].metadata['ppro.clip.start'], - instances[i].metadata['ppro.clip.end'] - )); + instances[i].files.push($.pype.render(request.stagingDir, key, representations[key], instances[i].name, instances[i].version, instances[i].metadata['ppro.clip.start'], instances[i].metadata['ppro.clip.end'])); waitFile = request.stagingDir + '/' + instances[i].files[(instances[i].files.length - 1)]; } else if (key === 'thumbnail') { - instances[i].files.push($.pype.exportThumbnail( - instances[i].name, - key, - instances[i].version, - request.stagingDir, - (instances[i].metadata['ppro.clip.start'] + ((instances[i].metadata["ppro.clip.end"] - instances[i].metadata['ppro.clip.start']) / 2)), - instances[i].metadata['ppro.timeline.fps'] - )); + instances[i].files.push($.pype.exportThumbnail(instances[i].name, key, instances[i].version, request.stagingDir, (instances[i].metadata['ppro.clip.start'] + ((instances[i].metadata["ppro.clip.end"] - instances[i].metadata['ppro.clip.start']) / 2)), instances[i].metadata['ppro.timeline.fps'])); } else if (key === 'projectfile') { instances[i].files.push(instances[i].projectfile); }; @@ -946,7 +930,10 @@ $.pype = { }, render: function (outputPath, family, representation, clipName, version, inPoint, outPoint) { - var outputPresetPath = $.getenv('EXTENSION_PATH').split('/').concat(['encoding', (representation.preset + '.epr')]).join($._PPP_.getSep()); + var outputPresetPath = $.getenv('EXTENSION_PATH').split('/').concat([ + 'encoding', + (representation.preset + '.epr') + ]).join($._PPP_.getSep()); app.enableQE(); var activeSequence = qe.project.getActiveSequence(); // we use a QE DOM function, to determine the output extension. @@ -962,14 +949,8 @@ $.pype = { if (outputFormatExtension) { app.project.activeSequence.setInPoint(inPoint); app.project.activeSequence.setOutPoint(outPoint); - var file = clipName + '_' + - family + - '_v' + version + - '.' + - outputFormatExtension; - var fullPathToFile = outputPath + - $._PPP_.getSep() + - file; + var file = clipName + '_' + family + '_v' + version + '.' + outputFormatExtension; + var fullPathToFile = outputPath + $._PPP_.getSep() + file; var outFileTest = new File(fullPathToFile); @@ -987,17 +968,11 @@ $.pype = { app.encoder.bind('onEncoderJobQueued', $._PPP_.onEncoderJobQueued); app.encoder.bind('onEncoderJobCanceled', $._PPP_.onEncoderJobCanceled); - // use these 0 or 1 settings to disable some/all metadata creation. app.encoder.setSidecarXMPEnabled(0); 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? + var jobID = app.encoder.encodeSequence(app.project.activeSequence, fullPathToFile, outPreset.fsName, app.encoder.ENCODE_IN_TO_OUT, 1); // Remove from queue upon successful completion? $._PPP_.updateEventPanel('jobID = ' + jobID); outPreset.close(); @@ -1015,8 +990,13 @@ $.pype = { } }, - log: function (info) { - app.setSDKEventMessage(JSON.stringify(info), 'info'); + log: function (message) { + $.writeln(message); + message = JSON.stringify(message); + if (message.length > 100) { + message = message.slice(0, 100); + } + app.setSDKEventMessage(message, 'info'); }, message: function (msg) { @@ -1034,7 +1014,8 @@ $.pype = { var pattern = /_v([0-9]*)/g; var search = pattern.exec(outputName); var version = 1; - var newFileName, absPath; + var newFileName, + absPath; if (search) { return search[1] @@ -1083,7 +1064,8 @@ $.pype = { var pattern = /_v([0-9]*)/g; var search = pattern.exec(outputName); var version = 1; - var newFileName, absPath; + var newFileName, + absPath; if (search) { var match = parseInt(search[1], 10); @@ -1128,8 +1110,12 @@ $.pype = { } }, transcodeExternal: function (fileToTranscode, fileOutputPath) { - fileToTranscode = typeof fileToTranscode !== 'undefined' ? fileToTranscode : 'C:\\Users\\hubert\\_PYPE_testing\\projects\\jakub_projectx\\resources\\footage\\raw\\day01\\bbt_test_001_raw.mov'; - fileOutputPath = typeof fileOutputPath !== 'undefined' ? fileOutputPath : 'C:\\Users\\hubert\\_PYPE_testing\\projects\\jakub_projectx\\editorial\\e01\\work\\edit\\transcode'; + fileToTranscode = typeof fileToTranscode !== 'undefined' + ? fileToTranscode + : 'C:\\Users\\hubert\\_PYPE_testing\\projects\\jakub_projectx\\resources\\footage\\raw\\day01\\bbt_test_001_raw.mov'; + fileOutputPath = typeof fileOutputPath !== 'undefined' + ? fileOutputPath + : 'C:\\Users\\hubert\\_PYPE_testing\\projects\\jakub_projectx\\editorial\\e01\\work\\edit\\transcode'; app.encoder.launchEncoder(); var outputPresetPath = $.getenv('EXTENSION_PATH').split('/').concat(['encoding', 'prores422.epr']).join($._PPP_.getSep()); @@ -1137,13 +1123,7 @@ $.pype = { var srcOutPoint = 3.0; // encode stop time at 3s (optional--if omitted, encode entire file) var removeFromQueue = false; - app.encoder.encodeFile( - fileToTranscode, - fileOutputPath, - outputPresetPath, - removeFromQueue, - srcInPoint, - srcOutPoint); + app.encoder.encodeFile(fileToTranscode, fileOutputPath, outputPresetPath, removeFromQueue, srcInPoint, srcOutPoint); } }; @@ -1157,32 +1137,8 @@ Number.prototype.pad = function (size) { function include(arr, obj) { for (var i = 0; i < arr.length; i++) { - if (arr[i] === obj) return true; - } + if (arr[i] === obj) + return true; + } return false } - -// const url = 'http://localhost:8021/adobe/presets/J01_jakub_test'; -// const https = require('https'); -// $.writeln(url) -// $.writeln(https) - -// -// const url = 'http://localhost:8021/adobe/presets/J01_jakub_test'; -// const https = require('https'); -// -// https.get(url, (resp) => { -// let data = ''; -// -// // A chunk of data has been recieved. -// resp.on('data', (chunk) => { -// data += chunk; -// }); -// -// // The whole response has been received. Print out the result. -// resp.on('end', () => { -// $.writeln(JSON.parse(data).explanation); -// }); -// }).on('error', (err) => { -// $.writeln('Error: ' + err.message); -// }); diff --git a/pype/premiere/extensions/com.pype/jsx/testingCode._jsx b/pype/premiere/extensions/com.pype/jsx/testingCode._jsx new file mode 100644 index 0000000000..282d6374e9 --- /dev/null +++ b/pype/premiere/extensions/com.pype/jsx/testingCode._jsx @@ -0,0 +1,11 @@ +var extensionFolder = new Folder( + 'C:/Users/jezsc/CODE/pype-setup/repos/pype/pype/premiere/extensions/com.pype'); +$.writeln(extensionFolder); +var mainJsx = extensionFolder + '/pypeApp.jsx'; +$.evalFile(mainJsx); +var appName = 'PPRO'; +$._ext.evalJSXFiles(extensionFolder, appName); +$._ext.evalJSFiles(extensionFolder); +/////////////////////////////////////////////////////////////////////////////////////////////////////////// + +$.pype.getSequencePypeMetadata(app.project.activeSequence); diff --git a/pype/premiere/lib.py b/pype/premiere/lib.py index bb261bf51f..c69681a198 100644 --- a/pype/premiere/lib.py +++ b/pype/premiere/lib.py @@ -35,12 +35,15 @@ self.PUBLISH_PATH = os.path.join( ).replace("\\", "/") if os.getenv("PUBLISH_PATH", None): - os.environ["PUBLISH_PATH"] = os.pathsep.join( - os.environ["PUBLISH_PATH"].split(os.pathsep) + - [self.PUBLISH_PATH] - ) + if self.PUBLISH_PATH not in os.environ["PUBLISH_PATH"]: + os.environ["PUBLISH_PATH"] = os.pathsep.join( + os.environ["PUBLISH_PATH"].split(os.pathsep) + + [self.PUBLISH_PATH] + ) else: os.environ["PUBLISH_PATH"] = self.PUBLISH_PATH +log.debug("PUBLISH_PATH: `{}`".format(os.environ["PUBLISH_PATH"])) + _clearing_cache = ["com.pype", "com.pype.rename"] diff --git a/pype/premiere/ppro/js/pype.js b/pype/premiere/ppro/js/pype.js index 378bc7d8ea..fe5fb2a6a7 100644 --- a/pype/premiere/ppro/js/pype.js +++ b/pype/premiere/ppro/js/pype.js @@ -7,12 +7,14 @@ var timecodes = require('node-timecodes'); function displayResult (r) { console.log(r); - _pype.csi.evalScript('$.writeln( ' + JSON.stringify(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; } @@ -22,27 +24,17 @@ var _pype = { rootFolderPath: csi.getSystemPath(SystemPath.EXTENSION), displayResult: displayResult, displayError: displayError, - getPresets: function () { - var url = pras.getApiServerUrl(); - var projectName = 'J01_jakub_test'; - var urlType = 'adobe/presets'; - var restApiGetUrl = [url, urlType, projectName].join('/'); - return restApiGetUrl; - }, getEnv: function () { _pype.csi.evalScript('$.pype.getProjectFileData();', function (result) { process.env.EXTENSION_PATH = _pype.rootFolderPath; _pype.ENV = process.env; - var url = pras.getApiServerUrl(); - console.log(url); - // _pype.csi.evalScript('$.writeln( "' + url + '" );'); 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(window.ENV) + ')'); + csi.evalScript('$.pype.setEnvs(' + JSON.stringify(_pype.ENV) + ')'); }); } }; @@ -170,7 +162,7 @@ function publish () { var audioOnly = $.querySelector('input[name=audio-only]').checked; var jsonSendPath = $.querySelector('input[name=send-path]').value; var jsonGetPath = $.querySelector('input[name=get-path]').value; - var publishPath = _pype.ENV.publishPath; + var publishPath = _pype.ENV.PUBLISH_PATH; if (jsonSendPath === '') { // create temp staging directory on local @@ -192,61 +184,66 @@ function publish () { displayResult('project file coppied!'); }); - // 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)); + // 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)); - _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'; - $.querySelector('input[name=send-path]').value = jsonSendPath; - $.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)) { - // register publish path - pras.register_plugin_path(publishPath).then(displayResult); - // send json to pyblish - pras.publish(jsonSendPath, jsonGetPath, gui).then(function (result) { - // 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'); + _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'; + $.querySelector('input[name=send-path]').value = jsonSendPath; + $.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); + // register publish path + pras.register_plugin_path(publishPath).then(displayResult); + // send json to pyblish + pras.publish(jsonSendPath, jsonGetPath, gui).then(function (result) { + // 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) + ');'); - }); + 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();'); + // 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 { - // 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 { + displayResult('waiting'); + checkingFile(path); + } + }, timeout); + }; + checkingFile(jsonContent.waitingFor); + }); }); }); } else { @@ -394,11 +391,12 @@ $('#btn-generateRequest').click(function () { }); $('#btn-newWorkfileVersion').click(function () { - ; + displayResult('Saving new version of the project file'); + _pype.csi.evalScript('$.pype.versionUpWorkFile();'); }); $('#btn-testing').click(function () { - pras.get_presets('J01_jakub_tes'); + pras.get_presets(_pype.ENV.AVALON_PROJECT); }); _pype.getEnv(); diff --git a/pype/premiere/ppro/js/pype_restapi_client.js b/pype/premiere/ppro/js/pype_restapi_client.js index 4bb703dcf2..82bae9a941 100644 --- a/pype/premiere/ppro/js/pype_restapi_client.js +++ b/pype/premiere/ppro/js/pype_restapi_client.js @@ -12,18 +12,39 @@ var pras = { return url }, getRequestFromRestApiServer: function (url, callback) { - _pype.displayResult('inside of getRequestFromRestApiServer: ' + url) - fetch(url).then( - res => res.json()).then( - json => {callback(json)}); + + // send post request to rest api server + fetch(url) + .then(res => { + try { + return res.json(); + } catch(e) { + return res.text(); + } + }) + .then(json => { + if (isPypeData(json)) { + _pype.displayResult( + 'json: ' + JSON.stringify(json.data)); + + // send it to callback function + callback(json.data); + } else { + _pype.displayError( + 'Data comming from `{url}` are not correct'.format({url: url})); + callback(null) + } + }) + .catch(err => _pype.displayError( + 'Data comming from `{url}` are not correct.\n\nError: {error}'.format({url: url, error: err})) + ); }, 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) { - var data = null; + get_presets: function (projectName, callback) { var template = '{serverUrl}/adobe/presets/{projectName}'; var url = template.format({ serverUrl: pras.getApiServerUrl(), @@ -33,20 +54,32 @@ var pras = { // send request to server pras.getRequestFromRestApiServer(url, function (result) { - _pype.displayResult(JSON.stringify(result)); - if (result.hasOwnProperty ('success')) { - data = result.data; - _pype.displayResult('_ data came as dict'); - _pype.displayResult(JSON.stringify(data)); - } else { - _pype.displayResult('data came as nothing'); - _pype.displayError( - 'No data for `{projectName}` project in database'.format( - {projectName: projectName})); - } + 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); + // }); + }); + } }); }, register_plugin_path: function (publishPath) { + _pype.displayResult('_ publishPath: ' + publishPath); // preparation for getting representations from api server }, deregister_plugin_path: function () { @@ -54,9 +87,9 @@ var pras = { }, publish: function (jsonSendPath, jsonGetPath, gui) { // preparation for publishing with rest api server - console.log('__ publish:jsonSendPath: ' + jsonSendPath); - console.log('__ publish:jsonGetPath ' + jsonGetPath); - console.log('__ publish:gui ' + gui); + _pype.displayResult('__ publish:jsonSendPath: ' + jsonSendPath); + _pype.displayResult('__ publish:jsonGetPath ' + jsonGetPath); + _pype.displayResult('__ publish:gui ' + gui); }, context: function (project, asset, task, app) { // getting context of project @@ -75,3 +108,13 @@ String.prototype.format = function (arguments) { } return this_string; }; + +function isPypeData(v) { + try{ + return Object.prototype.hasOwnProperty.call( + v, 'success'); + } catch(e){ + /*console.error("not a dict",e);*/ + return false; + } +}