Where to register the Native Messaging Host in Chrome OS - google-chrome-app

In this documentation there's the location for Windows, Mac OS and Linux.
I assumed Chrome OS would work the same as "standard" linux, but i couldnt get my app working ...
com.my_app.host.json (located in /etc/opt/chrome/native-messaging-hosts/)
{
"name": "com.my_app.host",
"description": "My Host",
"path": "/home/user/bfd93db2180e0d7645b1f4cce2d2c7ed9e0d835c/Downloads/host.sh",
"type": "stdio",
"allowed_origins": [
"chrome-extension://APP_ID/"
]
}
main.js
var port = null;
var getKeys = function(obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}
return keys;
}
function appendMessage(text) {
document.getElementById('response').innerHTML += "<p>" + text + "</p>";
}
function updateUiState() {
if (port) {
document.getElementById('connect-button').style.display = 'none';
document.getElementById('input-text').style.display = 'block';
document.getElementById('send-message-button').style.display = 'block';
} else {
document.getElementById('connect-button').style.display = 'block';
document.getElementById('input-text').style.display = 'none';
document.getElementById('send-message-button').style.display = 'none';
}
}
function sendNativeMessage() {
message = {
"text": document.getElementById('input-text').value
};
port.postMessage(message);
appendMessage("Sent message: <b>" + JSON.stringify(message) + "</b>");
}
function onNativeMessage(message) {
appendMessage("Received message: <b>" + JSON.stringify(message) + "</b>");
}
function onDisconnected() {
appendMessage("Failed to connect: " + chrome.runtime.lastError.message);
port = null;
updateUiState();
}
function connect() {
var hostName = "com.my_app.host";
appendMessage("Connecting to native messaging host <b>" + hostName + "</b>")
port = chrome.runtime.connectNative(hostName);
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
updateUiState();
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('connect-button').addEventListener(
'click', connect);
document.getElementById('send-message-button').addEventListener(
'click', sendNativeMessage);
updateUiState();
});
index.html
<html>
<head>
<script src='./main.js'></script>
</head>
<body>
<button id='connect-button'>Connect</button>
<input id='input-text' type='text' />
<button id='send-message-button'>Send</button>
<div id='response'></div>
</body>
</html>
It just says:
Connecting to native messaging host com.my_app.host
Failed to connect: Specified native messaging host not found.
Also i cant enable logging as explained in the documentation because on Chrome OS you cant just open Chrome via a command.
Would be great if someone could help me :)
Basically i just want to create a little GUI for launching Crouton commands.

