Mobile notifications

This commit is contained in:
Vicente J. Ruiz Jurado 2018-08-02 12:42:19 +02:00
parent 47e9c18607
commit bf926514c9
13 changed files with 762 additions and 506 deletions

View file

@ -8,7 +8,12 @@ This is web service that notifies about fires detected in an area of your intere
Prerrequisites: a running meteor (we share the `fuegos` database with the telegram bot). Prerrequisites: a running meteor (we share the `fuegos` database with the telegram bot).
Install `meteor` and run `npm start` Install `meteor` and run `meteor npm install` and `npm start`
Some other development deps (in debian & ubuntu):
```
apt-get install libcairo2-dev libjpeg-dev libgif-dev pkg-config
```
### GeoIP ### GeoIP

View file

@ -2,6 +2,7 @@
/* eslint-disable import/no-absolute-path */ /* eslint-disable import/no-absolute-path */
import { Mongo } from 'meteor/mongo'; import { Mongo } from 'meteor/mongo';
import { Meteor } from 'meteor/meteor';
import SimpleSchema from 'simpl-schema'; import SimpleSchema from 'simpl-schema';
import { defaultCreatedAt, defaultUpdateAt } from '/imports/api/Utility/Utils.js'; import { defaultCreatedAt, defaultUpdateAt } from '/imports/api/Utility/Utils.js';
import LocationSchema from '/imports/api/Utility/LocationSchema.js'; import LocationSchema from '/imports/api/Utility/LocationSchema.js';
@ -22,11 +23,12 @@ Notifications.deny({
Notifications.schema = new SimpleSchema({ Notifications.schema = new SimpleSchema({
userId: String, userId: String,
subsId: { type: Meteor.Collection.ObjectID, optional: true, blackbox: true },
content: String, content: String,
geo: LocationSchema, geo: LocationSchema,
type: String, type: String,
webNotified: { type: Boolean, optional: true }, notified: { type: Boolean, optional: true },
webNotifiedAt: { type: Date, optional: true }, notifiedAt: { type: Date, optional: true },
emailNotified: { type: Boolean, optional: true }, emailNotified: { type: Boolean, optional: true },
emailNotifiedAt: { type: Date, optional: true }, emailNotifiedAt: { type: Date, optional: true },
when: Date, when: Date,

View file

@ -8,7 +8,7 @@ Meteor.methods({
check(notifId, Meteor.Collection.ObjectID); check(notifId, Meteor.Collection.ObjectID);
try { try {
Notifications.update(notifId, { $set: { webNotified: true, webNotifiedAt: new Date() } }); Notifications.update(notifId, { $set: { notified: true, notifiedAt: new Date() } });
return notifId; return notifId;
} catch (exception) { } catch (exception) {
throw new Meteor.Error('500', exception); throw new Meteor.Error('500', exception);

View file

@ -4,7 +4,7 @@ import { Meteor } from 'meteor/meteor';
import Notifications from '../Notifications'; import Notifications from '../Notifications';
Meteor.publish('mynotifications', function notifications() { Meteor.publish('mynotifications', function notifications() {
const notif = Notifications.find({ userId: this.userId, type: 'web', webNotified: null }); const notif = Notifications.find({ userId: this.userId, type: 'web', notified: null });
// console.log(`Notifications for user ${this.userId}: ${notif.count()}`); // console.log(`Notifications for user ${this.userId}: ${notif.count()}`);
return notif; return notif;
}); });

View file

@ -9,6 +9,7 @@ import SiteSettings from '/imports/api/SiteSettings/SiteSettings';
import FalsePositives from '/imports/api/FalsePositives/FalsePositives'; import FalsePositives from '/imports/api/FalsePositives/FalsePositives';
import Industries from '/imports/api/Industries/Industries'; import Industries from '/imports/api/Industries/Industries';
import IndustryRegistries from '/imports/api/Industries/IndustryRegistries'; import IndustryRegistries from '/imports/api/Industries/IndustryRegistries';
import Notifications from '/imports/api/Notifications/Notifications';
import { Mongo } from 'meteor/mongo'; import { Mongo } from 'meteor/mongo';
Meteor.startup(() => { Meteor.startup(() => {
@ -227,6 +228,18 @@ Meteor.startup(() => {
} }
}); });
Migrations.add({
version: 17,
up: function renameWebNotifiedField() {
Notifications.update({ webNotified: { $exists: true } }, {
$rename: { webNotifiedAt: 'notifiedAt' }
}, { upsert: false, multi: true });
Notifications.update({ webNotified: { $exists: true } }, {
$rename: { webNotified: 'notified' }
}, { upsert: false, multi: true });
}
});
// Set createdAt in users & subs // Set createdAt in users & subs
Migrations.migrateTo('latest'); Migrations.migrateTo('latest');

View file

@ -10,13 +10,19 @@ import sendEmail, { subjectTruncate } from '/imports/modules/server/send-email';
// import { hr } from '/imports/startup/server/email'; // import { hr } from '/imports/startup/server/email';
import getEmailOf from '/imports/modules/get-email-of-user'; import getEmailOf from '/imports/modules/get-email-of-user';
import image from 'google-maps-image-api-url'; import image from 'google-maps-image-api-url';
import gcm from 'node-gcm';
import { trim } from '/imports/ui/components/NotificationsObserver/util.js'; import { trim } from '/imports/ui/components/NotificationsObserver/util.js';
Meteor.startup(() => { Meteor.startup(() => {
if (!(Meteor.settings.private.fcmApiToken && Meteor.settings.private.fcmApiToken.length > 0)) {
console.warn('Missing settings.private.fcmApiToken key, mobile notifications will not work');
}
const fcmSender = new gcm.Sender(Meteor.settings.private.fcmApiToken);
// https://www.npmjs.com/package/google-maps-image-api-url // https://www.npmjs.com/package/google-maps-image-api-url
// https://stackoverflow.com/questions/24355007/is-there-no-way-to-embed-a-google-map-into-an-html-email // https://stackoverflow.com/questions/24355007/is-there-no-way-to-embed-a-google-map-into-an-html-email
// https://developers.google.com/maps/documentation/static-maps/intro // https://developers.google.com/maps/documentation/static-maps/intro
function imgUrl(lat, lng) { function imgUrl(lat, lng) {
return image({ return image({
key: Meteor.settings.gmaps.key, key: Meteor.settings.gmaps.key,
@ -36,7 +42,48 @@ Meteor.startup(() => {
} */ } */
function process(notif) { function process(notif) {
if (notif.type === 'web' && !notif.emailNotified) { if (notif.type === 'mobile' && !notif.notified) {
const user = Meteor.users.findOne({ _id: notif.userId });
moment.locale(user.lang);
// duplicate code below
const body = `${trim(notif.content)} (${i18n.t('fireDetectedAt', { when: dateLongFormat(notif.when) })}).`;
// https://firebase.google.com/docs/cloud-messaging/concept-options
const msg = new gcm.Message();
msg.addNotification({
title: i18n.t('Alerta de fuego'),
body,
click_action: 'FLUTTER_NOTIFICATION_CLICK',
tag: notif._id, // prevent duplication of fire notifications
sound: 'default', // Indicates sound to be played. Supports only default currently.
icon: 'launch_image' // 'ic_launcher'
});
msg.addData('id', notif._id);
msg.addData('description', body);
msg.addData('lat', notif.geo.coordinates[1]);
msg.addData('lon', notif.geo.coordinates[0]);
msg.addData('when', notif.when);
msg.addData('subsId', notif.subsId._str);
msg.addData('sealed', notif.sealed);
const registrationTokens = [];
if (!user.fireBaseToken) {
console.warn('This mobile user doesn\'t have a firebase registration token');
} else {
registrationTokens.push(user.fireBaseToken);
// FIXME: better join users
fcmSender.send(msg, { registrationTokens }, (err, response) => {
if (err) {
console.error(err);
} else {
// console.log(response);
Notifications.update(notif._id, { $set: { notified: true, notifiedAt: new Date() } });
}
});
}
} else if (notif.type === 'web' && !notif.emailNotified) {
const user = Meteor.users.findOne({ _id: notif.userId }); const user = Meteor.users.findOne({ _id: notif.userId });
const { firstName, emailAddress } = getEmailOf(user); const { firstName, emailAddress } = getEmailOf(user);

View file

@ -3,7 +3,7 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor'; import { Meteor } from 'meteor/meteor';
import { Line } from 'react-progressbar.js'; import { Line } from 'react-progress-bar.js';
import './LoadingBar.scss'; import './LoadingBar.scss';

View file

@ -12,7 +12,7 @@ import { trim } from './util.js';
function process(notif) { function process(notif) {
// No already notified // No already notified
if (Push.Permission.has()) { if (Push.Permission.has()) {
if (!notif.webNotified) { if (!notif.notified && notif.type === 'web') {
Push.create(i18n.t('AppName'), { Push.create(i18n.t('AppName'), {
body: `${trim(notif.content)} (${i18n.t('fireDetected', { when: dateFromNow(notif.when) })})`, body: `${trim(notif.content)} (${i18n.t('fireDetected', { when: dateFromNow(notif.when) })})`,
icon: '/n-fire-marker.png', icon: '/n-fire-marker.png',
@ -47,7 +47,7 @@ Meteor.startup(() => {
if (Meteor.userId()) { if (Meteor.userId()) {
Meteor.subscribe('mynotifications'); Meteor.subscribe('mynotifications');
// Check for notifications not processed at startup // Check for notifications not processed at startup
Notifications.find({ webNotified: null }).forEach((notif) => { Notifications.find({ notified: null, type: 'web' }).forEach((notif) => {
process(notif); process(notif);
}); });
} }

1170
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -52,7 +52,9 @@
"modernizr": "^3.6.0", "modernizr": "^3.6.0",
"moment": "^2.19.1", "moment": "^2.19.1",
"moment-timezone": "^0.5.14", "moment-timezone": "^0.5.14",
"node-gcm": "^1.0.2",
"node-geocoder": "^3.21.1", "node-geocoder": "^3.21.1",
"node-gyp": "^3.7.0",
"nodemailer": "^4.4.2", "nodemailer": "^4.4.2",
"npm": "^5.8.0", "npm": "^5.8.0",
"pm2-master": "^1.1.3", "pm2-master": "^1.1.3",
@ -75,7 +77,7 @@
"react-leaflet-google": "^3.2.1", "react-leaflet-google": "^3.2.1",
"react-leaflet-sidebarv2": "^0.5.1", "react-leaflet-sidebarv2": "^0.5.1",
"react-places-autocomplete": "^5.4.3", "react-places-autocomplete": "^5.4.3",
"react-progressbar.js": "git://github.com/squarecat/react-progressbar.js.git", "react-progress-bar.js": "^0.2.3",
"react-resize-detector": "^1.1.0", "react-resize-detector": "^1.1.0",
"react-router-bootstrap": "^0.24.4", "react-router-bootstrap": "^0.24.4",
"react-router-dom": "^4.2.2", "react-router-dom": "^4.2.2",

View file

@ -250,5 +250,6 @@
"Hay más información sobre un fuego": "Hay más información sobre un fuego":
"There is more information about a fire", "There is more information about a fire",
"esDecirTalDia": "That is on {{date}}", "esDecirTalDia": "That is on {{date}}",
"Actualizando...": "Updating..." "Actualizando...": "Updating...",
"Alerta de fuego": "Alert of fire"
} }

View file

@ -335,5 +335,6 @@
"Hay más información sobre un fuego": "Hay más información sobre un fuego":
"Hay más información sobre un fuego", "Hay más información sobre un fuego",
"esDecirTalDia": "Es decir el {{date}}", "esDecirTalDia": "Es decir el {{date}}",
"Actualizando...": "Actualizando..." "Actualizando...": "Actualizando...",
"Alerta de fuego": "Alerta de fuego"
} }

View file

@ -31,6 +31,7 @@
"loginStyle": "popup" "loginStyle": "popup"
} }
}, },
"fcmApiToken": "",
"proxies_count": 0, "proxies_count": 0,
"ironPassword": "SomePasswordAlLeast32LongYouKnowHowToCount", "ironPassword": "SomePasswordAlLeast32LongYouKnowHowToCount",
"internalApiToken": "someSimilarPasswordForUseOurAPIinternally", "internalApiToken": "someSimilarPasswordForUseOurAPIinternally",