Albirew/nyaa-pantsu
Archivé
1
0
Bifurcation 0

go fmt all the code

Cette révision appartient à :
Eliot Whalan 2017-05-24 17:11:13 +10:00
Parent 58631c6bd4
révision b4b1b1c26a
Aucune clé n'a été trouvée pour cette signature dans la base de données
ID de la clé GPG: C0A42175139840D6
36 fichiers modifiés avec 283 ajouts et 298 suppressions

Voir le fichier

@ -5,7 +5,6 @@ import (
"strings"
)
type Status uint8
const (
@ -109,16 +108,15 @@ func (c *Category) Parse(s string) (ok bool) {
return
}
// deprecated for TorrentParam
type SearchParam struct {
Order bool // True means acsending
Status Status
Sort SortMode
Category Category
Page int
UserID uint
Max uint
NotNull string
Query string
Order bool // True means acsending
Status Status
Sort SortMode
Category Category
Page int
UserID uint
Max uint
NotNull string
Query string
}

Voir le fichier

@ -32,4 +32,3 @@ func (p *TorrentParam) Clone() TorrentParam {
NameLike: p.NameLike,
}
}

Voir le fichier

@ -12,12 +12,12 @@ import (
const (
// LastOldTorrentID is the highest torrent ID
// that was copied from the original Nyaa
LastOldTorrentID = 923000
TorrentsTableName = "torrents"
ReportsTableName = "torrent_reports"
CommentsTableName = "comments"
UploadsOldTableName = "user_uploads_old"
FilesTableName = "files"
LastOldTorrentID = 923000
TorrentsTableName = "torrents"
ReportsTableName = "torrent_reports"
CommentsTableName = "comments"
UploadsOldTableName = "user_uploads_old"
FilesTableName = "files"
NotificationTableName = "notifications"
// for sukebei:
@ -33,7 +33,6 @@ func IsSukebei() bool {
return TorrentsTableName == "sukebei_torrents"
}
type Config struct {
Host string `json:"host"`
Port int `json:"port"`

Voir le fichier

@ -22,8 +22,7 @@ var DefaultMetainfoFetcherConfig = MetainfoFetcherConfig{
MaxFailCooldown: 48 * 60 * 60,
WakeUpInterval: 300, // 5 min
UploadRateLimiter: 1024, // kbps
DownloadRateLimiter: 1024,
UploadRateLimiter: 1024, // kbps
DownloadRateLimiter: 1024,
FetchNewTorrentsOnly: true, // Only fetch torrents newer than config.LastOldTorrentID
}

Voir le fichier

@ -1,9 +1,9 @@
package config
var TorrentStatus = map[int]bool{
0:true,
1:true,
2:true,
3:true,
4:true,
}
0: true,
1: true,
2: true,
3: true,
4: true,
}

Voir le fichier

@ -7,8 +7,8 @@ const (
TorrentStorageLink = ""
// TODO: deprecate this and move all files to the same server
TorrentCacheLink = "http://anicache.com/torrent/%s.torrent"
UploadsDisabled = false
AdminsAreStillAllowedTo = true
TorrentCacheLink = "http://anicache.com/torrent/%s.torrent"
UploadsDisabled = false
AdminsAreStillAllowedTo = true
TrustedUsersAreStillAllowedTo = true
)

Voir le fichier

@ -1,6 +1,5 @@
package config
/*
* Here we config the notifications options
* Uses in user model for default setting
@ -8,15 +7,15 @@ package config
* in service/user/form/form_validator.go
*/
var DefaultUserSettings = map[string]bool {
"new_torrent": true,
"new_torrent_email": false,
"new_comment": true,
"new_comment_email": false,
"new_responses": false,
var DefaultUserSettings = map[string]bool{
"new_torrent": true,
"new_torrent_email": false,
"new_comment": true,
"new_comment_email": false,
"new_responses": false,
"new_responses_email": false,
"new_follower": false,
"new_follower_email": false,
"followed": false,
"followed_email": false,
}
"new_follower": false,
"new_follower_email": false,
"followed": false,
"followed_email": false,
}

Voir le fichier

@ -2,7 +2,7 @@ package model
import (
"time"
"github.com/NyaaPantsu/nyaa/config"
)

Voir le fichier

@ -1,8 +1,8 @@
package model
import (
"time"
"html/template"
"time"
"github.com/NyaaPantsu/nyaa/util"
)
@ -15,16 +15,16 @@ type DatabaseDump struct {
}
type DatabaseDumpJSON struct {
Date string `json:"date"`
Filesize string `json:"filesize"`
Name string `json:"name"`
Date string `json:"date"`
Filesize string `json:"filesize"`
Name string `json:"name"`
//Magnet template.URL `json:"magnet"`
TorrentLink template.URL `json:"torrent"`
TorrentLink template.URL `json:"torrent"`
}
func (dump *DatabaseDump) ToJSON() DatabaseDumpJSON {
json := DatabaseDumpJSON{
Date: dump.Date.Format(time.RFC3339),
Date: dump.Date.Format(time.RFC3339),
Filesize: util.FormatFilesize(dump.Filesize),
Name: dump.Name,
TorrentLink: template.URL(dump.TorrentLink),

Voir le fichier

@ -6,8 +6,8 @@ import (
)
type File struct {
ID uint `gorm:"column:file_id;primary_key"`
TorrentID uint `gorm:"column:torrent_id;unique_index:idx_tid_path"`
ID uint `gorm:"column:file_id;primary_key"`
TorrentID uint `gorm:"column:torrent_id;unique_index:idx_tid_path"`
// this path is bencode'd, call Path() to obtain
BencodedPath string `gorm:"column:path;unique_index:idx_tid_path"`
Filesize int64 `gorm:"column:filesize"`
@ -19,7 +19,7 @@ func (f File) TableName() string {
// Returns the total size of memory allocated for this struct
func (f File) Size() int {
return (2 + len(f.BencodedPath) + 1) * 8;
return (2 + len(f.BencodedPath) + 1) * 8
}
func (f *File) Path() (out []string) {
@ -36,4 +36,3 @@ func (f *File) SetPath(path []string) error {
f.BencodedPath = encoded
return nil
}

Voir le fichier

@ -5,13 +5,13 @@ import (
)
type Notification struct {
ID uint
Content string
Read bool
ID uint
Content string
Read bool
Identifier string
Url string
UserID uint
// User *User `gorm:"AssociationForeignKey:UserID;ForeignKey:user_id"` // Don't think that we need it here
Url string
UserID uint
// User *User `gorm:"AssociationForeignKey:UserID;ForeignKey:user_id"` // Don't think that we need it here
}
func NewNotification(identifier string, c string, url string) Notification {
@ -21,4 +21,3 @@ func NewNotification(identifier string, c string, url string) Notification {
func (n *Notification) TableName() string {
return config.NotificationTableName
}

Voir le fichier

@ -87,7 +87,7 @@ func (t Torrent) TableName() string {
}
func (t *Torrent) Identifier() string {
return "torrent_"+strconv.Itoa(int(t.ID))
return "torrent_" + strconv.Itoa(int(t.ID))
}
func (t Torrent) IsNormal() bool {
@ -116,11 +116,11 @@ type ApiResultJSON struct {
}
type CommentJSON struct {
Username string `json:"username"`
UserID int `json:"user_id"`
UserAvatar string `json:"user_avatar"`
Content template.HTML `json:"content"`
Date time.Time `json:"date"`
Username string `json:"username"`
UserID int `json:"user_id"`
UserAvatar string `json:"user_avatar"`
Content template.HTML `json:"content"`
Date time.Time `json:"date"`
}
type FileJSON struct {

Voir le fichier

@ -2,8 +2,8 @@ package model
import (
"encoding/json"
"time"
"fmt"
"time"
"github.com/NyaaPantsu/nyaa/config"
)
@ -29,15 +29,15 @@ type User struct {
UserSettings string `gorm:"column:settings"`
// TODO: move this to PublicUser
Likings []User // Don't work `gorm:"foreignkey:user_id;associationforeignkey:follower_id;many2many:user_follows"`
Liked []User // Don't work `gorm:"foreignkey:follower_id;associationforeignkey:user_id;many2many:user_follows"`
Likings []User // Don't work `gorm:"foreignkey:user_id;associationforeignkey:follower_id;many2many:user_follows"`
Liked []User // Don't work `gorm:"foreignkey:follower_id;associationforeignkey:user_id;many2many:user_follows"`
MD5 string `json:"md5" gorm:"column:md5"` // Hash of email address, used for Gravatar
Torrents []Torrent `gorm:"ForeignKey:UploaderID"`
MD5 string `json:"md5" gorm:"column:md5"` // Hash of email address, used for Gravatar
Torrents []Torrent `gorm:"ForeignKey:UploaderID"`
Notifications []Notification `gorm:"ForeignKey:UserID"`
UnreadNotifications int `gorm:"-"` // We don't want to loop every notifications when accessing user unread notif
Settings UserSettings `gorm:"-"` // We don't want to load settings everytime, stock it as a string, parse it when needed
UnreadNotifications int `gorm:"-"` // We don't want to loop every notifications when accessing user unread notif
Settings UserSettings `gorm:"-"` // We don't want to load settings everytime, stock it as a string, parse it when needed
}
type UserJSON struct {
@ -78,7 +78,7 @@ func (u User) IsModerator() bool {
}
func (u User) GetUnreadNotifications() int {
if u.UnreadNotifications == 0 {
if u.UnreadNotifications == 0 {
for _, notif := range u.Notifications {
if !notif.Read {
u.UnreadNotifications++
@ -104,7 +104,7 @@ type UserUploadsOld struct {
}
type UserSettings struct {
Settings map[string]bool`json:"settings"`
Settings map[string]bool `json:"settings"`
}
func (c UserUploadsOld) TableName() string {
@ -126,9 +126,9 @@ func (u *User) ToJSON() UserJSON {
/* User Settings */
func(s *UserSettings) Get(key string) bool {
if val, ok:= s.Settings[key]; ok {
return val
func (s *UserSettings) Get(key string) bool {
if val, ok := s.Settings[key]; ok {
return val
} else {
return config.DefaultUserSettings[key]
}
@ -156,7 +156,7 @@ func (s *UserSettings) Initialize() {
func (u *User) SaveSettings() {
byteArray, err := json.Marshal(u.Settings)
if (err != nil) {
if err != nil {
fmt.Print(err)
}
u.UserSettings = string(byteArray)
@ -170,4 +170,4 @@ func (u *User) ParseSettings() {
u.Settings.Initialize()
u.Settings.ToDefault()
}
}
}

Voir le fichier

@ -1,10 +1,10 @@
package router
import (
"fmt"
"net/http"
"os"
"path/filepath"
"net/http"
"fmt"
"time"
"github.com/NyaaPantsu/nyaa/model"
@ -24,7 +24,7 @@ func DatabaseDumpHandler(w http.ResponseWriter, r *http.Request) {
files, err := filepath.Glob(filepath.Join(DatabaseDumpPath, "*.torrent"))
var dumpsJson []model.DatabaseDumpJSON
// TODO Filter *.torrent files
for _, f := range files {
for _, f := range files {
// TODO Use config from cli
file, err := os.Open(f)
if err != nil {
@ -43,7 +43,7 @@ func DatabaseDumpHandler(w http.ResponseWriter, r *http.Request) {
Name: tf.TorrentName(),
TorrentLink: "/dbdumps/" + file.Name()}
dumpsJson = append(dumpsJson, dump.ToJSON())
}
}
// TODO Remove ?
navigationTorrents := Navigation{0, 0, 0, "search_page"}
@ -55,4 +55,3 @@ func DatabaseDumpHandler(w http.ResponseWriter, r *http.Request) {
log.Errorf("DatabaseDump(): %s", err)
}
}

Voir le fichier

@ -31,7 +31,7 @@ func HomeHandler(w http.ResponseWriter, r *http.Request) {
maxPerPage = 50 // default Value maxPerPage
}
}
if (deleteVar != nil) {
if deleteVar != nil {
messages.AddInfoTf("infos", "torrent_deleted", "")
}
pagenum := 1
@ -72,8 +72,8 @@ func HomeHandler(w http.ResponseWriter, r *http.Request) {
common.Navigation = navigationTorrents
htv := HomeTemplateVariables{
CommonTemplateVariables: common,
ListTorrents: torrentsJson,
Infos: messages.GetAllInfos(),
ListTorrents: torrentsJson,
Infos: messages.GetAllInfos(),
}
err = homeTemplate.ExecuteTemplate(w, "index.html", htv)

Voir le fichier

@ -29,8 +29,8 @@ func SeeLanguagesHandler(w http.ResponseWriter, r *http.Request) {
} else {
clv := ChangeLanguageVariables{
CommonTemplateVariables: NewCommonVariables(r),
Language: Tlang.Tag,
Languages: availableLanguages,
Language: Tlang.Tag,
Languages: availableLanguages,
}
err := changeLanguageTemplate.ExecuteTemplate(w, "index.html", clv)
if err != nil {
@ -51,7 +51,7 @@ func ChangeLanguageHandler(w http.ResponseWriter, r *http.Request) {
// If logged in, update user language; if not, set cookie.
user, _ := userService.CurrentUser(r)
if user.ID > 0 {
if user.ID > 0 {
user.Language = lang
// I don't know if I should use this...
userService.UpdateUserCore(&user)

Voir le fichier

@ -134,19 +134,19 @@ func TorrentsListPanel(w http.ResponseWriter, r *http.Request) {
if !log.CheckError(err) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
searchParam, torrents, count, err := search.SearchByQueryWithUser(r, pagenum)
searchForm := SearchForm{
SearchParam: searchParam,
Category: searchParam.Category.String(),
ShowItemsPerPage: true,
}
searchParam, torrents, count, err := search.SearchByQueryWithUser(r, pagenum)
searchForm := SearchForm{
SearchParam: searchParam,
Category: searchParam.Category.String(),
ShowItemsPerPage: true,
}
messages := msg.GetMessages(r)
common := NewCommonVariables(r)
common.Navigation = Navigation{ count, int(searchParam.Max), pagenum, "mod_tlist_page"}
common.Navigation = Navigation{count, int(searchParam.Max), pagenum, "mod_tlist_page"}
common.Search = searchForm
ptlv := PanelTorrentListVbs{common, torrents, messages.GetAllErrors(), messages.GetAllInfos()}
err = panelTorrentList.ExecuteTemplate(w, "admin_index.html", ptlv)
@ -234,7 +234,7 @@ func CommentsListPanel(w http.ResponseWriter, r *http.Request) {
func TorrentEditModPanel(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
torrent, _ := torrentService.GetTorrentById(id)
messages:= msg.GetMessages(r)
messages := msg.GetMessages(r)
torrentJson := torrent.ToJSON()
uploadForm := NewUploadForm()
@ -341,8 +341,6 @@ func TorrentsPostListPanel(w http.ResponseWriter, r *http.Request) {
TorrentsListPanel(w, r)
}
/*
* Controller to modify multiple torrents and can be used by the owner of the torrent or admin
*/
@ -374,7 +372,7 @@ func torrentManyAction(r *http.Request) {
torrent.Status = moveTo
db.ORM.Save(&torrent)
messages.AddInfoTf("infos", "torrent_moved", torrent.Name)
} else {
} else {
messages.AddErrorTf("errors", "no_status_exist", moveTo)
}
case "delete":
@ -389,7 +387,7 @@ func torrentManyAction(r *http.Request) {
}
} else {
messages.AddErrorTf("errors", "torrent_not_exist", torrent_id)
}
}
}
}
}

Voir le fichier

@ -17,7 +17,7 @@ func init() {
imgHandler := http.FileServer(http.Dir("./public/img/"))
// TODO Use config from cli
// TODO Make sure the directory exists
dumpsHandler := http.FileServer(http.Dir(DatabaseDumpPath))
dumpsHandler := http.FileServer(http.Dir(DatabaseDumpPath))
// TODO Use config from cli
// TODO Make sure the directory exists
gpgKeyHandler := http.FileServer(http.Dir(GPGPublicKeyPath))
@ -76,25 +76,25 @@ func init() {
// INFO Everything under /mod should be wrapped by WrapModHandler. This make
// sure the page is only accessible by moderators
// TODO Find a native mux way to add a 'prehook' for route /mod
Router.HandleFunc("/mod", WrapModHandler(IndexModPanel)).Name("mod_index")
Router.HandleFunc("/mod/torrents", WrapModHandler(TorrentsListPanel)).Name("mod_tlist").Methods("GET")
Router.HandleFunc("/mod", WrapModHandler(IndexModPanel)).Name("mod_index")
Router.HandleFunc("/mod/torrents", WrapModHandler(TorrentsListPanel)).Name("mod_tlist").Methods("GET")
Router.HandleFunc("/mod/torrents/{page}", WrapModHandler(TorrentsListPanel)).Name("mod_tlist_page").Methods("GET")
Router.HandleFunc("/mod/torrents", WrapModHandler(TorrentsPostListPanel)).Methods("POST")
Router.HandleFunc("/mod/torrents/{page}", WrapModHandler(TorrentsPostListPanel)).Methods("POST")
Router.HandleFunc("/mod/reports", WrapModHandler(TorrentReportListPanel)).Name("mod_trlist")
Router.HandleFunc("/mod/reports/{page}", WrapModHandler(TorrentReportListPanel)).Name("mod_trlist_page")
Router.HandleFunc("/mod/users", WrapModHandler(UsersListPanel)).Name("mod_ulist")
Router.HandleFunc("/mod/users/{page}", WrapModHandler(UsersListPanel)).Name("mod_ulist_page")
Router.HandleFunc("/mod/comments", WrapModHandler(CommentsListPanel)).Name("mod_clist")
Router.HandleFunc("/mod/reports", WrapModHandler(TorrentReportListPanel)).Name("mod_trlist")
Router.HandleFunc("/mod/reports/{page}", WrapModHandler(TorrentReportListPanel)).Name("mod_trlist_page")
Router.HandleFunc("/mod/users", WrapModHandler(UsersListPanel)).Name("mod_ulist")
Router.HandleFunc("/mod/users/{page}", WrapModHandler(UsersListPanel)).Name("mod_ulist_page")
Router.HandleFunc("/mod/comments", WrapModHandler(CommentsListPanel)).Name("mod_clist")
Router.HandleFunc("/mod/comments/{page}", WrapModHandler(CommentsListPanel)).Name("mod_clist_page")
Router.HandleFunc("/mod/comment", WrapModHandler(CommentsListPanel)).Name("mod_cedit") // TODO
Router.HandleFunc("/mod/torrent/", WrapModHandler(TorrentEditModPanel)).Name("mod_tedit").Methods("GET")
Router.HandleFunc("/mod/torrent/", WrapModHandler(TorrentPostEditModPanel)).Name("mod_ptedit").Methods("POST")
Router.HandleFunc("/mod/torrent/delete", WrapModHandler(TorrentDeleteModPanel)).Name("mod_tdelete")
Router.HandleFunc("/mod/report/delete", WrapModHandler(TorrentReportDeleteModPanel)).Name("mod_trdelete")
Router.HandleFunc("/mod/comment/delete", WrapModHandler(CommentDeleteModPanel)).Name("mod_cdelete")
Router.HandleFunc("/mod/reassign", WrapModHandler(TorrentReassignModPanel)).Name("mod_treassign").Methods("GET")
Router.HandleFunc("/mod/reassign", WrapModHandler(TorrentPostReassignModPanel)).Name("mod_treassign").Methods("POST")
Router.HandleFunc("/mod/comment", WrapModHandler(CommentsListPanel)).Name("mod_cedit") // TODO
Router.HandleFunc("/mod/torrent/", WrapModHandler(TorrentEditModPanel)).Name("mod_tedit").Methods("GET")
Router.HandleFunc("/mod/torrent/", WrapModHandler(TorrentPostEditModPanel)).Name("mod_ptedit").Methods("POST")
Router.HandleFunc("/mod/torrent/delete", WrapModHandler(TorrentDeleteModPanel)).Name("mod_tdelete")
Router.HandleFunc("/mod/report/delete", WrapModHandler(TorrentReportDeleteModPanel)).Name("mod_trdelete")
Router.HandleFunc("/mod/comment/delete", WrapModHandler(CommentDeleteModPanel)).Name("mod_cdelete")
Router.HandleFunc("/mod/reassign", WrapModHandler(TorrentReassignModPanel)).Name("mod_treassign").Methods("GET")
Router.HandleFunc("/mod/reassign", WrapModHandler(TorrentPostReassignModPanel)).Name("mod_treassign").Methods("POST")
//reporting a torrent
Router.HandleFunc("/report/{id}", ReportTorrentHandler).Methods("POST").Name("torrent_report")

Voir le fichier

@ -32,7 +32,6 @@ func SearchHandler(w http.ResponseWriter, r *http.Request) {
}
}
searchParam, torrents, nbTorrents, err := search.SearchByQuery(r, pagenum)
if err != nil {
util.SendError(w, err, 400)

Voir le fichier

@ -162,10 +162,10 @@ var FuncMap = template.FuncMap{
// because time.* isn't available in templates...
return t.Format(time.RFC3339)
},
"GetCategories": func(keepParent bool) map[string]string {
"GetCategories": func(keepParent bool) map[string]string {
return categories.GetCategoriesSelect(keepParent)
},
"CategoryName": func(category string, sub_category string) string {
},
"CategoryName": func(category string, sub_category string) string {
s := category + "_" + sub_category
if category, ok := categories.GetCategories()[s]; ok {
@ -173,17 +173,17 @@ var FuncMap = template.FuncMap{
} else {
return ""
}
},
"fileSize": func(filesize int64, T languages.TemplateTfunc) template.HTML {
if (filesize == 0) {
return T("unknown")
}
return template.HTML(util.FormatFilesize(filesize))
},
},
"fileSize": func(filesize int64, T languages.TemplateTfunc) template.HTML {
if filesize == 0 {
return T("unknown")
}
return template.HTML(util.FormatFilesize(filesize))
},
"makeCaptchaData": func(captchaID string, T languages.TemplateTfunc) captchaData {
return captchaData{captchaID, T}
},
"DefaultUserSettings": func(s string) bool{
"DefaultUserSettings": func(s string) bool {
return config.DefaultUserSettings[s]
},
}

Voir le fichier

@ -30,8 +30,8 @@ type ViewTemplateVariables struct {
CommonTemplateVariables
Torrent model.TorrentJSON
CaptchaID string
FormErrors map[string][]string
Infos map[string][]string
FormErrors map[string][]string
Infos map[string][]string
}
type UserRegisterTemplateVariables struct {
@ -68,7 +68,7 @@ type UserProfileVariables struct {
type UserProfileNotifVariables struct {
CommonTemplateVariables
Infos map[string][]string
Infos map[string][]string
}
type UserTorrentEdVbs struct {
@ -81,25 +81,25 @@ type UserTorrentEdVbs struct {
type HomeTemplateVariables struct {
CommonTemplateVariables
ListTorrents []model.TorrentJSON
Infos map[string][]string
Infos map[string][]string
}
type DatabaseDumpTemplateVariables struct {
CommonTemplateVariables
ListDumps []model.DatabaseDumpJSON
GPGLink string
ListDumps []model.DatabaseDumpJSON
GPGLink string
}
type UploadTemplateVariables struct {
CommonTemplateVariables
Upload UploadForm
FormErrors map[string][]string
FormErrors map[string][]string
}
type ChangeLanguageVariables struct {
CommonTemplateVariables
Language string
Languages map[string]string
Language string
Languages map[string]string
}
/* MODERATION Variables */
@ -114,17 +114,17 @@ type PanelIndexVbs struct {
type PanelTorrentListVbs struct {
CommonTemplateVariables
Torrents []model.Torrent
Errors map[string][]string
Infos map[string][]string
Torrents []model.Torrent
Errors map[string][]string
Infos map[string][]string
}
type PanelUserListVbs struct {
CommonTemplateVariables
Users []model.User
Users []model.User
}
type PanelCommentListVbs struct {
CommonTemplateVariables
Comments []model.Comment
Comments []model.Comment
}
type PanelTorrentEdVbs struct {
@ -155,8 +155,8 @@ type CommonTemplateVariables struct {
Search SearchForm
T languages.TemplateTfunc
User *model.User
URL *url.URL // for parsing URL in templates
Route *mux.Route // for getting current route in templates
URL *url.URL // for parsing URL in templates
Route *mux.Route // for getting current route in templates
}
type Navigation struct {
@ -201,4 +201,3 @@ func NewCommonVariables(r *http.Request) CommonTemplateVariables {
Route: mux.CurrentRoute(r),
}
}

Voir le fichier

@ -257,7 +257,7 @@ func (f *UploadForm) ExtractEditInfo(r *http.Request) error {
if !categories.CategoryExists(f.Category) {
return ErrInvalidTorrentCategory
}
f.CategoryID = CatID
f.SubCategoryID = SubCatID
} else {
@ -292,4 +292,4 @@ func NewUploadForm(params ...string) (uploadForm UploadForm) {
uploadForm.Description = "Description"
}
return
}
}

Voir le fichier

@ -80,12 +80,12 @@ func UploadPostHandler(w http.ResponseWriter, r *http.Request) {
url, err := Router.Get("view_torrent").URL("id", strconv.FormatUint(uint64(torrent.ID), 10))
if (user.ID > 0 && config.DefaultUserSettings["new_torrent"]) { // If we are a member and notifications for new torrents are enabled
userService.GetLikings(user) // We populate the liked field for users
if len(user.Likings) > 0 { // If we are followed by at least someone
if user.ID > 0 && config.DefaultUserSettings["new_torrent"] { // If we are a member and notifications for new torrents are enabled
userService.GetLikings(user) // We populate the liked field for users
if len(user.Likings) > 0 { // If we are followed by at least someone
for _, follower := range user.Likings {
follower.ParseSettings() // We need to call it before checking settings
if follower.Settings.Get("new_torrent") {
if follower.Settings.Get("new_torrent") {
T, _, _ := languages.TfuncAndLanguageWithFallback(follower.Language, follower.Language) // We need to send the notification to every user in their language
notifierService.NotifyUser(&follower, torrent.Identifier(), fmt.Sprintf(T("new_torrent_uploaded"), torrent.Name, user.Username), url.String(), follower.Settings.Get("new_torrent_email"))
@ -128,8 +128,8 @@ func UploadGetHandler(w http.ResponseWriter, r *http.Request) {
utv := UploadTemplateVariables{
CommonTemplateVariables: NewCommonVariables(r),
Upload: uploadForm,
FormErrors: messages.GetAllErrors(),
Upload: uploadForm,
FormErrors: messages.GetAllErrors(),
}
err := uploadTemplate.ExecuteTemplate(w, "index.html", utv)
if err != nil {

Voir le fichier

@ -147,7 +147,6 @@ func UserProfileFormHandler(w http.ResponseWriter, r *http.Request) {
userForm := form.UserForm{}
userSettingsForm := form.UserSettingsForm{}
Ts, _ := languages.GetTfuncAndLanguageFromRequest(r)
if len(r.PostFormValue("email")) > 0 {
@ -277,7 +276,7 @@ func UserLoginPostHandler(w http.ResponseWriter, r *http.Request) {
}
}
if messages.HasErrors() {
UserLoginFormHandler(w,r)
UserLoginFormHandler(w, r)
}
}

Voir le fichier

@ -149,7 +149,7 @@ func ReportTorrentHandler(w http.ResponseWriter, r *http.Request) {
func TorrentEditUserPanel(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
torrent, _ := torrentService.GetTorrentById(id)
messages:= msg.GetMessages(r)
messages := msg.GetMessages(r)
currentUser := GetUser(r)
if userPermission.CurrentOrAdmin(currentUser, torrent.UploaderID) {
uploadForm := NewUploadForm()
@ -196,9 +196,9 @@ func TorrentPostEditUserPanel(w http.ResponseWriter, r *http.Request) {
db.ORM.Save(&torrent)
messages.AddInfoT("infos", "torrent_updated")
}
htv := UserTorrentEdVbs{NewCommonVariables(r), uploadForm, messages.GetAllErrors(), messages.GetAllInfos()}
err_ := userTorrentEd.ExecuteTemplate(w, "index.html", htv)
log.CheckError(err_)
htv := UserTorrentEdVbs{NewCommonVariables(r), uploadForm, messages.GetAllErrors(), messages.GetAllInfos()}
err_ := userTorrentEd.ExecuteTemplate(w, "index.html", htv)
log.CheckError(err_)
} else {
NotFoundHandler(w, r)
}
@ -210,7 +210,7 @@ func TorrentDeleteUserPanel(w http.ResponseWriter, r *http.Request) {
torrent, _ := torrentService.GetTorrentById(id)
if userPermission.CurrentOrAdmin(currentUser, torrent.UploaderID) {
_, err := torrentService.DeleteTorrent(id)
if (err == nil) {
if err == nil {
//delete reports of torrent
whereParams := serviceBase.CreateWhereParams("torrent_id = ?", id)
reports, _, _ := reportService.GetTorrentReportsOrderBy(&whereParams, "", 0, 0)
@ -223,4 +223,4 @@ func TorrentDeleteUserPanel(w http.ResponseWriter, r *http.Request) {
} else {
NotFoundHandler(w, r)
}
}
}

Voir le fichier

@ -1,64 +1,63 @@
package router
import (
"net/http"
"github.com/NyaaPantsu/nyaa/service/user/permission"
)
type wrappedResponseWriter struct {
Rw http.ResponseWriter
Ignore bool
}
func (wrw *wrappedResponseWriter) WriteHeader(status int) {
if status==404 {
wrw.Ignore=true
} else {
wrw.Rw.WriteHeader(status)
}
}
func (wrw *wrappedResponseWriter) Write(p []byte) (int, error) {
if wrw.Ignore {
return 0, nil
}
return wrw.Rw.Write(p)
}
func (wrw *wrappedResponseWriter) Header() http.Header {
return wrw.Rw.Header()
}
type wrappedHandler struct {
h http.Handler
}
func (wh *wrappedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
wrw := wrappedResponseWriter{w, false}
wh.h.ServeHTTP(&wrw, r)
if wrw.Ignore==true {
wrw.Rw.Header().Del("Content-Encoding")
wrw.Rw.Header().Del("Vary")
wrw.Rw.Header().Set("Content-Type", "text/html; charset=utf-8")
NotFoundHandler(wrw.Rw, r)
}
}
func wrapHandler(handler http.Handler) http.Handler {
return &wrappedHandler{handler}
}
// Make sure the user is a moderator, otherwise return forbidden
// TODO Clean this
func WrapModHandler(handler func (w http.ResponseWriter, r *http.Request)) (func (w http.ResponseWriter, r *http.Request)) {
return func (w http.ResponseWriter, r *http.Request) {
currentUser := GetUser(r)
if userPermission.HasAdmin(currentUser) {
handler(w, r)
} else {
http.Error(w, "admins only", http.StatusForbidden)
}
}
}
package router
import (
"net/http"
"github.com/NyaaPantsu/nyaa/service/user/permission"
)
type wrappedResponseWriter struct {
Rw http.ResponseWriter
Ignore bool
}
func (wrw *wrappedResponseWriter) WriteHeader(status int) {
if status == 404 {
wrw.Ignore = true
} else {
wrw.Rw.WriteHeader(status)
}
}
func (wrw *wrappedResponseWriter) Write(p []byte) (int, error) {
if wrw.Ignore {
return 0, nil
}
return wrw.Rw.Write(p)
}
func (wrw *wrappedResponseWriter) Header() http.Header {
return wrw.Rw.Header()
}
type wrappedHandler struct {
h http.Handler
}
func (wh *wrappedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
wrw := wrappedResponseWriter{w, false}
wh.h.ServeHTTP(&wrw, r)
if wrw.Ignore == true {
wrw.Rw.Header().Del("Content-Encoding")
wrw.Rw.Header().Del("Vary")
wrw.Rw.Header().Set("Content-Type", "text/html; charset=utf-8")
NotFoundHandler(wrw.Rw, r)
}
}
func wrapHandler(handler http.Handler) http.Handler {
return &wrappedHandler{handler}
}
// Make sure the user is a moderator, otherwise return forbidden
// TODO Clean this
func WrapModHandler(handler func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
currentUser := GetUser(r)
if userPermission.HasAdmin(currentUser) {
handler(w, r)
} else {
http.Error(w, "admins only", http.StatusForbidden)
}
}
}

Voir le fichier

@ -5,23 +5,22 @@ import (
"github.com/NyaaPantsu/nyaa/model"
)
func NotifyUser(user *model.User, name string, msg string, url string, email bool) {
if (user.ID > 0) {
if user.ID > 0 {
notification := model.NewNotification(name, msg, url)
notification.UserID = user.ID
db.ORM.Create(&notification)
// TODO: Email notification
/* if email {
}*/
/* if email {
}*/
}
}
func ToggleReadNotification(identifier string, id uint) { //
func ToggleReadNotification(identifier string, id uint) { //
db.ORM.Model(&model.Notification{}).Where("identifier = ? AND user_id = ?", identifier, id).Updates(model.Notification{Read: true})
}
func DeleteAllNotifications(id uint) { //
func DeleteAllNotifications(id uint) { //
db.ORM.Where("user_id = ?", id).Delete(&model.Notification{})
}
}

Voir le fichier

@ -1,11 +1,11 @@
package torrentform
type PanelPost struct {
Name string `form:"name" needed:"true" len_min:"3" len_max:"20"`
Hash string `form:"hash" needed:"true"`
Category int `form:"cat" needed:"true"`
Sub_Category int `form:"subcat"`
Status string `form:"status" needed:"true"`
Description string `form:"desc"`
WebsiteLink string `form:"website"`
}
Name string `form:"name" needed:"true" len_min:"3" len_max:"20"`
Hash string `form:"hash" needed:"true"`
Category int `form:"cat" needed:"true"`
Sub_Category int `form:"subcat"`
Status string `form:"status" needed:"true"`
Description string `form:"desc"`
WebsiteLink string `form:"website"`
}

Voir le fichier

@ -229,13 +229,13 @@ func (fetcher *MetainfoFetcher) fillQueue() {
for id, _ := range fetcher.failedOperations {
excludedIDS = append(excludedIDS, id)
}
tFiles := config.FilesTableName
tTorrents := config.TorrentsTableName
// Select the torrents with no filesize, or without any rows with torrent_id in the files table...
queryString := "((filesize IS NULL OR filesize = 0) OR ("+tTorrents+".torrent_id NOT "+
"IN (SELECT "+tFiles+".torrent_id FROM "+tFiles+" WHERE "+tFiles+
".torrent_id = "+tTorrents+".torrent_id)))"
queryString := "((filesize IS NULL OR filesize = 0) OR (" + tTorrents + ".torrent_id NOT " +
"IN (SELECT " + tFiles + ".torrent_id FROM " + tFiles + " WHERE " + tFiles +
".torrent_id = " + tTorrents + ".torrent_id)))"
var whereParamsArgs []interface{}
// that are newer than maxDays...

Voir le fichier

@ -11,7 +11,7 @@ import (
"github.com/NyaaPantsu/nyaa/model"
"github.com/NyaaPantsu/nyaa/service"
"github.com/NyaaPantsu/nyaa/util"
// "github.com/NyaaPantsu/nyaa/util/log"
// "github.com/NyaaPantsu/nyaa/util/log"
)
/* Function to interact with Models

Voir le fichier

@ -17,9 +17,9 @@ import (
)
const (
CookieName = "session"
CookieName = "session"
UserContextKey = "user"
)
)
// If you want to keep login cookies between restarts you need to make these permanent
var cookieHandler = securecookie.New(
@ -159,10 +159,10 @@ func CurrentUser(r *http.Request) (model.User, error) {
func getUserFromContext(r *http.Request) model.User {
if rv := context.Get(r, UserContextKey); rv != nil {
return rv.(model.User)
}
return model.User{}
return rv.(model.User)
}
return model.User{}
}
func setUserToContext(r *http.Request, val model.User) {
context.Set(r, UserContextKey, val)
context.Set(r, UserContextKey, val)
}

Voir le fichier

@ -76,16 +76,16 @@ type UserForm struct {
// UserSettingsForm is used when updating a user.
type UserSettingsForm struct {
NewTorrent bool `form:"new_torrent" default:"true"`
NewTorrentEmail bool `form:"new_torrent_email" default:"true"`
NewComment bool `form:"new_comment" default:"true"`
NewCommentEmail bool `form:"new_comment_email" default:"false"`
NewResponses bool `form:"new_responses" default:"true"`
NewResponsesEmail bool `form:"new_responses_email" default:"false"`
NewFollower bool `form:"new_follower" default:"true"`
NewFollowerEmail bool `form:"new_follower_email" default:"true"`
Followed bool `form:"followed" default:"false"`
FollowedEmail bool `form:"followed_email" default:"false"`
NewTorrent bool `form:"new_torrent" default:"true"`
NewTorrentEmail bool `form:"new_torrent_email" default:"true"`
NewComment bool `form:"new_comment" default:"true"`
NewCommentEmail bool `form:"new_comment_email" default:"false"`
NewResponses bool `form:"new_responses" default:"true"`
NewResponsesEmail bool `form:"new_responses_email" default:"false"`
NewFollower bool `form:"new_follower" default:"true"`
NewFollowerEmail bool `form:"new_follower_email" default:"true"`
Followed bool `form:"followed" default:"false"`
FollowedEmail bool `form:"followed_email" default:"false"`
}
// PasswordForm is used when updating a user password.

Voir le fichier

@ -60,7 +60,7 @@ func CategoryExists(category string) bool {
}
func GetCategoriesSelect(keepParent bool) map[string]string {
categories := GetCategories()
categories := GetCategories()
catSelect := make(map[string]string, len(categories))
for k, v := range categories {
if len(k) > 2 || keepParent {
@ -68,4 +68,4 @@ func GetCategoriesSelect(keepParent bool) map[string]string {
}
}
return catSelect
}
}

Voir le fichier

@ -31,6 +31,7 @@ var htmlFlags = 0 |
func init() {
HtmlMdRenderer = md.HtmlRenderer(htmlFlags, "", "")
}
var HtmlMdRenderer md.Renderer
// TODO: restrict certain types of markdown
@ -38,13 +39,12 @@ func MarkdownToHTML(markdown string) template.HTML {
if len(markdown) >= 3 && markdown[:3] == ">" {
markdown = ">" + markdown[3:]
}
markdown = strings.Replace(markdown,"\n>","\n>", -1)
markdown = strings.Replace(markdown, "\n>", "\n>", -1)
unsafe := md.MarkdownOptions([]byte(markdown), HtmlMdRenderer, md.Options{Extensions: mdOptions})
html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
return template.HTML(html)
}
/*
* Sanitize a message passed as a string according to a setted model or allowing a set of html tags and output a string
*/
@ -273,4 +273,4 @@ func repairHTMLTags(brokenHtml string) string {
html.Render(&b, root)
fixedHTML := b.String()
return fixedHTML
}
}

Voir le fichier

@ -1,49 +1,50 @@
package Messages
import (
"github.com/gorilla/context"
"fmt"
"net/http"
"github.com/nicksnyder/go-i18n/i18n"
"github.com/NyaaPantsu/nyaa/util/languages"
"github.com/gorilla/context"
"github.com/nicksnyder/go-i18n/i18n"
"net/http"
)
const MessagesKey = "messages"
type Messages struct {
Errors map[string][]string
Infos map[string][]string
r *http.Request
T i18n.TranslateFunc
Infos map[string][]string
r *http.Request
T i18n.TranslateFunc
}
func GetMessages(r *http.Request) *Messages {
if rv := context.Get(r, MessagesKey); rv != nil {
mes := rv.(*Messages)
T, _ := languages.GetTfuncAndLanguageFromRequest(r)
mes.T = T
mes.r = r
return mes
} else {
context.Set(r, MessagesKey, &Messages{})
T, _ := languages.GetTfuncAndLanguageFromRequest(r)
return &Messages{make(map[string][]string),make(map[string][]string), r, T}
}
mes := rv.(*Messages)
T, _ := languages.GetTfuncAndLanguageFromRequest(r)
mes.T = T
mes.r = r
return mes
} else {
context.Set(r, MessagesKey, &Messages{})
T, _ := languages.GetTfuncAndLanguageFromRequest(r)
return &Messages{make(map[string][]string), make(map[string][]string), r, T}
}
}
func (mes *Messages) AddError(name string, msg string) {
if (mes.Errors == nil) {
if mes.Errors == nil {
mes.Errors = make(map[string][]string)
}
mes.Errors[name] = append(mes.Errors[name], msg)
mes.setMessagesInContext()
}
func (mes *Messages) AddErrorf( name string, msg string, args ...interface{}) {
func (mes *Messages) AddErrorf(name string, msg string, args ...interface{}) {
mes.AddError(name, fmt.Sprintf(msg, args...))
}
func (mes *Messages) AddErrorTf( name string, id string, args ...interface{}) {
func (mes *Messages) AddErrorTf(name string, id string, args ...interface{}) {
mes.AddErrorf(name, mes.T(id), args...)
}
func (mes *Messages) AddErrorT( name string, id string) {
func (mes *Messages) AddErrorT(name string, id string) {
mes.AddError(name, mes.T(id))
}
func (mes *Messages) ImportFromError(name string, err error) {
@ -51,7 +52,7 @@ func (mes *Messages) ImportFromError(name string, err error) {
}
func (mes *Messages) AddInfo(name string, msg string) {
if (mes.Infos == nil) {
if mes.Infos == nil {
mes.Infos = make(map[string][]string)
}
mes.Infos[name] = append(mes.Infos[name], msg)
@ -104,5 +105,5 @@ func (mes *Messages) HasInfos() bool {
}
func (mes *Messages) setMessagesInContext() {
context.Set(mes.r, MessagesKey, mes)
}
context.Set(mes.r, MessagesKey, mes)
}

Voir le fichier

@ -151,13 +151,13 @@ func searchByQuery(r *http.Request, pagenum int, countAll bool, withUser bool) (
orderBy += "asc"
if db.ORM.Dialect().GetName() == "postgres" {
orderBy += " NULLS FIRST"
}
}
default:
orderBy += "desc"
if db.ORM.Dialect().GetName() == "postgres" {
orderBy += " NULLS LAST"
}
}
}
}
parameters := serviceBase.WhereParams{
Params: make([]interface{}, 0, 64),