Chrome OS does not support third-party native messaging hosts. As of writing, only two native messaging hosts are supported. One for testing, and one for Chrome Remote Desktop (source: native_message_host_chromeos.cc).
On Chrome OS, logs are available at /var/log/chrome/chrome and /var/log/ui/ui.LATEST. There are other ways to read/toggle the log (see
https://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/building-chromium-browser#TOC-Debugging and
https://github.com/ds-hwang/wiki/wiki/Build-Chromium-for-Chromium-OS-and-Deploy-to-real-device#log).
But the absence of built-in support for native messaging hosts does not mean that you cannot achieve what you want. Start a local HTTP server in Crouton, and communicate between the Chrome extension / app and the HTTP server via the standard Web APIs (XMLHttpRequest, fetch, WebSocket, ...). On the server (running in Crouton), you can do whatever you want (e.g. starting local scripts).
Make sure that the server implements proper authentication (to prevent unauthorized access by other web sites or extensions) (and preferably bind to a local address only to make the server inaccessible over network).

Related

iPhone doesn't connect to the web socket but the simulator does

Physical devices cannot connect to my web socket. I tried it with 3 different phone and with different networks. It works fine with my simulators though. I am not getting an error message apart from the standard "Cannot connect to the server" from socket.io on the client.
I don't know if this is a valid indicator but I also tried using https://www.websocket.org/ with the following parameter:
wss://converzone.htl-perg.ac.at:5134
I am getting a "ERROR: undefined DISCONNECTED" there.
I am using an ubuntu server which runs Ubuntu 16.04. The web socket is from socket.io and I am coding with Swift on the client and with Node.js on the server. This whole thing is running on my school's server.
// Here is an array of all connections to the server
var connections = {};
io.sockets.on('connection', newConnection);
function newConnection(socket) {
console.log(socket.id + " connected.");
socket.on('add-user', function(user) {
connections[user.id] = {
"socket": socket.id
};
});
socket.on('chat-message', function(message) {
console.log(message);
if (connections[message.receiver]) {
console.log("Send to: " + connections[message.receiver].socket);
//io.sockets.connected[connections[message.receiver].socket].emit("chat-message", message);
io.to(connections[message.receiver].socket).emit('chat-message', message);
} else {
console.log("Send push notification")
sendPushNotificationToIOS(message.senderName, message, message.deviceToken, message.sound)
}
});
//Removing the socket on disconnect
socket.on('disconnect', function() {
console.log("The client disconnected");
console.log("The new list of clients is: " + connections)
for (var id in connections) {
if (connections[id].socket === socket.id) {
delete connections[id];
break;
}
}
})
}
Please understand that this problem seems very weird to me. I have changed the AppTransferProtocol in my plist and changed the port from 3000 to 5134. Nothing changed. Tell me what code would seem relevant apart from the (minimal) server code.

How to stream video to browser with Kodi

Not sure if this is the correct place to ask this but here goes nothing.
I setup openelec's Kodi on a Raspberry pi2. I uploaded a video and managed to get it to play on a connected TV via HDMI. What I can't seem to figure out is how to have Kodi serve as a media server so I can browse media using my phone's or computer's browser and play it. I've been through the settings available, installed several addons(i.e chorus etc) and I still can't see how to make this happen. Whenever I open a video on my browser after logging into the Kodi web interface, it still plays it on the TV connected to the PI.
Almost all Google results out there talk about casting from device onto TV and chromecast. I want to be able to play this media on my local browser. And no, I can't use the Kodi app because I'm using an un-supported Phone and computer OS.
In your case, it's better to use plex instead of kodi.
Kodi is not exactly a media server, it works as a media center. However, with plex, you can set up your media center and have access to your media from your web browser.
Try looking for the differences between kodi and plex.
Chorus should still have an option to play the video in the browser. It seems to not work with Chrome or Firefox anymore, but have a look here: https://github.com/xbmc/chorus2/issues/127
This functionality depends on Flash Player, this feature had been removed from most of the web-browsers.
REF: https://support.google.com/chrome/answer/6258784?visit_id=637521928282450874-904852602&rd=1
I've modified the Chorus web interface to allow streaming with a nodejs process in the background.
NodeJS script:
const express = require('express')
const fs = require('fs')
const path = require('path')
const app = express()
const url = require('url')
const gracefulFs = require('graceful-fs')
gracefulFs.gracefulify(fs)
app.get('/video', function(req, res) {
var q = url.parse(req.url, true).query;
var filepath = q.src;
fs.stat(filepath, function(err, stats){
if (err){
if (err.code === 'ENOENT'){
//404 Error if file not found
res.writeHead(404, {
"Accept-Ranges" : "bytes",
"Content-Range" : "bytes " + start + "-" + end + "/" + total,
"Content-Length" : chunksize,
"Content-Type" : "video/mp4"
});
}
res.end(err);
}
var start;
var end;
var chunksize;
var total = stats.size;
var range = req.headers.range;
if (range) {
var parts = range.replace(/bytes=/, "").split("-");
start = parseInt(parts[0], 10);
end = parts[1] ? parseInt(parts[1], 10) : total - 1;
} else {
start = 0;
end = total - 1;
}
if (start > end || start < 0 || end > total - 1){
//error 416 is "Range Not Satisfiable"
res.writeHead(416, {
"Accept-Ranges" : "bytes",
"Content-Range" : "*/" + stats.size,
"Content-Type" : "video/mp4"
});
res.end();
return;
}
if (start == 0 && end == (total -1)){
res.writeHead(200, {
'Accept-Ranges': 'bytes',
'Content-Range': `bytes ${start}-${end}/${total}`,
'Content-Length': total,
'Content-Type': 'video/mp4'
});
} else {
chunksize = (end - start) + 1;
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${total}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4'
});
}
var stream = fs.createReadStream(filepath, {
start : start,
end : end
}).on("open", function() {
stream.pipe(res);
}).on("error", function(err) {
console.log(err);
res.end(err);
});
});
});
app.listen(<port>, function () {
console.log('Listening on port <port>!');
});
Modified the file "Kodi\addons\webinterface.chorus\tpl\MovieView.html" under div id="movie-watch" so:
<div id="movie-watch" class="tab-pane">
<div class="col-1">
<video id="videoPlayer" controls width="100%" height="90%" preload="metadata">
<source src="http://<mydomain>:<port>/video?src=<%=encodeURIComponent(file) %>&movieId=<%= movieid %>" type="video/mp4">
</video>
<!--
<h2>HTML5 player</h2>
<p>Codec support is very limited in the browser.
H.264 video generally works but only with 2 channel audio. Works best in Chrome, may crash browser and/or XBMC!</p>
<div class="buttons">
Launch HTML5 player
</div>
<br />
<h2>VLC player</h2>
<p>VLC Player provides an
embeddable video player, it will play most videos, but does require you to
download and install extra software.
Works well in Chrome and Firefox.</p>
<div class="buttons">
Launch VLC player
</div>-->
Modified the file "Kodi\addons\webinterface.chorus\tpl\TvshowView.html" under div id="movie-watch" so:
<div id="tv-watch" class="tab-pane">
<div class="col-1">
<video id="videoPlayer" controls width="100%" height="90%">
<source src="http://<mydomain>:<port>/video?src=<%=encodeURIComponent(file) %>&episodeId=<%= episodeid %>" type="video/mp4">
</video>
<!--
<h2>HTML5 player</h2>
<p>Codec support is very limited in the browser.
H.264 video generally works but only with 2 channel audio. Works best in Chrome, may crash browser and/or XBMC!</p>
<div class="buttons">
Launch HTML5 player
</div>
<br />
<h2>VLC player</h2>
<p>VLC Player provides an
embeddable video player, it will play most videos, but does require you to
download and install extra software.
Works well in Chrome and Firefox.</p>
<div class="buttons">
Launch VLC player
</div>-->

