Can I use https.request in vscode extension - https

I am creating a VSCode Extension.
I have added MSTranslator as a node module because I want to call the Microsoft Translator API
but when I run the example either nothing happens,
or I get a Error Connect EACCES. I get this error 2 or 3 times but now it has stopped returning anything, it just jumps the code and continues
I am running this on a MacBook
if (!api_key) {
console.log('missing api_key');
}
var params = {
text: 'How\'s it going?',
from: 'en',
to: 'es'
};
var client = new MsTranslator({ api_key: api_key });
client.initialize_token(function (err) {
if (err) {
console.log("initialize_token", err);
return;
}
client.translate(params, function (err, data) {
if (err) console.log('error:' + err.message);
console.log(data);
process.exit();
});
});
and when it enters client.initialize_token it reaches this line in MsTranslator and does nothing, just jumps out of function.
var req = https.request(self.options, function(res) {
My Radio Silence firewall is switched off, and the network monitor shows no activity.
If I call the same URL using the same details in self.options using Postman, I get back a token as expected.
Is there a problem running https.request within a VSCode extension, or do I have a different problem?

Related

Svelte/Sveltekit and socket.io-client not working in dev (works in preview)

I'm trying to make socket.io-client work in a svelte front end app to talk to an existing API server that already uses socket.io. After a number of challenges, I managed to make this work but I can only get this to work with sveltekit's preview and not in dev mode. Wondered if someone with some knowledge of those could explain why or suggest what I need to do to get it connecting in dev?
svelte 3.34.0
sveltekit next-169
socket.io(-client) 4.2.0
basic code as follows, currently within a file $lib/db.js where I define a few stores that are pulled into the layout for general use..
import { io } from "socket.io-client";
import { browser } from '$app/env';
const initSocket = async () => {
console.log('creating socket...');
let socket = io('http://192.168.1.5:4000', { 'connect timeout': 5000 });
socket.on("connect", () => {
// always works in preview...
console.log('socket created with ID:', socket.id);
});
socket.on("connect_error", (error) => {
// permanently fired in dev...
console.error('Failed to connect', error);
});
socket.on("error", (error) => {
console.error('Error on socket', error);
});
socket.on("foo", data => {
// works in preview when server emits a message of type 'foo'..
console.log("FOO:", data);
});
};
if (browser) {
initSocket();
}
// stores setup and exports omitted..
with svelte-kit preview --host I see the socket creation log message with the socket ID and the same can be seen on the api server where it logs the same ID. The socket works and data is received as expected.
with svelte-kit dev --host however, the log message from socket.on("connect").. is never output and I just see an endless stream of error messages in the browser console from the socket.on("connect_error").. call..
Failed to connect Error: xhr poll error
at XHR.onError (transport.js:31)
at Request.<anonymous> (polling-xhr.js:93)
at Request.Emitter.emit (index.js:145)
at Request.onError (polling-xhr.js:242)
at polling-xhr.js:205
Importantly, there is no attempt to actually contact the server at all. The server never receives a connection request and wireshark/tcpdump confirm that no packet is ever transmitted to 192.168.1.5:4000
Obviously having to rebuild and re-run preview mode on each code change makes development pretty painful, does anyone have insight as to what the issue is here or suggestions on how to proceed?
I've had a similar problem, I solved it by adding this code to svelte.config.js:
const config = {
kit: {
vite: {
resolve: {
alias: {
"xmlhttprequest-ssl": "./node_modules/engine.io-client/lib/xmlhttprequest.js",
},
},
},
},
};
The solution was provided by this comment from the vite issues.

Parse Cloud Code Queries do not return anything ever

I have some parse cloud code im running on my self hosted server but im running into an issue where queries are not doing anything. I can run commands through terminal and get data back but when I run a query.find.. nothing happens. For Example:
Parse.Cloud.job("getall", function(request, response) {
var itemStatus = Parse.Object.extend('MovieStatus');
var query = new Parse.Query(itemStatus);
query.find({
success: function(results) {
console.log(results.length)
response.success(results.length);
},
error: function(err) {
response.error(err);
},
useMasterKey : true
})
})
Nothing happens. No error no response. I have added console logs to make sure its at least getting called and it is, but for some reason nothing every returns from the server when I do query.find
I have tried all sorts of things to figure out what the issue is but this affects all of my cloud code so it has to be something in there.
You are using an old syntax. Since version 3.0, Parse Server supports async/await style. Try this:
Parse.Cloud.job("getall", async request => {
​const { log, message } = request;
const ItemStatus = Parse.Object.extend('MovieStatus');
const query = new Parse.Query(ItemStatus);
const results = await query.find({ useMasterKey: true });
log(response.length);
message(response.length);
})
Not this is a job and not a cloud code function. You can invoke this job using Parse Dashboard and you should see the message in the job status section.

Cannot get the getCallbackTokenAsync to function correctly

I am a newbie to outlook js. I am developing a very simple add-in. The add-in simply will forward a selected email to a defined email address. So we click a button and forward the message. My command handler gets called, but that is about all I have gotten to work. The first problem is the authorization does not appear to work. I have followed the example on https://learn.microsoft.com/en-us/outlook/add-ins/use-rest-api.
The permission in my manifest is set to ReadWriteMailbox.
var accessToken;
Office.onReady(info => {
// If needed, Office.js is ready to be called
Office.context.mailbox.getCallbackTokenAsync({ isRest: true }, function(result) {
if (result.status === "succeeded") {
accessToken = result.value;
} else {
accessToken = "error";
}
});
});
function MyButtonClick(event) {
const message = {
type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
message: "Performed action. Access token: " + accessToken,
icon: "Icon.80x80",
persistent: true
}
Office.context.mailbox.item.notificationMessages.replaceAsync("action", message);
event.completed();
}
I have tried moving the getCallbackTokenAsync all around, but it seems not to work properly. The accessToken is always undefined.
I have been messing with this for the past day. So I am assuming I am missing something.
We are primarily targeting Outlook 2016 on the mac and windows 10.
Any thoughts?
Tom

Cloud Code Error in Saving user

I have a function in my cloud code, which works, but I'm not sure how to fix a problem related to it.
Original Problem:
Parse.Cloud.define("assignTokenToUser", function(request, response) {
console.log("Inside assignTokenToUser");
var token = Math.random().toString(30).substring(7);
query = new Parse.Query("User"),
email = request.params.email;
query.equalTo("username", email);
query.find({ useMasterKey: true }).then(function(results) {
query.first({
success: function(user) {
// Successfully retrieved the object.
user.set("emailToken", token);
user.save();
console.log("success...");
response.success(token);
},
error: function(error) {
console.log("error 1...");
response.error(error);
}
});
}, function(error) {
console.log("error 2...");
response.error(error);
});
});
This seemed to be a common problem after scanning the internet, and my analysis is that the useMasterKey needs to be passed each time we use the query object. Correspondingly, my log file shows that when trying to save the user, it gives a Code 206 error.
Log file output:
Inside assignTokenToUser
success...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: "p66qm34jd80p0j6ne03fe1q7f" functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
going to send an email... with result: p66qm34jd80p0j6ne03fe1q7f
fullLink: https://beatthegym.com/emailVerified?username=maryam.zafar#emumba.com&token=p66qm34jd80p0j6ne03fe1q7f
^[[31merror^[[39m: Error generating response. ParseError { code: 206, message: 'Cannot modify user 4m0VZFsKVt.' } code=206, message=Cannot modify user 4m0VZFsKVt.
[object Object]
So I went on to change my code to the following:
Code:
Parse.Cloud.define("assignTokenToUser", function(request, response) {
console.log("Inside assignTokenToUser");
var token = Math.random().toString(30).substring(7);
query = new Parse.Query("User"),
email = request.params.email;
query.equalTo("username", email);
query.find({ useMasterKey: true }).then(function(results) {
console.log("inside query.find...");
query.first(null, { useMasterKey: true }).then(function(user) {
console.log("inside query.first...");
// Successfully retrieved the object.
user.set("emailToken", token);
user.save(null, { useMasterKey: true }).then(function() {
console.log("inside user.save...");
response.success();
}, function(error) {
response.error(error);
});
response.success(token);
},
function(error) {
console.log("error 1...");
response.error(error);
});
}, function(error) {
console.log("error 2...");
response.error(error);
});
});
Log file:
Inside assignTokenToUser
inside query.find...
inside query.first...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: "tqc8m9lo2tcsrqn69c3q0e1q7f" functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
inside user.save...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: undefined functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
[object Object]
Now, the log file gives me a user as "undefined", and the call to the function gives me a pending status in the Chrome Network tab in the Inspector tool, until it turns into 502, and then the request is auto generated by the browser again. All other requests get a correct 200 response.
However, the data seems to be saved.. the record against this email address saves the token generated correctly. But the request from the browser fails and the user is "undefined" while in the original log file, I see the correct user Id... everytime it fails, the function automatically runs again (because the browser is generating another request everytime it gets a 502) and since it is actually supposed to send an email, it's running again and again keeps on generating infinate emails...
Thank you in advance..
Understood this finally:
The user will remain undefined until and unlesss I obtain it using the Parse.User.current() method. The data does save into the database because it is a forced update to the record, however until the user is aunthenticated using the current() method, it will remain undefined.
I see this is an old post but I spotted clear error in the code:
query = new Parse.Query("User")
Should be:
query = new Parse.Query(Parse.User)
Or at least:
query = new Parse.Query("_User")
As User is a predefined class in Parse.

Cannot submit form with supertest and mocha

I am using supertest and mocha to test a nodejs application. One of the things users can do is to submit a very simple form, which is picked up by the node server and parsed using formidable.
Here is the mocha test code:
var should = require('should'),
express = require('express'),
app = require('../app.js'),
request = require('supertest'),
csrfToken,
sessionId,
cookies = [];
describe('Post Handler', function(){
it('Uploads new post', function(done){
var req = request(app).post('/post?_csrf=' + csrfToken);
req.cookies = cookies;
req
.type('form')
.send({fieldTitle: 'autopost'})
.send({fieldContent: 'autocontent'})
.send({contentType: 'image/png'})
.send({blobId: 'icon_23943.png'})
.expect(200)
.end(function(error, res){
console.log('here');
done();
});
});
csrfToken retrieves a csrf token from the server, since I am using the csurf module and every POST method requires a csrf token. cookies stores the session cookie that is provided by the node server so I can persist the session between requests.
The form is processed by the following code:
//Takes HTTP form posted by client and creates a new post in the Db
exports.postPostUpload = function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
console.log(err);
if (err) res.redirect(303, '/error');
else {
var new_post = new post_model.Post().createNewPost(fields);
new_post.setUserId(req.session.passport.user.userId);
new_post.uploadPostToDb(function (error, result) {
if (error) return res.status(500).end();
else {
if (new_post.media.contentType.indexOf('video') !== -1) {
addMessageToEncodingQueue(new_post, function (error, result, response) {
if (error) {
errorHelper.reportError({
stack: new Error().stack,
error: error
});
res.status(500).end();
}
else res.status(200).send(new_post.cuid);
});
}
else return res.status(200).send(new_post.cuid);
}
});
}
});
}
My current problem is, that once the form handler executes the line form.parse(req, function (err, fields, files) {, nothing happens. Formidable does not return error, it just does not return anything. Consequently, the mocha test never receives a reply from the server, and eventually the socket hangs and the test crashes. Needless to say, the form is successfully submit if you do it manually via the website.
There must be an error in the way supertest/mocha are executing this test, but I have not been able to find it. Any pointers are highly appreciated.

Resources