Adobe Premiere Pro CEP- Cannot start nodejs localserver alongside panel - javascript

I've been experimenting with panels development for Premiere Pro CC 2019, and am now trying to follow the tutorial found on https://medium.com/adobetech/how-to-build-a-node-js-server-in-a-panel-ba1d63ea67e2 on creating a localserver with nodejs alongside a panel, but I can't get it to work
I've uploaded my code here, which doesn't differ much from the tutorial beside updated manifest.xml version numbers: https://github.com/VanMuylemSven/AdobePanelNodeSample
Clicking the panel returns an empty alert, tested in both Premiere Pro CC 2019 and Photoshop CC 2019
Enabling the debug always tells me that the connection is refused, and none of the console logs in the localserver ever get triggered.
Manifest.xml
<?xml version="1.0" encoding="UTF-8"?>
<ExtensionManifest Version="7.0" ExtensionBundleId="com.my.test" ExtensionBundleVersion="1.0.0"
ExtensionBundleName="NodeSamplePanel" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ExtensionList>
<Extension Id="com.my.test.panel" Version="1.0" />
<Extension Id="com.my.localserver" Version="1.0" />
</ExtensionList>
<ExecutionEnvironment>
<HostList>
<Host Name="PHXS" Version="14.0" />
<Host Name="PHSP" Version="14.0" />
<Host Name="PPRO" Version="7.0" />
</HostList>
<LocaleList>
<Locale Code="All" />
</LocaleList>
<RequiredRuntimeList>
<RequiredRuntime Name="CSXS" Version="7.0" />
</RequiredRuntimeList>
</ExecutionEnvironment>
<DispatchInfoList>
<Extension Id="com.my.test.panel">
<DispatchInfo >
<Resources>
<MainPath>./client/index.html</MainPath>
<CEFCommandLine>
<Parameter>--allow-file-access</Parameter>
<Parameter>--allow-file-access-from-files</Parameter>
<Parameter>--enable-nodejs</Parameter>
<Parameter>--mixed-context</Parameter>
</CEFCommandLine>
<ScriptPath>./host/index.jsx</ScriptPath>
</Resources>
<Lifecycle>
<AutoVisible>true</AutoVisible>
</Lifecycle>
<UI>
<Type>Panel</Type>
<Menu>NodeJS SAMPLE PANEL</Menu>
<Geometry>
<Size>
<Height>540</Height>
<Width>600</Width>
</Size>
</Geometry>
</UI>
</DispatchInfo>
</Extension>
<Extension Id="com.my.localserver">
<DispatchInfo>
<Resources>
<MainPath>./client/localServer.html</MainPath>
<CEFCommandLine>
<Parameter>--allow-file-access</Parameter>
<Parameter>--allow-file-access-from-files</Parameter>
<Parameter>--enable-nodejs</Parameter>
<Parameter>--mixed-context</Parameter>
</CEFCommandLine>
</Resources>
<Lifecycle>
<AutoVisible>false</AutoVisible>
</Lifecycle>
<UI>
<Type>Custom</Type>
<Icons />
</UI>
</DispatchInfo>
</Extension>
</DispatchInfoList>
</ExtensionManifest>
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Your First Fullstack Panel</title>
<script>
console.log(" console log in index.html test " );
</script>
</head>
<body>
<!-- Simple HTML UI elements to get us started. -->
<h1>Your First Full Stack Panel</h1>
<button id="import-button">Import from external server</button>
<!-- Add you dependencies here -->
<script src="../lib/jquery-1.9.1.js"></script>
<script src="CSInterface.js"></script>
<script src="index.js"></script>
</body>
</html>
index.js
/* Create an instance of CSInterface. */
var csInterface = new CSInterface();
/* Load your server extension */
csInterface.requestOpenExtension("com.my.localserver", "");
/* Make a reference to your HTML button and add a click handler. */
var openButton = document.querySelector("#import-button");
openButton.addEventListener("click", importDoc);
if (typeof(require) !== 'undefined') {
alert("Node.js is enabled");
} else {
alert("Node.js is disabled");
}
/* Get the path for your panel */
var extensionDirectory = csInterface.getSystemPath("extension");
function importDoc() {
/* Make sure to include the full URL */
//https://www.countryflags.io/be/flat/64.png //Test url, this one returns a success, but doesn't execute server code?
console.log("Function: importDoc()");
console.log("extensiondirectory = " + extensionDirectory);
var url = "http://localhost:3200/import"; //Port 8088 atleast returns "Not Found"-error instead of nothing, but that might be becuase of the .debug port.
console.log("communicating with server");
/* Use ajax to communicate with your server */
$.ajax({
type: "GET",
url: url,
headers: {
"directory": extensionDirectory
},
success: response => {
/* Use the ExtendScript function to display the downloaded file */
console.log("SUCCESS IN RESPONSE");
csInterface.evalScript(`openDocument("${response}")`);
},
error: (jqXHR, textStatus, errorThrown) => {
console.log(jqXHR);
console.log(" ///textstatus= " + textStatus);
console.log(" /// errorthrown= " + errorThrown);
alert(errorThrown, jqXHR.responseJSON);
}
})
}
localserver.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
console.log(" ============== localserver.html ================= " );
console.log(__dirname + + '/server/main.js');
/* This script uses cep_node to start the Node.js server located at '/server/main.js' */
var localServer = cep_node.require(__dirname + '/server/main.js')();
</script>
<title>Import Example App</title>
</head>
<body>
</body>
</html>
server/main.js
/* npm Modules */
const express = require("express");
const app = express();
const request = require('request');
const http = require('http');
const path = require("path");
const bodyParser = require("body-parser");
const fs = require('fs');
const httpServer = http.Server(app);
console.log("main.js code started");
module.exports = run
function run(){
console.log("//////////////////////////////////////")
console.log("SERVER CODE")
var port = 3200;
var hostname = "localhost"
/* Start the server */
httpServer.listen(port, hostname);
/* Middlewares */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ limit: '50mb',extended: true }));
app.use(express.static(path.join(__dirname, "../client")));
/* /import route that can be hit from the client side */
app.get("/import", (req, res, next) => {
console.log(" ========================= app.get ===========================");
/* Get the directory path from the header and name the file */
var path = req.headers["directory"] + "/placeholder.png"
/* This is an example URL */
var uri = "http://via.placeholder.com/350x150";
/* write a helper function to download the image and save it */
var saveImage = function(uri, filepath, callback){
request.head(uri, function(err, res, body){
request(uri).pipe(fs.createWriteStream(filepath)).on('close', callback);
});
};
saveImage(uri, path, function(){
/* Send the path back to the client side */
res.status(200).send(path)
});
});
}
host/index.jsx
// function openDocument(){
// var fileRef = new File("~/Downloads/MyFile.jpg");
// var docRef = app.open(fileRef);
// }
function openDocument(location){
var fileRef = new File(location);
var docRef = app.open(fileRef);
}
Is there something blatantly ovious I'm doing wrong? Does this have something to do with the wrong version numbers in the manifest.xml? I really don't know why the server wouldn't even start or give any feedback seeing as nodejs itself is definitely enabled, any help would be appreciated.

