2017-05-17 07:58:40 +02:00
package router
2017-05-13 00:28:56 +02:00
import (
2017-05-13 02:01:17 +02:00
"encoding/json"
2017-05-13 00:28:56 +02:00
"net/http"
2017-05-17 07:58:40 +02:00
"github.com/NyaaPantsu/nyaa/service/user"
"github.com/NyaaPantsu/nyaa/util/languages"
2017-05-21 02:12:29 +02:00
"github.com/NyaaPantsu/nyaa/util/timeHelper"
2017-05-13 00:28:56 +02:00
)
2017-05-25 21:54:58 +02:00
// LanguagesJSONResponse : Structure containing all the languages to parse it as a JSON response
2017-05-13 02:01:17 +02:00
type LanguagesJSONResponse struct {
2017-05-17 07:58:40 +02:00
Current string ` json:"current" `
2017-05-13 02:01:17 +02:00
Languages map [ string ] string ` json:"languages" `
}
2017-05-25 21:54:58 +02:00
// SeeLanguagesHandler : Controller to view the languages
2017-05-13 00:28:56 +02:00
func SeeLanguagesHandler ( w http . ResponseWriter , r * http . Request ) {
2017-05-14 21:45:50 +02:00
_ , Tlang := languages . GetTfuncAndLanguageFromRequest ( r )
2017-05-13 00:28:56 +02:00
availableLanguages := languages . GetAvailableLanguages ( )
2017-05-19 04:55:59 +02:00
contentType := r . Header . Get ( "Content-Type" )
if contentType == "application/json" {
2017-05-13 02:01:17 +02:00
w . Header ( ) . Set ( "Content-Type" , "application/json" )
err := json . NewEncoder ( w ) . Encode ( LanguagesJSONResponse { Tlang . Tag , availableLanguages } )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
} else {
2017-05-25 21:54:58 +02:00
clv := changeLanguageVariables {
commonTemplateVariables : newCommonVariables ( r ) ,
2017-05-24 09:11:13 +02:00
Language : Tlang . Tag ,
Languages : availableLanguages ,
2017-05-19 04:55:59 +02:00
}
2017-05-13 02:01:17 +02:00
err := changeLanguageTemplate . ExecuteTemplate ( w , "index.html" , clv )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
2017-05-13 00:28:56 +02:00
}
}
2017-05-25 21:54:58 +02:00
// ChangeLanguageHandler : Controller for changing the current language
2017-05-13 00:28:56 +02:00
func ChangeLanguageHandler ( w http . ResponseWriter , r * http . Request ) {
lang := r . FormValue ( "language" )
availableLanguages := languages . GetAvailableLanguages ( )
if _ , exists := availableLanguages [ lang ] ; ! exists {
http . Error ( w , "Language not available" , http . StatusInternalServerError )
return
}
// If logged in, update user language; if not, set cookie.
2017-05-21 02:12:29 +02:00
user , _ := userService . CurrentUser ( r )
2017-05-24 09:11:13 +02:00
if user . ID > 0 {
2017-05-13 00:28:56 +02:00
user . Language = lang
// I don't know if I should use this...
userService . UpdateUserCore ( & user )
}
2017-05-21 02:12:29 +02:00
http . SetCookie ( w , & http . Cookie { Name : "lang" , Value : lang , Expires : timeHelper . FewDaysLater ( 365 ) } )
2017-05-13 00:28:56 +02:00
url , _ := Router . Get ( "home" ) . URL ( )
http . Redirect ( w , r , url . String ( ) , http . StatusSeeOther )
}