I'm having trouble understanding how to retrieve an XMPP roster (and eventually the presence state of each contact) in node-xmpp (GTalk account).
My example code can login and connect, but I'm a bit lost as to what to send and listen for:
var xmpp = require('node-xmpp')
jid = 'example#gmail.com'
password = 'xxxxxxxxxxxxxx'
// Establish a connection
var conn = new xmpp.Client({
jid: jid,
password: password,
host: 'talk.google.com',
port: 5222
})
conn.on('online', function() {
console.log('ONLINE')
var roster = new xmpp.Element('iq', {
type: 'get',
from: jid,
id: new Date().getTime()
}).c('query', { xmlns: 'jabber:iq:roster' })
conn.send(roster) // Now what?
})
conn.on('error', function(e) {
console.log(e)
})
Looks like the structure of my roster query was wrong, this works correctly:
conn.on('online', function() {
console.log('ONLINE')
var roster = new xmpp.Element('iq', {
id: 'roster_0',
type: 'get'
}).c('query', {
xmlns: 'jabber:iq:roster'
})
conn.send(roster)
})
Related
I'm trying to connect to snowflake database, using snowflake-sdk connector.
First I installed the snowflake-sdk, using the command line:
npm install snowflake-sdk
After I followed all the instructions reported here.
i created the file index.js containing:
var snowflake = require('snowflake-sdk');
var connection = snowflake.createConnection( {
account : 'xxxx.east-us-2'
username: 'MYUSERNAME'
password: 'MYPASSWORD'
}
);
connection.connect(
function(err, conn) {
if (err) {
console.error('Unable to connect: ' + err.message);
}
else {
console.log('Successfully connected to Snowflake.');
}
}
);
and after I run the command node index.js
and I had the Connection error:
Unable to connect: Network error. Could not reach Snowflake.
I Tried again, changing the account value in xxxx.east-us-2.azure.snowflakecomputing.com but nothing changed.
Your account name should include cloud provider as well.
Change the account name as :
var connection = snowflake.createConnection( {
account : 'xxxx.east-us-2.azure'
username: 'MYUSERNAME'
password: 'MYPASSWORD'
}
For full account names refer docs
The issue is with your account name. Please pass your account name as xxxx.east-us-2.azure
Here's the code I used in a tiny issue reproduction that I sent to the Snowflake support people.
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const snowflake = require("snowflake-sdk");
const Q = require("q");
const SNOWFLAKE_HOST_SUFFIX = 'snowflakecomputing.com';
const SNOWFLAKE_ACCOUNT = 'companyname';
function getSFConnection(connParams) {
var d = Q.defer();
let connection = snowflake.createConnection({
account: connParams.account || SNOWFLAKE_ACCOUNT,
username: connParams.user,
password: connParams.password || '',
database: connParams.name,
warehouse: connParams.warehouse
});
connection.connect(function (err, conn) {
if (err) {
console.error('Unable to connect: ' + err.message);
d.reject(err);
}
else {
console.info('Successfully connected as id: ' + connection.getId());
connection.close = function () {
return disconnectSF(connection);
};
d.resolve(connection);
}
});
return d.promise;
}
and I used it like:
getSFConnection({
user: 'username',
account: 'companyname',
password: 'password',
name: '',
warehouse: 'warehouse_name'
}).then...
upon reflection I wonder why I have the host suffix set, but am not using it.. but there it is.
Following is the right config for "snowflake-sdk": "^1.5.3"
var connection = snowflake.createConnection({
account: 'xxx.us-east-1',
username: 'yourUsername',
password: 'yourPassword',
});
Do not specify the region.
region — Deprecated https://docs.snowflake.com/en/user-guide/nodejs-driver-use.html
I want to get the latest email from the email address using imap. I was using searchCriteria 1:2 but I am getting oldest 2 emails, I also used 'NEW' and 'RECENT' but that is also not working. How can I fetch latest emails of my inbox. Here is my code:
var imaps = require('imap-simple');
var config = {
imap: {
user: 'xxxx#gmail.com',
password: 'xxxxx',
host: 'imap.gmail.com',
port: 993,
tls: true,
authTimeout: 3000
}
};
imaps.connect(config).then(function (connection) {
return connection.openBox('INBOX').then(function () {
var searchCriteria = [
'UNSEEN'
];
var fetchOptions =
{ bodies: ['HEADER.FIELDS (FROM TO SUBJECT DATE)'], struct: true }
return connection.search(searchCriteria, fetchOptions).then(function (messages) {
messages.forEach(function (message) {
console.log(message.parts[0].body);
});
});
});
});
I'm saving the users data in an array see the below code
server code
socket.on('add user', function(data) {
if (users.indexOf(data.id) == -1) {
users.push({
id: socket.id,
userId: data.id,
firstName: data.firstName,
lastName: data.lastName
});
}
len = users.length;
len--;
io.emit('user join', users, users[len].userId, users[len].id);
});
I'm sending request from front end to a user for that first i'm checking whether user in online or not for sending request to specific user. If user there I'm assigning user socket.id to userId variable based on that I'm sending data see the below code
server code
socket.on('addNewFriend', function(userId) {
console.log(userId);
for(var i=0;i<users.length;i++){
if(users[i].userId==userId){
var socketid=users[i].id;
console.log(socketid);
io.to(socketid).emit('addFriend',"hai");
}
}
});
Instead of keeping just the socket Id, keep the socket connection itself as well.
users.push({
id: socket.id,
socket: socket
userId: data.id,
firstName: data.firstName,
lastName: data.lastName
});
It would be easier, if you use a map, instead of an array to save users,
users[socket.id] = {
socket: socket
userId: data.id,
firstName: data.firstName,
lastName: data.lastName
}
Then when you want to send a message, use the socket connection,
users[socketId].socket.emit(/*args*/)
If you save sockets in an array instead, you will need to filter the user object manually and then do the same.
Edit: So the full code for the listener is as below,
socket.on('addNewFriend', function(userId) {
for(var i=0;i<users.length;i++){
if(users[i].userId == userId){
var socketId = users[i].id;
console.log(socketId);
users[socketId].socket.emit('addFriend', "hai");
}
}
});
Hye there,
I'm trying to prepare a scheduled script in NetSuite which will pick a particular directory from file cabinet and deploy it on SFTP server. I'm using 2.0 module and here is my code -
require(["N/sftp",'N/record','N/file'], function(sftp,record,file) {
function onRequest() {
var myPwdGuid = "13139ac567b14f74bdaXXXXXXX";
var myHostKey = "AAAAB3NzaC1ycXXXXX";
var connection = sftp.createConnection({
username: 'Your user name',
passwordGuid: myPwdGuid,
url: 'Your host name',
directory: '/directory to upload files/',
hostKey: myHostKey
});
var myFileToUpload = file.create({
name: 'originalname.js',
fileType: file.fileType.PLAINTEXT,
contents: 'I am a test file. Hear me roar.'
});
connection.upload({
directory: 'relative/path/to/remote/dir',
filename: 'newFileNameOnServer.js',
file: myFileToUpload,
replaceExisting: true
});
var downloadedFile = connection.download({
directory: 'relative/path/to/file',
filename: 'downloadMe.js'
});
}
onRequest();
return {
onRequest: onRequest
};
});
Now the issue is when i try to run these lines of code i get an error saying "AN_ERROR_OCCURRED_WHILE_DECRYPT_PASSWORDGUID".
What i've found so far through my research is GUID can only be generated by SuitLet form having credential field which will again require GET and POST method. However i Dont want to create a suitelet and invoke it manually in order to generate GUID. All i want to to do is - Run a scheduled script which will Establish connection to SFTP. Pick a directory in file cabinet and upload it on SFTP.
Any help would be greatly appreciated! Thanks in advance!
Its easier and faster than you might think. Take the below code and load it to NetSuite. Create a script file and deployment quick, run the SUITElet to get your GUID, paste that value into your Scheduled Script and don't mess with it again unless the password changes.
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define([
'N/ui/serverWidget',
'N/https'
],
function (
ui,
https
) {
var HOST_KEY_TOOL_URL = 'https://ursuscode.com/tools/sshkeyscan.php?url=';
function getFormTemplate() {
var form;
form = ui.createForm({
title: 'Password Form'
});
form.addSubmitButton({
label: 'Submit'
});
return form;
}
function addSelectorFields(form) {
var select = form.addField({
id: 'selectaction',
type: ui.FieldType.SELECT,
label: 'Select Action'
});
select.addSelectOption({
value: 'getpasswordguid',
text: 'Get Password GUID'
});
select.addSelectOption({
value: 'gethostkey',
text: 'Get Host Key'
});
return form;
}
function addPasswordGUID1Fields(form) {
var frm = form;
frm.addField({
id: 'restricttoscriptids',
type: ui.FieldType.TEXT,
label: 'Restrict To Script Ids'
}).isMandatory = true;
frm.addField({
id: 'restricttodomains',
type: ui.FieldType.TEXT,
label: 'Restrict To Domains'
}).isMandatory = true;
return frm;
}
function addPasswordGUID2Fields(form, restrictToScriptIds, restrictToDomains) {
form.addCredentialField({
id: 'password',
label: 'Password',
restrictToScriptIds: restrictToScriptIds.replace(' ', '').split(','),
restrictToDomains: restrictToDomains.replace(' ', '').split(',')
});
return form;
}
function addHostKeyFields(form) {
form.addField({
id: 'url',
type: ui.FieldType.TEXT,
label: 'URL (Required)'
});
form.addField({
id: 'port',
type: ui.FieldType.INTEGER,
label: 'Port (Optional)'
});
form.addField({
id: 'hostkeytype',
type: ui.FieldType.TEXT,
label: 'Type (Optional)'
});
return form;
}
function onRequest(option) {
var method;
var form;
var selectAction;
var port;
var hostKeyType;
var restricttoscriptids;
var restricttodomains;
var password;
var theResponse;
var myUrl;
var url;
method = option.request.method;
form = getFormTemplate(method);
if (method === 'GET') {
form = addSelectorFields(form);
}
if (method === 'POST') {
selectAction = option.request.parameters.selectaction;
if (selectAction === 'getpasswordguid') {
form = addPasswordGUID1Fields(form);
} else if (selectAction === 'gethostkey') {
form = addHostKeyFields(form);
} else {
password = option.request.parameters.password;
url = option.request.parameters.url;
port = option.request.parameters.port;
hostKeyType = option.request.parameters.hostkeytype;
restricttoscriptids = option.request.parameters.restricttoscriptids;
restricttodomains = option.request.parameters.restricttodomains;
if (restricttoscriptids && restricttodomains) {
form = addPasswordGUID2Fields(form, restricttoscriptids, restricttodomains);
}
if (password) {
form.addField({
id: 'passwordguidresponse',
type: ui.FieldType.LONGTEXT,
label: 'PasswordGUID Response',
displayType: ui.FieldDisplayType.INLINE
}).defaultValue = password;
}
if (url) {
myUrl = HOST_KEY_TOOL_URL + url + '&port=' + port + '&type=' + hostKeyType;
theResponse = https.get({ url: myUrl }).body;
form.addField({
id: 'hostkeyresponse',
type: ui.FieldType.LONGTEXT,
label: 'Host Key Response',
displayType: ui.FieldDisplayType.INLINE
}).defaultValue = theResponse;
}
}
}
option.response.writePage(form);
}
return {
onRequest: onRequest
};
});
The ability to directly hard-code an SFTP password is not supported in NetSuite. NetSuite uses password tokenization in order to prevent scripts from having access to user credentials. For this reason, only an authenticated user may store a password, and a script may only access it via an identifier (GUID/Token).
im building an application to collect votes for a live event.
the api doesnt give us option to select users from a time frame so im polling the endpoint every second.
i currently have 13 entries that return from the endpoint, i parse them into and array and for loop around them setting my mongoose schema with the attributes and trying to save them, but when i do
db.votes.count() my result is always 1
my node module looks like
var express = require('express');
var unirest = require('unirest');
var voteSchema = require(GLOBAL.rootdir + '/modules/voting/models/votes');
var seconds = 0;
var interval = 1000;
express({
votePoller : setInterval(function () {
seconds++;
if (typeof GLOBAL.accessToken != 'undefined') {
var Request = unirest.get('https://api.domain.io/api/v1/guests');
Request
.header('Accept', 'application/json')
.header('Content-Type', 'application/json; charset=utf-8')
.header('Authorization', 'Bearer ' + GLOBAL.accessToken)
.end(function (response) {
if(response.code === 200){
var votesModel = new voteSchema;
var payloadArray = JSON.parse(response.raw_body);
for(var i in payloadArray.guests){
console.log(i);
console.log(payloadArray.guests[i]);
votesModel.ctid = payloadArray.guests[i].id;
votesModel.email = payloadArray.guests[i].username;
votesModel.voteStatus = 0;
votesModel.createdAt = new Date(1000 * payloadArray.guests[i].created_at);
votesModel.save(function(err) {
if (err) {
console.log(err);
console.log({ message: err });
} else {
console.log({ message: 'vote saved' });
}
});
console.log('Done');
}
}
});
}
console.log(seconds);
}, interval)
});
var votePoller = express;
module.exports = votePoller;
my mongoose model is
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var votesSchema = new Schema({
ctid: { type: String, required: true, unique: true },
fullName: { type: String},
email: { type: String, required: true, unique: true },
mobileNumber: { type: String },
vote: { type: Number},
voteStatus: Boolean,
createdAt: Date
});
var Votes = mongoose.model('Votes', votesSchema);
module.exports = Votes;
the console log counts out each i in the array so why the save function isn't being fired is stumping me
Thanks in advance
You need to use an async function to do an async for loop, there are many answer on here for that code. I would suggest a control flow library like async or if using a new version of node, use native promises instead. Promises all method is the best way to achieve this.