Detect internet connection in Electron - javascript

Our Electron app needs some configuration files and usually downloads them from our server. In case the client is offline, we don't want him to see any error messages. We are using Electron Download Manager to get the files.
This is how we request the files
try{
DownloadManager.bulkDownload({
urls: links
}, function (error, finished, errors) {
if (error) {
console.log("ERROR: Encountered error during config file download!");
console.log("Finished Files: " + finished);
console.log("Errors: " + errors);
return;
}
console.log("Finished loading all configuration files.");
});
} catch (err){
online_status = false;
console.log("Couldn't get online configuration. Starting app as offline.");
}
With this code the error Uncaught Exception: Error: net::ERR_ADDRESS_UNREACHABLE is thrown, when not connected to the internet.
I tried implementing the official event detection from Electron but as they state:
Such as in cases where the computer is running a virtualization
software that has virtual ethernet adapters that are always
“connected.” Therefore, if you really want to determine the internet
access status of Electron, you should develop additional means for
checking.
Then I went on trying just to ping the server like in this thread but this doesn't work at all for me, it's possible that it doesn't work anymore.

This is a bug in Electron Download Manager, documented in an GitHub Issue like #JeffRSon stated. A pull request is ready for a merge but not merged yet (posted 06.06.2019).
I hope this helps you. I will update this question if it get's merged and works.

Related

Firebase AppCheck web app not working in production mode

I cannot get Firebase AppCheck to work in production mode on a Vue.js project with Firestore and Storage. But It works normally in development.
const appCheck: AppCheck = initializeAppCheck(firebaseApp, {
provider: new ReCaptchaV3Provider(reCaptchaSiteKey),
isTokenAutoRefreshEnabled: true,
});
getToken(appCheck)
.then((result: AppCheckTokenResult) => {
console.log(process.env.NODE_ENV);
console.log(result.token);
})
.catch((e: FirebaseError) => {
console.log(process.env.NODE_ENV);
console.log(e.code + ": " + e.message);
});
In Development mode, using vite, get the token back:
In Production mode, with firebase serve, get appCheck/fecth-status-error:
Firebaser here!
The error you are receiving is due to the App Check backend not being able to verify the underlying reCAPTCHA attestation.
Things to check for:
is reCAPTCHA providing a valid attestation and not somehow thinking your device is a bot?
does the site secret uploaded to App Check for this App match the client ID you are using in the App?
If you are using a Debug Token in your development build, that might explain why that one is succeeding.

Firebase FCM React project issue - firebase-messaging-sw.js wrong type?

Im tryin to get Firebase FCM working in my React project(using webpack )
When trying to getToken() using:
messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
return messaging.getToken();
})
.then(function(token) {
console.log('token')
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
the exception is thrown as follows:
browserErrorMessage: "Failed to register a ServiceWorker: The scrip
has an unsupported MIME type ('text/html')
I understand that this issue is related to the missing service worker file: firebase-messaging-sw.js, which I added to the root of the project but I'm still getting the same error.
Im not sure what im doing wrong here, i've set up vanilla java script project and it works fine ....
Any ideas about this issue ?
For those using create-react-app, you can create the firebase-messaging-sw.js inside public folder and, on index.js add:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
}).catch(function(err) {
console.log('Service worker registration failed, error:', err);
});
}
If you are using create-react-app. Add firebase-messaging-sw.js to your public folder and rebuild. firebase-messaging-sw.js can be an empty file
If you are using firebase, react and you scaffold with create react app things you need to do:
create (or move) a file in the public folder name it firebase-messaging-sw-.js
this issue is because the default route is your root folder, but since the scaffolder uses webpack you can't put the simple file in your root folder, it got to be placed in your public folder or do some config in your webpack dev server to be able to load that file from a different route
register your service worker and associate that file with firebase
you can do this in the index file (bootstrap)
Check that your service worker has been registered in your browser
for chrome you go to Devtools > Application > ServiceWorker and check yours is register
if you have any issue delete you service worker and register it again
(based on #Humble Student answer)
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
.then(function(registration) {
firebase.messaging().useServiceWorker(registration);
}).catch(function(err) {
console.log('Service worker registration failed, error:', err);
});
}
Hope that helps!
In order to receive messages, you will need to create a file called firebase-messaging-sw.js. See the section Handle messages when your web app is in the foreground in the Firebase documentation:
In order to receive the onMessage event, your app must define the Firebase messaging service worker in firebase-messaging-sw.js.
The issue here was that my project setup didn't 'see' service worker file.
Since i'm using node with express, the firebase-messaging-sw.js had to be place where express is picking up static content. In my case line:
server.use(Express.static(path.join(__dirname, '../..', 'dist')));
means that I had to put firebase-messaging-sw.js into /dist folder.
I have the same exact problem as in the original question, and I have gone through all kinds of solutions without any luck over the past 3 days. I am using ReactJS and Webpack. I've tried to include file called firebase-messaging-sw.js in my root folder, but it does nothing.
Someone, please help, since the firebase notification is a much needed feature in the project I am developing...
EDIT.
I managed to solve the registration problem by installing a webpack plugin called sw-precache-webpack-plugin. This plugin autogenerates a service-worker file for you into your build directory.

Every JS file throws error until it's opened and saved on Azure