There's a comment on the article which was originally posted here:
https://community.adobe.com/t5/premiere-pro/cannot-get-csinterface-to-open-extension-server-invisibly-alongside-panel/td-p/10437661 by sven-vm
He says replace:
<UI>
<Type>Custom</Type>
<Icons />
</UI>
with
<UI>
<Type>Custom</Type>
<Geometry>
<Size>
<Height>600</Height>
<Width>600</Width>
</Size>
</Geometry>
</UI>
This worked for me.

Related

Client side js file is not working | node.js

So I just made a HTML page added a script tag with src to a js file and sent the HTML file as response with node js using HTTP module.
But the js file is not working and when I checked the network tab I saw js file is received as text/html file.
Following are the js and html codes.
Server code with node js
const http = require('http') ;
const file = require('fs') ;
const server = http.createServer((req, res) => {
file.readFile('public/login.html', (err, data) => {
if (err) throw err ;
res.writeHead(200, {'Content-Type': 'text/html'}) ;
res.write(data) ;
res.end() ;
})
}) ;
server.listen(5000) ;
front end code : login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<script defer src="js/index.js"></script>
</head>
<body>
<h1>Login</h1>
<form action="" method="post">
<input type="email" name="user" id="user">
<input type="password" name="pass" id="pass">
<button type="submit" name="button" value="login">Login</button>
</form>
</body>
</html>
now when I load the page at localhost:5000, js does not execute and it's received as text/html.
The browser will receive the HTML, see the script tag, and request js/index.js from your server. But your server only sends your HTML file. It doesn't pay any attention to what the browser requested, it just always sends back the HTML. So the script is never sent to the browser, so the browser can't execute it.
Your server code needs to look at req to determine what was requested (looking at url, etc.), and send an appropriate response, rather than always sending back the same content.
Here's a fairly simple example that handles /, /login.html, and /js/index.js paths (making the first two synonyms):
const http = require('http');
const file = require('fs');
const FILENAME_404 = "public/404.html";
const server = http.createServer((req, res) => {
let filename = null;
let contentType = "text/html";
let status = 200;
// What did the browser ask for?
switch (req.url.toLowerCase()) {
case "/":
case "/login.html":
// The login page
filename = "public/login.html";
break;
case "/js/index.js":
// The JavaScript file
filename = "public/js/index.js";
contentType = "text/javascript";
break;
default:
// Something we don't support -- send a 404
filename = FILENAME_404;
status = 404;
break;
}
sendFile(res, filename, contentType, status);
});
function sendFile(res, filename, contentType, status, callback) {
file.readFile(filename, (err, data) => {
if (err) {
// Couldn't read the file, send a 404
if (filename !== FILENAME_404) {
sendFile(res, FILENAME_404, "text/html", 404);
} else {
// Couldn't even find the 404 file, send a minimal plaintext 404
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("The requested resource does not exist on this server.");
res.end();
}
} else {
res.writeHead(status, {"Content-Type": contentType});
res.write(data);
res.end();
}
});
}
server.listen(5000);
Note: This is just an example. If you're going to build anything of any size, you'll want more structure than this. You might look at Express or Koa or others that handle more of the HTTP plumbing, URL routing, etc. for you and have modules available for other things as well.

