Compare commits
10 commits
e61a3a9bcb
...
c50690cc8a
| Author | SHA1 | Date | |
|---|---|---|---|
| c50690cc8a | |||
| 07993ffb91 | |||
| 2e298f9ee5 | |||
| 1ef0012af9 | |||
| bddfb392c1 | |||
| 9ff9abacc3 | |||
| f775d4ac26 | |||
| 8dead27d22 | |||
| 6b6f02d92d | |||
| bc778bfd97 |
58 changed files with 1534 additions and 7468 deletions
|
|
@ -30,7 +30,6 @@ audit-argument-checks@1.0.8
|
|||
ddp-rate-limiter@1.2.2
|
||||
dynamic-import@0.7.4
|
||||
static-html@1.4.0
|
||||
alexwine:bootstrap-4
|
||||
|
||||
gadicc:blaze-react-component # Add braze to react
|
||||
255kb:meteor-status # Connect status
|
||||
|
|
@ -45,9 +44,15 @@ ostrio:meteor-root
|
|||
aldeed:schema-deny
|
||||
dburles:collection-helpers
|
||||
reywood:publish-composite
|
||||
# Bootstrap CSS/JS now comes from the `bootstrap` npm package (BS5), imported in
|
||||
# imports/startup/client/index.js. The old alexwine:bootstrap-4 package (BS4 CSS +
|
||||
# jQuery + BS4 JS) was removed after the navbar/carousel/dropdown/feedback widgets
|
||||
# were migrated off jQuery.
|
||||
facts-base@1.0.2
|
||||
nspangler:autoreconnect
|
||||
quave:synced-cron
|
||||
# lmachens:kadira
|
||||
nimble:restivus@0.8.12
|
||||
underscore@1.6.4
|
||||
|
||||
meteortesting:mocha # test driver (see `npm test` / `npm run test-watch`)
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ accounts-password@3.0.3
|
|||
aldeed:collection2@4.2.0
|
||||
aldeed:schema-deny@4.0.2
|
||||
aldeed:simple-schema@1.13.1
|
||||
alexwine:bootstrap-4@4.1.0
|
||||
allow-deny@2.0.0
|
||||
audit-argument-checks@1.0.8
|
||||
autoupdate@2.0.0
|
||||
|
|
@ -60,6 +59,9 @@ logging@1.3.5
|
|||
mdg:geolocation@1.3.0
|
||||
meteor@2.0.2
|
||||
meteor-base@1.5.2
|
||||
meteortesting:browser-tests@1.8.0
|
||||
meteortesting:mocha@3.3.0
|
||||
meteortesting:mocha-core@8.2.0
|
||||
minifier-css@2.0.0
|
||||
minifier-js@3.0.1
|
||||
minimongo@2.0.2
|
||||
|
|
|
|||
|
|
@ -3,3 +3,5 @@ cucumber
|
|||
output.json
|
||||
# REST smoke-test harness runs standalone (Node), never as Meteor server code
|
||||
smoke
|
||||
# Ops/deploy scripts (p.ej. scripts/*.mongo.js usan el global `db` de mongosh, no de Meteor)
|
||||
scripts
|
||||
|
|
|
|||
84
PENDIENTE.md
84
PENDIENTE.md
|
|
@ -18,7 +18,7 @@ desarrollo (no en producción) y **bloquean el salto a React 19**. Estado:
|
|||
| react-bootstrap | 0.31 → 2 | ✅ hecho (CSS sigue en Bootstrap 4) |
|
||||
| reactstrap + 3 deps muertas | — | ✅ eliminadas (0 usos) |
|
||||
| react-router-dom | 4.2 → 6.30 | ✅ hecho (history 5, HOC `withRouterCompat`) |
|
||||
| **react-leaflet + leaflet** | 1.8/1.3 → 4/1.9 | ⏸️ **diferida** (mapa = feature central; 4 plugins v1-only sin equivalente v4; ver UPGRADE.md) |
|
||||
| react-leaflet + leaflet | 1.8/1.3 → 4.2/1.9 | ✅ hecho (Map→MapContainer, refs directas, useMap/useMapEvents; 4 plugins reimplementados: MapControl portal, GoogleMutantLayer, fullscreen, sleep/graphicscale vanilla; ver UPGRADE.md) |
|
||||
| **Bootstrap CSS/JS** | 4.1 → 5 | ⏸️ **diferida** (carrusel/navbar jQuery BS4; ver UPGRADE.md) |
|
||||
|
||||
Lo verificado en navegador tras cada lib: `/`, `/fires`, `/fire/archive/<hex>`,
|
||||
|
|
@ -28,40 +28,64 @@ parámetros por defecto; `UNSAFE_componentWillReceiveProps` (FromNow, FireStats,
|
|||
Fires, SelectionMap) → `getDerivedStateFromProps`/`componentDidUpdate`; Reconnect
|
||||
(banner Blaze `meteorStatus` con `findDOMNode`) → React nativo con
|
||||
`useTracker(Meteor.status)`; react-share 2→5 y react-progress-bar.js → progressbar.js
|
||||
(ambos tiraban `findDOMNode`/`defaultProps`). **Tras esto, la ÚNICA fuente de
|
||||
warnings en consola es react-leaflet + sus 4 plugins (diferida).** (Queda un
|
||||
`findDOMNode` menor solo en `/status`: el `<Blaze serverFacts>` de Status.js, página admin.)
|
||||
(ambos tiraban `findDOMNode`/`defaultProps`); y react-leaflet 1.8→4.2 (mapa central,
|
||||
4 plugins reimplementados). **Tras esto la consola tiene 0 warnings de React en las
|
||||
rutas principales** (verificado forzando re-render en / y /fires). Único resto para
|
||||
React 19: el `<Blaze serverFacts>` de Status.js (`findDOMNode`), solo en `/status` (admin).
|
||||
|
||||
---
|
||||
|
||||
## 2. Deuda funcional / de calidad de la web (independiente de prod)
|
||||
|
||||
- **Comentarios (feature React nueva): verificación manual en staging.** No la
|
||||
cubre el smoke. Probar en una página de fuego: publicar/editar/borrar,
|
||||
like/dislike, embed de imagen y YouTube, y el email a otros comentaristas.
|
||||
- **`FireContainer` usa `FiresCollection.findOne()` sin selector**
|
||||
(`imports/ui/pages/Fires/Fires.js`): puede devolver un doc de una suscripción
|
||||
previa. Endurecer filtrando por el `_id` de la URL. (Preexistente, no bloquea,
|
||||
pero conviene antes de prod.)
|
||||
- **Suite de tests sin runner.** El stack de test (meteortesting:mocha, chai…)
|
||||
se eliminó en la migración 2.x (arrastraba coffeescript que crasheaba el build).
|
||||
Quedan tests Jest en `test/` (`rest.test.js`, `email.test.js`, …) y
|
||||
`npm test → jest`, pero hay que **verificar/actualizar** que pasan sobre el
|
||||
código async de Meteor 3. Hoy la ÚNICA red automática es `smoke/`.
|
||||
- **Rate-limit de publications** pendiente (`imports/startup/server/api.js:18`).
|
||||
- **Google Maps** se carga sin `loading=async` (aviso de rendimiento); el loader
|
||||
`google-maps` npm es viejo → valorar el loader async moderno.
|
||||
- **i18n de cuentas (`meteor-accounts-t9n`, T9n):** paquete antiguo aún usado
|
||||
(Login, VerifyEmail, i18n). Verificar que funciona en Meteor 3; traducción
|
||||
gallega (gl) incompleta (varios TODO en `i18n.js`).
|
||||
- **Salto Bootstrap 4→5 (CSS/JS) pendiente:** react-bootstrap ya está en v2 y
|
||||
corre sobre el CSS Bootstrap 4 actual (`alexwine:bootstrap-4`) con un único
|
||||
shim `.form-label` en `forms.scss`. El salto a Bootstrap 5 npm está diferido
|
||||
porque el carrusel del home (`bootstrap-carousel-swipe`, jQuery/BS4) y el
|
||||
collapse del navbar dependen del JS jQuery de BS4 (`data-toggle`, `data-slide`).
|
||||
Al hacerlo: importar `bootstrap@5` SCSS+JS, reescribir el carrusel (BS5 trae
|
||||
swipe nativo → quitar el plugin), `data-toggle`→`data-bs-toggle`,
|
||||
`ml-auto`→`ms-auto`, revisar `new-age.scss`/`custom.scss`/`bootstrap-overrides.scss`.
|
||||
- **Comentarios (feature React nueva): verificación manual en staging.** El smoke
|
||||
no llega a la UI. Los **métodos** (insert/edit/remove/like/dislike) y el embed
|
||||
(`mediaAnalyzers`) ya están cubiertos por mocha (`test/server/comments.test.js`),
|
||||
pero quedan por probar a mano en una página de fuego:
|
||||
- publicar / editar / borrar un comentario (UI React)
|
||||
- like / dislike (toggle)
|
||||
- render del embed de imagen y de YouTube
|
||||
- email a otros comentaristas (`onCommentAdd.js`, entrega real de correo)
|
||||
- ✅ **`FireContainer` endurecido** (`imports/ui/pages/Fires/Fires.js`): el
|
||||
`findOne()` sin selector ahora se acota por el `_id` de la URL en la ruta
|
||||
`archive` (`new Meteor.Collection.ObjectID(id)`); en active/alert/hash cada
|
||||
publicación deja un único fire en minimongo, así que el read vacío es correcto.
|
||||
- ✅ **Suite de tests con runner (`meteortesting:mocha`).** `npm test` corre
|
||||
`meteor test … --driver-package meteortesting:mocha` (watch: `npm run test-watch`).
|
||||
Tests reescritos a `chai` + APIs async de Meteor 3 en `test/server/*.test.js`
|
||||
(server-only), incluyendo cobertura nueva de los métodos de comentarios. Jest y
|
||||
`rest.test.js` (ya cubierto por `smoke/`) eliminados. **36 passing.** Pendiente
|
||||
menor: portar los casos de token inválido (401/400) de `rest.test.js` al smoke.
|
||||
- ✅ **Rate-limit de publications** (`imports/startup/server/api.js`): reglas
|
||||
`type: 'subscription'` vía `rateLimitSubscriptions` — 5/1000ms en `fireFrom*` y
|
||||
`comments.forReference`; 10/1000ms en las subs geo (map pan/zoom).
|
||||
- ✅ **Google Maps con `loading=async`** (`imports/startup/client/Gkeys.js`):
|
||||
se envuelve `GoogleMapsLoader.createUrl` para añadir el parámetro (el paquete
|
||||
`google-maps` npm no expone hook). *Verificar en staging que el mapa carga y el
|
||||
aviso de consola desaparece.*
|
||||
- ✅ **`meteor-accounts-t9n` actualizado** a `^2.6.0` (es/en OK). El paquete sigue
|
||||
sin build gallego (`gl`), así que se mantiene el fallback gl→es documentado en
|
||||
`i18n.js`. Traducción gallega de la app (`gl/common.json`): 0 claves faltantes.
|
||||
- ✅ **Salto Bootstrap 4→5 (CSS/JS) hecho** — react-bootstrap v2 ahora corre sobre
|
||||
su CSS nativo (BS5). **Compila y arranca; falta SOLO verificación visual en
|
||||
staging** (BS4→5 cambia sutilezas de grid/gutters/tipografía en todas las páginas).
|
||||
- Widgets jQuery/BS4 migrados a React (los blockers): navbar collapse
|
||||
(`Navigation.js`/`NavItem.js`), carrusel del home (`Index.js` → `<Carousel>`,
|
||||
conserva `.lazy` vía `onSlide`), dropdowns de idioma/tipo (`Profile.js`/
|
||||
`Fires.js` → `<Dropdown>`), y toggle del feedback (`Feedback.js` → estado React).
|
||||
Deps `bootstrap-carousel-swipe` y `alexwine:bootstrap-4` eliminadas; jQuery
|
||||
global ya no se usa (solo `jquery`+`jquery-validation` vía npm en `validate.js`).
|
||||
- CSS: `bootstrap@5` npm importado en `imports/startup/client/index.js` (antes
|
||||
que `app.scss`, para que los overrides ganen). Renombres de utilidades:
|
||||
`ml-auto`→`ms-auto`, `float-right`→`float-end`, `btn-block`→`w-100`,
|
||||
`data-toggle`→`data-bs-toggle`, `sr-only`→`.visually-hidden` (shim).
|
||||
- **QA visual pendiente en staging (todas las páginas):** formularios (react-
|
||||
bootstrap ya emite markup BS5 → deberían mejorar), navbar, botones, modales,
|
||||
cards, grid/gutters, y los widgets migrados (menú móvil, carrusel, dropdowns,
|
||||
feedback). Alertas de `themeteorchef:bert` (comprobar que siguen bien sin el
|
||||
jQuery de alexwine).
|
||||
- Menor: `popper.js@1` en `package.json` es legacy sin uso (react-bootstrap trae
|
||||
`@popperjs/core@2`) → se puede quitar. El bloque `.form-label` de `forms.scss`
|
||||
ya es redundante (BS5 lo trae) salvo por el `display:block` explícito.
|
||||
- **Limpieza menor:** migración 217 `// TODO remove falsepositives lowercase
|
||||
collection`; `prerender.js` gating comentado; sección per-fire del sitemap
|
||||
eliminada (era código muerto tras `firesMapEnabled=false`).
|
||||
|
|
|
|||
|
|
@ -308,7 +308,7 @@ MONGO_CONTAINER=tcef-mongo7 MONGO_SHELL=mongosh MONGO_PORT=27019 ./smoke/smoke.s
|
|||
|
||||
| Dep | From | Target | Status |
|
||||
|---|---|---|---|
|
||||
| React / react-dom | 16.0 | 18 | ✅ done — 18.3.1 + createRoot. The peripheral react-* libs that only worked on 18 via legacy context are now all modernized (rows below) **except react-leaflet** (deferred). Our own React-19 blockers are also cleared: `defaultProps` on function components → default params; `UNSAFE_componentWillReceiveProps` → `getDerivedStateFromProps`/`componentDidUpdate`; the Blaze/findDOMNode `Reconnect` → native React; react-share 2→5 and react-progress-bar.js → progressbar.js (both dropped their findDOMNode/defaultProps). **Sole remaining console warnings are react-leaflet + its 4 plugins** — nothing else. |
|
||||
| React / react-dom | 16.0 | 18 | ✅ done — 18.3.1 + createRoot. The peripheral react-* libs that only worked on 18 via legacy context are now all modernized (rows below) **except react-leaflet** (deferred). Our own React-19 blockers are also cleared: `defaultProps` on function components → default params; `UNSAFE_componentWillReceiveProps` → `getDerivedStateFromProps`/`componentDidUpdate`; the Blaze/findDOMNode `Reconnect` → native React; react-share 2→5 and react-progress-bar.js → progressbar.js (both dropped their findDOMNode/defaultProps). react-leaflet 1.8→4.2 done too (row below). **Dev console is now 0 React warnings** on the main routes. The only React-19 leftover is the Blaze `serverFacts` on the /status admin page (findDOMNode via gadicc:blaze-react-component). |
|
||||
| react-share | 2.0 | 5.3 | ✅ done — v2 shipped function-component `defaultProps` (React-19 blocker). v5 is clean. Dropped the dead GooglePlus button (removed upstream in v4+); the other 6 share buttons are API-compatible. |
|
||||
| react-progress-bar.js | 0.2.3 | — (progressbar.js 1.1) | ✅ removed — the wrapper used the deprecated `findDOMNode`. `LoadingBar` now drives `progressbar.js` (its own underlying dep, promoted to direct) through a ref. |
|
||||
| gadicc:blaze-react-component (in Reconnect) | — | native React | ✅ Reconnect's Blaze `meteorStatus` bridge used `findDOMNode` and was always mounted → rewritten with `useTracker(Meteor.status)` + countdown effect, reusing 255kb:meteor-status's CSS. (Status.js's Blaze `serverFacts` kept — /status admin page only.) |
|
||||
|
|
@ -320,7 +320,7 @@ MONGO_CONTAINER=tcef-mongo7 MONGO_SHELL=mongosh MONGO_PORT=27019 ./smoke/smoke.s
|
|||
| react-meteor-data | 0.2.16 | 3.0.6 | ✅ done — 0.2.16 (React-15/16-era) looped `withTracker` on fire-detail pages under React 18 (never-ready → blank). `meteor add react-meteor-data@3.0.6`; no call-site changes (HOC API kept). Also dropped `tmeasday:check-npm-versions` (the constraint pinning 0.2.16). See section above. |
|
||||
| i18next | 10.5 | 23.16 | ✅ done — with react-i18next 14. `whitelist`→`supportedLngs`, added `compatibilityJSON: 'v3'` (our locale JSON uses natural-language keys + v3 `_plural` layout, not the v4 `_one`/`_other` suffixes), custom separators `ß`/`ð`/`đ` kept. `sendMissing`→`saveMissing`, missingKeyHandler signature is `(lngs, ns, key, fallbackValue)` now (array first). See react-i18next row. |
|
||||
| react-i18next | 7.4 | 14.1 | ✅ done — 48 `translate([], {wait:true})`/`translate()` HOCs → `withTranslation()`; `react.wait:true`→`react.useSuspense:false`. `<Trans>` unchanged (locale JSON already stores the indexed-tag format `<1><0>{{x}}</0></1>`). ReSendEmail: removed `<Interpolate>` (deleted in v10) → `<Trans i18nKey values={{email}}/>`, dropped the removed bare `t` export. This is what silenced the per-component `Translate`/`I18n` legacy-context console spam. Backends: xhr→`i18next-http-backend` (client), sync-fs→`i18next-fs-backend` (server); `i18next-localstorage-cache` dropped (was `enabled:false`); languagedetector 2→8. Browser-verified: es/en switch, `<Trans>` interpolation (`{{countTotal}}`+`<strong>`) renders on /fires. |
|
||||
| react-leaflet + leaflet | 1.8 / 1.3.1 | 4.x / 1.9 | ⏸️ **deferred as debt** (the one lib not modernized this pass). react-leaflet v4 is a ground-up hooks rewrite of the app's core feature (the fire map), and the migration is deeply entangled: (a) **4 unmaintained v1-only plugins with no v4 equivalent** — `react-leaflet-control` (custom map buttons, 3 maps), `react-leaflet-fullscreen`, `react-leaflet-google` (`GoogleLayer` base layers in DefMapLayers), `leaflet-sleep` (`sleep`/`wakeTime`… props on `<Map>`) — each needs a bespoke `createControlComponent`/`createLayerComponent`/googlemutant reimplementation; (b) the **controlled-viewport** pattern (`onViewportChanged` + `state.center/zoom` in FiresMap/SelectionMap) is gone in v4 (`MapContainer` center/zoom are initial-only; you drive it via a `useMap()` child); (c) `.leafletElement` refs in 6 files/13 sites (FiresMap, SelectionMap, SubscriptionsMap, Fires, SubsUnion) — v4 hands you the `L.Map`/layer directly with different timing; (d) `Leaflet.control.graphicScale().addTo(map)` + `subsUnion` reach into the raw map via the ref. **v1.8 works on React 18** (verified: all maps render), so this only blocks the eventual React 19 jump. Do it as its own focused project with heavy in-browser verification (drag markers, viewport-driven fire reload, fitBounds, layer switch, fullscreen, sleep, custom controls). Stays pinned at 1.8 until then. **After the rest of the front-end modernization + warning cleanup, react-leaflet + these 4 plugins are the SOLE remaining source of dev-console warnings** (legacy context on Map/LayersControl/TileLayer/Marker/CircleMarker/Circle/Tooltip and the plugins, plus `ReactDOM.render` from react-leaflet-control). |
|
||||
| react-leaflet + leaflet | 1.8 / 1.3.1 | 4.2.1 / 1.9.4 | ✅ done — the last and hardest lib; a ground-up hooks rewrite of the app's core map. `<Map>`→`<MapContainer>`; `.leafletElement` refs (6 files/13 sites) → the map/layer instances directly (via a `<MapReady>` child using `useMap`, and plain refs on Marker/Circle/GeoJSON); the controlled-viewport pattern (`onViewportChanged`+`state.center/zoom`) → `<MapEvents>` (`useMapEvents` moveend/zoomend) + imperative `setView`; `onClick`→`eventHandlers={{click}}`, path styling → `pathOptions`/`style`; `subsUnion` takes the `L.Map` directly. **The 4 v1-only plugins were reimplemented** with react-leaflet v4's factories / vanilla Leaflet plugins: `react-leaflet-control`→ in-repo `MapControl` (L.Control + createPortal), `react-leaflet-google`→ `GoogleMutantLayer` (`createLayerComponent` + `leaflet.gridlayer.googlemutant`; Google Maps API already loaded by Gkeys), `react-leaflet-fullscreen`→ `createControlComponent` + `leaflet.fullscreen`, `leaflet-sleep`/`leaflet-graphicscale` kept as vanilla (work on leaflet 1.9). Browser-verified: /fires (tiles, OSM+Google layer switch, custom control, fullscreen, graphic scale, pan/zoom→re-fetch pipeline, no NaN), fire detail (GeoJSON rect + fitBounds), home (all 3 maps coexist; SelectionMap draggable marker→updatePosition + distance circle). **Console now 0 warnings** across home/`/fires` (forced full re-render). REST smoke byte-identical. |
|
||||
| arkham:comments-ui | 1.4.x | — | ✅ replaced with in-repo React feature |
|
||||
| nimble:restivus | Atmosphere | vendored | ✅ local precompiled package, accounts-password 2.x |
|
||||
| maximum:server-transform, meteorhacks:zones, less, markdown, test stack | — | — | ✅ removed (dead/unused) |
|
||||
|
|
|
|||
163
docker-compose.staging.yml
Normal file
163
docker-compose.staging.yml
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
# Stack de STAGING de "Todos contra el fuego" para testfuegos.comunes.org.
|
||||
# Derivado de docker-compose.yml (validación local). Diferencias clave:
|
||||
# - web sirve en https://testfuegos.comunes.org (tras el proxy assange), puerto host 8004
|
||||
# - Mongo 7 AISLADO, sembrado con un volcado real de `fuegos` y contactos neutralizados
|
||||
# (NUNCA apunta al rsmain de producción)
|
||||
# - notificaciones en MODE=shadow / MATCHER_MODE=shadow: calcula y loguea, NO envía
|
||||
# - mailhog captura TODO el correo (nada sale a un SMTP real)
|
||||
# - node-red solo conversacional; si se prueba el bot, con un BOT DE PRUEBAS, nunca los reales
|
||||
#
|
||||
# Despliegue real: vía el role ansible roles/tcef_staging/ en el repo de Comunes
|
||||
# (~/proyectos/sync/comunes/shared-l2/ansible/). Este compose es la fuente que ese role monta.
|
||||
# Secretos: ./secrets/*.staging.* (gitignored). Uso: RUNBOOK.md.
|
||||
|
||||
name: tcef-staging
|
||||
|
||||
x-logging: &default-logging
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
services:
|
||||
mongo:
|
||||
image: mongo:7
|
||||
container_name: tcef-staging-mongo
|
||||
command: ["--replSet", "rs0", "--bind_ip_all"]
|
||||
volumes:
|
||||
- mongo-data:/data/db
|
||||
healthcheck:
|
||||
test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping').ok"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 20s
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
|
||||
# One-shot: inicia el replica set de un nodo y marca las migraciones a v18
|
||||
# (los datos reales llegan pre-migrados). Idéntico al compose de validación.
|
||||
mongo-init:
|
||||
image: mongo:7
|
||||
depends_on:
|
||||
mongo:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
entrypoint:
|
||||
- bash
|
||||
- -ec
|
||||
- |
|
||||
mongosh --host mongo --quiet --eval 'try { rs.status().ok } catch (e) { rs.initiate({_id: "rs0", members: [{_id: 0, host: "mongo:27017"}]}) }'
|
||||
for i in $$(seq 1 30); do
|
||||
state=$$(mongosh --host mongo --quiet --eval 'try { rs.isMaster().ismaster } catch (e) { false }')
|
||||
[ "$$state" = "true" ] && break
|
||||
sleep 1
|
||||
done
|
||||
mongosh --host mongo --quiet fuegos --eval 'db.migrations.replaceOne({_id: "control"}, {_id: "control", version: 18, locked: false}, {upsert: true})'
|
||||
echo "mongo-init: replica set + migrations OK"
|
||||
logging: *default-logging
|
||||
|
||||
web:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: tcef-web:meteor3
|
||||
container_name: tcef-staging-web
|
||||
depends_on:
|
||||
mongo-init:
|
||||
condition: service_completed_successfully
|
||||
environment:
|
||||
PORT: "3000"
|
||||
ROOT_URL: https://testfuegos.comunes.org
|
||||
MONGO_URL: mongodb://mongo:27017/fuegos?replicaSet=rs0
|
||||
METEOR_SETTINGS_FILE: /run/secrets/meteor-settings.json
|
||||
volumes:
|
||||
- ./secrets/meteor-settings.staging.json:/run/secrets/meteor-settings.json:ro
|
||||
# Solo el proxy (assange) llega a este puerto; se publica en la red interna del host.
|
||||
ports:
|
||||
- "8004:3000"
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
container_name: tcef-staging-redis
|
||||
command: ["redis-server", "--appendonly", "yes"]
|
||||
volumes:
|
||||
- redis-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 6
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
|
||||
notifications:
|
||||
build:
|
||||
context: ../tcef-notifications
|
||||
image: tcef-notifications:local
|
||||
container_name: tcef-staging-notifications
|
||||
depends_on:
|
||||
mongo-init:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_healthy
|
||||
# secrets/notifications.staging.env → MODE=shadow, MATCHER_MODE=shadow, sin FCM,
|
||||
# MAIL_URL=smtp://mailhog:1025. No envía nada a usuarios reales.
|
||||
env_file:
|
||||
- ./secrets/notifications.staging.env
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
|
||||
# Buzón SMTP de captura: TODO el correo (verificación/reset/notifs) aterriza aquí, nunca fuera.
|
||||
# UI web en 127.0.0.1:8025 (acceder por túnel SSH). SMTP interno en mailhog:1025.
|
||||
mailhog:
|
||||
image: mailhog/mailhog:latest
|
||||
container_name: tcef-staging-mailhog
|
||||
environment:
|
||||
MH_STORAGE: memory
|
||||
ports:
|
||||
- "127.0.0.1:8025:8025"
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
|
||||
node-red:
|
||||
image: nodered/node-red:4.0
|
||||
container_name: tcef-staging-node-red
|
||||
volumes:
|
||||
- nodered-data:/data
|
||||
ports:
|
||||
- "127.0.0.1:1880:1880"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO", "/dev/null", "http://127.0.0.1:1880/"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
|
||||
# Importador NASA FIRMS → escribe activefires en ESTE mongo (no en prod), alimentando el
|
||||
# matcher en shadow. No arranca con `up` (profile "importer"): lo dispara un systemd timer
|
||||
# del host cada 15 min con `docker compose run --rm importer`.
|
||||
# NOTA: requiere crear su Dockerfile en fires-csv-mongo-import/ (fase-3 §2). Hasta entonces,
|
||||
# este servicio queda declarado pero su build context debe completarse.
|
||||
importer:
|
||||
profiles: ["importer"]
|
||||
build:
|
||||
context: ../todos-contra-el-fuego/fires-csv-mongo-import
|
||||
image: tcef-nasa-importer:local
|
||||
container_name: tcef-staging-importer
|
||||
depends_on:
|
||||
mongo-init:
|
||||
condition: service_completed_successfully
|
||||
environment:
|
||||
MONGO_URL: mongodb://mongo:27017/fuegos?replicaSet=rs0
|
||||
restart: "no"
|
||||
logging: *default-logging
|
||||
|
||||
volumes:
|
||||
mongo-data:
|
||||
redis-data:
|
||||
nodered-data:
|
||||
|
|
@ -9,3 +9,15 @@ export default ({ methods, limit, timeRange }) => {
|
|||
}, limit, timeRange);
|
||||
}
|
||||
};
|
||||
|
||||
// Same idea for subscriptions. DDPRateLimiter matches subscribe calls only when
|
||||
// the rule pins `type: 'subscription'`, so this is a separate helper.
|
||||
export const rateLimitSubscriptions = ({ subscriptions, limit, timeRange }) => {
|
||||
if (Meteor.isServer) {
|
||||
DDPRateLimiter.addRule({
|
||||
type: 'subscription',
|
||||
name(name) { return subscriptions.indexOf(name) > -1; },
|
||||
connectionId() { return true; },
|
||||
}, limit, timeRange);
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -13,6 +13,11 @@ class GkeysC {
|
|||
// console.log(google.maps);
|
||||
GoogleMapsLoader.KEY = key;
|
||||
GoogleMapsLoader.LIBRARIES = ['places'];
|
||||
// The google-maps npm package (v3.2.1) builds the script URL without
|
||||
// `loading=async`, which Google now warns about. It exposes no hook for
|
||||
// extra params, so wrap createUrl to append it (no node_modules edit).
|
||||
const origCreateUrl = GoogleMapsLoader.createUrl;
|
||||
GoogleMapsLoader.createUrl = () => `${origCreateUrl()}&loading=async`;
|
||||
GoogleMapsLoader.load(() => {
|
||||
self.gmapkey.set(key);
|
||||
console.log('GMaps script just loaded');
|
||||
|
|
|
|||
|
|
@ -51,6 +51,8 @@ if (sendMissing && Meteor.isDevelopment) {
|
|||
}
|
||||
|
||||
function setT9(lang) {
|
||||
// meteor-accounts-t9n has no Galician build, so use Spanish for gl account
|
||||
// error messages (the closest shipped language). See common/i18n.js.
|
||||
if (lang === 'gl') {
|
||||
T9n.setLanguage('es');
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
/* global */
|
||||
// Bootstrap 5 CSS (npm) replaces the old `alexwine:bootstrap-4` meteor package.
|
||||
// Import it first so the app + component stylesheets below (and react-bootstrap,
|
||||
// which targets BS5) override it.
|
||||
import 'bootstrap/dist/css/bootstrap.css';
|
||||
import React from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { HelmetProvider } from 'react-helmet-async';
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@ 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
|
||||
// meteor-accounts-t9n (2.6.0) ships no Galician build (build/gl.js), so account
|
||||
// error messages fall back to Spanish for gl — see setT9() in client/i18n.js.
|
||||
// Re-enable this import if the upstream package ever adds a gl translation.
|
||||
// import gl from 'meteor-accounts-t9n/build/gl';
|
||||
|
||||
const backOpts = {
|
||||
|
|
|
|||
|
|
@ -15,8 +15,6 @@ 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';
|
||||
|
||||
|
|
@ -28,3 +26,26 @@ import '../../api/SiteSettings/server/publications';
|
|||
|
||||
import '../../api/FalsePositives/methods';
|
||||
import '../../api/FalsePositives/server/publications';
|
||||
|
||||
import { rateLimitSubscriptions } from '../../modules/rate-limit';
|
||||
|
||||
// Rate-limit the abusable publications (the old TODO above). Single-fire
|
||||
// lookups and the comments feed are cheap but brute-forceable, so keep them
|
||||
// tight; the geo subs fire on every map pan/zoom, so give them more headroom.
|
||||
rateLimitSubscriptions({
|
||||
subscriptions: [
|
||||
'fireFromHash', 'fireFromAlertId', 'fireFromActiveId', 'fireFromId',
|
||||
'comments.forReference'
|
||||
],
|
||||
limit: 5,
|
||||
timeRange: 1000
|
||||
});
|
||||
|
||||
rateLimitSubscriptions({
|
||||
subscriptions: [
|
||||
'activefiresmyloc', 'activefiresunionmyloc', 'fireAlerts',
|
||||
'falsePositivesMyloc', 'industriesMyloc'
|
||||
],
|
||||
limit: 10,
|
||||
timeRange: 1000
|
||||
});
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import './Feedback.scss';
|
|||
class Feedback extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = { open: false };
|
||||
this.handleSubmit = this.handleSubmit.bind(this);
|
||||
this.onTabClick = this.onTabClick.bind(this);
|
||||
}
|
||||
|
|
@ -50,7 +51,9 @@ class Feedback extends Component {
|
|||
}
|
||||
|
||||
onTabClick() {
|
||||
$('#feedback-form').toggle('slide');
|
||||
// Was `$('#feedback-form').toggle('slide')` — global jQuery from the BS4
|
||||
// meteor package. React state instead, so nothing depends on that global.
|
||||
this.setState(s => ({ open: !s.open }));
|
||||
}
|
||||
|
||||
handleSubmit() {
|
||||
|
|
@ -76,7 +79,7 @@ class Feedback extends Component {
|
|||
<div>
|
||||
{ !this.props.isHome &&
|
||||
<div id="feedback">
|
||||
<div id="feedback-form" ref={formdiv => (this.formdiv = formdiv)} style={{ display: 'none' }} className="card">
|
||||
<div id="feedback-form" ref={formdiv => (this.formdiv = formdiv)} style={{ display: this.state.open ? 'block' : 'none' }} className="card">
|
||||
<form
|
||||
ref={form => (this.form = form)}
|
||||
className="form card-body"
|
||||
|
|
@ -109,7 +112,7 @@ class Feedback extends Component {
|
|||
/>
|
||||
<Form.Control.Feedback />
|
||||
</Form.Group>
|
||||
<Button type="submit" variant="success" className="float-right" id={testId('sendFeedbackBtn')} >
|
||||
<Button type="submit" variant="success" className="float-end" id={testId('sendFeedbackBtn')} >
|
||||
{t('Enviar')}
|
||||
</Button>
|
||||
</form>
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ class FromNow extends Component {
|
|||
|
||||
render() {
|
||||
return (
|
||||
<span data-toggle="tooltip" className="from-now" title={this.thatIs()}>{this.state.when}</span>
|
||||
<span data-bs-toggle="tooltip" className="from-now" title={this.thatIs()}>{this.state.when}</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -88,7 +88,7 @@ class LocationAutocomplete extends React.Component {
|
|||
styles={myStyles}
|
||||
autocompleteItem={AutocompleteItem}
|
||||
classNames={{
|
||||
root: 'form-group',
|
||||
root: 'mb-3', // was BS4 `.form-group` (removed in BS5); mb-3 keeps the bottom margin
|
||||
input: 'form-control',
|
||||
autocompleteContainer: 'autocomplete-container'
|
||||
}}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
import React, { Component } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import { withTranslation } from 'react-i18next';
|
||||
import { GoogleLayer } from 'react-leaflet-google/lib/';
|
||||
import GoogleMutantLayer from '/imports/ui/components/Maps/GoogleMutantLayer';
|
||||
import Gkeys from '/imports/startup/client/Gkeys';
|
||||
import { TileLayer, LayersControl } from 'react-leaflet';
|
||||
|
||||
|
|
@ -54,15 +54,15 @@ class DefMapLayers extends Component {
|
|||
{/* React.Fragment does not work here */}
|
||||
{ this.state.gkey &&
|
||||
<BaseLayer name={t('Mapa de carreteras de Google')}>
|
||||
<GoogleLayer opacity={defOpacity} googlekey={this.state.gkey} maptype="ROADMAP" />
|
||||
<GoogleMutantLayer opacity={defOpacity} maptype="ROADMAP" />
|
||||
</BaseLayer> }
|
||||
{ this.state.gkey &&
|
||||
<BaseLayer name={t('Mapa de terreno de Google')} checked={this.props.terrain}>
|
||||
<GoogleLayer opacity={defOpacity} googlekey={this.state.gkey} maptype="TERRAIN" />
|
||||
<GoogleMutantLayer opacity={defOpacity} maptype="TERRAIN" />
|
||||
</BaseLayer> }
|
||||
{ this.state.gkey &&
|
||||
<BaseLayer name={t('Mapa de satélite de Google')} checked={this.props.satellite}>
|
||||
<GoogleLayer opacity={defOpacity} googlekey={this.state.gkey} maptype="SATELLITE" />
|
||||
<GoogleMutantLayer opacity={defOpacity} maptype="SATELLITE" />
|
||||
</BaseLayer> }
|
||||
</LayersControl>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ class FireCircleMark extends Component {
|
|||
} = this.props;
|
||||
const rect = rectangleAround({ lat, lon }, track, track);
|
||||
return (
|
||||
<GeoJSON data={rect} color="red" stroke width="1" opacity=".4" fillOpacity="1">
|
||||
<GeoJSON data={rect} style={{ color: 'red', stroke: true, weight: 1, opacity: 0.4, fillOpacity: 1 }}>
|
||||
<FirePopup t={t} history={history} id={id} nasa={nasa} lat={lat} lon={lon} when={when} />
|
||||
</GeoJSON>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -33,9 +33,9 @@ class FireIconMark extends Component {
|
|||
lat, lon, scan, track, nasa, id, history, falsePositives, industries, neighbour, when, t
|
||||
} = this.props;
|
||||
return (
|
||||
<div>
|
||||
<Fragment>
|
||||
{ !falsePositives && !industries &&
|
||||
<Marker position={[lat, lon]} icon={nasa ? this.getIcon(scan) : nFireIcon} onClick={this.onClick} >
|
||||
<Marker position={[lat, lon]} icon={nasa ? this.getIcon(scan) : nFireIcon} eventHandlers={{ click: this.onClick }} >
|
||||
<FirePopup t={t} history={history} id={id} nasa={nasa} lat={lat} lon={lon} when={when} />
|
||||
</Marker> }
|
||||
{ industries && <Marker position={[lat, lon]} icon={regIndustryIcon}>
|
||||
|
|
@ -43,23 +43,20 @@ class FireIconMark extends Component {
|
|||
</Marker> }
|
||||
{ /* disabled */ industries && false && <CircleMarker
|
||||
center={[lat, lon]}
|
||||
color="violet"
|
||||
stroke={false}
|
||||
fillOpacity="1"
|
||||
fill
|
||||
radius={1}
|
||||
pathOptions={{ color: 'violet', stroke: false, fillOpacity: 1, fill: true }}
|
||||
/>}
|
||||
{ falsePositives && !industries &&
|
||||
<Marker position={[lat, lon]} icon={industryIcon} onClick={this.onClick}>
|
||||
<Marker position={[lat, lon]} icon={industryIcon} eventHandlers={{ click: this.onClick }}>
|
||||
<Tooltip><Fragment>{t('Es una industria (fuente: nuestros usuarios/as)')}</Fragment></Tooltip>
|
||||
{ /* disabled because was a past fire (and can be marked multiple times) */ false && <FirePopup t={t} history={history} id={id} lat={lat} lon={lon} /> }
|
||||
</Marker>
|
||||
}
|
||||
{ !falsePositives && !industries &&
|
||||
<CircleMarker center={[lat, lon]} color={nasa ? 'red' : '#D35400'} stroke={false} fillOpacity="1" fill radius={1} onClick={this.onClick}>
|
||||
<CircleMarker center={[lat, lon]} radius={1} pathOptions={{ color: nasa ? 'red' : '#D35400', stroke: false, fillOpacity: 1, fill: true }} eventHandlers={{ click: this.onClick }}>
|
||||
<FirePopup t={t} history={history} id={id} nasa={nasa} lat={lat} lon={lon} when={when} />
|
||||
</CircleMarker> }
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,11 +12,8 @@ const FirePixel = ({
|
|||
}) => (
|
||||
<CircleMarker
|
||||
center={[lat, lon]}
|
||||
color={nasa ? 'red' : '#D35400'}
|
||||
stroke={false}
|
||||
fillOpacity="1"
|
||||
fill
|
||||
radius={nasa ? 1 : 2}
|
||||
pathOptions={{ color: nasa ? 'red' : '#D35400', stroke: false, fillOpacity: 1, fill: true }}
|
||||
>
|
||||
<FirePopup t={t} history={history} id={id} nasa={nasa} lat={lat} lon={lon} when={when} />
|
||||
</CircleMarker>
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ class FirePolygonMark extends Component {
|
|||
const lon = centerid.coordinates[0];
|
||||
const lat = centerid.coordinates[1];
|
||||
return (
|
||||
<GeoJSON data={shape} color="orange" stroke width="1" opacity=".2" fillOpacity=".0" />
|
||||
<GeoJSON data={shape} style={{ color: 'orange', stroke: true, weight: 1, opacity: 0.2, fillOpacity: 0 }} />
|
||||
);
|
||||
/* <FirePopup t={t} history={history} id={id} nasa={nasa} lat={lat} lon={lon} when={when} /> */
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +1,27 @@
|
|||
/* eslint-disable react/jsx-indent-props */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import React, { Component } from 'react';
|
||||
import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import { withTranslation } from 'react-i18next';
|
||||
import FullscreenControl from 'react-leaflet-fullscreen';
|
||||
import 'react-leaflet-fullscreen/dist/styles.css';
|
||||
import { createControlComponent } from '@react-leaflet/core';
|
||||
import L from 'leaflet';
|
||||
import 'leaflet.fullscreen';
|
||||
import 'leaflet.fullscreen/Control.FullScreen.css';
|
||||
|
||||
class FullScreenMap extends Component {
|
||||
render() {
|
||||
const { t } = this.props;
|
||||
return (
|
||||
<FullscreenControl
|
||||
position="topleft"
|
||||
title={t('Pantalla completa')}
|
||||
titleCancel={t('Salir de pantalla completa')}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
// Replacement for react-leaflet-fullscreen (v1-only): wrap the vanilla
|
||||
// leaflet.fullscreen control with react-leaflet v4's control factory.
|
||||
const FullscreenControl = createControlComponent(
|
||||
({ position = 'topleft', title, titleCancel }) => L.control.fullscreen({ position, title, titleCancel })
|
||||
);
|
||||
|
||||
const FullScreenMap = ({ t }) => (
|
||||
<FullscreenControl
|
||||
position="topleft"
|
||||
title={t('Pantalla completa')}
|
||||
titleCancel={t('Salir de pantalla completa')}
|
||||
/>
|
||||
);
|
||||
|
||||
FullScreenMap.propTypes = {
|
||||
t: PropTypes.func.isRequired
|
||||
|
|
|
|||
25
imports/ui/components/Maps/GoogleMutantLayer.js
Normal file
25
imports/ui/components/Maps/GoogleMutantLayer.js
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { createLayerComponent } from '@react-leaflet/core';
|
||||
import L from 'leaflet';
|
||||
import 'leaflet.gridlayer.googlemutant';
|
||||
|
||||
// Replacement for react-leaflet-google's GoogleLayer (v1-only). The Google Maps
|
||||
// JS API is already loaded (with the places library) by Gkeys before any Google
|
||||
// BaseLayer renders, so googlemutant can use window.google.maps directly.
|
||||
function createGoogleMutant({
|
||||
maptype = 'roadmap', opacity, googlekey, ...options
|
||||
}, ctx) {
|
||||
const instance = L.gridLayer.googleMutant({
|
||||
type: String(maptype).toLowerCase(),
|
||||
...(opacity != null ? { opacity } : {}),
|
||||
...options
|
||||
});
|
||||
return { instance, context: { ...ctx } };
|
||||
}
|
||||
|
||||
function updateGoogleMutant(instance, props, prevProps) {
|
||||
if (props.opacity != null && props.opacity !== prevProps.opacity) {
|
||||
instance.setOpacity(props.opacity);
|
||||
}
|
||||
}
|
||||
|
||||
export default createLayerComponent(createGoogleMutant, updateGoogleMutant);
|
||||
22
imports/ui/components/Maps/MapBridge.js
Normal file
22
imports/ui/components/Maps/MapBridge.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { useEffect } from 'react';
|
||||
import { useMap, useMapEvents } from 'react-leaflet';
|
||||
|
||||
// v4 replaces the v1 `ref`/`.leafletElement` + handleLeafletLoad pattern: this
|
||||
// child runs inside <MapContainer> and hands the ready Leaflet map to a class
|
||||
// parent once, so the parent can drive it imperatively (setView, fitBounds,
|
||||
// graphicScale, subsUnion, …).
|
||||
export const MapReady = ({ onReady }) => {
|
||||
const map = useMap();
|
||||
useEffect(() => {
|
||||
if (onReady) onReady(map);
|
||||
// run once per map instance
|
||||
}, [map]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return null;
|
||||
};
|
||||
|
||||
// Bridges Leaflet map events to callbacks (replaces the v1 onMoveend /
|
||||
// onViewportChanged / onZoomend props on <Map>).
|
||||
export const MapEvents = ({ handlers }) => {
|
||||
useMapEvents(handlers || {});
|
||||
return null;
|
||||
};
|
||||
32
imports/ui/components/Maps/MapControl.js
Normal file
32
imports/ui/components/Maps/MapControl.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { useMap } from 'react-leaflet';
|
||||
import L from 'leaflet';
|
||||
|
||||
// Replacement for react-leaflet-control (v1-only): mounts a Leaflet control at
|
||||
// the given corner and portals arbitrary React children into it. Click/scroll
|
||||
// on the control no longer pans/zooms the map underneath.
|
||||
const MapControl = ({ position = 'topright', children }) => {
|
||||
const map = useMap();
|
||||
const [container, setContainer] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
const ReactControl = L.Control.extend({
|
||||
onAdd: () => {
|
||||
const div = L.DomUtil.create('div', 'leaflet-control leaflet-control-react');
|
||||
L.DomEvent.disableClickPropagation(div);
|
||||
L.DomEvent.disableScrollPropagation(div);
|
||||
setContainer(div);
|
||||
return div;
|
||||
},
|
||||
onRemove: () => setContainer(null)
|
||||
});
|
||||
const control = new ReactControl({ position });
|
||||
control.addTo(map);
|
||||
return () => control.remove();
|
||||
}, [map, position]);
|
||||
|
||||
return container ? createPortal(children, container) : null;
|
||||
};
|
||||
|
||||
export default MapControl;
|
||||
|
|
@ -12,7 +12,8 @@ const subsUnion = (union, options) => {
|
|||
const interactive = options.interactive || false;
|
||||
|
||||
if (options.subs) {
|
||||
const lmap = options.map.leafletElement;
|
||||
// v4: options.map is the Leaflet map instance directly (no .leafletElement)
|
||||
const lmap = options.map;
|
||||
if (union) {
|
||||
lmap.removeLayer(union);
|
||||
}
|
||||
|
|
@ -30,7 +31,7 @@ const subsUnion = (union, options) => {
|
|||
if (options.fit && options.bounds) {
|
||||
// console.log(options.bounds);
|
||||
const bounds = JSON.parse(options.bounds);
|
||||
options.map.leafletElement.fitBounds(L.latLngBounds(bounds._northEast, bounds._southWest));
|
||||
lmap.fitBounds(L.latLngBounds(bounds._northEast, bounds._southWest));
|
||||
}
|
||||
} else if (options.subs.length > 0) {
|
||||
const result = calcUnion(L, options.subs, sub => sub, true);
|
||||
|
|
@ -43,7 +44,7 @@ const subsUnion = (union, options) => {
|
|||
});
|
||||
union.addTo(lmap);
|
||||
if (options.fit) {
|
||||
options.map.leafletElement.fitBounds(bounds);
|
||||
lmap.fitBounds(bounds);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@ import PropTypes from 'prop-types';
|
|||
|
||||
// Self-contained NavItem. The old one wrapped react-bootstrap 0.31's
|
||||
// `SafeAnchor` + `createChainedFunction` (both gone in v2); the markup this
|
||||
// navbar needs is just an <li><a> that toggles the collapsed menu on click.
|
||||
// navbar needs is just an <li><a>. The mobile menu is now collapsed from React
|
||||
// state in Navigation (the parent <ul onClick>), so the old jQuery
|
||||
// `data-toggle="collapse"` / `data-target` hooks were dropped here.
|
||||
const propTypes = {
|
||||
active: PropTypes.bool,
|
||||
disabled: PropTypes.bool,
|
||||
|
|
@ -57,8 +59,6 @@ class NavItem extends React.Component {
|
|||
return (
|
||||
<li
|
||||
role="presentation"
|
||||
data-toggle="collapse"
|
||||
data-target=".navbar-collapse.show"
|
||||
className={classNames(className, { active, disabled })}
|
||||
style={style}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -15,44 +15,51 @@ import './Navigation.scss';
|
|||
|
||||
// removed class: fixed-top
|
||||
// md instead of lg: no menu in medium
|
||||
const Navigation = ({ name = '', ...props }) => (
|
||||
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
|
||||
<div style={{ overflow: 'hidden' } /* for ribbon */} className="container">
|
||||
{/* <BetaRibbon /> */}
|
||||
<Link to="/" className={`navbar-brand ${window.location.pathname === '/' ? 'hide-brand' : ''}`} >
|
||||
{props.t('AppNameFull')}
|
||||
</Link>
|
||||
<button className="sr-only navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
|
||||
<span className="navbar-toggler-icon" />
|
||||
</button>
|
||||
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
|
||||
<span className="navbar-toggler-icon" />
|
||||
</button>
|
||||
{/* <Navbar.Collapse> */}
|
||||
<div className="collapse navbar-collapse" id="navbarNavDropdown">
|
||||
<ul className="navbar-nav ml-auto ">
|
||||
{/* <LinkContainer className="nav-item" anchorClassName="nav-link" to="/sandbox">
|
||||
<NavItem eventKey={1.1} href="/sandbox">Sandbox</NavItem>
|
||||
</LinkContainer> */}
|
||||
<LinkContainer id={testId('subscriptions')} className="nav-item" anchorClassName="nav-link" to="/subscriptions">
|
||||
<NavItem eventKey={1.2} href="/subscriptions">
|
||||
{props.authenticated ? <Trans>Mis zonas</Trans> : <Trans>Participar</Trans>}
|
||||
</NavItem>
|
||||
</LinkContainer>
|
||||
<LinkContainer id={testId('moniZones')} className="nav-item" anchorClassName="nav-link" to="/zones">
|
||||
<NavItem eventKey={2} href="/zones">{props.t('Zonas vigiladas')}</NavItem>
|
||||
</LinkContainer>
|
||||
<LinkContainer id={testId('activeFires')} className="nav-item" anchorClassName="nav-link" to="/fires">
|
||||
<NavItem eventKey={2.1} href="/fires">{props.t('activeFires')}</NavItem>
|
||||
</LinkContainer>
|
||||
//
|
||||
// Bootstrap 4→5 prep: the collapse used to be driven by Bootstrap's jQuery JS
|
||||
// (`data-toggle="collapse"`), which goes away when we drop `alexwine:bootstrap-4`
|
||||
// for `bootstrap@5`. Toggling the `.show` class from React state removes that
|
||||
// dependency and keeps working on the current BS4 CSS (`.collapse.show` is pure
|
||||
// CSS; jQuery only added the height animation). Clicking a nav link collapses the
|
||||
// mobile menu again — the old per-NavItem `data-target=".navbar-collapse.show"`.
|
||||
const Navigation = ({ name = '', ...props }) => {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const close = () => setOpen(false);
|
||||
return (
|
||||
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
|
||||
<div style={{ overflow: 'hidden' } /* for ribbon */} className="container">
|
||||
{/* <BetaRibbon /> */}
|
||||
<Link to="/" className={`navbar-brand ${window.location.pathname === '/' ? 'hide-brand' : ''}`} >
|
||||
{props.t('AppNameFull')}
|
||||
</Link>
|
||||
<button className="navbar-toggler" type="button" onClick={() => setOpen(o => !o)} aria-controls="navbarNavDropdown" aria-expanded={open} aria-label="Toggle navigation">
|
||||
<span className="navbar-toggler-icon" />
|
||||
</button>
|
||||
<div className={`collapse navbar-collapse${open ? ' show' : ''}`} id="navbarNavDropdown">
|
||||
{/* onClick closes the mobile menu when a main nav link is tapped */}
|
||||
<ul className="navbar-nav ms-auto " onClick={close}>
|
||||
{/* <LinkContainer className="nav-item" anchorClassName="nav-link" to="/sandbox">
|
||||
<NavItem eventKey={1.1} href="/sandbox">Sandbox</NavItem>
|
||||
</LinkContainer> */}
|
||||
<LinkContainer id={testId('subscriptions')} className="nav-item" anchorClassName="nav-link" to="/subscriptions">
|
||||
<NavItem eventKey={1.2} href="/subscriptions">
|
||||
{props.authenticated ? <Trans>Mis zonas</Trans> : <Trans>Participar</Trans>}
|
||||
</NavItem>
|
||||
</LinkContainer>
|
||||
<LinkContainer id={testId('moniZones')} className="nav-item" anchorClassName="nav-link" to="/zones">
|
||||
<NavItem eventKey={2} href="/zones">{props.t('Zonas vigiladas')}</NavItem>
|
||||
</LinkContainer>
|
||||
<LinkContainer id={testId('activeFires')} className="nav-item" anchorClassName="nav-link" to="/fires">
|
||||
<NavItem eventKey={2.1} href="/fires">{props.t('activeFires')}</NavItem>
|
||||
</LinkContainer>
|
||||
|
||||
</ul>
|
||||
{!props.authenticated ? <PublicNavigation /> : <AuthenticatedNavigation name={name} {...props} />}
|
||||
{/* </Navbar.Collapse> */}
|
||||
</ul>
|
||||
{!props.authenticated ? <PublicNavigation /> : <AuthenticatedNavigation name={name} {...props} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
</nav>
|
||||
);
|
||||
};
|
||||
|
||||
Navigation.propTypes = {
|
||||
t: PropTypes.func.isRequired,
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ const defaultCallback = (error) => {
|
|||
|
||||
const OAuthLoginButton = ({ service, callback = defaultCallback }) => (
|
||||
<button
|
||||
className={`btn btn-block btn-raised btn-danger OAuthLoginButton OAuthLoginButton-${service}`}
|
||||
className={`btn w-100 btn-raised btn-danger OAuthLoginButton OAuthLoginButton-${service}`}
|
||||
type="button"
|
||||
onClick={() => handleLogin(service, callback)}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
import React, { Component, Fragment } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { Map, Marker, CircleMarker, Circle, Tooltip } from 'react-leaflet';
|
||||
import { MapContainer, Marker, CircleMarker, Circle, Tooltip } from 'react-leaflet';
|
||||
import Leaflet from 'leaflet';
|
||||
import { withTranslation } from 'react-i18next';
|
||||
import { withTracker } from 'meteor/react-meteor-data';
|
||||
|
|
@ -18,7 +18,8 @@ import DefMapLayers from '/imports/ui/components/Maps/DefMapLayers';
|
|||
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css';
|
||||
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.js';
|
||||
import 'leaflet-sleep/Leaflet.Sleep.js';
|
||||
import Control from 'react-leaflet-control';
|
||||
import MapControl from '/imports/ui/components/Maps/MapControl';
|
||||
import { MapReady, MapEvents } from '/imports/ui/components/Maps/MapBridge';
|
||||
import { Row, Col, Button, ButtonGroup } from 'react-bootstrap';
|
||||
import subsUnion from '/imports/ui/components/Maps/SubsUnion/SubsUnion';
|
||||
import UserSubsToFiresCollection from '/imports/api/Subscriptions/Subscriptions';
|
||||
|
|
@ -51,13 +52,16 @@ class SelectionMap extends Component {
|
|||
this.fit = this.fit.bind(this);
|
||||
this.addScale = this.addScale.bind(this);
|
||||
this.onFstBtn = this.onFstBtn.bind(this);
|
||||
this.onViewportChanged = this.onViewportChanged.bind(this);
|
||||
this.onMapMove = this.onMapMove.bind(this);
|
||||
this.handleMapReady = this.handleMapReady.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
if (this.isValidState()) {
|
||||
this.addScale();
|
||||
}
|
||||
// v4: MapReady hands us the ready Leaflet map (replaces the componentDidMount
|
||||
// + ref/.leafletElement wiring)
|
||||
handleMapReady(map) {
|
||||
this.map = map;
|
||||
if (this.isValidState()) this.addScale();
|
||||
this.handleLeafletLoad(map);
|
||||
}
|
||||
|
||||
// Was UNSAFE_componentWillReceiveProps: pull center/distance from props into
|
||||
|
|
@ -75,6 +79,8 @@ class SelectionMap extends Component {
|
|||
marker: center[0] ? center : this.state.marker,
|
||||
distance: distance || this.state.distance
|
||||
});
|
||||
// v4 map is uncontrolled: move it imperatively on a real center change
|
||||
if (centerChanged && this.map) this.map.setView(center, this.state.zoom);
|
||||
}
|
||||
this.fit();
|
||||
}
|
||||
|
|
@ -90,7 +96,11 @@ class SelectionMap extends Component {
|
|||
this.props.onSndBtn();
|
||||
}
|
||||
|
||||
onViewportChanged(viewport) {
|
||||
// v4: fed by <MapEvents> on moveend/zoomend (was the v1 onViewportChanged prop)
|
||||
onMapMove() {
|
||||
if (!this.map) return;
|
||||
const c = this.map.getCenter();
|
||||
const viewport = { center: [c.lat, c.lng], zoom: this.map.getZoom() };
|
||||
if (this.props.onViewportChanged) {
|
||||
this.props.onViewportChanged(viewport);
|
||||
}
|
||||
|
|
@ -100,7 +110,7 @@ class SelectionMap extends Component {
|
|||
}
|
||||
|
||||
getMap() {
|
||||
return this.selectionMap.leafletElement;
|
||||
return this.map;
|
||||
}
|
||||
|
||||
toggleDraggable() {
|
||||
|
|
@ -108,7 +118,7 @@ class SelectionMap extends Component {
|
|||
}
|
||||
|
||||
updatePosition() {
|
||||
const { lat, lng } = this.marker.leafletElement.getLatLng();
|
||||
const { lat, lng } = this.marker.getLatLng();
|
||||
// console.log(`New marker lat ${lat} and lng ${lng}`);
|
||||
const currentDistance = this.state.distance;
|
||||
this.setState(update(this.state, { $merge: { marker: [lat, lng] } }));
|
||||
|
|
@ -122,10 +132,10 @@ class SelectionMap extends Component {
|
|||
// console.log("fit!");
|
||||
if (this.props.currentSubs.length > 0 && this.state.subsFit && this.props.action !== action.add) {
|
||||
// has autofit, do nothing
|
||||
} else if (this.selectionMap && this.distanceCircle) {
|
||||
if (!this.getMap().getBounds().contains(this.distanceCircle.leafletElement.getBounds())) {
|
||||
} else if (this.map && this.distanceCircle) {
|
||||
if (!this.getMap().getBounds().contains(this.distanceCircle.getBounds())) {
|
||||
// console.log('New area circle not visible');
|
||||
this.getMap().fitBounds(this.distanceCircle.leafletElement.getBounds()); // padding , [70, 70]);
|
||||
this.getMap().fitBounds(this.distanceCircle.getBounds()); // padding , [70, 70]);
|
||||
} else {
|
||||
// console.log('New area circle visible');
|
||||
}
|
||||
|
|
@ -133,7 +143,7 @@ class SelectionMap extends Component {
|
|||
}
|
||||
|
||||
addScale() {
|
||||
if (this.selectionMap) {
|
||||
if (this.map) {
|
||||
// https://www.npmjs.com/package/leaflet-graphicscale
|
||||
const map = this.getMap();
|
||||
const options = {
|
||||
|
|
@ -170,16 +180,10 @@ class SelectionMap extends Component {
|
|||
this.isValidState() ?
|
||||
<Row>
|
||||
<Col xs={12} sm={12} md={12} lg={12}>
|
||||
<Map
|
||||
ref={(map) => {
|
||||
this.selectionMap = map;
|
||||
this.handleLeafletLoad(map);
|
||||
}}
|
||||
<MapContainer
|
||||
zoom={this.state.zoom}
|
||||
center={this.state.center}
|
||||
className="selectionmap-leaflet-container"
|
||||
onViewportChanged={this.onViewportChanged}
|
||||
animate
|
||||
sleep={window.location.pathname === '/' && !isChrome}
|
||||
sleepTime={10750}
|
||||
wakeTime={750}
|
||||
|
|
@ -189,6 +193,8 @@ class SelectionMap extends Component {
|
|||
wakeMessageTouch={t('Pulsa para activar')}
|
||||
sleepOpacity={0.6}
|
||||
>
|
||||
<MapReady onReady={this.handleMapReady} />
|
||||
<MapEvents handlers={{ moveend: this.onMapMove, zoomend: this.onMapMove }} />
|
||||
<DefMapLayers osmcolor />
|
||||
{this.props.action === action.edit &&
|
||||
this.props.currentSubs.map((subs, index) => (
|
||||
|
|
@ -198,7 +204,7 @@ class SelectionMap extends Component {
|
|||
position={[subs.location.lat, subs.location.lon]}
|
||||
icon={removeIcon}
|
||||
title={t('Pulsa para borrar')}
|
||||
onClick={() => { onRemove(subs._id); }}
|
||||
eventHandlers={{ click: () => { onRemove(subs._id); } }}
|
||||
>
|
||||
{index === 0 &&
|
||||
<Tooltip
|
||||
|
|
@ -217,7 +223,7 @@ class SelectionMap extends Component {
|
|||
<Fragment>
|
||||
<Marker
|
||||
draggable={this.state.draggable}
|
||||
onDragend={this.updatePosition}
|
||||
eventHandlers={{ dragend: this.updatePosition }}
|
||||
position={this.state.marker}
|
||||
icon={positionIcon}
|
||||
title={t('Arrastrar para seleccionar otro punto')}
|
||||
|
|
@ -225,23 +231,18 @@ class SelectionMap extends Component {
|
|||
/>
|
||||
<CircleMarker
|
||||
center={this.state.marker}
|
||||
color="red"
|
||||
stroke={false}
|
||||
fillOpacity="1"
|
||||
fill
|
||||
radius={3}
|
||||
pathOptions={{ color: 'red', stroke: false, fillOpacity: 1, fill: true }}
|
||||
/>
|
||||
<Circle
|
||||
center={this.state.marker}
|
||||
ref={(ref) => { this.distanceCircle = ref; }}
|
||||
color="#145A32"
|
||||
fillColor="green"
|
||||
fillOpacity={0.1}
|
||||
pathOptions={{ color: '#145A32', fillColor: 'green', fillOpacity: 0.1 }}
|
||||
radius={this.state.distance * 1000}
|
||||
/>
|
||||
</Fragment>
|
||||
}
|
||||
<Control position="topright" >
|
||||
<MapControl position="topright" >
|
||||
<ButtonGroup>
|
||||
{ this.props.sndBtn && this.props.onSndBtn &&
|
||||
<Button
|
||||
|
|
@ -260,9 +261,9 @@ class SelectionMap extends Component {
|
|||
{this.props.fstBtn}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</Control>
|
||||
</MapControl>
|
||||
<FullScreenMap />
|
||||
</Map>
|
||||
</MapContainer>
|
||||
</Col>
|
||||
</Row>
|
||||
:
|
||||
|
|
|
|||
|
|
@ -6,11 +6,12 @@ import React, { Fragment } from 'react';
|
|||
import PropTypes from 'prop-types';
|
||||
import { withTracker } from 'meteor/react-meteor-data';
|
||||
import { withTranslation, Trans } from 'react-i18next';
|
||||
import { Row, Col, Alert, Form } from 'react-bootstrap';
|
||||
import { Row, Col, Alert, Form, Dropdown } from 'react-bootstrap';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { Bert } from 'meteor/themeteorchef:bert';
|
||||
import { Helmet } from 'react-helmet-async';
|
||||
import { Map, GeoJSON } from 'react-leaflet';
|
||||
import { MapContainer, GeoJSON } from 'react-leaflet';
|
||||
import { MapReady } from '/imports/ui/components/Maps/MapBridge';
|
||||
import { rectangleAround } from 'map-common-utils';
|
||||
import DefMapLayers from '/imports/ui/components/Maps/DefMapLayers';
|
||||
import NotFound from '/imports/ui/pages/NotFound/NotFound';
|
||||
|
|
@ -75,9 +76,15 @@ class Fire extends React.Component {
|
|||
});
|
||||
}
|
||||
|
||||
handleLeafletMapLoad(map) {
|
||||
if (map && map.leafletElement) {
|
||||
const lmap = map.leafletElement;
|
||||
// v4: MapReady hands us the ready Leaflet map directly (no ref/.leafletElement)
|
||||
handleMapReady(lmap) {
|
||||
this.fireMap = lmap;
|
||||
this.handleLeafletMapLoad(lmap);
|
||||
if (this.circle) lmap.fitBounds(this.circle.getBounds());
|
||||
}
|
||||
|
||||
handleLeafletMapLoad(lmap) {
|
||||
if (lmap) {
|
||||
const bounds = lmap.getBounds();
|
||||
const ne = bounds.getNorthEast();
|
||||
const sw = bounds.getSouthWest();
|
||||
|
|
@ -103,8 +110,9 @@ class Fire extends React.Component {
|
|||
}
|
||||
|
||||
handleLeafletCircleLoad(circle) {
|
||||
if (this.fireMap && this.fireMap.leafletElement && circle && circle.leafletElement) {
|
||||
this.fireMap.leafletElement.fitBounds(circle.leafletElement.getBounds());
|
||||
// v4: circle is the Leaflet GeoJSON layer; this.fireMap is the Leaflet map
|
||||
if (this.fireMap && circle) {
|
||||
this.fireMap.fitBounds(circle.getBounds());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -134,27 +142,17 @@ class Fire extends React.Component {
|
|||
{!loading &&
|
||||
<Fragment>
|
||||
<h4 className="page-header">{this.title}</h4>
|
||||
<Map
|
||||
ref={(map) => {
|
||||
this.fireMap = map;
|
||||
this.handleLeafletMapLoad(map);
|
||||
}}
|
||||
animate
|
||||
sleep={false}
|
||||
<MapContainer
|
||||
center={[fire.lat, fire.lon]}
|
||||
className="fire-leaflet-container"
|
||||
zoom={13}
|
||||
>
|
||||
<Fragment>
|
||||
<GeoJSON
|
||||
ref={(circle) => { this.circle = circle; this.handleLeafletCircleLoad(circle); }}
|
||||
data={rect}
|
||||
color="red"
|
||||
stroke
|
||||
width="1"
|
||||
fillOpacity="0.0"
|
||||
/>
|
||||
</Fragment>
|
||||
<MapReady onReady={map => this.handleMapReady(map)} />
|
||||
<GeoJSON
|
||||
ref={(circle) => { this.circle = circle; this.handleLeafletCircleLoad(circle); }}
|
||||
data={rect}
|
||||
style={{ color: 'red', stroke: true, weight: 1, fillOpacity: 0 }}
|
||||
/>
|
||||
<FireList
|
||||
t={t}
|
||||
history={this.props.history}
|
||||
|
|
@ -179,7 +177,7 @@ class Fire extends React.Component {
|
|||
/>
|
||||
<DefMapLayers satellite />
|
||||
<FullScreenMap />
|
||||
</Map>
|
||||
</MapContainer>
|
||||
<p>{t('Coordenadas:')} {fire.lat}, {fire.lon}</p>
|
||||
{(fire.type === 'modis' || fire.type === 'viirs') &&
|
||||
<Fragment>
|
||||
|
|
@ -206,24 +204,19 @@ class Fire extends React.Component {
|
|||
<Trans>Indícanos de que tipo de fuego se trata y ayúdanos así a mejorar nuestras notificaciones:</Trans>
|
||||
</div>
|
||||
<Form.Group>
|
||||
<div className="btn-group">
|
||||
<button className="btn btn-secondary btn-sm dropdown-toggle lang-selector" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
|
||||
<Dropdown className="btn-group">
|
||||
<Dropdown.Toggle variant="secondary" size="sm" className="lang-selector">
|
||||
{t('Elige un tipo')}
|
||||
</button>
|
||||
<div className="dropdown-menu">
|
||||
</Dropdown.Toggle>
|
||||
<Dropdown.Menu>
|
||||
{Object.keys(FalsePositiveTypes).map(key => (
|
||||
<button
|
||||
className="dropdown-item"
|
||||
onClick={() => this.onTypeSelect(key)}
|
||||
key={key}
|
||||
type="button"
|
||||
>
|
||||
<Trans>{FalsePositiveTypes[key]}</Trans>
|
||||
</button>
|
||||
<Dropdown.Item as="button" key={key} onClick={() => this.onTypeSelect(key)}>
|
||||
<Trans>{FalsePositiveTypes[key]}</Trans>
|
||||
</Dropdown.Item>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</Dropdown.Menu>
|
||||
</Dropdown>
|
||||
</Form.Group>
|
||||
</Fragment> }
|
||||
|
||||
|
|
@ -292,7 +285,22 @@ const FireContainer = withTracker(({ match }) => {
|
|||
// console.log(`Type of '${fireType}' fire, active: ${active}, archive: ${archive}, fromHash: ${fromHash}`);
|
||||
// console.log(`Subs ready: ${subscription.ready()}, fire: ${JSON.stringify(FiresCollection.findOne())}`);
|
||||
const loading = !subscription.ready();
|
||||
const notfound = !loading && FiresCollection.find().count() === 0;
|
||||
// Scope the client-side read to the fire named in the URL. Only the archive
|
||||
// route's param is a Fires `_id` (as 24-char hex, per hexId()); active/alert
|
||||
// params are ActiveFire/Alert ids and hash is an encrypted blob, so their
|
||||
// publications each put exactly one Fires doc in minimongo and an empty
|
||||
// selector is the correct read. Scoping archive by _id stops a lingering doc
|
||||
// from a previously-viewed fire being returned by a selector-less findOne().
|
||||
let selector = {};
|
||||
if (archive && id) {
|
||||
try {
|
||||
selector = new Meteor.Collection.ObjectID(id);
|
||||
} catch (e) {
|
||||
selector = {};
|
||||
}
|
||||
}
|
||||
const fire = FiresCollection.findOne(selector);
|
||||
const notfound = !loading && !fire;
|
||||
/* console.log(`loading fire: ${loading}`);
|
||||
* console.log(`Not found fire: ${notfound}`); */
|
||||
const falsePositives = FalsePositivesCollection.find().fetch().map(falsePositivesRemap);
|
||||
|
|
@ -304,9 +312,9 @@ const FireContainer = withTracker(({ match }) => {
|
|||
fromHash,
|
||||
falsePositives,
|
||||
industries,
|
||||
fire: FiresCollection.findOne(),
|
||||
fire,
|
||||
notfound,
|
||||
when: subscription.ready() && FiresCollection.findOne() ? FiresCollection.findOne().when : null
|
||||
when: fire ? fire.when : null
|
||||
};
|
||||
})(Fire);
|
||||
|
||||
|
|
|
|||
|
|
@ -11,8 +11,9 @@ import { withTracker } from 'meteor/react-meteor-data';
|
|||
import { Tracker } from 'meteor/tracker';
|
||||
import { Helmet } from 'react-helmet-async';
|
||||
import { Trans, withTranslation } from 'react-i18next';
|
||||
import { Map } from 'react-leaflet';
|
||||
import Control from 'react-leaflet-control';
|
||||
import { MapContainer } from 'react-leaflet';
|
||||
import MapControl from '/imports/ui/components/Maps/MapControl';
|
||||
import { MapReady, MapEvents } from '/imports/ui/components/Maps/MapBridge';
|
||||
import LoadingBar from '/imports/ui/components/Loading/LoadingBar';
|
||||
import _ from 'lodash';
|
||||
import store from 'store';
|
||||
|
|
@ -76,6 +77,24 @@ class FiresMap extends React.Component {
|
|||
this.onViewportChanged = this.onViewportChanged.bind(this);
|
||||
this.onMoveEnd = this.onMoveEnd.bind(this);
|
||||
this.onMoveStart = this.onMoveStart.bind(this);
|
||||
this.handleMoveEnd = this.handleMoveEnd.bind(this);
|
||||
this.handleMapReady = this.handleMapReady.bind(this);
|
||||
}
|
||||
|
||||
// v4: combined moveend/zoomend handler fed by <MapEvents> — clears the
|
||||
// moving flag and reports the new viewport (was the v1 onMoveend +
|
||||
// onViewportChanged props on <Map>).
|
||||
handleMoveEnd() {
|
||||
this.onMoveEnd();
|
||||
if (!this.map) return;
|
||||
const c = this.map.getCenter();
|
||||
this.onViewportChanged({ center: [c.lat, c.lng], zoom: this.map.getZoom() });
|
||||
}
|
||||
|
||||
// v4: MapReady hands us the ready Leaflet map (replaces ref/.leafletElement)
|
||||
handleMapReady(map) {
|
||||
this.map = map;
|
||||
this.handleLeafletLoad(map);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
|
|
@ -110,7 +129,7 @@ class FiresMap extends React.Component {
|
|||
}
|
||||
|
||||
getMap() {
|
||||
return this.fireMap.leafletElement;
|
||||
return this.map;
|
||||
}
|
||||
|
||||
setShowSubsUnion(showSubsUnion) {
|
||||
|
|
@ -124,7 +143,7 @@ class FiresMap extends React.Component {
|
|||
|
||||
handleViewportChange(viewport) {
|
||||
console.log(`Viewport changed: ${JSON.stringify(viewport)}`);
|
||||
if (this.fireMap) {
|
||||
if (this.map) {
|
||||
const bounds = this.getMap().getBounds();
|
||||
// console.log(bounds);
|
||||
mapSize.set([bounds.getNorthEast(), bounds.getSouthWest()]);
|
||||
|
|
@ -143,6 +162,8 @@ class FiresMap extends React.Component {
|
|||
|
||||
centerOnUserLocation(viewport) {
|
||||
this.setState({ viewport: { center: viewport.center, zoom: 10 } });
|
||||
// v4 map is uncontrolled: move it imperatively
|
||||
if (this.map) this.map.setView(viewport.center, 10);
|
||||
}
|
||||
|
||||
useMarkers(use) {
|
||||
|
|
@ -161,8 +182,8 @@ class FiresMap extends React.Component {
|
|||
}
|
||||
|
||||
handleLeafletLoad(map) {
|
||||
if (map && map.leafletElement && !this.state.moving) {
|
||||
const lmap = map.leafletElement;
|
||||
if (map && !this.state.moving) {
|
||||
const lmap = map;
|
||||
try {
|
||||
const bounds = lmap.getBounds();
|
||||
mapSize.set([bounds.getNorthEast(), bounds.getSouthWest()]);
|
||||
|
|
@ -266,24 +287,13 @@ class FiresMap extends React.Component {
|
|||
<LoadingBar progress={this.props.loading ? 0.9 : 1} />
|
||||
: ''}
|
||||
{/* https://github.com/CliffCloud/Leaflet.Sleep */}
|
||||
<Map
|
||||
ref={(map) => {
|
||||
this.fireMap = map;
|
||||
this.handleLeafletLoad(map);
|
||||
}}
|
||||
<MapContainer
|
||||
className="firesmap-leaflet-container"
|
||||
animate
|
||||
minZoom={5}
|
||||
center={this.state.viewport.center}
|
||||
zoom={this.state.viewport.zoom}
|
||||
preferCanvas
|
||||
viewport={this.state.viewport}
|
||||
onViewportChanged={this.onViewportChanged}
|
||||
sleep={isHome() && !isChrome}
|
||||
onMoveend={this.onMoveEnd}
|
||||
onMovestart={this.onMoveStart}
|
||||
onZoomend={this.onMoveEnd}
|
||||
onZoomstart={this.onMoveStart}
|
||||
sleepTime={10750}
|
||||
wakeTime={750}
|
||||
sleepNote
|
||||
|
|
@ -292,6 +302,14 @@ class FiresMap extends React.Component {
|
|||
wakeMessageTouch={this.props.t('Pulsa para activar')}
|
||||
sleepOpacity={0.6}
|
||||
>
|
||||
<MapReady onReady={this.handleMapReady} />
|
||||
<MapEvents handlers={{
|
||||
movestart: this.onMoveStart,
|
||||
zoomstart: this.onMoveStart,
|
||||
moveend: this.handleMoveEnd,
|
||||
zoomend: this.handleMoveEnd
|
||||
}}
|
||||
/>
|
||||
{/* http://wiki.openstreetmap.org/wiki/Tile_servers */}
|
||||
{!this.props.loading &&
|
||||
<Fragment>
|
||||
|
|
@ -349,13 +367,13 @@ class FiresMap extends React.Component {
|
|||
/>
|
||||
</Fragment> }
|
||||
<DefMapLayers gray />
|
||||
<Control position="topright" >
|
||||
<MapControl position="topright" >
|
||||
<ButtonGroup>
|
||||
<CenterInMyPosition onClick={viewport => this.centerOnUserLocation(viewport)} onlyIcon {... this.props} />
|
||||
</ButtonGroup>
|
||||
</Control>
|
||||
</MapControl>
|
||||
<FullScreenMap />
|
||||
</Map>
|
||||
</MapContainer>
|
||||
<Row>
|
||||
<Col xs={12} sm={12} md={12} lg={12}>
|
||||
<p className="firesmap-footnote"><span style={{ paddingRight: '5px' }}>(*)</span><Trans i18nKey="mapPrivacy" parent="span"><em>Para preservar la privacidad de nuestros usuarios/as, los datos reflejados están aleatoriamente alterados y son solo orientativos.</em></Trans></p>
|
||||
|
|
|
|||
|
|
@ -40,10 +40,47 @@
|
|||
height: 40px;
|
||||
}
|
||||
|
||||
// react-bootstrap v2 renders indicators as <button> (BS5 markup), not <li> (BS4),
|
||||
// so port the base "bar" look here — the BS4 CSS only styles <li>. The last two
|
||||
// rules are the original custom tweaks.
|
||||
.carousel-indicators button,
|
||||
.carousel-indicators li {
|
||||
box-sizing: content-box;
|
||||
flex: 0 1 auto;
|
||||
width: 30px;
|
||||
height: 5px;
|
||||
border-radius: 2px;
|
||||
padding: 0;
|
||||
margin-right: 3px;
|
||||
margin-left: 3px;
|
||||
text-indent: -999px;
|
||||
cursor: pointer;
|
||||
background-color: #fff;
|
||||
background-clip: padding-box;
|
||||
border: 0;
|
||||
border-top: 10px solid transparent;
|
||||
border-bottom: 10px solid transparent;
|
||||
border-radius: 2px;
|
||||
opacity: .5;
|
||||
transition: opacity .6s ease;
|
||||
}
|
||||
|
||||
.carousel-indicators .active {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
// BS5 renames BS4's `.sr-only` to `.visually-hidden`; react-bootstrap's carousel
|
||||
// prev/next labels use it. Shim it until the Bootstrap 5 CSS swap lands, else the
|
||||
// "Anterior"/"Siguiente" labels would render visible over the controls.
|
||||
.visually-hidden {
|
||||
position: absolute !important;
|
||||
width: 1px !important;
|
||||
height: 1px !important;
|
||||
padding: 0 !important;
|
||||
margin: -1px !important;
|
||||
overflow: hidden !important;
|
||||
clip: rect(0, 0, 0, 0) !important;
|
||||
white-space: nowrap !important;
|
||||
border: 0 !important;
|
||||
}
|
||||
|
||||
.carousel-snd-caption > h3,
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
/* eslint-disable import/no-absolute-path */
|
||||
/* eslint-disable react/jsx-indent-props */
|
||||
/* eslint-disable key-spacing */
|
||||
/* eslint-env jquery */
|
||||
import 'simple-line-icons/css/simple-line-icons.css';
|
||||
import React, { Component } from 'react';
|
||||
import { withTranslation, Trans } from 'react-i18next';
|
||||
import { Helmet } from 'react-helmet-async';
|
||||
import { Carousel } from 'react-bootstrap';
|
||||
import PropTypes from 'prop-types';
|
||||
// import { Link } from 'react-router-dom';
|
||||
// https://www.npmjs.com/package/react-resize-detector
|
||||
|
|
@ -13,7 +13,6 @@ import ReactResizeDetector from 'react-resize-detector';
|
|||
import MobileStoreButton from 'react-mobile-store-button';
|
||||
import _ from 'lodash';
|
||||
import 'html5-device-mockups/dist/device-mockups.min.css';
|
||||
import 'bootstrap-carousel-swipe/carousel-swipe';
|
||||
import { isAnyMobile } from '/imports/ui/components/Utils/isMobile';
|
||||
import SubscriptionEditor from '/imports/ui/components/SubscriptionEditor/SubscriptionEditor';
|
||||
import SubscriptionsMap from '/imports/ui/pages/Subscriptions/SubscriptionsMap';
|
||||
|
|
@ -30,32 +29,27 @@ class Index extends Component {
|
|||
constructor(props) {
|
||||
super(props);
|
||||
const self = this;
|
||||
// Progressive slide backgrounds: each carousel-item shows a blurred/low-res
|
||||
// bg until it becomes active, when the `.lazy` class swaps in the full image
|
||||
// (see Index-custom.scss). Was the jQuery `slide.bs.carousel` handler; now the
|
||||
// react-bootstrap <Carousel onSlide> marks the incoming index here.
|
||||
this.state = { mainLazy: {}, sndLazy: {} };
|
||||
this.myScaleFunction = _.debounce(() => {
|
||||
self.scaleHeader();
|
||||
}, 250);
|
||||
this.onResize = this.onResize.bind(this);
|
||||
this.getBotUrl = this.getBotUrl.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
const car1 = $('#carouselMainIndicators');
|
||||
const car2 = $('#carouselSndIndicators');
|
||||
car1.carousel();
|
||||
car2.carousel();
|
||||
/* _.defer(() => {
|
||||
$('#firsthomeslide').addClass('lazy');
|
||||
}); */
|
||||
const loadLazy = (ev) => {
|
||||
ev.relatedTarget.classList.add('lazy');
|
||||
};
|
||||
car1.on('slide.bs.carousel', loadLazy);
|
||||
car2.on('slide.bs.carousel', loadLazy);
|
||||
this.markLazy = this.markLazy.bind(this);
|
||||
}
|
||||
|
||||
onResize() {
|
||||
this.myScaleFunction();
|
||||
}
|
||||
|
||||
markLazy(which, index) {
|
||||
this.setState(s => ({ [which]: { ...s[which], [index]: true } }));
|
||||
}
|
||||
|
||||
getMap(isMobile, props) {
|
||||
if (!isMobile) {
|
||||
return (
|
||||
|
|
@ -112,67 +106,51 @@ class Index extends Component {
|
|||
<section className="sect1">
|
||||
<header>
|
||||
<ReactResizeDetector handleWidth handleHeight onResize={this.onResize} />
|
||||
<div
|
||||
<Carousel
|
||||
id="carouselMainIndicators"
|
||||
className="carousel slide"
|
||||
ref={(ref) => { this.slides = ref; }}
|
||||
className="slide"
|
||||
onSlide={index => this.markLazy('mainLazy', index)}
|
||||
prevLabel={t('Anterior')}
|
||||
nextLabel={t('Siguiente')}
|
||||
>
|
||||
{/* for dev ^^^: data-interval=false */}
|
||||
<ol className="carousel-indicators">
|
||||
<li key="sl1-1" data-target="#carouselMainIndicators" data-slide-to="0" className="active" />
|
||||
<li key="sl1-2" data-target="#carouselMainIndicators" data-slide-to="1" />
|
||||
<li key="sl1-3" data-target="#carouselMainIndicators" data-slide-to="2" />
|
||||
<li key="sl1-4" data-target="#carouselMainIndicators" data-slide-to="3" />
|
||||
</ol>
|
||||
<div className="carousel-inner" role="listbox">
|
||||
|
||||
<div id="firsthomeslide" className="carousel-item carousel-item-1 active">
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
className="slide-1-icon"
|
||||
onKeyDown={() => { this.gotoParticipe(); }}
|
||||
onClick={() => { this.gotoParticipe(); }}
|
||||
/>
|
||||
<div className="carousel-caption">
|
||||
<h3><Trans>Elige un lugar</Trans></h3>
|
||||
<p />
|
||||
</div>
|
||||
<Carousel.Item id="firsthomeslide" className="carousel-item-1">
|
||||
<div
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
className="slide-1-icon"
|
||||
onKeyDown={() => { this.gotoParticipe(); }}
|
||||
onClick={() => { this.gotoParticipe(); }}
|
||||
/>
|
||||
<div className="carousel-caption">
|
||||
<h3><Trans>Elige un lugar</Trans></h3>
|
||||
<p />
|
||||
</div>
|
||||
</Carousel.Item>
|
||||
|
||||
<div className="carousel-item carousel-item-2">
|
||||
<div className="slide-2-icon" />
|
||||
<div className="carousel-caption">
|
||||
<h3><Trans>Elige un radio de vigilancia</Trans></h3>
|
||||
<p />
|
||||
</div>
|
||||
<Carousel.Item className={`carousel-item-2${this.state.mainLazy[1] ? ' lazy' : ''}`}>
|
||||
<div className="slide-2-icon" />
|
||||
<div className="carousel-caption">
|
||||
<h3><Trans>Elige un radio de vigilancia</Trans></h3>
|
||||
<p />
|
||||
</div>
|
||||
</Carousel.Item>
|
||||
|
||||
<div className="carousel-item carousel-item-3">
|
||||
<div className="slide-3-icon" />
|
||||
<div className="carousel-caption">
|
||||
<h3><Trans>Recibe alertas de fuegos en esa zona</Trans></h3>
|
||||
<p />
|
||||
</div>
|
||||
<Carousel.Item className={`carousel-item-3${this.state.mainLazy[2] ? ' lazy' : ''}`}>
|
||||
<div className="slide-3-icon" />
|
||||
<div className="carousel-caption">
|
||||
<h3><Trans>Recibe alertas de fuegos en esa zona</Trans></h3>
|
||||
<p />
|
||||
</div>
|
||||
</Carousel.Item>
|
||||
|
||||
<div className="carousel-item carousel-item-4">
|
||||
<div className="slide-4-icon" />
|
||||
<div className="carousel-caption">
|
||||
<h3><Trans>Alerta cuando hay un fuego</Trans></h3>
|
||||
<p />
|
||||
</div>
|
||||
<Carousel.Item className={`carousel-item-4${this.state.mainLazy[3] ? ' lazy' : ''}`}>
|
||||
<div className="slide-4-icon" />
|
||||
<div className="carousel-caption">
|
||||
<h3><Trans>Alerta cuando hay un fuego</Trans></h3>
|
||||
<p />
|
||||
</div>
|
||||
</div>
|
||||
<a className="carousel-control-prev" href="#carouselMainIndicators" role="button" data-slide="prev">
|
||||
<span className="carousel-control-prev-icon" aria-hidden="true" />
|
||||
<span className="sr-only"><Trans>Anterior</Trans></span>
|
||||
</a>
|
||||
<a className="carousel-control-next" href="#carouselMainIndicators" role="button" data-slide="next">
|
||||
<span className="carousel-control-next-icon" aria-hidden="true" />
|
||||
<span className="sr-only"><Trans>Siguiente</Trans></span>
|
||||
</a>
|
||||
</div>
|
||||
</Carousel.Item>
|
||||
</Carousel>
|
||||
</header>
|
||||
<section className="py-5">
|
||||
<div className="container">
|
||||
|
|
@ -208,46 +186,32 @@ class Index extends Component {
|
|||
</div>
|
||||
</section>
|
||||
|
||||
<div
|
||||
<Carousel
|
||||
id="carouselSndIndicators"
|
||||
className="carousel slide"
|
||||
ref={(ref) => { this.slidesSnd = ref; }}
|
||||
className="slide"
|
||||
onSlide={index => this.markLazy('sndLazy', index)}
|
||||
prevLabel={t('Anterior')}
|
||||
nextLabel={t('Siguiente')}
|
||||
>
|
||||
{/* for dev ^^^: data-interval=false */}
|
||||
<ol className="carousel-indicators">
|
||||
<li key="sl2-1" data-target="#carouselSndIndicators" data-slide-to="0" className="active" />
|
||||
<li key="sl2-2" data-target="#carouselSndIndicators" data-slide-to="1" />
|
||||
</ol>
|
||||
<div className="carousel-inner" role="listbox">
|
||||
|
||||
<div className="carousel-item carousel-snd-item carousel-snd-item-1 active">
|
||||
<div className="carousel-caption carousel-snd-caption">
|
||||
<h3><Trans i18nKey="CO2emisions">¿Sabías que los fuegos <a href="https://www.livescience.com/1981-wildfires-release-cars.html" target="_blank">producen tanto CO² como los coches</a> y <a href="https://www.motherjones.com/politics/2014/08/wild-fires-are-so-so-bad-climate/" target="_blank">aproximadamente ⅕ de todas nuestras emisiones</a>?</Trans></h3>
|
||||
<p />
|
||||
<div className="row slides-footer">
|
||||
<p className="text-muted"><a href="https://commons.wikimedia.org/wiki/File:La_Tuna_fire_and_cityscape_1.jpg" target="_blank"><Trans>Fuego en La Tuna, Los Ángeles, Estados Unidos, septiembre de 2017</Trans></a></p>
|
||||
</div>
|
||||
<Carousel.Item className="carousel-snd-item carousel-snd-item-1">
|
||||
<div className="carousel-caption carousel-snd-caption">
|
||||
<h3><Trans i18nKey="CO2emisions">¿Sabías que los fuegos <a href="https://www.livescience.com/1981-wildfires-release-cars.html" target="_blank">producen tanto CO² como los coches</a> y <a href="https://www.motherjones.com/politics/2014/08/wild-fires-are-so-so-bad-climate/" target="_blank">aproximadamente ⅕ de todas nuestras emisiones</a>?</Trans></h3>
|
||||
<p />
|
||||
<div className="row slides-footer">
|
||||
<p className="text-muted"><a href="https://commons.wikimedia.org/wiki/File:La_Tuna_fire_and_cityscape_1.jpg" target="_blank"><Trans>Fuego en La Tuna, Los Ángeles, Estados Unidos, septiembre de 2017</Trans></a></p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="carousel-item carousel-snd-item carousel-snd-item-2">
|
||||
<div className="carousel-caption carousel-snd-caption">
|
||||
<h3><Trans>Ayúdanos a combatir el cambio climático y a proteger el medioambiente</Trans></h3>
|
||||
<p />
|
||||
<div className="row slides-footer">
|
||||
<p className="text-muted"><a href="https://commons.wikimedia.org/wiki/File:Smog_over_Almaty.jpg" target="_blank"><Trans>Polución en la ciudad de Almaty, Kazakhstan, enero de 2014</Trans></a></p>
|
||||
</div>
|
||||
</Carousel.Item>
|
||||
<Carousel.Item className={`carousel-snd-item carousel-snd-item-2${this.state.sndLazy[1] ? ' lazy' : ''}`}>
|
||||
<div className="carousel-caption carousel-snd-caption">
|
||||
<h3><Trans>Ayúdanos a combatir el cambio climático y a proteger el medioambiente</Trans></h3>
|
||||
<p />
|
||||
<div className="row slides-footer">
|
||||
<p className="text-muted"><a href="https://commons.wikimedia.org/wiki/File:Smog_over_Almaty.jpg" target="_blank"><Trans>Polución en la ciudad de Almaty, Kazakhstan, enero de 2014</Trans></a></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<a className="carousel-control-prev" href="#carouselSndIndicators" role="button" data-slide="prev">
|
||||
<span className="carousel-control-prev-icon" aria-hidden="true" />
|
||||
<span className="sr-only"><Trans>Anterior</Trans></span>
|
||||
</a>
|
||||
<a className="carousel-control-next" href="#carouselSndIndicators" role="button" data-slide="next">
|
||||
<span className="carousel-control-next-icon" aria-hidden="true" />
|
||||
<span className="sr-only"><Trans>Siguiente</Trans></span>
|
||||
</a>
|
||||
</div>
|
||||
</Carousel.Item>
|
||||
</Carousel>
|
||||
|
||||
<a id="participe" name="participe" />
|
||||
<section className="sect4">
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import { Row, Form, Button } from 'react-bootstrap';
|
||||
import { Row, Form, Button, Dropdown } from 'react-bootstrap';
|
||||
import _ from 'lodash';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { Accounts } from 'meteor/accounts-base';
|
||||
|
|
@ -200,24 +200,19 @@ class Profile extends React.Component {
|
|||
</Form.Group>
|
||||
<Form.Group>
|
||||
<Form.Label>{this.t('Idioma')}</Form.Label>
|
||||
<div className="btn-group">
|
||||
<button className="btn btn-secondary btn-sm dropdown-toggle lang-selector" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
|
||||
<Dropdown className="btn-group">
|
||||
<Dropdown.Toggle variant="secondary" size="sm" className="lang-selector">
|
||||
{langName[i18n.language]}
|
||||
</button>
|
||||
<div className="dropdown-menu">
|
||||
</Dropdown.Toggle>
|
||||
<Dropdown.Menu>
|
||||
{enabledLangs.map(lang => (
|
||||
<button
|
||||
className="dropdown-item"
|
||||
onClick={() => this.onLangSelect(lang)}
|
||||
key={lang}
|
||||
type="button"
|
||||
>
|
||||
<Dropdown.Item as="button" key={lang} onClick={() => this.onLangSelect(lang)}>
|
||||
{langName[lang]}
|
||||
</button>
|
||||
</Dropdown.Item>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</Dropdown.Menu>
|
||||
</Dropdown>
|
||||
<InputHint><i className="fa fa-language"></i> <a href="https://translate.comunes.org/projects/todos-contra-el-fuego/" rel="noopener noreferrer" target="_blank">{this.t('Puedes participar en las traducciones')}</a></InputHint>
|
||||
</Form.Group>
|
||||
<Form.Group>
|
||||
|
|
|
|||
|
|
@ -132,7 +132,7 @@ class Signup extends React.Component {
|
|||
{ Meteor.settings.public.telegramAuth &&
|
||||
<Col xs={12}>
|
||||
<button
|
||||
className="btn btn-block btn-raised btn-primary OAuthLoginButtonDis OAuthLoginButton-telegram"
|
||||
className="btn w-100 btn-raised btn-primary OAuthLoginButtonDis OAuthLoginButton-telegram"
|
||||
type="button"
|
||||
onClick={this.onTelegramAuth}
|
||||
>
|
||||
|
|
|
|||
|
|
@ -8,14 +8,15 @@ import { Button, ButtonGroup, Row, Col } from 'react-bootstrap';
|
|||
import { Meteor } from 'meteor/meteor';
|
||||
import { withTracker } from 'meteor/react-meteor-data';
|
||||
import { Trans, withTranslation } from 'react-i18next';
|
||||
import { Map } from 'react-leaflet';
|
||||
import { MapContainer } from 'react-leaflet';
|
||||
import { Helmet } from 'react-helmet-async';
|
||||
import L from 'leaflet';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css';
|
||||
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.js';
|
||||
import 'leaflet-sleep/Leaflet.Sleep.js';
|
||||
import Control from 'react-leaflet-control';
|
||||
import MapControl from '/imports/ui/components/Maps/MapControl';
|
||||
import { MapReady } from '/imports/ui/components/Maps/MapBridge';
|
||||
import CenterInMyPosition from '/imports/ui/components/CenterInMyPosition/CenterInMyPosition';
|
||||
import subsUnion from '/imports/ui/components/Maps/SubsUnion/SubsUnion';
|
||||
import DefMapLayers from '/imports/ui/components/Maps/DefMapLayers';
|
||||
|
|
@ -39,16 +40,27 @@ class SubscriptionsMap extends React.Component {
|
|||
},
|
||||
init: true
|
||||
};
|
||||
this.handleMapReady = this.handleMapReady.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
if (this.subscriptionsMap) {
|
||||
this.addScale();
|
||||
// The `subs-public-union` doc (~2.2MB) usually arrives via DDP *after* the map
|
||||
// is ready, so the one-shot MapReady draw runs with `userSubs` still null.
|
||||
// Redraw the union (and fit bounds on first real data) whenever it changes.
|
||||
componentDidUpdate(prevProps) {
|
||||
if (this.map && this.props.userSubs && this.props.userSubs !== prevProps.userSubs) {
|
||||
this.handleLeafletLoad(this.map);
|
||||
}
|
||||
}
|
||||
|
||||
getMap() {
|
||||
return this.subscriptionsMap.leafletElement;
|
||||
return this.map;
|
||||
}
|
||||
|
||||
// v4: <MapReady> hands us the ready Leaflet map (no ref/.leafletElement)
|
||||
handleMapReady(map) {
|
||||
this.map = map;
|
||||
this.addScale();
|
||||
this.handleLeafletLoad(map);
|
||||
}
|
||||
|
||||
addScale() {
|
||||
|
|
@ -63,7 +75,7 @@ class SubscriptionsMap extends React.Component {
|
|||
|
||||
handleLeafletLoad(map) {
|
||||
// console.log('Map loading');
|
||||
if (map && this.props.userSubs !== 'null') {
|
||||
if (map && this.props.userSubs && this.props.userSubs !== 'null') {
|
||||
// console.log(`Union of ${this.props.userSubs}`);
|
||||
this.state.union = subsUnion(this.state.union, {
|
||||
map,
|
||||
|
|
@ -71,14 +83,19 @@ class SubscriptionsMap extends React.Component {
|
|||
bounds: this.props.userSubsBounds,
|
||||
fromServer: true,
|
||||
show: true,
|
||||
fit: this.state.init
|
||||
// Only auto-fit to the union the first time we draw it with real data
|
||||
// (and never once the user has recentred), so later reactive updates
|
||||
// don't steal the current view. `fitDone` is a plain instance flag.
|
||||
fit: this.state.init && !this.fitDone
|
||||
});
|
||||
this.fitDone = true;
|
||||
}
|
||||
}
|
||||
|
||||
centerOnUserLocation(viewport) {
|
||||
console.log(`viewport: ${JSON.stringify(viewport)}`);
|
||||
this.setState({ init: false, viewport });
|
||||
// v4 map is uncontrolled: move it imperatively
|
||||
if (this.map) this.map.setView(viewport.center, viewport.zoom);
|
||||
}
|
||||
|
||||
gotoParticipe() {
|
||||
|
|
@ -112,15 +129,10 @@ class SubscriptionsMap extends React.Component {
|
|||
<Trans>En verde, las zonas vigiladas por nuestros usuari@s actualmente</Trans> (*)
|
||||
</Row>
|
||||
</Col>
|
||||
<Map
|
||||
ref={(map) => {
|
||||
this.subscriptionsMap = map;
|
||||
this.handleLeafletLoad(map);
|
||||
}}
|
||||
<MapContainer
|
||||
zoom={this.state.viewport.zoom}
|
||||
center={this.state.viewport.center}
|
||||
className="subscriptionsmap-leaflet-container"
|
||||
animate
|
||||
sleep={window.location.pathname === '/' && !isChrome}
|
||||
sleepTime={10750}
|
||||
wakeTime={750}
|
||||
|
|
@ -130,8 +142,9 @@ class SubscriptionsMap extends React.Component {
|
|||
wakeMessageTouch={this.props.t('Pulsa para activar')}
|
||||
sleepOpacity={0.6}
|
||||
>
|
||||
<MapReady onReady={this.handleMapReady} />
|
||||
<DefMapLayers gray />
|
||||
<Control position="topright" >
|
||||
<MapControl position="topright" >
|
||||
<ButtonGroup>
|
||||
<CenterInMyPosition onClick={viewport => this.centerOnUserLocation(viewport)} onlyIcon {... this.props} />
|
||||
<Button
|
||||
|
|
@ -141,9 +154,9 @@ class SubscriptionsMap extends React.Component {
|
|||
{this.props.t('Participa')}
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</Control>
|
||||
</MapControl>
|
||||
<FullScreenMap />
|
||||
</Map>
|
||||
</MapContainer>
|
||||
<Row>
|
||||
<Col xs={12} sm={12} md={12} lg={12}>
|
||||
<p className="subscriptionsmap-footnote"><span style={{ paddingRight: '5px' }}>(*)</span><Trans i18nKey="mapPrivacy" parent="span"><em>Para preservar la privacidad de nuestros usuarios/as, los datos reflejados están aleatoriamente alterados y son solo orientativos.</em></Trans></p>
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
@use './mixins' as *;
|
||||
@use './colors' as *;
|
||||
|
||||
// react-bootstrap v2 emits Bootstrap 5 form markup (`.form-label`) while we
|
||||
// still ship the Bootstrap 4 stylesheet (alexwine:bootstrap-4), which has no
|
||||
// `.form-label`. Shim it until the Bootstrap 4 -> 5 CSS jump lands (tracked as
|
||||
// debt in UPGRADE.md). v2's Form.Group is a plain div, so restore the old
|
||||
// per-field bottom margin the removed `.form-group` used to give.
|
||||
// Bootstrap 5 now provides `.form-label` natively, so this is no longer a shim —
|
||||
// we keep it only for the explicit `display: block` (v2's Form.Group is a plain
|
||||
// div and some fields render the label inline otherwise). The bottom margin
|
||||
// matches BS5's own `.form-label`.
|
||||
.form-label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
|
|
|
|||
6609
package-lock.json
generated
6609
package-lock.json
generated
File diff suppressed because it is too large
Load diff
23
package.json
23
package.json
|
|
@ -3,7 +3,8 @@
|
|||
"private": true,
|
||||
"scripts": {
|
||||
"start": "QT_QPA_PLATFORM='' MONGO_URL=mongodb://fuegos:fuegos@localhost:27017/fuegos meteor --settings settings-development.json",
|
||||
"test": "jest"
|
||||
"test": "meteor test --once --driver-package meteortesting:mocha --settings settings-development.json --port 3100",
|
||||
"test-watch": "TEST_WATCH=1 meteor test --driver-package meteortesting:mocha --settings settings-development.json --port 3100"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.29.7",
|
||||
|
|
@ -13,7 +14,7 @@
|
|||
"@turf/buffer": "^5.1.5",
|
||||
"babel-runtime": "^6.26.0",
|
||||
"bcrypt": "^5.1.1",
|
||||
"bootstrap-carousel-swipe": "0.0.6",
|
||||
"bootstrap": "^5.3.8",
|
||||
"commonmark": "^0.28.1",
|
||||
"core-js": "^2.5.1",
|
||||
"crypto-random-hex": "^1.0.0",
|
||||
|
|
@ -36,14 +37,16 @@
|
|||
"jquery-validation": "^1.17.0",
|
||||
"jsend": "^1.0.2",
|
||||
"juice": "^4.2.2",
|
||||
"leaflet": "^1.3.1",
|
||||
"leaflet": "^1.9.4",
|
||||
"leaflet-graphicscale": "0.0.2",
|
||||
"leaflet-sleep": "^0.5.1",
|
||||
"leaflet.fullscreen": "^3.0.2",
|
||||
"leaflet.gridlayer.googlemutant": "^0.14.1",
|
||||
"lodash": "^4.17.4",
|
||||
"loms.perlin": "^1.0.1",
|
||||
"map-common-utils": "^0.5.0",
|
||||
"maxmind": "^2.3.0",
|
||||
"meteor-accounts-t9n": "^2.0.3",
|
||||
"meteor-accounts-t9n": "^2.6.0",
|
||||
"meteor-node-stubs": "^0.3.2",
|
||||
"modernizr": "^3.6.0",
|
||||
"moment": "^2.19.1",
|
||||
|
|
@ -53,7 +56,6 @@
|
|||
"nodemailer": "^6.10.1",
|
||||
"npm": "^5.8.0",
|
||||
"pm2-master": "^1.1.3",
|
||||
"popper.js": "^1.12.7",
|
||||
"prerender-node": "^2.7.4",
|
||||
"progressbar.js": "^1.1.1",
|
||||
"prop-types": "^15.6.0",
|
||||
|
|
@ -66,10 +68,7 @@
|
|||
"react-dom": "^18.3.1",
|
||||
"react-helmet-async": "^2.0.5",
|
||||
"react-i18next": "^14.1.3",
|
||||
"react-leaflet": "^1.8.0",
|
||||
"react-leaflet-control": "^1.4.0",
|
||||
"react-leaflet-fullscreen": "0.0.6",
|
||||
"react-leaflet-google": "^3.2.1",
|
||||
"react-leaflet": "^4.2.1",
|
||||
"react-mobile-store-button": "0.0.3",
|
||||
"react-places-autocomplete": "^5.4.3",
|
||||
"react-resize-detector": "^1.1.0",
|
||||
|
|
@ -82,11 +81,8 @@
|
|||
"twit": "^2.2.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"babel-jest": "^21.2.0",
|
||||
"babel-plugin-lodash": "^3.2.11",
|
||||
"babel-preset-env": "^1.6.1",
|
||||
"babel-preset-react": "^6.24.1",
|
||||
"enzyme": "^3.1.0",
|
||||
"chai": "^4.5.0",
|
||||
"eslint": "^4.10.0",
|
||||
"eslint-config-airbnb": "^16.1.0",
|
||||
"eslint-import-resolver-meteor": "^0.4.0",
|
||||
|
|
@ -94,7 +90,6 @@
|
|||
"eslint-plugin-jsx-a11y": "^6.0.2",
|
||||
"eslint-plugin-meteor": "^4.1.6",
|
||||
"eslint-plugin-react": "^7.4.0",
|
||||
"jest": "^21.2.1",
|
||||
"sass": "^1.101.0"
|
||||
},
|
||||
"eslintConfig": {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
{
|
||||
"fireDetected": "lume detectado {{when}}",
|
||||
"fireDetectedAt": "lume detectado o {{when}}",
|
||||
"Alerta de fuego": "Alerta de lume",
|
||||
"Actualizado <1></1>.": "Actualizado <1></1>.",
|
||||
"Actualizando...": "Actualizando...",
|
||||
"Sí": "Si",
|
||||
"No": "Non",
|
||||
"AppName": "Tod@s contra o Lume",
|
||||
|
|
|
|||
161
scripts/neutralize-contacts.mongo.js
Normal file
161
scripts/neutralize-contacts.mongo.js
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
// Neutraliza los datos de contacto en un volcado REAL de `fuegos` restaurado en el
|
||||
// Mongo 7 de STAGING, para que ninguna notificación pueda alcanzar a un usuario real.
|
||||
// IDEMPOTENTE: se puede ejecutar varias veces sin efectos acumulativos indeseados.
|
||||
//
|
||||
// Uso (desde el host de staging, contra el contenedor del compose):
|
||||
// docker exec -i tcef-staging-mongo mongosh --quiet fuegos < scripts/neutralize-contacts.mongo.js
|
||||
//
|
||||
// SEGURIDAD: ejecutar SOLO contra el Mongo aislado de staging. Aborta si detecta que la
|
||||
// conexión no es la esperada (heurística: nombre de host contiene 'shiva'/'simone'/'rbg'/'rosaparks').
|
||||
|
||||
(function guardAgainstProd() {
|
||||
try {
|
||||
const host = db.getMongo().host || '';
|
||||
const prod = /shiva|simone|rbg|rosaparks|rsmain/i;
|
||||
if (prod.test(host)) {
|
||||
throw new Error('ABORTADO: la conexión (' + host + ') parece de PRODUCCIÓN. Este script solo debe correr contra el Mongo de staging.');
|
||||
}
|
||||
} catch (e) {
|
||||
if (/ABORTADO/.test(e.message)) { print(e.message); quit(1); }
|
||||
}
|
||||
})();
|
||||
|
||||
const dbx = db.getSiblingDB('fuegos');
|
||||
|
||||
// 1) users.emails[].address -> "<_id>@invalid.test" (único por usuario) + verified:false
|
||||
const rEmails = dbx.users.updateMany(
|
||||
{ emails: { $type: 'array', $ne: [] } },
|
||||
[{
|
||||
$set: {
|
||||
emails: {
|
||||
$map: {
|
||||
input: '$emails',
|
||||
as: 'e',
|
||||
in: {
|
||||
address: { $concat: [{ $toString: '$_id' }, '@invalid.test'] },
|
||||
verified: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}]
|
||||
);
|
||||
|
||||
// 2) users: purgar tokens/handles de notificación (FCM y Telegram)
|
||||
const rUserTokens = dbx.users.updateMany(
|
||||
{}, { $unset: {
|
||||
fireBaseToken: '',
|
||||
telegramChatId: '',
|
||||
telegramUsername: '',
|
||||
telegramFirstName: '',
|
||||
telegramLanguageCode: ''
|
||||
}}
|
||||
);
|
||||
|
||||
// 3) users.services.google.email -> invalidar (evita PII en OAuth); conservar el resto de services
|
||||
const rGoogle = dbx.users.updateMany(
|
||||
{ 'services.google.email': { $exists: true } },
|
||||
[{ $set: { 'services.google.email': { $concat: [{ $toString: '$_id' }, '@invalid.test'] } } }]
|
||||
);
|
||||
|
||||
// 3b) users.services.google: purgar CREDENCIALES VIVAS y nombre/foto reales.
|
||||
// accessToken/refreshToken/idToken son credenciales OAuth que dan acceso a la cuenta
|
||||
// de Google REAL del usuario — lo más grave del volcado. name/given_name/family_name/
|
||||
// picture/id son PII directa. (El paso 3 solo invalidaba el email.)
|
||||
const rGoogleCreds = dbx.users.updateMany(
|
||||
{ 'services.google': { $exists: true } },
|
||||
{ $unset: {
|
||||
'services.google.accessToken': '',
|
||||
'services.google.refreshToken': '',
|
||||
'services.google.idToken': '',
|
||||
'services.google.expiresAt': '',
|
||||
'services.google.scope': '',
|
||||
'services.google.id': '',
|
||||
'services.google.name': '',
|
||||
'services.google.given_name': '',
|
||||
'services.google.family_name': '',
|
||||
'services.google.picture': '',
|
||||
'services.google.locale': '',
|
||||
'services.google.gender': ''
|
||||
}}
|
||||
);
|
||||
|
||||
// 3c) users.profile.name -> nombres y apellidos REALES (first/last). Se vacía el subdoc.
|
||||
const rProfile = dbx.users.updateMany(
|
||||
{ 'profile.name': { $exists: true } },
|
||||
{ $unset: { 'profile.name.first': '', 'profile.name.last': '', 'profile.email': '' } }
|
||||
);
|
||||
|
||||
// 3d) users.services.resume.loginTokens -> tokens de SESIÓN vivos (permiten suplantar
|
||||
// al usuario sin contraseña). Se vacía el array. Idem verificationTokens de email.
|
||||
const rTokens = dbx.users.updateMany(
|
||||
{ $or: [ { 'services.resume.loginTokens.0': { $exists: true } },
|
||||
{ 'services.email.verificationTokens.0': { $exists: true } } ] },
|
||||
{ $set: { 'services.resume.loginTokens': [], 'services.email.verificationTokens': [] } }
|
||||
);
|
||||
|
||||
// NOTA (decisión consciente, NO es un olvido): `services.password.bcrypt` se CONSERVA.
|
||||
// Son hashes bcrypt (no reversibles directamente) y son la única forma de hacer QA de
|
||||
// login en staging — no hay cuenta de fixtures en el volcado real. Si se quisiera cerrar
|
||||
// también ese vector, hay que crear antes una cuenta de pruebas dedicada.
|
||||
|
||||
// 4) subscriptions: quitar el destino de Telegram (chatId) de las subs de ese tipo
|
||||
const rSubs = dbx.subscriptions.updateMany(
|
||||
{ chatId: { $exists: true } }, { $unset: { chatId: '' } }
|
||||
);
|
||||
|
||||
// 5) Cola de Mail-Time: el volcado de prod trae correos ya encolados con el
|
||||
// DESTINATARIO real "horneado" (p.ej. de 2020). Neutralizar users.emails NO los
|
||||
// toca; la web (isMailServer) los drenaría. Se vacían las colas de la cola/jobs.
|
||||
// (En staging MAIL_URL apunta a Mailhog, así que aunque quedaran, se capturarían;
|
||||
// esto es defensa en profundidad para no arrastrar direcciones reales.)
|
||||
const rMailQueue = dbx.getCollection('__mailTimeQueue__').deleteMany({});
|
||||
const rMailJobs = dbx.getCollection('__JobTasks__mailTimeQueue').deleteMany({});
|
||||
|
||||
printjson({
|
||||
usersEmailsNeutralizados: rEmails.modifiedCount,
|
||||
usersTokensPurgados: rUserTokens.modifiedCount,
|
||||
googleEmailsInvalidados: rGoogle.modifiedCount,
|
||||
googleCredsPurgadas: rGoogleCreds.modifiedCount,
|
||||
profileNombresPurgados: rProfile.modifiedCount,
|
||||
tokensSesionPurgados: rTokens.modifiedCount,
|
||||
subsChatIdEliminados: rSubs.modifiedCount,
|
||||
colaCorreoBorrada: rMailQueue.deletedCount,
|
||||
colaJobsBorrada: rMailJobs.deletedCount
|
||||
});
|
||||
|
||||
// Verificación rápida (debe dar 0 en todas). OJO: filtrar por $exists ANTES del
|
||||
// $not/regex — si no, los usuarios SIN email cuentan como "no invalidados" (falso positivo).
|
||||
const conToken = dbx.users.countDocuments({ fireBaseToken: { $exists: true } });
|
||||
const emailMalo = dbx.users.countDocuments({ 'emails.address': { $exists: true, $not: /@invalid\.test$/ } });
|
||||
const googleMalo = dbx.users.countDocuments({ 'services.google.email': { $exists: true, $not: /@invalid\.test$/ } });
|
||||
const subsConChat = dbx.subscriptions.countDocuments({ chatId: { $exists: true } });
|
||||
const colaCorreo = dbx.getCollection('__mailTimeQueue__').countDocuments({});
|
||||
// Campos que la primera versión del script NO comprobaba — por eso la fuga pasó
|
||||
// desapercibida (42 users con credenciales OAuth vivas + 99 con nombre real).
|
||||
const googleCreds = dbx.users.countDocuments({ $or: [
|
||||
{ 'services.google.accessToken': { $exists: true } },
|
||||
{ 'services.google.refreshToken': { $exists: true } },
|
||||
{ 'services.google.idToken': { $exists: true } }
|
||||
] });
|
||||
const googleNom = dbx.users.countDocuments({ 'services.google.name': { $exists: true } });
|
||||
const profileNom = dbx.users.countDocuments({ $or: [
|
||||
{ 'profile.name.first': { $exists: true } },
|
||||
{ 'profile.name.last': { $exists: true } }
|
||||
] });
|
||||
const sesiones = dbx.users.countDocuments({ 'services.resume.loginTokens.0': { $exists: true } });
|
||||
printjson({ verificacion: {
|
||||
usersConFireBaseToken: conToken, usersConEmailRealVisible: emailMalo,
|
||||
usersConGoogleEmailReal: googleMalo, usersConGoogleCredsVivas: googleCreds,
|
||||
usersConGoogleNombreReal: googleNom, usersConProfileNombreReal: profileNom,
|
||||
usersConTokenSesion: sesiones, subsConChatId: subsConChat, correosEnCola: colaCorreo
|
||||
} });
|
||||
const pendientes = conToken + emailMalo + googleMalo + googleCreds + googleNom +
|
||||
profileNom + sesiones + subsConChat + colaCorreo;
|
||||
if (pendientes === 0) {
|
||||
print('OK: contactos neutralizados. Ninguna notificación puede alcanzar a un usuario real,');
|
||||
print(' y no quedan credenciales OAuth/sesión ni nombres reales.');
|
||||
print('NOTA: services.password.bcrypt se conserva a propósito (QA de login) — ver comentario arriba.');
|
||||
} else {
|
||||
print('AVISO: quedan ' + pendientes + ' campos sin neutralizar — revisar antes de exponer el staging.');
|
||||
}
|
||||
46
secrets/meteor-settings.staging.json.example
Normal file
46
secrets/meteor-settings.staging.json.example
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
{
|
||||
"// AVISO": "Plantilla de STAGING (testfuegos.comunes.org). Copia a meteor-settings.staging.json y rellena los valores reales desde tcef-private-config/local/todos-contra-el-fuego-web/settings-staging.json. El fichero real está gitignorado.",
|
||||
"PrerenderIO": {
|
||||
"serviceUrl": "http://groucho.comunes.org:3000/render",
|
||||
"token": "PRERENDER_TOKEN"
|
||||
},
|
||||
"gmaps": {
|
||||
"key": "GMAPS_BROWSER_KEY",
|
||||
"serverKey": "GMAPS_SERVER_KEY"
|
||||
},
|
||||
"piwik": {
|
||||
"url": "https://piwik.comunes.org/piwik.php",
|
||||
"site_id": 7
|
||||
},
|
||||
"sentryPrivateDSN": "",
|
||||
"public": {
|
||||
"sentryPublicDSN": ""
|
||||
},
|
||||
"private": {
|
||||
"testEmail": "vjrj@ourproject.org",
|
||||
"// mail": "STAGING: correo capturado por Mailhog del compose. testMailer=false para no emitir 4 correos de autoprueba al arrancar; debugMailer=true para loguear la cola.",
|
||||
"testMailer": false,
|
||||
"debugMailer": true,
|
||||
"MAIL_URL": "smtp://mailhog:1025",
|
||||
"isMailServer": true,
|
||||
"fireIconUrl": "https://testfuegos.comunes.org/n-fire-marker.png",
|
||||
"OAuth": {
|
||||
"google": {
|
||||
"clientId": "GOOGLE_OAUTH_CLIENT_ID",
|
||||
"secret": "GOOGLE_OAUTH_SECRET",
|
||||
"loginStyle": "popup"
|
||||
}
|
||||
},
|
||||
"// fcm": "STAGING: sin fcmApiToken. El push lo gestiona tcef-notifications (en shadow, sin service account).",
|
||||
"proxies_count": 1,
|
||||
"ironPassword": "IRON_PASSWORD",
|
||||
"internalApiToken": "INTERNAL_API_TOKEN",
|
||||
"cron": {
|
||||
"debug": false
|
||||
},
|
||||
"twitter": {
|
||||
"es": { "enabled": false },
|
||||
"en": { "enabled": false }
|
||||
}
|
||||
}
|
||||
}
|
||||
40
secrets/notifications.staging.env.example
Normal file
40
secrets/notifications.staging.env.example
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
# tcef-notifications en STAGING (testfuegos.comunes.org). Copia a notifications.staging.env.
|
||||
# Referencia completa: ../../tcef-notifications/.env.example
|
||||
#
|
||||
# CERO ENVÍOS A USUARIOS REALES:
|
||||
# MODE=shadow → calcula decisiones y las loguea, NO envía (ver src/mode.ts decideSend)
|
||||
# MATCHER_MODE=shadow→ el matcher computa candidatos a notificar, NO inserta/envía
|
||||
# sin FCM_SERVICE_ACCOUNT → no se construye el cliente FCM (imposible enviar push)
|
||||
# MAIL_URL=smtp://mailhog:1025 → cualquier correo se captura en Mailhog, nunca sale
|
||||
# telegram FUERA de OWNED_CHANNELS → los bots reales ES/EN ni se tocan
|
||||
|
||||
MODE=shadow
|
||||
KILL_SWITCH=0
|
||||
OWNED_CHANNELS=fcm,email
|
||||
MATCHER_MODE=shadow
|
||||
LOG_LEVEL=debug
|
||||
|
||||
# Infra del compose de staging (nombres de servicio de docker-compose.staging.yml)
|
||||
MONGO_URL=mongodb://mongo:27017/fuegos?replicaSet=rs0
|
||||
MONGO_DB=fuegos
|
||||
REDIS_HOST=redis
|
||||
REDIS_PORT=6379
|
||||
|
||||
POLL_INTERVAL_MS=10000
|
||||
POLL_BATCH_SIZE=500
|
||||
|
||||
# Captura de correo (no un SMTP real). En shadow no se envía, pero se deja apuntando a Mailhog
|
||||
# como red de seguridad si alguien sube el MODE por error.
|
||||
MAIL_URL=smtp://mailhog:1025
|
||||
MAIL_FROM=Todos contra el Fuego (STAGING) <no-reply@testfuegos.comunes.org>
|
||||
|
||||
# NO configurar en staging (dejar comentado): sin service account no hay push posible.
|
||||
# FCM_SERVICE_ACCOUNT=/run/secrets/firebase-service-account.json
|
||||
# FCM_PROJECT_ID=angular-cosmos-108908
|
||||
|
||||
# OBLIGATORIO si MATCHER_MODE != off: el matcher lo exige para sellar notification.sealed
|
||||
# (createMatchContext falla al arrancar sin él, aun en shadow). = ironPassword de los settings.
|
||||
IRON_PASSWORD=IRON_PASSWORD_DE_LOS_SETTINGS
|
||||
|
||||
ROOT_URL=https://testfuegos.comunes.org/
|
||||
SERVICE_NAME=tcef-notifications-staging
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { chai } from 'meteor/practicalmeteor:chai';
|
||||
import ActiveFiresUnion from '/imports/api/ActiveFiresUnion/ActiveFiresUnion';
|
||||
|
||||
const centerid = { type: 'Point', coordinates: [-5.905956029891968, 43.55727622097011] };
|
||||
const shape = { type: 'Polygon', coordinates: [[[-5.9084, 43.5558], [-5.906, 43.5558], [-5.906, 43.5566], [-5.9036, 43.5566], [-5.9036, 43.5583], [-5.9061, 43.5583], [-5.9061, 43.558], [-5.9084, 43.558], [-5.9084, 43.5558]]] };
|
||||
const fireUnion = { centerid, shape, when: Date('2018-05-02T16:11:04.617Z') };
|
||||
|
||||
describe('activeFireUnion insert', () => {
|
||||
it('should insert fire union', () => {
|
||||
// Remove previous test register
|
||||
const alreadyInserted = ActiveFiresUnion.findOne({ centerid });
|
||||
if (alreadyInserted) {
|
||||
ActiveFiresUnion.remove(alreadyInserted._id);
|
||||
}
|
||||
|
||||
const insertedId = ActiveFiresUnion.insert(fireUnion);
|
||||
ActiveFiresUnion.schema.validate(fireUnion);
|
||||
|
||||
const inserted = ActiveFiresUnion.findOne(insertedId);
|
||||
delete inserted._id;
|
||||
chai.expect(fireUnion).to.deep.equal(inserted);
|
||||
ActiveFiresUnion.remove(insertedId);
|
||||
chai.expect(ActiveFiresUnion.find({ _id: inserted }).count()).equal(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { chai } from 'meteor/practicalmeteor:chai';
|
||||
import { subjectTruncate } from '/imports/modules/server/send-email';
|
||||
|
||||
describe('check email utilities', () => {
|
||||
it('small words', async () => {
|
||||
chai.expect('something').equal(subjectTruncate.apply('something', [50, true]));
|
||||
});
|
||||
|
||||
it('big sentences', async () => {
|
||||
chai.expect('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eget sed.')
|
||||
.equal(subjectTruncate.apply('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eget sed.'));
|
||||
});
|
||||
|
||||
it('big sentences space break', async () => {
|
||||
chai.expect('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi...')
|
||||
.equal(subjectTruncate.apply('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi mollis cras amet.'));
|
||||
});
|
||||
|
||||
it('big sentences no break', async () => {
|
||||
chai.expect('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi mollis...')
|
||||
.equal(subjectTruncate.apply('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi mollis cras amet.', [70, false]));
|
||||
});
|
||||
});
|
||||
|
|
@ -1,147 +0,0 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { chai } from 'meteor/practicalmeteor:chai';
|
||||
import ActiveFiresCollection from '/imports/api/ActiveFires/ActiveFires';
|
||||
import urlEnc from '/imports/modules/url-encode';
|
||||
import seeder from '@cleverbeagle/seeder';
|
||||
import { Accounts } from 'meteor/accounts-base';
|
||||
|
||||
const firesSeed = () => ({
|
||||
collection: ActiveFiresCollection,
|
||||
environments: ['development', 'staging'],
|
||||
noLimit: true,
|
||||
modelCount: 5,
|
||||
model(dataIndex) {
|
||||
return {
|
||||
ourid: {
|
||||
type: 'Point',
|
||||
coordinates: [
|
||||
149.751 + dataIndex,
|
||||
-10.021 + dataIndex
|
||||
]
|
||||
},
|
||||
type: 'modis',
|
||||
lat: -10.021 + dataIndex,
|
||||
lon: 149.751 + dataIndex,
|
||||
updatedAt: Date('2018-05-02T16:11:04.617Z'),
|
||||
acq_date: '2018-05-02',
|
||||
acq_time: '00:05',
|
||||
scan: 1.5,
|
||||
track: 1.2,
|
||||
satellite: 'T',
|
||||
confidence: 57,
|
||||
version: '6.0NRT',
|
||||
frp: 7.8,
|
||||
daynight: 'D',
|
||||
brightness: 304.3,
|
||||
bright_t31: 283.4,
|
||||
when: Date('2018-05-01T22:05:00.000Z'),
|
||||
createdAt: Date('2018-05-02T16:11:04.617Z')
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
async function encAndDec(obj) {
|
||||
delete obj._id;
|
||||
const sealed = await urlEnc.encrypt(obj);
|
||||
const unsealed = await urlEnc.decrypt(sealed);
|
||||
const w = unsealed.when;
|
||||
unsealed.when = new Date(w);
|
||||
const c = unsealed.createdAt;
|
||||
unsealed.createdAt = new Date(c);
|
||||
const u = unsealed.updatedAt;
|
||||
unsealed.updatedAt = new Date(u);
|
||||
chai.expect(unsealed).to.deep.equal(obj);
|
||||
}
|
||||
|
||||
describe('url encoding', () => {
|
||||
it('should encrypt and dcrypt basic objects', async (done) => {
|
||||
const obj = { lat: 2 };
|
||||
const sealed = await urlEnc.encrypt(obj);
|
||||
const unsealed = await urlEnc.decrypt(sealed);
|
||||
chai.expect(unsealed).to.deep.equal(obj);
|
||||
done();
|
||||
});
|
||||
|
||||
it('should encrypt and dcrypt objects with date', async (done) => {
|
||||
const obj = { lat: 40.234503, lon: -3.350386, when: (new Date()).toString() };
|
||||
const sealed = await urlEnc.encrypt(obj);
|
||||
const unsealed = await urlEnc.decrypt(sealed);
|
||||
chai.expect(unsealed).to.deep.equal(obj);
|
||||
done();
|
||||
});
|
||||
|
||||
it('should encrypt complete objects', async (done) => {
|
||||
const obj = {
|
||||
ourid: {
|
||||
type: 'Point',
|
||||
coordinates: [
|
||||
24.813,
|
||||
9.223
|
||||
]
|
||||
},
|
||||
type: 'modis',
|
||||
lat: 9.223,
|
||||
lon: 24.813,
|
||||
when: new Date('2017-12-13T00:00:00.000Z').toISOString(),
|
||||
scan: 1,
|
||||
track: 1,
|
||||
satellite: 'A',
|
||||
confidence: 'nominal',
|
||||
version: '6.0NRT',
|
||||
frp: 6.5,
|
||||
daynight: null,
|
||||
brightness: 305.9,
|
||||
bright_t31: 292.6
|
||||
};
|
||||
|
||||
const sealed = await urlEnc.encrypt(obj);
|
||||
const sealed2 = await urlEnc.encrypt(obj);
|
||||
// console.log(encodeURI(sealed));
|
||||
|
||||
const unsealed = await urlEnc.decrypt(sealed);
|
||||
chai.expect(unsealed).to.deep.equal(obj);
|
||||
chai.expect(sealed).to.equal(encodeURI(sealed));
|
||||
chai.expect(sealed).to.not.equal(sealed2);
|
||||
chai.expect(sealed).to.not.include('/');
|
||||
chai.expect(sealed).to.not.include('%');
|
||||
done();
|
||||
});
|
||||
|
||||
// This fails because Date is return as String (not as Date) and because _id
|
||||
it('should encrypt and dcrypt collection objects', async (done) => {
|
||||
seeder(ActiveFiresCollection, firesSeed());
|
||||
const obj = ActiveFiresCollection.findOne();
|
||||
encAndDec(obj);
|
||||
done();
|
||||
});
|
||||
|
||||
it('should decrypt node-red enc objects', async () => {
|
||||
const sealed = 'Fe26.2**7ae64199b871901d16a6ba031198c57b43b4a9231e15b851ff80014a8de230ca*RkB3_Uu_oJnTefyzB-Ocqg*2Z9rXYf--GxLJnYESHvdK5rC6lOMlSbMJ6YQyR2Mgpl57iBYopAHPWRLNTBgNkbUHFYa0IlEjdyeEz5VvLDtVvlSr1Sam-Cx8GUai4mharZO5-Wkze0dTr7M56WofSC9jpkv3kANrpsrit3HASE_E-5Z1JVYQVQqehw-VbSZTorrYj0GCJiAgXE5I0iY4boXRDYCv7fm_pzcuAbHlnNkKT1GbMFEPjyVViP4mVMRI5PDUhcWb0f62goMX4UnYLZXum4oYOIr84DG8AxqIdW2L94yslt0EZkD3yVhvKEGoauMpy6ry2illpSgaMaj4sU3AKWIjfAsJXvM6bHwbNh6G1_BJfCapuu3KijBBQPQMAnhYuwLAlY56WN-Y2efNIBJkp__kO6ak2nFqu8PufpxE-cv0uW7x6GWUtCpnFO2SeUJWVVMddUgJjLiM8Hkdl1v9huB0WdIvsoPEV0ZOwHZaC3jtdKFSO7Xe6LdqTXjXmdBMwtOv-HefyaB8LnEN6dAeKWwJuDu7g03QFTryDIiuwtpQ8mcLWTJGHcxoaluNhUESOBULkWSv_E1vOM1_fFv**1e41101b27c5da58bc11177448e91d88d7801bf911088a895844db0c542dfa7c*dPlOhtXJcyR47ezuL7CEgC2Z8d6C1asNOiqZmhD5TXY';
|
||||
const unsealed = await urlEnc.decrypt(sealed);
|
||||
// console.log(unsealed);
|
||||
});
|
||||
|
||||
it('should encrypt and dcrypt Accounts hashes', async (done) => {
|
||||
const token = Accounts._generateStampedLoginToken();
|
||||
const obj = Accounts._hashStampedToken(token);
|
||||
console.log(obj);
|
||||
const sealed = await urlEnc.encrypt(obj);
|
||||
const unsealed = await urlEnc.decrypt(sealed);
|
||||
const w = unsealed.when;
|
||||
unsealed.when = new Date(w);
|
||||
chai.expect(unsealed).to.deep.equal(obj);
|
||||
done();
|
||||
});
|
||||
|
||||
// limit 0 for no limit and test everything (and increase timeout)
|
||||
it('should encrypt and dcrypt all collection objects', async (done) => {
|
||||
seeder(ActiveFiresCollection, firesSeed());
|
||||
ActiveFiresCollection.find({}, { limit: 1000 }).fetch().forEach((obj) => {
|
||||
encAndDec(obj);
|
||||
});
|
||||
done();
|
||||
}).timeout(5000);
|
||||
});
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { chai } from 'meteor/practicalmeteor:chai';
|
||||
import { getFileNameOfLang } from '/imports/api/Utility/server/files.js';
|
||||
|
||||
describe('get file of page', () => {
|
||||
it('lang es retrieve es', async () => {
|
||||
chai.expect('pages/about-es.md').to.deep.equal(getFileNameOfLang('pages', 'about', 'md', 'es'));
|
||||
});
|
||||
|
||||
it('lang en retrieve en', async () => {
|
||||
chai.expect('pages/about-en.md').to.deep.equal(getFileNameOfLang('pages', 'about', 'md', 'en'));
|
||||
});
|
||||
|
||||
it('lang gl retrieve es', async () => {
|
||||
chai.expect('pages/about-es.md').to.deep.equal(getFileNameOfLang('pages', 'about', 'md', 'gl'));
|
||||
});
|
||||
|
||||
it('lang ast retrieve es', async () => {
|
||||
chai.expect('pages/about-es.md').to.deep.equal(getFileNameOfLang('pages', 'about', 'md', 'gl'));
|
||||
});
|
||||
|
||||
it('lang eu retrieve es', async () => {
|
||||
chai.expect('pages/about-es.md').to.deep.equal(getFileNameOfLang('pages', 'about', 'md', 'eu'));
|
||||
});
|
||||
|
||||
it('lang ca retrieve es', async () => {
|
||||
chai.expect('pages/about-es.md').to.deep.equal(getFileNameOfLang('pages', 'about', 'md', 'ca'));
|
||||
});
|
||||
|
||||
it('lang es-PE retrieve es', async () => {
|
||||
chai.expect('pages/about-es.md').to.deep.equal(getFileNameOfLang('pages', 'about', 'md', 'es-PE'));
|
||||
});
|
||||
});
|
||||
|
|
@ -1,293 +0,0 @@
|
|||
/* eslint-disable import/no-absolute-path */
|
||||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
|
||||
import { chai } from 'meteor/practicalmeteor:chai';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import { HTTP } from 'meteor/http';
|
||||
|
||||
const testPort = process.env.TEST_PORT;
|
||||
function url(path) {
|
||||
return `http://127.0.0.1:${testPort}/${path}`;
|
||||
}
|
||||
|
||||
describe('basic api v1 returns', () => {
|
||||
it('should return uptime', async done =>
|
||||
HTTP.get(url('api/v1/status/uptime'), {
|
||||
data: {
|
||||
}
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
chai.expect(result.statusCode).to.equal(200);
|
||||
chai.expect(typeof result.data.ms).to.equal('number');
|
||||
done();
|
||||
}));
|
||||
|
||||
it('should return last-fire', async done =>
|
||||
HTTP.get(url('api/v1/status/active-fires-count'), {
|
||||
data: {
|
||||
}
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
chai.expect(result.statusCode).equal(200);
|
||||
chai.expect(typeof result.data.total).to.equal('number');
|
||||
done();
|
||||
}));
|
||||
|
||||
const token = Meteor.settings.private.internalApiToken;
|
||||
|
||||
it('should return fires in some location', async done =>
|
||||
HTTP.get(url(`api/v1/fires-in/${token}/38.736946/-9.142685/100`), {
|
||||
data: {
|
||||
}
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
chai.expect(result.statusCode).equal(200);
|
||||
chai.expect(typeof result.data.total).to.equal('number');
|
||||
chai.expect(typeof result.data.real).to.equal('number');
|
||||
done();
|
||||
}));
|
||||
|
||||
it('should return full fires in some location', async done =>
|
||||
HTTP.get(url(`api/v1/fires-in-full/${token}/38.736946/-9.142685/100`), {
|
||||
data: {
|
||||
}
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
chai.expect(result.statusCode).equal(200);
|
||||
chai.expect(typeof result.data.total).to.equal('number');
|
||||
chai.expect(typeof result.data.real).to.equal('number');
|
||||
chai.expect(typeof result.data.falsePos).to.equal('object');
|
||||
chai.expect(typeof result.data.industries).to.equal('object');
|
||||
chai.expect(typeof result.data.fires).to.equal('object');
|
||||
done();
|
||||
}));
|
||||
|
||||
it('should not return full fires with some wrong token', async done =>
|
||||
HTTP.get(url('api/v1/fires-in-full/token/38.736946/-9.142685/100'), {
|
||||
data: {
|
||||
}
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
chai.expect(result.statusCode).equal(401);
|
||||
done();
|
||||
}));
|
||||
|
||||
it('should not return fires with some wrong token', async done =>
|
||||
HTTP.get(url('api/v1/fires-in/token/38.736946/-9.142685/100'), {
|
||||
data: {
|
||||
}
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
chai.expect(result.statusCode).equal(401);
|
||||
done();
|
||||
}));
|
||||
|
||||
it('should not return fires with some wrong distance', async done =>
|
||||
HTTP.get(url(`api/v1/fires-in-full/${token}/38.736946/-9.142685/1100`), (error, result) => {
|
||||
chai.expect(error, null);
|
||||
chai.expect(result.statusCode).equal(400);
|
||||
done();
|
||||
}));
|
||||
|
||||
const mobileToken = 'user-mobile-firebase-token';
|
||||
let testUserId;
|
||||
let returnedSubsId;
|
||||
const objId = new Meteor.Collection.ObjectID();
|
||||
|
||||
it('should create mobile users', async (done) => {
|
||||
// this are removed in the test database but we are testing in dev/ci database
|
||||
|
||||
// Delete the test account if it's still present
|
||||
// Meteor.users.remove({ fireBaseToken: mobileToken });
|
||||
|
||||
HTTP.post(url('api/v1/mobile/users'), {
|
||||
data: {
|
||||
token,
|
||||
mobileToken,
|
||||
lang: 'en'
|
||||
}
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
const jsendResult = result.data;
|
||||
chai.expect(jsendResult.status).equal('success');
|
||||
chai.expect(result.statusCode).equal(200);
|
||||
chai.expect(jsendResult.data.upsertResult.numberAffected).to.equal(1);
|
||||
chai.expect(jsendResult.data.mobileToken).to.equal(mobileToken);
|
||||
chai.expect(jsendResult.data.lang).to.equal('en');
|
||||
chai.expect(typeof jsendResult.data.username).to.equal('string');
|
||||
testUserId = jsendResult.data.userId;
|
||||
chai.expect(typeof testUserId).to.equal('string');
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should not create mobile users with wrong token', async (done) => {
|
||||
// this are removed in the test database but we are testing in dev/ci database
|
||||
// Delete the test account if it's still present
|
||||
// Meteor.users.remove({ fireBaseToken: mobileToken });
|
||||
|
||||
HTTP.post(url('api/v1/mobile/users'), {
|
||||
data: {
|
||||
token: 'wrong token',
|
||||
mobileToken,
|
||||
lang: 'en'
|
||||
}
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
chai.expect(result.statusCode).equal(401);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
function addSubs(done) {
|
||||
// this are removed in the test database but we are testing in dev/ci database
|
||||
// Remove previous subs of this user
|
||||
// Subscriptions.remove({ owner: testUserId });
|
||||
// chai.expect(Subscriptions.find({ owner: testUserId }).count()).to.equal(0);
|
||||
HTTP.post(url('api/v1/mobile/subscriptions'), {
|
||||
data: {
|
||||
token,
|
||||
mobileToken,
|
||||
id: objId._str,
|
||||
lat: 3.106111,
|
||||
lon: 53.5775,
|
||||
distance: 100
|
||||
}
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
if (result.statusCode !== 200) console.log(result);
|
||||
chai.expect(result.statusCode).equal(200);
|
||||
const jsendResult = result.data;
|
||||
chai.expect(jsendResult.status).equal('success');
|
||||
returnedSubsId = jsendResult.data.subsId;
|
||||
chai.expect(returnedSubsId.toString()).equal(objId._str);
|
||||
done();
|
||||
});
|
||||
}
|
||||
|
||||
it('should create mobile user subscriptions', async (done) => {
|
||||
addSubs(done);
|
||||
});
|
||||
|
||||
it('should not create mobile user subscriptions with wrong token', async (done) => {
|
||||
HTTP.post(url('api/v1/mobile/subscriptions'), {
|
||||
data: {
|
||||
token: 'wrongOne',
|
||||
mobileToken,
|
||||
id: objId._str,
|
||||
lat: 3.106111,
|
||||
lon: 53.5775,
|
||||
distance: 100
|
||||
}
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
if (result.statusCode !== 401) console.log(result);
|
||||
chai.expect(result.statusCode).equal(401);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should get all mobile user subscriptions', async (done) => {
|
||||
HTTP.get(url(`api/v1/mobile/subscriptions/all/${token}/${mobileToken}`), {
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
if (result.statusCode !== 200) console.log(result);
|
||||
chai.expect(result.statusCode).equal(200);
|
||||
const jsendResult = result.data;
|
||||
chai.expect(jsendResult.status).equal('success');
|
||||
chai.expect(typeof jsendResult.data.subscriptions).to.equal('object');
|
||||
chai.expect(typeof jsendResult.data.count).to.equal('number');
|
||||
if (jsendResult.data.count !== 1) console.log(result);
|
||||
chai.expect(jsendResult.data.count).to.equal(1);
|
||||
// console.log(JSON.stringify(jsendResult.data.subscriptions));
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
it('should remove mobile user subscriptions', async (done) => {
|
||||
// this are removed in the test database but we are testing in dev/ci database
|
||||
|
||||
HTTP.del(url(`api/v1/mobile/subscriptions/${token}/${mobileToken}/${returnedSubsId}`), {
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
if (result.statusCode !== 200) console.log(result);
|
||||
chai.expect(result.statusCode).equal(200);
|
||||
const jsendResult = result.data;
|
||||
chai.expect(jsendResult.status).equal('success');
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should get all mobile user subscriptions after deletion', async (done) => {
|
||||
HTTP.get(url(`api/v1/mobile/subscriptions/all/${token}/${mobileToken}`), {
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
if (result.statusCode !== 200) console.log(result);
|
||||
chai.expect(result.statusCode).equal(200);
|
||||
const jsendResult = result.data;
|
||||
chai.expect(jsendResult.status).equal('success');
|
||||
chai.expect(typeof jsendResult.data.subscriptions).to.equal('object');
|
||||
chai.expect(typeof jsendResult.data.count).to.equal('number');
|
||||
if (jsendResult.data.count !== 0) console.log(result);
|
||||
chai.expect(jsendResult.data.count).to.equal(0);
|
||||
// console.log(JSON.stringify(jsendResult.data.subscriptions));
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should not remove mobile user subscriptions with wrong token', async (done) => {
|
||||
HTTP.del(url(`api/v1/mobile/subscriptions/wrongOne/${mobileToken}/${returnedSubsId}`), {
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
if (result.statusCode !== 401) console.log(result);
|
||||
chai.expect(result.statusCode).equal(401);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should not get mobile user subscriptions with wrong token', async (done) => {
|
||||
HTTP.get(url(`api/v1/mobile/subscriptions/all/wrongOne/${mobileToken}`), {
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
if (result.statusCode !== 401) console.log(result);
|
||||
chai.expect(result.statusCode).equal(401);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should get all mobile user subscriptions', async (done) => {
|
||||
HTTP.get(url(`api/v1/mobile/subscriptions/all/${token}/${mobileToken}`), {
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
// console.log(result);
|
||||
if (result.statusCode !== 200) console.log(result);
|
||||
chai.expect(result.statusCode).equal(200);
|
||||
const jsendResult = result.data;
|
||||
chai.expect(jsendResult.status).equal('success');
|
||||
chai.expect(typeof jsendResult.data.subscriptions).to.equal('object');
|
||||
chai.expect(typeof jsendResult.data.count).to.equal('number');
|
||||
if (jsendResult.data.count !== 0) console.log(result);
|
||||
chai.expect(jsendResult.data.count).to.equal(0);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should del all mobile user subscriptions', async (done) => {
|
||||
// Add subs
|
||||
addSubs(() => {
|
||||
HTTP.del(url(`api/v1/mobile/subscriptions/all/${token}/${mobileToken}`), {
|
||||
}, (error, result) => {
|
||||
chai.expect(error, null);
|
||||
if (result.statusCode !== 200) console.log(result);
|
||||
chai.expect(result.statusCode).equal(200);
|
||||
const jsendResult = result.data;
|
||||
chai.expect(jsendResult.status).equal('success');
|
||||
chai.expect(typeof jsendResult.data.count).to.equal('number');
|
||||
chai.expect(jsendResult.data.count).to.be.at.most(1);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
14
test/server/00-setup.test.js
Normal file
14
test/server/00-setup.test.js
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
// `meteor test` does NOT load server/main.js, so the app's
|
||||
// server/00-collection2-init.js never runs and Mongo.Collection.prototype
|
||||
// .attachSchema stays unpatched — every collection with a schema then throws at
|
||||
// import time. This file mirrors that init. The `00-` prefix makes Meteor load
|
||||
// it before the other test/server/*.test.js files (same-directory files load
|
||||
// alphabetically), so attachSchema exists before any collection is imported.
|
||||
// It intentionally defines no tests.
|
||||
import 'meteor/aldeed:collection2/static.js';
|
||||
// Force accounts-base to initialize so Meteor.users exists for method tests
|
||||
// (server/main.js, which normally pulls in the accounts setup, is not loaded).
|
||||
import 'meteor/accounts-base';
|
||||
32
test/server/activeFiresUnion.test.js
Normal file
32
test/server/activeFiresUnion.test.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { expect } from 'chai';
|
||||
import ActiveFiresUnion from '/imports/api/ActiveFiresUnion/ActiveFiresUnion';
|
||||
|
||||
const centerid = { type: 'Point', coordinates: [-5.905956029891968, 43.55727622097011] };
|
||||
const shape = { type: 'Polygon', coordinates: [[[-5.9084, 43.5558], [-5.906, 43.5558], [-5.906, 43.5566], [-5.9036, 43.5566], [-5.9036, 43.5583], [-5.9061, 43.5583], [-5.9061, 43.558], [-5.9084, 43.558], [-5.9084, 43.5558]]] };
|
||||
// `new Date(...)` (the old test used bare `Date(...)`, which yields a string and
|
||||
// fails collection2 schema validation on a Date field).
|
||||
const fireUnion = { centerid, shape, when: new Date('2018-05-02T16:11:04.617Z') };
|
||||
|
||||
describe('activeFireUnion insert', () => {
|
||||
it('should insert fire union', async () => {
|
||||
// Remove any leftover from a previous run
|
||||
const alreadyInserted = await ActiveFiresUnion.findOneAsync({ centerid });
|
||||
if (alreadyInserted) {
|
||||
await ActiveFiresUnion.removeAsync(alreadyInserted._id);
|
||||
}
|
||||
|
||||
const insertedId = await ActiveFiresUnion.insertAsync(fireUnion);
|
||||
ActiveFiresUnion.schema.validate(fireUnion);
|
||||
|
||||
const inserted = await ActiveFiresUnion.findOneAsync(insertedId);
|
||||
delete inserted._id;
|
||||
expect(inserted).to.deep.equal(fireUnion);
|
||||
|
||||
await ActiveFiresUnion.removeAsync(insertedId);
|
||||
expect(await ActiveFiresUnion.find({ _id: insertedId }).countAsync()).to.equal(0);
|
||||
});
|
||||
});
|
||||
122
test/server/comments.test.js
Normal file
122
test/server/comments.test.js
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { expect } from 'chai';
|
||||
import { Meteor } from 'meteor/meteor';
|
||||
import Comments from '/imports/api/Comments/Comments';
|
||||
import getMediaFromContent from '/imports/api/Comments/mediaAnalyzers';
|
||||
// `meteor test` skips server/main.js, so nothing registers the comment methods.
|
||||
// Importing the module runs its Meteor.methods({...}) so the handlers exist.
|
||||
import '/imports/api/Comments/server/methods';
|
||||
|
||||
// -- Embed detection (pure) --------------------------------------------------
|
||||
describe('comment media analyzers', () => {
|
||||
it('detects an image url', () => {
|
||||
const media = getMediaFromContent('look at http://example.com/photo.jpg here');
|
||||
expect(media.type).to.equal('image');
|
||||
expect(media.content).to.match(/\.jpg$/);
|
||||
});
|
||||
|
||||
it('detects a youtube url and rewrites it to an embed url', () => {
|
||||
const media = getMediaFromContent('see https://www.youtube.com/watch?v=abc123 now');
|
||||
expect(media).to.deep.equal({ type: 'youtube', content: 'https://www.youtube.com/embed/abc123' });
|
||||
});
|
||||
|
||||
it('returns {} for plain text', () => {
|
||||
expect(getMediaFromContent('just some words with no media')).to.deep.equal({});
|
||||
});
|
||||
});
|
||||
|
||||
// -- Comment methods (server, via method handlers) ---------------------------
|
||||
// The methods gate on `this.userId`, so invoke the handlers with a fake
|
||||
// invocation context instead of going through a real login.
|
||||
describe('comment methods', () => {
|
||||
const ref = 'fire-ref-under-test';
|
||||
const owner = 'user-owner';
|
||||
const other = 'user-other';
|
||||
const handlers = Meteor.server.method_handlers;
|
||||
|
||||
const insert = (userId, content) => handlers['comments.insert'].apply({ userId }, [ref, content]);
|
||||
const edit = (userId, id, content) => handlers['comments.edit'].apply({ userId }, [id, content]);
|
||||
const remove = (userId, id) => handlers['comments.remove'].apply({ userId }, [id]);
|
||||
const like = (userId, id) => handlers['comments.like'].apply({ userId }, [id]);
|
||||
const dislike = (userId, id) => handlers['comments.dislike'].apply({ userId }, [id]);
|
||||
|
||||
beforeEach(async () => {
|
||||
await Comments.removeAsync({ referenceId: ref });
|
||||
});
|
||||
|
||||
it('insert creates an approved comment with detected media', async () => {
|
||||
const id = await insert(owner, 'hi http://example.com/pic.png');
|
||||
const c = await Comments.findOneAsync(id);
|
||||
expect(c.userId).to.equal(owner);
|
||||
expect(c.referenceId).to.equal(ref);
|
||||
expect(c.status).to.equal('approved');
|
||||
expect(c.media.type).to.equal('image');
|
||||
expect(c.likes).to.deep.equal([]);
|
||||
expect(c.dislikes).to.deep.equal([]);
|
||||
});
|
||||
|
||||
it('insert requires a logged-in user', async () => {
|
||||
let threw = false;
|
||||
try {
|
||||
await handlers['comments.insert'].apply({}, [ref, 'nope']);
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
expect(threw).to.equal(true);
|
||||
});
|
||||
|
||||
it('insert rejects an empty comment', async () => {
|
||||
let threw = false;
|
||||
try {
|
||||
await insert(owner, ' ');
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
expect(threw).to.equal(true);
|
||||
});
|
||||
|
||||
it('edit is allowed for the owner and denied for others', async () => {
|
||||
const id = await insert(owner, 'original');
|
||||
|
||||
let threw = false;
|
||||
try {
|
||||
await edit(other, id, 'hijacked');
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
expect(threw).to.equal(true);
|
||||
|
||||
await edit(owner, id, 'edited');
|
||||
expect((await Comments.findOneAsync(id)).content).to.equal('edited');
|
||||
});
|
||||
|
||||
it('like then dislike toggles the arrays', async () => {
|
||||
const id = await insert(owner, 'toggle me');
|
||||
|
||||
await like(other, id);
|
||||
expect((await Comments.findOneAsync(id)).likes).to.include(other);
|
||||
|
||||
await dislike(other, id);
|
||||
const c = await Comments.findOneAsync(id);
|
||||
expect(c.dislikes).to.include(other);
|
||||
expect(c.likes).to.not.include(other);
|
||||
});
|
||||
|
||||
it('remove is allowed for the owner only', async () => {
|
||||
const id = await insert(owner, 'delete me');
|
||||
|
||||
let threw = false;
|
||||
try {
|
||||
await remove(other, id);
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
expect(threw).to.equal(true);
|
||||
|
||||
await remove(owner, id);
|
||||
expect(await Comments.findOneAsync(id)).to.equal(undefined);
|
||||
});
|
||||
});
|
||||
27
test/server/email.test.js
Normal file
27
test/server/email.test.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { expect } from 'chai';
|
||||
import { subjectTruncate } from '/imports/modules/server/send-email';
|
||||
|
||||
describe('check email utilities', () => {
|
||||
it('small words', () => {
|
||||
expect(subjectTruncate.apply('something', [50, true])).to.equal('something');
|
||||
});
|
||||
|
||||
it('big sentences', () => {
|
||||
expect(subjectTruncate.apply('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eget sed.'))
|
||||
.to.equal('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eget sed.');
|
||||
});
|
||||
|
||||
it('big sentences space break', () => {
|
||||
expect(subjectTruncate.apply('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi mollis cras amet.'))
|
||||
.to.equal('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi...');
|
||||
});
|
||||
|
||||
it('big sentences no break', () => {
|
||||
expect(subjectTruncate.apply('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi mollis cras amet.', [70, false]))
|
||||
.to.equal('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi mollis...');
|
||||
});
|
||||
});
|
||||
63
test/server/encode.test.js
Normal file
63
test/server/encode.test.js
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { expect } from 'chai';
|
||||
import urlEnc from '/imports/modules/url-encode';
|
||||
|
||||
// NOTE: the old suite also seeded ActiveFires via @cleverbeagle/seeder and
|
||||
// round-tripped whole docs. Those cases were documented-broken (Date fields came
|
||||
// back as strings) and depended on a dev-only seeder package that is no longer
|
||||
// installed, so they were dropped. The crypto round-trip below is the real
|
||||
// contract this module owes.
|
||||
|
||||
describe('url encoding', () => {
|
||||
it('should encrypt and decrypt basic objects', async () => {
|
||||
const obj = { lat: 2 };
|
||||
const sealed = await urlEnc.encrypt(obj);
|
||||
const unsealed = await urlEnc.decrypt(sealed);
|
||||
expect(unsealed).to.deep.equal(obj);
|
||||
});
|
||||
|
||||
it('should encrypt and decrypt objects with date', async () => {
|
||||
const obj = { lat: 40.234503, lon: -3.350386, when: (new Date()).toString() };
|
||||
const sealed = await urlEnc.encrypt(obj);
|
||||
const unsealed = await urlEnc.decrypt(sealed);
|
||||
expect(unsealed).to.deep.equal(obj);
|
||||
});
|
||||
|
||||
it('should encrypt complete objects and produce url-safe, salted output', async () => {
|
||||
const obj = {
|
||||
ourid: { type: 'Point', coordinates: [24.813, 9.223] },
|
||||
type: 'modis',
|
||||
lat: 9.223,
|
||||
lon: 24.813,
|
||||
when: new Date('2017-12-13T00:00:00.000Z').toISOString(),
|
||||
scan: 1,
|
||||
track: 1,
|
||||
satellite: 'A',
|
||||
confidence: 'nominal',
|
||||
version: '6.0NRT',
|
||||
frp: 6.5,
|
||||
daynight: null,
|
||||
brightness: 305.9,
|
||||
bright_t31: 292.6
|
||||
};
|
||||
|
||||
const sealed = await urlEnc.encrypt(obj);
|
||||
const sealed2 = await urlEnc.encrypt(obj);
|
||||
const unsealed = await urlEnc.decrypt(sealed);
|
||||
|
||||
expect(unsealed).to.deep.equal(obj);
|
||||
expect(sealed).to.equal(encodeURI(sealed)); // already url-safe
|
||||
expect(sealed).to.not.equal(sealed2); // salted: same input, different output
|
||||
expect(sealed).to.not.include('/');
|
||||
expect(sealed).to.not.include('%');
|
||||
});
|
||||
|
||||
it('should decrypt a node-red produced blob without throwing', async () => {
|
||||
const sealed = 'Fe26.2**7ae64199b871901d16a6ba031198c57b43b4a9231e15b851ff80014a8de230ca*RkB3_Uu_oJnTefyzB-Ocqg*2Z9rXYf--GxLJnYESHvdK5rC6lOMlSbMJ6YQyR2Mgpl57iBYopAHPWRLNTBgNkbUHFYa0IlEjdyeEz5VvLDtVvlSr1Sam-Cx8GUai4mharZO5-Wkze0dTr7M56WofSC9jpkv3kANrpsrit3HASE_E-5Z1JVYQVQqehw-VbSZTorrYj0GCJiAgXE5I0iY4boXRDYCv7fm_pzcuAbHlnNkKT1GbMFEPjyVViP4mVMRI5PDUhcWb0f62goMX4UnYLZXum4oYOIr84DG8AxqIdW2L94yslt0EZkD3yVhvKEGoauMpy6ry2illpSgaMaj4sU3AKWIjfAsJXvM6bHwbNh6G1_BJfCapuu3KijBBQPQMAnhYuwLAlY56WN-Y2efNIBJkp__kO6ak2nFqu8PufpxE-cv0uW7x6GWUtCpnFO2SeUJWVVMddUgJjLiM8Hkdl1v9huB0WdIvsoPEV0ZOwHZaC3jtdKFSO7Xe6LdqTXjXmdBMwtOv-HefyaB8LnEN6dAeKWwJuDu7g03QFTryDIiuwtpQ8mcLWTJGHcxoaluNhUESOBULkWSv_E1vOM1_fFv**1e41101b27c5da58bc11177448e91d88d7801bf911088a895844db0c542dfa7c*dPlOhtXJcyR47ezuL7CEgC2Z8d6C1asNOiqZmhD5TXY';
|
||||
const unsealed = await urlEnc.decrypt(sealed);
|
||||
expect(unsealed).to.be.an('object');
|
||||
});
|
||||
});
|
||||
32
test/server/file.test.js
Normal file
32
test/server/file.test.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { expect } from 'chai';
|
||||
import { getFileNameOfLang } from '/imports/api/Utility/server/files.js';
|
||||
|
||||
describe('get file of page', () => {
|
||||
it('lang es retrieve es', () => {
|
||||
expect(getFileNameOfLang('pages', 'about', 'md', 'es')).to.equal('pages/about-es.md');
|
||||
});
|
||||
|
||||
it('lang en retrieve en', () => {
|
||||
expect(getFileNameOfLang('pages', 'about', 'md', 'en')).to.equal('pages/about-en.md');
|
||||
});
|
||||
|
||||
it('lang gl retrieve es', () => {
|
||||
expect(getFileNameOfLang('pages', 'about', 'md', 'gl')).to.equal('pages/about-es.md');
|
||||
});
|
||||
|
||||
it('lang eu retrieve es', () => {
|
||||
expect(getFileNameOfLang('pages', 'about', 'md', 'eu')).to.equal('pages/about-es.md');
|
||||
});
|
||||
|
||||
it('lang ca retrieve es', () => {
|
||||
expect(getFileNameOfLang('pages', 'about', 'md', 'ca')).to.equal('pages/about-es.md');
|
||||
});
|
||||
|
||||
it('lang es-PE retrieve es', () => {
|
||||
expect(getFileNameOfLang('pages', 'about', 'md', 'es-PE')).to.equal('pages/about-es.md');
|
||||
});
|
||||
});
|
||||
58
test/server/siteSettings.test.js
Normal file
58
test/server/siteSettings.test.js
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { expect } from 'chai';
|
||||
import SiteSettings from '/imports/api/SiteSettings/SiteSettings';
|
||||
import SiteSettingsTypes from '/imports/api/SiteSettings/SiteSettingsTypes';
|
||||
|
||||
const setting = {
|
||||
name: 'site-test',
|
||||
value: 'Some value',
|
||||
description: 'Some description',
|
||||
isPublic: true,
|
||||
type: 'string'
|
||||
};
|
||||
|
||||
describe('site settings store', () => {
|
||||
before(async () => {
|
||||
await SiteSettings.createIndexAsync({ name: 1 }, { unique: true });
|
||||
await SiteSettings.removeAsync({ name: setting.name });
|
||||
});
|
||||
|
||||
it('should get settingstypes', () => {
|
||||
expect(SiteSettingsTypes.string.value.type).to.equal(String);
|
||||
});
|
||||
|
||||
it('should insert settings', async () => {
|
||||
const id = await SiteSettings.insertAsync(setting);
|
||||
SiteSettings.getSchema(setting.type).validate(setting);
|
||||
|
||||
const inserted = await SiteSettings.findOneAsync(id);
|
||||
delete inserted._id;
|
||||
expect(inserted).to.deep.equal(setting);
|
||||
|
||||
await SiteSettings.removeAsync(id);
|
||||
expect(await SiteSettings.find({ _id: id }).countAsync()).to.equal(0);
|
||||
});
|
||||
|
||||
it('should not be inserted twice', async () => {
|
||||
const id = await SiteSettings.insertAsync(setting);
|
||||
// The unique index on `name` must reject the duplicate.
|
||||
let threw = false;
|
||||
try {
|
||||
await SiteSettings.insertAsync(setting);
|
||||
} catch (e) {
|
||||
threw = true;
|
||||
}
|
||||
expect(threw).to.equal(true);
|
||||
expect(await SiteSettings.find(id).countAsync()).to.equal(1);
|
||||
await SiteSettings.removeAsync(id);
|
||||
});
|
||||
|
||||
it('should fail validation', () => {
|
||||
expect(() => {
|
||||
SiteSettings.getSchema('boolean').validate(setting);
|
||||
}).to.throw('Value must be of type Boolean');
|
||||
});
|
||||
});
|
||||
51
test/server/tweets.test.js
Normal file
51
test/server/tweets.test.js
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { expect } from 'chai';
|
||||
import { composeIberiaTweet } from '/imports/api/ActiveFires/server/tweetFiresInZone';
|
||||
|
||||
const tr = (stats) => {
|
||||
const keys = Object.keys(stats);
|
||||
const newStats = [];
|
||||
keys.map((key) => {
|
||||
newStats[key] = { count: stats[key] };
|
||||
});
|
||||
return newStats;
|
||||
};
|
||||
|
||||
describe('compose tweets of fires', () => {
|
||||
it('No fires', () => {
|
||||
expect(composeIberiaTweet(0, { })).to.equal('');
|
||||
});
|
||||
|
||||
it('a fire in a zone', () => {
|
||||
expect(composeIberiaTweet(1, tr({ Asturias: 1 }))).to.equal('Un #fuego activo en #Asturias');
|
||||
});
|
||||
|
||||
it('some fires in a zone', () => {
|
||||
expect(composeIberiaTweet(4, tr({ Asturias: 4 }))).to.equal('4 #fuegos activos en #Asturias');
|
||||
});
|
||||
|
||||
it('some fires in two zones', () => {
|
||||
expect(composeIberiaTweet(5, tr({ Asturias: 1, Madrid: 4 }))).to.equal('Un #fuego activo en #Asturias y otros 4 en #Madrid');
|
||||
});
|
||||
|
||||
it('some fires in some zones', () => {
|
||||
expect(composeIberiaTweet(8, tr({ Catalunya: 3, Asturias: 1, Madrid: 4 }))).to.equal('3 #fuegos activos en #Catalunya, otro en #Asturias y otros 4 en #Madrid');
|
||||
});
|
||||
|
||||
it('other fires in some zones', () => {
|
||||
expect(composeIberiaTweet(6, tr({ Catalunya: 1, Asturias: 1, Madrid: 4 }))).to.equal('Un #fuego activo en #Catalunya, otro en #Asturias y otros 4 en #Madrid');
|
||||
});
|
||||
|
||||
it('other fires in two zones', () => {
|
||||
expect(composeIberiaTweet(2, tr({ Catalunya: 1, Asturias: 1 }))).to.equal('Un #fuego activo en #Catalunya y otro en #Asturias');
|
||||
});
|
||||
|
||||
it('many fires in many zones', () => {
|
||||
expect(composeIberiaTweet(11, tr({
|
||||
Cataluña: 3, Cantabria: 1, Andalucia: 4, Galicia: 1, Madrid: 2
|
||||
}))).to.equal('3 #fuegos activos en #Cataluña, otro en #Cantabria, otros 4 en #Andalucia, otro en #Galicia y otros 2 en #Madrid');
|
||||
});
|
||||
});
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { chai } from 'meteor/practicalmeteor:chai';
|
||||
import SiteSettings from '/imports/api/SiteSettings/SiteSettings';
|
||||
import SiteSettingsTypes from '/imports/api/SiteSettings/SiteSettingsTypes';
|
||||
import { resetDatabase } from 'meteor/xolvio:cleaner';
|
||||
|
||||
resetDatabase('siteSettings');
|
||||
SiteSettings._ensureIndex({ name: 1 }, { unique: 1 });
|
||||
|
||||
const setting = {
|
||||
name: 'site-test',
|
||||
value: 'Some value',
|
||||
description: 'Some description',
|
||||
isPublic: true,
|
||||
type: 'string'
|
||||
};
|
||||
|
||||
describe('site settings store', () => {
|
||||
it('should get settingstypes', () => {
|
||||
chai.expect(SiteSettingsTypes.string.value.type).equal(String);
|
||||
});
|
||||
|
||||
it('should insert settings', () => {
|
||||
// Remove previous test register
|
||||
const alreadyInserted = SiteSettings.findOne({ name: 'site-test' });
|
||||
if (alreadyInserted) {
|
||||
SiteSettings.remove(alreadyInserted._id);
|
||||
}
|
||||
const id = SiteSettings.insert(setting);
|
||||
SiteSettings.getSchema(setting.type).validate(setting);
|
||||
|
||||
const inserted = SiteSettings.findOne(id);
|
||||
delete inserted._id;
|
||||
chai.expect(setting).to.deep.equal(inserted);
|
||||
SiteSettings.remove(id);
|
||||
chai.expect(SiteSettings.find({ _id: inserted }).count()).equal(0);
|
||||
});
|
||||
|
||||
it('should not be inserted twice', () => {
|
||||
const id = SiteSettings.insert(setting);
|
||||
// If this fails manual check that the setting it's not already in the db.
|
||||
chai.expect(() => {
|
||||
SiteSettings.insert(setting);
|
||||
}).to.throw();
|
||||
const inserted = SiteSettings.find(id).count();
|
||||
chai.expect(inserted).equal(1);
|
||||
SiteSettings.remove(id);
|
||||
chai.expect(SiteSettings.find({ _id: inserted }).count()).equal(0);
|
||||
});
|
||||
|
||||
it('should fail validation', () => {
|
||||
chai.expect(() => {
|
||||
SiteSettings.getSchema('boolean').validate(setting);
|
||||
}).to.throw('Value must be of type Boolean');
|
||||
});
|
||||
});
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
/* eslint-env mocha */
|
||||
/* eslint-disable func-names, prefer-arrow-callback */
|
||||
/* eslint-disable import/no-absolute-path */
|
||||
|
||||
import { chai } from 'meteor/practicalmeteor:chai';
|
||||
import { composeIberiaTweet } from '/imports/api/ActiveFires/server/tweetFiresInZone';
|
||||
|
||||
const tr = (stats) => {
|
||||
const keys = Object.keys(stats);
|
||||
const newStats = [];
|
||||
keys.map((key) => {
|
||||
newStats[key] = { count: stats[key] };
|
||||
});
|
||||
return newStats;
|
||||
};
|
||||
|
||||
describe('compose tweets of fires', () => {
|
||||
it('No fires', async () => {
|
||||
chai.expect('').to.deep.equal(composeIberiaTweet(0, { }));
|
||||
});
|
||||
|
||||
it('a fire in a zone', async () => {
|
||||
chai.expect('Un #fuego activo en #Asturias').to.deep.equal(composeIberiaTweet(1, tr({ Asturias: 1 })));
|
||||
});
|
||||
|
||||
it('some fires in a zone', async () => {
|
||||
chai.expect('4 #fuegos activos en #Asturias').to.deep.equal(composeIberiaTweet(4, tr({ Asturias: 4 })));
|
||||
});
|
||||
|
||||
it('some fires in two zones', async () => {
|
||||
chai.expect('Un #fuego activo en #Asturias y otros 4 en #Madrid').to.deep.equal(composeIberiaTweet(5, tr({ Asturias: 1, Madrid: 4 })));
|
||||
});
|
||||
|
||||
it('some fires in some zones', async () => {
|
||||
chai.expect('3 #fuegos activos en #Catalunya, otro en #Asturias y otros 4 en #Madrid').to.deep.equal(composeIberiaTweet(8, tr({ Catalunya: 3, Asturias: 1, Madrid: 4 })));
|
||||
});
|
||||
|
||||
it('other fires in some zones', async () => {
|
||||
chai.expect('Un #fuego activo en #Catalunya, otro en #Asturias y otros 4 en #Madrid').to.deep.equal(composeIberiaTweet(6, tr({ Catalunya: 1, Asturias: 1, Madrid: 4 })));
|
||||
});
|
||||
|
||||
it('other fires in two zones', async () => {
|
||||
chai.expect('Un #fuego activo en #Catalunya y otro en #Asturias').to.deep.equal(composeIberiaTweet(2, tr({ Catalunya: 1, Asturias: 1 })));
|
||||
});
|
||||
|
||||
it('many fires in many zones', async () => {
|
||||
chai.expect('3 #fuegos activos en #Cataluña, otro en #Cantabria, otros 4 en #Andalucia, otro en #Galicia y otros 2 en #Madrid').to.deep.equal(composeIberiaTweet(11, tr({
|
||||
Cataluña: 3, Cantabria: 1, Andalucia: 4, Galicia: 1, Madrid: 2
|
||||
})));
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue