Email translations

This commit is contained in:
vjrj 2018-01-22 13:27:46 +01:00
parent 952431d296
commit 6c8fa91f64
30 changed files with 1844 additions and 107 deletions

View file

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

View file

@ -1,17 +1,20 @@
import i18n from 'i18next';
import sendEmail from '../../../modules/server/send-email';
import getOAuthProfile from '../../../modules/get-oauth-profile';
export default (options, user) => {
const OAuthProfile = getOAuthProfile(options, user);
const applicationName = '¡Tod@s contra el Fuego!';
const applicationName = i18n.t('AppName');
const firstName = OAuthProfile ? OAuthProfile.name.first : options.profile.name.first;
const emailAddress = OAuthProfile ? OAuthProfile.email : options.email;
const { lang } = user.lang;
return sendEmail({
to: emailAddress,
from: `${applicationName} <noreply@comunes.org>`,
subject: `[${applicationName}] Welcome, ${firstName}!`,
lang,
template: 'welcome',
templateVars: {
applicationName,

View file

@ -0,0 +1,26 @@
import fs from 'fs';
const as = f => `assets/app/${f}`;
export const getFallbackLang = (lang) => {
if (lang === 'ast' || lang === 'gl' || lang === 'eu' || lang === 'ca') {
return 'es';
}
return 'en';
};
export const getFileNameOfLang = (dir, fileName, ext, lang) => {
const base = `${dir}/${fileName}`;
const fallback = getFallbackLang(lang);
let file = `${base}-${lang}.${ext}`;
if (!fs.existsSync(as(file))) {
console.log(`Page '${fileName}' not found for '${lang}' lang`);
file = `${base}-${fallback}.${ext}`;
if (!fs.existsSync(as(file))) {
console.log(`Page '${fileName}' not found for '${fallback}' lang`);
file = `${base}.${ext}`;
}
}
return file;
};

View file

@ -1,15 +1,24 @@
import { Meteor } from 'meteor/meteor';
import { Email } from 'meteor/email';
// import { Email } from 'meteor/email';
import getPrivateFile from './get-private-file';
import templateToText from './handlebars-email-to-text';
import templateToHTML from './handlebars-email-to-html';
import { getFileNameOfLang } from '/imports/api/Utility/server/files.js';
import sendMail from '/imports/startup/server/email';
import i18n from 'i18next';
const sendEmail = (options, { resolve, reject }) => {
try {
Meteor.defer(() => {
// TODO: replace with import sendMail from '/imports/startup/server/email';
console.log(`Email options: ${options}`);
Email.send(options);
// Meteor email options:
// basic: from, to/cc/bcc/replyTo, subject, html, text,
// others: watchHtml, icalEvent, headers, attachments, mailComposer, inReplyTo, references, messageId
const opts = options;
opts.template = '<body><h2>{{appName}}</h2>{{{html}}}</body>';
opts.appName = i18n.t('AppName');
// console.log(`Email options: ${JSON.stringify(opts)}`);
sendMail(opts, true);
// Email.send(options);
resolve();
});
} catch (exception) {
@ -18,14 +27,14 @@ const sendEmail = (options, { resolve, reject }) => {
};
export default ({
text, html, template, templateVars, ...rest
text, html, lang, template, templateVars, ...rest
}) => {
if (text || html || template) {
return new Promise((resolve, reject) => {
sendEmail({
...rest,
text: template ? templateToText(getPrivateFile(`email-templates/${template}.txt`), (templateVars || {})) : text,
html: template ? templateToHTML(getPrivateFile(`email-templates/${template}.html`), (templateVars || {})) : html
text: template ? templateToText(getPrivateFile(getFileNameOfLang('email-templates', template, 'txt', lang)), (templateVars || {})) : text,
html: template ? templateToHTML(getPrivateFile(getFileNameOfLang('email-templates', template, 'html', lang)), (templateVars || {})) : html
}, { resolve, reject });
});
}

View file

@ -1,10 +1,12 @@
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import i18n from 'i18next';
import { getFileNameOfLang } from '/imports/api/Utility/server/files.js';
import getPrivateFile from '../../../modules/server/get-private-file';
import templateToHTML from '../../../modules/server/handlebars-email-to-html';
import templateToText from '../../../modules/server/handlebars-email-to-text';
const name = '¡Tod@s contra el Fuego!';
const name = i18n.t('AppName');
const email = '<noreply@comunes.org>';
const from = `${name} ${email}`;
const emailTemplates = Accounts.emailTemplates;
@ -17,7 +19,7 @@ emailTemplates.verifyEmail = {
return `[${name}] Verify Your Email Address`;
},
html(user, url) {
return templateToHTML(getPrivateFile('email-templates/verify-email.html'), {
return templateToHTML(getPrivateFile(getFileNameOfLang('email-templates', 'verify-email', 'html', user.lang)), {
applicationName: name,
firstName: user.profile.name.first,
verifyUrl: url.replace('#/', '')
@ -26,12 +28,12 @@ emailTemplates.verifyEmail = {
text(user, url) {
const urlWithoutHash = url.replace('#/', '');
if (Meteor.isDevelopment) console.info(`Verify Email Link: ${urlWithoutHash}`); // eslint-disable-line
return templateToText(getPrivateFile('email-templates/verify-email.txt'), {
return templateToText(getPrivateFile(getFileNameOfLang('email-templates', 'verify-email', 'txt', user.lang)), {
applicationName: name,
firstName: user.profile.name.first,
verifyUrl: urlWithoutHash,
verifyUrl: urlWithoutHash
});
},
}
};
emailTemplates.resetPassword = {
@ -39,21 +41,21 @@ emailTemplates.resetPassword = {
return `[${name}] Reset Your Password`;
},
html(user, url) {
return templateToHTML(getPrivateFile('email-templates/reset-password.html'), {
return templateToHTML(getPrivateFile(getFileNameOfLang('email-templates', 'reset-password', 'html', user.lang)), {
firstName: user.profile.name.first,
applicationName: name,
emailAddress: user.emails[0].address,
resetUrl: url.replace('#/', ''),
resetUrl: url.replace('#/', '')
});
},
text(user, url) {
const urlWithoutHash = url.replace('#/', '');
if (Meteor.isDevelopment) console.info(`Reset Password Link: ${urlWithoutHash}`); // eslint-disable-line
return templateToText(getPrivateFile('email-templates/reset-password.txt'), {
return templateToText(getPrivateFile(getFileNameOfLang('email-templates', 'reset-password', 'txt', user.lang)), {
firstName: user.profile.name.first,
applicationName: name,
emailAddress: user.emails[0].address,
resetUrl: urlWithoutHash,
resetUrl: urlWithoutHash
});
},
}
};

View file

@ -3,7 +3,15 @@ import sendWelcomeEmail from '../../../api/Users/server/send-welcome-email';
Accounts.onCreateUser((options, user) => {
const userToCreate = user;
if (options.profile) userToCreate.profile = options.profile;
sendWelcomeEmail(options, user);
console.log(JSON.stringify(user));
console.log(JSON.stringify(options));
if (options.profile) {
userToCreate.profile = options.profile;
userToCreate.lang = options.profile.lang;
delete options.profile.lang;
} else {
// TODO others (google, etc) ?
}
sendWelcomeEmail(options, userToCreate);
return userToCreate;
});

View file

@ -5,8 +5,9 @@ import { Meteor } from 'meteor/meteor';
import moment from 'moment';
import { dateLongFormat } from '/imports/api/Common/dates';
import Notifications from '/imports/api/Notifications/Notifications';
import sendMail from '/imports/startup/server/email';
import { hr } from '/imports/startup/server/email';
// import sendMail from '/imports/startup/server/email';
import sendEmail from '/imports/modules/server/send-email';
// import { hr } from '/imports/startup/server/email';
import getOAuthProfile from '/imports/modules/get-oauth-profile';
import image from 'google-maps-image-api-url';
import { trim } from '/imports/ui/components/NotificationsObserver/util.js';
@ -40,9 +41,10 @@ Meteor.startup(() => {
});
}
/*
function imgEl(lat, lng) {
return `<img src="${imgUrl(lat, lng)}" width="640" height="480"/>`;
}
} */
function process(notif) {
if (notif.type === 'web' && !notif.emailNotified) {
@ -58,31 +60,41 @@ Meteor.startup(() => {
const emailAddress = OAuthProfile ? OAuthProfile.email :
user && user.emails[0] && user.emails[0].verified ? user.emails[0].address : null;
if (emailAddress) {
const img = imgEl(notif.geo.coordinates[1], notif.geo.coordinates[0]);
const img = imgUrl(notif.geo.coordinates[1], notif.geo.coordinates[0]);
// const url = imgUrl(notif.geo.coordinates[1], notif.geo.coordinates[0]);
const fireUrl = `${Meteor.absoluteUrl('fire/')}${notif.sealed}`;
const fireHtmlUrl = `<a href="${fireUrl}">${i18n.t('Más información sobre este fuego')}</a>`;
// const fireHtmlUrl = `<a href="${fireUrl}">${i18n.t('Más información sobre este fuego')}</a>`;
// TODO get _id of fire
const fireTextUrl = `${i18n.t('Más información sobre este fuego')}:\n${fireUrl}`;
// const fireTextUrl = `${i18n.t('Más información sobre este fuego')}:\n${fireUrl}`;
// FIXME use our map as url and static map as img
moment.locale(user.lang);
// moment user tz ?
const message = `${trim(notif.content)} (${i18n.t('fireDetectedAt', { when: dateLongFormat(notif.when) })}).`;
// TODO unsubscribe link
// TODO Address
// TODO Comunes Address
const emailOpts = {
to: emailAddress,
userName: firstName,
sendAt: new Date(),
// userName: firstName,
// sendAt: new Date(),
subject: truncate.apply(message, [50, true]),
text: `${message}\n\n${fireTextUrl}\n\n`,
template: '<body><h2>{{appName}}</h2>{{{html}}}</body>',
appName: i18n.t('AppName'),
html: `<p>${message}</p><p>${fireHtmlUrl}</p>${hr}<p>${img}</p>`
// text: `${message}\n\n${fireTextUrl}\n\n`,
// template: '<body><h2>{{appName}}</h2>{{{html}}}</body>',
lang: user.lang,
template: 'new-fire',
templateVars: {
applicationName: i18n.t('AppName'),
firstName,
message,
fireUrl,
img,
subsUrl: Meteor.absoluteUrl('subscriptions')
}
};
sendMail(emailOpts, true);
sendEmail(emailOpts).catch((error) => {
throw new Meteor.Error('500', `${error}`);
});
// sendMail(emailOpts, true);
Notifications.update(notif._id, { $set: { emailNotified: true, emailNotifiedAt: new Date() } });
}
}

View file

@ -11,7 +11,7 @@ const Privacy = props => (
<div className="Privacy">
<Page
title={props.t('Política de Privacidad')}
subtitle={props.t('Última actualización, {{when}}', { when: dateParseShortFormat('2017-01-19') })}
subtitle={props.t('Última actualización, {{when}}', { when: dateParseShortFormat('2018-01-19') })}
page="privacy"
/>
</div>

View file

@ -48,34 +48,34 @@ class Profile extends React.Component {
required() {
// Only required if newPassword field has a value.
return component.newPassword.value.length > 0;
},
}
},
newPassword: {
required() {
// Only required if currentPassword field has a value.
return component.currentPassword.value.length > 0;
},
},
}
}
},
messages: {
firstName: {
required: this.t("¿Cuál es tu nombre?"),
required: this.t('¿Cuál es tu nombre?')
},
lastName: {
required: this.t("¿Cuál es tu apellido?"),
required: this.t('¿Cuál es tu apellido?')
},
emailAddress: {
required: this.t("Necesitamos una contraseña aquí."),
email: this.t("¿Es correcto este correo?"),
required: this.t('Necesitamos una contraseña aquí.'),
email: this.t('¿Es correcto este correo?')
},
currentPassword: {
required: this.t("Necesito tu contraseña si la quieres cambiar."),
required: this.t('Necesito tu contraseña si la quieres cambiar.')
},
newPassword: {
required: this.t("Necesito tu nueva contraseña si la quieres cambiar."),
},
required: this.t('Necesito tu nueva contraseña si la quieres cambiar.')
}
},
submitHandler() { component.handleSubmit(); },
submitHandler() { component.handleSubmit(); }
});
}
@ -104,16 +104,16 @@ class Profile extends React.Component {
profile: {
name: {
first: this.firstName.value,
last: this.lastName.value,
},
},
last: this.lastName.value
}
}
};
Meteor.call('users.editProfile', profile, (error) => {
if (error) {
Bert.alert(T9n.get(`error.accounts.${error.reason}`), 'danger');
} else {
Bert.alert(this.t("¡Perfíl actualizado!"), 'success');
Bert.alert(this.t('¡Perfíl actualizado!'), 'success');
}
});
@ -134,29 +134,32 @@ class Profile extends React.Component {
{Object.keys(user.services).map(service => (
<div key={service} className={`LoggedInWith ${service}`}>
<img src={`/${service}.svg`} alt={service} />
<p>{`You're logged in with ${_.capitalize(service)} using the email address ${user.services[service].email}.`}</p>
<p>{this.props.t('Has iniciado sesión con {{service}} usando la dirección de correo {{email}}.', { service: _.capitalize(service), email: user.services[service].email })}</p>
<Button
className={`btn btn-${service}`}
href={{
facebook: 'https://www.facebook.com/settings',
google: 'https://myaccount.google.com/privacy#personalinfo',
github: 'https://github.com/settings/profile',
github: 'https://github.com/settings/profile'
}[service]}
target="_blank"
>{this.t("Editar perfíl en")} {_.capitalize(service)}</Button>
>{this.t('Editar perfíl en')} {_.capitalize(service)}
</Button>
</div>
))}
</div>) : <div />;
}
renderPasswordUser(loading, user) {
const {t, i18n} = this.props;
const langName = { 'en': 'English', 'es': 'Español', 'gl': 'Galego', 'ast': 'Asturianu', 'ca': 'Català' };
const { t, i18n } = this.props;
const langName = {
en: 'English', es: 'Español', gl: 'Galego', ast: 'Asturianu', ca: 'Català'
};
return !loading ? (<div>
<Row>
<Col xs={6}>
<FormGroup>
<ControlLabel>{this.t("Nombre")}</ControlLabel>
<ControlLabel>{this.t('Nombre')}</ControlLabel>
<input
type="text"
name="firstName"
@ -168,7 +171,7 @@ class Profile extends React.Component {
</Col>
<Col xs={6}>
<FormGroup>
<ControlLabel>{this.t("Apellidos")}</ControlLabel>
<ControlLabel>{this.t('Apellidos')}</ControlLabel>
<input
type="text"
name="lastName"
@ -180,7 +183,7 @@ class Profile extends React.Component {
</Col>
</Row>
<FormGroup>
<ControlLabel>{this.t("Correo electrónico")}</ControlLabel>
<ControlLabel>{this.t('Correo electrónico')}</ControlLabel>
<input
type="email"
name="emailAddress"
@ -190,27 +193,28 @@ class Profile extends React.Component {
/>
</FormGroup>
<FormGroup>
<ControlLabel>{this.t("Idioma")}</ControlLabel>
<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">
{langName[i18n.language]}
</button>
<div className="dropdown-menu">
{i18n.languages.map(lang => (
<button
className="dropdown-item"
onClick={() => this.onLangSelect(lang)}
key={lang}
type="button">
{langName[lang]}
</button>
<ControlLabel>{this.t('Idioma')}</ControlLabel>
<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">
{langName[i18n.language]}
</button>
<div className="dropdown-menu">
{i18n.languages.map(lang => (
<button
className="dropdown-item"
onClick={() => this.onLangSelect(lang)}
key={lang}
type="button"
>
{langName[lang]}
</button>
))
}
</div>
</div>
</div>
</FormGroup>
<FormGroup>
<ControlLabel>{this.t("Contraseña actual")}</ControlLabel>
<ControlLabel>{this.t('Contraseña actual')}</ControlLabel>
<input
type="password"
name="currentPassword"
@ -219,23 +223,23 @@ class Profile extends React.Component {
/>
</FormGroup>
<FormGroup>
<ControlLabel>{this.t("Nueva contraseña")}</ControlLabel>
<ControlLabel>{this.t('Nueva contraseña')}</ControlLabel>
<input
type="password"
name="newPassword"
ref={newPassword => (this.newPassword = newPassword)}
className="form-control"
/>
<InputHint>{this.t("Usa al menos seis caracteres.")}</InputHint>
<InputHint>{this.t('Usa al menos seis caracteres.')}</InputHint>
</FormGroup>
<Button type="submit" bsStyle="success">{this.t("Guardar perfíl")}</Button>
<Button type="submit" bsStyle="success">{this.t('Guardar perfíl')}</Button>
</div>) : <div />;
}
renderProfileForm(loading, user) {
return !loading ? ({
password: this.renderPasswordUser,
oauth: this.renderOAuthUser,
oauth: this.renderOAuthUser
}[this.getUserType(user)])(loading, user) : <div />;
}
@ -244,7 +248,7 @@ class Profile extends React.Component {
return (<div className="Profile">
<Row className="align-items-center justify-content-center">
<Col xs={12} sm={6} md={4}>
<h4 className="page-header">{this.t("Editar perfíl")}</h4>
<h4 className="page-header">{this.t('Editar perfíl')}</h4>
<form ref={form => (this.form = form)} onSubmit={event => event.preventDefault()}>
{this.renderProfileForm(loading, user)}
</form>

View file

@ -1,7 +1,7 @@
/* eslint-disable react/jsx-indent-props */
import React from 'react';
import { Row, FormGroup, ControlLabel, Button } from 'react-bootstrap';
import { Row, FormGroup, ControlLabel, Button, Checkbox } from 'react-bootstrap';
import Col from '../../components/Col/Col';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
@ -15,7 +15,7 @@ import InputHint from '../../components/InputHint/InputHint';
import AccountPageFooter from '../../components/AccountPageFooter/AccountPageFooter';
import validate from '../../../modules/validate';
import './Signup.scss';
import { translate } from 'react-i18next';
import { translate, Trans } from 'react-i18next';
import { T9n } from 'meteor-accounts-t9n';
class Signup extends React.Component {
@ -24,7 +24,8 @@ class Signup extends React.Component {
this.t = props.t;
this.handleSubmit = this.handleSubmit.bind(this);
// console.log(props.location.state);
this.state = props.location.state;
this.state = props.location.state ? props.location.state : {};
this.state.termsAccept = false;
}
componentDidMount() {
@ -68,12 +69,13 @@ class Signup extends React.Component {
}
handleSubmit() {
const { history, t } = this.props;
const { history, t, i18n } = this.props;
Accounts.createUser({
email: this.emailAddress.value,
password: this.password.value,
profile: {
lang: i18n.language,
name: {
first: this.firstName.value,
last: this.lastName.value
@ -90,6 +92,10 @@ class Signup extends React.Component {
});
}
setTermsAccept(termsAccept) {
this.setState({ termsAccept });
}
render() {
const { t, history } = this.props;
return (<div className="Signup">
@ -161,7 +167,11 @@ class Signup extends React.Component {
/>
<InputHint>{t('Usa al menos seis caracteres.')}</InputHint>
</FormGroup>
<Button type="submit" bsStyle="success">{t('Registrarse')}</Button>
<Checkbox inline={false} defaultChecked={this.state.termsAccept} onClick={e => this.setTermsAccept(e.target.checked)}>
<Trans className="mark-checkbox" parent="span" i18nKey="termsAccept">Acepto las <a target="_blank" href="/terms">condiciones de servicio</a> de este sitio</Trans>
</Checkbox>
<Button type="submit" disabled={!this.state.termsAccept} bsStyle="success">{t('Registrarse')}</Button>
<AccountPageFooter>
<p>{t('¿Ya tienes un cuenta?')} <Link to={{ pathname: '/login', state: this.state }} >{t('Iniciar sesión')}</Link>.</p>
</AccountPageFooter>

View file

@ -11,7 +11,7 @@ const Terms = props => (
<div className="Terms">
<Page
title={props.t('Términos de Servicio')}
subtitle={props.t('Última actualización, {{when}}', { when: dateParseShortFormat('2017-01-19') })}
subtitle={props.t('Última actualización, {{when}}', { when: dateParseShortFormat('2018-01-19') })}
page="terms"
/>
</div>