Added cron tweets for active fires in 'es' and 'pt'

This commit is contained in:
vjrj 2018-03-17 20:06:00 +01:00
parent c99559d442
commit 0c56bcf7e0
9 changed files with 252 additions and 3 deletions

View file

@ -0,0 +1,64 @@
/* eslint-disable import/no-absolute-path */
import { whichAreFalsePositives, firesUnion } from '/imports/api/FalsePositives/server/publications';
import FalsePositives from '/imports/api/FalsePositives/FalsePositives';
import Industries from '/imports/api/Industries/Industries';
import ActiveFires from '../ActiveFires';
const cleanProv = (prov, stringsToRemove) => {
let lprov = prov;
stringsToRemove.forEach((st) => {
lprov = lprov.replace(st, '');
});
return lprov;
};
const findFiresInRegion = (zone) => {
const result = ActiveFires.find({
ourid: {
$geoWithin: {
$geometry: zone.geometry
}
}
});
/* console.log(`False positive total: ${falsePos.count()}`);
console.log(`False positives: ${JSON.stringify(falsePos.fetch())}`); */
return result;
};
const countFires = (regions, stringsToRemove) => {
let total = 0;
const fireStats = {};
regions.features.forEach((region) => {
const regionName = cleanProv(region.properties.name, stringsToRemove);
try {
const fires = findFiresInRegion(region);
// TODO Also check neighbour fires (when better implementation of that part)
let count = fires.count();
if (count > 0) {
/* console.log(regionName);
* console.log(count); */
fires.forEach((fire) => {
const union = firesUnion([fire]);
const falsePos = whichAreFalsePositives(FalsePositives, union);
const industries = whichAreFalsePositives(Industries, union);
if (falsePos.count() > 0 || industries.count() > 0) {
count -= 1;
}
});
// console.log(count);
if (count > 0) {
total += count;
fireStats[regionName] = count;
}
}
// console.log(countFiresInRegion(prov));
} catch (e) {
console.log(e);
}
});
return { total, fires: fireStats };
};
export default countFires;

View file

@ -0,0 +1,68 @@
/* eslint-disable import/no-absolute-path */
import getPrivateFile from '/imports/modules/server/get-private-file';
import { Meteor } from 'meteor/meteor';
import tbuffer from '@turf/buffer';
import tweet from '/imports/modules/server/twitter';
import countFires from './countFires';
const autonomies = tbuffer(JSON.parse(getPrivateFile('data/es-atlas-autonomies.json')), 0);
const portugal = tbuffer(JSON.parse(getPrivateFile('data/pt-atlas.json')), 0);
const stringsToRemove = [
'Ciudad Autónoma de',
'País Vasco/',
'Comunidad Foral de',
'Región de',
'Comunidad de',
'Cataluña/',
'Castilla-',
'Principado de',
' '
];
const composeTweet = (num, stats) => {
if (num <= 0) {
return '';
}
const keys = Object.keys(stats);
const numZones = keys.length;
let text = '';
keys.map((key, index) => { // , index
const zoneFires = stats[key];
const zoneFiresText = zoneFires > 1 ? index === 0 ? zoneFires : `otros ${zoneFires}` : index === 0 ? 'Un' : 'otro';
const what = index > 0 ? ' ' : zoneFires > 1 ? ' fuegos activos ' : ' fuego activo ';
const subText = `${zoneFiresText}${what}en #${key}`;
const delimiter = index === numZones - 1 ? ' y' : ',';
const subTexts = index === 0 ? subText : `${delimiter} ${subText}`;
text += subTexts;
return '';
});
return `${text}`;
};
const tweetHeaders = ['🔥 '];
const tweetFooters = ['Más info en: https://fuegos.comunes.org/fires'];
const tweetFires = () => {
const resultEs = countFires(autonomies, stringsToRemove);
const resultPt = countFires(portugal, stringsToRemove);
const fires = Object.assign(resultEs.fires, resultPt.fires);
const total = resultEs.total + resultPt.total;
// console.log(`Total fires ${total}, ${JSON.stringify(fires)}`);
if (total > 0) {
const tweetText = `${tweetHeaders[0]} ${composeTweet(total, fires)}. ${tweetFooters[0]}`;
if (Meteor.isDevelopment) {
console.log(tweet);
} else {
tweet(tweetText, 'es');
}
}
};
if (Meteor.isDevelopment) {
tweetFires();
}
export { composeTweet, tweetHeaders, tweetFooters, tweetFires };

