websocket rails javascript not working - javascript

I use websocket rails channel and trigger it from a sidekiq worker. the trigger get logged in the websocket-rails log correctly, like this, with a removed < before StationSongs:
I [2014-12-31 16:19:28.788] [Channel] [station10938] #StationSongs _id: 54a41400446562680e17c102, name: "Fedde & Di-Rect Le Grand", title: "Dream Dance Vol.73 - 14 - Where We Belong", info: nil, week: 1, year: 2014, date: 2014-12-31 15:19:28 UTC, station_id: 10938>
It get triggered like this:
channel = "station" + station_id.to_s
WebsocketRails[:"#{channel}"].trigger(:new, stationsong)
I then set subscribe for the channel station10938, the javascritp code looks like this:
var dispatcher = new WebSocketRails('localhost/websocket');
var stationid = $('#songhistorylist').data("id"); // is 10938
var stationname = 'station' + String(stationid);
var channel = dispatcher.subscribe(stationname);
console.log(channel);
channel.bind('new', function (song) {
console.log(song);
console.log('a new song about ' + song.name + " - " + song.title + ' arrived!');
});
This will only print out channel, not anything else, even if the channel comes up in the log all the time.
What have I done wrong?

On the line: WebsocketRails[:"#{channel}"].trigger(:new, stationsong), remove the ":".
It should be: WebsocketRails["station#{station_id}"].trigger(:new, stationsong)
In your JS, your dispatcher should look like this:
var dispatcher = new WebSocketRails(window.location.host + '/websocket') because your server port might change.
Your server should have (assuming stationsong is set correctly):
channel = "station" + station_id.to_s
WebsocketRails["#{channel}"].trigger(:new, stationsong)
Your client JS should have:
var dispatcher = new WebSocketRails(window.location.host + '/websocket')
var stationid = $('#songhistorylist').data("id"); // is 10938
var stationname = 'station' + String(stationid);
var channel = dispatcher.subscribe(stationname);
console.log(channel);
channel.bind('new', function (song) {
console.log(song);
console.log('a new song about ' + song.name + " - " + song.title + ' arrived!');
});

Related

How to post mentions to slack incoming webhooks

