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/router/view_torrent_handler.go

296 lignes
9.0 KiB
Go
Brut Vue normale Historique

package router
2017-05-06 10:36:37 +02:00
import (
2017-05-22 00:22:42 +02:00
"fmt"
"io"
2017-05-06 10:36:37 +02:00
"net/http"
"strconv"
2017-05-10 22:09:17 +02:00
"strings"
2017-05-08 19:26:29 +02:00
"time"
"os"
"github.com/NyaaPantsu/nyaa/config"
2017-05-17 07:58:40 +02:00
"github.com/NyaaPantsu/nyaa/db"
"github.com/NyaaPantsu/nyaa/model"
2017-05-23 04:05:33 +02:00
"github.com/NyaaPantsu/nyaa/service"
"github.com/NyaaPantsu/nyaa/service/api"
2017-05-17 07:58:40 +02:00
"github.com/NyaaPantsu/nyaa/service/captcha"
2017-05-21 01:06:40 +02:00
"github.com/NyaaPantsu/nyaa/service/notifier"
2017-05-23 04:05:33 +02:00
"github.com/NyaaPantsu/nyaa/service/report"
2017-05-17 07:58:40 +02:00
"github.com/NyaaPantsu/nyaa/service/torrent"
"github.com/NyaaPantsu/nyaa/service/user/permission"
"github.com/NyaaPantsu/nyaa/util"
"github.com/NyaaPantsu/nyaa/util/filelist"
2017-05-17 07:58:40 +02:00
"github.com/NyaaPantsu/nyaa/util/log"
msg "github.com/NyaaPantsu/nyaa/util/messages"
"github.com/NyaaPantsu/nyaa/util/publicSettings"
"github.com/gorilla/mux"
)
// ViewHandler : Controller for displaying a torrent
func ViewHandler(w http.ResponseWriter, r *http.Request) {
2017-05-27 03:50:31 +02:00
defer r.Body.Close()
vars := mux.Vars(r)
id := vars["id"]
messages := msg.GetMessages(r)
user := getUser(r)
if r.URL.Query()["success"] != nil {
messages.AddInfo("infos", "Torrent uploaded successfully!")
}
torrent, err := torrentService.GetTorrentByID(id)
if r.URL.Query()["notif"] != nil {
2017-05-21 01:06:40 +02:00
notifierService.ToggleReadNotification(torrent.Identifier(), user.ID)
}
if err != nil {
NotFoundHandler(w, r)
return
}
b := torrent.ToJSON()
folder := filelist.FileListToFolder(torrent.FileList, "root")
captchaID := ""
if userPermission.NeedsCaptcha(user) {
captchaID = captcha.GetID()
}
htv := viewTemplateVariables{newCommonVariables(r), b, folder, captchaID, messages.GetAllErrors(), messages.GetAllInfos()}
err = viewTemplate.ExecuteTemplate(w, "index.html", htv)
if err != nil {
log.Errorf("ViewHandler(): %s", err)
}
2017-05-06 10:36:37 +02:00
}
// ViewHeadHandler : Controller for checking a torrent
func ViewHeadHandler(w http.ResponseWriter, r *http.Request) {
2017-05-27 03:50:31 +02:00
defer r.Body.Close()
vars := mux.Vars(r)
id, err := strconv.ParseInt(vars["id"], 10, 32)
if err != nil {
return
}
_, err = torrentService.GetRawTorrentByID(uint(id))
if err != nil {
NotFoundHandler(w, r)
return
}
w.Write(nil)
}
// PostCommentHandler : Controller for posting a comment
func PostCommentHandler(w http.ResponseWriter, r *http.Request) {
2017-05-27 03:50:31 +02:00
defer r.Body.Close()
vars := mux.Vars(r)
id := vars["id"]
torrent, err := torrentService.GetTorrentByID(id)
if err != nil {
2017-05-22 00:22:42 +02:00
NotFoundHandler(w, r)
return
}
currentUser := getUser(r)
2017-05-21 19:38:39 +02:00
messages := msg.GetMessages(r)
if userPermission.NeedsCaptcha(currentUser) {
userCaptcha := captcha.Extract(r)
if !captcha.Authenticate(userCaptcha) {
2017-05-23 04:05:33 +02:00
messages.AddErrorT("errors", "bad_captcha")
}
}
content := util.Sanitize(r.FormValue("comment"), "comment")
if strings.TrimSpace(content) == "" {
2017-05-23 04:05:33 +02:00
messages.AddErrorT("errors", "comment_empty")
}
2017-05-29 13:25:36 +02:00
if len(content) > 500 {
messages.AddErrorT("errors", "comment_toolong")
}
2017-05-21 19:38:39 +02:00
if !messages.HasErrors() {
userID := currentUser.ID
2017-05-29 13:25:36 +02:00
2017-05-22 00:22:42 +02:00
comment := model.Comment{TorrentID: torrent.ID, UserID: userID, Content: content, CreatedAt: time.Now()}
err := db.ORM.Create(&comment).Error
comment.Torrent = &torrent
url, err := Router.Get("view_torrent").URL("id", strconv.FormatUint(uint64(torrent.ID), 10))
torrent.Uploader.ParseSettings()
if torrent.Uploader.Settings.Get("new_comment") {
T, _, _ := publicSettings.TfuncAndLanguageWithFallback(torrent.Uploader.Language, torrent.Uploader.Language) // We need to send the notification to every user in their language
2017-05-22 00:22:42 +02:00
notifierService.NotifyUser(torrent.Uploader, comment.Identifier(), fmt.Sprintf(T("new_comment_on_torrent"), torrent.Name), url.String(), torrent.Uploader.Settings.Get("new_comment_email"))
}
2017-05-21 19:38:39 +02:00
if err != nil {
messages.ImportFromError("errors", err)
}
}
ViewHandler(w, r)
}
2017-05-10 10:17:21 +02:00
// ReportTorrentHandler : Controller for sending a torrent report
2017-05-10 10:17:21 +02:00
func ReportTorrentHandler(w http.ResponseWriter, r *http.Request) {
2017-05-27 03:50:31 +02:00
defer r.Body.Close()
2017-05-10 10:17:21 +02:00
vars := mux.Vars(r)
id := vars["id"]
2017-05-21 19:38:39 +02:00
messages := msg.GetMessages(r)
currentUser := getUser(r)
if userPermission.NeedsCaptcha(currentUser) {
userCaptcha := captcha.Extract(r)
if !captcha.Authenticate(userCaptcha) {
2017-05-23 04:05:33 +02:00
messages.AddErrorT("errors", "bad_captcha")
}
}
2017-05-21 19:38:39 +02:00
if !messages.HasErrors() {
idNum, err := strconv.Atoi(id)
userID := currentUser.ID
report := model.TorrentReport{
Description: r.FormValue("report_type"),
TorrentID: uint(idNum),
UserID: userID,
CreatedAt: time.Now(),
}
2017-05-10 10:17:21 +02:00
2017-05-21 19:38:39 +02:00
err = db.ORM.Create(&report).Error
if err != nil {
messages.ImportFromError("errors", err)
}
2017-05-10 10:17:21 +02:00
}
ViewHandler(w, r)
2017-05-10 10:17:21 +02:00
}
2017-05-23 04:05:33 +02:00
// TorrentEditUserPanel : Controller for editing a user torrent by a user, after GET request
2017-05-23 04:05:33 +02:00
func TorrentEditUserPanel(w http.ResponseWriter, r *http.Request) {
2017-05-27 03:50:31 +02:00
defer r.Body.Close()
2017-05-23 04:05:33 +02:00
id := r.URL.Query().Get("id")
torrent, _ := torrentService.GetTorrentByID(id)
2017-05-24 09:11:13 +02:00
messages := msg.GetMessages(r)
currentUser := getUser(r)
2017-05-23 04:05:33 +02:00
if userPermission.CurrentOrAdmin(currentUser, torrent.UploaderID) {
uploadForm := apiService.NewTorrentRequest()
2017-05-23 04:12:02 +02:00
uploadForm.Name = torrent.Name
uploadForm.Category = strconv.Itoa(torrent.Category) + "_" + strconv.Itoa(torrent.SubCategory)
uploadForm.Remake = torrent.Status == model.TorrentStatusRemake
uploadForm.WebsiteLink = string(torrent.WebsiteLink)
uploadForm.Description = string(torrent.Description)
uploadForm.Hidden = torrent.Hidden
htv := formTemplateVariables{newCommonVariables(r), uploadForm, messages.GetAllErrors(), messages.GetAllInfos()}
2017-05-23 04:05:33 +02:00
err := userTorrentEd.ExecuteTemplate(w, "index.html", htv)
log.CheckError(err)
} else {
NotFoundHandler(w, r)
}
}
// TorrentPostEditUserPanel : Controller for editing a user torrent by a user, after post request
2017-05-23 04:05:33 +02:00
func TorrentPostEditUserPanel(w http.ResponseWriter, r *http.Request) {
2017-05-27 03:50:31 +02:00
defer r.Body.Close()
var uploadForm apiService.TorrentRequest
2017-05-23 04:05:33 +02:00
id := r.URL.Query().Get("id")
messages := msg.GetMessages(r)
torrent, _ := torrentService.GetTorrentByID(id)
currentUser := getUser(r)
2017-05-23 04:05:33 +02:00
if torrent.ID > 0 && userPermission.CurrentOrAdmin(currentUser, torrent.UploaderID) {
errUp := uploadForm.ExtractEditInfo(r)
if errUp != nil {
messages.AddErrorT("errors", "fail_torrent_update")
}
if !messages.HasErrors() {
status := model.TorrentStatusNormal
if uploadForm.Remake { // overrides trusted
status = model.TorrentStatusRemake
} else if currentUser.IsTrusted() {
status = model.TorrentStatusTrusted
}
// update some (but not all!) values
torrent.Name = uploadForm.Name
torrent.Category = uploadForm.CategoryID
torrent.SubCategory = uploadForm.SubCategoryID
torrent.Status = status
torrent.Hidden = uploadForm.Hidden
2017-05-23 04:05:33 +02:00
torrent.WebsiteLink = uploadForm.WebsiteLink
torrent.Description = uploadForm.Description
Deleted torrents mod done (#732) * Torrent Mass Edit Api (WIP) * Torrents can be deleted in mass from frontend with api post request * Torrents status can be edited from frontend with api post request -- Look to function doc for more info on how to use it It is a WIP so it might not work =D * Finished Mass mod Api As per suggestion of @yiiTT in #720, I added: * Changing torrents category * Deletion of reports with deletion of a torrent * Changing owner of multiple torrents Commit also add some new translation strings. * Make some changes * Reports can now be cleared for the torrents selected without having to delete them * Users with no admin rights can't delete reports * Fix moveto to status moveto deprecated in api * Tested and works! Changes: * Updates only the colomns of torrent table * Moved categories config in config/torrents.go * Forgot this file in last commit * Less useless queries The use of Save makes it that users are created and updates also all the associatiated models. Better to just update the colomns needed (less useless queries) * Some Updates * Added a new status of 5 for locking torrents * Modifying the list torrents view for using it in deleted torrents view * Added function to get deleted torrents * Torrents (and reports) can be definitely deleted * Some new translation string * Fixing * fix 2 * Added upload check for locked torrents If a user owns a torrent, has deleted it and try to repload it. As long as it has not been locked, he can. * Fixing wrong condition in isdeleted * Finished * Info messages on success when deletes or lock * Fixed double deleted_at is Null * Added Link to view of deleted torrents * Added new translation string
2017-05-25 02:19:05 +02:00
// torrent.Uploader = nil // GORM will create a new user otherwise (wtf?!)
db.ORM.Model(&torrent).UpdateColumn(&torrent)
2017-05-23 04:05:33 +02:00
messages.AddInfoT("infos", "torrent_updated")
}
htv := formTemplateVariables{newCommonVariables(r), uploadForm, messages.GetAllErrors(), messages.GetAllInfos()}
err := userTorrentEd.ExecuteTemplate(w, "index.html", htv)
log.CheckError(err)
2017-05-23 04:05:33 +02:00
} else {
NotFoundHandler(w, r)
}
}
// TorrentDeleteUserPanel : Controller for deleting a user torrent by a user
2017-05-23 04:05:33 +02:00
func TorrentDeleteUserPanel(w http.ResponseWriter, r *http.Request) {
2017-05-27 03:50:31 +02:00
defer r.Body.Close()
2017-05-23 04:05:33 +02:00
id := r.URL.Query().Get("id")
currentUser := getUser(r)
torrent, _ := torrentService.GetTorrentByID(id)
2017-05-23 04:05:33 +02:00
if userPermission.CurrentOrAdmin(currentUser, torrent.UploaderID) {
_, err := torrentService.DeleteTorrent(id)
2017-05-24 09:11:13 +02:00
if err == nil {
2017-05-23 04:05:33 +02:00
//delete reports of torrent
whereParams := serviceBase.CreateWhereParams("torrent_id = ?", id)
reports, _, _ := reportService.GetTorrentReportsOrderBy(&whereParams, "", 0, 0)
for _, report := range reports {
reportService.DeleteTorrentReport(report.ID)
}
}
url, _ := Router.Get("home").URL()
http.Redirect(w, r, url.String()+"?deleted", http.StatusSeeOther)
} else {
NotFoundHandler(w, r)
}
2017-05-24 09:11:13 +02:00
}
// DownloadTorrent : Controller for downloading a torrent
func DownloadTorrent(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
vars := mux.Vars(r)
hash := vars["hash"]
if hash == "" && len(config.Conf.Torrents.FileStorage) == 0 {
//File not found, send 404
http.Error(w, "File not found.", 404)
return
}
//Check if file exists and open
Openfile, err := os.Open(fmt.Sprintf("%s%c%s.torrent", config.Conf.Torrents.FileStorage, os.PathSeparator, hash))
defer Openfile.Close() //Close after function return
if err != nil {
//File not found, send 404
http.Error(w, "File not found.", 404)
return
}
//Get the file size
FileStat, _ := Openfile.Stat() //Get info from file
FileSize := strconv.FormatInt(FileStat.Size(), 10) //Get file size as a string
torrent, err := torrentService.GetRawTorrentByHash(hash)
if err != nil {
//File not found, send 404
http.Error(w, "File not found.", 404)
return
}
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.torrent\"", torrent.Name))
w.Header().Set("Content-Type", "application/x-bittorrent")
w.Header().Set("Content-Length", FileSize)
//Send the file
// We reset the offset to 0
Openfile.Seek(0, 0)
io.Copy(w, Openfile) //'Copy' the file to the client
return
}