Using WebSockets on Samsung Smart TV

My requirement is to have a listening socket in my Samsung Smart TV app, in order to receive events from a device in the same local network.
I've been searching the web for methods to do that and I came across terms like Node.js, Socket.io, websocket. Even though i understand these terms in terms of web development (I think), I am unable to picture a method to open a listening socket in my Samsung Smart Tv App.
Just for the sake of playing around I wrote a TCP Server code on iOS using GCD Async Sockets and thought of connecting it to the smart tv and send a welcome message.
This is the code on my smart tv -
//var wsUri = "wss://echo.websocket.org/";
var wsUri = "ws://192.168.1.116:9898/";
//var output;
var webSocketObj={};
webSocketObj.init = function()
{
//output = document.getElementById("output");
this.testWebSocket();
};
webSocketObj.testWebSocket = function()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt); };
websocket.onclose = function(evt) { onClose(evt); };
websocket.onmessage = function(evt) { onMessage(evt); };
websocket.onerror = function(evt) { onError(evt); };
};
function onOpen(evt)
{
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
websocket.close();
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message)
{
/* var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);*/
alert('SOCKET HELPER SAYS : '+message);
}
I have a button and I'm calling webSocketObj.init() on the button click.
Logs of my didReadData of the server :
Client says : GET / HTTP/1.1
Log from SmartTv :
[JS ALERT]: Scenewebsocket.handleKeyDown(29443)
[JS ERROR]:
File: file://
Line No: 0
Error Detail:
[JS ALERT]: SOCKET HELPER SAYS : DISCONNECTED
ALSO I tried echoing the message back to the Smart Tv from the server. And this time i got the logs
Client says : GET / HTTP/1.1
Client says : Upgrade: WebSocket
Client says : Connection: Upgrade
Client says : Host: 192.168.1.116:9898
Client says : Origin: file://
Client says : Sec-WebSocket-Key1: 1504l73 8Ew/J 4 ,L7W6
Client says : Sec-WebSocket-Key2: TK2 81d A64Bo7 118 0
I know i'm doing something horribly wrong...what is it? Pls help.
Have you tried socket.io server and client libraries?
We have socket.io server on node.js, and TV can connect to it using socket.io-client library. On 2012 TV it uses websocket. On 2011 TV it uses XHR fallback.
You can use socket.io library to make it easier for yourself to use WebSockets.
You would include a web browser version of socket.io in the samsung tv like this:
<script src="http://*some ip address*/socket.io/socket.io.js"></script>
Where some ip address is the ip address of a nodejs server that you control.
On your server you would need to install NodeJS with the socket.io server version.

socket.io: Failed to load resource