The mentions I send to the incoming webhook renders as plain text.
Note: Sending post request using the request package.
Tried the following:
sending mentions as <#userid>
Result: <#userid> // as plain text
request.post(
`${channels[message.channel.name]}`,
{
json: {
text:
'To: ' + mapDiscordToSlackNames(message.mentions.users) + '\n' +
'Discord channel: #' + message.channel.name + '\n' +
'Link: <' + message.url + '|Link to post>' + '\n' +
Result: To: #soda // as plain text not as mention to #soda user
Entire Code
// require the discord.js module
const Discord = require('discord.js');
const devs = require('./devs.json');
const channels = require('./channels.json');
const dotenv = require('dotenv');
const path = require('path');
var request = require('request');
dotenv.load({
path: path.join(__dirname, `.env`),
silent: true
});
// create a new Discord client
const client = new Discord.Client();
// Map discord usernames of devs to slack usernames
function mapDiscordToSlackNames(discordUsers) {
return discordUsers.map( user => {
return '#' + devs[user.username];
})
}
// when the client is ready, run this code
// this event will only trigger one time after logging in
client.once('ready', () => {
console.log('Discord Connected!');
});
// on message on discord
client.on('message', message => {
console.log(channels[message.channel.name]);
request.post(
`${channels[message.channel.name]}`,
{
json: {
text:
'To: ' + mapDiscordToSlackNames(message.mentions.users) + '\n' +
'Discord channel: #' + message.channel.name + '\n' +
'Link: <' + message.url + '|Link to post>' + '\n' +
'Original Message: \n' +
'\t"' + message.author.username + ': ' + message.cleanContent + '"\n' +
`Attachements: ${message.attachments.map(attachment => attachment.url)}`
},
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
);
});
// login to Discord with app's token
client.login(process.env.DISCORD_TOKEN);
devs is a json object which has returns slack usernames corresponding to discord usernames.
Turns out I was sending userid by escaping '<' & '>' in string like
'&lt#userid&gt' and so it was passing as plain text.
To mention someone in slack do 'To: <#' + userid + '>'
The userid starts with U and can be found after the team/ in url of
your workspace eg: Cxxxxx/team/Uxxxxx/

Can't send sms with Twilio, Node.js and Sequelize

I have a program which respond automatically a sms when receive an income message.
It works when I don't use Sequelize to save data to the database. But when I add the code below, the twiml.message(msg) is never executed.
The problem is when call twiml.message(msg) inside the then it doesn't work. So how to resolve this problem? Thanks
Info.create(param)
.then(info => {
var msg = 'Numero: ' + info.id +
' Nom:' + info.nom +
' Date: ' + info.datesms);
var twiml = new MessagingResponse();
twiml.message(msg);
});

Callback a function after a process

I use the bittorent-tracker package for get numbers of seeders and leechers for a given torrent but there is no way to know if the torrent scraping procedure is terminated client.on('scrape_terminated') for exemple ... Is there a way to detects the scraping is terminated ?
var Tracker = require('bittorrent-tracker')
var magnet = require('magnet-uri')
var magnetURI = "magnet:?xt=urn:btih:7a0e02e22744ddb807480f580cc328925d5810d4&dn=Terminator+2%3A+Judgment+Day+DC+%281991%29+1080p+BrRip+x264+-+YIFY&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969"
var parsedTorrent = magnet(magnetURI)
var opts = {
infoHash: parsedTorrent.infoHash,
announce: parsedTorrent.announce,
peerId: new Buffer('01234567890123456789'), // hex string or Buffer
port: 6881 // torrent client port
}
var client = new Tracker(opts)
client.scrape();
client.on('scrape', function (data) {
console.log('number of seeders in the swarm: ' + data.complete)
console.log('number of leechers in the swarm: ' + data.incomplete)
});
client.on('error',function(data) {
console.log('erreur');
})

How to send data to specific sockets created using net.createServer() connection event?

I am used to perl and POE programming when it comes to sockets, and I am looking at using node.js for an application server that is not web based. I have JavaScript knowledge from writing webpage user interfaces.
I have been working with the net module and have successfully been able to connect to it from multiple clients at the same time.
var net = require('net');
var port = 63146;
var socketNum = 0;
var adminServer = net.createServer(function(socket){
//add connection count
socketNum++;
socket.nickname = "Con# " + socketNum;
var clientName = socket.nickname;
console.log(clientName + "connected from " + socket.remoteAddress);
socket.write("You have been given the client name of " + clientName);
});
adminServer.listen(port, function() {
console.log("Server listening at" + port);
});
So the issue I am having is if I have another function created that needs to send data to a specific client, not a broadcast to all of them, I can't figure out how to do it.
I have done extensive searching here and Google. Lots of examples of simple tcp servers and echo servers to a single client, but nothing for multiple clients.
I am trying to do this WITHOUT socket.io as not all the clients are going to be web based.
Any help would be appreciated,
Z
You have to store them yourself somehow, whether that's simply adding to an array or adding to an object keyed on some unique identifier for example.
Here's using an object:
var net = require('net');
var port = 63146;
var socketNum = 0;
var sockets = Object.create(null);
var adminServer = net.createServer(function(socket){
//add connection count
socketNum++;
socket.nickname = "Con# " + socketNum;
var clientName = socket.nickname;
sockets[clientName] = socket;
socket.on('close', function() {
delete sockets[clientName];
});
console.log(clientName + " connected from " + socket.remoteAddress);
socket.write("You have been given the client name of " + clientName);
});
adminServer.listen(port, function() {
console.log("Server listening at" + port);
});
Then you can find a particular socket by its assigned nickname.
Here is the example working code. Hopefully this will be useful to others!
var net = require('net');
var port = 63146;
var conSeen = Object.create(null);
var socketNum = 0;
var adminServer = net.createServer(function(socket){
//add connection count
socketNum++;
socket.nickname = "Con" + socketNum;
var clientName = socket.nickname;
//console.log(socket);
conSeen[clientName] = socket;
socket.on('close', function() {
delete sockets[clientName];
});
console.log(clientName + " has connected from " + socket.remoteAddress);
socket.write("You have been given the client name of " + clientName + "\r\n");
socket.on('data', function(inputSeen) {
var clientName = socket.nickname;
var input = inputSeen.toString('utf8');
input = input.replace(/(\r\n|\n|\r)/gm,"");
console.log("Saw : " + input + " from " + clientName + "\r\n");
if (input === 'sendTest') {
conSeen[clientName].write('test 123\r\n');
}
});
});
adminServer.listen(port, function() {
console.log("Server listening on " + port);
});

retry sql connection using JavaScript

I know using javascript is not the best way to connect to a SQL server but this is for an in-house application. I connect using the following:
dbNSConnection = new ActiveXObject("ADODB.Connection") ;
var sNSConnectionString="Driver={SQL Server};TrustedConnection=Yes;Server=" + sNSServer + ";Database=" + sNSDatabase + ";UID=" + sNSUID + ";PWD=" + sNSPWD;
dbNSConnection.Open(sNSConnectionString);
How can I make sure connection has gone thru and how do I retry if not connected?
Isn't there any other way you could get this done on the codebehind, and pass the results to the javascript? This may be an example of what I'm talking about originally.
If not, can't you simply do the following?
try
{
dbNSConnection = new ActiveXObject("ADODB.Connection") ;
var sNSConnectionString="Driver={SQL Server};TrustedConnection=Yes;Server=" + sNSServer + ";Database=" + sNSDatabase + ";UID=" + sNSUID + ";PWD=" + sNSPWD;
dbNSConnection.Open(sNSConnectionString);
//Run rest of query here
}
catch(err)
{
var message = err.message;
//Finish building errors message here
}

Categories

Resources