diff --git a/models/torrents/delete.go b/models/torrents/delete.go index 1c241fd9..70c4b40d 100644 --- a/models/torrents/delete.go +++ b/models/torrents/delete.go @@ -1,5 +1,12 @@ package torrents +import ( + "errors" + "net/http" + "nyaa-master/util/log" + + "github.com/NyaaPantsu/nyaa/models" +) // DeleteTorrent : delete a torrent based on id func DeleteTorrent(id uint) (*models.Torrent, int, error) { diff --git a/models/torrents/helpers.go b/models/torrents/helpers.go index bd1bd74f..bae28b9c 100644 --- a/models/torrents/helpers.go +++ b/models/torrents/helpers.go @@ -7,6 +7,8 @@ import ( "github.com/NyaaPantsu/nyaa/config" "github.com/NyaaPantsu/nyaa/models" + "github.com/NyaaPantsu/nyaa/models/activities" + "github.com/NyaaPantsu/nyaa/models/notifications" "github.com/NyaaPantsu/nyaa/util/publicSettings" ) @@ -14,13 +16,13 @@ import ( func ExistOrDelete(hash string, user *models.User) error { torrentIndb := models.Torrent{} models.ORM.Unscoped().Model(&models.Torrent{}).Where("torrent_hash = ?", hash).First(&torrentIndb) - if torrentInmodels.ID > 0 { - if user.CurrentUserIdentical(torrentInmodels.UploaderID) && torrentInmodels.IsDeleted() && !torrentInmodels.IsBlocked() { // if torrent is not locked and is deleted and the user is the actual owner - torrent, _, err := DefinitelyDeleteTorrent(strconv.Itoa(int(torrentInmodels.ID))) + if torrentIndb.ID > 0 { + if user.CurrentUserIdentical(torrentIndb.UploaderID) && torrentIndb.IsDeleted() && !torrentIndb.IsBlocked() { // if torrent is not locked and is deleted and the user is the actual owner + torrent, _, err := DefinitelyDelete(torrentIndb.ID) if err != nil { return err } - activity.Log(&models.User{}, torrent.Identifier(), "delete", "torrent_deleted_by", strconv.Itoa(int(torrent.ID)), torrent.Uploader.Username, user.Username) + activities.Log(&models.User{}, torrent.Identifier(), "delete", "torrent_deleted_by", strconv.Itoa(int(torrent.ID)), torrent.Uploader.Username, user.Username) } else { return errors.New("Torrent already in database") } @@ -32,13 +34,13 @@ func ExistOrDelete(hash string, user *models.User) error { func NewTorrentEvent(user *models.User, torrent *models.Torrent) error { url := "/view/" + strconv.FormatUint(uint64(torrent.ID), 10) if user.ID > 0 && config.Conf.Users.DefaultUserSettings["new_torrent"] { // If we are a member and notifications for new torrents are enabled - userService.GetFollowers(user) // We populate the liked field for users - if len(user.Followers) > 0 { // If we are followed by at least someone + user.GetFollowers() // We populate the liked field for users + if len(user.Followers) > 0 { // If we are followed by at least someone for _, follower := range user.Followers { follower.ParseSettings() // We need to call it before checking settings if follower.Settings.Get("new_torrent") { T, _, _ := publicSettings.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, follower.Settings.Get("new_torrent_email")) + notifications.NotifyUser(&follower, torrent.Identifier(), fmt.Sprintf(T("new_torrent_uploaded"), torrent.Name, user.Username), url, follower.Settings.Get("new_torrent_email")) } } } diff --git a/models/torrents/torrent.go b/models/torrents/torrent.go index 6a66c421..d438670a 100644 --- a/models/torrents/torrent.go +++ b/models/torrents/torrent.go @@ -2,17 +2,13 @@ package torrents import ( "errors" - "fmt" "net/http" - "nyaa-master/service/userService/userPermission" "strconv" "strings" "github.com/NyaaPantsu/nyaa/config" "github.com/NyaaPantsu/nyaa/models" "github.com/NyaaPantsu/nyaa/service" - "github.com/NyaaPantsu/nyaa/util/log" - "github.com/NyaaPantsu/nyaa/util/publicSettings" ) /* Function to interact with Models @@ -23,17 +19,12 @@ import ( // FindByID : get a torrent with its id func FindByID(id uint) (torrent models.Torrent, err error) { - // Postgres DB integer size is 32-bit - idInt, err := strconv.ParseInt(id, 10, 32) - if err != nil { - return - } tmp := models.ORM.Where("torrent_id = ?", id).Preload("Scrape").Preload("Comments") - if idInt > int64(config.Conf.Models.LastOldTorrentID) { + if id > config.Conf.Models.LastOldTorrentID { tmp = tmp.Preload("FileList") } - if idInt <= int64(config.Conf.Models.LastOldTorrentID) && !config.IsSukebei() { + if id <= config.Conf.Models.LastOldTorrentID && !config.IsSukebei() { // only preload old comments if they could actually exist tmp = tmp.Preload("OldComments") } @@ -155,32 +146,32 @@ func findOrderBy(parameters *serviceBase.WhereParams, orderBy string, limit int, return } -// FindRawByID obtain a list of torrents matching 'parameters' from the +// Find obtain a list of torrents matching 'parameters' from the // 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 FindRawByID(parameters serviceBase.WhereParams, limit int, offset int) ([]models.Torrent, int, error) { - return findOrderBy(¶meters, "", limit, offset) +func Find(parameters serviceBase.WhereParams, limit int, offset int) ([]models.Torrent, int, error) { + return FindOrderBy(¶meters, "", limit, offset) } // FindDB : Get Torrents with where parameters but no limit and order by default (get all the torrents corresponding in the db) func FindDB(parameters serviceBase.WhereParams) ([]models.Torrent, int, error) { - return findOrderBy(¶meters, "", 0, 0) + return FindOrderBy(¶meters, "", 0, 0) } // FindAllOrderBy : Get all torrents ordered by parameters func FindAllOrderBy(orderBy string, limit int, offset int) ([]models.Torrent, int, error) { - return findOrderBy(nil, orderBy, limit, offset) + return FindOrderBy(nil, orderBy, limit, offset) } // FindAll : Get all torrents without order func FindAll(limit int, offset int) ([]models.Torrent, int, error) { - return findOrderBy(nil, "", limit, offset) + return FindOrderBy(nil, "", limit, offset) } // GetAllInDB : Get all torrents func GetAllInDB() ([]models.Torrent, int, error) { - return findOrderBy(nil, "", 0, 0) + return FindOrderBy(nil, "", 0, 0) } // ToggleBlock ; Lock/Unlock a torrent based on id @@ -200,93 +191,8 @@ func ToggleBlock(id uint) (models.Torrent, int, error) { return torrent, http.StatusOK, nil } -// Update : Update a torrent based on model -func Update(torrent *models.Torrent) (int, error) { - if models.ORM.Model(torrent).UpdateColumn(torrent).Error != nil { - return http.StatusInternalServerError, errors.New("Torrent was not updated") - } - - // TODO Don't create a new client for each request - if models.ElasticSearchClient != nil { - err := torrent.AddToESIndex(models.ElasticSearchClient) - if err == nil { - log.Infof("Successfully updated torrent to ES index.") - } else { - log.Errorf("Unable to update torrent to ES index: %s", err) - } - } - - return http.StatusOK, nil -} - -// UpdateUnscope : Update a torrent based on model -func UpdateUnscope(torrent *models.Torrent) (int, error) { - if models.ORM.Unscoped().Model(torrent).UpdateColumn(torrent).Error != nil { - return http.StatusInternalServerError, errors.New("Torrent was not updated") - } - - // TODO Don't create a new client for each request - if models.ElasticSearchClient != nil { - err := torrent.AddToESIndex(models.ElasticSearchClient) - if err == nil { - log.Infof("Successfully updated torrent to ES index.") - } else { - log.Errorf("Unable to update torrent to ES index: %s", err) - } - } - - return http.StatusOK, nil -} - // FindDeleted : Gets deleted torrents based on search params func FindDeleted(parameters *serviceBase.WhereParams, orderBy string, limit int, offset int) (torrents []models.Torrent, count int, err error) { torrents, count, err = findOrderBy(parameters, orderBy, limit, offset, true, true, true) return } - -// ExistOrDelete : Check if a torrent exist with the same hash and if it can be replaced, it is replaced -func ExistOrDelete(hash string, user *models.User) error { - torrentIndb := models.Torrent{} - models.ORM.Unscoped().Model(&models.Torrent{}).Where("torrent_hash = ?", hash).First(&torrentIndb) - if torrentInmodels.ID > 0 { - if userPermission.CurrentUserIdentical(user, torrentInmodels.UploaderID) && torrentInmodels.IsDeleted() && !torrentInmodels.IsBlocked() { // if torrent is not locked and is deleted and the user is the actual owner - torrent, _, err := DefinitelyDeleteTorrent(strconv.Itoa(int(torrentInmodels.ID))) - if err != nil { - return err - } - activity.Log(&models.User{}, torrent.Identifier(), "delete", "torrent_deleted_by", strconv.Itoa(int(torrent.ID)), torrent.Uploader.Username, user.Username) - } else { - return errors.New("Torrent already in database") - } - } - return nil -} - -// NewTorrentEvent : Should be called when you create a new torrent -func NewTorrentEvent(user *models.User, torrent *models.Torrent) error { - url := "/view/" + strconv.FormatUint(uint64(torrent.ID), 10) - if user.ID > 0 && config.Conf.Users.DefaultUserSettings["new_torrent"] { // If we are a member and notifications for new torrents are enabled - userService.GetFollowers(user) // We populate the liked field for users - if len(user.Followers) > 0 { // If we are followed by at least someone - for _, follower := range user.Followers { - follower.ParseSettings() // We need to call it before checking settings - if follower.Settings.Get("new_torrent") { - T, _, _ := publicSettings.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, follower.Settings.Get("new_torrent_email")) - } - } - } - } - return nil -} - -// HideTorrentUser : hides a torrent user for hidden torrents -func HideTorrentUser(uploaderID uint, uploaderName string, torrentHidden bool) (uint, string) { - if torrentHidden { - return 0, "れんちょん" - } - if uploaderID == 0 { - return 0, uploaderName - } - return uploaderID, uploaderName -} diff --git a/models/torrents/update.go b/models/torrents/update.go deleted file mode 100644 index e5036a06..00000000 --- a/models/torrents/update.go +++ /dev/null @@ -1,48 +0,0 @@ -package torrents - -import ( - "errors" - "net/http" - - "github.com/NyaaPantsu/nyaa/util/log" - - "github.com/NyaaPantsu/nyaa/models" -) - -// Update : Update a torrent based on model -func Update(torrent *models.Torrent) (int, error) { - if models.ORM.Model(torrent).UpdateColumn(torrent).Error != nil { - return http.StatusInternalServerError, errors.New("Torrent was not updated") - } - - // TODO Don't create a new client for each request - if models.ElasticSearchClient != nil { - err := torrent.AddToESIndex(models.ElasticSearchClient) - if err == nil { - log.Infof("Successfully updated torrent to ES index.") - } else { - log.Errorf("Unable to update torrent to ES index: %s", err) - } - } - - return http.StatusOK, nil -} - -// UpdateUnscope : Update a torrent based on model -func UpdateUnscope(torrent *models.Torrent) (int, error) { - if models.ORM.Unscoped().Model(torrent).UpdateColumn(torrent).Error != nil { - return http.StatusInternalServerError, errors.New("Torrent was not updated") - } - - // TODO Don't create a new client for each request - if models.ElasticSearchClient != nil { - err := torrent.AddToESIndex(models.ElasticSearchClient) - if err == nil { - log.Infof("Successfully updated torrent to ES index.") - } else { - log.Errorf("Unable to update torrent to ES index: %s", err) - } - } - - return http.StatusOK, nil -} diff --git a/service/api/api.go b/service/api/api.go index 41150a82..10494d40 100644 --- a/service/api/api.go +++ b/service/api/api.go @@ -84,13 +84,6 @@ type TorrentsRequest struct { MaxPerPage int `json:"limit"` } -// Use this, because we seem to avoid using models, and we would need -// the torrent ID to create the File in the DB -type uploadedFile struct { - Path []string `json:"path"` - Filesize int64 `json:"filesize"` -} - // APIResultJSON for torrents in json for api type APIResultJSON struct { Torrents []TorrentJSON `json:"torrents"` @@ -98,35 +91,7 @@ type APIResultJSON struct { TotalRecordCount int `json:"totalRecordCount"` } -// TorrentRequest struct -// Same json name as the constant! -type TorrentRequest struct { - Name string `json:"name,omitempty"` - Magnet string `json:"magnet,omitempty"` - Category string `json:"c"` - Remake bool `json:"remake,omitempty"` - Description string `json:"desc,omitempty"` - Status int `json:"status,omitempty"` - Hidden bool `json:"hidden,omitempty"` - CaptchaID string `json:"-"` - WebsiteLink string `json:"website_link,omitempty"` - SubCategory int `json:"sub_category,omitempty"` - Language string `json:"language,omitempty"` - Infohash string `json:"hash,omitempty"` - CategoryID int `json:"-"` - SubCategoryID int `json:"-"` - Filesize int64 `json:"filesize,omitempty"` - Filepath string `json:"-"` - FileList []uploadedFile `json:"filelist,omitempty"` - Trackers []string `json:"trackers,omitempty"` -} - -// UpdateRequest struct -type UpdateRequest struct { - ID int `json:"id"` - Update TorrentRequest `json:"update"` -} // ToParams : Convert a torrentsrequest to searchparams func (r *TorrentsRequest) ToParams() serviceBase.WhereParams { diff --git a/util/validator/torrent/forms.go b/util/validator/torrent/forms.go index e69de29b..8121af19 100644 --- a/util/validator/torrent/forms.go +++ b/util/validator/torrent/forms.go @@ -0,0 +1,38 @@ +package torrentValidator + +// TorrentRequest struct +// Same json name as the constant! +type TorrentRequest struct { + Name string `json:"name,omitempty"` + Magnet string `json:"magnet,omitempty"` + Category string `json:"c"` + Remake bool `json:"remake,omitempty"` + Description string `json:"desc,omitempty"` + Status int `json:"status,omitempty"` + Hidden bool `json:"hidden,omitempty"` + CaptchaID string `json:"-"` + WebsiteLink string `json:"website_link,omitempty"` + SubCategory int `json:"sub_category,omitempty"` + Language string `json:"language,omitempty"` + + Infohash string `json:"hash,omitempty"` + CategoryID int `json:"-"` + SubCategoryID int `json:"-"` + Filesize int64 `json:"filesize,omitempty"` + Filepath string `json:"-"` + FileList []uploadedFile `json:"filelist,omitempty"` + Trackers []string `json:"trackers,omitempty"` +} + +// UpdateRequest struct +type UpdateRequest struct { + ID int `json:"id"` + Update TorrentRequest `json:"update"` +} + +// Use this, because we seem to avoid using models, and we would need +// the torrent ID to create the File in the DB +type uploadedFile struct { + Path []string `json:"path"` + Filesize int64 `json:"filesize"` +}