I'm trying to getting started with socket.io and node.js.
Following the first example on the socket.io's site I'm getting the following error in the browser's console:
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3001/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined
This is my server.js
var app = require('express').createServer()
, io = require('socket.io').listen(app);
app.listen(3001);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
And this is my index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8" />
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</body>
</html>
I've already installed socket.io..
The Issues
First of all you need to be looking at the server port that the server is bound on (app.listen(3001);) on the client side in order to reach the server at all.
As for socket.io, adding http://localhost:3001 before the rest of the source in the link tag solves this problem. This is apparently due to the way the network binds ports to localhost, however I will try to find some more information on the cause;
What to change:
The port binding for the server:
var socket = io.connect('http://localhost');
should be change to
var socket = io.connect('http://localhost:3001');
Making socket.io behave:
<script src="/socket.io/socket.io.js"></script>
should be change to
<script src="http://localhost:3001/socket.io/socket.io.js"></script>
If you are using express version 3.x there are Socket.IO compatibility issues that require a bit of fine tuning to migrate:
Socket.IO's .listen() method takes an http.Server instance as an argument.
As of 3.x, the return value of express() is not an http.Server instance. To get Socket.IO working with Express 3.x, make sure you manually create and pass your http.Server instance to Socket.IO's .listen() method.
Here is a quick example:
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
Firstly, the Socket.io "How To Use" documentation is vague (perhaps misleading); especially when documenting code for the Socket.io client.
Secondly the answers you've been given here on StackOverflow are too specific. You shouldn't have to manually hardcode the protocol, hostname, and port number for the Socket.io client; that's not a scalable solution. Javascript can handle this for you with the location object - window.location.origin.
Getting started with Socket.io
Installation
Socket.io requires the installation of a server and client.
To install the server
npm install socket.io
To use the client, add this script to your document (index.html)
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
Implementation with Express 3/4
Create the following files:
Server (app.js)
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Client (index.html)
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
// origin = http(s)://(hostname):(port)
// The Socket.io client needs an origin
// with an http(s) protocol for the initial handshake.
// Web sockets don't run over the http(s) protocol,
// so you don't need to provide URL pathnames.
var origin = window.location.origin;
var socket = io.connect(origin);
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
change;
<script src="/socket.io/socket.io.js"></script>
to;
<script src="https://cdn.socket.io/4.5.0/socket.io.min.js" integrity="sha384-7EyYLQZgWBi67fBtVxw60/OWl1kjsfrPFcaU0pp0nAh+i8FD068QogUvg85Ewy1k" crossorigin="anonymous"></script>
and drop between to head tags.
And Try it!
If you're trying to make this run on a different computer and you are getting this error, you may find this useful.
var host = window.location.hostname;
var socket = io.connect('http://' + host);
If you're using https, then obviously you need to change the protocol as well. In my case I needed to create a server that would run on several local computers, so putting here a fixed address would not work, as the socket would need to connect to a different address depending on what server you are loading the page from. Adding this here as it may help someone else too.
Try this
var app = express()
,http = require('http');
var server = http.createServer(app);
server.listen(3001);
io = require('socket.io').listen(server);
io.set('log level', 1);
Hope it helps
The following changes finally worked for me
const app = express(); const http = require('http'); const server = http.createServer(app); const io = require('socket.io')(server)
I know this is very very late, but I found a solution for those who might have previously set node.js up. My machine needed get hardware replaced, when it came back, I noticed quite a few settings were back to factory default. I was also getting the error discussed above.
Running
sudo apachectl start
from the terminal fixed up my issue.

Net Module Nodester not Listening to Port

I have a basic node.js app that is designed to open up a connection between two clients and echo the input of one to the other.
var net = require("net");
console.log("Relay Started");
var id = 0;
var Socket = [];
relay = net.createServer(function(socket) {
socket.on('connect', function() {
console.log('Connected');
if(socket.id==null) {
socket.id = id;
Socket[id]=socket;
id++;
}
});
socket.on('data', function(data) {
data = data.toString()
if (socket.id==0) {
Socket[1].write(data);
} else if (socket.id==1) {
Socket[0].write(data);
}
console.log(socket);
console.log(data.toString());
});
})
relay.listen(process.env['app_port']||8080);
It works fine when run locally, however when I put it onto a Nodester development server, I am unable to connect by using telnet zapcs.nodester.com 18007 (it is hosted under the name zapcs, and the given port is 18007). The Relay Started is logged, but nothing after that, and no connection. Any ideas on why this would be?
~
you can not telnet zapcs.nodester.com 18007, you only can connect to zapcs.nodester.com:80 by http or websock, nodester will route your request to your app actual port (18007) on the host.
And check this: http://www.slideshare.net/cmatthieu/nodester-architecture-overview-roadmap-9382423