I'm deploying a node app to Azure, using local git deployment. I have it working without issues in the staging environment (also on Azure) and I'm now setting up a production environment.
Every single file involved in the app throws an error - but as soon as I open that file in my FTP client and just save it, without making changes, the error for that particular file goes away - and the next file used throws an error.
So the steps I took are something like this:
Run deployment, refresh browser.
Get error like Unexpected token ILLEGAL on server.js line 1
Save server.js in FTP client, without making changes.
Restart app, refresh browser.
server.js now has no issues, but the first file it requires, express, gives an error cannot find module ./lib/express on node_modules/express/index.js:11 (./lib/express is definitely there)
Save node_modules/express/index.js:11 in FTP client, without making changes.
Restart app, refresh browser.
Now, node_modules/express/index.js has no issues, but the first file it requires, ./lib/express will then give an error: cannot find module merge-descriptors on node_modules/lib/express.js:16
I'll stop there, but in real life I continued and the behaviour is consistently ongoing - each file errors on the first thing it tries to require, until it's been saved in the FTP client.
To top it all off, I left the app unchanged for 20 minutes, came back, and I was back to the beginning - with an Unexpected token ILLEGAL on server.js line 1 despite NO changes to my code. I tried saving each file and basically just repeated the steps above, getting the same results.
I'm completely stuck and have no idea what to do next short of saving every single file in the codebase. Any idea what could be going on here, or how I could move forwards with debugging the issue?
You most likely have a Byte-Order-Mark at the beginning of your files.
There is a simple gist by Domenic Denicola that shows how you can detect and remove this for all files in the current directory:
var fs = require("fs");
var path = require("path");
var wrench = require("wrench");
var BOM_CHAR_CODE = 65279;
var BOM = String.fromCharCode(BOM_CHAR_CODE);
var fileNames = wrench.readdirSyncRecursive(process.cwd()).filter(function (fileName) {
return path.extname(fileName) === ".js";
});
fileNames.forEach(function (fileName) {
fs.readFile(fileName, "utf8", function (err, fileContents) {
if (err) { throw err; }
if (fileContents.charCodeAt(0) !== BOM_CHAR_CODE) {
fs.writeFile(fileName, BOM + fileContents, "utf8", function (err) {
if (err) { throw err; }
});
}
});
});
After being in touch with Azure support, it turns out the issue was due to WEBSITE_DYNAMIC_CACHE being set to 1, not 0. The feature isn't visible in the azure portal, and is "in development and is currently in private preview." The issue I came across is a known bug with WEBSITE_DYNAMIC_CACHE and node apps.
We're still not sure how / why it got set to 1 in the first place, but it's fixed, so we don't care for now.
What a fun day!

Uncaught Reference Error: LocalFileSystem not defined

This question has been asked before on this forum but I could not find a satisfactory solution to the problem. Hence the question again.
I am trying to download and store a file from the internet into the local file system on my phone. I am getting the following error:
Uncaught ReferenceError: LocalFileSystem is not defined
The code I have so far is:
function storeFile(bucketName, csvfile){
var region;
s3Client.getBucketLocation(params = {Bucket: bucketName},function(err,data){
if(err) console.log("Error :: Cannot retrieve bucket location", err);
else {
console.log(data);
region = data;
}
});
var url = "http://s3-"+region+".amazonaws.com/"+bucketName+"/"+csvfile;
window.requestFileSystem(LocalFileSystem.PERSISTENT,0,
function(fs){
filePath = fs.root.fullPath + "/" + csvfile;
fileTransfer = new FileTransfer();
fileTransfer.download(url, filePath,
function (entry) {
console.log(entry.fullPath); // entry is fileEntry object
},
function (error) {
console.log("Some error");
});
}, function(err){
console.log("Request File System failure");
});
}
Do I need to add any plugins into my app? I already have the File and FileTransfer plugins added. By the way this function is called after onDeviceReady is fired.
EDITED:
I am not working with AngularJs. My code is on NodeJs. Secondly, I have no dependencies like the ionic framework etc. which could possibly present a problem. This same code has been tested on other data which have been successfully downloaded and stored. The problem has occurred after I changed the code to download from a specific location on the amazon server. If someone could address this problem for me, it would be great. I am able to access the bucket and the region through code. The only problem is the LocalFileSystem.
Was able to solve the problem. Just removed and re-added the file and file-transfer plugins.
cordova plugin rm org.apache.cordova.file and cordova plugin rm org.apache.cordova.file-transfer to remove.
cordova plugin add org.apache.cordova.file and cordova plugin add org.apache.cordova.file-transfer to add.
It may tell you that these plugins are soon to be deprecated or something like that. You also have the option of using the later versions. To add you can use
cordova plugin add cordova-plugin-file and cordova plugin add cordova-plugin-file-transfer. Just check if they are available under the respective builds in the platforms folder.

node.js - PM2 log uncaught exceptions to third-party service (as Logentries)

I'm using pm2 (https://github.com/Unitech/pm2) in my node.js project. Also I'm sending logs of errors of the app in Logentries (https://logentries.com).
I wonder is it possible to log uncaught exceptions from the app (when something fails badly and pm2 restarts the app for example)? I know that using process.on('uncaughtException') is bad practice so would like to hear some suggestions.
Thanks!
Where did you read that process.on('uncaughtException') is a bad practice?
As long as you exit the process after logging the exception I don't see what's bad, here is an example:
process.on('uncaughtException', function(e) {
console.error('Ouch, an unhandled exception');
//I like using new Error() for my errors (1)
console.error(e instanceof Error ? e.message : e);
process.exit(1);
});
(1): Javascript Error reference
Edit
pm2-interface is now deprecated, use require('pm2') instead. You will be able to do exactly the same as below by using bus system events.
An alternative with pm2 is to use pm2-interface and listening to the process:exit or process:exception events:
var ipm2 = require('pm2-interface')();
ipm2.on('ready', function() {
console.log('Connected to pm2');
ipm2.bus.on('process:exception', function(data){
console.log(data.pm2_env.name + 'had an exception');
});
});
This is really usefull when managing more than one process through a monitoring process.
You might want to check the blog post on how to build a custom pm2 logger. It can give you some ideas about monitoring processes through pm2-interface.

Categories

Resources