Albirew/nyaa-pantsu
Archivé
1
0
Bifurcation 0
Cette révision appartient à :
ayame-git 2017-05-10 21:42:20 +03:00
Parent c07149d43c
révision 1bf4012eb2
14 fichiers modifiés avec 234 ajouts et 140 suppressions

36
model/report.go Fichier normal
Voir le fichier

@ -0,0 +1,36 @@
package model
// TODO Add field to specify kind of reports
// TODO Add CreatedAt field
// INFO User can be null (anonymous reports)
// FIXME can't preload field Torrents for model.TorrentReport
type TorrentReport struct {
ID uint `gorm:"column:torrent_report_id;primary_key"`
Description string `gorm:"column:type"`
TorrentID uint `gorm:"column:torrent_id"`
UserID uint `gorm:"column:user_id"`
Torrent Torrent `gorm:"AssociationForeignKey:TorrentID;ForeignKey:torrent_id"`
User User `gorm:"AssociationForeignKey:UserID;ForeignKey:ID"`
}
type TorrentReportJson struct {
ID uint `json:"id"`
Description string `json:"description"`
Torrent TorrentJSON `json:"torrent"`
User string
}
/* Model Conversion to Json */
func (report *TorrentReport) ToJson() TorrentReportJson {
json := TorrentReportJson{report.ID, report.Description, report.Torrent.ToJSON(), report.User.Username}
return json
}
func TorrentReportsToJSON(reports []TorrentReport) []TorrentReportJson {
json := make([]TorrentReportJson, len(reports))
for i := range reports {
json[i] = reports[i].ToJson()
}
return json
}

Voir le fichier

@ -67,19 +67,6 @@ func (t Torrent) Size() (s int) {
}
// TODO Add field to specify kind of reports
// TODO Add CreatedAt field
// INFO User can be null (anonymous reports)
// FIXME can't preload field Torrents for model.TorrentReport
type TorrentReport struct {
ID uint `gorm:"column:torrent_report_id;primary_key"`
Description string `gorm:"column:type"`
TorrentID uint
UserID uint
Torrent Torrent `gorm:"AssociationForeignKey:TorrentID;ForeignKey:ID"`
User User `gorm:"AssociationForeignKey:UserID;ForeignKey:ID"`
}
/* We need a JSON object instead of a Gorm structure because magnet URLs are
not in the database and have to be generated dynamically */
@ -115,20 +102,6 @@ type TorrentJSON struct {
TorrentLink template.URL `json:"torrent"`
}
type TorrentReportJson struct {
ID uint `json:"id"`
Description string `json:"description"`
Torrent TorrentJSON `json:"torrent"`
User string
}
/* Model Conversion to Json */
func (report *TorrentReport) ToJson() TorrentReportJson {
json := TorrentReportJson{report.ID, report.Description, report.Torrent.ToJSON(), report.User.Username}
return json
}
// ToJSON converts a model.Torrent to its equivalent JSON structure
func (t *Torrent) ToJSON() TorrentJSON {
magnet := util.InfoHashToMagnet(strings.TrimSpace(t.Hash), t.Name, config.Trackers...)
@ -181,11 +154,3 @@ func TorrentsToJSON(t []Torrent) []TorrentJSON { // TODO: Convert to singular ve
}
return json
}
func TorrentReportsToJSON(reports []TorrentReport) []TorrentReportJson {
json := make([]TorrentReportJson, len(reports))
for i := range reports {
json[i] = reports[i].ToJson()
}
return json
}

Voir le fichier