Spotify Implicit Grant won't work on node

I am trying to make the codes you see here:
https://glitch.com/edit/#!/amusing-swallow?path=index.html:7:68
executable on my node js application. Please note that the codes on that link is working.
What I did is that I set up an environment like this:
root folder
--public
--index.html
--script.js
--app.js
--package.json
And then I copied the html code to my index.html file like this:
<!DOCTYPE html>
<html>
<head>
<title>Spotify Implicit Grant Template</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://sp-bootstrap.global.ssl.fastly.net/8.0.0/sp-bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body class="container">
<h1 class="text-salmon">Spotify Implicit Grant Template</h1>
<h3>This app uses the implicit grant authorization flow to authenticate users and get user data.</h3>
<p>
Here are your top artists on Spotify:
<ol id="top-artists"></ol>
</p>
<script src="../script.js" type='text/javascript'></script>
</body>
</html>
Nothing special and then I made the script.js a self invoking function like this:
(function() {
// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split("&")
.reduce(function(initial, item) {
if (item) {
var parts = item.split("=");
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = "";
// Set token
let _token = hash.access_token;
const authEndpoint = "https://accounts.spotify.com/authorize";
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = "xxxxxxxxxxxxxxxxxxxxxxxx";
const redirectUri = "http://localhost:8888/callback/";
const scopes = ["user-top-read"];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join(
"%20"
)}&response_type=token&show_dialog=true`;
}
// Make a call using the token
$.ajax({
url:
"https://api.spotify.com/v1/search?query=tania+bowra&offset=0&limit=20&type=artist",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + _token);
},
success: function(data) {
// Do something with the returned data
data.items.map(function(artist) {
let item = $("<li>" + artist.name + "</li>");
item.appendTo($("#top-artists"));
});
}
});
})();
And then finally on my app.js for express:
var express = require("express"); // Express web server framework
var app = express();
app.use(express.static(__dirname + "/public"));
console.log("Listening on host 8888......");
app.listen(8888);
So I tried to run this and whenever I visit the localhost:8888, I keep on getting these:
GET http://localhost:8888/script.js 404 (Not Found)
Refused to execute script from 'http://localhost:8888/script.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
I am not sure why. But I just copied the same exact code and just put my credentials there but it won't still work. Any idea what am I doing wrong?

Node JS and AngularJS - script and links not found - 404

I am trying to build a Node.js/AngularJS app with Openshift 2. The server is being run successfully and if I go to local adress I get index.html(but blank as it does not load the css), I cant get scripts and links on index.html, I get an error 404 but I dont know why.
Folder structure:
sw [sw master]
pages
index.html
inicio.html
css
inicio.css
js
angular.js
aplicacion.js
app.js
start.js
app.js
const http = require('http'),
fs = require('fs'),
path = require('path'),
contentTypes = require('./utils/content-types'),
sysInfo = require('./utils/sys-info'),
env = process.env;
let server = http.createServer(function (req, res) {
let url = req.url;
if (url == '/') {
url += '/index.html';
}
// IMPORTANT: Your application HAS to respond to GET /health with status 200
// for OpenShift health monitoring
if (url == '/health') {
res.writeHead(200);
res.end();
} else if (url == '/info/gen' || url == '/info/poll') {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache, no-store');
res.end(JSON.stringify(sysInfo[url.slice(6)]()));
} else {
fs.readFile('./pages' + url, function (err, data) {
if (err) {
res.writeHead(404);
res.end('Not found');
} else {
let ext = path.extname(url).slice(1);
if (contentTypes[ext]) {
res.setHeader('Content-Type', contentTypes[ext]);
}
if (ext === 'html') {
res.setHeader('Cache-Control', 'no-cache, no-store');
}
res.end(data);
}
});
}
});
server.listen(env.NODE_PORT || 3000, env.NODE_IP || 'localhost', function () {
console.log(`Application worker ${process.pid} started...`);
});
index.html
<!DOCTYPE html>
<html lang="es" data-ng-app="TFG">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Página principal</title>
<script src="../js/angular.js"></script>
<script src="../js/app.js"></script>
<link href="../css/inicio.css" rel="stylesheet" />
</head>
<body>
<!--CUERPO-->
<div data-ng-view></div>
</body>
</html>
your index file should be at root level as you are providing path in your nodejs file.
Right now your index.html is under "pages" folder.
pages
index.html
inicio.html
I think this will be your tree
sw [sw master]
pages
inicio.html
css
inicio.css
js
angular.js
aplicacion.js
emphasized textindex.html
app.js
start.js
The Node.js script running the server will render html from page folder. This index.html has the css and js linked by relative path from the folder structure but you need to expose that publicly too to get reached by the browser when it tries to get the resources. You will need some code to serve that static content.
In fact, is your own code returning that 404 as the URL that the browser is trying to get the resources (css and js) from your pages folder and they are not found.
fs.readFile('./pages' + url, function (err, data) {
if (err) {
res.writeHead(404);
res.end('Not found');
}
You should include some code that return the css and js files.

Send upload progress update to client using node.js, node-formidable and socket.io

My code shows a simple upload form (node-formidable and node.js). I am using socket.io to update the client on it's current upload file progress. My problem is that I currently emit the progress update to every clients. As an example, if I start an upload with clientA, then connect to the website with clientB, clientB will see the exact same progress bar as clientA. Normally, clientA and clientB should be different, with their own respective progress bars, linked only with their respective uploads.
This is my app.js file
// Required modules
var formidable = require('formidable'),
http = require('http'),
util = require('util'),
fs = require('fs-extra');
// Path to save file, server side
var savePath = "./uploadedFiles/";
// Loading index.html
var server = http.createServer(function(req, res) {
// Form uploading Process code
//Upload route
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// creates a new incoming form.
var form = new formidable.IncomingForm();
// set the path to save the uploaded file on server
form.uploadDir = savePath;
// updating the progress of the upload
form.on('progress', function(bytesReceived, bytesExpected) {
io.sockets.in('sessionId').emit('uploadProgress', (bytesReceived * 100) / bytesExpected);
});
// parse a file upload
form.parse(req, function (err, fields, files) {
res.writeHead(200, { 'content-type': 'text/plain' });
res.write('Upload received :\n');
res.end(util.inspect({ fields: fields, files: files }));
});
form.on('end', function (fields, files) {
/* Temporary location of our uploaded file */
var temp_path = this.openedFiles[0].path;
/* The file name of the uploaded file */
var file_name = this.openedFiles[0].name;
/* Files are nammed correctly */
fs.rename(temp_path, savePath + file_name, function(err) {
if ( err ) console.log('ERROR: ' + err);
});
});
return;
}
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
// socket.io
var io = require('socket.io').listen(server);
io.on('connection', function (socket) {
socket.join("sessionId");
});
server.listen(8080);
This is my index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Socket.io</title>
</head>
<body>
<h1>Test d'upload</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('uploadProgress' , function (progress){
document.getElementById("currentProgress").value = progress;
});
</script>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="upload" multiple="multiple"><br>
<input type="submit" value="Upload">
</form>
<p><progress id="currentProgress" value="0" max="100"></progress></p>
</body>
</html>
I do not have more code than this. I am new to node.js and socket.io, so I am not sure about the interactions between them and between the client and server.
How can I change my code to update only the right client?
Thank you anyway for your time.
a suggestion
there is a basic way
socketIO.sockets.socket(this.socketid).emit(<event>, dataObj);
if your function is inside your socket code...otherwise I will often do something like this
connection.query("select socketid from websocket_sessions where user_id=" + data.form.user_id, function(err, users) {
socketIO.sockets.socket(users[0].socketid).emit(<event>, dataObj);
});
where I am always updating or a

Node.js server issue - added "/" when looking for files in browser

I'm trying to write my first Nodejs server for getting to know Angular/Node and eventually the whole MEAN stack.
My server is running but there's a problem in my code, for some reason when I enter a non existing file, it should redirect to 404, but it doesn't. For some reason the URL gets a double dash;
How would I go about making the redirect to 404 work?
check this image
Here is my code for the server so far.
var http = require('http'),
fs = require('fs'),
path = require('path'),
root = __dirname + '/public/', //magic var
mime = require('mime');
//Server
var server = http.createServer(function (req, res) {
// Check is root is queried
var fileName = '';
var url = req.url;
if (url === '/'){
url = 'index.html'; // redirect when no file specified
}
fileName = root + url;
// check if file exists
fs.exists(fileName, function(exists){
if (exists) {
serveFile(fileName); // yes
} else {
path = root + '404.html'; //no
serveFile(fileName);
}
})
//serve file
function serveFile(requestFile) {
// maak a stream based on events
var stream = fs.createReadStream(requestFile);
res.writeHead(200, {'Content-Type': mime.lookup(requestFile)});
stream.on('data', function (chunk){
res.write(chunk);
});
stream.on('end', function(){
res.end();
});
stream.on('error', function(err){
console.log('error: '+ err);
});
}
});
server.listen(3000); //server start
console.log('Server gestart op http://localhost:3000 ');
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>angular</title>
<link href="https://cdn.jsdelivr.net/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="styles/app.css" rel="stylesheet"/>
</head>
<body ng-app class="bg">
<h1>First name?</h1>
<input type="text" placeholder="Type your name" ng-model='firstName'
class="input-lg"/>
<p>
Hi, {{firstName}}
</p>
<img src="https://static.pexels.com/photos/7720/night-animal-dog-pet.jpg" height="100px" width="100px"/>
</body>
<script type="text/javascript" src="https://cdn.jsdelivr.net/angularjs/1.5.5/angular.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/angularjs/1.5.5/angular.min.js"></script>
</html>
Could anyone tell me what's going wrong here?
Thanks in advance!
get rid of the '/' after public:
root = __dirname + '/public'
It is the default behaviour of Node JS. ie. If you request for xxx.com/sample.txt, then the req.url will be "/sample.txt".
https://nodejs.org/api/http.html#http_message_url
So you have consider that in your code, as #Jordan mentioned, remove the "/".
Your redirect also should work fine.

Categories