Albirew/nyaa-pantsu
Archivé
1
0
Bifurcation 0

Switch to new schema: make it compile

Cette révision appartient à :
sfan5 2017-05-08 19:26:29 +02:00
Parent e3a271cca7
révision a3d13f768a
13 fichiers modifiés avec 101 ajouts et 193 suppressions

Voir le fichier

@ -31,8 +31,8 @@ func GormInit(conf *config.Config) (*gorm.DB, error) {
if config.Environment == "DEVELOPMENT" {
db.LogMode(true)
// db.DropTable(&model.User{}, "UserFollower")
db.AutoMigrate(&model.Torrents{}, &model.UsersFollowers{}, &model.User{}, &model.Role{}, &model.Language{}, &model.Comment{})
// db.AutoMigrate(&model.Comment{})
db.AutoMigrate(&model.User{}, &model.UserFollows{})
db.AutoMigrate(&model.User{}, &model.Torrents{}, &model.Comment{}, &model.OldComment{})
// db.Model(&model.User{}).AddIndex("idx_user_token", "token")
}

Voir le fichier

@ -4,16 +4,28 @@ import (
"time"
)
// Comment is a comment model.
type Comment struct {
Id int `json:"id"`
Content string `json:"content"`
UserId int `json:"userId"`
Username string `json:"username"` // this is duplicate but it'll be faster rite?
TorrentId int
// LikingCount int `json:"likingCount"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt""`
User User `json:"user"`
Id uint `gorm:"column:comment_id;primary_key"`
TorrentId uint `gorm:"column:torrent_id"`
UserId uint `gorm:"column:user_id"`
Content string `gorm:"column:content"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
Torrent *Torrents `gorm:"ForeignKey:TorrentId"`
User *User `gorm:"ForeignKey:UserId"`
}
type OldComment struct {
TorrentId uint `gorm:"column:torrent_id"`
Username string `gorm:"column:username"`
Content string `gorm:"column:content"`
Date time.Time `gorm:"column:date"`
Torrent *Torrents `gorm:"ForeignKey:TorrentId"`
}
func (c OldComment) TableName() string {
// cba to renamed this in the db
return "comments_old"
}

Voir le fichier

@ -1,8 +0,0 @@
package model
// Role is a role model for user permission.
type Role struct {
Id uint `json:"id"`
Name string `json:"name",sql:"size:255"`
Description string `json:"description",sql:"size:255"`
}

Voir le fichier

@ -1,7 +0,0 @@
package model
//user status e.g. verified, filtered, etc
type Status struct {
Id int `json:"id"`
Name string `json:"name",sql:"size:255"`
}

Voir le fichier

@ -4,7 +4,7 @@ import (
"github.com/ewhal/nyaa/config"
"github.com/ewhal/nyaa/util"
"encoding/json"
// "encoding/json"
"html"
"html/template"
"strconv"
@ -21,18 +21,23 @@ type Feed struct {
}
type Torrents struct {
Id int `gorm:"column:torrent_id;primary_key"`
Id uint `gorm:"column:torrent_id;primary_key"`
Name string `gorm:"column:torrent_name"`
Category int `gorm:"column:category_id"`
Sub_Category int `gorm:"column:sub_category_id"`
Status int `gorm:"column:status_id"`
Hash string `gorm:"column:torrent_hash"`
Date int64 `gorm:"column:date"`
Category int `gorm:"column:category"`
Sub_Category int `gorm:"column:sub_category"`
Status int `gorm:"column:status"`
Date time.Time `gorm:"column:date"`
UploaderId uint `gorm:"column:uploader"`
Downloads int `gorm:"column:downloads"`
Stardom int `gorm:"column:stardom"`
Filesize int64 `gorm:"column:filesize"`
Description string `gorm:"column:description"`
OldComments []byte `gorm:"column:comments"`
Comments []Comment `gorm:"ForeignKey:TorrentId"`
WebsiteLink string `gorm:"column:website_link"`
Uploader *User `gorm:"ForeignKey:UploaderId"`
OldComments []OldComment `gorm:"ForeignKey:Id"`
Comments []Comment `gorm:"ForeignKey:Id"`
}
/* We need JSON Object instead because of Magnet URL that is not in the database but generated dynamically
@ -80,9 +85,9 @@ type TorrentsJson struct {
func (t *Torrents) ToJson() TorrentsJson {
magnet := util.InfoHashToMagnet(strings.TrimSpace(t.Hash), t.Name, config.Trackers...)
offset := 0
//offset := 0
var commentsJson []CommentsJson
if len(t.OldComments) != 0 {
/*if len(t.OldComments) != 0 {
b := []OldCommentsJson{}
err := json.Unmarshal([]byte(t.OldComments), &b)
if err == nil {
@ -100,13 +105,13 @@ func (t *Torrents) ToJson() TorrentsJson {
}
for i, comment := range t.Comments {
commentsJson[i+offset] = CommentsJson{Content: template.HTML(comment.Content), Username: comment.Username}
}
}*/
res := TorrentsJson{
Id: strconv.Itoa(t.Id),
Id: strconv.FormatUint(uint64(t.Id), 10),
Name: html.UnescapeString(t.Name),
Status: t.Status,
Hash: t.Hash,
Date: time.Unix(t.Date, 0).Format(time.RFC3339),
Date: t.Date.Format(time.RFC3339),
Filesize: util.FormatFilesize2(t.Filesize),
Description: template.HTML(t.Description),
Comments: commentsJson,

Voir le fichier

@ -7,78 +7,27 @@ import (
// omit is the bool type for omitting a field of struct.
type omit bool
// User is a user model
type User struct {
Id uint `json:"id"`
Email string `json:"email",sql:"size:255;unique"`
Password string `json:"password",sql:"size:255"`
Username string `json:"username",sql:"size:255;unique"`
Description string `json:"description",sql:"size:100"`
Token string `json:"token"`
TokenExpiration time.Time `json:"tokenExperiation"`
// email md5 for gravatar
Md5 string `json:"md5"`
// admin
Activation bool `json:"activation"`
PasswordResetToken string `json:"passwordResetToken"`
ActivationToken string `json:"activationToken"`
PasswordResetUntil time.Time `json:"passwordResetUntil"`
ActivateUntil time.Time `json:"activateUntil"`
ActivatedAt time.Time `json:"activatedAt"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `json:"deletedAt"`
LastLoginAt time.Time `json:"lastLoginAt"`
CurrentLoginAt time.Time `json:"currentLoginAt"`
LastLoginIp string `json:"lastLoginIp",sql:"size:100"`
CurrentLoginIp string `json:"currentLoginIp",sql:"size:100"`
// Liking
LikingCount int `json:"likingCount"`
LikedCount int `json:"likedCount"`
Likings []User `gorm:"foreignkey:userId;associationforeignkey:follower_id;many2many:users_followers;"`
Liked []User `gorm:"foreignkey:follower_id;associationforeignkey:userId;many2many:users_followers;"`
//Connections []Connection
Languages string
Roles []Role `gorm:"many2many:users_roles;"` // Many To Many, users_roles
Torrents []Torrents
Id uint `gorm:"column:user_id;primary_key"`
Username string `gorm:"column:username"`
Password string `gorm:"column:password"`
Email string `gorm:"column:email"`
Status int `gorm:"column:status"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
/*Api*/Token string `gorm:"column:api_token"`
//ApiTokenExpiry
TokenExpiration time.Time `gorm:"column:api_token_expiry"`
Language string `gorm:"column:language"`
}
// UsersFollowers is a relation table to relate users each other.
type UsersFollowers struct {
UserID uint `json:"user_id"`
FollowerID uint `json:"follower_id"`
}
// PublicUser is a public user model that contains only a few information for everyone.
type PublicUser struct {
*User
Email omit `json:"email,omitempty",sql:"size:255;unique"`
Password omit `json:"password,omitempty",sql:"size:255"`
Token omit `json:"token,omitempty"`
TokenExpiration omit `json:"tokenExperiation,omitempty"`
// admin
Activation omit `json:"activation,omitempty"`
PasswordResetToken omit `json:"passwordResetToken,omitempty"`
ActivationToken omit `json:"activationToken,omitempty"`
PasswordResetUntil omit `json:"passwordResetUntil,omitempty"`
ActivateUntil omit `json:"activateUntil,omitempty"`
ActivatedAt omit `json:"activatedAt,omitempty"`
UpdatedAt omit `json:"updatedAt,omitempty"`
DeletedAt omit `json:"deletedAt,omitempty"`
LastLoginAt omit `json:"lastLoginAt,omitempty"`
CurrentLoginAt omit `json:"currentLoginAt,omitempty"`
LastLoginIp omit `json:"lastLoginIp,omitempty",sql:"size:100"`
CurrentLoginIp omit `json:"currentLoginIp,omitempty",sql:"size:100"`
//Connections omit `json:"connections,omitempty"`
Languages omit `json:"languages,omitempty"`
Roles omit `json:"roles,omitempty"`
Torrents omit `json:"articles,omitempty"` //should user torrents not be displayed?
User *User
}
type UserFollows struct {
User User `gorm:"ForeignKey:user_id"`
Following User `gorm:"ForeignKey:following"`
}

Voir le fichier

@ -100,7 +100,7 @@ func ApiUploadHandler(w http.ResponseWriter, r *http.Request) {
Sub_Category: sub_category,
Status: 1,
Hash: b.Hash,
Date: time.Now().Unix(),
Date: time.Now(),
Filesize: 0,
Description: string(b.Description)}
db.ORM.Create(&torrent)

Voir le fichier

@ -15,7 +15,7 @@ func RssHandler(w http.ResponseWriter, r *http.Request) {
created_as_time := time.Now()
if len(torrents) > 0 {
created_as_time = time.Unix(torrents[0].Date, 0)
created_as_time = torrents[0].Date
}
feed := &feeds.Feed{
Title: "Nyaa Pantsu",
@ -26,16 +26,15 @@ func RssHandler(w http.ResponseWriter, r *http.Request) {
feed.Items = make([]*feeds.Item, len(torrents))
for i, _ := range torrents {
timestamp_as_time := time.Unix(torrents[0].Date, 0)
torrent_json := torrents[i].ToJson()
feed.Items[i] = &feeds.Item{
// need a torrent view first
Id: "https://nyaa.pantsu.cat/view/" + strconv.Itoa(torrents[i].Id),
Id: "https://" + config.WebAddress + "/view/" + strconv.FormatUint(uint64(torrents[i].Id), 10),
Title: torrents[i].Name,
Link: &feeds.Link{Href: string(torrent_json.Magnet)},
Description: "",
Created: timestamp_as_time,
Updated: timestamp_as_time,
Created: torrents[0].Date,
Updated: torrents[0].Date,
}
}

Voir le fichier

@ -33,12 +33,12 @@ func UploadHandler(w http.ResponseWriter, r *http.Request) {
Sub_Category: uploadForm.SubCategoryId,
Status: 1,
Hash: uploadForm.Infohash,
Date: time.Now().Unix(),
Date: time.Now(),
Filesize: uploadForm.Filesize, // FIXME: should set to NULL instead of 0
Description: uploadForm.Description}
db.ORM.Create(&torrent)
fmt.Printf("%+v\n", torrent)
url, err := Router.Get("view_torrent").URL("id", strconv.Itoa(torrent.Id))
url, err := Router.Get("view_torrent").URL("id", strconv.FormatUint(uint64(torrent.Id), 10))
if err == nil {
http.Redirect(w, r, url.String(), 302)
}

Voir le fichier

@ -3,6 +3,7 @@ package router
import (
"net/http"
"strconv"
"time"
"github.com/ewhal/nyaa/db"
"github.com/ewhal/nyaa/model"
@ -41,14 +42,13 @@ func PostCommentHandler(w http.ResponseWriter, r *http.Request) {
currentUser := GetUser(r)
content := p.Sanitize(r.FormValue("comment"))
idNum, err := strconv.Atoi(id)
username := "れんちょん"
userId := 0
idNum_, err := strconv.Atoi(id)
var idNum uint = uint(idNum_)
var userId uint = 0
if (currentUser.Id > 0) {
username = currentUser.Username
userId = int(currentUser.Id)
userId = currentUser.Id
}
comment := model.Comment{Username: username, UserId: userId, Content: content, TorrentId: idNum}
comment := model.Comment{TorrentId: idNum, UserId: userId, Content: content, CreatedAt: time.Now()}
db.ORM.Create(&comment)
url, err := Router.Get("view_torrent").URL("id", id)

Voir le fichier

@ -150,6 +150,6 @@ func CurrentUser(r *http.Request) (model.User, error) {
if db.ORM.Select(config.UserPublicFields+", email").Where("token = ?", token).First(&user).RecordNotFound() {
return user, errors.New("User is not found.")
}
db.ORM.Model(&user).Association("Roles").Find(&user.Roles)
db.ORM.Model(&user)
return user, nil
}

Voir le fichier

@ -4,6 +4,7 @@ import (
"errors"
"net/http"
"strconv"
"time"
"golang.org/x/crypto/bcrypt"
@ -56,7 +57,6 @@ func CreateUserFromForm(registrationForm formStruct.RegistrationForm) (model.Use
var user model.User
log.Debugf("registrationForm %+v\n", registrationForm)
modelHelper.AssignValue(&user, &registrationForm)
user.Md5 = crypto.GenerateMD5Hash(user.Email) // Gravatar
token, err := crypto.GenerateRandomToken32()
if err != nil {
return user, errors.New("Token not generated.")
@ -101,7 +101,7 @@ func CreateUser(w http.ResponseWriter, r *http.Request) (int, error) {
// RetrieveUser retrieves a user.
func RetrieveUser(r *http.Request, id string) (*model.PublicUser, bool, uint, int, error) {
var user model.User
/*var user model.User
var currentUserId uint
var isAuthor bool
// var publicUser *model.PublicUser
@ -139,7 +139,8 @@ func RetrieveUser(r *http.Request, id string) (*model.PublicUser, bool, uint, in
log.Debugf("user liking %v\n", user.Likings)
log.Debugf("user liked %v\n", user.Liked)
return &model.PublicUser{User: &user}, isAuthor, currentUserId, http.StatusOK, nil
return &model.PublicUser{User: &user}, isAuthor, currentUserId, http.StatusOK, nil*/
return nil, false, 0, 0, errors.New("NotImpl")
}
// RetrieveUsers retrieves users.
@ -155,7 +156,6 @@ func RetrieveUsers() []*model.PublicUser {
// UpdateUserCore updates a user. (Applying the modifed data of user).
func UpdateUserCore(user *model.User) (int, error) {
user.Md5 = crypto.GenerateMD5Hash(user.Email)
token, err := crypto.GenerateRandomToken32()
if err != nil {
return http.StatusInternalServerError, errors.New("Token not generated.")
@ -165,6 +165,7 @@ func UpdateUserCore(user *model.User) (int, error) {
if db.ORM.Save(user).Error != nil {
return http.StatusInternalServerError, errors.New("User is not updated.")
}
user.UpdatedAt = time.Now()
return http.StatusOK, nil
}
@ -220,49 +221,6 @@ func DeleteUser(w http.ResponseWriter, id string) (int, error) {
return status, err
}
// AddRoleToUser adds a role to a user.
func AddRoleToUser(r *http.Request) (int, error) {
var form formStruct.UserRoleForm
var user model.User
var role model.Role
var roles []model.Role
modelHelper.BindValueForm(&form, r)
if db.ORM.First(&user, form.UserId).RecordNotFound() {
return http.StatusNotFound, errors.New("User is not found.")
}
if db.ORM.First(&role, form.RoleId).RecordNotFound() {
return http.StatusNotFound, errors.New("Role is not found.")
}
log.Debugf("user email : %s", user.Email)
log.Debugf("Role name : %s", role.Name)
db.ORM.Model(&user).Association("Roles").Append(role)
db.ORM.Model(&user).Association("Roles").Find(&roles)
if db.ORM.Save(&user).Error != nil {
return http.StatusInternalServerError, errors.New("Role not appended to user.")
}
return http.StatusOK, nil
}
// RemoveRoleFromUser removes a role from a user.
func RemoveRoleFromUser(w http.ResponseWriter, r *http.Request, userId string, roleId string) (int, error) {
var user model.User
var role model.Role
if db.ORM.First(&user, userId).RecordNotFound() {
return http.StatusNotFound, errors.New("User is not found.")
}
if db.ORM.First(&role, roleId).RecordNotFound() {
return http.StatusNotFound, errors.New("Role is not found.")
}
log.Debugf("user : %v\n", user)
log.Debugf("role : %v\n", role)
if db.ORM.Model(&user).Association("Roles").Delete(role).Error != nil {
return http.StatusInternalServerError, errors.New("Role is not deleted from user.")
}
return http.StatusOK, nil
}
// RetrieveCurrentUser retrieves a current user.
func RetrieveCurrentUser(r *http.Request) (model.User, int, error) {
user, err := CurrentUser(r)
@ -307,8 +265,7 @@ func RetrieveUserForAdmin(id string) (model.User, int, error) {
if db.ORM.First(&user, id).RecordNotFound() {
return user, http.StatusNotFound, errors.New("User is not found.")
}
db.ORM.Model(&user).Association("Languages").Find(&user.Languages)
db.ORM.Model(&user).Association("Roles").Find(&user.Roles)
db.ORM.Model(&user)
return user, http.StatusOK, nil
}
@ -318,8 +275,7 @@ func RetrieveUsersForAdmin() []model.User {
var userArr []model.User
db.ORM.Find(&users)
for _, user := range users {
db.ORM.Model(&user).Association("Languages").Find(&user.Languages)
db.ORM.Model(&user).Association("Roles").Find(&user.Roles)
db.ORM.Model(&user)
userArr = append(userArr, user)
}
return userArr
@ -328,7 +284,7 @@ func RetrieveUsersForAdmin() []model.User {
// ActivateUser toggle activation of a user.
func ActivateUser(r *http.Request, id string) (model.User, int, error) {
var user model.User
var form formStruct.ActivateForm
/*var form formStruct.ActivateForm
modelHelper.BindValueForm(&form, r)
if db.ORM.First(&user, id).RecordNotFound() {
return user, http.StatusNotFound, errors.New("User is not found.")
@ -337,7 +293,8 @@ func ActivateUser(r *http.Request, id string) (model.User, int, error) {
if db.ORM.Save(&user).Error != nil {
return user, http.StatusInternalServerError, errors.New("User not activated.")
}
return user, http.StatusOK, nil
return user, http.StatusOK, nil*/
return user, 0, errors.New("NotImpl")
}
// CreateUserAuthentication creates user authentication.

Voir le fichier

@ -3,15 +3,15 @@ package userService
import (
"errors"
"net/http"
"time"
// "time"
"github.com/ewhal/nyaa/config"
"github.com/ewhal/nyaa/db"
"github.com/ewhal/nyaa/model"
"github.com/ewhal/nyaa/util/crypto"
// "github.com/ewhal/nyaa/util/crypto"
"github.com/ewhal/nyaa/util/email"
"github.com/ewhal/nyaa/util/log"
"github.com/ewhal/nyaa/util/timeHelper"
// "github.com/ewhal/nyaa/util/log"
// "github.com/ewhal/nyaa/util/timeHelper"
"github.com/nicksnyder/go-i18n/i18n"
)
@ -28,7 +28,7 @@ func SendEmailVerfication(to string, token string, locale string) error {
// SendVerificationToUser sends an email verification token to user.
func SendVerificationToUser(user model.User) (int, error) {
var status int
/*var status int
var err error
user.ActivateUntil = timeHelper.TwentyFourHoursLater()
user.ActivationToken, err = crypto.GenerateRandomToken32()
@ -45,12 +45,12 @@ func SendVerificationToUser(user model.User) (int, error) {
if err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, err
return http.StatusOK, err*/
return 0, errors.New("NotImpl")
}
// SendVerification sends an email verification token.
func SendVerification(r *http.Request) (int, error) {
var user model.User
currentUser, err := CurrentUser(r)
if err != nil {
@ -65,7 +65,7 @@ func SendVerification(r *http.Request) (int, error) {
// EmailVerification verifies an email of user.
func EmailVerification(token string,w http.ResponseWriter) (int, error) {
var user model.User
/*var user model.User
log.Debugf("verifyEmailForm.ActivationToken : %s", token)
if db.ORM.Where(&model.User{ActivationToken: token}).First(&user).RecordNotFound() {
return http.StatusNotFound, errors.New("User is not found.")
@ -85,5 +85,6 @@ func EmailVerification(token string,w http.ResponseWriter) (int, error) {
return status, err
}
status, err = SetCookie(w, user.Token)
return status, err
return status, err*/
return 0, errors.New("NotImpl")
}