@ -11,6 +11,7 @@ import (
"github.com/ewhal/nyaa/config"
"github.com/ewhal/nyaa/db"
"github.com/ewhal/nyaa/model"
"github.com/ewhal/nyaa/service"
"github.com/ewhal/nyaa/service/api"
"github.com/ewhal/nyaa/service/torrent"
"github.com/ewhal/nyaa/util"
@ -21,7 +22,7 @@ import (
func ApiHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
page := vars["page"]
whereParams := torrentService.WhereParams{}
whereParams := serviceBase.WhereParams{}
req := apiService.TorrentsRequest{}
contentType := r.Header.Get("Content-Type")

Voir le fichier

@ -10,8 +10,9 @@ import (
"path/filepath"
"strconv"
"github.com/ewhal/nyaa/model"
"github.com/ewhal/nyaa/service/comment"
"github.com/ewhal/nyaa/service/moderation"
"github.com/ewhal/nyaa/service/report"
"github.com/ewhal/nyaa/service/torrent"
"github.com/ewhal/nyaa/service/torrent/form"
"github.com/ewhal/nyaa/service/user"
@ -24,7 +25,7 @@ import (
"github.com/gorilla/mux"
)
var panelIndex, panelTorrentList, panelUserList, panelCommentList, panelTorrentEd, torrentReportTemplate *template.Template
var panelIndex, panelTorrentList, panelUserList, panelCommentList, panelTorrentEd, panelTorrentReportList *template.Template
func init() {
panelTorrentList = template.Must(template.New("torrentlist").Funcs(FuncMap).ParseFiles(filepath.Join(TemplateDir, "admin_index.html"), filepath.Join(TemplateDir, "admin/torrentlist.html")))
@ -37,8 +38,8 @@ func init() {
panelIndex = template.Must(panelIndex.ParseGlob(filepath.Join("templates", "_*.html")))
panelTorrentEd = template.Must(template.New("torrent_ed").Funcs(FuncMap).ParseFiles(filepath.Join(TemplateDir, "admin_index.html"), filepath.Join(TemplateDir, "admin/paneltorrentedit.html")))
panelTorrentEd = template.Must(panelTorrentEd.ParseGlob(filepath.Join("templates", "_*.html")))
torrentReportTemplate = template.Must(template.New("torrent_report").Funcs(FuncMap).ParseFiles(filepath.Join(TemplateDir, "admin_index.html"), filepath.Join(TemplateDir, "admin/torrent_report.html")))
torrentReportTemplate = template.Must(torrentReportTemplate.ParseGlob(filepath.Join("templates", "_*.html")))
panelTorrentReportList = template.Must(template.New("torrent_report").Funcs(FuncMap).ParseFiles(filepath.Join(TemplateDir, "admin_index.html"), filepath.Join(TemplateDir, "admin/torrent_report.html")))
panelTorrentReportList = template.Must(panelTorrentReportList.ParseGlob(filepath.Join("templates", "_*.html")))
}
func IndexModPanel(w http.ResponseWriter, r *http.Request) {
@ -49,7 +50,13 @@ func IndexModPanel(w http.ResponseWriter, r *http.Request) {
torrents, _, _ := torrentService.GetAllTorrents(offset, 0)
users, _ := userService.RetrieveUsersForAdmin(offset, 0)
comments, _ := commentService.GetAllComments(offset, 0, "", "")
torrentReports, _, _ := moderationService.GetTorrentReports(offset, 0, "", "")
torrentReports, _, _ := reportService.GetAllTorrentReports(offset, 0)
for i, report := range torrentReports { //shit fix pls fix model
torrentReports[i].Torrent, _ = torrentService.GetTorrentById(fmt.Sprint(report.TorrentID))
}
fmt.Println(torrentReports)
languages.SetTranslationFromRequest(panelIndex, r, "en-us")
htv := PanelIndexVbs{torrents, torrentReports, users, comments, NewSearchForm(), currentUser, r.URL}
_ = panelIndex.ExecuteTemplate(w, "admin_index.html", htv)
@ -57,6 +64,7 @@ func IndexModPanel(w http.ResponseWriter, r *http.Request) {
http.Error(w, "admins only", http.StatusForbidden)
}
}
func TorrentsListPanel(w http.ResponseWriter, r *http.Request) {
currentUser := GetUser(r)
if userPermission.HasAdmin(currentUser) {
@ -90,6 +98,39 @@ func TorrentsListPanel(w http.ResponseWriter, r *http.Request) {
http.Error(w, "admins only", http.StatusForbidden)
}
}
func TorrentReportListPanel(w http.ResponseWriter, r *http.Request) {
currentUser := GetUser(r)
if userPermission.HasAdmin(currentUser) {
vars := mux.Vars(r)
page := vars["page"]
var err error
pagenum := 1
if page != "" {
pagenum, err = strconv.Atoi(html.EscapeString(page))
if !log.CheckError(err) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
offset := 100
torrentReports, nbReports, _ := reportService.GetAllTorrentReports(offset, (pagenum-1)*offset)
for i, report := range torrentReports { //shit fix pls fix the model
torrentReports[i].Torrent, _ = torrentService.GetTorrentById(fmt.Sprint(report.TorrentID))
}
reportJSON := model.TorrentReportsToJSON(torrentReports)
languages.SetTranslationFromRequest(panelUserList, r, "en-us")
htv := PanelTorrentReportListVbs{reportJSON, NewSearchForm(), Navigation{nbReports, offset, pagenum, "mod_trlist_page"}, currentUser, r.URL}
err = panelTorrentReportList.ExecuteTemplate(w, "admin_index.html", htv)
fmt.Println(err)
} else {
http.Error(w, "admins only", http.StatusForbidden)
}
}
func UsersListPanel(w http.ResponseWriter, r *http.Request) {
currentUser := GetUser(r)
if userPermission.HasAdmin(currentUser) {
@ -116,6 +157,7 @@ func UsersListPanel(w http.ResponseWriter, r *http.Request) {
http.Error(w, "admins only", http.StatusForbidden)
}
}
func CommentsListPanel(w http.ResponseWriter, r *http.Request) {
currentUser := GetUser(r)
if userPermission.HasAdmin(currentUser) {

Voir le fichier

@ -42,6 +42,7 @@ func init() {
gzipIndexModPanel := handlers.CompressHandler(http.HandlerFunc(IndexModPanel))
gzipTorrentsListPanel := handlers.CompressHandler(http.HandlerFunc(TorrentsListPanel))
gzipTorrentReportListPanel := handlers.CompressHandler(http.HandlerFunc(TorrentReportListPanel))
gzipUsersListPanel := handlers.CompressHandler(http.HandlerFunc(UsersListPanel))
gzipCommentsListPanel := handlers.CompressHandler(http.HandlerFunc(CommentsListPanel))
gzipTorrentEditModPanel := handlers.CompressHandler(http.HandlerFunc(TorrentEditModPanel))
@ -49,7 +50,6 @@ func init() {
gzipCommentDeleteModPanel := handlers.CompressHandler(http.HandlerFunc(CommentDeleteModPanel))
gzipTorrentDeleteModPanel := handlers.CompressHandler(http.HandlerFunc(TorrentDeleteModPanel))
gzipGetTorrentReportHandler := handlers.CompressHandler(http.HandlerFunc(GetTorrentReportHandler))
//gzipTorrentReportCreateHandler := handlers.CompressHandler(http.HandlerFunc(CreateTorrentReportHandler))
//gzipTorrentReportDeleteHandler := handlers.CompressHandler(http.HandlerFunc(DeleteTorrentReportHandler))
//gzipTorrentDeleteHandler := handlers.CompressHandler(http.HandlerFunc(DeleteTorrentHandler))
@ -107,8 +107,8 @@ func init() {
// TODO Allow only moderators to access /moderation/*
//Router.Handle("/moderation/report/delete", gzipTorrentReportDeleteHandler).Name("torrent_report_delete").Methods("POST")
//Router.Handle("/moderation/torrent/delete", gzipTorrentDeleteHandler).Name("torrent_delete").Methods("POST")
Router.Handle("/mod/reports", gzipGetTorrentReportHandler).Name("mod_trlist").Methods("GET")
Router.Handle("/mod/reports/{page}", gzipGetTorrentReportHandler).Name("mod_trlist").Methods("GET")
Router.Handle("/mod/reports", gzipTorrentReportListPanel).Name("mod_trlist").Methods("GET")
Router.Handle("/mod/reports/{page}", gzipTorrentReportListPanel).Name("mod_trlist_page").Methods("GET")
Router.NotFoundHandler = http.HandlerFunc(NotFoundHandler)
}

Voir le fichier

@ -152,7 +152,7 @@ type PanelTorrentEdVbs struct {
User *model.User
}
type ViewTorrentReportsVariables struct {
type PanelTorrentReportListVbs struct {
Torrents []model.TorrentReportJson
Search SearchForm
Navigation Navigation

Voir le fichier

@ -1,6 +1,6 @@
package router
import (
/*import (
"net/http"
"strconv"
@ -8,7 +8,8 @@ import (
"github.com/ewhal/nyaa/service/moderation"
"github.com/ewhal/nyaa/service/user/permission"
"github.com/gorilla/mux"
)
)*/
/*
func SanitizeTorrentReport(torrentReport *model.TorrentReport) {
// TODO unescape html ?
@ -62,8 +63,7 @@ func DeleteTorrentHandler(w http.ResponseWriter, r *http.Request) {
}
}*/
func GetTorrentReportHandler(w http.ResponseWriter, r *http.Request) {
/*func GetTorrentReportHandler(w http.ResponseWriter, r *http.Request) {
currentUser := GetUser(r)
if userPermission.HasAdmin(currentUser) {
vars := mux.Vars(r)
@ -90,4 +90,4 @@ func GetTorrentReportHandler(w http.ResponseWriter, r *http.Request) {
} else {
http.Error(w, "admins only", http.StatusForbidden)
}
}
}*/

Voir le fichier

@ -13,6 +13,8 @@ import (
"github.com/ewhal/nyaa/util/languages"
"github.com/ewhal/nyaa/util/log"
"github.com/gorilla/mux"
"fmt"
)
func ViewHandler(w http.ResponseWriter, r *http.Request) {
@ -75,9 +77,18 @@ func ReportTorrentHandler(w http.ResponseWriter, r *http.Request) {
currentUser := GetUser(r)
idNum, err := strconv.Atoi(id)
userID := currentUser.ID
report := model.TorrentReport{Description: r.FormValue("report_type"), TorrentID: uint(idNum), UserID: userID}
torrent, _ := torrentService.GetTorrentById(id)
report := model.TorrentReport{
Description: r.FormValue("report_type"),
TorrentID: uint(idNum),
UserID: userID,
Torrent: torrent,
User: *currentUser,
}
fmt.Println(report)
err = db.ORM.Create(&report).Error
if err != nil {

Voir le fichier

@ -8,7 +8,7 @@ import (
"strings"
"github.com/ewhal/nyaa/model"
"github.com/ewhal/nyaa/service/torrent"
"github.com/ewhal/nyaa/service"
)
type torrentsQuery struct {
@ -40,8 +40,8 @@ type UpdateRequest struct {
Update TorrentRequest `json:"update"`
}
func (r *TorrentsRequest) ToParams() torrentService.WhereParams {
res := torrentService.WhereParams{}
func (r *TorrentsRequest) ToParams() serviceBase.WhereParams {
res := serviceBase.WhereParams{}
conditions := ""
v := reflect.ValueOf(r.Query)

Voir le fichier

@ -1,40 +0,0 @@
package moderationService
import (
"errors"
"net/http"
"github.com/ewhal/nyaa/db"
"github.com/ewhal/nyaa/model"
)
// Return torrentReport in case we did modified it (ie: CreatedAt field)
func CreateTorrentReport(torrentReport model.TorrentReport) (model.TorrentReport, error) {
if db.ORM.Create(&torrentReport).Error != nil {
return torrentReport, errors.New("TorrentReport was not created")
}
return torrentReport, nil
}
func DeleteTorrentReport(id int) (int, error) {
var torrentReport model.TorrentReport
if db.ORM.First(&torrentReport, id).RecordNotFound() {
return http.StatusNotFound, errors.New("Trying to delete a torrent report that does not exists.")
}
if db.ORM.Delete(&torrentReport).Error != nil {
return http.StatusInternalServerError, errors.New("TorrentReport is not deleted.")
}
return http.StatusOK, nil
}
// TODO Add WhereParams to filter the torrent reports (ie: searching description)
// TODO Use limit, offset
func GetTorrentReports(limit int, offset int, conditions string, values ...interface{}) ([]model.TorrentReport, int, error) {
var torrentReports []model.TorrentReport
var nbReports int
db.ORM.Model(&torrentReports).Where(conditions, values...).Count(&nbReports)
if db.ORM.Preload("User").Preload("Torrent").Find(&torrentReports).Error != nil {
return torrentReports, nbReports, errors.New("Problem finding all torrent reports.")
}
return torrentReports, nbReports, nil
}

76
service/report/report.go Fichier normal
Voir le fichier

@ -0,0 +1,76 @@
package reportService
import (
"errors"
"net/http"
"strconv"
"strings"
"github.com/ewhal/nyaa/db"
"github.com/ewhal/nyaa/model"
"github.com/ewhal/nyaa/service"
)
// Return torrentReport in case we did modified it (ie: CreatedAt field)
func CreateTorrentReport(torrentReport model.TorrentReport) error {
if db.ORM.Create(&torrentReport).Error != nil {
return errors.New("TorrentReport was not created")
}
return nil
}
func DeleteTorrentReport(id int) (error, int) {
var torrentReport model.TorrentReport
if db.ORM.First(&torrentReport, id).RecordNotFound() {
return errors.New("Trying to delete a torrent report that does not exists."), http.StatusNotFound
}
if err := db.ORM.Delete(&torrentReport).Error; err != nil {
return err, http.StatusInternalServerError
}
return nil, http.StatusOK
}
func getTorrentReportsOrderBy(parameters *serviceBase.WhereParams, orderBy string, limit int, offset int, countAll bool) (
torrentReports []model.TorrentReport, count int, err error,
) {
var conditionArray []string
var params []interface{}
if parameters != nil { // if there is where parameters
if len(parameters.Conditions) > 0 {
conditionArray = append(conditionArray, parameters.Conditions)
}
params = parameters.Params
}
conditions := strings.Join(conditionArray, " AND ")
if countAll {
err = db.ORM.Model(&torrentReports).Where(conditions, params...).Count(&count).Error
if err != nil {
return
}
}
// TODO: Vulnerable to injections. Use query builder. (is it?)
// build custom db query for performance reasons
dbQuery := "SELECT * FROM torrent_reports"
if conditions != "" {
dbQuery = dbQuery + " WHERE " + conditions
}
if orderBy == "" { // default OrderBy
orderBy = "torrent_report_id DESC"
}
dbQuery = dbQuery + " ORDER BY " + orderBy
if limit != 0 || offset != 0 { // if limits provided
dbQuery = dbQuery + " LIMIT " + strconv.Itoa(limit) + " OFFSET " + strconv.Itoa(offset)
}
err = db.ORM.Raw(dbQuery, params...).Find(&torrentReports).Error
return
}
func GetTorrentReportsOrderBy(parameters *serviceBase.WhereParams, orderBy string, limit int, offset int) ([]model.TorrentReport, int, error) {
return getTorrentReportsOrderBy(parameters, orderBy, limit, offset, true)
}
func GetAllTorrentReports(limit int, offset int) ([]model.TorrentReport, int, error) {
return GetTorrentReportsOrderBy(nil, "", limit, offset)
}

17
service/service.go Fichier normal
Voir le fichier

@ -0,0 +1,17 @@
package serviceBase
type WhereParams struct {
Conditions string // Ex : name LIKE ? AND category_id LIKE ?
Params []interface{}
}
func CreateWhereParams(conditions string, params ...string) WhereParams {
whereParams := WhereParams{
Conditions: conditions,
Params: make([]interface{}, len(params)),
}
for i := range params {
whereParams.Params[i] = params[i]
}
return whereParams
}

Voir le fichier

@ -2,21 +2,17 @@ package torrentService
import (
"errors"
"net/http"
"strconv"
"strings"
"net/http"
"github.com/ewhal/nyaa/config"
"github.com/ewhal/nyaa/db"
"github.com/ewhal/nyaa/model"
"github.com/ewhal/nyaa/service"
"github.com/ewhal/nyaa/util"
)
type WhereParams struct {
Conditions string // Ex : name LIKE ? AND category_id LIKE ?
Params []interface{}
}
/* Function to interact with Models
*
* Get the torrents with where clause
@ -92,17 +88,17 @@ func GetTorrentById(id string) (torrent model.Torrent, err error) {
return
}
func GetTorrentsOrderByNoCount(parameters *WhereParams, orderBy string, limit int, offset int) (torrents []model.Torrent, err error) {
func GetTorrentsOrderByNoCount(parameters *serviceBase.WhereParams, orderBy string, limit int, offset int) (torrents []model.Torrent, err error) {
torrents, _, err = getTorrentsOrderBy(parameters, orderBy, limit, offset, false)
return
}
func GetTorrentsOrderBy(parameters *WhereParams, orderBy string, limit int, offset int) (torrents []model.Torrent, count int, err error) {
func GetTorrentsOrderBy(parameters *serviceBase.WhereParams, orderBy string, limit int, offset int) (torrents []model.Torrent, count int, err error) {
torrents, count, err = getTorrentsOrderBy(parameters, orderBy, limit, offset, true)
return
}
func getTorrentsOrderBy(parameters *WhereParams, orderBy string, limit int, offset int, countAll bool) (
func getTorrentsOrderBy(parameters *serviceBase.WhereParams, orderBy string, limit int, offset int, countAll bool) (
torrents []model.Torrent, count int, err error,
) {
var conditionArray []string
@ -152,12 +148,12 @@ func getTorrentsOrderBy(parameters *WhereParams, orderBy string, limit int, offs
// database. The list will be of length 'limit' and in default order.
// GetTorrents returns the first records found. Later records may be retrieved
// by providing a positive 'offset'
func GetTorrents(parameters WhereParams, limit int, offset int) ([]model.Torrent, int, error) {
func GetTorrents(parameters serviceBase.WhereParams, limit int, offset int) ([]model.Torrent, int, error) {
return GetTorrentsOrderBy(&parameters, "", limit, offset)
}
// Get Torrents with where parameters but no limit and order by default (get all the torrents corresponding in the db)
func GetTorrentsDB(parameters WhereParams) ([]model.Torrent, int, error) {
func GetTorrentsDB(parameters serviceBase.WhereParams) ([]model.Torrent, int, error) {
return GetTorrentsOrderBy(&parameters, "", 0, 0)
}
@ -173,17 +169,6 @@ func GetAllTorrentsDB() ([]model.Torrent, int, error) {
return GetTorrentsOrderBy(nil, "", 0, 0)
}
func CreateWhereParams(conditions string, params ...string) WhereParams {
whereParams := WhereParams{
Conditions: conditions,
Params: make([]interface{}, len(params)),
}
for i := range params {
whereParams.Params[i] = params[i]
}
return whereParams
}
func DeleteTorrent(id string) (int, error) {
var torrent model.Torrent
if db.ORM.First(&torrent, id).RecordNotFound() {

Voir le fichier

@ -11,6 +11,7 @@ import (
"github.com/ewhal/nyaa/common"
"github.com/ewhal/nyaa/db"
"github.com/ewhal/nyaa/model"
"github.com/ewhal/nyaa/service"
"github.com/ewhal/nyaa/service/torrent"
"github.com/ewhal/nyaa/util/log"
)
@ -96,7 +97,7 @@ func searchByQuery(r *http.Request, pagenum int, countAll bool) (
}
tor, count, err = cache.Get(search, func() (tor []model.Torrent, count int, err error) {
parameters := torrentService.WhereParams{
parameters := serviceBase.WhereParams{
Params: make([]interface{}, 0, 64),
}
conditions := make([]string, 0, 64)