i18n in server. Some fixes

This commit is contained in:
vjrj 2017-12-09 17:54:18 +01:00
parent 23ec2b8f55
commit a0e5dc4723
13 changed files with 543 additions and 121 deletions

View file

@ -4,22 +4,21 @@ import Perlin from 'loms.perlin';
Perlin.seed(Math.random());
Meteor.publishTransformed('userSubsToFires', function() {
Meteor.publishTransformed('userSubsToFires', function () {
// https://en.wikipedia.org/wiki/Location_obfuscation
// https://en.wikipedia.org/wiki/Decimal_degrees#Precision
// https://gis.stackexchange.com/questions/27792/what-simple-effective-techniques-for-obfuscating-points-are-available
return Subscriptions.find().serverTransform(function(doc) {
var location = doc.location;
return Subscriptions.find().serverTransform(function (doc) {
var location = doc.location;
/* doc.lat = location.lat;
* doc.lon = location.lon;*/
* doc.lon = location.lon; */
if (location) {
doc.lat = Math.round(location.lat * 10) / 10;
doc.lon = Math.round(location.lon * 10) / 10;
}
// console.log(`[${doc.lat}, ${doc.lon}]`);
var noiseBase = Perlin.perlin2(doc.lat, doc.lon)
var noise = Math.abs(noiseBase/3);
var noiseBase = Perlin.perlin2(doc.lat, doc.lon);
var noise = Math.abs(noiseBase / 3);
// console.log(`Noise ${noise}, abs: ${Math.abs(noise)}`);
doc.lat += noise;
doc.lon += noise;

View file

@ -1,12 +1,11 @@
/* global CookieConsent Intl */
import i18n from 'i18next';
import backend from 'i18next-xhr-backend';
import LngDetector from 'i18next-browser-languagedetector';
import Cache from 'i18next-localstorage-cache';
import { Meteor } from 'meteor/meteor';
import { T9n } from 'meteor-accounts-t9n';
import en from 'meteor-accounts-t9n/build/en';
import es from 'meteor-accounts-t9n/build/es';
import moment from 'moment';
import i18nOpts from '../common/i18n';
// Adapted from: https://github.com/appigram/ryfma-boilerplate/blob/44c1eabfb9928b5623afab36a23997969e5beb02/imports/startup/client/i18n.js
@ -21,7 +20,7 @@ const detectorOptions = {
// cache user language on
caches: ['localStorage', 'cookie'],
excludeCacheFor: ['cimode'], // languages to not persist (cookie, localStorage)
excludeCacheFor: ['cimode'] // languages to not persist (cookie, localStorage)
};
const cacheOptions = {
@ -32,78 +31,29 @@ const cacheOptions = {
// expiration
expirationTime: 7 * 24 * 60 * 60 * 1000,
// language versions
versions: {},
versions: {}
};
var backOpts = {
// path where resources get loaded from
loadPath: '/locales/{{lng}}/{{ns}}.json',
// path to post missing resources
addPath: '/locales/{{lng}}/{{ns}}.missing.json',
// jsonIndent to use when storing json files
jsonIndent: 2
i18nOpts.cache = cacheOptions;
i18nOpts.detection = detectorOptions;
i18nOpts.react = {
wait: true
// https://react.i18next.com/components/i18next-instance.ht
/* bindI18n: 'languageChanged loaded',
bindStore: 'added removed',
nsMode: 'default' */
};
T9N_LANGUAGES='es,en';
const forceDebug = false;
const shouldDebug = (forceDebug && !Meteor.isProduction);
i18n.use(backend)
.use(LngDetector)
.use(Cache)
.init({
backend: backOpts,
lng: 'es',
//fallbackLng: 'es',
fallbackLng: {
'en-US': ['en'],
'en-GB': ['en'],
'pt-BR': ['pt'],
'default': ['es']
},
interpolation: {
escapeValue: false, // not needed for react!!
formatSeparator: ",",
format: function(value, format, lng) {
// https://www.i18next.com/formatting.html
// console.log(`Value: ${value} with format: ${format} to lang: ${lng}`);
if (format === 'uppercase') return value.toUpperCase();
if (value instanceof Date) return moment(value).format(format);
if (format === 'number') return Intl.NumberFormat(lng).format(value);
return value;
}
},
whitelist: false,
// whitelist: ['es', 'en'], // allowed languages
load: 'all', // es-ES -> es, en-US -> en
debug: shouldDebug,
ns: 'common',
defaultNS: 'common',
saveMissing: shouldDebug, // if true seems it's fails to getResourceBundle
saveMissingTo: 'es',
keySeparator: 'ß',
nsSeparator: 'ð',
pluralSeparator: 'đ',
cache: cacheOptions,
detection: detectorOptions,
react: {
wait: true,
// https://react.i18next.com/components/i18next-instance.ht
/* bindI18n: 'languageChanged loaded',
bindStore: 'added removed',
nsMode: 'default' */
}
}, function(err, t) {
.init(i18nOpts, (err, t) => {
// initialized and ready to
if (err) {
console.error(err);
return;
}
document.title = t("AppName");
document.title = t('AppName');
// Accounts translation
// https://github.com/softwarerero/meteor-accounts-t9n
// console.log("Language: " + i18n.language);
@ -111,11 +61,11 @@ i18n.use(backend)
// console.log(T9n.get('error.accounts.User not found'));
// cookies eu consent
var cookiesOpt = {
const cookiesOpt = {
cookieTitle: t('Uso de Cookies'),
cookieMessage: t('Utilizamos cookies para asegurar un mejor uso de nuestra web. Si continúas navegando, consideramos que aceptas su uso'),
/* cookieMessage: t('Uso de Cookies'),
cookieMessageImply: t('Utilizamos cookies para asegurar un mejor uso de nuestra web. Si continúas navegando, consideramos que aceptas su uso'),*/
cookieMessageImply: t('Utilizamos cookies para asegurar un mejor uso de nuestra web. Si continúas navegando, consideramos que aceptas su uso'), */
showLink: false,
position: 'bottom',
linkText: 'Lee más',
@ -129,7 +79,7 @@ i18n.use(backend)
CookieConsent.init(cookiesOpt);
});
i18n.on('languageChanged', function(lng) {
i18n.on('languageChanged', (lng) => {
moment.locale(lng);
T9n.setLanguage(lng);
});

View file

@ -0,0 +1,56 @@
import { Meteor } from 'meteor/meteor';
import moment from 'moment';
// Load the js langs
import es from 'meteor-accounts-t9n/build/es';
import en from 'meteor-accounts-t9n/build/en';
var backOpts = {
// path where resources get loaded from
loadPath: '/locales/{{lng}}/{{ns}}.json',
// path to post missing resources
addPath: '/locales/{{lng}}/{{ns}}.missing.json',
// jsonIndent to use when storing json files
jsonIndent: 2
};
const forceDebug = false;
const shouldDebug = (forceDebug && !Meteor.isProduction);
var i18nOpts = {
backend: backOpts,
lng: 'es',
// fallbackLng: 'es',
fallbackLng: {
'en-US': ['en'],
'en-GB': ['en'],
'pt-BR': ['pt'],
'default': ['es']
},
interpolation: {
escapeValue: false, // not needed for react!!
formatSeparator: ',',
format: function (value, format, lng) {
// https://www.i18next.com/formatting.html
// console.log(`Value: ${value} with format: ${format} to lang: ${lng}`);
if (format === 'uppercase') return value.toUpperCase();
if (value instanceof Date) return moment(value).format(format);
if (format === 'number') return Intl.NumberFormat(lng).format(value);
return value;
}
},
whitelist: false,
// whitelist: ['es', 'en'], // allowed languages
load: 'all', // es-ES -> es, en-US -> en
debug: shouldDebug,
ns: 'common',
defaultNS: 'common',
saveMissing: shouldDebug, // if true seems it's fails to getResourceBundle
saveMissingTo: 'es',
keySeparator: 'ß',
nsSeparator: 'ð',
pluralSeparator: 'đ'
};
export default i18nOpts;

View file

@ -1,3 +1,79 @@
import { Meteor } from 'meteor/meteor';
import nodemailer from 'nodemailer';
import { MailTime } from 'meteor/ostrio:mailer';
import i18n from 'i18next';
if (Meteor.isDevelopment) process.env.MAIL_URL = Meteor.settings.private.MAIL_URL;
// console.log(i18n.t('Inicio del mailer'));
const transports = [];
// First transport
const fstTransport = nodemailer.createTransport(Meteor.settings.private.MAIL_URL);
transports.push(fstTransport);
// console.log(fstTransport.options.auth.user);
const db = Meteor.users.rawDatabase(); // new Mongo.Collection('__mailTimeQueue__').rawDatabase();
// Use __mailTimeQueue collection in any db
// db.getCollection("__mailTimeQueue__").count()
// https://litmus.com/community/discussions/4633-is-there-a-reliable-1px-horizontal-rule-method
const hr = `<table cellspacing="0" cellpadding="0" border="0" width="100%" style="width: 100% !important;">
<tr>
<td align="left" valign="top" width="600px" height="1" style="background-color: #f0f0f0; border-collapse:collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; mso-line-height-rule: exactly; line-height: 1px;"><!--[if gte mso 15]>&nbsp;<![endif]--></td>
</tr>
</table>`;
const MailQueue = new MailTime({
db,
type: 'server',
strategy: 'balancer', // Transports will be used in round robin chain
transports,
from(transport) {
// To pass spam-filters `from` field should be correctly set
// for each transport, check `transport` object for more options
return `"${i18n.t('AppName')}" <${transport.options.auth.user}>`;
},
debug: true,
concatEmails: true, // Concatenate emails to the same addressee
concatSubject: `${i18n.t('Nuevas notificaciones de {{app}}', { app: i18n.t('AppName') })}`,
/* eslint-disable */
concatDelimiter: hr + '<h2>{{{subject}}}</h2>', // Start each concatenated email with it's own subject
/* eslint-enable */
// concatThrottling: 30,
template: MailTime.Template // Use default template
});
// A Client (not used yet)
// const MailQueueClient = new MailTime({
// db,
// type: 'client',
// debug: true,
// strategy: 'balancer', // Transports will be used in round robin chain
// concatEmails: true // Concatenate emails to the same address
// });
export default function sendMail(opts, debug) {
if (debug) {
MailQueue.sendMail(opts, (err, info) => { if (err) { console.error(err); } else { console.log(info); } });
} else {
MailQueue.sendMail(opts);
}
}
if (Meteor.settings.private.testMailer) {
const emailOpts = {
to: Meteor.settings.private.testEmail,
userName: 'someone',
sendAt: new Date(),
subject: 'Some new notification',
text: 'Plain text message',
template: '<body>{{appName}}<h2>{{{subject}}}</h2>{{{html}}}</body>',
appName: i18n.t('AppName'),
html: '<p>Styled message</p>'
};
sendMail(emailOpts, true);
sendMail(emailOpts, true);
sendMail(emailOpts, true);
sendMail(emailOpts, true);
}

View file

@ -0,0 +1,31 @@
import { Meteor } from 'meteor/meteor';
import i18n from 'i18next';
import backend from 'i18next-sync-fs-backend';
import i18nOpts from '../common/i18n';
// import moment from 'moment';
// import { T9n } from 'meteor-accounts-t9n';
i18nOpts.backend.loadPath = `${Meteor.absolutePath}/public${i18nOpts.backend.loadPath}`;
i18nOpts.backend.addPath = `${Meteor.absolutePath}/public${i18nOpts.backend.addPath}`;
// console.log(i18nOpts.backend.loadPath);
i18nOpts.debug = false;
i18nOpts.saveMissing = true;
i18nOpts.initImmediate = false;
i18n
.use(backend)
.init(i18nOpts, (err) => {
if (err) {
console.error(err);
}
});
/* export function setUserLang (lng) {
* moment.locale(lng);
* T9n.setLanguage(lng);
* } */
// console.log(i18n.t('Servidor arrancado'));
export default i18n;

View file

@ -1,3 +1,4 @@
import './i18n';
import './accounts';
import './api';
import './fixtures';

View file

@ -18,10 +18,10 @@ const positionIcon = new Leaflet.Icon({
/* shadowUrl: require('../public/marker-shadow.png'), */
iconSize: [50, 77], // size of the icon
/* shadowSize: [50, 64], // size of the shadow */
iconAnchor: [25, 82], // point of the icon which will correspond to marker's location
iconAnchor: [25, 82] // point of the icon which will correspond to marker's location
/* shadowAnchor: [4, 62], // the same for the shadow
* popupAnchor: [-3, -76]// point from which the popup should open relative to the iconAnchor*/
})
});
class SelectionMap extends Component {
constructor(props) {
@ -45,11 +45,11 @@ class SelectionMap extends Component {
}
toggleDraggable = () => {
this.setState({ draggable: !this.state.draggable })
this.setState({ draggable: !this.state.draggable });
}
updatePosition = () => {
const { lat, lng } = this.refs.marker.leafletElement.getLatLng()
const { lat, lng } = this.refs.marker.leafletElement.getLatLng();
this.setState({
marker: [ lat, lng ],
modified: true
@ -71,8 +71,8 @@ class SelectionMap extends Component {
const map = this.getMap();
var options = {
fill: 'fill',
showSubunits: true,
}
showSubunits: true
};
var graphicScale = L.control.graphicScale([options]).addTo(map);
}
@ -129,7 +129,7 @@ class SelectionMap extends Component {
</Control>
</Map> }
</div>
)
);
}
}

View file

@ -4,7 +4,7 @@ import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import { Trans, translate } from 'react-i18next';
import 'leaflet/dist/leaflet.css';
import { Circle, CircleMarker, Map, Marker, Popup, TileLayer, PropTypes as MapPropTypes } from 'react-leaflet'
import { Circle, CircleMarker, Map, Marker, Popup, TileLayer, PropTypes as MapPropTypes } from 'react-leaflet';
import ActiveFiresCollection from '../../../api/ActiveFires/ActiveFires';
import FireAlertsCollection from '../../../api/FireAlerts/FireAlerts';
import UserSubsToFiresCollection from '../../../api/Subscriptions/Subscriptions';
@ -12,7 +12,7 @@ import CenterInMyPosition from '/imports/ui/components/CenterInMyPosition/Center
import { withTracker } from 'meteor/react-meteor-data';
import Loading from '../../components/Loading/Loading';
import './FiresMap.scss';
import Leaflet from 'leaflet'
import Leaflet from 'leaflet';
import LGeo from 'leaflet-geodesy';
import union from '@turf/union';
import 'leaflet-graphicscale/dist/Leaflet.GraphicScale.min.css';
@ -36,7 +36,7 @@ const fireIcon = new Leaflet.Icon({
/* shadowUrl: require('../public/marker-shadow.png'), */
iconSize: [16, 24], // size of the icon
/* shadowSize: [50, 64], // size of the shadow */
iconAnchor: [8, 26], // point of the icon which will correspond to marker's location
iconAnchor: [8, 26] // point of the icon which will correspond to marker's location
/* shadowAnchor: [4, 62], // the same for the shadow
* popupAnchor: [-3, -76]// point from which the popup should open relative to the iconAnchor*/
})
@ -46,7 +46,7 @@ const nFireIcon = new Leaflet.Icon({
/* shadowUrl: require('../public/marker-shadow.png'), */
iconSize: [16, 24], // size of the icon
/* shadowSize: [50, 64], // size of the shadow */
iconAnchor: [8, 26], // point of the icon which will correspond to marker's location
iconAnchor: [8, 26] // point of the icon which will correspond to marker's location
/* shadowAnchor: [4, 62], // the same for the shadow
* popupAnchor: [-3, -76]// point from which the popup should open relative to the iconAnchor*/
})
@ -60,38 +60,38 @@ const MyPopupMarker = ({ children, lat, lon, nasa}) => (
</Marker>
<CircleMarker center={[lat, lon]} color={nasa? "red": "#D35400"} stroke={false} fillOpacity="1" fill={true} radius={1} />
</div>
)
);
const FireMark = ({ lat, lon, scan, nasa }) => (
<Circle center={[lat, lon]} color="red" stroke={false} fillOpacity="1" fill={true} radius={scan*1000} />
)
);
/* Less acurate (1 pixel per fire) but faster */
const FirePixel = ({ lat, lon, nasa }) => (
<CircleMarker center={[lat, lon]} color={nasa? "red": "#D35400"}
stroke={false} fillOpacity="1" fill={true} radius={2} />
)
);
MyPopupMarker.propTypes = {
// https://github.com/PaulLeCam/react-leaflet/tree/master/src/propTypes
children: MapPropTypes.children,
lat: PropTypes.number.isRequired,
lon: PropTypes.number.isRequired,
nasa: PropTypes.bool.isRequired,
}
nasa: PropTypes.bool.isRequired
};
FirePixel.propTypes = {
lat: PropTypes.number.isRequired,
lon: PropTypes.number.isRequired,
nasa: PropTypes.bool.isRequired,
}
nasa: PropTypes.bool.isRequired
};
FireMark.propTypes = {
scan: PropTypes.number.isRequired,
lat: PropTypes.number.isRequired,
lon: PropTypes.number.isRequired,
nasa: PropTypes.bool.isRequired,
}
nasa: PropTypes.bool.isRequired
};
// Below this use only pixels
const MAXZOOM = 7;
@ -99,9 +99,9 @@ const MAXZOOM = 7;
const MyMarkersList = ({ markers }) => {
const items = markers.map(({ key, ...props }) => (
<MyPopupMarker key={key} {...props} />
))
return <div style={{ display: 'none' }}>{items}</div>
}
));
return <div style={{ display: 'none' }}>{items}</div>;
};
const FireList = ({ fires, scale, useMarkers, nasa }) => {
/* if (nasa) {
@ -112,20 +112,20 @@ const FireList = ({ fires, scale, useMarkers, nasa }) => {
* }*/
const items = fires.map(({ _id, ...props }) => (
useMarkers && !scale? <MyPopupMarker key={_id} nasa={nasa} {...props} />:
(!nasa && !scale)? <FirePixel key={_id} nasa={nasa} {...props} />:<FireMark key={_id} nasa={nasa} {...props} />))
return <div style={{ display: 'none' }}>{items}</div>
}
(!nasa && !scale)? <FirePixel key={_id} nasa={nasa} {...props} />:<FireMark key={_id} nasa={nasa} {...props} />));
return <div style={{ display: 'none' }}>{items}</div>;
};
MyMarkersList.propTypes = {
markers: PropTypes.array.isRequired,
}
markers: PropTypes.array.isRequired
};
const DEF_LAT = 35.159028;
const DEF_LNG = -46.738057;
const DEFAULT_VIEWPORT = {
center: [DEF_LAT, DEF_LNG], // a point in the sea
zoom: 8,
}
zoom: 8
};
class FiresMap extends React.Component {
@ -136,13 +136,13 @@ class FiresMap extends React.Component {
modified: false,
useMarkers: false,
showSubsUnion: true
}
};
this.unionGroup = new L.LayerGroup();
}
centerOnUserLocation = (viewport) => {
this.onViewportChanged(viewport);
}
};
componentDidMount() {
height.set(this.divElement.clientHeight);
@ -156,7 +156,9 @@ class FiresMap extends React.Component {
lng.set(viewport.center[1]);
self.state.viewport = viewport;
self.state.modified = true;
self.showSubsUnion(self.state.showSubsUnion);
if (self.props.subsready && self.refs.fireMap) {
self.showSubsUnion(self.state.showSubsUnion);
}
}, 2000);
}
@ -192,17 +194,17 @@ class FiresMap extends React.Component {
if (show) {
// http://leafletjs.com/reference-1.2.0.html#path
var copts = {
parts: 144,
parts: 144
};
UserSubsToFiresCollection.find().forEach( function(subs){
var circle = LGeo.circle([subs.lat, subs.lon], subs.distance * 1000, copts)
var circle = LGeo.circle([subs.lat, subs.lon], subs.distance * 1000, copts);
circle.addTo(unionGroup);
});
this.union = unify(unionGroup.getLayers());
this.union.setStyle({
color: "#145A32",
fillColor: "green",
fillOpacity: .1,
fillOpacity: .1
});
this.union.addTo(map);
}
@ -213,15 +215,15 @@ class FiresMap extends React.Component {
const map = this.getMap();
var options = {
fill: 'fill',
showSubunits: true,
}
showSubunits: true
};
var graphicScale = L.control.graphicScale([options]).addTo(map);
}
render() {
this.state.viewport = !this.state.modified && this.props.viewport && Array.isArray(this.props.viewport.center)? this.props.viewport: this.state.viewport;
if (this.props.subsready && this.refs['fireMap']) {
if (this.props.subsready && this.refs.fireMap) {
// Show union of users
this.showSubsUnion(this.state.showSubsUnion);
};
@ -240,12 +242,12 @@ class FiresMap extends React.Component {
<h4 className="page-header"><Trans parent="span">Fuegos activos</Trans></h4>
<Row>
<Col xs={12} sm={6} md={6} lg={6} >
<p>
<p>
{this.props.activefires.length === 0?
<Trans parent="span" i18nKey="noActiveFireInMapCount">No hay fuegos activos en esta zona del mapa. Hay un total de <strong>{{countTotal: this.props.activefirestotal}}</strong> fuegos activos detectados en todo el mundo.</Trans>:<Trans parent="span" i18nKey="activeFireInMapCount">En rojo, <strong>{{count: this.props.activefires.length}}</strong> fuegos activos en el mapa. Hay un total de <strong>{{countTotal: this.props.activefirestotal}}</strong> fuegos activos detectados en todo el mundo por la NASA.</Trans>
}
</p>
<p><Trans parent="span" i18nKey="activeNeigFireInMapCount">En naranja, los fuegos notificados por nuestros usuarios/as recientemente.</Trans></p>
</p>
<p><Trans parent="span" i18nKey="activeNeigFireInMapCount">En naranja, los fuegos notificados por nuestros usuarios/as recientemente.</Trans></p>
</Col>
<Col xs={12} sm={6} md={6} lg={6} >
<Checkbox inline={false} defaultChecked={this.state.showSubsUnion} onClick={e => this.showSubsUnion(e.target.checked)}>
@ -288,8 +290,8 @@ class FiresMap extends React.Component {
</Row>
</div>
);
}
}
};
};
const zoom = new ReactiveVar(8);
const lat = new ReactiveVar(DEF_LAT);
@ -343,7 +345,7 @@ export default translate([], { wait: true }) (withTracker(() => {
userSubs: UserSubsToFiresCollection.find().fetch(),
viewport: {
center: [lat.get(), lng.get()], // a point in the sea
zoom: zoom.get(),
zoom: zoom.get()
}
};
})(FiresMap));

View file

@ -26,7 +26,8 @@ class Sandbox extends React.Component {
<div>
<FireSubscription />
</div>
)
);
}
}
export default translate([], { wait: true }) (Sandbox);