diff --git a/.gitignore b/.gitignore index da6ed88..603fb12 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,18 @@ node_modules settings-demo.json settings-staging.json settings-production.json +settings-development.json +private/GeoLite2-City.mmdb* +npm-debug.log +**/.sass-cache +.deploy/ +public/locales/undefined/ +.deploy-staging +.screenshots +.vscode +output.json + +# fase-0 higiene: variantes de settings con secretos (no versionar) +settings-production-*.json +settings-tests.json +*.json~ diff --git a/.meteor/packages b/.meteor/packages index c710a80..5cca156 100644 --- a/.meteor/packages +++ b/.meteor/packages @@ -4,32 +4,66 @@ # 'meteor add' and 'meteor remove' will edit this file for you, # but you can also edit it by hand. -meteor-base@1.1.0 # Packages every Meteor app needs to have -mobile-experience@1.0.4 # Packages for a great mobile UX -mongo@1.1.18 # The database Meteor supports right now +meteor-base@1.3.0 # Packages every Meteor app needs to have +mobile-experience@1.0.5 # Packages for a great mobile UX +mongo@1.4.7 # The database Meteor supports right now reactive-var@1.0.11 # Reactive variable for tracker tracker@1.1.3 # Meteor's client-side reactive programming library -standard-minifier-css@1.3.4 # CSS minifier run for production mode -standard-minifier-js@2.1.0 # JS minifier run for production mode -es5-shim@4.6.15 # ECMAScript 5 compatibility for older browsers. -ecmascript@0.8.0 # Enable ECMAScript2015+ syntax in app code -shell-server@0.2.3 # Server-side component of the `meteor shell` command +standard-minifier-css@1.4.0 # CSS minifier run for production mode +standard-minifier-js@2.3.1 # JS minifier run for production mode +es5-shim@4.7.0 # ECMAScript 5 compatibility for older browsers. +ecmascript@0.10.6 # Enable ECMAScript2015+ syntax in app code +shell-server@0.3.1 # Server-side component of the `meteor shell` command react-meteor-data alanning:roles fourseven:scss -twbs:bootstrap -accounts-base@1.3.0 -accounts-password@1.3.6 +accounts-base@1.4.2 +accounts-password@1.5.0 service-configuration@1.0.11 -accounts-facebook@1.2.0 -accounts-github@1.3.0 -accounts-google@1.2.0 +accounts-facebook@1.3.1 +accounts-github@1.4.1 +accounts-google@1.3.1 themeteorchef:bert fortawesome:fontawesome -aldeed:collection2-core@2.0.0 +aldeed:collection2-core@2.0.1 audit-argument-checks@1.0.7 ddp-rate-limiter@1.0.7 -dynamic-import +dynamic-import@0.3.0 static-html +alexwine:bootstrap-4 + +selaias:cookie-consent # Cookie consent +gadicc:blaze-react-component # Add braze to react +255kb:meteor-status # Connect status +# mixmax:smart-disconnect # Disconnect on lost focus (disabled to get notif) +flowkey:raven # js errors +vjrj:piwik # Stats +mdg:geolocation +natestrauser:publish-performant-counts +maximum:server-transform +mys:fonts # fonst in npm +ostrio:mailer # mailer +# babrahams:constellation # dev utility +percolate:migrations # db migrations +ostrio:meteor-root +meteortesting:mocha +practicalmeteor:chai +aldeed:schema-deny +aldeed:template-extension +dburles:collection-helpers +less@2.7.11 +markdown@1.0.12 +mongo-livedata@1.0.12 +reywood:publish-composite +barbatus:stars-rating +arkham:comments-ui +facts@1.0.9 +gadicohen:sitemaps +nspangler:autoreconnect +saucecode:timezoned-synced-cron +# lmachens:kadira +meteorhacks:zones +nimble:restivus +xolvio:cleaner diff --git a/.meteor/release b/.meteor/release index 025f64e..011385b 100644 --- a/.meteor/release +++ b/.meteor/release @@ -1 +1 @@ -METEOR@1.5 +METEOR@1.6.1.1 diff --git a/.meteor/versions b/.meteor/versions index d3915c8..9cbf1c3 100644 --- a/.meteor/versions +++ b/.meteor/versions @@ -1,104 +1,155 @@ -accounts-base@1.3.0 -accounts-facebook@1.2.0 -accounts-github@1.3.0 -accounts-google@1.2.0 +255kb:meteor-status@1.5.0 +accounts-base@1.4.2 +accounts-facebook@1.3.1 +accounts-github@1.4.1 +accounts-google@1.3.1 accounts-oauth@1.1.15 -accounts-password@1.3.6 +accounts-password@1.5.1 alanning:roles@1.2.16 -aldeed:collection2-core@2.0.1 -allow-deny@1.0.5 +aldeed:collection2-core@2.1.2 +aldeed:schema-deny@2.0.1 +aldeed:template-extension@4.1.0 +alexwine:bootstrap-4@4.1.0 +allow-deny@1.1.0 +arkham:comments-ui@1.4.4 audit-argument-checks@1.0.7 -autoupdate@1.3.12 -babel-compiler@6.19.1 -babel-runtime@1.0.1 -base64@1.0.10 +autoupdate@1.4.0 +babel-compiler@7.0.7 +babel-runtime@1.2.2 +barbatus:stars-rating@1.1.1 +base64@1.0.11 binary-heap@1.0.10 blaze@2.3.2 blaze-tools@1.0.10 -boilerplate-generator@1.1.0 -caching-compiler@1.1.9 +boilerplate-generator@1.4.0 +browser-policy@1.1.0 +browser-policy-common@1.0.11 +browser-policy-content@1.1.0 +browser-policy-framing@1.1.0 +caching-compiler@1.1.11 caching-html-compiler@1.1.2 -callback-hook@1.0.10 -check@1.2.5 -ddp@1.2.5 -ddp-client@1.3.4 -ddp-common@1.2.8 +callback-hook@1.1.0 +check@1.3.1 +coffeescript@1.0.17 +dburles:collection-helpers@1.1.0 +dburles:mongo-collection-instances@0.3.5 +ddp@1.4.0 +ddp-client@2.3.2 +ddp-common@1.4.0 ddp-rate-limiter@1.0.7 -ddp-server@1.3.14 +ddp-server@2.1.2 deps@1.0.12 -diff-sequence@1.0.7 -dynamic-import@0.1.0 -ecmascript@0.8.0 -ecmascript-runtime@0.4.1 -ecmascript-runtime-client@0.4.1 -ecmascript-runtime-server@0.4.1 -ejson@1.0.13 -email@1.2.1 -es5-shim@4.6.15 -facebook-oauth@1.3.1 -fastclick@1.0.13 +diff-sequence@1.1.0 +dynamic-import@0.3.0 +ecmascript@0.10.7 +ecmascript-runtime@0.5.0 +ecmascript-runtime-client@0.6.2 +ecmascript-runtime-server@0.5.0 +ejson@1.1.0 +email@1.2.3 +es5-shim@4.7.3 +facebook-oauth@1.4.0 +facts@1.0.9 +flowkey:raven@1.1.0 fortawesome:fontawesome@4.7.0 fourseven:scss@4.5.4 +gadicc:blaze-react-component@1.4.0 +gadicohen:robots-txt@0.0.10 +gadicohen:sitemaps@0.0.26 geojson-utils@1.0.10 github-oauth@1.2.0 -google-oauth@1.2.4 +google-oauth@1.2.5 hot-code-push@1.0.4 html-tools@1.0.11 htmljs@1.0.11 -http@1.2.12 -id-map@1.0.9 -jquery@1.11.10 +http@1.4.0 +id-map@1.1.0 +jquery@1.11.11 +lai:collection-extensions@0.2.1_1 launch-screen@1.1.1 +less@2.7.12 livedata@1.0.18 -localstorage@1.1.0 -logging@1.1.17 -meteor@1.6.1 -meteor-base@1.1.0 -minifier-css@1.2.16 -minifier-js@2.1.0 -minimongo@1.2.0 -mobile-experience@1.0.4 +localstorage@1.2.0 +logging@1.1.20 +markdown@1.0.12 +maximum:package-base@1.1.2 +maximum:server-transform@0.5.0 +mdg:geolocation@1.3.0 +meteor@1.8.6 +meteor-base@1.3.0 +meteorhacks:inject-initial@1.0.4 +meteorhacks:zones@1.6.0 +meteortesting:browser-tests@0.2.0 +meteortesting:mocha@0.5.1 +minifier-css@1.3.1 +minifier-js@2.3.4 +minimongo@1.4.4 +mobile-experience@1.0.5 mobile-status-bar@1.0.14 -modules@0.9.0 -modules-runtime@0.8.0 -mongo@1.1.18 -mongo-id@1.0.6 -npm-bcrypt@0.9.2 -npm-mongo@2.2.24 -oauth@1.1.13 -oauth2@1.1.11 +modules@0.11.6 +modules-runtime@0.9.2 +mongo@1.4.7 +mongo-dev-server@1.1.0 +mongo-id@1.0.7 +mongo-livedata@1.0.12 +mys:fonts@0.0.2 +natestrauser:publish-performant-counts@0.1.2 +nimble:restivus@0.8.12 +npm-bcrypt@0.9.3 +npm-mongo@2.2.34 +nspangler:autoreconnect@0.0.1 +oauth@1.2.3 +oauth2@1.2.0 observe-sequence@1.0.16 -ordered-dict@1.0.9 -promise@0.8.9 +ordered-dict@1.1.0 +ostrio:cookies@2.1.3 +ostrio:mailer@2.1.0 +ostrio:meteor-root@1.0.7 +peerlibrary:assert@0.2.5 +peerlibrary:fiber-utils@0.6.0 +peerlibrary:reactive-mongo@0.1.1 +peerlibrary:server-autorun@0.5.2 +percolate:migrations@1.0.2 +practicalmeteor:chai@2.1.0_1 +practicalmeteor:mocha-core@1.0.1 +promise@0.10.2 raix:eventemitter@0.1.3 -random@1.0.10 -rate-limit@1.0.8 -react-meteor-data@0.2.11 -reactive-dict@1.1.9 +random@1.1.0 +rate-limit@1.0.9 +react-meteor-data@0.2.16 +reactive-dict@1.2.0 reactive-var@1.0.11 -reload@1.1.11 -retry@1.0.9 -routepolicy@1.0.12 +reload@1.2.0 +retry@1.1.0 +reywood:publish-composite@1.6.0 +routepolicy@1.0.13 +saucecode:timezoned-synced-cron@1.2.11 +selaias:cookie-consent@0.4.0 +server-render@0.3.0 service-configuration@1.0.11 session@1.1.7 sha@1.0.9 -shell-server@0.2.3 +shell-server@0.3.1 +shim-common@0.1.0 +simple:json-routes@2.1.0 +socket-stream-client@0.1.0 spacebars@1.0.15 -spacebars-compiler@1.1.2 +spacebars-compiler@1.1.3 srp@1.0.10 -standard-minifier-css@1.3.4 -standard-minifier-js@2.1.0 +standard-minifier-css@1.4.1 +standard-minifier-js@2.3.3 static-html@1.2.2 templating@1.3.2 -templating-compiler@1.3.2 +templating-compiler@1.3.3 templating-runtime@1.3.2 templating-tools@1.1.2 themeteorchef:bert@2.1.3 -tmeasday:check-npm-versions@0.3.1 +tmeasday:check-npm-versions@0.3.2 tracker@1.1.3 -twbs:bootstrap@3.3.6 ui@1.0.13 underscore@1.0.10 -url@1.1.0 -webapp@1.3.16 +url@1.2.0 +vjrj:piwik@0.3.1 +webapp@1.5.0 webapp-hashing@1.0.9 +xolvio:cleaner@0.3.3 diff --git a/.meteorignore b/.meteorignore new file mode 100644 index 0000000..b25101c --- /dev/null +++ b/.meteorignore @@ -0,0 +1,3 @@ +# Don't reload meteor server when we modify or do test +cucumber +output.json diff --git a/API.md b/API.md new file mode 100644 index 0000000..ed2561b --- /dev/null +++ b/API.md @@ -0,0 +1,7 @@ +Basic API: + +```bash +curl -X GET http://localhost:3000/api/v1/status/last-fire-detected +curl -X GET http://localhost:3000/api/v1/status/last-fire-check +curl -X GET http://localhost:3000/api/v1/status/active-fires-count +``` diff --git a/COPYRIGHT.md b/COPYRIGHT.md new file mode 100644 index 0000000..06197fa --- /dev/null +++ b/COPYRIGHT.md @@ -0,0 +1,36 @@ +**Data** + +We acknowledge the use of data and imagery from LANCE FIRMS operated by the NASA/GSFC/Earth Science Data and Information System (ESDIS) with funding provided by NASA/HQ. + +**Images** + +* Home slide 1: Sotres, Picos de Europa, Asturias, photo by Mick Stephenson, license CC-BY-SA 3.0, [source](https://es.wikipedia.org/wiki/Sotres#/media/File:SotresPanorama.jpg). +* Home slide 2: Silverhorne, United States, photo by Nathan Anderson [source](https://unsplash.com/photos/ZLOZC1uUdns). +* Home slide 3: Bitterroot National Forest, Montana, United States, photo by John McColgan, Public Domain, [source](https://commons.wikimedia.org/wiki/File:Deerfire_high_res.jpg). +* Home slide 4: Cox Valley Fire, Olympic NP, United States, August 2016, [source](https://www.nps.gov/olym/learn/management/current-fire-status.htm). +* Wildfire home photo: [California Wildfires, October 23th 2007](https://commons.wikimedia.org/wiki/File:California_Wildfires_October_23_2007.jpg), [fuente](http://www.nasa.gov/vision/earth/lookingatearth/socal_wildfires_oct07.html). +* Default avatar: A colored Emoji from Noto project, released under Apache license, [source](https://commons.wikimedia.org/wiki/File:Emoji_u1f469_1f3fd_200d_1f692.svg). + +**The rest** + +Copyright + +(c) 2017-2018 Licensed to the Comunes Association (CA) under one or +more contributor license agreements. The CA licenses this software to +you under the GNU Affero General Public License version 3, (the "License"); +you may not use this software except in compliance with the License. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +See our [LICENSE](https://github.com/comunes/todos-contra-el-fuego-web/blob/tcef-master/LICENSE.md), for a complete text. diff --git a/History.md b/History.md new file mode 100644 index 0000000..f64a6d7 --- /dev/null +++ b/History.md @@ -0,0 +1,69 @@ +## v.NEXT + +- Improve [#96](https://github.com/cleverbeagle/pup/issues/96). Fix miscellaneous ESLint errors (h/t [@cdolek](https://github.com/cdolek) for sniffing these out). +- Improve [#95](https://github.com/cleverbeagle/pup/issues/95). Migrate from `createContainer` method to `withTracker` for data containers (h/t [@cdolek](https://github.com/cdolek) for sniffing these out). +- Improve [#94](https://github.com/cleverbeagle/pup/issues/94). Bump Meteor to v1.6 and bump Atmosphere and NPM deps. +- Improve [#53](https://github.com/cleverbeagle/pup/issues/53). Move method imports to be on both the client and the server to leverage Meteor's latency compensation by default (h/t [@zodern](https://github.com/zodern) for refactoring this). +- Improve [#78](https://github.com/cleverbeagle/pup/issues/78). Deprecate `@cleverbeagle/dates` package in favor of a local file of date helpers (h/t [@zodern](https://github.com/zodern) for refactoring this). +- Improve [#79](https://github.com/cleverbeagle/pup/issues/79). Add `babel-plugin-lodash` to reduce footprint of Lodash to only methods that are used in the project (h/t [@ninjaPixel](https://github.com/ninjaPixel) for finding/implementing this). +- Improve [#80](https://github.com/cleverbeagle/pup/issues/80). Add exception to disable `max-len` ESLint rule (h/t [@ninjaPixel](https://github.com/ninjaPixel) for implementing this). +- Improve [#60](https://github.com/cleverbeagle/pup/issues/60). Move to `babel-preset-env` from `babel-preset-es2015` (h/t [@pilarArr](https://github.com/pilarArr) for implementing this). +- Fix [#59](https://github.com/cleverbeagle/pup/issues/59). Fix ESLint throwing a tantrum about line endings on Windows (h/t [@pilarArr](https://github.com/pilarArr) for implementing this). +- Improve [#47](https://github.com/cleverbeagle/pup/issues/47). Move `getUserName()` function in `/imports/ui/layouts/App/App.js` into its own file (h/t [@pilarArr](https://github.com/pilarArr) for implementing this). +- Improve [#46](https://github.com/cleverbeagle/pup/issues/46). Move the resend verification email bar into its own component (h/t [@pilarArr](https://github.com/pilarArr) for implementing this). + +## v1.2.2, September 30th, 2017 + +- Fix [#66](https://github.com/cleverbeagle/pup/issues/66). Remove unnecessary `callback` argument causing trouble in `/imports/modules/server/send-email.js`. + +- Fix [#74](https://github.com/cleverbeagle/pup/issues/74). Fix typo in `/imports/ui/components/Public/Public.js`. + +## v1.2.1, September 24th, 2017 + +- Fix [#68](https://github.com/cleverbeagle/pup/issues/68). Update Meteor to v1.5.2 and bump Atmosphere dependencies to latest versions. + +## v1.2.0, September 7th, 2017 + +- Fix [#31](https://github.com/cleverbeagle/pup/issues/31). Fix name not rendering for users logged in via OAuth with Google. +- Fix [#32](https://github.com/cleverbeagle/pup/issues/32). Fix route props not being passed to rendered component in `` and ``. h/t @pilarArr for the fix. +- Improve [#37](https://github.com/cleverbeagle/pup/issues/37). Bump Atmosphere and NPM dependencies to latest versions. h/t @pilarArr for the refactor. +- Improve [#40](https://github.com/cleverbeagle/pup/issues/40). Move `Meteor.logout()` call to be triggered by visiting the `/logout` route. +- Add [#44](https://github.com/cleverbeagle/pup/issues/44). Add support for transactional emails with HTML and text templates via Handlebars. +- Improve [#45](https://github.com/cleverbeagle/pup/issues/45). Clean up the UI/UX of the "Edit Profile" view for users who are logged in via OAuth. + +## v1.1.1, August 6th, 2017 + +- Fix [#27](https://github.com/cleverbeagle/pup/issues/27). Fix incorrect method name in rate limiter list in `/imports/api/Users/server/methods.js`. +- Fix [#28](https://github.com/cleverbeagle/pup/issues/28). Fix verify email message displaying for users who log in via OAuth. +- Fix [#29](https://github.com/cleverbeagle/pup/issues/29). Fix `@cleverbeagle/seeder` and `@cleverbeagle/dates` dependencies breaking initial startup. Also add `core-js` dependency as it was breaking some apps on startup. + +## v1.1.0, August 1st, 2017 + +- Improve [#16](https://github.com/cleverbeagle/pup/issues/16). Adds missing import for `/imports/startup/server/accounts/on-create-user.js` in `/imports/startup/server/accounts/index.js`. + [Add documentation on usage of `Accounts.onCreateUser()`](/pup/v1/accounts/on-create-user-hook). + +- Improve [#17](https://github.com/cleverbeagle/pup/issues/17). Move setting of user password in editing profile to client to ensure the user's current password is actually checked (implements Meteor's `Accounts.changePassword()` method). + +- Add [#20](https://github.com/cleverbeagle/pup/issues/20). Add support for `lodash` package via NPM and swap usage of `capitalize()` method from `@cleverbeagle/strings` package with lodash's `_.capitalize()` method. Remove `@cleverbeagle/strings` from NPM dependencies. + +- Add [#21](https://github.com/cleverbeagle/pup/issues/21). Add support for (non-blocking) email verification on user signup. [Add documentation on email verification process](/pup/v1/accounts/email-verification). + +- Fix [#23](https://github.com/cleverbeagle/pup/issues/23). Fixes a React PropTypes warning showing up when accessing a non-existing document on `/documents/:_id/edit`. Also improve 404 handling on `/documents/:_id/edit` and `/documents/:_id` when no document is passed. + +- Fix [#24](https://github.com/cleverbeagle/pup/issues/24). Remove unnecessary `_.pluck()` call obscuring the method names passed to the `rateLimit()` options object. + +## v1.0.3, July 9th, 2017 + +- Fix [#14](https://github.com/cleverbeagle/pup/issues/14). Remove unnecessary `loggingIn` check that was forcing the page to re-render. + +## v1.0.2, June 27th, 2017 + +- Fix [#12](https://github.com/cleverbeagle/pup/issues/12). Fixes prop type warning being thrown when transitioning to the `ViewDocument` page component from the `NewDocument` page component. + +## v1.0.1, June 14th, 2017 + +- Fix [#1](https://github.com/cleverbeagle/pup/issues/1). h/t to [@sczk](https://github.com/sczk) for pointing out the fix. + +## v1.0.0, June 13th, 2017 + +- Initial release of Pup. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..cba6f6a --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,660 @@ +### GNU AFFERO GENERAL PUBLIC LICENSE + +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +### Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains +free software for all its users. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing +under this license. + +The precise terms and conditions for copying, distribution and +modification follow. + +### TERMS AND CONDITIONS + +#### 0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public +License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +#### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +#### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +#### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +#### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +#### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +#### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +#### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +#### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +#### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +#### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +#### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +#### 13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your +version supports such interaction) an opportunity to receive the +Corresponding Source of your version by providing access to the +Corresponding Source from a network server at no charge, through some +standard or customary means of facilitating copying of software. This +Corresponding Source shall include the Corresponding Source for any +work covered by version 3 of the GNU General Public License that is +incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + +#### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU Affero General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever +published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +#### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +#### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +#### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +### How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper +mail. + +If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for +the specific requirements. + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU AGPL, see . diff --git a/README.md b/README.md index 5d2adc6..4417536 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,60 @@ -### Pup -A boilerplate for products. +# Tod@s contra el Fuego (All Against Fire) -[Read the Documentation](http://cleverbeagle.com/pup) +[![Build Status](http://ci.comunes.org/buildStatus/icon?job=todos-contra-el-fuego-web)](http://ci.comunes.org/job/todos-contra-el-fuego-web/) ---- +This is web service that notifies about fires detected in an area of your interest. It helps the early detection of fires and facilitates local mobilization, while the professional extinction services arrive. -Need help and want to stay accountable building your product? [Check out Clever Beagle](http://cleverbeagle.com). +## Install + +Prerrequisites: a running meteor (we share the `fuegos` database with the telegram bot). + +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 + +Configure [mirror and cron](https://www.npmjs.com/package/maxmind-geolite2-mirror) of the [geoip database](http://dev.maxmind.com/geoip/geoip2/geolite2/). + +## Telegram bot + +See our [bot](https://github.com/comunes/todos-contra-el-fuego/tree/master/telegram-bot). + +More platforms and services in the future... + +### Tests + +We do tests via: +``` +TEST_PORT=3000 TEST_WATCH=1 TEST_CLIENT=0 MONGO_URL=mongodb://localhost:27017/fuegostest meteor --settings settings-development.json test --driver-package meteortesting:mocha --port 3010 + +# and + +node_modules/.bin/chimp --watch --ddp=http://localhost:3000 --path=cucumber + +# and + +node_modules/.bin/chimp --ddp=http://localhost:3000 --path=cucumber + +``` + +### FAQ & Troubleshooting + +**Q** - I get something like `(...) /node_modules/fibers/future.js:280 (...) Error: Could not locate the bindings file.` What can I do? +**A** - Try `meteor npm rebuild` + +## Data source acknowledgements + +*We acknowledge the use of data and imagery from LANCE FIRMS operated by the NASA/GSFC/Earth Science Data and Information System (ESDIS) with funding provided by NASA/HQ*. + +## License + +GNU APLv3. See our [LICENSE](https://github.com/comunes/todos-contra-el-fuego-web/blob/tcef-master/LICENSE.md), for a complete text. + +## Thanks & other acknowlegments + +Thanks indeed to: +- Lupe Bao Reixa for Galician translation diff --git a/bin/au-dee-npi.awk b/bin/au-dee-npi.awk new file mode 100755 index 0000000..dec11cd --- /dev/null +++ b/bin/au-dee-npi.awk @@ -0,0 +1,16 @@ +# cat file.csv| ./au-dee-npi.awk | mongoimport -d "fuegos" -c "industries" + +gawk -F',' 'NR>1 { \ + gsub(/"/,"",$5); + gsub(/"/,"",$6); + gsub(/\t/,"",$13); + gsub(/\t/,"",$14); + gsub(/\x1a/,"",$13); + gsub(/\x1a/,"",$14); + lon = $14+0; + lat = $13+0; + name= $5", "$6 + gsub(/^, /,"",name); + if (lon != 0 && lat != 0 && lon > -180 && lon < 180 && lat >= -90 && lat <= 90) + printf("{name:\"%s\",geo:{type:\"Point\",coordinates:[%s,%s]},registry:\"4\"}\n" \ + ,name,lon,lat)}' diff --git a/bin/ca-godp-npri.awk b/bin/ca-godp-npri.awk new file mode 100755 index 0000000..e618ec6 --- /dev/null +++ b/bin/ca-godp-npri.awk @@ -0,0 +1,19 @@ +# cat file.csv| ./ca-godp-npri.awk | uniq | mongoimport -d "fuegos" -c "industries" + +gawk -F',' 'NR>1 { \ + gsub(/"/,"",$3); + gsub(/"/,"",$4); + gsub(/\t/,"",$3); + gsub(/\t/,"",$4); + gsub(/\x1a/,"",$3); + gsub(/\x1a/,"",$4); + lon = $16+0; + lat = $15+0; + if ($3 != $4) + name= $3", "$4 + else + name=$3 + gsub(/^, /,"",name); + # if (lon != 0 && lat != 0 && lon > -180 && lon < 180 && lat >= -90 && lat <= 90) + printf("{name:\"%s\",geo:{type:\"Point\",coordinates:[%s,%s]},registry:\"3\"}\n" \ + ,name,lon,lat)}' diff --git a/bin/eu-eea-e-prtr.awk b/bin/eu-eea-e-prtr.awk new file mode 100755 index 0000000..afaa839 --- /dev/null +++ b/bin/eu-eea-e-prtr.awk @@ -0,0 +1,14 @@ +# cat dbo.PUBLISH_FACILITYREPORT.csv| ./eu-eea-e-prtr.awk | mongoimport -d "fuegos" -c "industries" + +gawk -F',' 'NR>1 { \ + gsub(/"/,"",$6); + gsub(/"/,"",$5); + gsub(/\t/,"",$6); + gsub(/\t/,"",$5); + gsub(/\x1a/,"",$5); + gsub(/\x1a/,"",$6); + lon = $14+0; + lat = $13+0; + if (lon != 0 && lat != 0 && lon > -180 && lon < 180 && lat >= -90 && lat <= 90) + printf("{name:\"%s, %s\",geo:{type:\"Point\",coordinates:[%s,%s]},registry:\"1\"}\n" \ + ,$6,$5,lon,lat)}' diff --git a/bin/us-epa-frs.awk b/bin/us-epa-frs.awk new file mode 100755 index 0000000..56aec61 --- /dev/null +++ b/bin/us-epa-frs.awk @@ -0,0 +1,10 @@ +# cat NATIONAL_SINGLE.CSV| ./us-epa-frs.awk | mongoimport -d "fuegos" -c "industries" + +gawk -F',' 'NR>1{ \ + gsub(/"/,"",$33); + gsub(/"/,"",$32); + gsub(/"/,"",$3); + gsub(/\t/,"",$3); + lon = $33+0; + lat = $32+0; + if (lon != 0 && lat != 0 && lon > -180 && lon < 180 && lat >= -90 && lat <= 90) { printf("{name:\"%s\",geo:{type:\"Point\",coordinates:[%s,%s]},registry:\"2\"}\n",name,lon,lat)}}' diff --git a/client/main.html b/client/main.html index db2b85f..a2728e0 100644 --- a/client/main.html +++ b/client/main.html @@ -1,11 +1,17 @@ - Pup - + + All Against the Fire | Tod@s contra el Fuego + - - - + + + + + + + + diff --git a/client/main.js b/client/main.js index 1412f30..f139266 100644 --- a/client/main.js +++ b/client/main.js @@ -1 +1,4 @@ import '../imports/startup/client'; + +// https://github.com/GoogleChrome/rendertron#rendering-budget-timeout +window.renderComplete = false; diff --git a/cucumber/chimp-config.js b/cucumber/chimp-config.js new file mode 100644 index 0000000..7ec19dc --- /dev/null +++ b/cucumber/chimp-config.js @@ -0,0 +1,29 @@ +module.exports = { + // - - - - CHIMP - - - - + /* watch: false, + * watchTags: '@watch', + * offline: false, + */ + // - - - - CUCUMBER - - - - + /* path: './features', + * jsonOutput: 'output.json', */ + + // '- - - - DEBUGGING - - - - + log: 'info', + debug: false, + seleniumDebug: false, + webdriverLogLevel: false, + // debugBrkCucumber: 5858, + // - - - - WEBDRIVER-IO - - - - + webdriverio: { + waitforTimeout: 10000, + waitforInterval: 250, // KEEP SMALL (!!!) this is the INTERVAL in which waitFor* is looped fo + desiredCapabilities: { + chromeOptions: { + // args: ["headless", "disable-gpu"] + args: ['--disable-gpu', '--no-sandbox', '--headless'] + }, + isHeadless: true + } + } +}; diff --git a/cucumber/features/feedback.feature b/cucumber/features/feedback.feature new file mode 100644 index 0000000..3bbb113 --- /dev/null +++ b/cucumber/features/feedback.feature @@ -0,0 +1,22 @@ +Feature: Allow users to give feedback + + As a user (authenticated or not) + I want to give feedback about this site + + Scenario: A user can login and give feedback + Given I am on the zones page + And I have an account and I logged in + # Because is not verified + Then I can send feedback with email + When I sign out + Given I'm not logged + Then I can send feedback with email + + Scenario: A anon user can give feedback + Given I am on the fires page + Given I'm not logged + Then I can send feedback with email + + Scenario: A user cannot give feedback in home + Given I am on the home page + Then I cannot send feedback diff --git a/cucumber/features/general.feature b/cucumber/features/general.feature new file mode 100644 index 0000000..b1fd8f9 --- /dev/null +++ b/cucumber/features/general.feature @@ -0,0 +1,12 @@ +Feature: This app should generate a correct sitemap, etc + + Scenario: I verify that a sitemap is generated correctly + Given the page sitemap.xml + Then I check that exist this list of pages in the sitemap + | license | License | + | terms | Terms of Service | + | credits | Credits | + | privacy | Privacy Policy | + | fires | Active Fires | + | login | Login | + | signup | Signup | diff --git a/cucumber/features/login.feature b/cucumber/features/login.feature new file mode 100644 index 0000000..38fe003 --- /dev/null +++ b/cucumber/features/login.feature @@ -0,0 +1,34 @@ +Feature: Allow users to login and logout + + As a user + I want to login and logout + So that I can prove my identity and see personalized data + + Background: + Given I am on the home page + + Scenario: A user can login + Given I have an account and I logged in + When I sign out + When I enter my email and password + Then I should be logged in + And I can edit my profile + + Scenario: A user cannot login with bad information + Given I have an account and I logged in + When I sign out + When I enter incorrect authentication information + Then I should see a user not found error + + Scenario: A user can register and login + Given I register with some name, password and email + Then I should be registered + And I should be logged in + When I sign out + When I enter my email and password + Then I should be logged in + And I can edit my profile + + Scenario: A user cannot register without accepting service conditions + Given I register with some name, password and email but without accept conditions + Then I shouldn't be registered diff --git a/cucumber/features/pages.feature b/cucumber/features/pages.feature new file mode 100644 index 0000000..0807c2c --- /dev/null +++ b/cucumber/features/pages.feature @@ -0,0 +1,51 @@ +Feature: Test all secundary pages + + Background: + Given I am on the home page + + Scenario: Check that all secondary pages work well + Given a list of page ids and contents + | license | License | + | tos | Terms of Service | + | credits | Credits | + | privacy | Privacy Policy | + | activeFires | Active Fires | + | about | About | + Then I check that all pages works properly + + Scenario: Check that all secondary pages work well when not logged + Given I logout if logged + And a list of page urls and contents + | login | Login | true | + | signup | Sign Up | true | + | fires | Fires | true | + | zones | Monitored | true | + | recover-password | Recover Password | true | + | verify-email/something | Verify | true | + | fire/inexistent | This page doesn't exist | false | + | fire/Fe26.2**1a0361ed0384f741403682e26b4bbc3850bee24e775da13c9782b22365ea895f*r_3gmVad5vzkeyqPpo6UcA*1s5fFz3iDGKTYP2RCvXMshof00QCHf4ErDl9K2dxoX0u-J-t6scyOWG8pGp3ehg_FfEtyR_kYcEKU3rE0jaSlZbD09TIvhiIJeS3C6Uc8YD-rit0XBrgsVKfYSxKzTRoOYiYFJ8JYd298hMtfiASePjS05Z58hhicyCcJYYRlarqDScG3LiVY3lL5y2nfcdIMNuSjCiKOJWuMkxwd9nR1UHMudLl0hEoy56mPdnHpDYtP9IYUlIOk1LlWBxcmHKifbXeqHu94p8j13Kk20dh2R49Hw3KsSoE9UbWmGQA9wAZXT82301i3rGF5GPAKjlTlRYcWisQurnPwHSVmx3DhUdiYwKGxt4KeaM5QVI4BE9octvE41OOprB_-Il105diQEh2Y9vdvX51ZVWIRfCboICPM6rJb0Oin7U7F1iM-oD_5s3DGnelfM5LGBcKwiB5paMo5M5vdBMaO-zR216cW9yGVXw9IZqHx8xDQWnoHAZjt8NLHeiGF2QOmIGtEUH7qnwhGpkcvszajmAZzR8saZgoH1qfBfvpVA41YfV14gU**4d030f05e23ad75409cebc609107467fc60be5077d52cf041087cd024fc4dc45*GY97aGFc1MyAsoO3Qxqtgwk9j-MbAPdEGBmEHq6r8VU | Additional information | false | + Then I check that all page urls works properly + + # And they are spiderable + + @watch + Scenario: Check that all secondary pages work well when logged + Given I have an account and I logged in + And a list of page urls and contents + | status | Status | false | + | fires | Fires | true | + | zones | Monitored | true | + | verify-email/something | Verify | true | + | fire/inexistent | This page doesn't exist | false | + | fire/Fe26.2**1a0361ed0384f741403682e26b4bbc3850bee24e775da13c9782b22365ea895f*r_3gmVad5vzkeyqPpo6UcA*1s5fFz3iDGKTYP2RCvXMshof00QCHf4ErDl9K2dxoX0u-J-t6scyOWG8pGp3ehg_FfEtyR_kYcEKU3rE0jaSlZbD09TIvhiIJeS3C6Uc8YD-rit0XBrgsVKfYSxKzTRoOYiYFJ8JYd298hMtfiASePjS05Z58hhicyCcJYYRlarqDScG3LiVY3lL5y2nfcdIMNuSjCiKOJWuMkxwd9nR1UHMudLl0hEoy56mPdnHpDYtP9IYUlIOk1LlWBxcmHKifbXeqHu94p8j13Kk20dh2R49Hw3KsSoE9UbWmGQA9wAZXT82301i3rGF5GPAKjlTlRYcWisQurnPwHSVmx3DhUdiYwKGxt4KeaM5QVI4BE9octvE41OOprB_-Il105diQEh2Y9vdvX51ZVWIRfCboICPM6rJb0Oin7U7F1iM-oD_5s3DGnelfM5LGBcKwiB5paMo5M5vdBMaO-zR216cW9yGVXw9IZqHx8xDQWnoHAZjt8NLHeiGF2QOmIGtEUH7qnwhGpkcvszajmAZzR8saZgoH1qfBfvpVA41YfV14gU**4d030f05e23ad75409cebc609107467fc60be5077d52cf041087cd024fc4dc45*GY97aGFc1MyAsoO3Qxqtgwk9j-MbAPdEGBmEHq6r8VU | Additional information | false | + Then I check that all page urls works properly + + Scenario: Check that other non visible pages work well + Given I logout if logged + And a list of non visible pages ids and contents + | error | Upppps | false | + # FIXME: find a way to monitor json pages + # | api/v1/status/last-fire-detected | updateAt | + # | api/v1/status/last-fire-check | description | + # | api/v1/status/active-fires-count | total | + Then I check that all non visible pages works properly diff --git a/cucumber/features/steps_definitions/feedback.js b/cucumber/features/steps_definitions/feedback.js new file mode 100644 index 0000000..ffd78be --- /dev/null +++ b/cucumber/features/steps_definitions/feedback.js @@ -0,0 +1,50 @@ +/* global module expect require process client */ + +const { randomText, randomEmail } = require('./helper.js'); + +module.exports = function doSteps() { + this.Given(/^I am on the zones page$/, () => { + client.url(`${process.env.ROOT_URL}/zones`); + if (client.isVisible('#logout')) { + client.click('#logout'); + } + }); + + this.Then(/^I can send feedback without email$/, () => { + client.waitForVisible('#feedback-tab', 10000); + client.click('#feedback-tab'); + client.waitForVisible('#feedback-form', 10000); + client.setValue('#feedbackTextarea', randomText(500)); + client.click('#sendFeedbackBtn'); + client.waitForVisible('.bert-alert', 10000, true); + client.waitUntil(() => client.isVisible('.bert-alert') === false, 10000); + }); + + this.Then(/^I can send feedback with email$/, () => { + client.waitForVisible('#feedback-tab', 10000); + client.click('#feedback-tab'); + client.waitForVisible('#feedback-form', 10000); + client.waitForEnabled('input[name="email"]'); + client.setValue('input[name="email"]', randomEmail()); + client.setValue('#feedbackTextarea', randomText(500)); + client.click('#sendFeedbackBtn'); + client.waitForVisible('.bert-alert', 10000, true); + client.waitUntil(() => client.isVisible('.bert-alert') === false, 10000); + }); + + this.Given(/^I'm not logged$/, () => { + client.waitForVisible('#react-root', 5000); + if (client.isVisible('#logout')) { + client.click('#logout'); + } + }); + + this.Given(/^I am on the fires page$/, () => { + client.url(`${process.env.ROOT_URL}/fires`); + }); + + this.Then(/^I cannot send feedback$/, () => { + client.waitForVisible('#react-root', 5000); + client.waitUntil(() => client.isVisible('#feedback-tab') === false, 10000); + }); +}; diff --git a/cucumber/features/steps_definitions/general.js b/cucumber/features/steps_definitions/general.js new file mode 100644 index 0000000..33bb272 --- /dev/null +++ b/cucumber/features/steps_definitions/general.js @@ -0,0 +1,20 @@ +/* global module expect require process client */ + +module.exports = function doSteps() { + let pages; + + this.Then(/^I check that exist this list of pages in the sitemap$/, (table, callback) => { + // Write code here that turns the phrase above into concrete actions + pages = table.raw(); + for (let i = 0; i < pages.length; i += 1) { + // TODO download sitemap and parse + // client.waitForText('.text', pages[i][0]); + } + callback(); + }); + + this.Given(/^the page sitemap\.xml$/, (callback) => { + client.url(`${process.env.ROOT_URL}/sitemap.xml`); + callback(); + }); +}; diff --git a/cucumber/features/steps_definitions/helper.js b/cucumber/features/steps_definitions/helper.js new file mode 100644 index 0000000..7274a40 --- /dev/null +++ b/cucumber/features/steps_definitions/helper.js @@ -0,0 +1,32 @@ +// https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript +function makeid(size) { + let text = ''; + const possible = 'abcdefghijklmnopqrstuvwxyz0123456789'; + for (let i = 0; i < size; i += 1) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; +} + +export const randomText = n => makeid(n); + +export const randomUsername = () => makeid(7); + +export const randomPassword = () => randomUsername(); + +export const randomEmail = () => `${randomUsername()}@example.com`; + +export const goHome = (client) => { + client.url(process.env.ROOT_URL); + client.waitForVisible('#react-root', 10000); + expect(client.isVisible('#react-root')).toBe(true); + client.waitUntil(() => client.isVisible('.pg-loading-center-middle') === false, 5000); + client.waitUntil(() => client.isVisible('.pg-loading-center-middle') === false, 5000); + // Close alert + if (client.isVisible('.bert-content')) { + client.click('.bert-content'); + } + if (client.isVisible('#acceptCookies')) { + client.click('#acceptCookies'); + } +}; diff --git a/cucumber/features/steps_definitions/hooks.js b/cucumber/features/steps_definitions/hooks.js new file mode 100644 index 0000000..64b405a --- /dev/null +++ b/cucumber/features/steps_definitions/hooks.js @@ -0,0 +1,75 @@ +/* global client */ + +(function () { + module.exports = function () { + const printLog = (type) => { + client.log(type).value.forEach((logItem) => { + const { source, message } = logItem; + if (type === 'browser' && source === 'console-api') { + // Clean messages of type: + // http://localhost:3000/app/app.js?hash=34da4258bd2caa4e14c7c0c20ba6396f309e7236 13325:18 "GMaps script just loaded" + // to get the last part + const cleanMessage = message.replace(/[^ ]{1,} [^ ]{1,} "(.*)"$/g, '$1'); + console.log(`${logItem.level}: ${cleanMessage}`); + } else { + // Right now we don't need logs like: + // %cDownload the React DevTools for a better development experience: https://fb.me/react-devtools + // console.log(`${logItem.level}: ${message}`); + } + }); + }; + + this.StepResult((stepResult) => { + if (stepResult.getStatus() === 'failed') { + // http://webdriver.io/api/protocol/log.html + console.log(`Step result: ${stepResult.getStatus()}`); + printLog('browser'); + } + }); + + this.Before(() => { + // global.expect = require('@xolvio/jasmine-expect').expect; + + // https://github.com/webdriverio/webdriverio/issues/1145 + if (!this.initMyCmds) { + client.addCommand('waitForClickable', function elementClickable(selector, timeout) { + this.waitForVisible(selector, timeout); + this.waitForEnabled(selector, timeout); + }); + + client.addCommand('waitUntilText', function waitUntilText(selector, text, ms) { + ms = ms || 5000; + this.waitForVisible(selector); + const self = this; + this.waitUntil(() => self.getText(selector).includes(text), ms, `expected text in ${selector} be different after ${ms / 1000}s. Obtained: '${self.getText(selector)}' expected: '${text}'`); + }); + + this.initMyCmds = true; + } + + client.windowHandleSize({ width: 1500, height: 1000 }); + + // server.call('fixtures/reset'); + // server.call('emailStub/reset'); + // server.call('emailStub/stub'); + // server.call('fixtures/stubCloudFrontClient'); + + // go to the page first so we have access to the Meteor object + // console.log('Before all tests...'); + // client.url(process.env.ROOT_URL); + /* client.executeAsync(function (done) { + * var customer = { + * id: 'randomId', + * email: 'me@example.com', + * subscriptions: { + * data: [{ + * current_period_start: 1436716844, + * current_period_end: 1436716844 + * }] + * } + * }; */ + // this call will stub stripe both on the client and server + // Meteor.call('stripeStub/stub', customer, done); + }); + }; +}()); diff --git a/cucumber/features/steps_definitions/login.js b/cucumber/features/steps_definitions/login.js new file mode 100644 index 0000000..b255b96 --- /dev/null +++ b/cucumber/features/steps_definitions/login.js @@ -0,0 +1,150 @@ +/* global module expect require process client */ + +const { + goHome, randomUsername, randomPassword, randomEmail +} = require('./helper.js'); + +let firstName; +let lastName; +let pass; +let email; + +const setUserValues = (isEdit) => { + client.waitForVisible('input[name="firstName"]', 10000); + firstName = randomUsername(); + lastName = randomUsername(); + email = randomEmail(); + client.setValue('input[name="firstName"]', firstName); + client.setValue('input[name="lastName"]', lastName); + client.setValue('input[name="emailAddress"]', email); + if (isEdit) { + client.setValue('input[name="currentPassword"]', pass); + pass = randomPassword(); + client.setValue('input[name="newPassword"]', pass); + } else { + pass = randomPassword(); + client.setValue('input[name="password"]', pass); + } +}; + +module.exports = function doSteps(notos) { + this.Given(/^I am on the home page$/, () => { + goHome(client); + }); + + function waitNoBert() { + client.pause(2000); + if (client.isVisible('.bert-container')) { + // console.log('Removing bert alert'); + client.click('.bert-container'); + client.waitForVisible('.bert-container', 10000, true); + } else { + // console.log('No bert alert'); + } + } + + function logoutIfLogged() { + if (client.isVisible('#logout')) { + client.click('#logout'); + } + client.waitForVisible('#signup', 10000); + } + + function register() { + logoutIfLogged(); + client.waitForVisible('#signup', 10000); + client.click('#signup'); + setUserValues(); + if (!notos) { + client.click('input[name="tos"]'); + } + client.click('#signUpSubmit'); + client.waitForVisible('#logout', 10000); + } + + this.Given(/^I logout if logged$/, () => { + waitNoBert(); + logoutIfLogged(); + }); + + this.Given(/^I have an account and I logged in$/, () => { + register(); + }); + + function checkName() { + client.waitForVisible('#profile', 5000); + client.waitUntilText('#profile', firstName); + client.waitUntilText('#profile', lastName); + } + + this.Then(/^I should be logged in$/, () => { + client.waitUntil(() => client.isVisible('#logout') === true, 10000); + client.waitUntil(() => client.isVisible('#profile') === true, 10000); + }); + + /* this.Given(/^I am signed out$/, () => { + * client.waitUntil(() => client.isVisible('#logout') === true, 10000); + * }); + */ + + + this.When(/^I sign out$/, () => { + waitNoBert(); + client.waitForClickable('#logout', 10000); + // client.waitForVisible('#logout', 10000); + client.click('#logout'); + client.waitForVisible('#login', 10000); + }); + + function login(badpass) { + waitNoBert(); + client.waitForVisible('#login', 10000); + client.click('#login'); + client.waitForVisible('#loginSubmit', 5000); + client.setValue('input[name="emailAddress"]', email); + client.setValue('input[name="password"]', badpass ? randomPassword() : pass); + client.click('#loginSubmit'); + waitNoBert(); + } + + this.When(/^I enter my email and password$/, () => { + login(); + }); + + this.Then(/^I can edit my profile$/, () => { + waitNoBert(); + client.waitForClickable('#profile', 10000); + client.click('#profile'); + client.pause(2000); + setUserValues(true); + client.click('#profileSubmit'); + waitNoBert(); + checkName(); + }); + + this.When(/^I enter incorrect authentication information$/, () => { + login(true); + }); + + this.Then(/^I should see a user not found error$/, () => { + client.waitForVisible('.alert-danger', 10000, true); + }); + + this.Given(/^I register with some name, password and email$/, () => { + register(); + }); + + this.Then(/^I should be registered$/, () => { + client.waitForVisible('.bert-alert', 10000, true); + waitNoBert(); + }); + + this.Given(/^I register with some name, password and email but without accept conditions$/, () => { + register(true); + }); + + this.Then(/^I shouldn't be registered$/, () => { + client.waitForVisible('.bert-alert', 10000, true); + client.waitForVisible('#login', 10000, true); + }); +}; diff --git a/cucumber/features/steps_definitions/pages.js b/cucumber/features/steps_definitions/pages.js new file mode 100644 index 0000000..29f6aab --- /dev/null +++ b/cucumber/features/steps_definitions/pages.js @@ -0,0 +1,81 @@ +/* global module expect require process client */ + +const { goHome } = require('./helper.js'); + +// Does no works with arrow func +module.exports = function () { + let pages; + + this.Given(/^a list of page ids and contents$/, (table, callback) => { + pages = table.raw(); + callback(); + }); + + function processPage(i) { + const id = `#${pages[i][0]}`; + const content = pages[i][1]; + client.waitForVisible(id, 10000); + client.click(id); + client.waitUntilText('#react-root', content); + // https://jasmine.github.io/2.3/introduction.html#section-Expectations + expect(client.getTitle()).toContain(pages[i][1]); + } + + function processPageUrl(i) { + const url = `${pages[i][0]}`; + const content = pages[i][1]; + client.url(`${process.env.ROOT_URL}/${url}`); + client.waitForVisible('#react-root', 10000); + client.waitUntilText('#react-root', content); + const checkTitle = pages[i][2] === 'true'; + // https://jasmine.github.io/2.3/introduction.html#section-Expectations + if (checkTitle) { + expect(client.getTitle()).toContain(pages[i][1]); + } + } + + this.Given(/^a list of non visible pages ids and contents$/, (table, callback) => { + pages = table.raw(); + callback(); + }); + + this.Then(/^I check that all non visible pages works properly$/, (callback) => { + for (let i = 0; i < pages.length; i += 1) { + processPageUrl(i); + } + callback(); + }); + + this.Then(/^I check that all pages works properly$/, (callback) => { + goHome(client); + if (client.isVisible('#logout')) { + client.click('#logout'); + } + for (let i = 0; i < pages.length; i += 1) { + processPage(i); + } + callback(); + }); + + this.Given(/^a list of page urls and contents$/, (table, callback) => { + pages = table.raw(); + callback(); + }); + + this.Then(/^I check that all page urls works properly$/, (callback) => { + goHome(client); + for (let i = 0; i < pages.length; i += 1) { + processPageUrl(i); + } + callback(); + }); + + this.Then(/^they are spiderable$/, (callback) => { + // Write code here that turns the phrase above into concrete actions + for (let i = 0; i < pages.length; i += 1) { + client.url(`${process.env.ROOT_URL}/${pages[i][0]}?_escaped_fragment_=`); + client.waitUntilText('#react-root', pages[i][1]); + } + callback(); + }); +}; diff --git a/designs/California_Wildfires_October_23_2007.jpg b/designs/California_Wildfires_October_23_2007.jpg new file mode 100644 index 0000000..0ecf0b7 Binary files /dev/null and b/designs/California_Wildfires_October_23_2007.jpg differ diff --git a/designs/icons-tcef.svg b/designs/icons-tcef.svg new file mode 100644 index 0000000..0835ab8 --- /dev/null +++ b/designs/icons-tcef.svg @@ -0,0 +1,659 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/designs/mobile.xcf b/designs/mobile.xcf new file mode 100644 index 0000000..e1e2ada Binary files /dev/null and b/designs/mobile.xcf differ diff --git a/designs/telegram-capture-en.png b/designs/telegram-capture-en.png new file mode 100644 index 0000000..b12364b Binary files /dev/null and b/designs/telegram-capture-en.png differ diff --git a/designs/web-tcef.png b/designs/web-tcef.png new file mode 100644 index 0000000..7c6f94d Binary files /dev/null and b/designs/web-tcef.png differ diff --git a/designs/web-tcef.svg b/designs/web-tcef.svg new file mode 100644 index 0000000..93b6b29 --- /dev/null +++ b/designs/web-tcef.svg @@ -0,0 +1,316 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + TODOS CONTRA EL FUEGO + + + + + + + + + + + + + + + + + + + ESCOGE UN ÁREA DE TÚ INTERÉS + + + + INICIO MAPA ACTUAL CONTACTO HISTORIA ESPAÑOL MÁS + © COPYLEFT BLA BLA BLA + TE AVISAREMOS DEFUEGOS ACTIVOS + + + + + + + + diff --git a/fonts.json b/fonts.json new file mode 100644 index 0000000..81a6ae1 --- /dev/null +++ b/fonts.json @@ -0,0 +1,9 @@ +{ + "extensions": [ "ttf", "woff", "woff2" ], + "map": { + "node_modules/simple-line-icons/fonts/Simple-Line-Icons.woff": "/fonts/Simple-Line-Icons.woff?v=2.4.1", + "node_modules/simple-line-icons/fonts/Simple-Line-Icons.woff2": "/fonts/Simple-Line-Icons.woff2?v=2.4.1", + "node_modules/simple-line-icons/fonts/Simple-Line-Icons.ttf": "/fonts/Simple-Line-Icons.ttf?v=2.4.1" + }, + "verbose": false +} diff --git a/imports/api/ActiveFires/ActiveFires.js b/imports/api/ActiveFires/ActiveFires.js new file mode 100644 index 0000000..16e2760 --- /dev/null +++ b/imports/api/ActiveFires/ActiveFires.js @@ -0,0 +1,60 @@ +/* eslint-disable consistent-return */ + +import { Meteor } from 'meteor/meteor'; +import { Mongo } from 'meteor/mongo'; +import SimpleSchema from 'simpl-schema'; +import firesCommonSchema from '../Common/FiresSchema'; + +const ActiveFires = new Mongo.Collection('activefires', { idGeneration: 'MONGO' }); + +ActiveFires.allow({ + insert: () => false, + update: () => false, + remove: () => false +}); + +ActiveFires.deny({ + insert: () => true, + update: () => true, + remove: () => true +}); + +const activeFiresSchema = firesCommonSchema; + +activeFiresSchema.fireUnion = { type: Meteor.Collection.ObjectID, optional: true, blackbox: true }; + +ActiveFires.schema = new SimpleSchema(activeFiresSchema); + +ActiveFires.attachSchema(ActiveFires.schema); + +export default ActiveFires; + +/* Sample: + * { + * "_id" : ObjectId("5a208d7579095a1adba48191"), + * "ourid" : { + * "type" : "Point", + * "coordinates" : [ + * -42.84192, + * -25.54453 + * ] + * }, + * "lat" : 9.743, + * "lon" : -63.483, + * "updatedAt" : ISODate("2017-11-30T22:02:39.644Z"), + * "type" : "viirs", + * "when" : ISODate("2017-11-30T05:30:00Z"), + * "acq_date" : "2017-11-30", + * "acq_time" : "04:12", + * "scan" : 0.5, + * "track" : 0.4, + * "satellite" : "N", + * "confidence" : "nominal", + * "version" : "1.0NRT", + * "frp" : 4.3, + * "daynight" : "N", + * "bright_ti4" : 330.2, + * "bright_ti5" : 291, + * "createdAt" : ISODate("2017-11-30T08:07:33.720Z") + * } + * */ diff --git a/imports/api/ActiveFires/server/countFires.js b/imports/api/ActiveFires/server/countFires.js new file mode 100644 index 0000000..b3b8511 --- /dev/null +++ b/imports/api/ActiveFires/server/countFires.js @@ -0,0 +1,79 @@ +/* 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 ravenLogger from '/imports/startup/server/ravenLogger'; +import ActiveFires from '../ActiveFires'; + +const debug = 0; + +const cleanProv = (prov, stringsToRemove) => { + let lprov = prov; + stringsToRemove.forEach((st) => { + lprov = lprov.replace(st[0], st[1]); + }); + 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; +}; + +export const countRealFires = (firesCursor) => { + const realFires = []; + firesCursor.forEach((fire) => { + if (debug) console.log(`${JSON.stringify(fire)} -----`); + const union = firesUnion([fire]); + if (debug) console.log(`${JSON.stringify(union)} -----`); + const falsePos = whichAreFalsePositives(FalsePositives, union); + const industries = whichAreFalsePositives(Industries, union); + if (falsePos.count() === 0 && industries.count() === 0) { + realFires.push(fire); + } + }); + // group fires + const realUnion = firesUnion(realFires); + const unionCount = realUnion[0] && + realUnion[0].geometry && + realUnion[0].geometry.coordinates ? realUnion[0].geometry.coordinates.length : 0; + return unionCount; +}; + +const countFiresInRegions = (regions, stringsToRemove) => { + let total = 0; + const fireStats = {}; + + regions.features.forEach((region) => { + const regionName = cleanProv(region.properties.name, stringsToRemove); + const regionCode = region.properties.iso_a2; + if (debug) console.log(`${regionName} -----`); + try { + const fires = findFiresInRegion(region); + // TODO Also check neighbour fires (when better implementation of that part) + const initialCount = fires.count(); + if (initialCount > 0) { + const unionCount = countRealFires(fires); + if (debug) console.log(`${regionName} initial: ${initialCount}, union calc: ${unionCount}`); + if (unionCount > 0) { + total += unionCount; + fireStats[regionName] = { count: unionCount, code: regionCode }; + } + } + } catch (e) { + ravenLogger.log(e); + } + }); + return { total, fires: fireStats }; +}; + +export default countFiresInRegions; diff --git a/imports/api/ActiveFires/server/publications.js b/imports/api/ActiveFires/server/publications.js new file mode 100644 index 0000000..03878b3 --- /dev/null +++ b/imports/api/ActiveFires/server/publications.js @@ -0,0 +1,65 @@ +/* global Counter */ +/* eslint-disable import/no-absolute-path */ +/* eslint-disable prefer-arrow-callback */ + +import { Meteor } from 'meteor/meteor'; +import { check } from 'meteor/check'; +import { NumberBetween } from '/imports/modules/server/other-checks'; +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 counter = new Counter('countActiveFires', ActiveFires.find({})); + +Meteor.publish('activefirestotal', function total() { + return counter; +}); + +const activefires = (northEastLng, northEastLat, southWestLng, southWestLat, withMarks) => { + const fires = ActiveFires.find({ + ourid: { + $geoWithin: { + $box: [ + [southWestLng, southWestLat], + [northEastLng, northEastLat] + ] + } + } + }, { + fields: { + lat: 1, + lon: 1, + when: 1, + scan: 1, + track: 1 + } + }); + + if (Meteor.isDevelopment) console.log(`Active fires total: ${fires.count()}`); + + if (withMarks && fires.fetch().length > 0) { + const union = firesUnion(fires); + const falsePos = whichAreFalsePositives(FalsePositives, union); + const industries = whichAreFalsePositives(Industries, union); + return [fires, falsePos, industries]; + } + + return fires; +}; + +Meteor.publish('activefiresmyloc', function activeInMyLoc(northEastLng, northEastLat, southWestLng, southWestLat, withMarks) { + // latitude -90 and 90 and the longitude between -180 and 180 + check(northEastLng, NumberBetween(-180, 180)); + check(southWestLat, NumberBetween(-90, 90)); + check(southWestLng, NumberBetween(-180, 180)); + check(northEastLat, NumberBetween(-90, 90)); + check(withMarks, Boolean); + + return activefires(northEastLng, northEastLat, southWestLng, southWestLat, withMarks); +}); + +// Warning: this increase always by one the fire stats +Meteor.publish('lastFireDetected', function lastFireDetected() { + return ActiveFires.find({}, { limit: 1, sort: { when: -1 } }); +}); diff --git a/imports/api/ActiveFires/server/tweetFiresInZone.js b/imports/api/ActiveFires/server/tweetFiresInZone.js new file mode 100644 index 0000000..74d40fb --- /dev/null +++ b/imports/api/ActiveFires/server/tweetFiresInZone.js @@ -0,0 +1,155 @@ +/* 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 emojiFlags from 'emoji-flags'; +import tweet from '/imports/modules/server/twitter'; +import countFiresInRegions from './countFires'; + +const debug = false; + +const autonomies = tbuffer(JSON.parse(getPrivateFile('data/es-atlas-autonomies.json')), 0); +const portugal = tbuffer(JSON.parse(getPrivateFile('data/pt-atlas.json')), 0); + +const europe = tbuffer(JSON.parse(getPrivateFile('data/europe-atlas.json')), 0); + +const stringsToRemoveIberia = [ + ['Ciudad Autónoma de', ''], + ['País Vasco/', ''], + ['Pais Vasco', 'Euskadi'], + ['Comunidad Foral de', ''], + ['Región de', ''], + ['Valencia', 'CValenciana'], + ['Comunidad de Madrid', 'CMadrid'], + ['León', 'CyLeón'], + ['Leon', 'CyLeón'], + ['Castilla-', ''], + ['Cataluña/', ''], + ['Cataluña', 'Catalunya'], + ['La Mancha', 'CLMancha'], + ['Baleares', 'IllesBalears'], + ['Galicia', 'Galiza'], + ['Principado de', ''], + [' ', ''] +]; + +const emoji = (key, name, fires) => { + const emo = emojiFlags.countryCode(key.code); + if (!emo) { + if (Meteor.isDevelopment) console.log(`Cannot find flag for country ${name}: ${JSON.stringify(key)}`); + return ''; + } + return `${emo.emoji} ${fires}`; +}; + +const composeEuropeTweet = (num, stats, abrev) => { + if (num <= 0) { + return ''; + } + const keys = Object.keys(stats); + const numZones = keys.length; + let text = ''; + keys.map((key, index) => { // , index + const zoneFires = stats[key].count; + const zoneFiresText = zoneFires > 1 ? index === 0 ? zoneFires : `${zoneFires}` : index === 0 ? 'One' : '1'; + const what = index > 0 ? ' ' : zoneFires > 1 ? ' active #wildfires ' : ' active #wildfire '; + const subText = abrev ? emoji(stats[key], key, zoneFires) : + `${zoneFiresText}${what}in #{key}`; + let delimiter; + if (!abrev) { + delimiter = index === numZones - 1 ? ' and' : ','; + } else { + delimiter = ','; + } + + const subTexts = index === 0 ? subText : `${delimiter} ${subText}`; + text += subTexts; + return ''; + }); + return `${text}`; +}; + +const composeIberiaTweet = (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].count; + 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 correctTweetSize = (tweetText) => { + const length = tweetText.length; + if (length > 280) { + if (Meteor.isDevelopment) console.log(`Tweet is too big (${length}): ${tweetText}`); + return false; + } + return true; +}; + +const tweetEuropeFires = () => { + const resultEu = countFiresInRegions(europe, [[' ', '']]); + + if (resultEu.total > 0) { + let tweetText = `${tweetHeaders[0].trim()} ${composeEuropeTweet(resultEu.total, resultEu.fires, false)}. More info: https://fires.comunes.org/fires`; + if (!correctTweetSize(tweetText)) { + tweetText = `${tweetHeaders[0].trim()}Active #wildfires in #Europe:\n${composeEuropeTweet(resultEu.total, resultEu.fires, true)}. More info: https://fires.comunes.org/fires`; + } + if (!correctTweetSize(tweetText)) { + tweetText = `${tweetHeaders[0].trim()}Active #wildfires in #Europe:\n${composeEuropeTweet(resultEu.total, resultEu.fires, true)}`; + } + if (!correctTweetSize(tweetText)) { + tweetText = `${tweetHeaders[0].trim()} There are ${resultEu.total} active #wildfires in #Europe. More info: https://fires.comunes.org/fires`; + } + if (Meteor.isDevelopment) { + console.log(tweetText); + } else { + tweet(tweetText, 'en'); + } + return tweetText; + } +}; + +const tweetIberiaFires = () => { + const resultEs = countFiresInRegions(autonomies, stringsToRemoveIberia); + const resultPt = countFiresInRegions(portugal, stringsToRemoveIberia); + + 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].trim()} ${composeIberiaTweet(total, fires)}. ${tweetFooters[0]}`; + if (correctTweetSize(tweetText)) { + if (Meteor.isDevelopment) { + console.log(tweetText); + } else { + tweet(tweetText, 'es'); + } + } + return tweetText; + } + return ''; +}; + +if (Meteor.isDevelopment && debug) { + tweetIberiaFires(); + tweetEuropeFires(); +} + +export { composeIberiaTweet, tweetHeaders, tweetFooters, tweetIberiaFires, tweetEuropeFires }; diff --git a/imports/api/ActiveFiresUnion/ActiveFiresUnion.js b/imports/api/ActiveFiresUnion/ActiveFiresUnion.js new file mode 100644 index 0000000..2437e54 --- /dev/null +++ b/imports/api/ActiveFiresUnion/ActiveFiresUnion.js @@ -0,0 +1,71 @@ +/* eslint-disable consistent-return */ +/* eslint-disable import/no-absolute-path */ + +import { Mongo } from 'meteor/mongo'; +import SimpleSchema from 'simpl-schema'; +import LocationSchema from '/imports/api/Utility/LocationSchema.js'; +import { defaultCreatedAt, defaultUpdateAt } from '/imports/api/Utility/Utils.js'; + +const ActiveFiresUnion = new Mongo.Collection('activefiresunion', { idGeneration: 'MONGO' }); + +/* Sample: + * + * TODO + * + * */ + +// We have to store polygons and their centroids +// {"type":"Polygon","coordinates":[[[-5.8645,43.5524],[-5.8621,43.5524],[-5.8621,43.5546],[-5.8645,43.5546],[-5.8645,43.5524]]]} + +ActiveFiresUnion.allow({ + insert: () => false, + update: () => false, + remove: () => false +}); + +ActiveFiresUnion.deny({ + insert: () => true, + update: () => true, + remove: () => true +}); + +// https://www.npmjs.com/package/simpl-schema +const GeoJsonSchema = new SimpleSchema({ + type: { + type: String, + allowedValues: ['Polygon'] + }, + coordinates: { + type: Array + }, + 'coordinates.$': { + type: Array + }, + 'coordinates.$.$': { + type: Array + }, + 'coordinates.$.$.$': { + type: Number + } +}); + +const firesUnionSchema = { + centerid: LocationSchema, + + // https://docs.mongodb.com/manual/reference/geojson/ + // : { type: , coordinates: } + shape: GeoJsonSchema, + history: { type: Array, optional: true }, + 'history.$': GeoJsonSchema, + + when: Date, // First date + + createdAt: defaultCreatedAt, + updatedAt: defaultUpdateAt +}; + +ActiveFiresUnion.schema = new SimpleSchema(firesUnionSchema); + +ActiveFiresUnion.attachSchema(ActiveFiresUnion.schema); + +export default ActiveFiresUnion; diff --git a/imports/api/ActiveFiresUnion/server/publications.js b/imports/api/ActiveFiresUnion/server/publications.js new file mode 100644 index 0000000..6a126d8 --- /dev/null +++ b/imports/api/ActiveFiresUnion/server/publications.js @@ -0,0 +1,80 @@ +/* global Counter */ +/* eslint-disable import/no-absolute-path */ +/* eslint-disable prefer-arrow-callback */ + +import { Meteor } from 'meteor/meteor'; +import { check } from 'meteor/check'; +import { NumberBetween } from '/imports/modules/server/other-checks'; +// import { whichAreFalsePositives, firesUnion } from '/imports/api/FalsePositives/server/publications'; +// import FalsePositives from '/imports/api/FalsePositives/FalsePositives'; +// import Industries from '/imports/api/Industries/Industries'; +import ActiveFiresUnion from '../ActiveFiresUnion'; + +const counter = new Counter('countActiveFiresUnion', ActiveFiresUnion.find({})); + +Meteor.publish('activefiresuniontotal', function total() { + return counter; +}); + +const activeFiresUnion = (b1, b2, c1, c2, withMarks) => { + // a --- b + // c --- d + const geometry = { + $geometry: { + type: 'Polygon', + coordinates: [[ + [c1, c2], + [c1, b2], + [b1, b2], + [b1, c2], + [c1, c2] + ]] + } + }; + // console.log(JSON.stringify(geometry)); + const fires = ActiveFiresUnion.find({ + shape: { + $geoIntersects: geometry + } + }, { + fields: { + shape: 1, + centerid: 1, + when: 1, + createdAt: 1, + updatedAt: 1 + } + }); + + if (Meteor.isDevelopment) console.log(`Active fires union total: ${fires.count()}`); + + /* + if (withMarks && fires.fetch().length > 0) { + const union = firesUnion(fires); + const falsePos = whichAreFalsePositives(FalsePositives, union); + const industries = whichAreFalsePositives(Industries, union); + return [fires, falsePos, industries]; + } */ + + return fires; +}; + +Meteor.publish('activefiresunionmyloc', function activeInMyLoc(northEastLng, northEastLat, southWestLng, southWestLat, withMarks) { + // latitude -90 and 90 and the longitude between -180 and 180 + check(northEastLng, NumberBetween(-180, 180)); + check(southWestLat, NumberBetween(-90, 90)); + check(southWestLng, NumberBetween(-180, 180)); + check(northEastLat, NumberBetween(-90, 90)); + check(withMarks, Boolean); + + // I use this for fire stats + // if (!Meteor.isDevelopment) return this.ready(); // empty + return activeFiresUnion(northEastLng, northEastLat, southWestLng, southWestLat, withMarks); +}); + +// Warning: this increase always by one the fire stats +Meteor.publish('lastFireUnionDetected', function lastFireDetected() { + // I use this for fire stats + // if (!Meteor.isDevelopment) return this.ready(); // empty + return ActiveFiresUnion.find({}, { limit: 1, sort: { when: -1 } }); +}); diff --git a/imports/api/Common/FiresSchema.js b/imports/api/Common/FiresSchema.js new file mode 100644 index 0000000..26236b5 --- /dev/null +++ b/imports/api/Common/FiresSchema.js @@ -0,0 +1,40 @@ +/* eslint-disable import/no-absolute-path */ + +import { defaultCreatedAt, defaultUpdateAt } from '/imports/api/Utility/Utils.js'; +import LocationSchema from '/imports/api/Utility/LocationSchema.js'; + +const firesCommonSchema = { + ourid: LocationSchema, + lat: Number, + lon: Number, + type: String, + when: Date, + + // Neighbour notified fires + + owner: { type: String, optional: true }, + dateformat: { type: String, optional: true }, + ourversion: { type: String, optional: true }, + + // NASA types + address: { type: String, optional: true }, // reverse geo + scan: { type: Number, optional: true }, + track: { type: Number, optional: true }, + acq_date: { type: String, optional: true }, + acq_time: { type: String, optional: true }, + satellite: { type: String, optional: true }, + confidence: { type: Number, optional: true }, + version: { type: String, optional: true }, + frp: { type: Number, optional: true }, + daynight: { type: String, optional: true }, + brightness: { type: Number, optional: true }, + bright_t31: { type: Number, optional: true }, + bright_ti4: { type: Number, optional: true }, + bright_ti5: { type: Number, optional: true }, + + // common + createdAt: defaultCreatedAt, + updatedAt: defaultUpdateAt +}; + +export default firesCommonSchema; diff --git a/imports/api/Common/dates.js b/imports/api/Common/dates.js new file mode 100644 index 0000000..7fb4bf3 --- /dev/null +++ b/imports/api/Common/dates.js @@ -0,0 +1,7 @@ +import moment from 'moment-timezone'; + +export const momentTz = date => moment.tz(date, moment.tz.guess()); +export const dateLongFormat = date => momentTz(date).format('LLLL (z)'); +export const dateParseShortFormat = date => moment(date, 'YYYY-MM-DD').format('LL'); +export const dateYYYYMMDD = date => moment(date).format('YYYY-MM-DD'); +export const dateFromNow = date => momentTz(date).fromNow(); diff --git a/imports/api/Documents/server/publications.js b/imports/api/Documents/server/publications.js index f667a8b..02f546d 100644 --- a/imports/api/Documents/server/publications.js +++ b/imports/api/Documents/server/publications.js @@ -1,3 +1,5 @@ +/* eslint-disable prefer-arrow-callback */ + import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import Documents from '../Documents'; diff --git a/imports/api/FalsePositives/FalsePositiveTypes.js b/imports/api/FalsePositives/FalsePositiveTypes.js new file mode 100644 index 0000000..274fd5d --- /dev/null +++ b/imports/api/FalsePositives/FalsePositiveTypes.js @@ -0,0 +1,10 @@ +// FIXME Right now, only industry type should be a permanent 'false alarm', the rest are temporally + +const types = { + industry: 'Es una industria', + // TODO volcano: 'Es un volcán', + controled: 'Es una quema controlada', + falsealarm: 'Parece una falsa alarma' +}; + +export default types; diff --git a/imports/api/FalsePositives/FalsePositives.js b/imports/api/FalsePositives/FalsePositives.js new file mode 100644 index 0000000..eead435 --- /dev/null +++ b/imports/api/FalsePositives/FalsePositives.js @@ -0,0 +1,48 @@ +/* eslint-disable consistent-return */ + +import { Meteor } from 'meteor/meteor'; +import { Mongo } from 'meteor/mongo'; +import SimpleSchema from 'simpl-schema'; +import { defaultCreatedAt, defaultUpdateAt } from '/imports/api/Utility/Utils.js'; +import LocationSchema from '/imports/api/Utility/LocationSchema.js'; + +const FalsePositives = new Mongo.Collection('falsePositives', { idGeneration: 'MONGO' }); + +FalsePositives.allow({ + insert: () => false, + update: () => false, + remove: () => false +}); + +FalsePositives.deny({ + insert: () => true, + update: () => true, + remove: () => true +}); + +FalsePositives.schema = new SimpleSchema({ + geo: LocationSchema, + fireId: { type: Meteor.Collection.ObjectID, optional: true, blackbox: true }, + chatId: { type: Number, optional: true }, // only in 'telegram' type + owner: String, + type: String, + when: Date, + whendateformat: String, + createdAt: defaultCreatedAt, + updatedAt: defaultUpdateAt +}); + +FalsePositives.attachSchema(FalsePositives.schema); + +export const falsePositivesRemap = (odoc) => { + const doc = odoc; + const geo = doc.geo; + doc.lat = geo.coordinates[1]; + doc.lon = geo.coordinates[0]; + doc._id = doc.fireId; + doc.id = doc.fireId; + delete doc.geo; + return doc; +}; + +export default FalsePositives; diff --git a/imports/api/FalsePositives/methods.js b/imports/api/FalsePositives/methods.js new file mode 100644 index 0000000..85005ba --- /dev/null +++ b/imports/api/FalsePositives/methods.js @@ -0,0 +1,58 @@ +import { Meteor } from 'meteor/meteor'; +import { check } from 'meteor/check'; +import moment from 'moment'; +import FalsePositives from './FalsePositives'; +import FalsePositiveTypes from './FalsePositiveTypes'; +import Fires from '../Fires/Fires'; +import rateLimit from '../../modules/rate-limit'; + +export function upsertFalsePositive(keyType, owner, fire) { + const fireType = fire.type; + if (fireType === 'vecinal') { + throw new Meteor.Error('500', 'No se puede marcar este tipo de fuego'); + } + const date = new Date(); + const formated = moment(date).format('YYYYMMDD'); + try { + const set = { + owner, + type: keyType, + when: date, + whendateformat: formated, + fireId: fire._id, + geo: fire.ourid + }; + return FalsePositives.upsert({ geo: fire.ourid, owner }, { $set: set }, { multi: false, upsert: true }); + } catch (exception) { + console.log(exception); + throw new Meteor.Error('500', exception); + } +} + +Meteor.methods({ + 'falsePositives.insert': function falsePositivesInsert(fireId, keyType) { + check(fireId, Meteor.Collection.ObjectID); + check(keyType, String); + const type = FalsePositiveTypes[keyType]; + check(type, String); + if (!this.userId) { + throw new Meteor.Error('500', 'Regístrate o inicia sesión para aportar información sobre este fuego'); + } + check(this.userId, String); + const fire = Fires.findOne(fireId); + const owner = this.userId; + if (fire) { + upsertFalsePositive(keyType, owner, fire); + } else { + throw new Meteor.Error('500', 'Fuego no encontrado'); + } + } +}); + +rateLimit({ + methods: [ + 'falsePositives.insert' + ], + limit: 5, + timeRange: 1000 +}); diff --git a/imports/api/FalsePositives/server/publications.js b/imports/api/FalsePositives/server/publications.js new file mode 100644 index 0000000..a79ae1a --- /dev/null +++ b/imports/api/FalsePositives/server/publications.js @@ -0,0 +1,105 @@ +/* global Counter */ +/* eslint-disable import/no-absolute-path */ +/* eslint-disable prefer-arrow-callback */ + +import { Meteor } from 'meteor/meteor'; +import { check } from 'meteor/check'; +import { NumberBetween } from '/imports/modules/server/other-checks'; +import '/imports/startup/server/leaflet-workaround.js'; +import L from 'leaflet'; +import calcUnion from '/imports/ui/components/Maps/SubsUnion/Unify'; +import Industries from '/imports/api/Industries/Industries'; +import FalsePositives from '../FalsePositives'; + +const counter = new Counter('countFalsePositives', FalsePositives.find({})); + +Meteor.publish('falsePositivesTotal', function total() { + return counter; +}); + +export const firesUnion = (fires) => { + const firesArray = Array.isArray(fires) ? fires : fires.fetch(); // if not is a cursor + const remap = firesArray.map(function remap(doc) { + const isNASA = doc.type === 'modis' || doc.type === 'viirs'; + const pixelSize = doc.type === 'viirs' ? 0.375 : 1; // viirs has 375m pixel size, modis 1000m + // default 1 km for neightbor alerts + const map = { + location: { lat: doc.lat, lon: doc.lon }, + distance: isNASA ? doc.scan * pixelSize : 1, + distanceY: isNASA ? doc.track * pixelSize : 1 + }; + // console.log(map); + return map; + }); + const union = calcUnion(L, remap, sub => sub, false); + return union; +}; + +export const zoneToUnion = (lat, lon, distance) => { + const remap = [{ location: { lat, lon }, distance }]; + const union = calcUnion(L, remap, sub => sub, true); + return union; +}; + +export const whichAreFalsePositives = (collection, union) => { + const result = collection.find({ + geo: { + $geoWithin: { + $geometry: union[0].geometry + } + } + }, { + fields: { + geo: 1, + // type: 1, + // when: 1, + fireId: 1 + } + }); + + /* console.log(`False positive total: ${falsePos.count()}`); + console.log(`False positives: ${JSON.stringify(falsePos.fetch())}`); */ + return result; +}; + +const find = (collection, northEastLng, northEastLat, southWestLng, southWestLat) => { + const fires = collection.find({ + geo: { + $geoWithin: { + $box: [ + [southWestLng, southWestLat], + [northEastLng, northEastLat] + ] + } + } + }, { + fields: { + geo: 1, + // type: 1, + // when: 1, + fireId: 1 + } + }); + // console.log(`Fires total: ${fires.count()}`); + return fires; +}; + +Meteor.publishTransformed('falsePositivesMyloc', function falsePositivesInMyLoc(northEastLng, northEastLat, southWestLng, southWestLat) { + // latitude -90 and 90 and the longitude between -180 and 180 + check(northEastLng, NumberBetween(-180, 180)); + check(southWestLat, NumberBetween(-90, 90)); + check(southWestLng, NumberBetween(-180, 180)); + check(northEastLat, NumberBetween(-90, 90)); + + return find(FalsePositives, northEastLng, northEastLat, southWestLng, southWestLat); +}); + +Meteor.publishTransformed('industriesMyloc', function industriesInMyLoc(northEastLng, northEastLat, southWestLng, southWestLat) { + // latitude -90 and 90 and the longitude between -180 and 180 + check(northEastLng, NumberBetween(-180, 180)); + check(southWestLat, NumberBetween(-90, 90)); + check(southWestLng, NumberBetween(-180, 180)); + check(northEastLat, NumberBetween(-90, 90)); + + return find(Industries, northEastLng, northEastLat, southWestLng, southWestLat); +}); diff --git a/imports/api/FireAlerts/FireAlerts.js b/imports/api/FireAlerts/FireAlerts.js new file mode 100644 index 0000000..9c4a37d --- /dev/null +++ b/imports/api/FireAlerts/FireAlerts.js @@ -0,0 +1,25 @@ +/* eslint-disable consistent-return */ + +import { Mongo } from 'meteor/mongo'; +import SimpleSchema from 'simpl-schema'; +import firesCommonSchema from '../Common/FiresSchema'; + +const FireAlerts = new Mongo.Collection('avisosfuego', { idGeneration: 'MONGO' }); + +FireAlerts.allow({ + insert: () => false, + update: () => false, + remove: () => false +}); + +FireAlerts.deny({ + insert: () => true, + update: () => true, + remove: () => true +}); + +FireAlerts.schema = new SimpleSchema(firesCommonSchema); + +FireAlerts.attachSchema(FireAlerts.schema); + +export default FireAlerts; diff --git a/imports/api/FireAlerts/server/publications.js b/imports/api/FireAlerts/server/publications.js new file mode 100644 index 0000000..6642f35 --- /dev/null +++ b/imports/api/FireAlerts/server/publications.js @@ -0,0 +1,42 @@ +/* eslint-disable prefer-arrow-callback */ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import { check } from 'meteor/check'; +import { NumberBetween } from '/imports/modules/server/other-checks'; +import FireAlerts from '../FireAlerts'; + +Meteor.publish('fireAlerts', function fireAlerts(northEastLng, northEastLat, southWestLng, southWestLat) { + // latitude -90 and 90 and the longitude between -180 and 180 + check(northEastLng, NumberBetween(-180, 180)); + check(southWestLat, NumberBetween(-90, 90)); + check(southWestLng, NumberBetween(-180, 180)); + check(northEastLat, NumberBetween(-90, 90)); + + // https://stackoverflow.com/questions/29327222/mongodb-find-created-results-by-date-today/29327353 + const start = new Date(); + start.setHours(0, 0, 0, 0); + const end = new Date(); + end.setHours(23, 59, 59, 999); + + const fires = FireAlerts.find({ + ourid: { + $geoWithin: { + $box: [ + [southWestLng, southWestLat], + [northEastLng, northEastLat] + ] + } + }, + createdAt: { $gte: start, $lt: end } + }, { + fields: { + lat: 1, + lon: 1, + scan: 1, + track: 1 + } + }); + if (Meteor.isDevelopment) console.log(`Neighbour alerts total: ${fires.count()}`); + return fires; +}); diff --git a/imports/api/Fires/Fires.js b/imports/api/Fires/Fires.js new file mode 100644 index 0000000..12a87f5 --- /dev/null +++ b/imports/api/Fires/Fires.js @@ -0,0 +1,25 @@ +/* eslint-disable consistent-return */ + +import { Mongo } from 'meteor/mongo'; +import SimpleSchema from 'simpl-schema'; +import firesCommonSchema from '../Common/FiresSchema'; + +const Fires = new Mongo.Collection('fires', { idGeneration: 'MONGO' }); + +Fires.allow({ + insert: () => false, + update: () => false, + remove: () => false +}); + +Fires.deny({ + insert: () => true, + update: () => true, + remove: () => true +}); + +Fires.schema = new SimpleSchema(firesCommonSchema); + +Fires.attachSchema(Fires.schema); + +export default Fires; diff --git a/imports/api/Fires/methods.js b/imports/api/Fires/methods.js new file mode 100644 index 0000000..1d7758d --- /dev/null +++ b/imports/api/Fires/methods.js @@ -0,0 +1,22 @@ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import { check } from 'meteor/check'; +import rateLimit from '/imports/modules/rate-limit'; +import urlEnc from '/imports/modules/url-encode'; + +Meteor.methods({ + 'fire.decrypt': async function fireDecode(fireEnc) { + check(fireEnc, String); + const unsealed = await urlEnc.decrypt(fireEnc); + return unsealed; + } +}); + +rateLimit({ + methods: [ + 'fire.decode' + ], + limit: 5, + timeRange: 1000 +}); diff --git a/imports/api/Fires/server/publications.js b/imports/api/Fires/server/publications.js new file mode 100644 index 0000000..3862beb --- /dev/null +++ b/imports/api/Fires/server/publications.js @@ -0,0 +1,178 @@ +/* eslint-disable import/no-absolute-path */ +/* eslint-disable prefer-arrow-callback */ + +import { Meteor } from 'meteor/meteor'; +import { check } from 'meteor/check'; +import urlEnc from '/imports/modules/url-encode'; +import { Promise } from 'meteor/promise'; +import NodeGeocoder from 'node-geocoder'; +import { gmapServerKey } from '/imports/startup/server/IPGeocoder'; +import ActiveFiresCollection from '/imports/api/ActiveFires/ActiveFires'; +import FireAlertsCollection from '/imports/api/FireAlerts/FireAlerts'; +import { whichAreFalsePositives, firesUnion } from '/imports/api/FalsePositives/server/publications'; +import FalsePositives from '/imports/api/FalsePositives/FalsePositives'; +import Industries from '/imports/api/Industries/Industries'; +import ravenLogger from '/imports/startup/server/ravenLogger'; + +import FiresCollection from '../Fires'; + +function findFire(unsealed) { + const fire = FiresCollection.find({ ourid: { type: 'Point', coordinates: [unsealed.lon, unsealed.lat] }, when: unsealed.when, type: unsealed.type }); + return fire; +} + +const options = { + provider: 'google', + // Optional depending on the providers + httpAdapter: 'https', // Default + apiKey: gmapServerKey, // for Mapquest, OpenCage, Google Premier + formatter: null // 'gpx', 'string', ... +}; + +const geocoder = NodeGeocoder(options); + +const unseal = async (obj) => { + try { + const unsealed = await urlEnc.decrypt(obj); + return unsealed; + } catch (error) { + // console.warn(error); + return undefined; + } +}; + +const unsealW = obj => unseal(obj); + +const fixConfidence = (obj) => { + if (typeof obj.confidence === 'string') { + obj.confidence = Number.parseInt(obj.confidence, 10); + } + if (typeof obj.confidence === 'undefined' || isNaN(obj.confidence)) { + delete obj.confidence; + } + return obj; +}; + +const findOrCreateFire = (obj) => { + const fire = findFire(obj); + // console.log(`Found: ${fire.count()}`); + if (!obj.address) { + try { + const rev = Promise.await(geocoder.reverse({ lat: obj.lat, lon: obj.lon })); + if (rev[0]) { + obj.address = rev[0].formattedAddress; + } + // console.log(obj.address); + } catch (reve) { + console.warn(reve); + } + } + if (fire.count() === 0) { + // const result = + // console.log('Creating new fire'); + FiresCollection.upsert({ ourid: obj.ourid, when: obj.when, type: obj.type }, { $set: obj }, { multi: false, upsert: true }); + // console.log(JSON.stringify(result)); + } + return findFire(obj); +}; + +Meteor.publish('fireFromAlertId', function fireFromAlertId(_id) { + try { + check(_id, String); + // console.log(`Looking for alert fire ${_id}`); + const fire = FireAlertsCollection.findOne(new Meteor.Collection.ObjectID(_id)); + if (fire) { + // console.info(`Active fire found: ${_id}`); + return findOrCreateFire(fixConfidence(fire)); + } + console.info(`Alert fire not found: ${_id}`); + // Not found in active fires! + return this.ready(); + } catch (e) { + console.info(`Alert fire not found (with error): ${_id}`); + return this.ready(); + } +}); + +Meteor.publish('fireFromActiveId', function fireFromActiveId(_id) { + try { + check(_id, String); + // console.log(`Looking for active fire ${_id}`); + const fire = ActiveFiresCollection.findOne(new Meteor.Collection.ObjectID(_id)); + if (fire) { + // console.info(`Active fire found: ${_id}`); + return findOrCreateFire(fixConfidence(fire)); + } + console.info(`Active fire not found: ${_id}`); + // Not found in active fires! + return this.ready(); + } catch (e) { + console.info(`Active fire not found (with error): ${_id}`); + return this.ready(); + } +}); + +Meteor.publish('fireFromId', function fireFromId(_id) { + try { + check(_id, String); + // console.log(`Looking for archive fire ${_id}`); + const fire = FiresCollection.find(new Meteor.Collection.ObjectID(_id)); + if (fire.count() !== 0) { + // console.info(`Archive fire found: ${_id}`); + const union = firesUnion(fire); + const falsePos = whichAreFalsePositives(FalsePositives, union); + const industries = whichAreFalsePositives(Industries, union); + return [fire, falsePos, industries]; + } + console.info(`Fire not found: ${_id}`); + // Not found in active fires! + return this.ready(); + } catch (e) { + console.info(`Archive fire not found (with error): ${_id}`); + return this.ready(); + } +}); + +function logUrl(fireEnc, params) { + const message = `Wrong fire: ${fireEnc}. Params received in url: ${JSON.stringify(params)}`; + console.log(message); + ravenLogger.log(message); +} + +export function fireFromHash(fireEnc, params) { + check(fireEnc, String); + check(params, Object); + + // console.log(fireEnc); + // const unsealed = Promise.await(urlEnc.decrypt(fireEnc)); + const unsealed = Promise.await(unsealW(fireEnc)); + if (unsealed === undefined) { + throw Error(`Fail to unseal '${fireEnc}'`); + } + const w = unsealed.when; + unsealed.when = new Date(w); + const c = unsealed.createdAt; + unsealed.createdAt = !c ? new Date() : new Date(c); + const u = unsealed.updatedAt; + unsealed.updatedAt = !u ? new Date() : new Date(u); + // console.log(unsealed); + // FIXME: + const unsealedFix = fixConfidence(unsealed); + FiresCollection.schema.validate(unsealedFix); + return findOrCreateFire(unsealedFix); + /* console.log(`fires: ${fire.count()}`); + * return fire; */ +} + +Meteor.publish('fireFromHash', function fireFromHashFunc(fireEnc, params) { + check(fireEnc, String); + check(params, Object); + try { + return fireFromHash(fireEnc, params); + } catch (e) { + console.warn(e); + logUrl(fireEnc, params); + // https://guide.meteor.com/data-loading.html + return this.ready(); + } +}); diff --git a/imports/api/Industries/Industries.js b/imports/api/Industries/Industries.js new file mode 100644 index 0000000..dd1fde0 --- /dev/null +++ b/imports/api/Industries/Industries.js @@ -0,0 +1,58 @@ +/* eslint-disable consistent-return */ + +import { Mongo } from 'meteor/mongo'; +import SimpleSchema from 'simpl-schema'; +import LocationSchema from '/imports/api/Utility/LocationSchema.js'; + +const Industries = new Mongo.Collection('industries'); + +// https://prtr.unece.org/prtr-global-map +// For now using: + +// AUSTRALIA +// https://data.gov.au/dataset/npi# +// +// EUROPE +// https://www.eea.europa.eu/data-and-maps/data/member-states-reporting-art-7-under-the-european-pollutant-release-and-transfer-register-e-prtr-regulation-16 +// +// CANADA +// https://www.canada.ca/en/environment-climate-change/services/national-pollutant-release-inventory/tools-resources-data/access.html +// +// USA +// https://www.epa.gov/enviro/epa-frs-facilities-state-single-file-csv-download + +// TODO: +// http://www.nite.go.jp/ +// http://www.retc.cl/datos-retc/ + +Industries.allow({ + insert: () => false, + update: () => false, + remove: () => false +}); + +Industries.deny({ + insert: () => true, + update: () => true, + remove: () => true +}); + +Industries.schema = new SimpleSchema({ + geo: LocationSchema, + name: { type: String, optional: true }, + registry: String +}); + +Industries.attachSchema(Industries.schema); + +export const industriesRemap = (odoc) => { + const doc = odoc; + const geo = doc.geo; + doc.lat = geo.coordinates[1]; + doc.lon = geo.coordinates[0]; + doc.id = doc._id; + delete doc.geo; + return doc; +}; + +export default Industries; diff --git a/imports/api/Industries/IndustryRegistries.js b/imports/api/Industries/IndustryRegistries.js new file mode 100644 index 0000000..5eec43b --- /dev/null +++ b/imports/api/Industries/IndustryRegistries.js @@ -0,0 +1,29 @@ +/* eslint-disable consistent-return */ + +import { Mongo } from 'meteor/mongo'; +import SimpleSchema from 'simpl-schema'; + +const IndustryRegistries = new Mongo.Collection('industryregistries', { idGeneration: 'MONGO' }); + +IndustryRegistries.allow({ + insert: () => false, + update: () => false, + remove: () => false +}); + +IndustryRegistries.deny({ + insert: () => true, + update: () => true, + remove: () => true +}); + +IndustryRegistries.schema = new SimpleSchema({ + name: String, + agency: String, + region: String + +}); + +IndustryRegistries.attachSchema(IndustryRegistries.schema); + +export default IndustryRegistries; diff --git a/imports/api/Notifications/Notifications.js b/imports/api/Notifications/Notifications.js new file mode 100644 index 0000000..0355540 --- /dev/null +++ b/imports/api/Notifications/Notifications.js @@ -0,0 +1,42 @@ +/* eslint-disable consistent-return */ +/* eslint-disable import/no-absolute-path */ + +import { Mongo } from 'meteor/mongo'; +import { Meteor } from 'meteor/meteor'; +import SimpleSchema from 'simpl-schema'; +import { defaultCreatedAt, defaultUpdateAt } from '/imports/api/Utility/Utils.js'; +import LocationSchema from '/imports/api/Utility/LocationSchema.js'; + +const Notifications = new Mongo.Collection('notifications', { idGeneration: 'MONGO' }); + +Notifications.allow({ + insert: () => false, + update: () => false, + remove: () => false +}); + +Notifications.deny({ + insert: () => true, + update: () => true, + remove: () => true +}); + +Notifications.schema = new SimpleSchema({ + userId: String, + subsId: { type: Meteor.Collection.ObjectID, optional: true, blackbox: true }, + content: String, + geo: LocationSchema, + type: String, + notified: { type: Boolean, optional: true }, + notifiedAt: { type: Date, optional: true }, + emailNotified: { type: Boolean, optional: true }, + emailNotifiedAt: { type: Date, optional: true }, + when: Date, + sealed: String, + createdAt: defaultCreatedAt, + updatedAt: defaultUpdateAt +}); + +Notifications.attachSchema(Notifications.schema); + +export default Notifications; diff --git a/imports/api/Notifications/methods.js b/imports/api/Notifications/methods.js new file mode 100644 index 0000000..05d7d08 --- /dev/null +++ b/imports/api/Notifications/methods.js @@ -0,0 +1,25 @@ +import { Meteor } from 'meteor/meteor'; +import { check } from 'meteor/check'; +import Notifications from './Notifications'; +import rateLimit from '../../modules/rate-limit'; + +Meteor.methods({ + 'notifications.sent': function notificationsUpdate(notifId) { + check(notifId, Meteor.Collection.ObjectID); + + try { + Notifications.update(notifId, { $set: { notified: true, notifiedAt: new Date() } }); + return notifId; + } catch (exception) { + throw new Meteor.Error('500', exception); + } + } +}); + +rateLimit({ + methods: [ + 'notifications.sent' + ], + limit: 5, + timeRange: 1000 +}); diff --git a/imports/api/Notifications/server/publications.js b/imports/api/Notifications/server/publications.js new file mode 100644 index 0000000..d868692 --- /dev/null +++ b/imports/api/Notifications/server/publications.js @@ -0,0 +1,10 @@ +/* eslint-disable prefer-arrow-callback */ + +import { Meteor } from 'meteor/meteor'; +import Notifications from '../Notifications'; + +Meteor.publish('mynotifications', function notifications() { + const notif = Notifications.find({ userId: this.userId, type: 'web', notified: null }); + // console.log(`Notifications for user ${this.userId}: ${notif.count()}`); + return notif; +}); diff --git a/imports/api/Rest/Rest.js b/imports/api/Rest/Rest.js new file mode 100644 index 0000000..ae5e383 --- /dev/null +++ b/imports/api/Rest/Rest.js @@ -0,0 +1,457 @@ +/* global Restivus */ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import { NumberBetween } from '/imports/modules/server/other-checks'; +import Fires from '/imports/api/Fires/Fires'; +import { check } from 'meteor/check'; +import SiteSettings from '/imports/api/SiteSettings/SiteSettings'; +import ActiveFiresCollection from '/imports/api/ActiveFires/ActiveFires'; +import { countRealFires } from '/imports/api/ActiveFires/server/countFires'; +import { whichAreFalsePositives, firesUnion, zoneToUnion } from '/imports/api/FalsePositives/server/publications'; +import { fireFromHash } from '/imports/api/Fires/server/publications.js'; +import FalsePositives from '/imports/api/FalsePositives/FalsePositives'; +import Industries from '/imports/api/Industries/Industries'; +import Subscriptions from '/imports/api/Subscriptions/Subscriptions'; +import jsend from 'jsend'; +import { Random } from 'meteor/random'; +import { subscriptionsInsert } from '/imports/api/Subscriptions/methods.js'; +import { Mongo } from 'meteor/mongo'; +import { upsertFalsePositive } from '/imports/api/FalsePositives/methods.js'; + +const debug = false; + +const uptime = new Date(); + +const restivusError = (code, message) => ({ status: 'error', statusCode: code, body: message }); + + +function failMsg(msg) { + return restivusError(500, `Unexpected error in REST call: ${msg}`); +} + +function fail(e) { + return restivusError(500, `Unexpected error in REST call: ${e}`); +} + +function defaultFailParams(e) { + return restivusError(400, `Wrong REST params: ${e}`); +} + +function checkAuthToken(token) { + if (!Meteor.settings.private.internalApiToken || token !== Meteor.settings.private.internalApiToken) { + const message = 'Unauthorized auth token in REST API'; + console.warn(message); + return restivusError(401, message); + } + return undefined; +} + +function checkLatLonDist(km, lat, lng) { + check(lng, NumberBetween(-180, 180)); + check(lat, NumberBetween(-90, 90)); + check(km, NumberBetween(0, Meteor.isDevelopment ? 1000 : 100)); +} + +if (!Meteor.settings.private.internalApiToken) { + console.warn('Meteor.settings.private.internalApiToken is not configured so we don\'t enable our REST API'); +} else { +// export + const apiV1 = new Restivus({ + useDefaultAuth: true, + apiPath: 'api', + version: 'v1', + prettyJson: true + }); + + // Generates: POST on /api/users and GET, DELETE /api/users/:id for + // Meteor.users collection + /* apiV1.addCollection(Meteor.users, { + * excludedEndpoints: ['getAll', 'put', 'delete', 'patch', 'get'], + * routeOptions: { + * authRequired: true + * }, + * endpoints: { + * post: { + * authRequired: false + * }, + * delete: { + * roleRequired: 'admin' + * } + * } + * }); */ + + apiV1.addCollection(Fires, { + excludedEndpoints: ['put', 'post', 'patch', 'delete'], + // excludedEndpoints: ['getAll', 'put', 'post', 'patch', 'delete'], + routeOptions: { + authRequired: false + }, + endpoints: { + get: { + action: function getFire() { + return Fires.findOne(new Meteor.Collection.ObjectID(this.urlParams.id)); + } + } + } + }); + + // Maps to: /api/v1/status/last-fire-check + apiV1.addRoute('status/last-fire-check', { authRequired: false }, { + get: function get() { + return SiteSettings.findOne({ name: 'last-fire-check' }); + } + }); + + // Maps to: /api/v1/status/last-fire-detected + apiV1.addRoute('status/last-fire-detected', { authRequired: false }, { + get: function get() { + return ActiveFiresCollection.findOne({}, { sort: { when: -1 } }); + } + }); + + // Maps to: /api/v1/status/active-fires-count + apiV1.addRoute('status/active-fires-count', { authRequired: false }, { + get: function get() { + return { total: ActiveFiresCollection.find({}).count() }; + } + }); + + // Maps to: /api/v1/status/uptime + apiV1.addRoute('status/uptime', { authRequired: false }, { + get: function get() { + return { ms: new Date() - uptime }; + } + }); + + function getFires(route, full) { + const lat = Number(route.urlParams.lat); + const lng = Number(route.urlParams.lng); + const km = Number(route.urlParams.km); + const { token } = route.urlParams; + try { + checkLatLonDist(km, lat, lng); + check(token, String); + } catch (e) { + return defaultFailParams(e); + } + + const failed = checkAuthToken(token); + if (failed) return failed; + + if (debug) console.log(`Query for fires in ${lat}, ${lng} in ${km} km radius`); + + const fires = ActiveFiresCollection.find({ + ourid: { + $near: { + $geometry: { + type: 'Point', + coordinates: [lng, lat] + }, + $maxDistance: km * 1000, + $minDistance: 0 + } + } + }, { + fields: { + lat: 1, + lon: 1, + when: 1, + type: 1, // modis, viirs, vecinal + scan: 1, + track: 1 + } + }); + + const result = { total: fires.count(), real: countRealFires(fires) }; + if (debug) console.log(`Query for fires in ${lat}, ${lng} in ${km} km radius ${result}`); + + if (!full) { + return result; + } + + let union; + + // TODO only get real + const firesA = fires.fetch(); + + if (firesA.length > 0) { + union = firesUnion(fires); + } else { + union = zoneToUnion(lat, lng, km); + } + const falsePos = whichAreFalsePositives(FalsePositives, union); + const industries = whichAreFalsePositives(Industries, union); + result.fires = firesA; + result.industries = industries.fetch(); + result.falsePos = falsePos.fetch(); + return result; + } + + // Maps to: /api/v1/fires-in/:lat/:lng/:km + // 100 km max + // Ex: http://127.0.0.1:3000/api/v1/fires-in/token/38.736946/-9.142685/100 + apiV1.addRoute('fires-in/:token/:lat/:lng/:km', { authRequired: false }, { + get: function get() { + return getFires(this, false); + } + }); + + apiV1.addRoute('fires-in-full/:token/:lat/:lng/:km', { authRequired: false }, { + get: function get() { + return getFires(this, true); + } + }); + + // Add mobile user: + // curl -X POST http://localhost:3000/api/v1/users/mobile -d "token: thisAppAutToken" -d "mobileToken: user-mobile-firebase-token" + // Response: + // + // https://docs.meteor.com/api/passwords.html#Accounts-createUser + apiV1.addRoute('mobile/users', { authRequired: false }, { + post: function post() { + const { token, mobileToken, lang } = this.bodyParams; + try { + check(token, String); + check(lang, String); + check(mobileToken, String); + } catch (e) { + return defaultFailParams(e); + } + + const failed = checkAuthToken(token); + if (failed) return failed; + + let username; + + const already = Meteor.users.find({ fireBaseToken: mobileToken }); + + if (already.count() > 1) { + return restivusError(500, 'Unexpected error in REST call: several users with that mobile token?'); + } else if (already.count() === 1) { + username = already.fetch()[0].username; + } else { + do { + username = Random.id(15); + } while (Meteor.users.find({ username }).count() !== 0); + } + + // FIXME check valid lang + + const now = new Date(); + + const result = Meteor.users.upsert({ + fireBaseToken: mobileToken + }, { + $set: { + username, + fireBaseToken: mobileToken, + lang, + profile: { }, + createdAt: now, + updatedAt: now + } + }); + + + if (debug) { + console.log(this.bodyParams); + console.log(this.urlParams); + console.log(this.queryParams); + } + + const upsertUser = Meteor.users.findOne({ username }); + + if (debug) console.log(upsertUser); + + return jsend.success({ + upsertResult: result, + username, + userId: upsertUser._id, + lang: upsertUser.lang, + mobileToken: upsertUser.fireBaseToken + }); + } + + }); + + // max sitance: 100km + apiV1.addRoute('mobile/subscriptions', { authRequired: false }, { + post: function post() { + const { + token, + mobileToken, + id, + lat, + lon, + distance + } = this.bodyParams; + let oid; + try { + check(token, String); + check(mobileToken, String); + check(id, String); + oid = new Mongo.ObjectID(id); + check(oid, Meteor.Collection.ObjectID); + check(lat, Number); + check(lon, Number); + check(distance, Number); + checkLatLonDist(distance, lat, lon); + } catch (e) { + if (debug) console.log(e); + return defaultFailParams(e); + } + + const failed = checkAuthToken(token); + if (failed) return failed; + + const user = Meteor.users.findOne({ fireBaseToken: mobileToken }); + if (!user) return failMsg('User not found'); + + const newSubs = {}; + newSubs._id = new Meteor.Collection.ObjectID(id); + newSubs.location = {}; + newSubs.location.lat = lat; + newSubs.location.lon = lon; + newSubs.distance = distance; + + let result; + try { + result = subscriptionsInsert(newSubs, user._id, 'mobile'); + } catch (e) { + return fail(e); + } + return jsend.success({ subsId: result._str }); + } + }); + + apiV1.addRoute('mobile/subscriptions/:token/:mobileToken/:subsId', { authRequired: false }, { + delete: function del() { + const { + token, + mobileToken, + subsId + } = this.urlParams; + try { + check(token, String); + check(mobileToken, String); + check(subsId, String); + } catch (e) { + return defaultFailParams(e); + } + + const failed = checkAuthToken(token); + if (failed) return failed; + + const user = Meteor.users.findOne({ fireBaseToken: mobileToken }); + if (!user) return failMsg('User not found'); + + try { + Subscriptions.remove({ owner: user._id, _id: new Meteor.Collection.ObjectID(subsId) }); + } catch (e) { + return fail(e); + } + + return jsend.success({}); + } + }); + + apiV1.addRoute('mobile/subscriptions/all/:token/:mobileToken', { authRequired: false }, { + get: function get() { + const { token, mobileToken } = this.urlParams; + try { + check(token, String); + check(mobileToken, String); + } catch (e) { + return defaultFailParams(e); + } + + const failed = checkAuthToken(token); + if (failed) return failed; + + const user = Meteor.users.findOne({ fireBaseToken: mobileToken }); + if (!user) return failMsg('User not found'); + + const result = Subscriptions.find({ owner: user._id }); + + return jsend.success({ subscriptions: result.fetch(), count: result.count() }); + }, + delete: function delAll() { + const { token, mobileToken } = this.urlParams; + try { + check(token, String); + check(mobileToken, String); + } catch (e) { + return defaultFailParams(e); + } + + const failed = checkAuthToken(token); + if (failed) return failed('Auth api check failed'); + + if (Meteor.users.find({ fireBaseToken: mobileToken }).count() !== 1) return fail; + + const user = Meteor.users.findOne({ fireBaseToken: mobileToken }); + if (!user) return failMsg('User not found'); + + const toRemove = Subscriptions.find({ owner: user._id }).count(); + Subscriptions.remove({ owner: user._id }); + + return jsend.success({ count: toRemove }); + } + }); + + apiV1.addRoute('status/subs-public-union/:token', { authRequired: false }, { + get: function get() { + const { token } = this.urlParams; + try { + check(token, String); + } catch (e) { + return defaultFailParams(e); + } + + const failed = checkAuthToken(token); + if (failed) return failed; + + const currentUnion = SiteSettings.findOne({ name: 'subs-public-union' }); + const userSubsBounds = SiteSettings.findOne({ name: 'subs-public-union-bounds' }); + + return jsend.success({ union: currentUnion, bounds: userSubsBounds }); + } + }); + + apiV1.addRoute('mobile/falsepositive', { authRequired: false }, { + post: function post() { + const { + token, + mobileToken, + sealed, + type + } = this.bodyParams; + try { + check(token, String); + check(mobileToken, String); + check(sealed, String); + check(type, String); + } catch (e) { + if (debug) console.log(e); + return defaultFailParams(e); + } + + const failed = checkAuthToken(token); + if (failed) return failed; + + const user = Meteor.users.findOne({ fireBaseToken: mobileToken }); + if (!user) return failMsg('User not found'); + + console.log(`Marking hash fire as '${type}' false positive: ${sealed}`); + const fireC = fireFromHash(sealed, { id: sealed }); + if (fireC && typeof fireC === 'object') { + const fire = fireC.fetch()[0]; + console.log(`Marking fire as false positive: ${fire._id}`); + const result = upsertFalsePositive(type, user._id, fire); + return jsend.success({ upsert: result }); + } + return failMsg('Cannot mark fire as false positive'); + } + }); +} diff --git a/imports/api/SiteSettings/SiteSettings.js b/imports/api/SiteSettings/SiteSettings.js new file mode 100644 index 0000000..2bbd95f --- /dev/null +++ b/imports/api/SiteSettings/SiteSettings.js @@ -0,0 +1,50 @@ +/* eslint-disable consistent-return */ +/* eslint-disable import/no-absolute-path */ + +import { Mongo } from 'meteor/mongo'; +import SimpleSchema from 'simpl-schema'; +import { defaultCreatedAt, defaultUpdateAt } from '/imports/api/Utility/Utils.js'; +import SiteSettingsTypes from './SiteSettingsTypes'; + +const SiteSettings = new Mongo.Collection('siteSettings', { idGeneration: 'MONGO' }); + +SiteSettings.allow({ + insert: () => false, + update: () => false, + remove: () => false +}); + +SiteSettings.deny({ + insert: () => true, + update: () => true, + remove: () => true +}); + +SiteSettings.get = (name) => { + const setting = SiteSettings.findOne({ + name + }); + return typeof setting === 'object' ? setting.value : undefined; +}; + +SiteSettings.observe = (name, callback) => { + SiteSettings.find({ name }).observe({ + added: (document) => { + callback(document.value); + } + }); +}; + +SiteSettings.getSchema = type => new SimpleSchema({ + name: String, + type: String, + description: String, + value: SiteSettingsTypes[type].value, + isPublic: Boolean, + createdAt: defaultCreatedAt, + updatedAt: defaultUpdateAt +}); + +// SiteSettings.attachSchema(SiteSettings.schema); + +export default SiteSettings; diff --git a/imports/api/SiteSettings/SiteSettingsTypes.js b/imports/api/SiteSettings/SiteSettingsTypes.js new file mode 100644 index 0000000..bff3c00 --- /dev/null +++ b/imports/api/SiteSettings/SiteSettingsTypes.js @@ -0,0 +1,66 @@ +// Adapted from: https://github.com/yogiben/meteor-admin-settings + +const SiteSettingsTypes = { + string: { + value: { + type: String + } + }, + textarea: { + value: { + type: String + /* autoform: { + * afFieldInput: { + * rows: 5 + * } + * } */ + } + }, + number: { + value: { + type: Number + } + }, + boolean: { + value: { + type: Boolean + /* autoform: { + * afFieldInput: { + * type: 'boolean-select' + * } + * } */ + } + }, + date: { + value: { + type: Date + /* autoform: { + * afFieldInput: { + * type: 'date' + * } + * } */ + } + }, + color: { + value: { + type: String + /* autoform: { + * afFieldInput: { + * type: 'color' + * } + * } */ + } + }, + password: { + value: { + type: String + /* autoform: { + * afFieldInput: { + * type: 'password' + * } + * } */ + } + } +}; + +export default SiteSettingsTypes; diff --git a/imports/api/SiteSettings/methods.js b/imports/api/SiteSettings/methods.js new file mode 100644 index 0000000..5f9d73d --- /dev/null +++ b/imports/api/SiteSettings/methods.js @@ -0,0 +1,60 @@ +import { Meteor } from 'meteor/meteor'; +/* import { check } from 'meteor/check'; +import SiteSettings from './SiteSettings'; +import SiteSettingsTypes from './SiteSettingsTypes'; */ +import rateLimit from '../../modules/rate-limit'; + +Meteor.methods({ +/* 'siteSettings.insert': function siteSettingsInsert(setting) { + check(setting, { + name: String, + type: String, + description: String, + value: SiteSettingsTypes[self.type].value + }); + + SiteSettings.getSchema.validate(setting); + + try { + return SiteSettings.insert({ owner: this.userId, ...setting }); + } catch (exception) { + throw new Meteor.Error('500', exception); + } + }, + 'siteSettings.update': function siteSettingsUpdate(setting) { + check(setting, { + _id: String, + name: String, + type: String, + description: String, + value: SiteSettingsTypes[self.type].value + }); + + try { + const siteSettingId = setting._id; + SiteSettings.update(siteSettingId, { $set: setting }); + return siteSettingId; // Return _id so we can redirect to siteSetting after update. + } catch (exception) { + throw new Meteor.Error('500', exception); + } + }, + 'siteSettings.remove': function siteSettingsRemove(siteSettingId) { + check(siteSettingId, String); + + try { + return SiteSettings.remove(siteSettingId); + } catch (exception) { + throw new Meteor.Error('500', exception); + } + } */ +}); + +rateLimit({ + methods: [ + /* 'siteSettings.insert', + 'siteSettings.update', + 'siteSettings.remove' */ + ], + limit: 5, + timeRange: 1000 +}); diff --git a/imports/api/SiteSettings/server/publications.js b/imports/api/SiteSettings/server/publications.js new file mode 100644 index 0000000..ab9f1b2 --- /dev/null +++ b/imports/api/SiteSettings/server/publications.js @@ -0,0 +1,6 @@ +/* eslint-disable prefer-arrow-callback */ + +import { Meteor } from 'meteor/meteor'; +import SiteSettings from '../SiteSettings'; + +Meteor.publish('settings', () => SiteSettings.find({ isPublic: true })); diff --git a/imports/api/Subscriptions/Subscriptions.js b/imports/api/Subscriptions/Subscriptions.js new file mode 100644 index 0000000..c69e20b --- /dev/null +++ b/imports/api/Subscriptions/Subscriptions.js @@ -0,0 +1,62 @@ +/* eslint-disable consistent-return */ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import { Mongo } from 'meteor/mongo'; +import SimpleSchema from 'simpl-schema'; +import { defaultCreatedAt, defaultUpdateAt } from '/imports/api/Utility/Utils.js'; +import LocationSchema from '/imports/api/Utility/LocationSchema.js'; + +const Subscriptions = new Mongo.Collection('subscriptions', { idGeneration: 'MONGO' }); + +Subscriptions.allow({ + insert: () => false, + update: () => false, + remove: () => false +}); + +Subscriptions.deny({ + insert: () => true, + update: () => true, + remove: () => true +}); + + +/* Sample: + * { + * "_id" : ObjectId("5a0bfb5a79095a1adba47513"), + * "chatId" : -253600015, + * "location" : { + * "lat" : 40.234503, + * "lon" : -3.350386 + * }, + * "geo" : { + * "type" : "Point", + * "coordinates" : [ + * -3.350386, + * 40.234503 + * ] + * }, + * "distance" : 40 + * } + * */ + + +Subscriptions.schema = new SimpleSchema({ + _id: { type: Meteor.Collection.ObjectID, optional: true, blackbox: true }, + location: Object, + 'location.lat': Number, + 'location.lon': Number, + geo: LocationSchema, + distance: Number, + chatId: { type: Number, optional: true }, // only in 'telegram' type + telegramBot: { type: String, optional: true }, // only in 'telegram' type + owner: String, + type: String, + createdAt: defaultCreatedAt, + updatedAt: defaultUpdateAt +}); + +Subscriptions.attachSchema(Subscriptions.schema); + +export default Subscriptions; diff --git a/imports/api/Subscriptions/methods.js b/imports/api/Subscriptions/methods.js new file mode 100644 index 0000000..cf927e0 --- /dev/null +++ b/imports/api/Subscriptions/methods.js @@ -0,0 +1,88 @@ +import { Meteor } from 'meteor/meteor'; +import { check, Match } from 'meteor/check'; +import Subscriptions from './Subscriptions'; +import rateLimit from '../../modules/rate-limit'; + +function geo(doc) { + return { + type: 'Point', + coordinates: [doc.location.lon, doc.location.lat] + }; +} + +export function subscriptionsInsert(doc, userId, type) { + check(doc, { + _id: Match.Maybe(Meteor.Collection.ObjectID), + location: Match.ObjectIncluding({ lat: Number, lon: Number }), + distance: Number + }); + const newDoc = { + owner: userId, + type, + geo: geo(doc), + ...doc + }; + // console.log(newDoc); + const already = Subscriptions.findOne(newDoc); + if (already) { + throw new Meteor.Error('on-already-subscribed', 'The user is already subscribed to this area'); + } + try { + return Subscriptions.insert(newDoc); + } catch (exception) { + // console.error(exception); + throw new Meteor.Error('500', exception); + } +} + +export function subscriptionsRemove(subscriptionId) { + check(subscriptionId, Meteor.Collection.ObjectID); + + try { + return Subscriptions.remove(subscriptionId); + } catch (exception) { + console.error(exception); + throw new Meteor.Error('500', exception); + } +} + +Meteor.methods({ + 'subscriptions.insert': function subscriptionInsertMethod(doc) { + check(doc, { + location: Match.ObjectIncluding({ lat: Number, lon: Number }), + distance: Number + }); + return subscriptionsInsert(doc, this.userId, 'web'); + }, + 'subscriptions.update': function subscriptionsUpdate(doc) { + check(doc, { + _id: Meteor.Collection.ObjectID, + location: Match.ObjectIncluding({ lat: Number, lon: Number }), + distance: Number + }); + + try { + const dup = doc; + const subscriptionId = doc._id; + dup.geo = geo(doc); + Subscriptions.update(subscriptionId, { $set: dup }); + return subscriptionId; // Return _id so we can redirect to subscription after update. + } catch (exception) { + throw new Meteor.Error('500', exception); + } + }, + 'subscriptions.remove': function subscriptionsRemoveMethod(subscriptionId) { + check(subscriptionId, Meteor.Collection.ObjectID); + return subscriptionsRemove(subscriptionId); + } +}); + +rateLimit({ + methods: [ + 'subscriptions.insert', + 'subscriptions.update', + 'subscriptions.remove' + ], + limit: 5, + timeRange: 1000 +}); diff --git a/imports/api/Subscriptions/server/publications.js b/imports/api/Subscriptions/server/publications.js new file mode 100644 index 0000000..adf6e13 --- /dev/null +++ b/imports/api/Subscriptions/server/publications.js @@ -0,0 +1,18 @@ +/* eslint-disable prefer-arrow-callback */ + +import { Meteor } from 'meteor/meteor'; +import { Mongo } from 'meteor/mongo'; +import { check } from 'meteor/check'; +import Subscriptions from '../Subscriptions'; + +Meteor.publish('mysubscriptions', function subscriptions() { + return Subscriptions.find({ owner: this.userId }); // type: 'web' +}); + +// Note: subscriptions.view is also used when editing an existing subscription. +Meteor.publish('subscriptions.view', function subscriptionsView(subscriptionId) { + check(subscriptionId, String); + const id = new Mongo.ObjectID(subscriptionId); + check(id, Meteor.Collection.ObjectID); + return Subscriptions.find({ _id: id, owner: this.userId, type: 'web' }); +}); diff --git a/imports/api/Users/Users.js b/imports/api/Users/Users.js new file mode 100644 index 0000000..8911a47 --- /dev/null +++ b/imports/api/Users/Users.js @@ -0,0 +1,115 @@ +/* eslint-disable consistent-return */ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import SimpleSchema from 'simpl-schema'; +import { defaultCreatedAt, defaultUpdateAt } from '/imports/api/Utility/Utils.js'; + +const schemaUserProfile = new SimpleSchema({ + /* Our users has a name of type Object while Google Service, for instance, String, so blackbox in true in profile */ + /* name: { type: String, optional: true }, */ + name: { type: Object, optional: true }, + 'name.first': String, + 'name.last': String +}); + +const schemaUser = new SimpleSchema({ + username: { + type: String, + // i18nLabel: 'Usuario/a', + regEx: /^[a-z0-9A-Z_]{3,15}$/, + // For accounts-password, either emails or username is required, + // but not both. + // It is OK to make this optional here because the accounts-password + // package + // does its own validation. + // Third-party login packages may not require either. + // Adjust this schema as necessary for your usage. + optional: true + }, + emails: { + type: Array, + min: 1, + // label() { return i18n.t('Lista de emails de contacto'); }, + // For accounts-password, either emails or username is required, + // but not both. + // It is OK to make this optional here because the accounts-password + // package + // does its own validation. + // Third-party login packages may not require either. + // Adjust this schema as necessary for your usage. + optional: true + }, + 'emails.$': { + label: false, + type: Object + }, + 'emails.$.address': { + type: String, + label: '', + regEx: SimpleSchema.RegEx.Email + }, + 'emails.$.verified': { + type: Boolean, + optional: true // if not present === notVerified + }, + // Make sure this services field is in your schema + // if you're using any of the accounts packages + services: { + type: Object, + optional: true, + // autoform: { type: 'hidden' }, + blackbox: true + }, + // Add `roles` to your schema if you use the meteor-roles package. + // Option 1: Object type + // If you specify that type as Object, you must also specify the + // `Roles.GLOBAL_GROUP` group whenever you add a user to a role. + // Example: + // Roles.addUsersToRoles(userId, ['admin'], Roles.GLOBAL_GROUP); + // You can't mix and match adding with and without a group since + // you will fail validation in some cases. + // roles: { + // type: Object, + // optional: true, + // autoform: { type: 'hidden' }, + // blackbox: true + // } + // Option 2: [String] type + // If you are sure you will never need to use role groups, then + // you can specify [String] as the type + roles: { type: Array, optional: true }, + 'roles.$': { type: String, optional: true }, + // https://github.com/todda00/meteor-friendly-slugs/issues/1 + friendlySlugs: { + type: Object, + optional: true, + blackbox: true + }, + slug: { + type: String, + optional: true + }, + profile: { + type: schemaUserProfile, + optional: true, + blackbox: true + }, + // https://guide.meteor.com/accounts.html#custom-user-data + + /* Our users has a name of type Object while Google Service, for instance, not */ + /* name: { type: String, optional: true }, */ + /* name: Object, + 'name.first': String, + 'name.last': String, */ + lang: { type: String, optional: true }, + telegramChatId: { type: SimpleSchema.Integer, optional: true }, + telegramUsername: { type: String, optional: true }, + telegramFirstName: { type: String, optional: true }, + telegramLanguageCode: { type: String, optional: true }, + fireBaseToken: { type: String, optional: true }, + createdAt: defaultCreatedAt, + updatedAt: defaultUpdateAt +}); + +Meteor.users.attachSchema(schemaUser); diff --git a/imports/api/Users/server/methods.js b/imports/api/Users/server/methods.js index d97c515..dc3c232 100644 --- a/imports/api/Users/server/methods.js +++ b/imports/api/Users/server/methods.js @@ -1,11 +1,19 @@ +/* eslint-disable import/no-absolute-path */ import { Meteor } from 'meteor/meteor'; -import { check } from 'meteor/check'; +import { check, Match } from 'meteor/check'; import { Accounts } from 'meteor/accounts-base'; +import urlEnc from '/imports/modules/url-encode'; import editProfile from './edit-profile'; import rateLimit from '../../../modules/rate-limit'; +const validLangCode = Match.Where((lang) => { + check(lang, String); + const regexp = /^[a-z]{2,3}(?:-[A-Z]{2,3}(?:-[a-zA-Z]{4})?)?$/; + return regexp.test(lang); +}); + Meteor.methods({ - 'users.sendVerificationEmail': function usersResendVerification() { + 'users.sendVerificationEmail': function usersSendVerificationEmail() { return Accounts.sendVerificationEmail(this.userId); }, 'users.editProfile': function usersEditProfile(profile) { @@ -14,24 +22,35 @@ Meteor.methods({ profile: { name: { first: String, - last: String, - }, - }, + last: String + } + } }); return editProfile({ userId: this.userId, profile }) - .then(response => response) - .catch((exception) => { - throw new Meteor.Error('500', exception); - }); + .then(response => response) + .catch((exception) => { + throw new Meteor.Error('500', exception); + }); }, + 'users.setLang': function userLang(lang) { + check(lang, validLangCode); + Meteor.users.update({ _id: this.userId }, { $set: { lang } }); + }, + 'auth.getHash': async function getHash() { + const token = Accounts._generateStampedLoginToken(); + const obj = Accounts._hashStampedToken(token); + // console.log(obj); + const sealed = await urlEnc.encrypt(obj); + return sealed; + } }); rateLimit({ methods: [ - 'users.resendVerification', - 'users.editProfile', + 'users.sendVerificationEmail', + 'users.editProfile' ], limit: 5, - timeRange: 1000, + timeRange: 1000 }); diff --git a/imports/api/Users/server/publications.js b/imports/api/Users/server/publications.js index 7728b4b..08787d6 100644 --- a/imports/api/Users/server/publications.js +++ b/imports/api/Users/server/publications.js @@ -1,4 +1,7 @@ +/* eslint-disable prefer-arrow-callback */ + import { Meteor } from 'meteor/meteor'; +import '../Users'; Meteor.publish('users.editProfile', function usersProfile() { return Meteor.users.find(this.userId, { @@ -6,6 +9,16 @@ Meteor.publish('users.editProfile', function usersProfile() { emails: 1, profile: 1, services: 1, - }, + lang: 1 + } }); }); + +Meteor.publish('userData', function userData() { + if (this.userId) { + return Meteor.users.find({ _id: this.userId }, { + fields: { lang: 1 } + }); + } + this.ready(); +}); diff --git a/imports/api/Users/server/send-welcome-email.js b/imports/api/Users/server/send-welcome-email.js new file mode 100644 index 0000000..f93c7d2 --- /dev/null +++ b/imports/api/Users/server/send-welcome-email.js @@ -0,0 +1,30 @@ +import { Meteor } from 'meteor/meteor'; +import i18n from 'i18next'; +import sendEmail from '../../../modules/server/send-email'; +import getOAuthProfile from '../../../modules/get-oauth-profile'; + +export default (options, user, lang) => { + const OAuthProfile = getOAuthProfile(options, user); + + i18n.changeLanguage(lang); + const applicationName = i18n.t('AppName'); + const firstName = OAuthProfile ? OAuthProfile.name.first : options.profile.name.first; + const emailAddress = OAuthProfile ? OAuthProfile.email : options.email; + const welcome = i18n.t('welcome'); + if (emailAddress) { + sendEmail({ + to: emailAddress, + from: `${applicationName} `, + subject: `[${applicationName}] ${welcome} ${firstName}!`, + lang, + template: 'welcome', + templateVars: { + applicationName, + firstName, + welcomeUrl: Meteor.absoluteUrl('subscriptions') // e.g., returns http://localhost:3000/documents + } + }).catch((error) => { + throw new Meteor.Error('500', `${error}`); + }); + } +}; diff --git a/imports/api/Utility/LocationSchema.js b/imports/api/Utility/LocationSchema.js new file mode 100644 index 0000000..6aaf812 --- /dev/null +++ b/imports/api/Utility/LocationSchema.js @@ -0,0 +1,34 @@ +import SimpleSchema from 'simpl-schema'; + +// https://stackoverflow.com/questions/24492333/meteor-simple-schema-for-mongo-geo-location-data +// https://github.com/aldeed/meteor-simple-schema/issues/606 +const LocationSchema = new SimpleSchema({ + type: { + type: String, + allowedValues: ['Point'] + }, + coordinates: { + type: Array, + minCount: 2, + maxCount: 2, + custom: function custom() { + if (!(this.value[0] >= -180 && this.value[0] <= 180)) { + return 'lngOutOfRange'; + } + if (!(this.value[1] >= -90 && this.value[1] <= 90)) { + return 'latOutOfRange'; + } + return true; + } + }, + 'coordinates.$': { + type: Number + } +}); + +LocationSchema.messageBox.messages({ + latOutOfRange: '[label] latitude should be between -90 and 90', + lngOutOfRange: '[label] longitude should be between -180 and 180' +}); + +export default LocationSchema; diff --git a/imports/api/Utility/Utils.js b/imports/api/Utility/Utils.js new file mode 100644 index 0000000..4384ff3 --- /dev/null +++ b/imports/api/Utility/Utils.js @@ -0,0 +1,29 @@ +/* eslint-disable consistent-return */ +/* eslint-disable prefer-arrow-callback */ + +export const defaultCreatedAt = { + type: Date, + // autoform: { type: 'hidden' }, + // Prefer normal function: https://github.com/aldeed/meteor-simple-schema/issues/562 + autoValue: function autovalue() { + if (this.isInsert) { + return new Date(); + } + // Prevent user from supplying their own value + this.unset(); + }, + optional: true // TODO: Use migration for users +}; + +export const defaultUpdateAt = { + type: Date, + // autoform: { type: 'hidden' }, + autoValue: function autovalue() { + if (this.isUpdate || this.isInsert) { + return new Date(); + } + }, + // Commented because we want to have updateAt = createAt initialy + // denyInsert: true, + optional: true +}; diff --git a/imports/api/Utility/server/files.js b/imports/api/Utility/server/files.js new file mode 100644 index 0000000..6f02058 --- /dev/null +++ b/imports/api/Utility/server/files.js @@ -0,0 +1,21 @@ +/* eslint-disable import/no-absolute-path */ + +import fs from 'fs'; +import getFallbackLang from '/imports/modules/lang-fallback'; + +const as = f => `assets/app/${f}`; + +export const getFileNameOfLang = (dir, fileName, ext, lang) => { + const base = `${dir}/${fileName}`; + const fallback = getFallbackLang(lang); + let file = `${base}-${lang}.${ext}`; + if (!fs.existsSync(as(file))) { + // console.log(`Page '${fileName}' not found for '${lang}' lang`); + file = `${base}-${fallback}.${ext}`; + if (!fs.existsSync(as(file))) { + // console.log(`Page '${fileName}' not found for '${fallback}' lang`); + file = `${base}.${ext}`; + } + } + return file; +}; diff --git a/imports/api/Utility/server/methods.js b/imports/api/Utility/server/methods.js index 498caae..aaaf041 100644 --- a/imports/api/Utility/server/methods.js +++ b/imports/api/Utility/server/methods.js @@ -1,11 +1,21 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import i18n from 'i18next'; +import { getFileNameOfLang } from '/imports/api/Utility/server/files.js'; import getPrivateFile from '../../../modules/server/get-private-file'; import parseMarkdown from '../../../modules/parse-markdown'; Meteor.methods({ - 'utility.getPage': function utilityGetPage(fileName) { + 'utility.getPage': function utilityGetPage(fileName, lang) { check(fileName, String); - return parseMarkdown(getPrivateFile(`pages/${fileName}.md`)); + check(lang, String); + return parseMarkdown(getPrivateFile(getFileNameOfLang('pages', fileName, 'md', lang))); }, + 'utility.saveMissingI18n': function saveMissing(key, value) { + check(key, String); + check(value, String); + if (!Meteor.isProduction) { + i18n.t(key, value); + } + } }); diff --git a/imports/modules/get-email-of-user.js b/imports/modules/get-email-of-user.js new file mode 100644 index 0000000..c69262d --- /dev/null +++ b/imports/modules/get-email-of-user.js @@ -0,0 +1,19 @@ +/* eslint-disable import/no-absolute-path */ + +import getOAuthProfile from '/imports/modules/get-oauth-profile'; + +const getEmailOf = (user) => { + const hasPassword = user.services && user.services.password && user.services.password.bcrypt; + + // console.log(`Has password: ${hasPassword}`); + const OAuthProfile = getOAuthProfile({ + password: hasPassword, + profile: user.profile + }, user); + const firstName = OAuthProfile ? OAuthProfile.name.first : user.profile.name.first; + const emailAddress = OAuthProfile ? OAuthProfile.email : + user && user.emails[0] && user.emails[0].verified ? user.emails[0].address : null; + return { emailAddress, firstName }; +}; + +export default getEmailOf; diff --git a/imports/modules/get-oauth-profile.js b/imports/modules/get-oauth-profile.js new file mode 100644 index 0000000..8e427a1 --- /dev/null +++ b/imports/modules/get-oauth-profile.js @@ -0,0 +1,39 @@ +const parseGoogleData = service => ({ + email: service.email, + name: { + first: service.given_name, + last: service.family_name + }, + lang: service.locale +}); + +const parseGithubData = (profile, service) => { + const name = profile.name.split(' '); + return { + email: service.email, + name: { + first: name[0], + last: name[1] + } + }; +}; + +const parseFacebookData = service => ({ + email: service.email, + name: { + first: service.first_name, + last: service.last_name + } +}); + +const getDataForService = (profile, services) => { + if (services.facebook) return parseFacebookData(services.facebook); + if (services.github) return parseGithubData(profile, services.github); + if (services.google) return parseGoogleData(services.google); +}; + +export default (options, user) => { + const isOAuth = !options.password; + const serviceData = isOAuth ? getDataForService(options.profile, user.services) : null; + return isOAuth ? serviceData : null; +}; diff --git a/imports/modules/lang-fallback.js b/imports/modules/lang-fallback.js new file mode 100644 index 0000000..d912347 --- /dev/null +++ b/imports/modules/lang-fallback.js @@ -0,0 +1,9 @@ +const getFallbackLang = (lang) => { + if (lang && (lang === 'ast' || lang === 'gl' || lang === 'eu' || + lang === 'es' || lang === 'ca' || lang.match(/^es-/))) { + return 'es'; + } + return 'en'; +}; + +export default getFallbackLang; diff --git a/imports/modules/server/handlebars-email-to-html.js b/imports/modules/server/handlebars-email-to-html.js new file mode 100644 index 0000000..4d7e809 --- /dev/null +++ b/imports/modules/server/handlebars-email-to-html.js @@ -0,0 +1,11 @@ +import handlebars from 'handlebars'; +import juice from 'juice'; + +export default (handlebarsMarkup, context, options) => { + if (handlebarsMarkup && context) { + const template = handlebars.compile(handlebarsMarkup); + return options && !options.inlineCss ? template(context) : juice(template(context)); // Use juice to inline CSS styles from unless disabled. + } + + throw new Error('Please pass Handlebars markup to compile and a context object with data mapping to the Handlebars expressions used in your template.'); +}; diff --git a/imports/modules/server/handlebars-email-to-text.js b/imports/modules/server/handlebars-email-to-text.js new file mode 100644 index 0000000..c348901 --- /dev/null +++ b/imports/modules/server/handlebars-email-to-text.js @@ -0,0 +1,10 @@ +import handlebars from 'handlebars'; + +export default (handlebarsMarkup, context) => { + if (handlebarsMarkup && context) { + const template = handlebars.compile(handlebarsMarkup); + return template(context); + } + + throw new Error('Please pass Handlebars markup to compile and a context object with data mapping to the Handlebars expressions used in your template.'); +}; diff --git a/imports/modules/server/notificationsProcess.js b/imports/modules/server/notificationsProcess.js new file mode 100644 index 0000000..657aa2a --- /dev/null +++ b/imports/modules/server/notificationsProcess.js @@ -0,0 +1,153 @@ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import Notifications from '/imports/api/Notifications/Notifications'; +import i18n from 'i18next'; +import moment from 'moment'; +import { dateLongFormat } from '/imports/api/Common/dates'; +// import sendMail from '/imports/startup/server/email'; +import sendEmail, { subjectTruncate } from '/imports/modules/server/send-email'; +import { isMailServerMaster } from '/imports/startup/server/email'; +// import { hr } from '/imports/startup/server/email'; +import getEmailOf from '/imports/modules/get-email-of-user'; +import image from 'google-maps-image-api-url'; +import gcm from 'node-gcm'; +import { trim } from '/imports/ui/components/NotificationsObserver/util.js'; +import ravenLogger from '/imports/startup/server/ravenLogger'; + +let validFcmSender = true; + +if (!(Meteor.settings.private.fcmApiToken && Meteor.settings.private.fcmApiToken.length > 0)) { + console.warn('Missing settings.private.fcmApiToken key, mobile notifications will not work'); + validFcmSender = false; +} + +// 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://developers.google.com/maps/documentation/static-maps/intro +function imgUrl(lat, lng) { + return image({ + key: Meteor.settings.gmaps.key, + type: 'staticmap', + center: `${lat},${lng}`, + size: '640x480', + zoom: 16, + maptype: 'hybrid', + language: 'es', + markers: `icon: ${Meteor.settings.private.fireIconUrl}|${lat},${lng}` + }); +} + +/* + function imgEl(lat, lng) { + return ``; + } */ + +// Cutover flag (fase 1a): channels listed in +// Meteor.settings.private.notifDisabledChannels (e.g. ['mobile','web']) are +// handled by the tcef-notifications microservice, so the old observer/cron must +// NOT send them. Mutual exclusion per channel — reversible by editing settings, +// no code deploy needed. ES5-compatible on purpose (Meteor 1.6 / Node 8). +const notifDisabledChannels = (Meteor.settings.private && Meteor.settings.private.notifDisabledChannels) || []; + +const processNotif = (notif) => { + if (notifDisabledChannels.indexOf(notif.type) !== -1) { + // This channel was migrated to tcef-notifications; do nothing here. + return; + } + if (isMailServerMaster && validFcmSender && notif.type === 'mobile' && notif.notified !== true) { + const fcmSender = new gcm.Sender(Meteor.settings.private.fcmApiToken); + const user = Meteor.users.findOne({ _id: notif.userId }); + moment.locale(user.lang); + // duplicate code below + const body = `${trim(notif.content)}`; + + // 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._str); + 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 + if (validFcmSender) { + fcmSender.send(msg, { registrationTokens }, Meteor.bindEnvironment(function processResult(err, response) { + if (err) { + console.error(`FCM error: ${err}`); + // FIXME send to sentry + ravenLogger.log(err); + } else { + // console.log(`FCM response: ${response}`); + Notifications.update(notif._id, { $set: { notified: true, notifiedAt: new Date() } }); + } + })); + } + } + } + if (isMailServerMaster && notif.type === 'web' && notif.emailNotified !== true) { + const user = Meteor.users.findOne({ _id: notif.userId }); + const { firstName, emailAddress } = getEmailOf(user); + + if (emailAddress) { + const img = imgUrl(notif.geo.coordinates[1], notif.geo.coordinates[0]); + // const url = imgUrl(notif.geo.coordinates[1], notif.geo.coordinates[0]); + const fireUrl = `${Meteor.absoluteUrl('fire/')}${notif.sealed}`; + // const fireHtmlUrl = `${i18n.t('Más información sobre este fuego')}`; + // TODO get _id of fire + // const fireTextUrl = `${i18n.t('Más información sobre este fuego')}:\n${fireUrl}`; + // FIXME use our map as url and static map as img + moment.locale(user.lang); + // moment user tz ? + const message = `${trim(notif.content)} (${i18n.t('fireDetectedAt', { when: dateLongFormat(notif.when) })}).`; + + // TODO Comunes Address + + const emailOpts = { + to: emailAddress, + // userName: firstName, + // sendAt: new Date(), + subject: subjectTruncate.apply(message), + // text: `${message}\n\n${fireTextUrl}\n\n`, + // template: '

{{appName}}

{{{html}}}', + lang: user.lang, + template: 'new-fire', + templateVars: { + applicationName: i18n.t('AppName'), + firstName, + message, + fireUrl, + img, + subsUrl: Meteor.absoluteUrl('subscriptions') + } + }; + sendEmail(emailOpts).catch((error) => { + throw new Meteor.Error('500', `${error}`); + }); + // sendMail(emailOpts, true); + Notifications.update(notif._id, { $set: { emailNotified: true, emailNotifiedAt: new Date() } }); + } else { + // Not email or not verified -> remove notif so we don't retry to send it + Notifications.remove({ _id: notif._id }); + } + } +}; + +export default processNotif; diff --git a/imports/modules/server/other-checks.js b/imports/modules/server/other-checks.js new file mode 100644 index 0000000..85dcbbe --- /dev/null +++ b/imports/modules/server/other-checks.js @@ -0,0 +1,25 @@ +import { check, Match } from 'meteor/check'; + +export const validZoom = Match.Where((zoom) => { + // http://wiki.openstreetmap.org/wiki/Zoom_levels + check(zoom, Number); + return zoom >= 0 && zoom <= 19; +}); + +// https://github.com/3stack-software/meteor-match-library +export function NumberBetween(min, max) { + return Match.Where((x) => { + check(x, Number); + return min <= x && x <= max; + }); +} + +export function NullOr(type) { + return Match.Where((x) => { + if (x === null) { + return true; + } + check(x, type); + return true; + }); +} diff --git a/imports/modules/server/send-email.js b/imports/modules/server/send-email.js new file mode 100644 index 0000000..8fc4629 --- /dev/null +++ b/imports/modules/server/send-email.js @@ -0,0 +1,56 @@ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import i18n from 'i18next'; +import { getFileNameOfLang } from '/imports/api/Utility/server/files.js'; +import sendMail from '/imports/startup/server/email'; +import getPrivateFile from './get-private-file'; +import templateToText from './handlebars-email-to-text'; +import templateToHTML from './handlebars-email-to-html'; + +export function subjectTruncate(n = 70, useWordBoundary = true) { + // https://stackoverflow.com/questions/1199352/smart-way-to-shorten-long-strings-with-javascript + if (this.length <= n) { + return `${this}`; + } + const subString = this.substr(0, n - 1); + return `${useWordBoundary ? subString.substr(0, subString.lastIndexOf(' ')) : subString}...`; +} + +const sendEmail = (options, { resolve, reject }) => { + try { + Meteor.defer(() => { + // console.log(`Current user lang ${options.lang}`); + i18n.changeLanguage(options.lang); + // Meteor email options: + // basic: from, to/cc/bcc/replyTo, subject, html, text, + // others: watchHtml, icalEvent, headers, attachments, mailComposer, inReplyTo, references, messageId + const opts = options; + // opts.template = '

{{appName}}

{{{html}}}'; + opts.template = '{{{html}}}'; + opts.appName = i18n.t('AppName'); + // console.log(`Email options: ${JSON.stringify(opts)}`); + sendMail(opts, true); + // Email.send(options); + resolve(); + }); + } catch (exception) { + reject(exception); + } +}; + +export default ({ + text, html, lang, template, templateVars, ...rest +}) => { + if (text || html || template) { + return new Promise((resolve, reject) => { + sendEmail({ + lang, + ...rest, + text: template ? templateToText(getPrivateFile(getFileNameOfLang('email-templates', template, 'txt', lang)), (templateVars || {})) : text, + html: template ? templateToHTML(getPrivateFile(getFileNameOfLang('email-templates', template, 'html', lang)), (templateVars || {})) : html + }, { resolve, reject }); + }); + } + throw new Error('Please pass an HTML string, text, or template name to compile for your message\'s body.'); +}; diff --git a/imports/modules/server/twitter.js b/imports/modules/server/twitter.js new file mode 100644 index 0000000..bff6c15 --- /dev/null +++ b/imports/modules/server/twitter.js @@ -0,0 +1,27 @@ +import { Meteor } from 'meteor/meteor'; +import Twit from 'twit'; + +// https://www.npmjs.com/package/twit +const confTwitter = (lang) => { + const tConf = Meteor.settings.private.twitter[lang]; + + const T = new Twit({ + consumer_key: tConf.consumer_key, + consumer_secret: tConf.consumer_secret, + access_token: tConf.access_token, + access_token_secret: tConf.access_token_secret + // timeout_ms: 60*1000, // optional HTTP request timeout to apply to all requests. + }); + + return T; +}; + +const tweet = (message, lang) => { + const T = confTwitter(lang); + T.post('statuses/update', { status: message }, (err, data, response) => { + // console.log(data); + // console.log(response); + }); +}; + +export default tweet; diff --git a/imports/modules/url-encode.js b/imports/modules/url-encode.js new file mode 100644 index 0000000..291514a --- /dev/null +++ b/imports/modules/url-encode.js @@ -0,0 +1,6 @@ +import { Meteor } from 'meteor/meteor'; +import Iron from 'iron'; + +exports.encrypt = obj => Iron.seal(obj, Meteor.settings.private.ironPassword, Iron.defaults); + +exports.decrypt = obj => Iron.unseal(obj, Meteor.settings.private.ironPassword, Iron.defaults); diff --git a/imports/startup/client/Gkeys.js b/imports/startup/client/Gkeys.js new file mode 100644 index 0000000..0a1f83e --- /dev/null +++ b/imports/startup/client/Gkeys.js @@ -0,0 +1,50 @@ +import { Meteor } from 'meteor/meteor'; +import { ReactiveVar } from 'meteor/reactive-var'; +import { Tracker } from 'meteor/tracker'; +import GoogleMapsLoader from 'google-maps'; + +class GkeysC { + constructor() { + this.gmapkey = new ReactiveVar(null); + const self = this; + this.callbacks = []; + Meteor.startup(() => { + Meteor.call('getMapKey', (error, key) => { + // console.log(google.maps); + GoogleMapsLoader.KEY = key; + GoogleMapsLoader.LIBRARIES = ['places']; + GoogleMapsLoader.load(() => { + self.gmapkey.set(key); + console.log('GMaps script just loaded'); + self.doCallbacks(key); + }); + }); + }); + } + + doCallbacks(key) { + for (let i = 0; i < this.callbacks.length; i += 1) { + this.callbacks[i](null, key); + } + this.callbacks = []; + } + + load(callback) { + this.callbacks.push(callback); + Tracker.autorun((computation) => { + const key = this.gmapkey.get(); + if (key) { + // already loaded + // console.log('GMaps already loaded'); + this.doCallbacks(key); + computation.stop(); + } else { + console.log('Waiting for the gkey'); + } + }); + } +} + +const Gkeys = new GkeysC(); + +export default Gkeys; diff --git a/imports/startup/client/comments.js b/imports/startup/client/comments.js new file mode 100644 index 0000000..94cbe90 --- /dev/null +++ b/imports/startup/client/comments.js @@ -0,0 +1,42 @@ +/* global Comments */ +/* eslint-disable import/no-absolute-path */ + +import i18n from '/imports/startup/client/i18n'; +import '/imports/startup/common/comments'; + +import './comments.scss'; + +i18n.init((err, t) => { + Comments.ui.setContent({ + title: ' ', // i18n.t('Comentarios'), + save: t('Guardar'), + reply: t('Responder'), + edit: t('Editar'), + remove: t('Borrar'), + 'placeholder-textarea': t('Añadir un comentario'), + 'add-button-reply': t('Añadir una respuesta'), + 'add-button': t('Añadir comentario'), + 'you-need-to-login': t('Necesitas iniciar sesión para'), + 'add comments': t('añadir comentarios'), + 'like comments': t('puntuar comentarios'), + 'rate comments': t('puntuar comentarios'), + 'add replies': t('responder'), + 'load-more': t('Más comentarios') + }); + + /* This in client side */ + Comments.ui.config({ + limit: 20, // default 10 + loadMoreCount: 20, // default 20 + /* generateAvatar: function genAvatar(user, isAnonymous) { + if (isAnonymous) { + return i18n.t('Anónimo'); + } + return user.profile && user.profile.name && user.profile.name.first ? user.profile.name.first : null; + }, */ + template: 'bootstrap', // default 'semantic-ui' + // default 'http://s3.amazonaws.com/37assets/svn/765-default-avatar.png' + defaultAvatar: '/default-avatar.png', + markdown: true + }); +}); diff --git a/imports/startup/client/comments.scss b/imports/startup/client/comments.scss new file mode 100644 index 0000000..de93e65 --- /dev/null +++ b/imports/startup/client/comments.scss @@ -0,0 +1,29 @@ +.comments-section { + width: 100%; +} + +.comments-box { + max-width: inherit; + padding: 0; +} + +p.comment-content { + /* white-space: pre-line; */ +} + +/* remove comment btn danger style */ + +div.media-body.comment> div> div> div.btn.btn-danger.remove-action { + background-color: white; + border: 1px solid rgb(204, 204, 204); + color: rgb(51, 51, 51); +} + +/* text-area height */ +.form-control .create-comment { + height: 9em; +} + +.img-avatar { + margin-right: 5px; +} \ No newline at end of file diff --git a/imports/startup/client/geolocation.js b/imports/startup/client/geolocation.js new file mode 100644 index 0000000..a43d784 --- /dev/null +++ b/imports/startup/client/geolocation.js @@ -0,0 +1,20 @@ +import { Meteor } from 'meteor/meteor'; +import { ReactiveVar } from 'meteor/reactive-var'; + +const geolocation = new ReactiveVar(); + +Meteor.startup(() => { + Meteor.call('geo', (error, response) => { + if (error) { + console.warn(error); + } else { + const pos = [ + response.location.latitude, + response.location.longitude + ]; + geolocation.set(pos); + } + }); +}); + +export default geolocation; diff --git a/imports/startup/client/i18n.js b/imports/startup/client/i18n.js new file mode 100644 index 0000000..384053f --- /dev/null +++ b/imports/startup/client/i18n.js @@ -0,0 +1,137 @@ +/* global CookieConsent Intl */ +import i18n from 'i18next'; +import { Meteor } from 'meteor/meteor'; +import { Tracker } from 'meteor/tracker'; +import { ReactiveVar } from 'meteor/reactive-var'; +import backend from 'i18next-xhr-backend'; +import LngDetector from 'i18next-browser-languagedetector'; +import Cache from 'i18next-localstorage-cache'; +import { T9n } from 'meteor-accounts-t9n'; +import moment from 'moment'; +import 'moment/locale/es'; +import 'moment/locale/pt'; +import 'moment/locale/gl'; +import i18nOpts from '../common/i18n'; + +// Adapted from: https://github.com/appigram/ryfma-boilerplate/blob/44c1eabfb9928b5623afab36a23997969e5beb02/imports/startup/client/i18n.js + +const detectorOptions = { + // order and from where user language should be detected + order: ['querystring', 'navigator', 'cookie', 'localStorage', 'htmlTag'], + + // keys or params to lookup language from + lookupQuerystring: 'lng', + lookupCookie: 'i18next', + lookupLocalStorage: 'i18nextLng', + + // cache user language on + caches: ['localStorage', 'cookie'], + excludeCacheFor: ['cimode'] // languages to not persist (cookie, localStorage) +}; + +export const i18nReady = new ReactiveVar(false); + +const cacheOptions = { + // turn on or off + enabled: false, + // prefix for stored languages + prefix: 'i18next_res_', + // expiration + expirationTime: 7 * 24 * 60 * 60 * 1000, + // language versions + versions: {} +}; + +i18nOpts.cache = cacheOptions; +i18nOpts.detection = detectorOptions; +i18nOpts.react = { + wait: true, + defaultTransParent: 'span' + // https://react.i18next.com/components/i18next-instance.ht + /* bindI18n: 'languageChanged loaded', + bindStore: 'added removed', + nsMode: 'default' */ +}; + +const sendMissing = true; // Meteor.isDevelopment; +if (sendMissing && Meteor.isDevelopment) { + i18nOpts.sendMissing = true; + i18nOpts.missingKeyHandler = function miss(lng, ns, key, defaultValue) { + Meteor.call('utility.saveMissingI18n', key, defaultValue); + }; +} + +function setT9(lang) { + if (lang === 'gl') { + T9n.setLanguage('es'); + } else { + T9n.setLanguage(lang); + } +} + +i18n.use(backend) + .use(LngDetector) + .use(Cache) + .init(i18nOpts, (err, t) => { + // initialized and ready to + if (err) { + console.error(err); + return; + } + console.log(`Language initialized: ${i18n.language}`); + + // document.title = t('AppName'); + // Accounts translation + // https://github.com/softwarerero/meteor-accounts-t9n + setT9(i18n.language); + // console.log(T9n.get('error.accounts.User not found')); + moment.locale(i18n.language); + + i18nReady.set(true); + + // cookies eu consent + const cookiesOpt = { + cookieTitle: t('Uso de Cookies'), + cookieMessage: t('Utilizamos cookies para asegurar un mejor uso de nuestra web. Si continúas navegando, consideramos que aceptas su uso'), + /* cookieMessage: t('Uso de Cookies'), + cookieMessageImply: t('Utilizamos cookies para asegurar un mejor uso de nuestra web. Si continúas navegando, consideramos que aceptas su uso'), */ + showLink: false, + position: 'bottom', + linkText: 'Lee más', + linkRouteName: '/privacy', + acceptButtonText: t('Aceptar'), + html: false, + expirationInDays: 70, + forceShow: false + }; + + CookieConsent.init(cookiesOpt); + }); + +Meteor.subscribe('userData'); // lang is there + +i18n.on('languageChanged', (lng) => { + moment.locale(lng); + // TODO fix this when gl is translated + setT9(lng); + Tracker.autorun((computation) => { + if (Meteor.userId()) { + // logged + if (Meteor.user() && (typeof Meteor.user().lang === 'undefined' || + Meteor.user().lang !== lng) + ) { + // Set the autodetected/changed lang + console.log(`Setting the autodetected lang ${lng}, from previous ${Meteor.user().lang}`); + // console.log(Meteor.user()); + Meteor.call('users.setLang', lng, (error) => { + if (error) { + console.error(error); + } + }); + computation.stop(); // not need it again til new lang change + } + } + }); +}); + +export default i18n; diff --git a/imports/startup/client/index.js b/imports/startup/client/index.js index ccebfda..147cf4f 100644 --- a/imports/startup/client/index.js +++ b/imports/startup/client/index.js @@ -1,8 +1,19 @@ +/* global */ import React from 'react'; import { render } from 'react-dom'; import { Meteor } from 'meteor/meteor'; +import '/imports/startup/client/modernizr'; import App from '../../ui/layouts/App/App'; import '../../ui/stylesheets/app.scss'; -Meteor.startup(() => render(, document.getElementById('react-root'))); +// https://stackoverflow.com/questions/19562207/jquery-detect-browser-ie9-and-below-and-throw-up-a-modal-to-upgrade +const isIE9OrBelow = () => /MSIE\s/.test(navigator.userAgent) && parseFloat(navigator.appVersion.split('MSIE')[1]) < 10; + +if (isIE9OrBelow()) window.alert('You are using an outdated browser. Please use Chrome or Firefox to display this site.'); +else { + Modernizr.on('webp', (result) => { + if (Meteor.isDevelopment) console.log(`webp ${result ? '' : 'not '}supported`); + }); + Meteor.startup(() => render(, document.getElementById('react-root'))); +} diff --git a/imports/startup/client/meta.js b/imports/startup/client/meta.js new file mode 100644 index 0000000..e1c64f2 --- /dev/null +++ b/imports/startup/client/meta.js @@ -0,0 +1,4 @@ +/* eslint-env jquery */ + +// remove static description so it's not duplicated +$('meta[name=description]').remove(); diff --git a/imports/startup/client/modernizr.js b/imports/startup/client/modernizr.js new file mode 100644 index 0000000..f6ac835 --- /dev/null +++ b/imports/startup/client/modernizr.js @@ -0,0 +1,3 @@ +/*! modernizr 3.6.0 (Custom Build) | MIT * + * https://modernizr.com/download/?-webp-prefixedcss-setclasses !*/ +!function(e,n,t){function r(e,n){return typeof e===n}function o(){var e,n,t,o,i,a,s;for(var l in w)if(w.hasOwnProperty(l)){if(e=[],n=w[l],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(t=0;tp;p++)if(d=e[p],m=E.style[d],f(d,"-")&&(d=s(d)),E.style[d]!==t){if(i||r(o,"undefined"))return a(),"pfx"==n?d:!0;try{E.style[d]=o}catch(v){}if(E.style[d]!=m)return a(),"pfx"==n?d:!0}return a(),!1}function v(e,n,t,o,i){var a=e.charAt(0).toUpperCase()+e.slice(1),s=(e+" "+B.join(a+" ")+a).split(" ");return r(n,"string")||r(n,"undefined")?h(s,n,o,i):(s=(e+" "+U.join(a+" ")+a).split(" "),p(s,n,t))}var y=[],w=[],C={_version:"3.6.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,n){var t=this;setTimeout(function(){n(t[e])},0)},addTest:function(e,n,t){w.push({name:e,fn:n,options:t})},addAsyncTest:function(e){w.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=C,Modernizr=new Modernizr;var _,b=n.documentElement,S="svg"===b.nodeName.toLowerCase();!function(){var e={}.hasOwnProperty;_=r(e,"undefined")||r(e.call,"undefined")?function(e,n){return n in e&&r(e.constructor.prototype[n],"undefined")}:function(n,t){return e.call(n,t)}}(),C._l={},C.on=function(e,n){this._l[e]||(this._l[e]=[]),this._l[e].push(n),Modernizr.hasOwnProperty(e)&&setTimeout(function(){Modernizr._trigger(e,Modernizr[e])},0)},C._trigger=function(e,n){if(this._l[e]){var t=this._l[e];setTimeout(function(){var e,r;for(e=0;ea;a++){var s=prefixes[a],l=s.toUpperCase()+"_"+r;if(l in i)return"@-"+s.toLowerCase()+"-"+n}return!1};C.atRule=Q;var U=C._config.usePrefixes?x.toLowerCase().split(" "):[];C._domPrefixes=U;var R={elem:u("modernizr")};Modernizr._q.push(function(){delete R.elem});var E={style:R.elem.style};Modernizr._q.unshift(function(){delete E.style}),C.testAllProps=v;var T=C.prefixed=function(e,n,t){return 0===e.indexOf("@")?Q(e):(-1!=e.indexOf("-")&&(e=s(e)),n?v(e,n,t):v(e,"pfx"))};C.prefixedCSS=function(e){var n=T(e);return n&&a(n)};o(),i(y),delete C.addTest,delete C.addAsyncTest;for(var P=0;P Tracker.autorun(() => { + const userId = Meteor.userId(); + Meteor.Piwik.setUserInfo(userId); +})); diff --git a/imports/startup/client/ravenLogger.js b/imports/startup/client/ravenLogger.js new file mode 100644 index 0000000..d678591 --- /dev/null +++ b/imports/startup/client/ravenLogger.js @@ -0,0 +1,16 @@ +import RavenLogger from 'meteor/flowkey:raven'; +import { Meteor } from 'meteor/meteor'; + +const ravenOptions = {}; +const publicDSN = Meteor.settings.public.sentryPublicDSN; +const enabled = !!publicDSN; + +const ravenLogger = enabled ? new RavenLogger({ + publicDSN, // will be used on the client + shouldCatchConsoleError: true, // default + trackUser: true // default +}, ravenOptions) : { log: (error) => { console.log(error); } }; + +console.log(`ravenLogger ${enabled ? 'enabled' : 'disabled'}`); + +export default ravenLogger; diff --git a/imports/startup/client/reconnect.js b/imports/startup/client/reconnect.js new file mode 100644 index 0000000..4659b20 --- /dev/null +++ b/imports/startup/client/reconnect.js @@ -0,0 +1,8 @@ +/* global reconnecToServer */ + +import { Meteor } from 'meteor/meteor'; + +Meteor.startup(() => { + // Reconnect Function + reconnectToServer(5000, true); +}); diff --git a/imports/startup/common/comments.js b/imports/startup/common/comments.js new file mode 100644 index 0000000..7b9ab18 --- /dev/null +++ b/imports/startup/common/comments.js @@ -0,0 +1,21 @@ +/* global Comments */ + +// Client and Server +Comments.config({ + rating: 'likes-and-dislikes', + allowAnonymous: () => false, + allowReplies: () => false, // disabled right now: I don't know hot to get referenceId of replies + anonymousSalt: 'klasddl3lala0l3lasdlas0ol3lasdlao3lasdoaslaldal3lasdclasdlal3lasdladlaq', + publishUserFields: { + profile: 1 + }, + mediaAnalyzers: [ + Comments.analyzers.image, + Comments.analyzers.youtube + ], + generateUsername: function genUser(user) { + // console.log(JSON.stringify(user)); + // FIXME + return user.profile && user.profile.name && user.profile.name.first ? user.profile.name.first : ''; + } +}); diff --git a/imports/startup/common/i18n.js b/imports/startup/common/i18n.js new file mode 100644 index 0000000..218e46d --- /dev/null +++ b/imports/startup/common/i18n.js @@ -0,0 +1,55 @@ +import { Meteor } from 'meteor/meteor'; +import moment from 'moment'; +// Load the js langs +import es from 'meteor-accounts-t9n/build/es'; +import en from 'meteor-accounts-t9n/build/en'; +// TODO ask for translation of this +// import gl from 'meteor-accounts-t9n/build/gl'; + +const backOpts = { + // path where resources get loaded from + loadPath: '/locales/{{lng}}/{{ns}}.json', + + // path to post missing resources + addPath: '/locales/{{lng}}/{{ns}}.missing.json', + + // jsonIndent to use when storing json files + jsonIndent: 2 +}; + +const forceDebug = true; +const shouldDebug = (forceDebug && !Meteor.isProduction); + +const i18nOpts = { + backend: backOpts, + // lng: 'es', + fallbackLng: { + gl: ['es'], + default: ['en'] + }, + sendMissingTo: 'fallback', + interpolation: { + escapeValue: false, // not needed for react!! + formatSeparator: ',', + format: function f(value, format, lng) { + // https://www.i18next.com/formatting.html + // console.log(`Value: ${value} with format: ${format} to lang: ${lng}`); + if (format === 'uppercase') return value.toUpperCase(); + if (value instanceof Date) return moment(value).format(format); + if (format === 'number') return Intl.NumberFormat(lng).format(value); + return value; + } + }, + whitelist: ['es', 'en', 'gl'], // allowed languages + load: 'languageOnly', // 'es' o 'en', previously: 'all', // es-ES -> es, en-US -> en + debug: shouldDebug, + ns: 'common', + defaultNS: 'common', + saveMissing: shouldDebug, // if true seems it's fails to getResourceBundle + saveMissingTo: 'es', + keySeparator: 'ß', + nsSeparator: 'ð', + pluralSeparator: 'đ' +}; + +export default i18nOpts; diff --git a/imports/startup/server/IPGeocoder.js b/imports/startup/server/IPGeocoder.js new file mode 100644 index 0000000..96c5ef1 --- /dev/null +++ b/imports/startup/server/IPGeocoder.js @@ -0,0 +1,69 @@ +/* eslint-disable prefer-arrow-callback */ + +import { Meteor } from 'meteor/meteor'; +import maxmind from 'maxmind'; +import fs from 'fs'; + +process.env.HTTP_FORWARDED_COUNT = Meteor.settings.private.proxies_count; +if (!Meteor.isDevelopment) { + console.log(`Number or proxies (needed for client IP lookup): ${process.env.HTTP_FORWARDED_COUNT}`); +} + +// https://stackoverflow.com/questions/13969655/how-do-you-check-whether-the-given-ip-is-internal-or-not +function isPrivateIP(ip) { + const parts = ip.split('.'); + return parts[0] === '10' || + parts[0] === '127' || + (parts[0] === '172' && (parseInt(parts[1], 10) >= 16 && parseInt(parts[1], 10) <= 31)) || + (parts[0] === '192' && parts[1] === '168'); +} + +const dbpath = '/usr/local/share/maxmind-geolite2/GeoLite2-City.mmdb'; +// const dbpath = `${process.env.PWD}/private/GeoLite2-City.mmdb`; + +if (!fs.existsSync(dbpath)) { + console.error(`Maxmind db not found ${dbpath}, download via cron with https://www.npmjs.com/package/maxmind-geolite2-mirror`); +} + +const IPGeocoder = maxmind.openSync(dbpath); +export default IPGeocoder; + +// Warning: Meteor cannot access to this.connection with arrow functions +export function localize() { + // https://stackoverflow.com/questions/14843232/how-to-get-the-user-ip-address-in-meteor-server/22657421#22657421 + let clientIP; + if (this.connection && this.connection.clientAddress) { + clientIP = this.connection.clientAddress; + } else { + console.warn(`We cannot get this meteor connection IP for this connection (${this.connection})`); + clientIP = '80.58.61.250'; + } + if (isPrivateIP(clientIP)) { + clientIP = '80.58.61.250'; // Some Spain IP address + } + // console.log(`Geolocating ${clientIP}`); + + // TODO: cron download GeoLite-City + // http://dev.maxmind.com/geoip/geoip2/geolite2/ + const geo = IPGeocoder.get(clientIP); + // console.warn(geo); + if (geo.location && geo.location.latitude && geo.location.longitude) { + return geo; + } + // geoIP fallback, Madrid + return { location: { latitude: 40.4146500, longitude: -3.7004000 } }; +} + +export const gmapKey = process.env.GMAPS_KEY || Meteor.settings.gmaps.key; +export const gmapServerKey = Meteor.settings.gmaps.serverKey; + +Meteor.methods({ + geo: localize, + getMapKey() { + // http://meteorpedia.com/read/Environment_Variables + // https://developers.google.com/maps/documentation/javascript/get-api-key + // https://console.developers.google.com/ + // export GMAPS_KEY=SomeGMapsKey + return gmapKey; + } +}); diff --git a/imports/startup/server/accounts/email-templates.js b/imports/startup/server/accounts/email-templates.js index 234065c..fdb25a3 100644 --- a/imports/startup/server/accounts/email-templates.js +++ b/imports/startup/server/accounts/email-templates.js @@ -1,34 +1,69 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; +import i18n from 'i18next'; +import { getFileNameOfLang } from '/imports/api/Utility/server/files.js'; +import getPrivateFile from '../../../modules/server/get-private-file'; +import templateToHTML from '../../../modules/server/handlebars-email-to-html'; +import templateToText from '../../../modules/server/handlebars-email-to-text'; -const name = 'Application Name'; -const email = ''; -const from = `${name} ${email}`; +const name = (lang) => { + i18n.changeLanguage(lang); + return i18n.t('AppName'); +}; +const email = ''; +const from = `${name('en')} ${email}`; +// const from = 'noreply@comunes.org'; const emailTemplates = Accounts.emailTemplates; emailTemplates.siteName = name; emailTemplates.from = from; emailTemplates.verifyEmail = { - subject() { - return `[${name}] Verify Your Email Address`; + subject(user) { + i18n.changeLanguage(user.lang); + const msg = i18n.t('Verifica tu dirección de correo'); + return `[${name(user.lang)}] ${msg}`; + }, + html(user, url) { + return templateToHTML(getPrivateFile(getFileNameOfLang('email-templates', 'verify-email', 'html', user.lang)), { + applicationName: name(user.lang), + firstName: user.profile.name.first, + verifyUrl: url.replace('#/', '') + }); }, text(user, url) { - const userEmail = user.emails[0].address; const urlWithoutHash = url.replace('#/', ''); if (Meteor.isDevelopment) console.info(`Verify Email Link: ${urlWithoutHash}`); // eslint-disable-line - return `Hey, ${user.profile.name.first}! Welcome to ${name}.\n\nTo verify your email address (${userEmail}), click the link below:\n\n${urlWithoutHash}\n\nIf you feel something is wrong, please contact our support team: ${email}.`; - }, + return templateToText(getPrivateFile(getFileNameOfLang('email-templates', 'verify-email', 'txt', user.lang)), { + applicationName: name(user.lang), + firstName: user.profile.name.first, + verifyUrl: urlWithoutHash + }); + } }; emailTemplates.resetPassword = { - subject() { - return `[${name}] Reset Your Password`; + subject(user) { + i18n.changeLanguage(user.lang); + const msg = i18n.t('Resetea tu contraseña'); + return `[${name(user.lang)}] ${msg}`; + }, + html(user, url) { + return templateToHTML(getPrivateFile(getFileNameOfLang('email-templates', 'reset-password', 'html', user.lang)), { + firstName: user.profile.name.first, + applicationName: name(user.lang), + emailAddress: user.emails[0].address, + resetUrl: url.replace('#/', '') + }); }, text(user, url) { - const userEmail = user.emails[0].address; const urlWithoutHash = url.replace('#/', ''); if (Meteor.isDevelopment) console.info(`Reset Password Link: ${urlWithoutHash}`); // eslint-disable-line - return `A password reset has been requested for the account related to this address (${userEmail}).\n\nTo reset the password, visit the following link: \n\n${urlWithoutHash}\n\n If you did not request this reset, please ignore this email. If you feel something is wrong, please contact our support team: ${email}.`; - }, + return templateToText(getPrivateFile(getFileNameOfLang('email-templates', 'reset-password', 'txt', user.lang)), { + firstName: user.profile.name.first, + applicationName: name(user.lang), + emailAddress: user.emails[0].address, + resetUrl: urlWithoutHash + }); + } }; diff --git a/imports/startup/server/accounts/on-create-user.js b/imports/startup/server/accounts/on-create-user.js index ede5150..566acc6 100644 --- a/imports/startup/server/accounts/on-create-user.js +++ b/imports/startup/server/accounts/on-create-user.js @@ -1,7 +1,28 @@ +/* eslint-disable import/no-absolute-path */ + import { Accounts } from 'meteor/accounts-base'; +import getFallbackLang from '/imports/modules/lang-fallback'; +import sendWelcomeEmail from '/imports/api/Users/server/send-welcome-email'; +import getOAuthProfile from '/imports/modules/get-oauth-profile'; Accounts.onCreateUser((options, user) => { const userToCreate = user; - if (options.profile) userToCreate.profile = options.profile; + // console.log(JSON.stringify(user)); + // console.log(JSON.stringify(options)); + + let lang = 'en'; // fallback + if (options.profile) { + userToCreate.profile = options.profile; + userToCreate.lang = options.profile.lang; + // console.log(JSON.stringify(user)); + lang = userToCreate.lang; + delete options.profile.lang; + } + const OAuthProfile = getOAuthProfile(options, user); + if (OAuthProfile) { + userToCreate.lang = getFallbackLang(OAuthProfile && OAuthProfile.lang ? OAuthProfile.lang : lang); + lang = userToCreate.lang; + } + sendWelcomeEmail(options, userToCreate, lang); return userToCreate; }); diff --git a/imports/startup/server/api.js b/imports/startup/server/api.js index e351317..a6044b4 100644 --- a/imports/startup/server/api.js +++ b/imports/startup/server/api.js @@ -7,3 +7,24 @@ import '../../api/Users/server/methods'; import '../../api/Users/server/publications'; import '../../api/Utility/server/methods'; + +import '../../api/ActiveFires/server/publications'; +import '../../api/ActiveFiresUnion/server/publications'; +import '../../api/FireAlerts/server/publications'; + +import '../../api/Subscriptions/methods'; +import '../../api/Subscriptions/server/publications'; + +// TODO add rate-limit to these publications + +import '../../api/Notifications/methods'; +import '../../api/Notifications/server/publications'; + +import '../../api/Fires/methods'; +import '../../api/Fires/server/publications'; + +import '../../api/SiteSettings/methods'; +import '../../api/SiteSettings/server/publications'; + +import '../../api/FalsePositives/methods'; +import '../../api/FalsePositives/server/publications'; diff --git a/imports/startup/server/catchExceptions.js b/imports/startup/server/catchExceptions.js new file mode 100644 index 0000000..179ab8b --- /dev/null +++ b/imports/startup/server/catchExceptions.js @@ -0,0 +1,19 @@ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import ravenLogger from '/imports/startup/server/ravenLogger'; + +Meteor.startup(() => { + const bound = Meteor.bindEnvironment((callback) => { callback(); }); + process.on('uncaughtException', (err) => { + bound(() => { + console.error(err); + + // https://github.com/flowkey/meteor-raven + ravenLogger.log(err); + + // https://github.com/nodejs/node-v0.x-archive/blob/master/doc/api/process.markdown#exit-codes + process.exit(7); + }); + }); +}); diff --git a/imports/startup/server/comments.js b/imports/startup/server/comments.js new file mode 100644 index 0000000..b010405 --- /dev/null +++ b/imports/startup/server/comments.js @@ -0,0 +1,80 @@ +/* global Comments */ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import i18n from 'i18next'; +import sendEmail, { subjectTruncate } from '/imports/modules/server/send-email'; +import getEmailOf from '/imports/modules/get-email-of-user'; +import '../common/comments'; + +/* import i18n from 'i18next'; +import moment from 'moment'; +import { dateLongFormat } from '/imports/api/Common/dates'; +import Notifications from '/imports/api/Notifications/Notifications'; +// import sendMail from '/imports/startup/server/email'; +// import { hr } from '/imports/startup/server/email'; +import getOAuthProfile from '/imports/modules/get-oauth-profile'; +import image from 'google-maps-image-api-url'; +import { trim } from '/imports/ui/components/NotificationsObserver/util.js'; */ + +Meteor.startup(() => { + // On Server or Client (preferably on Server) + Comments.config({ + onEvent: (name, action, payload) => { + // e.g send a mail + // console.log(`name: ${name}, action: ${action}, payload: ${JSON.stringify(payload)}`); + + // Samples: + + // name: comment, action: add, payload: {"referenceId":"fire-56a9cc5a5586879eb9cc6dd7","content":"asdfasdf asd fasd fas","userId":"tdK4e43ikjDXct7Gj","isAnonymous":false,"createdAt":"2018-03-04T14:53:40.319Z","likes":[],"dislikes":[],"replies":[],"media":{},"status":"approved","starRatings":[],"ratingScore":0,"_id":"mfAe3HL9qNofhiAnh"} + // name: reply, action: add, payload: {"replyId":"teSLaz4f8RxHjptBm","content":"sas fasdfasdasdf","userId":"tdK4e43ikjDXct7Gj","createdAt":"2018-03-04T14:54:56.965Z","replies":[],"likes":[],"lastUpdatedAt":"2018-03-04T14:54:56.965Z","isAnonymous":false,"status":"approved","media":{},"ratingScore":0,"_id":"DyHt28rF6rTDnC5fP","rootUserId":"tdK4e43ikjDXct7Gj"} + // name: reply, action: like, payload: {"replyId":"teSLaz4f8RxHjptBm","content":"sas fasdfasdasdf","userId":"tdK4e43ikjDXct7Gj","createdAt":"2018-03-04T14:54:56.965Z","replies":[],"likes":["tdK4e43ikjDXct7Gj"],"lastUpdatedAt":"2018-03-04T14:54:56.965Z","isAnonymous":false,"status":"approved","media":{},"ratingScore":1,"_id":"DyHt28rF6rTDnC5fP","ratedUserId":"tdK4e43ikjDXct7Gj","rootUserId":"tdK4e43ikjDXct7Gj"} + // name: comment, action: like, payload: {"_id":"mfAe3HL9qNofhiAnh","ratedUserId":"tdK4e43ikjDXct7Gj"} + // name: reply, action: edit, payload: {"_id":"DyHt28rF6rTDnC5fP","replyId":"teSLaz4f8RxHjptBm","content":"sas fasdfasdasdf dasd fadsfa","userId":"tdK4e43ikjDXct7Gj","createdAt":"2018-03-04T14:54:56.965Z","replies":[],"likes":[],"lastUpdatedAt":"2018-03-04T14:54:56.965Z","isAnonymous":false,"status":"approved","media":{},"ratingScore":0,"starRatings":[],"ratedUserId":"tdK4e43ikjDXct7Gj","rootUserId":"tdK4e43ikjDXct7Gj"} + // name: reply, action: remove, payload: {"_id":"DyHt28rF6rTDnC5fP","rootUserId":"tdK4e43ikjDXct7Gj"} + + // name: (comment|reply) + // action: (add|like|edit|remove) + + if (name === 'comment' && action.match(/add|like|edit/)) { + if (action === 'add') { + // Check for other users that did comments and send an email (uniq users, and not this user) + // console.log(payload.referenceId); + const query = payload.isAnonymous ? + { referenceId: payload.referenceId } : + { referenceId: payload.referenceId, userId: { $ne: payload.userId } }; + Comments.getCollection().rawCollection().distinct('userId', query).then((users) => { + // console.log(users); + const path = payload.referenceId.replace(/fire-/, 'fire/archive/'); + const fireUrl = Meteor.absoluteUrl(path); + // console.log(fireUrl); + Meteor.users.find({ _id: { $in: users } }).forEach((user) => { + const { firstName, emailAddress } = getEmailOf(user); + // console.log(JSON.stringify(user)); + if (emailAddress) { + const emailOpts = { + to: emailAddress, + subject: subjectTruncate.apply(i18n.t('Hay más información sobre un fuego')), + lang: user.lang, + template: 'new-fire-comment', + templateVars: { + applicationName: i18n.t('AppName'), + firstName, + fireUrl + } + }; + sendEmail(emailOpts).catch((error) => { + throw new Meteor.Error('500', `${error}`); + }); + } + }); + }); + } + } + if (name === 'reply' && action.match(/add|like|edit/)) { + // Check for other previous users to this thread and send an email + // console.log('Reply op'); + } + } + }); +}); diff --git a/imports/startup/server/cron.js b/imports/startup/server/cron.js new file mode 100644 index 0000000..843e55b --- /dev/null +++ b/imports/startup/server/cron.js @@ -0,0 +1,135 @@ +/* global SyncedCron */ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import { tweetIberiaFires, tweetEuropeFires } from '/imports/api/ActiveFires/server/tweetFiresInZone'; +import { isMailServerMaster, sendEmailsFromQueue } from '/imports/startup/server/email'; +import Notifications from '/imports/api/Notifications/Notifications'; +import processNotif from '/imports/modules/server/notificationsProcess.js'; + +// https://github.com/thesaucecode/meteor-synced-cron/ + +Meteor.startup(() => { + SyncedCron.config({ + // Log job run details to console + log: Meteor.settings.private.cron.debug || false, + + // Use a custom logger function (defaults to Meteor's logging package) + // workaround to disable logging succesfully + logger: Meteor.settings.private.cron.debug ? null : () => {} + + // Name of collection to use for synchronisation and logging + // collectionName: 'cronHistory', + + // Default to localTime + // Options: 'utc', 'localtime', or specific timezones 'America/New_York' + // Will be applied to jobs with no timezone defined + // timezone: 'utc', + + /* + TTL in seconds for history records in collection to expire + NOTE: Unset to remove expiry but ensure you remove the index from + mongo by hand + + ALSO: SyncedCron can't use the `_ensureIndex` command to modify + the TTL index. The best way to modify the default value of + `collectionTTL` is to remove the index by hand (in the mongo shell + run `db.cronHistory.dropIndex({startedAt: 1})`) and re-run your + project. SyncedCron will recreate the index with the updated TTL. + */ + // collectionTTL: 172800 + }); + + if (isMailServerMaster) { + SyncedCron.add({ + name: 'Send emails', + timezone: 'Europe/Madrid', + schedule: (parser) => { + // http://bunkat.github.io/later/ + const sched = parser.text('every 10 min'); + if (sched.error !== -1) { + console.error(`Mail cron 'when' field parsed with errors: ${sched.error}`); + } + return sched; + }, + job: () => sendEmailsFromQueue() + }); + + SyncedCron.add({ + name: 'Process pending notif', + timezone: 'Europe/Madrid', + schedule: (parser) => { + // http://bunkat.github.io/later/ + const sched = parser.text('every 15 min'); + if (sched.error !== -1) { + console.error(`Mail cron 'when' field parsed with errors: ${sched.error}`); + } + return sched; + }, + job: () => { + const mobileNotif = Notifications.find({ nofitied: null, type: 'mobile' }); + mobileNotif.forEach((notif) => { + processNotif(notif); + }); + const emailNotif = Notifications.find({ emailNofitied: null, type: 'web' }); + emailNotif.forEach((notif) => { + processNotif(notif); + }); + return { mobile: mobileNotif.count(), web: emailNotif.count() }; + } + }); + } + + const esEn = Meteor.settings.private.twitter.es.enabled; + const enEn = Meteor.settings.private.twitter.en.enabled; + + if (esEn) { + SyncedCron.add({ + name: 'Check for fires stats in Spain and tweet about', + timezone: 'Europe/Madrid', + // Optionally set a positive offset if you wish to 'snooze' a schedule + // offset: 30 * 60 * 100, + // context: { + // userID: 'xyz' + // }, + 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/ + 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: () => tweetIberiaFires() + /* console.log('cron is working'); + * console.log(this.userID) // Context Object becomes this argument + * console.log(this.magic) / + * var numbersCrunched = CrushSomeNumbers(); + * return numbersCrunched; + return tweetFires(); */ + }); + } + + if (enEn) { + SyncedCron.add({ + name: 'Check for fires stats in Europe and tweet about', + timezone: 'Europe/Madrid', + schedule: (parser) => { + const sched = parser.text(Meteor.settings.private.twitter.en.when); + if (sched.error !== -1) { + console.error(`Twitter cron 'when' field parsed with errors: ${sched.error}`); + } + return sched; + }, + job: () => tweetEuropeFires() + }); + } + + + if (isMailServerMaster || esEn || enEn) { + SyncedCron.start(); + } +}); diff --git a/imports/startup/server/email.js b/imports/startup/server/email.js index 377599c..42752cd 100644 --- a/imports/startup/server/email.js +++ b/imports/startup/server/email.js @@ -1,3 +1,91 @@ import { Meteor } from 'meteor/meteor'; +import nodemailer from 'nodemailer'; +import { MailTime } from 'meteor/ostrio:mailer'; +import i18n from 'i18next'; +import isMaster from './isMaster'; -if (Meteor.isDevelopment) process.env.MAIL_URL = Meteor.settings.private.MAIL_URL; +const transports = []; + +// First transport +const fstTransport = nodemailer.createTransport(Meteor.settings.private.MAIL_URL); +transports.push(fstTransport); +// console.log(fstTransport.options.auth.user); + +const db = Meteor.users.rawDatabase(); // new Mongo.Collection('__mailTimeQueue__').rawDatabase(); + +// https://litmus.com/community/discussions/4633-is-there-a-reliable-1px-horizontal-rule-method +export const hr = ` + + + +
`; + +let MailQueue; + +export const isMailServerMaster = Meteor.settings.private.isMailServer && isMaster(); + +if (isMailServerMaster) { + console.log('I\'m the mail server'); + MailQueue = new MailTime({ + db, + type: 'client', // instead of 'server' for now to avoid use the JosK task manager at 250ms, we use our cron + // see https://github.com/VeliovGroup/Mail-Time/issues/5 + strategy: 'balancer', // Transports will be used in round robin chain + transports, + from(transport) { + // To pass spam-filters `from` field should be correctly set + // for each transport, check `transport` object for more options + if (!Meteor.isProduction) { + // only for test purposes + return `${i18n.t('AppName')} `; + } + return `${i18n.t('AppName')} <${transport.options.auth.user}>`; + }, + debug: Meteor.settings.private.debugMailer, + concatEmails: true, // Concatenate emails to the same addressee + concatSubject: `${i18n.t('Nuevas notificaciones de {{app}}', { app: i18n.t('AppName') })}`, + /* eslint-disable */ + concatDelimiter: hr + '

{{{subject}}}

', // Start each concatenated email with it's own subject + /* eslint-enable */ + // concatThrottling: 30, + template: MailTime.Template // Use default template + }); +} else { + console.log('I\'m a mail client'); + MailQueue = new MailTime({ + db, + type: 'client', + debug: Meteor.settings.private.debugMailer, + strategy: 'balancer', // Transports will be used in round robin chain + concatEmails: true // Concatenate emails to the same address + }); +} + +export default function sendMail(opts, debug) { + if (debug) { + MailQueue.sendMail(opts, (err, info) => { if (err) { console.error(err); } else { console.log(info); } }); + } else { + MailQueue.sendMail(opts); + } +} + +if (Meteor.settings.private.testMailer) { + const emailOpts = { + to: Meteor.settings.private.testEmail, + userName: 'someone', + sendAt: new Date(), + subject: 'Some new notification', + text: 'Plain text message', + template: '{{appName}}

{{{subject}}}

{{{html}}}', + appName: i18n.t('AppName'), + html: '

Styled message

' + }; + sendMail(emailOpts, true); + sendMail(emailOpts, true); + sendMail(emailOpts, true); + sendMail(emailOpts, true); +} + +export const sendEmailsFromQueue = () => { + MailQueue.___send(() => { }); +}; diff --git a/imports/startup/server/facts.js b/imports/startup/server/facts.js new file mode 100644 index 0000000..0c75843 --- /dev/null +++ b/imports/startup/server/facts.js @@ -0,0 +1,9 @@ +/* global Facts */ +import { Roles } from 'meteor/alanning:roles'; +import { Meteor } from 'meteor/meteor'; + +Facts.setUserIdFilter((userId) => { + const user = Meteor.users.findOne(userId); + // console.log(`User roles: ${user.roles}`); + return Roles.userIsInRole(userId, ['admin']); +}); diff --git a/imports/startup/server/feedback.js b/imports/startup/server/feedback.js new file mode 100644 index 0000000..c1d028b --- /dev/null +++ b/imports/startup/server/feedback.js @@ -0,0 +1,25 @@ +/* eslint-disable prefer-arrow-callback */ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import i18n from 'i18next'; +import { check } from 'meteor/check'; +import sendEmail from '/imports/startup/server/email'; + +Meteor.methods({ + 'send-feedback': function sendFeedback(email, feedback) { + check(email, String); + check(feedback, String); + const appName = i18n.t('AppName'); + sendEmail({ + to: 'fires@comunes.org', + from: `${appName} `, + subject: `Feedback de ${email}!`, + sendAt: new Date(), + text: `Feedback de ${email}\n\n${feedback}`, + html: `

${feedback}

`, + template: '{{appName}}

{{{subject}}}

{{{html}}}', + appName + }, true); + } +}); diff --git a/imports/startup/server/fibers.js b/imports/startup/server/fibers.js new file mode 100644 index 0000000..ff96265 --- /dev/null +++ b/imports/startup/server/fibers.js @@ -0,0 +1,7 @@ +// Workaround for: https://github.com/meteor/meteor/issues/9796 +// https://github.com/meteor/meteor/issues/9796#issuecomment-381676326 +// https://github.com/sandstorm-io/sandstorm/blob/0f1fec013fe7208ed0fd97eb88b31b77e3c61f42/shell/server/00-startup.js#L99-L129 + +import Fiber from 'fibers'; + +Fiber.poolSize = 1e9; diff --git a/imports/startup/server/i18n.js b/imports/startup/server/i18n.js new file mode 100644 index 0000000..053d487 --- /dev/null +++ b/imports/startup/server/i18n.js @@ -0,0 +1,32 @@ +import { Meteor } from 'meteor/meteor'; +import i18n from 'i18next'; +import backend from 'i18next-sync-fs-backend'; +import i18nOpts from '../common/i18n'; +// import moment from 'moment'; +// import { T9n } from 'meteor-accounts-t9n'; + +// vi ostrio:meteor-root +i18nOpts.backend.loadPath = `${Meteor.rootPath}/../web.browser/app/${i18nOpts.backend.loadPath}`; +i18nOpts.backend.addPath = `${Meteor.rootPath}/../web.browser/app/${i18nOpts.backend.addPath}`; + +// console.log(i18nOpts.backend.loadPath); +i18nOpts.debug = false; +i18nOpts.saveMissing = Meteor.isDevelopment; +i18nOpts.initImmediate = false; + +i18n + .use(backend) + .init(i18nOpts, (err) => { + if (err) { + console.error(err); + } + }); + +/* export function setUserLang (lng) { + * moment.locale(lng); + * T9n.setLanguage(lng); + * } */ + +// console.log(i18n.t('Servidor arrancado')); + +export default i18n; diff --git a/imports/startup/server/index.js b/imports/startup/server/index.js index 09fb6b3..7f84dde 100644 --- a/imports/startup/server/index.js +++ b/imports/startup/server/index.js @@ -1,4 +1,20 @@ +import './ravenLogger'; +import './catchExceptions'; +import './fibers'; +import './i18n'; import './accounts'; import './api'; import './fixtures'; import './email'; +import './IPGeocoder'; +import './migrations'; +import './notificationsObserver'; +import './facts'; +import './comments'; +import './sitemaps'; +import './subsUnion'; +import './prerender'; +import './feedback'; +import './cron'; +import './isMaster'; +import './rest'; diff --git a/imports/startup/server/isMaster.js b/imports/startup/server/isMaster.js new file mode 100644 index 0000000..1bcdd32 --- /dev/null +++ b/imports/startup/server/isMaster.js @@ -0,0 +1,16 @@ +/* eslint-disable import/no-absolute-path */ + +import pm2Master from 'pm2-master'; +import { Meteor } from 'meteor/meteor'; + +Meteor.startup(() => { + if (pm2Master.isMaster()) { + console.log('This is the master process'); + } else { + console.log('This is a worker process'); + } +}); + +const isMaster = () => pm2Master.isMaster(); + +export default isMaster; diff --git a/imports/startup/server/leaflet-workaround.js b/imports/startup/server/leaflet-workaround.js new file mode 100644 index 0000000..740aa3b --- /dev/null +++ b/imports/startup/server/leaflet-workaround.js @@ -0,0 +1,19 @@ +// imports/startup/server/leaflet-workaround.js +global.window = { + screen: { + deviceXDPI: 1, + logicalXDPI: 1 + } +}; +global.document = { + documentElement: { + style: {} + }, + createElement: () => { + return {}; + } +}; +global.navigator = { + userAgent: 'foo', + platform: 'bar' +}; diff --git a/imports/startup/server/migrations.js b/imports/startup/server/migrations.js new file mode 100644 index 0000000..e3bfac9 --- /dev/null +++ b/imports/startup/server/migrations.js @@ -0,0 +1,260 @@ +/* global Migrations, Comments */ +/* eslint-disable import/no-absolute-path */ +import { Meteor } from 'meteor/meteor'; +import { Accounts } from 'meteor/accounts-base'; +import randomHex from 'crypto-random-hex'; +import UserSubsToFiresCollection from '/imports/api/Subscriptions/Subscriptions'; +import FireAlertsCollection from '/imports/api/FireAlerts/FireAlerts'; +import SiteSettings from '/imports/api/SiteSettings/SiteSettings'; +import FalsePositives from '/imports/api/FalsePositives/FalsePositives'; +import Industries from '/imports/api/Industries/Industries'; +import IndustryRegistries from '/imports/api/Industries/IndustryRegistries'; +import Notifications from '/imports/api/Notifications/Notifications'; +import ActiveFiresUnion from '/imports/api/ActiveFiresUnion/ActiveFiresUnion'; +import { Mongo } from 'meteor/mongo'; + +Meteor.startup(() => { + // https://github.com/percolatestudio/meteor-migrations + + Migrations.config({ + // Log job run details to console + log: Meteor.isProduction + }); + + Migrations.add({ + version: 1, + up: function migrateIds() { + // https://docs.mongodb.com/manual/reference/operator/query/type/ + Meteor.users.find({ _id: { $type: 7 } }).forEach((user) => { + const migratedUser = user; + const id = user._id.valueOf(); + console.log(`Migrating id of user: ${JSON.stringify(user)}`); + Meteor.users.remove({ _id: user._id }); + migratedUser._id = id; + Meteor.users.insert(migratedUser); + }); + } + }); + + Migrations.add({ + version: 2, + up: function migrateSubsForeignKey() { + UserSubsToFiresCollection.find({ owner: null }).forEach((sub) => { + console.log(`Migrating subs of chatId: ${sub.chatId}`); + const subsUser = Meteor.users.findOne({ telegramChatId: sub.chatId }); + if (subsUser) { + console.log(`Migrating linking to user: ${JSON.stringify(subsUser)}`); + UserSubsToFiresCollection.update({ _id: sub._id }, { $set: { owner: subsUser._id } }); + } else { + // create user with chatId and def language + const username = `tel${sub.chatId.toString().replace(/^-/, '')}`; + console.log(`Linking to new user: ${username}`); + const newUserId = Accounts.createUser({ + username, + password: randomHex(50), + profile: { name: {} } + }); + Meteor.users.update({ _id: newUserId }, { + $set: { + emails: [], + roles: ['user'], + telegramChatId: sub.chatId, + lang: 'es' + } + }); + UserSubsToFiresCollection.update({ _id: sub._id }, { $set: { owner: newUserId } }); + } + }); + } + }); + + Migrations.add({ + version: 3, + up: function emptySubsTypes() { + UserSubsToFiresCollection.find({ type: null }).forEach((sub) => { + UserSubsToFiresCollection.update({ _id: sub._id }, { $set: { type: 'telegram' } }); + }); + } + }); + + Migrations.add({ + version: 4, + up: function deleteOldAlertFiresAndIndexes() { + FireAlertsCollection.remove({ createdAd: null }); + const raw = FireAlertsCollection.rawCollection(); + raw.createIndex({ ourid: '2dsphere' }); + raw.createIndex({ when: 1 }); + raw.createIndex({ updatedAt: 1 }); + raw.createIndex({ createdAt: 1 }); + raw.createIndex({ ourid: 1, type: 1 }); + } + }); + + Migrations.add({ + version: 5, + up: function siteSettingsIndex() { + // other way: + SiteSettings._ensureIndex({ name: 1 }, { unique: 1 }); + } + }); + + Migrations.add({ + version: 6, + up: function falsePositiveIndexes() { + FalsePositives._ensureIndex({ chatId: 1 }); + FalsePositives._ensureIndex({ owner: 1 }); + FalsePositives._ensureIndex({ fireId: 1 }); + FalsePositives._ensureIndex({ type: 1 }); + FalsePositives._ensureIndex({ geo: '2dsphere' }); + } + }); + + Migrations.add({ + version: 7, + up: function defLangIfNull() { + Meteor.users.find({ lang: null }).forEach((user) => { + Meteor.users.update({ _id: user._id }, { + $set: { + lang: 'es' + } + }); + }); + } + }); + + Migrations.add({ + version: 8, + up: function siteSettingsAddIndex() { + SiteSettings._ensureIndex({ isPublic: 1 }); + SiteSettings.find({ isPublic: null }).forEach((setting) => { + SiteSettings.update({ _id: setting._id }, { $set: { isPublic: true } }); + }); + } + }); + + Migrations.add({ + version: 9, + up: function siteSettingsAddIndex() { + Industries._ensureIndex({ registry: 1 }); + Industries._ensureIndex({ geo: '2dsphere' }); + // https://www.eea.europa.eu/data-and-maps/data/member-states-reporting-art-7-under-the-european-pollutant-release-and-transfer-register-e-prtr-regulation-16 + IndustryRegistries.insert({ + _id: '1', name: 'E-PRTR', agency: 'EEA', region: 'EU' + }); + // https://www.epa.gov/enviro/epa-frs-facilities-state-single-file-csv-download + IndustryRegistries.insert({ + _id: '2', name: 'FRS', agency: 'EPA', region: 'US' + }); + } + }); + + Migrations.add({ + version: 10, + up: function siteSettingsAddIndex() { + IndustryRegistries.insert({ + _id: '3', name: 'NPRI', agency: 'GCODP', region: 'Canada' + }); + IndustryRegistries.insert({ + _id: '4', name: 'NPI', agency: 'DEE', region: 'Australia' + }); + } + }); + + Migrations.add({ + version: 11, + up: function noAnonComments() { + Comments.getCollection().remove({ isAnonymous: true }); + } + }); + + Migrations.add({ + version: 12, + up: function setTelegramUsersBotId() { + Meteor.users.update({ telegramChatId: { $ne: null }, telegramBot: null }, { + $set: { + telegramBot: 'es' + } + }, { multi: true }); + } + }); + + Migrations.add({ + version: 13, + up: function removeTelegramBotFromUsersId() { + Meteor.users.update({}, { + $unset: { + telegramBot: '' + } + }, { multi: true }); + } + }); + + Migrations.add({ + version: 14, + up: function setTelegramUsersBotId() { + UserSubsToFiresCollection.update({ chatId: { $ne: null }, telegramBot: null }, { + $set: { + telegramBot: 'es' + } + }, { multi: true }); + } + }); + + Migrations.add({ + version: 15, + up: function moveToFalsePositivesUppercase() { + /* const falsepositiveslower = new Mongo.Collection('falsepositives', { idGeneration: 'MONGO' }); + * falsepositiveslower.find({}).forEach((falseDoc) => { + * FalsePositives.insert(falseDoc); + * });*/ + // TODO remove falsepositives lowercase collection + } + }); + + Migrations.add({ + version: 16, + up: function moveToFalsePositivesUppercaseWithUser() { + const falsepositiveslower = new Mongo.Collection('falsepositives', { idGeneration: 'MONGO' }); + const now = new Date(); + falsepositiveslower.find({}).forEach((falseDoc) => { + const user = Meteor.users.findOne({ telegramChatId: falseDoc.chatId }); + if (user) { + falseDoc.owner= user._id; + } + falseDoc.type = 'industry'; + falseDoc.createdAt = now; + falseDoc.updatedAt = now; + FalsePositives.insert(falseDoc); + }); + } + }); + + 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 }); + } + }); + + Migrations.add({ + version: 18, + up: () => { + const raw = ActiveFiresUnion.rawCollection(); + raw.createIndex({ centerid: '2dsphere' }); + raw.createIndex({ shape: '2dsphere' }); + raw.createIndex({ when: 1 }); + raw.createIndex({ createdAt: 1 }); + raw.createIndex({ updatedAt: 1 }); + } + }); + + // Set createdAt in users & subs + Migrations.migrateTo('latest'); + + // Migrations.migrateTo('14,rerun'); +}); diff --git a/imports/startup/server/notificationsObserver.js b/imports/startup/server/notificationsObserver.js new file mode 100644 index 0000000..70be8e0 --- /dev/null +++ b/imports/startup/server/notificationsObserver.js @@ -0,0 +1,19 @@ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import Notifications from '/imports/api/Notifications/Notifications'; +import processNotif from '/imports/modules/server/notificationsProcess.js'; +import { isMailServerMaster } from '/imports/startup/server/email'; + +Meteor.startup(() => { + if (isMailServerMaster) { + Notifications.find().observe({ + added: function notifAdded(notif) { + processNotif(notif); + }, + changed: function notifChanged(updatedNotif) { // , oldNotif) { + processNotif(updatedNotif); + } + }); + } +}); diff --git a/imports/startup/server/prerender.js b/imports/startup/server/prerender.js new file mode 100644 index 0000000..dedee0b --- /dev/null +++ b/imports/startup/server/prerender.js @@ -0,0 +1,46 @@ +/* global WebApp */ + +import { Meteor } from 'meteor/meteor'; +import prerenderIO from 'prerender-node'; + +// NOTE: Fetch as Google needs the /?_escaped_fragment_= +// https://webmasters.stackexchange.com/questions/72819/fetch-as-google-doesnt-find-the-html-snapshot-for-my-ajax-content + +// https://forums.meteor.com/t/any-guide-for-prerender-node-and-your-own-server-on-meteor/22054/9 +const settings = Meteor.settings.PrerenderIO; + +// https://github.com/dferber90/meteor-prerender/blob/master/server/prerender.js +const token = process.env.PRERENDERIO_TOKEN || (settings && settings.token); +const protocol = process.env.PRERENDERIO_PROTOCOL || (settings && settings.protocol); +// service url (support `prerenderServiceUrl` (for historical reasons) and `serviceUrl`) +let serviceUrl = settings && (settings.prerenderServiceUrl || settings.serviceUrl); +serviceUrl = process.env.PRERENDERIO_SERVICE_URL || serviceUrl; + +Meteor.startup(() => { + /* TODO if (!__meteor_runtime_config__.ROOT_URL.match(/www|stg|app/)) return; */ + + prerenderIO.set('prerenderToken', token); + + if (serviceUrl) prerenderIO.set('prerenderServiceUrl', serviceUrl); + prerenderIO.set('prerenderToken', token); + if (protocol) prerenderIO.set('protocol', protocol); + + prerenderIO.set('beforeRender', (req, done) => { + if (Meteor.isDevelopment) console.log('\nprerender before', req.headers, '\n\n'); + /* This method is intended to be used for caching, but could be used to save analytics or anything else you need to do for each crawler request. If you return a string from beforeRender, the middleware will serve that to the crawler (with status 200) instead of making a request to the prerender service. If you return an object the middleware will look for a status and body property (defaulting to 200 and "" respectively) and serve those instead. */ + done(); + }); + + prerenderIO.set('afterRender', (err, req, prerender_res) => { + /* This method is intended to be used for caching, but could be used to save analytics or anything else you need to do for each crawler request. This method is a noop and is called after the prerender service returns HTML. */ + if (err) { + console.log('prerenderio error', err); + return; + } + if (Meteor.isDevelopment) console.log('prerender after', req.url, '\nheaders:', req.headers, '\nres complete:', prerender_res.complete, prerender_res.statusCode, prerender_res.statusMessage, '\nres headers:', prerender_res.headers, '\nres body', prerender_res); + }); + + WebApp.rawConnectHandlers.use(prerenderIO); + + // console.log('\nprerender service:', settings); +}); diff --git a/imports/startup/server/ravenLogger.js b/imports/startup/server/ravenLogger.js new file mode 100644 index 0000000..b3b83a3 --- /dev/null +++ b/imports/startup/server/ravenLogger.js @@ -0,0 +1,18 @@ +import RavenLogger from 'meteor/flowkey:raven'; +import { Meteor } from 'meteor/meteor'; + +const ravenOptions = {}; +const publicDSN = Meteor.settings.public.sentryPublicDSN; +const privateDSN = Meteor.settings.sentryPrivateDSN; +const enabled = publicDSN && privateDSN; + +const ravenLogger = enabled ? new RavenLogger({ + publicDSN, + privateDSN, + shouldCatchConsoleError: true, // default true + trackUser: true // default false +}, ravenOptions) : { log: (error) => { console.log(error); } }; + +console.log(`ravenLogger ${enabled ? 'enabled' : 'disabled'}`); + +export default ravenLogger; diff --git a/imports/startup/server/rest.js b/imports/startup/server/rest.js new file mode 100644 index 0000000..64e8172 --- /dev/null +++ b/imports/startup/server/rest.js @@ -0,0 +1 @@ +import '../../api/Rest/Rest.js'; diff --git a/imports/startup/server/sitemaps.js b/imports/startup/server/sitemaps.js new file mode 100644 index 0000000..8026449 --- /dev/null +++ b/imports/startup/server/sitemaps.js @@ -0,0 +1,44 @@ +/* global sitemaps Comments */ +/* eslint-disable import/no-absolute-path */ + +import Fires from '/imports/api/Fires/Fires'; +// import Comments from '/imports/api/Comments/Comments'; + +const firesMapEnabled = false; + +sitemaps.add('/sitemap.xml', () => { + const today = new Date(); + + const out = []; + out.push({ page: '/fires', lastmod: today }); + out.push({ page: '/login', lastmod: today }); + out.push({ page: '/signup', lastmod: today }); + out.push({ page: '/recover-password', lastmod: today }); + out.push({ page: '/credits', lastmod: today }); + out.push({ page: '/terms', lastmod: today }); + out.push({ page: '/license', lastmod: today }); + out.push({ page: '/privacy', lastmod: today }); + out.push({ page: '/about', lastmod: today }); + + // When user has public page + /* const users = Meteor.users.find().fetch(); + _.each(users, function(user) { + out.push({ + page: '/persona/' + user.username, + lastmod: user.updatedAt + }); + }); */ + + if (firesMapEnabled) { + Fires.find({}, { limit: 100, sort: { createdAt: -1 } }).fetch().forEach((fire) => { + // Search the last comment of tha fire + const lastComment = Comments.getCollection().findOne({ referenceId: `fire-${fire._id}` }, { sort: { createdAt: -1 } }); + out.push({ + page: `/fire/archive/${fire._id._str}`, + lastmod: lastComment ? lastComment.createdAt : fire.updatedAt + }); + }); + } + + return out; +}); diff --git a/imports/startup/server/subsUnion.js b/imports/startup/server/subsUnion.js new file mode 100644 index 0000000..2643359 --- /dev/null +++ b/imports/startup/server/subsUnion.js @@ -0,0 +1,123 @@ +/* eslint-disable import/no-absolute-path */ + +import { Meteor } from 'meteor/meteor'; +import Subscriptions from '/imports/api/Subscriptions/Subscriptions'; +import SiteSettings from '/imports/api/SiteSettings/SiteSettings'; +import Perlin from 'loms.perlin'; +import './leaflet-workaround'; +import L from 'leaflet'; +import calcUnion from '/imports/ui/components/Maps/SubsUnion/Unify'; +import { isMailServerMaster } from '/imports/startup/server/email'; + +// sudo apt-get install libcairo2-dev libjpeg-dev libgif-dev + +Meteor.startup(() => { + if (!isMailServerMaster) { + console.log('We only process subsUnion in master'); + return; + } + const debug = true; // Meteor.isDevelopment; + Perlin.seed(Math.random()); + + const addNoisy = (osub) => { + const sub = osub; + let lat = Math.round(sub.location.lat * 10) / 10; + let lon = Math.round(sub.location.lon * 10) / 10; + const noiseBase = Perlin.perlin2(lat, lon); + const noise = Math.abs(noiseBase / 3); + lat += noise; + lon += noise; + sub.location.lat = lat; + sub.location.lon = lon; + sub.distance += noiseBase; + return sub; + }; + + const noNoisy = sub => sub; + + const process = (isPublic) => { + const subscribers = Subscriptions.find().fetch(); + const result = calcUnion(L, subscribers, isPublic ? addNoisy : noNoisy, true); + const union = result[0]; + const bounds = result[1]; + + const publicl = isPublic ? 'public' : 'private'; + const Publicl = publicl.replace(/\b\w/g, l => l.toUpperCase()); + + if (typeof union === 'object') { + const unionSet = { + $set: { + name: `subs-${publicl}-union`, + value: JSON.stringify(union), + isPublic, + description: `${Publicl} subscriptions union`, + type: 'string' + } + }; + const boundsSet = { + $set: { + name: `subs-${publicl}-union-bounds`, + value: JSON.stringify(bounds), + isPublic, + description: `${Publicl} subscriptions union bounds`, + type: 'string' + } + }; + const sizeSet = { + $set: { + name: 'subs-union-count', + value: subscribers.length, + isPublic: false, + description: 'Subscriptions count', + type: 'number' + } + }; + // FIXME, take care of object size: + // https://stackoverflow.com/questions/10827812/what-is-the-length-maximum-for-a-string-data-type-in-mongodb-used-with-ruby + SiteSettings.upsert({ name: `subs-${publicl}-union` }, unionSet, { multi: false }); + SiteSettings.upsert({ name: `subs-${publicl}-union-bounds` }, boundsSet, { multi: false }); + SiteSettings.upsert({ name: 'subs-union-count' }, sizeSet, { multi: false }); + if (debug) console.log(`${Publicl} subscription union calculated`); + } else { + console.log('Subscription union failed!'); + } + }; + + // At startup, we check if it's necessary to calc subscriptions union again + const currentUnion = SiteSettings.findOne({ name: 'subs-public-union' }); + const lastSubs = Subscriptions.findOne({}, { sort: { updatedAt: -1 } }); + const countUnionSubs = SiteSettings.findOne({ name: 'subs-union-count' }); + const countSubs = Subscriptions.find({}).count(); + if (currentUnion && lastSubs) { + const lastUnionUpdated = currentUnion.updatedAt; + const lastSubsUpdated = lastSubs.updatedAt; + if (lastUnionUpdated > lastSubsUpdated || !countUnionSubs || countSubs !== countUnionSubs.value) { + console.log('Subs union outdated'); + process(true); + process(false); + } else { + console.log('Subs union up-to-date'); + } + } + + Subscriptions.find({ createdAt: { $gt: new Date() } }).observe({ + added: function newSubAdded() { // doc) { + if (debug) console.log('Subs added so recreate union'); + process(true); + process(false); + } + }); + + Subscriptions.find().observe({ + changed: function subsChanged() { // updatedDoc, oldDoc) { + if (debug) console.log('Subs changed so recreate union'); + process(true); + process(false); + }, + removed: function subsRemoved() { // oldDoc) { + if (debug) console.log('Subs removed so recreate union'); + process(true); + process(false); + } + }); +}); diff --git a/imports/ui/components/Authenticated/Authenticated.js b/imports/ui/components/Authenticated/Authenticated.js index 7207ad0..f34da2f 100644 --- a/imports/ui/components/Authenticated/Authenticated.js +++ b/imports/ui/components/Authenticated/Authenticated.js @@ -2,13 +2,14 @@ import React from 'react'; import PropTypes from 'prop-types'; import { Route, Redirect } from 'react-router-dom'; -const Authenticated = ({ loggingIn, authenticated, component, ...rest }) => ( +const Authenticated = ({ loggingIn, authenticated, component, path, exact, ...rest }) => ( ( authenticated ? - (React.createElement(component, { ...props, loggingIn, authenticated })) : - () + (React.createElement(component, { ...props, ...rest, loggingIn, authenticated })) : + () )} /> ); diff --git a/imports/ui/components/AuthenticatedNavigation/AuthenticatedNavigation.js b/imports/ui/components/AuthenticatedNavigation/AuthenticatedNavigation.js index d8518b8..e479f8f 100644 --- a/imports/ui/components/AuthenticatedNavigation/AuthenticatedNavigation.js +++ b/imports/ui/components/AuthenticatedNavigation/AuthenticatedNavigation.js @@ -1,30 +1,42 @@ +/* eslint-disable import/no-absolute-path */ import React from 'react'; import PropTypes from 'prop-types'; +import { withRouter } from 'react-router-dom'; import { LinkContainer } from 'react-router-bootstrap'; -import { Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap'; -import { Meteor } from 'meteor/meteor'; +/* import { Nav, NavDropdown } from 'react-bootstrap'; */ +import { translate, Trans } from 'react-i18next'; +import { testId } from '/imports/ui/components/Utils/TestUtils'; -const AuthenticatedNavigation = ({ name }) => ( -
- - -
+/* + FIXME: + navitem needs a nav-link class but does not works + https://github.com/react-bootstrap/react-bootstrap/issues/2644 + className="nav-link" + so we did a custom NavLink + */ +import NavItem from '../NavItem/NavItem'; + +const AuthenticatedNavigation = ({ name, history, props }) => ( +
    + {/* */} +
); AuthenticatedNavigation.propTypes = { - name: PropTypes.string.isRequired, + name: PropTypes.string.isRequired }; -export default AuthenticatedNavigation; +export default translate([], { wait: true })(withRouter(AuthenticatedNavigation)); diff --git a/imports/ui/components/BetaRibbon/BetaRibbon.js b/imports/ui/components/BetaRibbon/BetaRibbon.js new file mode 100644 index 0000000..584f38d --- /dev/null +++ b/imports/ui/components/BetaRibbon/BetaRibbon.js @@ -0,0 +1,33 @@ +/* eslint-disable react/jsx-indent-props */ +/* eslint-disable import/no-absolute-path */ +/* eslint-disable import/no-absolute-path */ + +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; +import { translate } from 'react-i18next'; + +import './BetaRibbon.scss'; + +class BetaRibbon extends Component { + constructor(props) { + super(props); + this.t = props.t; + this.state = { + }; + } + + render() { + return ( +
BETA
+ ); + } +} + +BetaRibbon.propTypes = { + t: PropTypes.func.isRequired +}; + +BetaRibbon.defaultProps = { +}; + +export default translate([], { wait: true })(BetaRibbon); diff --git a/imports/ui/components/BetaRibbon/BetaRibbon.scss b/imports/ui/components/BetaRibbon/BetaRibbon.scss new file mode 100644 index 0000000..cd150c2 --- /dev/null +++ b/imports/ui/components/BetaRibbon/BetaRibbon.scss @@ -0,0 +1,43 @@ +.ribbon { + position: absolute; + left: -5px; top: -5px; + z-index: 2000; + overflow: hidden; + width: 75px; height: 75px; + text-align: right; +} +.ribbon span { + font-size: 10px; + font-weight: bold; + color: #FFF; + text-transform: uppercase; + text-align: center; + line-height: 20px; + transform: rotate(-45deg); + -webkit-transform: rotate(-45deg); + width: 100px; + display: block; + background: #79A70A; + background: linear-gradient(#9BC90D 0%, #9BC90D 100%); + box-shadow: 0 3px 10px -5px rgba(0, 0, 0, 1); + position: absolute; + top: 19px; left: -21px; +} +.ribbon span::before { + content: ""; + position: absolute; left: 0px; top: 100%; + z-index: -1; + border-left: 3px solid #9BC90D; + border-right: 3px solid transparent; + border-bottom: 3px solid transparent; + border-top: 3px solid #9BC90D; +} +.ribbon span::after { + content: ""; + position: absolute; right: 0px; top: 100%; + z-index: -1; + border-left: 3px solid transparent; + border-right: 3px solid #9BC90D; + border-bottom: 3px solid transparent; + border-top: 3px solid #9BC90D; +} \ No newline at end of file diff --git a/imports/ui/components/CenterInMyPosition/CenterInMyPosition.js b/imports/ui/components/CenterInMyPosition/CenterInMyPosition.js new file mode 100644 index 0000000..6fde995 --- /dev/null +++ b/imports/ui/components/CenterInMyPosition/CenterInMyPosition.js @@ -0,0 +1,66 @@ +/* global Geolocation */ +import React from 'react'; +import PropTypes from 'prop-types'; +import { Tracker } from 'meteor/tracker'; +import { ReactiveVar } from 'meteor/reactive-var'; +import { Button } from 'react-bootstrap'; +import { translate } from 'react-i18next'; +import { Bert } from 'meteor/themeteorchef:bert'; + +import './CenterInMyPosition.scss'; + +class CenterInMyPosition extends React.Component { + onClick() { + // this.props.onClick(event); + // https://atmospherejs.com/mdg/geolocation + // only with SSL: + // https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition + + // https://stackoverflow.com/questions/31608579/somethings-wrong-with-my-meteor-geolocation-functions + const userGeoLocation = new ReactiveVar(null); + const self = this; + Tracker.autorun((computation) => { + userGeoLocation.set(Geolocation.latLng()); + if (userGeoLocation.get()) { + // stop the tracker if we got something + const viewport = { + center: [userGeoLocation.get().lat, userGeoLocation.get().lng], + zoom: 11 + }; + self.props.onClick(viewport); + computation.stop(); + } + // https://developer.mozilla.org/en-US/docs/Web/API/PositionError) + const error = Geolocation.error(); + if (error) { + const cod = error.code; + // window.alert(cod); + if (cod === 1) Bert.alert(self.props.t('geo-not-perms-error'), 'danger'); + else if (cod === 2) Bert.alert(self.props.t('geo-not-avail-error'), 'danger'); + else if (cod === 3) Bert.alert(self.props.t('geo-not-timeout-error'), 'danger'); + else Bert.alert(error.message, 'danger'); + computation.stop(); + } + }); + } + + render() { + const { onlyIcon, t } = this.props; + const msg = t('Centrar en tu ubicación'); + return ( + ); + } +} + +CenterInMyPosition.defaultProps = { + onlyIcon: false +}; + +CenterInMyPosition.propTypes = { + t: PropTypes.func.isRequired, + onlyIcon: PropTypes.bool +}; + +export default translate([], { wait: true })(CenterInMyPosition); diff --git a/imports/ui/components/CenterInMyPosition/CenterInMyPosition.scss b/imports/ui/components/CenterInMyPosition/CenterInMyPosition.scss new file mode 100644 index 0000000..f579e99 --- /dev/null +++ b/imports/ui/components/CenterInMyPosition/CenterInMyPosition.scss @@ -0,0 +1,9 @@ +i.location { + background: url(/my_location.svg) no-repeat top left; + background-size: contain; + cursor: pointer; + display: inline-block; + height: 30px; + width: 35px; + vertical-align: middle; +} diff --git a/imports/ui/components/Chronos/Chronos.js b/imports/ui/components/Chronos/Chronos.js new file mode 100644 index 0000000..6a96c31 --- /dev/null +++ b/imports/ui/components/Chronos/Chronos.js @@ -0,0 +1,122 @@ +// Adapted from: https://github.com/remcoder/chronos (MIT License) + +import { Meteor } from 'meteor/meteor'; +import { Tracker } from 'meteor/tracker'; +import { ReactiveVar } from 'meteor/reactive-var'; +import moment from 'moment'; + +const _timers = {}; + +function Timer(interval) { + this.interval = interval || 1000; + this.time = new ReactiveVar(0); +} + +Timer.prototype.start = function () { + if (this._timer) throw new Error('Trying to start Chronos.Timer but it is already running.'); + this.time.set(new Date()); + + + this._timer = setInterval(Meteor.bindEnvironment(() => { + // console.log('tick', this._timer); + this.time.set(new Date()); + }), this.interval); +}; + +Timer.prototype.stop = function () { + // console.log('stopping timer'); + clearInterval(this._timer); + this._timer = null; +}; + +function _update(interval) { + // get current reactive context + const comp = Tracker.currentComputation; + if (!comp) { return; } // no nothing when used outside a reactive context + + // only create one timer per reactive context to prevent stacking of timers + const cid = comp && comp._id; + if (!_timers[cid]) { + const timer = new Timer(interval); + _timers[cid] = timer; + + // add destroy method that stops the timer and removes itself from the list + timer.destroy = function () { + timer.stop(); + delete _timers[cid]; + }; + + timer.start(); + } + + // make sure to stop and delete the attached timer when the computation is stopped + comp.onInvalidate(() => { + // console.log('onInvalidated',comp); + if (comp.stopped && _timers[cid]) { + // console.log('computation stopped'); + _timers[cid].destroy(); + } + }); + + _timers[cid].time.dep.depend(comp); // make dependent on time + + // console.log(_timers); + return _timers[cid]; +} + +// reactive version of moment() +// please install moment separately +// example usage: Chronos.moment(someTimestamp).format('ss'); +function _moment(/* arguments */) { + if (!moment) throw new Error('moment not found. Please install it first'); + + _update(); + return moment(...arguments); +} + +// reactive version of new Date() get the current date/time +function _date(interval) { + _update(interval); + return new Date(); +} + +// reactive version of Date.now(). get the current # of milliseconds since the start of the epoch +function _now(interval) { + _update(interval); + return Date.now(); +} + +// export global +const Chronos = { + + // a simple reactive timer + // usage: var timer = new Timer(); + // get current time: timer.time.get(); + Timer, + + // handy util func for making reactive contexts live updating in time + // usage: simply call Chronos.update() in your helper to make it execute + // every interval + update: _update, + + // reactive version of new Date() get the current date/time + date: _date, + + // reactive version of Date.now(). get the current # of milliseconds since the start of the epoch + now: _now, + + // reactive version of moment() + // please install moment separately + // example usage: Chronos.moment(someTimestamp).format('ss'); + moment: _moment, + + // for debugging and testing + _timers, + + // deprecated. but kept for backwards compatibility + liveUpdate: _update, + currentTime: _date, + liveMoment: _moment +}; + +export default Chronos; diff --git a/imports/ui/components/Col/Col.js b/imports/ui/components/Col/Col.js new file mode 100644 index 0000000..2a20586 --- /dev/null +++ b/imports/ui/components/Col/Col.js @@ -0,0 +1,111 @@ +import classNames from 'classnames'; +import React from 'react'; +import PropTypes from 'prop-types'; +import elementType from 'prop-types-extra/lib/elementType'; + +import { bsClass, prefix, splitBsProps } from 'react-bootstrap/lib/utils/bootstrapUtils'; +import { DEVICE_SIZES } from 'react-bootstrap/lib/utils/StyleConfig'; + +const column = PropTypes.oneOfType([ + PropTypes.oneOf(['auto']), + PropTypes.number, +]); + +const propTypes = { + componentClass: elementType, + + /** + * The number of columns you wish to span + * + * for Extra small devices Phones (<576px) + * + * class-prefix `col-` + */ + xs: column, + + /** + * The number of columns you wish to span + * + * for Small devices Tablets (≥576px) + * + * class-prefix `col-sm-` + */ + sm: column, + + /** + * The number of columns you wish to span + * + * for Medium devices Desktops (≥768px) + * + * class-prefix `col-md-` + */ + md: column, + + /** + * The number of columns you wish to span + * + * for Large devices Desktops (≥992px) + * + * class-prefix `col-lg-` + */ + lg: column, + + /** + * The number of columns you wish to span + * + * for Large devices Desktops (≥1200px) + * + * class-prefix `col-xl-` + */ + xl: column, +}; + +const defaultProps = { + componentClass: 'div', +}; + +class Col extends React.Component { + render() { + const { componentClass: Component, className, ...props } = this.props; + const [bsProps, elementProps] = splitBsProps(props); + + const classes = []; + + DEVICE_SIZES.forEach((size) => { + const propValue = elementProps[size]; + + if (propValue == null) return; + + if (size === 'xs') { + // col and col-4 + classes.push(propValue === true ? + bsProps.bsClass : + prefix(bsProps, `${propValue}`), + ); + } else { + // col-md-3 + classes.push( + prefix(bsProps, `${size}-${propValue}`), + ); + } + + delete elementProps[size]; + }); + + if (!classes.length) { + classes.push(bsProps.bsClass); // plain 'col' + } + + return ( + + ); + } +} + +Col.propTypes = propTypes; +Col.defaultProps = defaultProps; + +export default bsClass('col', Col); diff --git a/imports/ui/components/DistanceSlider/DistanceSlider.js b/imports/ui/components/DistanceSlider/DistanceSlider.js new file mode 100644 index 0000000..f5d20f1 --- /dev/null +++ b/imports/ui/components/DistanceSlider/DistanceSlider.js @@ -0,0 +1,110 @@ +/* eslint-disable react/jsx-indent-props */ +/* eslint-disable import/no-absolute-path */ +import React from 'react'; +import PropTypes from 'prop-types'; +import { Trans, translate } from 'react-i18next'; +import Tooltip from 'rc-tooltip'; +import Slider from 'rc-slider'; +import 'rc-slider/assets/index.css'; +import './DistanceSlider.scss'; + +// https://www.npmjs.com/package/rc-slider +const createSliderWithTooltip = Slider.createSliderWithTooltip; +const Handle = Slider.Handle; + +const handle = (props) => { + const { + value, + dragging, + index, + ...restProps + } = props; + return ( + + + + ); +}; + +// https://github.com/react-component/slider/tree/master/examples +class DistanceSlider extends React.Component { + constructor(props) { + super(props); + this.state = { + value: 10 + }; + this.onSliderChange = this.onSliderChange.bind(this); + this.onAfterChange = this.onAfterChange.bind(this); + this.props.onChange(10); + } + + onSliderChange(value) { + // console.log(value); + this.setState({ + value + }); + this.props.onChange(value); + } + + onAfterChange(value) { + // console.log(`After change: ${value}`); //eslint-disable-line + this.props.onChange(value); + } + + render() { + return ( +
+

¿A que distancia a la redonda quieres recibir notificaciones de fuegos?

+ +
+ ); + } +} + +DistanceSlider.defaultProps = { + onChange: null +}; + +DistanceSlider.propTypes = { + onChange: PropTypes.func +}; + +export default translate([], { wait: true })(DistanceSlider); diff --git a/imports/ui/components/DistanceSlider/DistanceSlider.scss b/imports/ui/components/DistanceSlider/DistanceSlider.scss new file mode 100644 index 0000000..629b81f --- /dev/null +++ b/imports/ui/components/DistanceSlider/DistanceSlider.scss @@ -0,0 +1,17 @@ +@import '../../stylesheets/mixins'; + +.dist-slider { + width: 400px; + margin: 30px; +} + +@include breakpoint(mobile) { + .dist-slider { + width: 100%; + margin: 10px; + } + + .rc-slider { + margin: 0 0 0 -10px; + } +} \ No newline at end of file diff --git a/imports/ui/components/ErrorBoundary/ErrorBoundary.js b/imports/ui/components/ErrorBoundary/ErrorBoundary.js new file mode 100644 index 0000000..f57fe79 --- /dev/null +++ b/imports/ui/components/ErrorBoundary/ErrorBoundary.js @@ -0,0 +1,66 @@ +/* eslint-disable react/jsx-indent-props */ +/* eslint-disable import/no-absolute-path */ +/* eslint-disable import/no-absolute-path */ + +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; +import { Row, Col } from 'react-bootstrap'; +import ravenLogger from '/imports/startup/client/ravenLogger'; +import './ErrorBoundary.scss'; + +// https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html +class ErrorBoundary extends Component { + constructor(props) { + super(props); + this.state = { hasError: false }; + } + + componentDidCatch(error, info) { + // Display fallback UI + this.setState({ hasError: true }); + // You can also log the error to an error reporting service + // console.log(`typeof error ${typeof error}`); + // console.log(`typeof info ${typeof info}`); + ravenLogger.log(error, info); + // ravenLogger.log(info); + } + + render() { + const { + appName, title, subTitle, children + } = this.props; + if (this.state.hasError) { + // You can render any custom fallback UI + return ( +
+ + +

{appName}

+

{title}

+

{subTitle}

+ +
+
+ ); + } + return children; + } +} + +ErrorBoundary.propTypes = { + appName: PropTypes.string, + title: PropTypes.string, + subTitle: PropTypes.string, + children: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.node), + PropTypes.node + ]).isRequired +}; + +ErrorBoundary.defaultProps = { + appName: 'All Against the Fire!', + title: 'Upppps: Something has gone wrong', + subTitle: 'We are investigating the problem, try again in a while' +}; + +export default ErrorBoundary; diff --git a/imports/ui/components/ErrorBoundary/ErrorBoundary.scss b/imports/ui/components/ErrorBoundary/ErrorBoundary.scss new file mode 100644 index 0000000..225e4ca --- /dev/null +++ b/imports/ui/components/ErrorBoundary/ErrorBoundary.scss @@ -0,0 +1,10 @@ +.error-boundary { + background-image: url('/error-background.png'); + height: 100%; + min-height: 55vh; + margin: 40px 10px 10px 10px; +} + +.error-boundary > div > div > h4 { + line-height: 1.3em; +} diff --git a/imports/ui/components/Feedback/Feedback.js b/imports/ui/components/Feedback/Feedback.js new file mode 100644 index 0000000..bbcab29 --- /dev/null +++ b/imports/ui/components/Feedback/Feedback.js @@ -0,0 +1,141 @@ +/* eslint-disable react/jsx-indent-props */ +/* eslint-disable import/no-absolute-path */ +/* eslint-disable import/no-absolute-path */ + +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; +import { Meteor } from 'meteor/meteor'; +import { translate } from 'react-i18next'; +import { FormGroup, Button, FormControl } from 'react-bootstrap'; +import { Bert } from 'meteor/themeteorchef:bert'; +import { withTracker } from 'meteor/react-meteor-data'; +import { isHome } from '/imports/ui/components/Utils/location'; +import { testId } from '/imports/ui/components/Utils/TestUtils'; +import validate from '/imports/modules/validate'; + +import './Feedback.scss'; + +class Feedback extends Component { + constructor(props) { + super(props); + this.handleSubmit = this.handleSubmit.bind(this); + this.onTabClick = this.onTabClick.bind(this); + } + + componentDidMount() { + const component = this; + const { t } = this.props; + + validate(component.form, { + rules: { + email: { + required: true, + email: true + }, + feedbackText: { + required: true + } + }, + messages: { + feedbackText: { + required: t('Por favor, escribe aquí tu feedback...') + }, + email: { + required: t('Tu correo'), + email: t('¿Es correcto este correo?') + } + }, + submitHandler() { component.handleSubmit(); } + }); + } + + onTabClick() { + $('#feedback-form').toggle('slide'); + } + + handleSubmit() { + const email = this.email.value.trim(); + const feedbackText = this.feedbackText.value.trim(); + + Meteor.call('send-feedback', email, feedbackText, (error) => { + if (error) { + Bert.alert(error.reason, 'danger'); + } else { + this.form.reset(); + Bert.alert('Feedback recibido, gracias...', 'success'); + this.onTabClick(); + } + }); + } + + render() { + // console.log(`Render Feedback because isHome ${this.props.isHome}, email: '${this.props.emailAddress}'`); + const disabled = this.props.emailVerified && this.props.emailAddress; + const { t } = this.props; + return ( +
+ { !this.props.isHome && +
+
(this.formdiv = formdiv)} style={{ display: 'none' }} className="card"> +
(this.form = form)} + className="form card-body" + onSubmit={event => event.preventDefault()} + > + + (this.email = email)} + placeholder={t('Tu correo')} + key={disabled ? 'disabledEmail' : 'enabledEmail'} + disabled={disabled} + defaultValue={disabled ? this.props.emailAddress : ''} + type="email" + /> + + +