Albirew/nyaa-pantsu
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/templates/template_functions.go

471 lignes
13 KiB
Go
Brut Lien permanent Vue normale Historique

package templates
import (
"html/template"
"path/filepath"
"math"
"math/rand"
"net/url"
"strconv"
"time"
"os"
"fmt"
"strings"
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 13:42:38 +02:00
"github.com/CloudyKit/jet"
2017-05-17 07:58:40 +02:00
"github.com/NyaaPantsu/nyaa/config"
2017-06-29 13:15:23 +02:00
"github.com/NyaaPantsu/nyaa/models"
"github.com/NyaaPantsu/nyaa/models/torrents"
"github.com/NyaaPantsu/nyaa/utils/categories"
"github.com/NyaaPantsu/nyaa/utils/filelist"
"github.com/NyaaPantsu/nyaa/utils/format"
"github.com/NyaaPantsu/nyaa/utils/publicSettings"
"github.com/NyaaPantsu/nyaa/utils/torrentLanguages"
)
// FuncMap : Functions accessible in templates by {{ $.Function }}
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 13:42:38 +02:00
func templateFunctions(vars jet.VarMap) jet.VarMap {
vars.Set("getRawQuery", getRawQuery)
vars.Set("genSearchWithOrdering", genSearchWithOrdering)
vars.Set("genSearchWithCategory", genSearchWithCategory)
vars.Set("genSortArrows", genSortArrows)
vars.Set("genNav", genNav)
vars.Set("Sukebei", config.IsSukebei)
vars.Set("getDefaultLanguage", publicSettings.GetDefaultLanguage)
vars.Set("FlagCode", flagCode)
vars.Set("getAvatar", getAvatar)
vars.Set("torrentFileExists", torrentFileExists)
vars.Set("GetHostname", format.GetHostname)
vars.Set("GetCategories", categories.GetSelect)
vars.Set("GetCategory", getCategory)
vars.Set("CategoryName", categoryName)
Janitor (#1728) * Fix "torrent is being generated" message showing up even when the torrent couldn't be generated * Add janitor user status * Remove usage of deprecated HasAdmin() function * Give Janitors access to mod panel * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Update edit.go * Update profile.go * Rollback bad changes, remove redundant email check and stop using deprecated function * Show every userstatus (member, janitor, banned, mod) in comments * Return empty status if anonymous * Show no userstatus for anonymous profile * Show moderation link to janitors too * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Add Janitor to userstatus select in user edit * "Janitor" translation string * didnt mean to commit this change * rollback wrongfully comitted changes * rollback commit * Update CHANGELOG.md * Fix wrong id for translation * remove deprecated HasAdmin() function again * change name of variable used in comment loop for clarity purposes * visual cue for locked torrents in torrent listing for admins * add visual cues for hidden torrents in admin torrent listing * Dont show delete buttons for janitors * janitor cannot delete torrents * show block/unblock button in torrent list for janitors instead of delete button * fix function that didnt get executed * add ban buttons on userlist & visual cue for banned users * Fix "user successfully deleted" message showing even if user wasnt deleted * Add "ban" button, no "delete" button for jantiors * add "unban" and "ban" translation strings * add "unban" and "ban" translation strings * different <form> for ban button * Update index.jet.html * add userprofile ban route * add toggleBan() function, janitors dont need captcha either * fix panic error when deleting an anonymous comment * add user_banned_by and user_unbanned_by * add user_banned_by and user_unbanned_by * Make ToggleBan() return whether or not the user is now banned * Add handler for /ban route * change log filter * hide locked torrents from regular users * hide locked torrents from regular users * hide locked torrent from api search for regular users * change function to CurrentOrJanitor * change function to currentorjanitor * change function to currentorjanitor * add CurrentOrJanitor function * fix extra ( * fix extra ) and wrong variable name * Fix wrong value for janitor user status * Fix user edit that did not work because of "unique constraint user.emails" error * only immediately visually update user if user has been updated successfully * use FindAllForAdminsOrderBy in order to preload users * create FindAllForAdminsOrderBy that preloads users * Show username instead of ID in Uploader column in admin panel * Fix userprofile buttons overflowing at some specific resolutions * Mods can set users as janitors * Show ban/unban buttons on userprofile for janitors * Identical styling for usermenu links and buttons * dont show ban buttons on other staff * add ban message through get parameter * make toggleBan() trigger user update * Add "user_banned" and "user_unbanned" * add "user_banned" and "user_unbanned" * Visual cue for banned user * banned users can still log in * visual cue for banned user in badgemenu * locked status if banned user on upload * banned users cannot comment * Put "banned" text between () * add GetCategoryName() to template_test * add GetCategoryName() that returns full category name from full category string * Show search content in page title if it exists, or search category if it exists, otherwise shows "Home" * error message when user uploads an torrent & is banned * add torrent_uploaded_locked * add torrent_uploaded_locked * fix delete definitely button that never appeared * Show delete definitely button on admin panel index * admins can undelete a torrent by editing it's status * Trigger ViewHandler() directly instead of redirecting * Render the template directly instead of triggering torrent view handler * bigger usermenu buttons once responsive design kicks in * make btn-* class non-bold * Responsive notification page * visual cue for locked torrents in torrent listing * Update search.go * Update search.go * Update api.go * Update helpers.go * Update template.go * Update torrentParam.go * remove "hidden" class * Update search.go * fix an html error * Add files via upload * Update admin.jet.html * Update index.go * Update index.go * Update router.go * Update torrentParam_test.go * Update torrentParam_test.go * fix extra " * fix bad copypaste * Update CHANGELOG.md * Update guidelines.jet.html * Update CHANGELOG.md * add Guidelines and Moderation Guidelines * fix missing commas * Update torrentlist.jet.html * Update find.go * Update stats.go * Update view.jet.html * Update index.jet.html
2017-11-14 09:39:39 +01:00
vars.Set("GetCategoryName", GetCategoryName)
vars.Set("GetTorrentLanguages", torrentLanguages.GetTorrentLanguages)
vars.Set("GenSearchName", GenSearchName)
vars.Set("LanguageName", languageName)
vars.Set("LanguageNameFromCode", languageNameFromCode)
vars.Set("fileSize", fileSize)
vars.Set("DefaultUserSettings", defaultUserSettings)
vars.Set("makeTreeViewData", makeTreeViewData)
vars.Set("lastID", lastID)
vars.Set("getReportDescription", getReportDescription)
vars.Set("genUploaderLink", genUploaderLink)
vars.Set("genActivityContent", genActivityContent)
vars.Set("contains", contains)
2017-11-01 08:52:44 +01:00
vars.Set("strcmp", strcmp)
vars.Set("strfind", strfind)
2017-11-01 09:05:27 +01:00
vars.Set("rand", rand.Intn)
2017-11-01 09:59:06 +01:00
vars.Set("toString", strconv.Itoa)
vars.Set("getDomainName", getDomainName)
vars.Set("getThemeList", getThemeList)
vars.Set("formatThemeName", formatThemeName)
vars.Set("formatDate", formatDate)
return vars
}
func getRawQuery(currentURL *url.URL) string {
return currentURL.RawQuery
}
func genSearchWithOrdering(currentURL *url.URL, sortBy string, searchRoute string) string {
values := currentURL.Query()
order := false //Default is DESC
sort := "2" //Default is Date (Actually ID, but Date is the same thing)
if _, ok := values["order"]; ok {
order, _ = strconv.ParseBool(values["order"][0])
}
if _, ok := values["sort"]; ok {
sort = values["sort"][0]
}
2017-05-18 01:03:11 +02:00
if sort == sortBy {
order = !order //Flip order by repeat-clicking
} else {
order = false //Default to descending when sorting by something new
}
values.Set("sort", sortBy)
values.Set("order", strconv.FormatBool(order))
2017-05-14 14:30:09 +02:00
u, _ := url.Parse(searchRoute)
u.RawQuery = values.Encode()
return u.String()
}
2017-05-18 01:03:11 +02:00
func genSearchWithCategory(currentURL *url.URL, category string, searchRoute string) string {
values := currentURL.Query()
cat := "_" //Default
if _, ok := values["c"]; ok {
cat = values["c"][0]
}
cat = category
"No comments" message, avatar in comments, classic theme improvements, some other changes, Old Navigation (#1545) * Update view.jet.html * Update en-us.all.json * Update view.jet.html * Update CHANGELOG.md * fix travis * Update classic.css * Update view.jet.html * Update main.css * Update classic.css * Update classic.css * Update classic.css * add link to user page & avatar in comment * stylisation for avatar in main.css * Update classic.css * Fix wrongly placed ::before * Add rule list to terms of service * import rules on register * fix refine-container-2's inputs * Update base.jet.html * Update en-us.all.json * Update CHANGELOG.md * GenNav changes to constantly put HTML for nav arrows regardless of page * css changes for website nav etc etc * add OldNav global variable * Add OldNav to test.go * Update publicSettings.go * change OldNav's value type * Old navigation in settings * add OldNav in user variables * add oldNav input handler in settings.go * Change OldNav's default value into false * Create OldNav.jet.html * Update search.jet.html * remove character that had nothing to do here * fix wrong variable name * fix worng variable name and travis * Update classic.css * Add sort order & type to old nav * add toString() function in test * add toString() function * translation string for oldnav setting * Use translation string in settings.jet.html * fix few html errors * ditto * travis fix test * remove useless charset * remove useless things * add spaces before attributes * attempt at fixing travis 2 * fix wrong variable name * Update classic.css * fix travis plsss
2017-09-11 19:45:39 +02:00
values.Set("c", cat)
u, _ := url.Parse(searchRoute)
u.RawQuery = values.Encode()
return u.String()
}
"No comments" message, avatar in comments, classic theme improvements, some other changes, Old Navigation (#1545) * Update view.jet.html * Update en-us.all.json * Update view.jet.html * Update CHANGELOG.md * fix travis * Update classic.css * Update view.jet.html * Update main.css * Update classic.css * Update classic.css * Update classic.css * add link to user page & avatar in comment * stylisation for avatar in main.css * Update classic.css * Fix wrongly placed ::before * Add rule list to terms of service * import rules on register * fix refine-container-2's inputs * Update base.jet.html * Update en-us.all.json * Update CHANGELOG.md * GenNav changes to constantly put HTML for nav arrows regardless of page * css changes for website nav etc etc * add OldNav global variable * Add OldNav to test.go * Update publicSettings.go * change OldNav's value type * Old navigation in settings * add OldNav in user variables * add oldNav input handler in settings.go * Change OldNav's default value into false * Create OldNav.jet.html * Update search.jet.html * remove character that had nothing to do here * fix wrong variable name * fix worng variable name and travis * Update classic.css * Add sort order & type to old nav * add toString() function in test * add toString() function * translation string for oldnav setting * Use translation string in settings.jet.html * fix few html errors * ditto * travis fix test * remove useless charset * remove useless things * add spaces before attributes * attempt at fixing travis 2 * fix wrong variable name * Update classic.css * fix travis plsss
2017-09-11 19:45:39 +02:00
func genSortArrows(currentURL *url.URL, sortBy string) template.HTML {
values := currentURL.Query()
leftclass := "sortarrowdim"
rightclass := "sortarrowdim"
2017-05-18 01:03:11 +02:00
order := false
sort := "2"
if _, ok := values["order"]; ok {
order, _ = strconv.ParseBool(values["order"][0])
}
if _, ok := values["sort"]; ok {
sort = values["sort"][0]
}
if sort == sortBy {
if order {
rightclass = ""
} else {
leftclass = ""
}
}
arrows := "<span class=\"sortarrowleft " + leftclass + "\">▼</span><span class=\"" + rightclass + "\">▲</span>"
return template.HTML(arrows)
}
func genNav(nav Navigation, currentURL *url.URL, pagesSelectable int) template.HTML {
var ret = ""
if nav.TotalItem > 0 {
maxPages := math.Ceil(float64(nav.TotalItem) / float64(nav.MaxItemPerPage))
href := ""
display := " style=\"display:none;\""
if nav.CurrentPage-1 > 0 {
display = ""
href = " href=\"" + "/" + nav.Route + "/1" + "?" + currentURL.RawQuery + "\""
}
ret = ret + "<a class=\"page-prev\"" + display + href + " aria-label=\"Previous\"><span aria-hidden=\"true\">&laquo;</span></a>"
startValue := 1
if nav.CurrentPage > pagesSelectable/2 {
startValue = (int(math.Min((float64(nav.CurrentPage)+math.Floor(float64(pagesSelectable)/2)), maxPages)) - pagesSelectable + 1)
}
if startValue < 1 {
startValue = 1
}
endValue := (startValue + pagesSelectable - 1)
if endValue > int(maxPages) {
endValue = int(maxPages)
}
for i := startValue; i <= endValue; i++ {
pageNum := strconv.Itoa(i)
url := "/" + nav.Route + "/" + pageNum
ret = ret + "<a aria-label=\"Page " + strconv.Itoa(i) + "\" href=\"" + url + "?" + currentURL.RawQuery + "\">" + "<span"
if i == nav.CurrentPage {
ret = ret + " class=\"active\""
}
ret = ret + ">" + strconv.Itoa(i) + "</span></a>"
}
href = ""
display = " style=\"display:none;\""
if nav.CurrentPage < int(maxPages) {
display = ""
href = " href=\"" + "/" + nav.Route + "/" + strconv.Itoa(int(maxPages)) + "?" + currentURL.RawQuery + "\""
}
ret = ret + "<a class=\"page-next\"" + display + href +" aria-label=\"Next\"><span aria-hidden=\"true\">&raquo;</span></a>"
itemsThisPageStart := nav.MaxItemPerPage*(nav.CurrentPage-1) + 1
itemsThisPageEnd := nav.MaxItemPerPage * nav.CurrentPage
if nav.TotalItem < itemsThisPageEnd {
itemsThisPageEnd = nav.TotalItem
}
ret = ret + "<p>" + strconv.Itoa(itemsThisPageStart) + "-" + strconv.Itoa(itemsThisPageEnd) + "/" + strconv.Itoa(nav.TotalItem) + "</p>"
}
return template.HTML(ret)
}
func flagCode(languageCode string) string {
return publicSettings.Flag(languageCode, true)
}
func getAvatar(hash string, size int) string {
2017-10-31 22:56:10 +01:00
if hash != "" {
return "https://www.gravatar.com/avatar/" + hash + "?s=" + strconv.Itoa(size)
} else {
2017-10-31 23:19:10 +01:00
if config.IsSukebei() {
return "/img/sukebei_avatar_" + strconv.Itoa(size) + ".jpg"
}
2017-10-31 22:56:10 +01:00
return "/img/avatar_" + strconv.Itoa(size) + ".jpg"
}
}
func getCategory(category string, keepParent bool) categories.Categories {
cats := categories.GetSelect(true, true)
found := false
categoryRet := categories.Categories{}
for _, v := range cats {
if v.ID == category+"_" {
found = true
if keepParent {
categoryRet = append(categoryRet, v)
}
} else if len(v.ID) <= 2 && len(categoryRet) > 0 {
break
} else if found {
categoryRet = append(categoryRet, v)
}
}
return categoryRet
}
func categoryName(category string, subCategory string) string {
Janitor (#1728) * Fix "torrent is being generated" message showing up even when the torrent couldn't be generated * Add janitor user status * Remove usage of deprecated HasAdmin() function * Give Janitors access to mod panel * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Update edit.go * Update profile.go * Rollback bad changes, remove redundant email check and stop using deprecated function * Show every userstatus (member, janitor, banned, mod) in comments * Return empty status if anonymous * Show no userstatus for anonymous profile * Show moderation link to janitors too * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Add Janitor to userstatus select in user edit * "Janitor" translation string * didnt mean to commit this change * rollback wrongfully comitted changes * rollback commit * Update CHANGELOG.md * Fix wrong id for translation * remove deprecated HasAdmin() function again * change name of variable used in comment loop for clarity purposes * visual cue for locked torrents in torrent listing for admins * add visual cues for hidden torrents in admin torrent listing * Dont show delete buttons for janitors * janitor cannot delete torrents * show block/unblock button in torrent list for janitors instead of delete button * fix function that didnt get executed * add ban buttons on userlist & visual cue for banned users * Fix "user successfully deleted" message showing even if user wasnt deleted * Add "ban" button, no "delete" button for jantiors * add "unban" and "ban" translation strings * add "unban" and "ban" translation strings * different <form> for ban button * Update index.jet.html * add userprofile ban route * add toggleBan() function, janitors dont need captcha either * fix panic error when deleting an anonymous comment * add user_banned_by and user_unbanned_by * add user_banned_by and user_unbanned_by * Make ToggleBan() return whether or not the user is now banned * Add handler for /ban route * change log filter * hide locked torrents from regular users * hide locked torrents from regular users * hide locked torrent from api search for regular users * change function to CurrentOrJanitor * change function to currentorjanitor * change function to currentorjanitor * add CurrentOrJanitor function * fix extra ( * fix extra ) and wrong variable name * Fix wrong value for janitor user status * Fix user edit that did not work because of "unique constraint user.emails" error * only immediately visually update user if user has been updated successfully * use FindAllForAdminsOrderBy in order to preload users * create FindAllForAdminsOrderBy that preloads users * Show username instead of ID in Uploader column in admin panel * Fix userprofile buttons overflowing at some specific resolutions * Mods can set users as janitors * Show ban/unban buttons on userprofile for janitors * Identical styling for usermenu links and buttons * dont show ban buttons on other staff * add ban message through get parameter * make toggleBan() trigger user update * Add "user_banned" and "user_unbanned" * add "user_banned" and "user_unbanned" * Visual cue for banned user * banned users can still log in * visual cue for banned user in badgemenu * locked status if banned user on upload * banned users cannot comment * Put "banned" text between () * add GetCategoryName() to template_test * add GetCategoryName() that returns full category name from full category string * Show search content in page title if it exists, or search category if it exists, otherwise shows "Home" * error message when user uploads an torrent & is banned * add torrent_uploaded_locked * add torrent_uploaded_locked * fix delete definitely button that never appeared * Show delete definitely button on admin panel index * admins can undelete a torrent by editing it's status * Trigger ViewHandler() directly instead of redirecting * Render the template directly instead of triggering torrent view handler * bigger usermenu buttons once responsive design kicks in * make btn-* class non-bold * Responsive notification page * visual cue for locked torrents in torrent listing * Update search.go * Update search.go * Update api.go * Update helpers.go * Update template.go * Update torrentParam.go * remove "hidden" class * Update search.go * fix an html error * Add files via upload * Update admin.jet.html * Update index.go * Update index.go * Update router.go * Update torrentParam_test.go * Update torrentParam_test.go * fix extra " * fix bad copypaste * Update CHANGELOG.md * Update guidelines.jet.html * Update CHANGELOG.md * add Guidelines and Moderation Guidelines * fix missing commas * Update torrentlist.jet.html * Update find.go * Update stats.go * Update view.jet.html * Update index.jet.html
2017-11-14 09:39:39 +01:00
return GetCategoryName( category + "_" + subCategory)
}
Janitor (#1728) * Fix "torrent is being generated" message showing up even when the torrent couldn't be generated * Add janitor user status * Remove usage of deprecated HasAdmin() function * Give Janitors access to mod panel * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Update edit.go * Update profile.go * Rollback bad changes, remove redundant email check and stop using deprecated function * Show every userstatus (member, janitor, banned, mod) in comments * Return empty status if anonymous * Show no userstatus for anonymous profile * Show moderation link to janitors too * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Add Janitor to userstatus select in user edit * "Janitor" translation string * didnt mean to commit this change * rollback wrongfully comitted changes * rollback commit * Update CHANGELOG.md * Fix wrong id for translation * remove deprecated HasAdmin() function again * change name of variable used in comment loop for clarity purposes * visual cue for locked torrents in torrent listing for admins * add visual cues for hidden torrents in admin torrent listing * Dont show delete buttons for janitors * janitor cannot delete torrents * show block/unblock button in torrent list for janitors instead of delete button * fix function that didnt get executed * add ban buttons on userlist & visual cue for banned users * Fix "user successfully deleted" message showing even if user wasnt deleted * Add "ban" button, no "delete" button for jantiors * add "unban" and "ban" translation strings * add "unban" and "ban" translation strings * different <form> for ban button * Update index.jet.html * add userprofile ban route * add toggleBan() function, janitors dont need captcha either * fix panic error when deleting an anonymous comment * add user_banned_by and user_unbanned_by * add user_banned_by and user_unbanned_by * Make ToggleBan() return whether or not the user is now banned * Add handler for /ban route * change log filter * hide locked torrents from regular users * hide locked torrents from regular users * hide locked torrent from api search for regular users * change function to CurrentOrJanitor * change function to currentorjanitor * change function to currentorjanitor * add CurrentOrJanitor function * fix extra ( * fix extra ) and wrong variable name * Fix wrong value for janitor user status * Fix user edit that did not work because of "unique constraint user.emails" error * only immediately visually update user if user has been updated successfully * use FindAllForAdminsOrderBy in order to preload users * create FindAllForAdminsOrderBy that preloads users * Show username instead of ID in Uploader column in admin panel * Fix userprofile buttons overflowing at some specific resolutions * Mods can set users as janitors * Show ban/unban buttons on userprofile for janitors * Identical styling for usermenu links and buttons * dont show ban buttons on other staff * add ban message through get parameter * make toggleBan() trigger user update * Add "user_banned" and "user_unbanned" * add "user_banned" and "user_unbanned" * Visual cue for banned user * banned users can still log in * visual cue for banned user in badgemenu * locked status if banned user on upload * banned users cannot comment * Put "banned" text between () * add GetCategoryName() to template_test * add GetCategoryName() that returns full category name from full category string * Show search content in page title if it exists, or search category if it exists, otherwise shows "Home" * error message when user uploads an torrent & is banned * add torrent_uploaded_locked * add torrent_uploaded_locked * fix delete definitely button that never appeared * Show delete definitely button on admin panel index * admins can undelete a torrent by editing it's status * Trigger ViewHandler() directly instead of redirecting * Render the template directly instead of triggering torrent view handler * bigger usermenu buttons once responsive design kicks in * make btn-* class non-bold * Responsive notification page * visual cue for locked torrents in torrent listing * Update search.go * Update search.go * Update api.go * Update helpers.go * Update template.go * Update torrentParam.go * remove "hidden" class * Update search.go * fix an html error * Add files via upload * Update admin.jet.html * Update index.go * Update index.go * Update router.go * Update torrentParam_test.go * Update torrentParam_test.go * fix extra " * fix bad copypaste * Update CHANGELOG.md * Update guidelines.jet.html * Update CHANGELOG.md * add Guidelines and Moderation Guidelines * fix missing commas * Update torrentlist.jet.html * Update find.go * Update stats.go * Update view.jet.html * Update index.jet.html
2017-11-14 09:39:39 +01:00
func GetCategoryName(category string) string {
if cat, ok := categories.GetByID(category); ok {
return cat.Name
}
return ""
}
Janitor (#1728) * Fix "torrent is being generated" message showing up even when the torrent couldn't be generated * Add janitor user status * Remove usage of deprecated HasAdmin() function * Give Janitors access to mod panel * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Update edit.go * Update profile.go * Rollback bad changes, remove redundant email check and stop using deprecated function * Show every userstatus (member, janitor, banned, mod) in comments * Return empty status if anonymous * Show no userstatus for anonymous profile * Show moderation link to janitors too * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Stop using deprecated HasAdmin() function * Add Janitor to userstatus select in user edit * "Janitor" translation string * didnt mean to commit this change * rollback wrongfully comitted changes * rollback commit * Update CHANGELOG.md * Fix wrong id for translation * remove deprecated HasAdmin() function again * change name of variable used in comment loop for clarity purposes * visual cue for locked torrents in torrent listing for admins * add visual cues for hidden torrents in admin torrent listing * Dont show delete buttons for janitors * janitor cannot delete torrents * show block/unblock button in torrent list for janitors instead of delete button * fix function that didnt get executed * add ban buttons on userlist & visual cue for banned users * Fix "user successfully deleted" message showing even if user wasnt deleted * Add "ban" button, no "delete" button for jantiors * add "unban" and "ban" translation strings * add "unban" and "ban" translation strings * different <form> for ban button * Update index.jet.html * add userprofile ban route * add toggleBan() function, janitors dont need captcha either * fix panic error when deleting an anonymous comment * add user_banned_by and user_unbanned_by * add user_banned_by and user_unbanned_by * Make ToggleBan() return whether or not the user is now banned * Add handler for /ban route * change log filter * hide locked torrents from regular users * hide locked torrents from regular users * hide locked torrent from api search for regular users * change function to CurrentOrJanitor * change function to currentorjanitor * change function to currentorjanitor * add CurrentOrJanitor function * fix extra ( * fix extra ) and wrong variable name * Fix wrong value for janitor user status * Fix user edit that did not work because of "unique constraint user.emails" error * only immediately visually update user if user has been updated successfully * use FindAllForAdminsOrderBy in order to preload users * create FindAllForAdminsOrderBy that preloads users * Show username instead of ID in Uploader column in admin panel * Fix userprofile buttons overflowing at some specific resolutions * Mods can set users as janitors * Show ban/unban buttons on userprofile for janitors * Identical styling for usermenu links and buttons * dont show ban buttons on other staff * add ban message through get parameter * make toggleBan() trigger user update * Add "user_banned" and "user_unbanned" * add "user_banned" and "user_unbanned" * Visual cue for banned user * banned users can still log in * visual cue for banned user in badgemenu * locked status if banned user on upload * banned users cannot comment * Put "banned" text between () * add GetCategoryName() to template_test * add GetCategoryName() that returns full category name from full category string * Show search content in page title if it exists, or search category if it exists, otherwise shows "Home" * error message when user uploads an torrent & is banned * add torrent_uploaded_locked * add torrent_uploaded_locked * fix delete definitely button that never appeared * Show delete definitely button on admin panel index * admins can undelete a torrent by editing it's status * Trigger ViewHandler() directly instead of redirecting * Render the template directly instead of triggering torrent view handler * bigger usermenu buttons once responsive design kicks in * make btn-* class non-bold * Responsive notification page * visual cue for locked torrents in torrent listing * Update search.go * Update search.go * Update api.go * Update helpers.go * Update template.go * Update torrentParam.go * remove "hidden" class * Update search.go * fix an html error * Add files via upload * Update admin.jet.html * Update index.go * Update index.go * Update router.go * Update torrentParam_test.go * Update torrentParam_test.go * fix extra " * fix bad copypaste * Update CHANGELOG.md * Update guidelines.jet.html * Update CHANGELOG.md * add Guidelines and Moderation Guidelines * fix missing commas * Update torrentlist.jet.html * Update find.go * Update stats.go * Update view.jet.html * Update index.jet.html
2017-11-14 09:39:39 +01:00
func languageName(lang publicSettings.Language, T publicSettings.TemplateTfunc) string {
if strings.Contains(lang.Name, ",") {
langs := strings.Split(lang.Name, ", ")
tags := strings.Split(lang.Tag, ", ")
for k := range langs {
langs[k] = strings.Title(publicSettings.Translate(tags[k], string(T("language_code"))))
}
return strings.Join(langs, ", ")
}
return strings.Title(lang.Translate(T("language_code")))
}
func languageNameFromCode(languageCode string, T publicSettings.TemplateTfunc) string {
if strings.Contains(languageCode, ",") {
tags := strings.Split(languageCode, ", ")
var langs []string
for k := range tags {
langs = append(langs, strings.Title(publicSettings.Translate(tags[k], string(T("language_code")))))
}
return strings.Join(langs, ", ")
}
return strings.Title(publicSettings.Translate(languageCode, string(T("language_code"))))
}
2017-10-31 01:37:24 +01:00
func fileSize(filesize int64, T publicSettings.TemplateTfunc, showUnknown bool) template.HTML {
if showUnknown && filesize == 0 {
return T("unknown")
}
return template.HTML(format.FileSize(filesize))
}
func defaultUserSettings(s string) bool {
return config.Get().Users.DefaultUserSettings[s]
}
func makeTreeViewData(f *filelist.FileListFolder, nestLevel int, identifierChain string) interface{} {
return struct {
Folder *filelist.FileListFolder
NestLevel int
IdentifierChain string
}{f, nestLevel, identifierChain}
}
func lastID(currentURL *url.URL, torrents []models.TorrentJSON) int {
if len(torrents) == 0 {
return 0
}
values := currentURL.Query()
order := false
sort := "2"
if _, ok := values["order"]; ok {
order, _ = strconv.ParseBool(values["order"][0])
}
if _, ok := values["sort"]; ok {
sort = values["sort"][0]
}
lastID := 0
if sort == "2" || sort == "" {
if order {
lastID = int(torrents[len(torrents)-1].ID)
} else if len(torrents) > 0 {
lastID = int(torrents[0].ID)
}
}
return lastID
}
func getReportDescription(d string, T publicSettings.TemplateTfunc) string {
if d == "illegal" {
return "Illegal content"
} else if d == "spam" {
return "Spam / Garbage"
} else if d == "wrongcat" {
return "Wrong category"
} else if d == "dup" {
return "Duplicate / Deprecated"
}
return string(T(d))
}
func genUploaderLink(uploaderID uint, uploaderName template.HTML, torrentHidden bool) template.HTML {
uploaderID, username := torrents.HideUser(uploaderID, string(uploaderName), torrentHidden)
if uploaderID == 0 {
return template.HTML(username)
}
url := "/user/" + strconv.Itoa(int(uploaderID)) + "/" + username
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 13:42:38 +02:00
return template.HTML("<a href=\"" + url + "\">" + username + "</a>")
}
func genActivityContent(a models.Activity, T publicSettings.TemplateTfunc) template.HTML {
return a.ToLocale(T)
}
func contains(arr interface{}, comp string) bool {
switch str := arr.(type) {
case string:
if str == comp {
return true
}
case publicSettings.Language:
if str.Code == comp {
return true
}
default:
return false
}
return false
}
func torrentFileExists(hash string, TorrentLink string) bool {
Torrent Generation on not found error (#1600) * [WIP] Torrent Generation on not found error As asked in #1517, it allows on-the-fly torrent generation. Since it uses magnet links, it needs some time to connect to peers. So it can't be instant generation, we need the user to wait and try after a minute at least. * Replace Fatal by simple error * attempt at fixing travis * del * Add Anacrolyx dependency * Add back difflib * Remove .torrent suffix in the url example * Add some explanations when file missing page shown * Ignore downloads directory * Either use cache (third-party site) or own download directory * Wrong import * If there is an error then it means we aren't generating a torrent file May it be "torrent not found" or "We do not store torrent files" which are the two only existing errors for this page * hash is never empty * TorrentLink may be empty at times So we add a /download/:hash link if it is * Update README.md * Made a mistake here, need to check if false * Update en-us.all.json * Update CHANGELOG.md * Torrent file generation can be triggered by click on button if JS enabled * Update download.go * Update download.go * Use c.JSON instead of text/template * Return to default behavior if we don't generate the file * Don't do the query if returned to default behavior * Add "Could not generate torrent file" error * Fix JS condition & lower delay until button updates * Start download automatically once torrent file is generated * Fix torrentFileExists() constantly returning false if external torrent download URL * torrent-view-data is two tables instead of one This allows the removal of useless things without any problem (e.g Website link), but also a better responsibe design since the previous one separated stats after a certain res looking very wonky * CSS changes to go along * Remove useless <b></b> * Update main.css * In torrentFileExists, check if filestorage path exists instead of looking at the domain in torrent link When checking if the file is stored on another server i used to simply check if the domain name was inside the torrent link, but we can straight up check for filestorage length * Fix JS of on-demand stat fetching * ScrapeAge variable accessible through view.jet.html Contains last scraped time in hours, is at -1 is torrent has never been scraped Stats will get updated if it's either at -1 or above 1460 (2 months old) * Refresh stats if older than two months OR unknown and older than 24h Show last scraped date even if stats are unknown * Add StatsObsolete variable to torrent Indicating if: - They can be shown - They need to be updated * Update scraped data even if Unknown, prevent users from trying to fetch stats every seconds * Torrent file stored locally by default * no need to do all of that if no filestorage * fix filestorage path * Fix torrent download button stuck on "Generating torrent file" at rare times * fix some css rules that didn't work on IE * Fix panic error Seems like this error is a known bug from anacrolyx torrent https://github.com/anacrolix/torrent/issues/83 To prevent it, I'm creating a single client and modifying the socket.go to make it not raise a panic but a simple error log.
2017-10-21 09:40:43 +02:00
if(len(config.Get().Torrents.FileStorage) == 0) {
//File isn't stored on our servers
return true
}
Openfile, err := os.Open(fmt.Sprintf("%s%c%s.torrent", config.Get().Torrents.FileStorage, os.PathSeparator, hash))
Things (#1740) * Add new followers directly to user.Followers * Update user.go * Remove useless condition * Query an update of user followers if at 0 when looking at his profile * Fix comment not appearing until you refreshed the torrent page * call ViewHandler so that comments visually update properly * Remove now useless imports * Add "uploader" userstatus in comment * GetLikings() & GetFollowers() now return count too * Don't update follower count here * Update follower count directly here * show liking count * Update user.go * Update profile.jet.html * Update torrentParam.go * Fix locked torrents that were shown even when they should not * Update torrentParam_test.go * remove inline styling * Update main.css * Update upload.jet.html * Update main.css * Update tomorrow.css * Update classic.css * Update classic_colors.css * Update index_site.jet.html * Make announcements support markdown * Add markdown form to announcement creation * fix "report" text position * Add exclude search option to exclude words * Make sure the "NameLike" value is the search query because we edit it during a search * Show search content in page title for /feed too * rollback * Add "Search" variable that shows exactly what is being searched * Use "Search.Search" variable here instead of NameLike because NameLike is edited * Update torrentParam_test.go * Update torrentParam.go * remove redundant spaces from NameLike * Update torrentParam.go * Update torrentParam.go * Update torrentParam.go * Update torrentParam.go * turn date input into type date * bigger date inputs * add support for YYYY-MM-DD dates * rollback this change * rollback * Update search.jet.html * Update helpers.go * Update template_functions.go * Update torrentParam.go * only uploader & staff can comment on locked torrents * Add "Upload to Nyaa/Sukebei" button for mods * Update torrentlist.jet.html * Update view.jet.html * Update view.jet.html * fix wrong page title for notifications page
2017-11-20 02:13:00 +01:00
if err != nil || len(TorrentLink) == 0 {
Torrent Generation on not found error (#1600) * [WIP] Torrent Generation on not found error As asked in #1517, it allows on-the-fly torrent generation. Since it uses magnet links, it needs some time to connect to peers. So it can't be instant generation, we need the user to wait and try after a minute at least. * Replace Fatal by simple error * attempt at fixing travis * del * Add Anacrolyx dependency * Add back difflib * Remove .torrent suffix in the url example * Add some explanations when file missing page shown * Ignore downloads directory * Either use cache (third-party site) or own download directory * Wrong import * If there is an error then it means we aren't generating a torrent file May it be "torrent not found" or "We do not store torrent files" which are the two only existing errors for this page * hash is never empty * TorrentLink may be empty at times So we add a /download/:hash link if it is * Update README.md * Made a mistake here, need to check if false * Update en-us.all.json * Update CHANGELOG.md * Torrent file generation can be triggered by click on button if JS enabled * Update download.go * Update download.go * Use c.JSON instead of text/template * Return to default behavior if we don't generate the file * Don't do the query if returned to default behavior * Add "Could not generate torrent file" error * Fix JS condition & lower delay until button updates * Start download automatically once torrent file is generated * Fix torrentFileExists() constantly returning false if external torrent download URL * torrent-view-data is two tables instead of one This allows the removal of useless things without any problem (e.g Website link), but also a better responsibe design since the previous one separated stats after a certain res looking very wonky * CSS changes to go along * Remove useless <b></b> * Update main.css * In torrentFileExists, check if filestorage path exists instead of looking at the domain in torrent link When checking if the file is stored on another server i used to simply check if the domain name was inside the torrent link, but we can straight up check for filestorage length * Fix JS of on-demand stat fetching * ScrapeAge variable accessible through view.jet.html Contains last scraped time in hours, is at -1 is torrent has never been scraped Stats will get updated if it's either at -1 or above 1460 (2 months old) * Refresh stats if older than two months OR unknown and older than 24h Show last scraped date even if stats are unknown * Add StatsObsolete variable to torrent Indicating if: - They can be shown - They need to be updated * Update scraped data even if Unknown, prevent users from trying to fetch stats every seconds * Torrent file stored locally by default * no need to do all of that if no filestorage * fix filestorage path * Fix torrent download button stuck on "Generating torrent file" at rare times * fix some css rules that didn't work on IE * Fix panic error Seems like this error is a known bug from anacrolyx torrent https://github.com/anacrolix/torrent/issues/83 To prevent it, I'm creating a single client and modifying the socket.go to make it not raise a panic but a simple error log.
2017-10-21 09:40:43 +02:00
//File doesn't exist
return false
}
defer Openfile.Close()
return true
}
2017-11-01 08:52:44 +01:00
func strcmp(str1 string, str2 string, end int, start int) bool {
//Compare two strings but has length arguments
len1 := len(str1)
len2 := len(str2)
if end == -1 && len1 != len2 {
return false
}
if end == -1 || end > len1 {
end = len1
}
if end > len2 {
end = len2
}
if start >= end {
return false
}
return strings.Compare(str1[start:end], str2[start:end]) == 0
}
2017-11-01 08:52:44 +01:00
func strfind(str1 string, searchfor string, start int) bool {
//Search a string inside another with start parameter
//start parameter indicates where we start searching
len1 := len(str1)
Torrent Generation on not found error (#1600) * [WIP] Torrent Generation on not found error As asked in #1517, it allows on-the-fly torrent generation. Since it uses magnet links, it needs some time to connect to peers. So it can't be instant generation, we need the user to wait and try after a minute at least. * Replace Fatal by simple error * attempt at fixing travis * del * Add Anacrolyx dependency * Add back difflib * Remove .torrent suffix in the url example * Add some explanations when file missing page shown * Ignore downloads directory * Either use cache (third-party site) or own download directory * Wrong import * If there is an error then it means we aren't generating a torrent file May it be "torrent not found" or "We do not store torrent files" which are the two only existing errors for this page * hash is never empty * TorrentLink may be empty at times So we add a /download/:hash link if it is * Update README.md * Made a mistake here, need to check if false * Update en-us.all.json * Update CHANGELOG.md * Torrent file generation can be triggered by click on button if JS enabled * Update download.go * Update download.go * Use c.JSON instead of text/template * Return to default behavior if we don't generate the file * Don't do the query if returned to default behavior * Add "Could not generate torrent file" error * Fix JS condition & lower delay until button updates * Start download automatically once torrent file is generated * Fix torrentFileExists() constantly returning false if external torrent download URL * torrent-view-data is two tables instead of one This allows the removal of useless things without any problem (e.g Website link), but also a better responsibe design since the previous one separated stats after a certain res looking very wonky * CSS changes to go along * Remove useless <b></b> * Update main.css * In torrentFileExists, check if filestorage path exists instead of looking at the domain in torrent link When checking if the file is stored on another server i used to simply check if the domain name was inside the torrent link, but we can straight up check for filestorage length * Fix JS of on-demand stat fetching * ScrapeAge variable accessible through view.jet.html Contains last scraped time in hours, is at -1 is torrent has never been scraped Stats will get updated if it's either at -1 or above 1460 (2 months old) * Refresh stats if older than two months OR unknown and older than 24h Show last scraped date even if stats are unknown * Add StatsObsolete variable to torrent Indicating if: - They can be shown - They need to be updated * Update scraped data even if Unknown, prevent users from trying to fetch stats every seconds * Torrent file stored locally by default * no need to do all of that if no filestorage * fix filestorage path * Fix torrent download button stuck on "Generating torrent file" at rare times * fix some css rules that didn't work on IE * Fix panic error Seems like this error is a known bug from anacrolyx torrent https://github.com/anacrolix/torrent/issues/83 To prevent it, I'm creating a single client and modifying the socket.go to make it not raise a panic but a simple error log.
2017-10-21 09:40:43 +02:00
if start >= len1 || searchfor == "" {
return false
}
return strings.Contains(str1[start:len1], searchfor)
}
func getDomainName() string {
domain := config.Get().Cookies.DomainName
if config.Get().Environment == "DEVELOPMENT" {
domain = ""
}
return domain
}
func getThemeList() ([]string) {
searchDir := "public/css/themes/"
themeList := []string{}
filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error {
2017-11-01 08:52:44 +01:00
if strfind(path, ".css", len(searchDir)) {
//we only want .css file
fileName := path[len(searchDir):strings.Index(path, ".css")]
//Remove file extension and path, keep only file name
themeList = append(themeList, fileName)
}
return nil
})
return themeList
}
func formatThemeName(name string, T publicSettings.TemplateTfunc) string {
translationString := fmt.Sprintf("themes_%s", name)
translatedName := string(T(translationString))
if translatedName != translationString {
//Translation string exists
return translatedName
}
if len(name) == 1 {
name = fmt.Sprintf("/%c/", name[0])
} else {
name = strings.Replace(name, "_", " ", -1)
name = strings.Title(name)
//Upper case at each start of word
}
return name
}
func formatDate(Date time.Time, short bool) string {
Date = Date.UTC()
if short {
return fmt.Sprintf("%.3s %d, %d", Date.Month(), Date.Day(), Date.Year())
}
if Date.Hour() >= 12 {
return fmt.Sprintf("%d/%d/%d, %d:%.2d:%.2d PM UTC+0", Date.Month(), Date.Day(), Date.Year(), Date.Hour() - 12, Date.Minute(), Date.Second())
} else {
return fmt.Sprintf("%d/%d/%d, %d:%.2d:%.2d AM UTC+0", Date.Month(), Date.Day(), Date.Year(), Date.Hour(), Date.Minute(), Date.Second())
}
}
func GenSearchName(Search SearchForm, currentURL string, T publicSettings.TemplateTfunc) string {
if currentURL == "/" {
return string(T("home"))
}
if Search.UserName != "" {
return Search.UserName
}
if Search.NameSearch != "" {
return Search.NameSearch
}
if Search.Category != "" {
return string(T(GetCategoryName(Search.Category)))
}
return string(T("search"))
}