diff --git a/src/i18n.js b/src/i18n.js index 9b1cf27998..b09e84f1c7 100644 --- a/src/i18n.js +++ b/src/i18n.js @@ -53,7 +53,7 @@ _.each(langCodes, function(code){ }catch (e){} }); -var getUserLanguage = function(req, callback){ +var getUserLanguage = function(req, res, next){ var getFromBrowser = function(){ var acceptable = _(req.acceptedLanguages).map(function(lang){ return lang.slice(0, 2); @@ -62,25 +62,26 @@ var getUserLanguage = function(req, callback){ return matches.length > 0 ? matches[0] : 'en'; }; - if(req.session && req.session.userId){ + var getFromUser = function(user){ + var lang; + if(user && user.preferences.language && translations[user.preferences.language]){ + lang = _.find(avalaibleLanguages, {code: user.preferences.language}) || 'en'; + }else{ + lang = _.find(avalaibleLanguages, {code: getFromBrowser()}) || 'en'; + } + req.language = lang; + next(); + }; + + if(req.locals && req.locals.user){ + getFromUser(req.locals.user); + }else if(req.session && req.session.userId){ User.findOne({_id: req.session.userId}, function(err, user){ if(err) return callback(err); - if(user && user.preferences.language && translations[user.preferences.language]){ - return callback(null, _.find(avalaibleLanguages, {code: user.preferences.language})); - }else{ - var langCode = getFromBrowser(); - // Because english is usually always avalaible as an acceptable language for the browser, - // if the user visit the page when his own language is not avalaible yet - // he'll have english set in his preferences, which is not good. - //if(user && translations[langCode]){ - //user.preferences.language = langCode; - //user.save(); //callback? - //} - return callback(null, _.find(avalaibleLanguages, {code: langCode})) - } + getFromUser(user); }); }else{ - return callback(null, _.find(avalaibleLanguages, {code: getFromBrowser()})); + getFromUser(null); } }; diff --git a/src/middleware.js b/src/middleware.js index 232c0ab355..60e4e3f0ae 100644 --- a/src/middleware.js +++ b/src/middleware.js @@ -142,36 +142,33 @@ var getManifestFiles = function(page){ } module.exports.locals = function(req, res, next) { - i18n.getUserLanguage(req, function(err, language){ - if(err) return res.json(500, {err: err}); + var language = req.language; + var isStaticPage = req.url.split('/')[1] === 'static'; // If url contains '/static/' - var isStaticPage = req.url.split('/')[1] === 'static'; // If url contains '/static/' + // Load moment.js language file only when not on static pages + language.momentLang = ((!isStaticPage && i18n.momentLangs[language.code]) || undefined); - // Load moment.js language file only when not on static pages - language.momentLang = ((!isStaticPage && i18n.momentLangs[language.code])|| undefined); + res.locals.habitrpg = { + NODE_ENV: nconf.get('NODE_ENV'), + BASE_URL: nconf.get('BASE_URL'), + GA_ID: nconf.get("GA_ID"), + IS_MOBILE: /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(req.header('User-Agent')), + STRIPE_PUB_KEY: nconf.get('STRIPE_PUB_KEY'), + getManifestFiles: getManifestFiles, + getBuildUrl: getBuildUrl, + avalaibleLanguages: i18n.avalaibleLanguages, + language: language, + isStaticPage: isStaticPage, + translations: i18n.translations[language.code], + t: function(){ // stringName and vars are the allowed parameters + var args = Array.prototype.slice.call(arguments, 0); + args.push(language.code); + return shared.i18n.t.apply(null, args); + }, + siteVersion: siteVersion + } - res.locals.habitrpg = { - NODE_ENV: nconf.get('NODE_ENV'), - BASE_URL: nconf.get('BASE_URL'), - GA_ID: nconf.get("GA_ID"), - IS_MOBILE: /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(req.header('User-Agent')), - STRIPE_PUB_KEY: nconf.get('STRIPE_PUB_KEY'), - getManifestFiles: getManifestFiles, - getBuildUrl: getBuildUrl, - avalaibleLanguages: i18n.avalaibleLanguages, - language: language, - isStaticPage: isStaticPage, - translations: i18n.translations[language.code], - t: function(){ // stringName and vars are the allowed parameters - var args = Array.prototype.slice.call(arguments, 0); - args.push(language.code); - return shared.i18n.t.apply(null, args); - }, - siteVersion: siteVersion - } - - next(); - }); + next(); } module.exports.enTranslations = function(stringName, vars){ diff --git a/src/routes/apiv2.coffee b/src/routes/apiv2.coffee index f78d8c5707..9fbc5c4b6a 100644 --- a/src/routes/apiv2.coffee +++ b/src/routes/apiv2.coffee @@ -19,6 +19,7 @@ middleware = require("../middleware") cron = user.cron _ = require('lodash') content = require('habitrpg-shared').content +i18n = require('../i18n') module.exports = (swagger, v2) -> @@ -47,7 +48,7 @@ module.exports = (swagger, v2) -> spec: description: "Export user history" method: 'GET' - middleware: auth.auth + middleware: [auth.auth, i18n.getUserLanguage] action: dataexport.history #[todo] encode data output options in the data controller and use these to build routes # --------------------------------- @@ -138,7 +139,7 @@ module.exports = (swagger, v2) -> path("id", "Task ID", "string") query 'keep',"When unlinking a challenge task, how to handle the orphans?",'string',['keep','keep-all','remove','remove-all'] ] - middleware: auth.auth ## removing cron since they may want to remove task first + middleware: [auth.auth, i18n.getUserLanguage] ## removing cron since they may want to remove task first action: challenges.unlink @@ -227,7 +228,7 @@ module.exports = (swagger, v2) -> path: '/user' method: 'DELETE' description: "Delete a user object entirely, USE WITH CAUTION!" - middleware: auth.auth + middleware: [auth.auth, i18n.getUserLanguage] action: user["delete"] "/user/revive": @@ -299,6 +300,26 @@ module.exports = (swagger, v2) -> ] action: user.unlock +<<<<<<< HEAD +======= + "/user/buy-gems": + spec: method: 'POST', description: "Do not use this route" + middleware: [auth.auth, i18n.getUserLanguage] + action:user.buyGems + + "/user/cancel-subscription": + spec: method: 'POST', description: "Do not use this route" + middleware: [auth.auth, i18n.getUserLanguage] + action:user.cancelSubscription + + "/user/buy-gems/paypal-ipn": + spec: + method: 'POST' + description: "Don't use this route" + middleware: [] + action: user.buyGemsPaypalIPN + +>>>>>>> refactor(i18n): refactor user language detection, add to api methods "/user/batch-update": spec: method: 'POST' @@ -306,7 +327,7 @@ module.exports = (swagger, v2) -> parameters:[ body '','The array of batch-operations to perform','object' ] - middleware: [middleware.forceRefresh, auth.auth, cron] + middleware: [middleware.forceRefresh, auth.auth, i18n.getUserLanguage, cron] action: user.batchUpdate # Tags @@ -350,7 +371,7 @@ module.exports = (swagger, v2) -> parameters: [ query 'type',"Comma-separated types of groups to return, eg 'party,guilds,public,tavern'",'string' ] - middleware: auth.auth + middleware: [auth.auth, i18n.getUserLanguage] action: groups.list @@ -362,7 +383,7 @@ module.exports = (swagger, v2) -> parameters: [ body '','Group object (see GroupSchema)','object' ] - middleware: auth.auth + middleware: [auth.auth, i18n.getUserLanguage] action: groups.create "/groups/{gid}:GET": @@ -370,7 +391,7 @@ module.exports = (swagger, v2) -> path: '/groups/{gid}' description: "Get a group" parameters: [path('gid','Group ID','string')] - middleware: auth.auth + middleware: [auth.auth, i18n.getUserLanguage] action: groups.get "/groups/{gid}:POST": @@ -379,7 +400,7 @@ module.exports = (swagger, v2) -> method: 'POST' description: "Edit a group" parameters: [body('','Group object (see GroupSchema)','object')] - middleware: [auth.auth, groups.attachGroup] + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] action: groups.update "/groups/{gid}/join": @@ -387,7 +408,7 @@ module.exports = (swagger, v2) -> method: 'POST' description: 'Join a group' parameters: [path('gid','Id of the group to join','string')] - middleware: [auth.auth, groups.attachGroup] + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] action: groups.join "/groups/{gid}/leave": @@ -395,7 +416,7 @@ module.exports = (swagger, v2) -> method: 'POST' description: 'Leave a group' parameters: [path('gid','ID of the group to leave','string')] - middleware: [auth.auth, groups.attachGroup] + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] action: groups.leave "/groups/{gid}/invite": @@ -406,7 +427,7 @@ module.exports = (swagger, v2) -> path 'gid','Group id','string' query 'uuid','User id to invite','string' ] - middleware: [auth.auth, groups.attachGroup] + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] action:groups.invite "/groups/{gid}/removeMember": @@ -417,7 +438,7 @@ module.exports = (swagger, v2) -> path 'gid','Group id','string' query 'uuid','User id to boot','string' ] - middleware: [auth.auth, groups.attachGroup] + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] action:groups.removeMember "/groups/{gid}/questAccept": @@ -428,7 +449,7 @@ module.exports = (swagger, v2) -> path 'gid',"Group id",'string' query 'key',"optional. if provided, trigger new invite, if not, accept existing invite",'string' ] - middleware: [auth.auth, groups.attachGroup] + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] action:groups.questAccept "/groups/{gid}/questReject": @@ -438,7 +459,7 @@ module.exports = (swagger, v2) -> parameters: [ path 'gid','Group id','string' ] - middleware: [auth.auth, groups.attachGroup] + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] action: groups.questReject "/groups/{gid}/questAbort": @@ -446,7 +467,7 @@ module.exports = (swagger, v2) -> method: 'POST' description: 'Abort quest' parameters: [path('gid','Group to abort quest in','string')] - middleware: [auth.auth, groups.attachGroup] + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] action: groups.questAbort #TODO PUT /groups/:gid/chat/:messageId @@ -455,8 +476,12 @@ module.exports = (swagger, v2) -> spec: path: "/groups/{gid}/chat" description: "Get all chat messages" +<<<<<<< HEAD parameters: [path('gid','Group to return the chat from ','string')] middleware: [auth.auth, groups.attachGroup] +======= + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] +>>>>>>> refactor(i18n): refactor user language detection, add to api methods action: groups.getChat @@ -469,7 +494,7 @@ module.exports = (swagger, v2) -> query 'message', 'Chat message','string' path 'gid','Group id','string' ] - middleware: [auth.auth, groups.attachGroup] + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] action: groups.postChat # placing before route below, so that if !=='seen' it goes to next() @@ -480,7 +505,7 @@ module.exports = (swagger, v2) -> parameters: [ path 'gid','Group id','string' ] - middleware: [] + middleware: [i18n.getUserLanguage] action: groups.seenMessage "/groups/{gid}/chat/{messageId}": @@ -488,7 +513,7 @@ module.exports = (swagger, v2) -> method: 'DELETE' description: 'Delete a group' parameters: [path('gid','ID of group to delete','string')] - middleware: [auth.auth, groups.attachGroup] + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] action: groups.deleteChatMessage "/groups/{gid}/chat/{mid}/like": @@ -499,7 +524,7 @@ module.exports = (swagger, v2) -> path 'gid','Group id','string' path 'mid','Message id','string' ] - middleware: [auth.auth, groups.attachGroup] + middleware: [auth.auth, i18n.getUserLanguage, groups.attachGroup] action: groups.likeChatMessage # --------------------------------- @@ -514,19 +539,19 @@ module.exports = (swagger, v2) -> # --------------------------------- "/hall/heroes": spec: {} - middleware:[auth.auth] + middleware:[auth.auth, i18n.getUserLanguage] action: hall.getHeroes "/hall/heroes/{uid}:GET": spec: path: "/hall/heroes/{uid}" - middleware:[auth.auth, hall.ensureAdmin] + middleware:[auth.auth, i18n.getUserLanguage, hall.ensureAdmin] action: hall.getHero "/hall/heroes/{uid}:POST": spec: method: 'POST' path: "/hall/heroes/{uid}" - middleware: [auth.auth, hall.ensureAdmin] + middleware: [auth.auth, i18n.getUserLanguage, hall.ensureAdmin] action: hall.updateHero "/hall/patrons": @@ -534,7 +559,7 @@ module.exports = (swagger, v2) -> parameters: [ query 'page','Page number to fetch (this list is long)','string' ] - middleware:[auth.auth] + middleware:[auth.auth, i18n.getUserLanguage] action: hall.getPatrons @@ -549,7 +574,7 @@ module.exports = (swagger, v2) -> spec: path: '/challenges' description: "Get a list of challenges" - middleware: [auth.auth] + middleware: [auth.auth, i18n.getUserLanguage] action: challenges.list @@ -559,7 +584,7 @@ module.exports = (swagger, v2) -> method: 'POST' description: "Create a challenge" parameters: [body('','Challenge object (see ChallengeSchema)','object')] - middleware: [auth.auth] + middleware: [auth.auth, i18n.getUserLanguage] action: challenges.create "/challenges/{cid}:GET": @@ -584,7 +609,7 @@ module.exports = (swagger, v2) -> path 'cid','Challenge id','string' body('','Challenge object (see ChallengeSchema)','object') ] - middleware: [auth.auth] + middleware: [auth.auth, i18n.getUserLanguage] action: challenges.update "/challenges/{cid}:DELETE": @@ -593,7 +618,7 @@ module.exports = (swagger, v2) -> method: 'DELETE' description: "Delete a challenge" parameters: [path('cid','Challenge id','string')] - middleware: [auth.auth] + middleware: [auth.auth, i18n.getUserLanguage] action: challenges["delete"] "/challenges/{cid}/close": @@ -604,7 +629,7 @@ module.exports = (swagger, v2) -> path 'cid','Challenge id','string' query 'uid','User ID of the winner','string',true ] - middleware: [auth.auth] + middleware: [auth.auth, i18n.getUserLanguage] action: challenges.selectWinner "/challenges/{cid}/join": @@ -612,7 +637,7 @@ module.exports = (swagger, v2) -> method: 'POST' description: "Join a challenge" parameters: [path('cid','Challenge id','string')] - middleware: [auth.auth] + middleware: [auth.auth, i18n.getUserLanguage] action: challenges.join "/challenges/{cid}/leave": @@ -620,7 +645,7 @@ module.exports = (swagger, v2) -> method: 'POST' description: 'Leave a challenge' parameters: [path('cid','Challenge id','string')] - middleware: [auth.auth] + middleware: [auth.auth, i18n.getUserLanguage] action: challenges.leave "/challenges/{cid}/member/{uid}": @@ -630,7 +655,7 @@ module.exports = (swagger, v2) -> path 'cid','Challenge id','string' path 'uid','User id','string' ] - middleware: [auth.auth] + middleware: [auth.auth, i18n.getUserLanguage] action: challenges.getMember @@ -662,7 +687,7 @@ module.exports = (swagger, v2) -> #type: 'Pet' errorResponses: [] method: 'GET' - route.middleware ?= if path.indexOf('/user') is 0 then [auth.auth, cron] else [] + route.middleware ?= if path.indexOf('/user') is 0 then [auth.auth, i18n.getUserLanguage, cron] else [] swagger["add#{route.spec.method}"](route);true diff --git a/src/routes/dataexport.js b/src/routes/dataexport.js index b84fe09bd3..ad2e2797d0 100644 --- a/src/routes/dataexport.js +++ b/src/routes/dataexport.js @@ -3,10 +3,11 @@ var router = new express.Router(); var dataexport = require('../controllers/dataexport'); var auth = require('../controllers/auth'); var nconf = require('nconf'); +var i18n = require('../i18n') /* Data export */ -router.get('/history.csv',auth.authWithSession,dataexport.history); //[todo] encode data output options in the data controller and use these to build routes -router.get('/userdata.xml',auth.authWithSession,dataexport.leanuser,dataexport.userdata.xml); -router.get('/userdata.json',auth.authWithSession,dataexport.leanuser,dataexport.userdata.json); +router.get('/history.csv',auth.authWithSession,i18n.getUserLanguage,dataexport.history); //[todo] encode data output options in the data controller and use these to build routes +router.get('/userdata.xml',auth.authWithSession,i18n.getUserLanguage,dataexport.leanuser,dataexport.userdata.xml); +router.get('/userdata.json',auth.authWithSession,i18n.getUserLanguage,dataexport.leanuser,dataexport.userdata.json); module.exports = router; diff --git a/src/routes/pages.js b/src/routes/pages.js index 80e7be54e1..d18a50cfaa 100644 --- a/src/routes/pages.js +++ b/src/routes/pages.js @@ -3,11 +3,15 @@ var express = require('express'); var router = new express.Router(); var _ = require('lodash'); var middleware = require('../middleware'); +<<<<<<< HEAD var user = require('../controllers/user'); var auth = require('../controllers/auth'); +======= +var i18n = require('../i18n'); +>>>>>>> refactor(i18n): refactor user language detection, add to api methods // -------- App -------- -router.get('/', middleware.locals, function(req, res) { +router.get('/', i18n.getUserLanguage, middleware.locals, function(req, res) { if (!req.headers['x-api-user'] && !req.headers['x-api-key'] && !(req.session && req.session.userId)) return res.redirect('/static/front') @@ -19,35 +23,35 @@ router.get('/', middleware.locals, function(req, res) { // -------- Marketing -------- -router.get('/static/front', middleware.locals, function(req, res) { +router.get('/static/front', i18n.getUserLanguage, middleware.locals, function(req, res) { res.render('static/front', {env: res.locals.habitrpg}); }); -router.get('/static/privacy', middleware.locals, function(req, res) { +router.get('/static/privacy', i18n.getUserLanguage, middleware.locals, function(req, res) { res.render('static/privacy', {env: res.locals.habitrpg}); }); -router.get('/static/terms', middleware.locals, function(req, res) { +router.get('/static/terms', i18n.getUserLanguage, middleware.locals, function(req, res) { res.render('static/terms', {env: res.locals.habitrpg}); }); -router.get('/static/api', middleware.locals, function(req, res) { +router.get('/static/api', i18n.getUserLanguage, middleware.locals, function(req, res) { res.render('static/api', {env: res.locals.habitrpg}); }); -router.get('/static/features', middleware.locals, function(req, res) { +router.get('/static/features', i18n.getUserLanguage, middleware.locals, function(req, res) { res.render('static/features', {env: res.locals.habitrpg}); }); -router.get('/static/videos', middleware.locals, function(req, res) { +router.get('/static/videos', i18n.getUserLanguage, middleware.locals, function(req, res) { res.render('static/videos', {env: res.locals.habitrpg}); }); -router.get('/static/contact', middleware.locals, function(req, res) { +router.get('/static/contact', i18n.getUserLanguage, middleware.locals, function(req, res) { res.render('static/contact', {env: res.locals.habitrpg}); }); -router.get('/static/plans', middleware.locals, function(req, res) { +router.get('/static/plans', i18n.getUserLanguage, middleware.locals, function(req, res) { res.render('static/plans', {env: res.locals.habitrpg}); });