View file

@ -18,7 +18,8 @@ Meteor.publish('falsePositivesTotal', function total() {
export const firesUnion = (fires) => {
const group = new L.FeatureGroup();
const remap = fires.fetch().map(function remap(doc) {
const firesArray = Array.isArray(fires) ? fires : fires.fetch(); // if not is a cursor
const remap = firesArray.map(function remap(doc) {
// default scan: 1 for neightbor alerts
return { location: { lat: doc.lat, lon: doc.lon }, distance: doc.scan || 1 };
});

View file

@ -1,6 +1,8 @@
/* global SyncedCron */
/* eslint-disable import/no-absolute-path */
import { Meteor } from 'meteor/meteor';
import { tweetFires } from '/imports/api/ActiveFires/server/tweetFiresInZone';
// https://github.com/thesaucecode/meteor-synced-cron/
@ -42,13 +44,19 @@ Meteor.startup(() => {
// context: {
// userID: 'xyz'
// },
schedule: parser =>
schedule: (parser) => {
// this.magic = true; // Context is accesible here as this context.
// parser is a later.parse object
// return parser.text('every 2 minutes');
// http://bunkat.github.io/later/
parser.text('at 9:15 am also at 15:15 pm also at 22:00 pm'),
const sched = parser.text(Meteor.settings.private.twitter.es.when);
if (sched.error !== -1) {
console.error(`Twitter cron 'when' field parsed with errors: ${sched.error}`);
}
return sched;
},
job: () => {
tweetFires();
// console.log('cron is working');
/* console.log(this.userID) // Context Object becomes this argument
* console.log(this.magic) /

63
package-lock.json generated
View file

@ -20,6 +20,46 @@
"faker": "4.1.0"
}
},
"@turf/bbox": {
"version": "5.1.5",
"resolved": "https://registry.npmjs.org/@turf/bbox/-/bbox-5.1.5.tgz",
"integrity": "sha1-MFHfUUrUxQ9KT5uKLRX9i2hA7aM=",
"requires": {
"@turf/helpers": "5.1.5",
"@turf/meta": "5.2.0"
}
},
"@turf/buffer": {
"version": "5.1.5",
"resolved": "https://registry.npmjs.org/@turf/buffer/-/buffer-5.1.5.tgz",
"integrity": "sha1-hByWJ8+5dLEirE4alW8EZrwCMcQ=",
"requires": {
"@turf/bbox": "5.1.5",
"@turf/center": "5.1.5",
"@turf/helpers": "5.1.5",
"@turf/meta": "5.2.0",
"@turf/projection": "5.1.5",
"d3-geo": "1.7.1",
"turf-jsts": "1.2.2"
}
},
"@turf/center": {
"version": "5.1.5",
"resolved": "https://registry.npmjs.org/@turf/center/-/center-5.1.5.tgz",
"integrity": "sha1-RKss2VT2PA03dX9xWKmcPvURS4A=",
"requires": {
"@turf/bbox": "5.1.5",
"@turf/helpers": "5.1.5"
}
},
"@turf/clone": {
"version": "5.1.5",
"resolved": "https://registry.npmjs.org/@turf/clone/-/clone-5.1.5.tgz",
"integrity": "sha1-JT6NNUdxgZduM636tQoPAqfw42c=",
"requires": {
"@turf/helpers": "5.1.5"
}
},
"@turf/helpers": {
"version": "5.1.5",
"resolved": "https://registry.npmjs.org/@turf/helpers/-/helpers-5.1.5.tgz",
@ -33,6 +73,16 @@
"@turf/helpers": "5.1.5"
}
},
"@turf/projection": {
"version": "5.1.5",
"resolved": "https://registry.npmjs.org/@turf/projection/-/projection-5.1.5.tgz",
"integrity": "sha1-JFF+7rLzaBa6n3EueubWo2jt91c=",
"requires": {
"@turf/clone": "5.1.5",
"@turf/helpers": "5.1.5",
"@turf/meta": "5.2.0"
}
},
"@turf/truncate": {
"version": "5.1.5",
"resolved": "https://registry.npmjs.org/@turf/truncate/-/truncate-5.1.5.tgz",
@ -2933,6 +2983,19 @@
"es5-ext": "0.10.37"
}
},
"d3-array": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-1.2.1.tgz",
"integrity": "sha512-CyINJQ0SOUHojDdFDH4JEM0552vCR1utGyLHegJHyYH0JyCpSeTPxi4OBqHMA2jJZq4NH782LtaJWBImqI/HBw=="
},
"d3-geo": {
"version": "1.7.1",
"resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-1.7.1.tgz",
"integrity": "sha512-O4AempWAr+P5qbk2bC2FuN/sDW4z+dN2wDf9QV3bxQt4M5HfOEeXLgJ/UKQW0+o1Dj8BE+L5kiDbdWUMjsmQpw==",
"requires": {
"d3-array": "1.2.1"
}
},
"d3-queue": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/d3-queue/-/d3-queue-2.0.3.tgz",

View file

@ -8,6 +8,7 @@
"dependencies": {
"@cleverbeagle/dates": "^0.5.1",
"@cleverbeagle/seeder": "^1.3.1",
"@turf/buffer": "^5.1.5",
"@turf/truncate": "^5.1.5",
"@turf/union": "^5.1.5",
"babel-runtime": "^6.26.0",

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

42
test/tweets.test.js Normal file
View file

@ -0,0 +1,42 @@
/* eslint-env mocha */
/* eslint-disable func-names, prefer-arrow-callback */
/* eslint-disable import/no-absolute-path */
import { chai } from 'meteor/practicalmeteor:chai';
import { composeTweet } from '/imports/api/ActiveFires/server/tweetFiresInZone';
describe('compose tweets of fires', () => {
it('No fires', async () => {
chai.expect('').to.deep.equal(composeTweet(0, { }));
});
it('a fire in a zone', async () => {
chai.expect('Un fuego activo en #Asturias').to.deep.equal(composeTweet(1, { Asturias: 1 }));
});
it('some fires in a zone', async () => {
chai.expect('4 fuegos activos en #Asturias').to.deep.equal(composeTweet(4, { Asturias: 4 }));
});
it('some fires in two zones', async () => {
chai.expect('Un fuego activo en #Asturias y otros 4 en #Madrid').to.deep.equal(composeTweet(5, { Asturias: 1, Madrid: 4 }));
});
it('some fires in some zones', async () => {
chai.expect('3 fuegos activos en #Catalunya, otro en #Asturias y otros 4 en #Madrid').to.deep.equal(composeTweet(8, { Catalunya: 3, Asturias: 1, Madrid: 4 }));
});
it('other fires in some zones', async () => {
chai.expect('Un fuego activo en #Catalunya, otro en #Asturias y otros 4 en #Madrid').to.deep.equal(composeTweet(6, { Catalunya: 1, Asturias: 1, Madrid: 4 }));
});
it('other fires in two zones', async () => {
chai.expect('Un fuego activo en #Catalunya y otro en #Asturias').to.deep.equal(composeTweet(2, { Catalunya: 1, Asturias: 1 }));
});
it('many fires in many zones', async () => {
chai.expect('3 fuegos activos en #Cataluña, otro en #Cantabria, otros 4 en #Andalucia, otro en #Galicia y otros 2 en #Madrid').to.deep.equal(composeTweet(11, {
Cataluña: 3, Cantabria: 1, Andalucia: 4, Galicia: 1, Madrid: 2
}));
});
});