Albirew/nyaa-pantsu
Archivé
1
0
Bifurcation 0
Ce dépôt a été archivé le 2022-05-07. Vous pouvez voir ses fichiers ou le cloner, mais pas ouvrir de ticket ou de demandes d'ajout, ni soumettre de changements.
nyaa-pantsu/util/publicSettings/publicSettings.go
akuma06 5991a21818 First batch of changes for the refactor (#1078)
* First batch of changes for the refactor

Added the support of gin in routes and other services/utils
Begining implementation of JetHTML

* Remove os folder

* Move scrapers to own repo

* Second batch of changes

All .jet.html are the working templates.
You can now test this PR, the index Page and upload works. If you want to complete the other html templates, you're welcome

* Move captcha to util

* Move uploadService to utils

* Use govalidator instead of regex

* Third batch of changes

All the front end should as previously.
I also fixed some minor things unrelated to the refactor (mostly style issues on static pages)
Now errors can be accessed by importing the "errors" helpers and using the `yield errors(name="xxx")` command in templates.
Same for infos.
Templates are now more hierarchized with a base template "base.jet.html" which is extended depending on the context in "index_site" or "index_admin" layouts. Those layouts are extended than in every pages.
Other helpers are captcha to render a captcha `yield captcha(captchaid="xxx")`
And also csrf, with the command `yield csrf_field()`
To translate, you don't have anymore to do `call $.T "xxx"`, you just have to do `T("xxx")`.

Pages for the website part are in folders in the folder "templates/site". Pages for the admin part are in "templates/admin". Layouts are separated in "templates/layouts". Helpers and menu are in "templates/layouts/helpers" and "templates/layouts/menu". Error pages should be put in "templates/errors"

* Added test on templates

When adding a new template, you have to tell to template_test.go, the context of the new template (if it doesn't use the common context)

* Panel admin works

Now the templating part should work. The PR can now be fully tested.

I think we should push the templating PR  and do the routes/controllers/removal of services in another branch. So we know that this one is functional

* Updated dependencies

* Fixed test for modelhelper

* Fix testing for commentlist

* Fix travis :')

* Just renamed router and removed network

* Applying same SEO fix

* Update form_validator.go

* Added back regexp package
2017-06-28 21:42:38 +10:00

183 lignes
5,1 Kio
Go

package publicSettings
import (
"errors"
"fmt"
"html/template"
"path"
"path/filepath"
"github.com/NyaaPantsu/nyaa/config"
"github.com/NyaaPantsu/nyaa/model"
"github.com/gin-gonic/gin"
"github.com/nicksnyder/go-i18n/i18n"
"github.com/nicksnyder/go-i18n/i18n/language"
)
// UserRetriever : this interface is required to prevent a cyclic import between the languages and userService package.
type UserRetriever interface {
RetrieveCurrentUser(c *gin.Context) (model.User, error)
}
// TemplateTfunc : T func used in template
type TemplateTfunc func(string, ...interface{}) template.HTML
var (
defaultLanguage = config.Conf.I18n.DefaultLanguage
userRetriever UserRetriever
)
// InitI18n : Initialize the languages translation
func InitI18n(conf config.I18nConfig, retriever UserRetriever) error {
defaultLanguage = conf.DefaultLanguage
userRetriever = retriever
defaultFilepath := path.Join(conf.Directory, defaultLanguage+".all.json")
err := i18n.LoadTranslationFile(defaultFilepath)
if err != nil {
panic(fmt.Sprintf("failed to load default translation file '%s': %v", defaultFilepath, err))
}
paths, err := filepath.Glob(path.Join(conf.Directory, "*.json"))
if err != nil {
return fmt.Errorf("failed to get translation files: %v", err)
}
for _, file := range paths {
err := i18n.LoadTranslationFile(file)
if err != nil {
return fmt.Errorf("failed to load translation file '%s': %v", file, err)
}
}
return nil
}
// GetDefaultLanguage : returns the default language from config
func GetDefaultLanguage() string {
return defaultLanguage
}
// TfuncAndLanguageWithFallback : When go-i18n finds a language with >0 translations, it uses it as the Tfunc
// However, if said language has a missing translation, it won't fallback to the "main" language
func TfuncAndLanguageWithFallback(language string, languages ...string) (i18n.TranslateFunc, *language.Language, error) {
fallbackLanguage := GetDefaultLanguage()
tFunc, tLang, err1 := i18n.TfuncAndLanguage(language, languages...)
// If fallbackLanguage fails, it will give the "id" field so we don't
// care about the error
fallbackT, fallbackTlang, _ := i18n.TfuncAndLanguage(fallbackLanguage)
translateFunction := func(translationID string, args ...interface{}) string {
if translated := tFunc(translationID, args...); translated != translationID {
return translated
}
return fallbackT(translationID, args...)
}
if err1 != nil {
tLang = fallbackTlang
}
return translateFunction, tLang, err1
}
// GetAvailableLanguages : Get languages available on the website
func GetAvailableLanguages() (languages map[string]string) {
languages = make(map[string]string)
var T i18n.TranslateFunc
for _, languageTag := range i18n.LanguageTags() {
T, _ = i18n.Tfunc(languageTag)
/* Translation files should have an ID with the translated language name.
If they don't, just use the languageTag */
if languageName := T("language_name"); languageName != "language_name" {
languages[languageTag] = languageName
} else {
languages[languageTag] = languageTag
}
}
return
}
// GetDefaultTfunc : Gets T func from default language
func GetDefaultTfunc() (i18n.TranslateFunc, error) {
return i18n.Tfunc(defaultLanguage)
}
// GetTfuncAndLanguageFromRequest : Gets the T func and chosen language from the request
func GetTfuncAndLanguageFromRequest(c *gin.Context) (T i18n.TranslateFunc, Tlang *language.Language) {
userLanguage := ""
user, _ := getCurrentUser(c)
if user.ID > 0 {
userLanguage = user.Language
}
cookie, err := c.Cookie("lang")
cookieLanguage := ""
if err == nil {
cookieLanguage = cookie
}
// go-i18n supports the format of the Accept-Language header
headerLanguage := c.Request.Header.Get("Accept-Language")
T, Tlang, _ = TfuncAndLanguageWithFallback(userLanguage, cookieLanguage, headerLanguage)
return
}
// GetTfuncFromRequest : Gets the T func from the request
func GetTfuncFromRequest(c *gin.Context) TemplateTfunc {
T, _ := GetTfuncAndLanguageFromRequest(c)
return func(id string, args ...interface{}) template.HTML {
return template.HTML(fmt.Sprintf(T(id), args...))
}
}
// GetThemeFromRequest: Gets the user selected theme from the request
func GetThemeFromRequest(c *gin.Context) string {
user, _ := getCurrentUser(c)
if user.ID > 0 {
return user.Theme
}
cookie, err := c.Cookie("theme")
if err == nil {
return cookie
}
return ""
}
// GetThemeFromRequest: Gets the user selected theme from the request
func GetMascotFromRequest(c *gin.Context) string {
user, _ := getCurrentUser(c)
if user.ID > 0 {
return user.Mascot
}
cookie, err := c.Cookie("mascot")
if err == nil {
return cookie
}
return "show"
}
// GetMascotUrlFromRequest: Get the user selected mascot url from the request.
// Returns an empty string if not set.
func GetMascotUrlFromRequest(c *gin.Context) string {
user, _ := getCurrentUser(c)
if user.ID > 0 {
return user.MascotURL
}
cookie, err := c.Cookie("mascot_url")
if err == nil {
return cookie
}
return ""
}
func getCurrentUser(c *gin.Context) (model.User, error) {
if userRetriever == nil {
return model.User{}, errors.New("failed to get current user: no user retriever set")
}
return userRetriever.RetrieveCurrentUser(c)
}