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-13 00:28:56 +02:00
"github.com/gorilla/mux"
)
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-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-13 02:01:17 +02:00
format := r . URL . Query ( ) . Get ( "format" )
if format == "json" {
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-15 13:55:16 +02:00
clv := ChangeLanguageVariables { NewSearchForm ( ) , NewNavigation ( ) , Tlang . Tag , availableLanguages , GetUser ( r ) , r . URL , mux . CurrentRoute ( r ) }
2017-05-14 21:45:50 +02:00
languages . SetTranslationFromRequest ( changeLanguageTemplate , r )
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
}
}
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.
user , err := userService . CurrentUser ( r )
if err == nil {
user . Language = lang
// I don't know if I should use this...
userService . UpdateUserCore ( & user )
} else {
http . SetCookie ( w , & http . Cookie { Name : "lang" , Value : lang } )
}
url , _ := Router . Get ( "home" ) . URL ( )
http . Redirect ( w , r , url . String ( ) , http . StatusSeeOther )
}