Albirew/nyaa-pantsu
Albirew
/
nyaa-pantsu
Archivé
1
0
Bifurcation 0
Cette révision appartient à :
akuma06 2017-05-21 19:38:39 +02:00
Parent 32c51a57cb
révision 5639033370
8 fichiers modifiés avec 133 ajouts et 131 suppressions

Voir le fichier

@ -1,13 +0,0 @@
package config
/*
* Here we config the notifications options
*/
var EnableNotifications = map[string]bool {
"new_torrent": true,
"new_comment_owner": true,
"new_comment_all": true,
"new_follower": false,
"followed": false,
}

22
config/user_settings.go Fichier normal
Voir le fichier

@ -0,0 +1,22 @@
package config
/*
* Here we config the notifications options
* Uses in user model for default setting
* Be aware, default values in user update form are
* 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": true,
"new_responses_email": false,
"new_follower": false,
"new_follower_email": false,
"followed": false,
"followed_email": false,
}

Voir le fichier

@ -35,7 +35,7 @@ type User struct {
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 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 {
@ -124,23 +124,32 @@ func (u *User) ToJSON() UserJSON {
/* User Settings */
func(s *UserSettings) Get(key string) interface{} {
func(s UserSettings) Get(key string) interface{} {
if (s.settings[key] != nil) {
return s.settings[key]
} else {
return config.DefaultUserSettings[key]
}
}
func (s *UserSettings) Set(key string, val interface{}) {
s.settings[key] = val
}
func (s *UserSettings) GetSettings() {
func (s UserSettings) GetSettings() {
return s.settings
}
func (u *User) SaveSettings() {
func (s UserSettings) Set(key string, val interface{}) {
s.settings[key] = val
}
func (s UserSettings) ToDefault() {
s.settings = config.DefaultUserSettings
}
func (u User) SaveSettings() {
u.UserSettings , _ = json.Marshal(u.Settings.GetSettings())
}
func (u *User) ParseSettings() {
if len(u.Settings.GetSettings()) == 0
json.Unmarshal([]byte(u.UserSettings), u.Settings)
func (u User) ParseSettings() {
if len(u.Settings.GetSettings()) == 0 && u.UserSettings != "" {
json.Unmarshal([]byte(u.UserSettings), u.Settings)
}
}

Voir le fichier

@ -251,15 +251,15 @@ func TorrentEditModPanel(w http.ResponseWriter, r *http.Request) {
func TorrentPostEditModPanel(w http.ResponseWriter, r *http.Request) {
var uploadForm UploadForm
id := r.URL.Query().Get("id")
err := form.NewErrors()
messages := msg.GetMessages(r)
infos := form.NewInfos()
torrent, _ := torrentService.GetTorrentById(id)
if torrent.ID > 0 {
errUp := uploadForm.ExtractEditInfo(r)
if errUp != nil {
err["errors"] = append(err["errors"], "Failed to update torrent!")
messages.AddError("errors", "Failed to update torrent!")
}
if len(err) == 0 {
if !messages.HasErrors() {
// update some (but not all!) values
torrent.Name = uploadForm.Name
torrent.Category = uploadForm.CategoryID
@ -269,10 +269,10 @@ func TorrentPostEditModPanel(w http.ResponseWriter, r *http.Request) {
torrent.Description = uploadForm.Description
torrent.Uploader = nil // GORM will create a new user otherwise (wtf?!)
db.ORM.Save(&torrent)
infos["infos"] = append(infos["infos"], "Torrent details updated.")
messages.AddInfo("infos", "Torrent details updated.")
}
}
htv := PanelTorrentEdVbs{NewPanelCommonVariables(r), uploadForm, err, infos}
htv := PanelTorrentEdVbs{NewPanelCommonVariables(r), uploadForm, messages.GetAllErrors(), messages.GetAllInfos()}
err_ := panelTorrentEd.ExecuteTemplate(w, "admin_index.html", htv)
log.CheckError(err_)
}
@ -280,7 +280,6 @@ func TorrentPostEditModPanel(w http.ResponseWriter, r *http.Request) {
func CommentDeleteModPanel(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
_ = form.NewErrors()
_, _ = userService.DeleteComment(id)
url, _ := Router.Get("mod_clist").URL()
http.Redirect(w, r, url.String()+"?deleted", http.StatusSeeOther)
@ -288,7 +287,6 @@ func CommentDeleteModPanel(w http.ResponseWriter, r *http.Request) {
func TorrentDeleteModPanel(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
_ = form.NewErrors()
_, _ = torrentService.DeleteTorrent(id)
//delete reports of torrent
@ -305,7 +303,6 @@ func TorrentReportDeleteModPanel(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
fmt.Println(id)
idNum, _ := strconv.ParseUint(id, 10, 64)
_ = form.NewErrors()
_, _ = reportService.DeleteTorrentReport(uint(idNum))
url, _ := Router.Get("mod_trlist").URL()
@ -320,22 +317,22 @@ func TorrentReassignModPanel(w http.ResponseWriter, r *http.Request) {
func TorrentPostReassignModPanel(w http.ResponseWriter, r *http.Request) {
var rForm ReassignForm
err := form.NewErrors()
messages := msg.GetMessages(r)
infos := form.NewInfos()
err2 := rForm.ExtractInfo(r)
if err2 != nil {
err["errors"] = append(err["errors"], err2.Error())
messages.ImportFromError("errors", err2)
} else {
count, err2 := rForm.ExecuteAction()
if err2 != nil {
err["errors"] = append(err["errors"], "Something went wrong")
messages.AddError("errors", "Something went wrong")
} else {
infos["infos"] = append(infos["infos"], fmt.Sprintf("%d torrents updated.", count))
messages.AddInfof("infos", "%d torrents updated.", count)
}
}
htv := PanelTorrentReassignVbs{NewPanelCommonVariables(r), rForm, err, infos}
htv := PanelTorrentReassignVbs{NewPanelCommonVariables(r), rForm, messages.GetAllErrors(), messages.GetAllInfos()}
err_ := panelTorrentReassign.ExecuteTemplate(w, "admin_index.html", htv)
log.CheckError(err_)
}

Voir le fichier

@ -79,7 +79,7 @@ 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.EnableNotifications["new_torrent"]) { // If we are a member and notifications for new torrents are enabled
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 {

Voir le fichier

@ -25,13 +25,14 @@ func UserRegisterFormHandler(w http.ResponseWriter, r *http.Request) {
HomeHandler(w, r)
return
}
messages := msg.GetMessages(r)
registrationForm := form.RegistrationForm{}
modelHelper.BindValueForm(&registrationForm, r)
registrationForm.CaptchaID = captcha.GetID()
urtv := UserRegisterTemplateVariables{
CommonTemplateVariables: NewCommonVariables(r),
RegistrationForm: registrationForm,
FormErrors: form.NewErrors(),
FormErrors: messages.GetAllErrors(),
}
err := viewRegisterTemplate.ExecuteTemplate(w, "index.html", urtv)
if err != nil {
@ -41,13 +42,20 @@ func UserRegisterFormHandler(w http.ResponseWriter, r *http.Request) {
// Getting View User Login
func UserLoginFormHandler(w http.ResponseWriter, r *http.Request) {
_, errorUser := userService.CurrentUser(r)
// User is already connected, redirect to home
if errorUser == nil {
HomeHandler(w, r)
return
}
loginForm := form.LoginForm{}
modelHelper.BindValueForm(&loginForm, r)
messages := msg.GetMessages(r)
ulfv := UserLoginFormVariables{
CommonTemplateVariables: NewCommonVariables(r),
LoginForm: loginForm,
FormErrors: form.NewErrors(),
FormErrors: messages.GetAllErrors(),
}
err := viewLoginTemplate.ExecuteTemplate(w, "index.html", ulfv)
@ -61,33 +69,33 @@ func UserProfileHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
T := languages.GetTfuncFromRequest(r)
messages := msg.GetMessages(r)
userProfile, _, errorUser := userService.RetrieveUserForAdmin(id)
if errorUser == nil {
currentUser := GetUser(r)
follow := r.URL.Query()["followed"]
unfollow := r.URL.Query()["unfollowed"]
infosForm := form.NewInfos()
deleteVar := r.URL.Query()["delete"]
if (deleteVar != nil) && (userPermission.CurrentOrAdmin(currentUser, userProfile.ID)) {
err := form.NewErrors()
_, errUser := userService.DeleteUser(w, currentUser, id)
if errUser != nil {
err["errors"] = append(err["errors"], errUser.Error())
messages.ImportFromError("errors", errUser)
}
htv := UserVerifyTemplateVariables{NewCommonVariables(r), err}
htv := UserVerifyTemplateVariables{NewCommonVariables(r), messages.GetAllErrors()}
errorTmpl := viewUserDeleteTemplate.ExecuteTemplate(w, "index.html", htv)
if errorTmpl != nil {
http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
}
} else {
if follow != nil {
infosForm["infos"] = append(infosForm["infos"], fmt.Sprintf(string(T("user_followed_msg")), userProfile.Username))
messages.AddInfof("infos", string(T("user_followed_msg")), userProfile.Username)
}
if unfollow != nil {
infosForm["infos"] = append(infosForm["infos"], fmt.Sprintf(string(T("user_unfollowed_msg")), userProfile.Username))
messages.AddInfof("infos", string(T("user_unfollowed_msg")), userProfile.Username)
}
htv := UserProfileVariables{NewCommonVariables(r), &userProfile, infosForm}
htv := UserProfileVariables{NewCommonVariables(r), &userProfile, messages.GetAllInfos()}
err := viewProfileTemplate.ExecuteTemplate(w, "index.html", htv)
if err != nil {
@ -95,10 +103,7 @@ func UserProfileHandler(w http.ResponseWriter, r *http.Request) {
}
}
} else {
err := notFoundTemplate.ExecuteTemplate(w, "index.html", NotFoundTemplateVariables{NewCommonVariables(r)})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
NotFoundHandler(w, r)
}
}
@ -107,23 +112,22 @@ func UserDetailsHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
currentUser := GetUser(r)
messages := msg.GetMessages(r)
userProfile, _, errorUser := userService.RetrieveUserForAdmin(id)
if errorUser == nil && userPermission.CurrentOrAdmin(currentUser, userProfile.ID) {
if userPermission.CurrentOrAdmin(currentUser, userProfile.ID) {
b := form.UserForm{}
modelHelper.BindValueForm(&b, r)
availableLanguages := languages.GetAvailableLanguages()
htv := UserProfileEditVariables{NewCommonVariables(r), &userProfile, b, form.NewErrors(), form.NewInfos(), availableLanguages}
htv := UserProfileEditVariables{NewCommonVariables(r), &userProfile, b, messages.GetAllErrors(), messages.GetAllInfos(), availableLanguages}
err := viewProfileEditTemplate.ExecuteTemplate(w, "index.html", htv)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
} else {
err := notFoundTemplate.ExecuteTemplate(w, "index.html", NotFoundTemplateVariables{NewCommonVariables(r)})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
NotFoundHandler(w, r)
}
}
@ -194,29 +198,30 @@ func UserProfileFormHandler(w http.ResponseWriter, r *http.Request) {
// Post Registration controller, we do some check on the form here, the rest on user service
func UserRegisterPostHandler(w http.ResponseWriter, r *http.Request) {
b := form.RegistrationForm{}
err := form.NewErrors()
messages = msg.GetMessages(r)
if !captcha.Authenticate(captcha.Extract(r)) {
err["errors"] = append(err["errors"], "Wrong captcha!")
messages.AddError("errors", "Wrong captcha!")
}
if len(err) == 0 {
if !messages.HasErrors() {
if len(r.PostFormValue("email")) > 0 {
_, err = form.EmailValidation(r.PostFormValue("email"), err)
form.EmailValidation(r.PostFormValue("email"), &messages)
}
_, err = form.ValidateUsername(r.PostFormValue("username"), err)
if len(err) == 0 {
form.ValidateUsername(r.PostFormValue("username"), &messages)
if !messages.HasErrors() {
modelHelper.BindValueForm(&b, r)
err = modelHelper.ValidateForm(&b, err)
if len(err) == 0 {
modelHelper.ValidateForm(&b, &messages)
if !messages.HasErrors() {
_, errorUser := userService.CreateUser(w, r)
if errorUser != nil {
err["errors"] = append(err["errors"], errorUser.Error())
messages.ImportFromError("errors", errorUser)
}
if len(err) == 0 {
if !messages.HasErrors() {
common := NewCommonVariables(r)
common.User = &model.User{
Email: r.PostFormValue("email"), // indicate whether user had email set
}
htv := UserRegisterTemplateVariables{common, b, err}
htv := UserRegisterTemplateVariables{common, b, messages.GetAllErrors()}
errorTmpl := viewRegisterSuccessTemplate.ExecuteTemplate(w, "index.html", htv)
if errorTmpl != nil {
http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
@ -225,25 +230,21 @@ func UserRegisterPostHandler(w http.ResponseWriter, r *http.Request) {
}
}
}
if len(err) > 0 {
b.CaptchaID = captcha.GetID()
htv := UserRegisterTemplateVariables{NewCommonVariables(r), b, err}
errorTmpl := viewRegisterTemplate.ExecuteTemplate(w, "index.html", htv)
if errorTmpl != nil {
http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
}
if messages.HasErrors() {
UserRegisterFormHandler(w, r)
}
}
func UserVerifyEmailHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
token := vars["token"]
err := form.NewErrors()
messages := msg.GetMessages(r)
_, errEmail := userService.EmailVerification(token, w)
if errEmail != nil {
err["errors"] = append(err["errors"], errEmail.Error())
messages.ImportFromError("errors", errEmail)
}
htv := UserVerifyTemplateVariables{NewCommonVariables(r), err}
htv := UserVerifyTemplateVariables{NewCommonVariables(r), messages.GetAllErrors()}
errorTmpl := viewVerifySuccessTemplate.ExecuteTemplate(w, "index.html", htv)
if errorTmpl != nil {
http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
@ -254,13 +255,14 @@ func UserVerifyEmailHandler(w http.ResponseWriter, r *http.Request) {
func UserLoginPostHandler(w http.ResponseWriter, r *http.Request) {
b := form.LoginForm{}
modelHelper.BindValueForm(&b, r)
err := form.NewErrors()
err = modelHelper.ValidateForm(&b, err)
if len(err) == 0 {
messages := msg.GetAllErrors()
modelHelper.ValidateForm(&b, &messages)
if !messages.HasErrors() {
_, errorUser := userService.CreateUserAuthentication(w, r)
if errorUser != nil {
err["errors"] = append(err["errors"], errorUser.Error())
htv := UserLoginFormVariables{NewCommonVariables(r), b, err}
messages.ImportFromError("errors", errorUser)
htv := UserLoginFormVariables{NewCommonVariables(r), b, messages.GetAllErrors()}
errorTmpl := viewLoginTemplate.ExecuteTemplate(w, "index.html", htv)
if errorTmpl != nil {
http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
@ -271,12 +273,8 @@ func UserLoginPostHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, url.String(), http.StatusSeeOther)
}
}
if len(err) > 0 {
htv := UserLoginFormVariables{NewCommonVariables(r), b, err}
errorTmpl := viewLoginTemplate.ExecuteTemplate(w, "index.html", htv)
if errorTmpl != nil {
http.Error(w, errorTmpl.Error(), http.StatusInternalServerError)
}
if messages.HasErrors() {
UserLoginFormHandler(w,r)
}
}

Voir le fichier

@ -56,72 +56,59 @@ func PostCommentHandler(w http.ResponseWriter, r *http.Request) {
id := vars["id"]
currentUser := GetUser(r)
messages := msg.GetMessages(r)
if userPermission.NeedsCaptcha(currentUser) {
userCaptcha := captcha.Extract(r)
if !captcha.Authenticate(userCaptcha) {
http.Error(w, "bad captcha", 403)
return
messages.AddError("errors", "Bad captcha!")
}
}
content := p.Sanitize(r.FormValue("comment"))
if strings.TrimSpace(content) == "" {
http.Error(w, "comment empty", 406)
return
messages.AddError("errors", "Comment empty!")
}
if !messages.HasErrors() {
idNum, err := strconv.Atoi(id)
idNum, err := strconv.Atoi(id)
userID := currentUser.ID
comment := model.Comment{TorrentID: uint(idNum), UserID: userID, Content: content, CreatedAt: time.Now()}
userID := currentUser.ID
comment := model.Comment{TorrentID: uint(idNum), UserID: userID, Content: content, CreatedAt: time.Now()}
err = db.ORM.Create(&comment).Error
if err != nil {
util.SendError(w, err, 500)
return
}
url, err := Router.Get("view_torrent").URL("id", id)
if err == nil {
http.Redirect(w, r, url.String(), 302)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
err = db.ORM.Create(&comment).Error
if err != nil {
messages.ImportFromError("errors", err)
}
}
ViewHandler(w,r)
}
func ReportTorrentHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
messages := msg.GetMessages(r)
currentUser := GetUser(r)
if userPermission.NeedsCaptcha(currentUser) {
userCaptcha := captcha.Extract(r)
if !captcha.Authenticate(userCaptcha) {
http.Error(w, "bad captcha", 403)
return
messages.AddError("errors", "Bad captcha!")
}
}
if !messages.HasErrors() {
idNum, err := strconv.Atoi(id)
userID := currentUser.ID
idNum, err := strconv.Atoi(id)
userID := currentUser.ID
report := model.TorrentReport{
Description: r.FormValue("report_type"),
TorrentID: uint(idNum),
UserID: userID,
CreatedAt: time.Now(),
}
report := model.TorrentReport{
Description: r.FormValue("report_type"),
TorrentID: uint(idNum),
UserID: userID,
CreatedAt: time.Now(),
}
err = db.ORM.Create(&report).Error
if err != nil {
util.SendError(w, err, 500)
return
}
url, err := Router.Get("view_torrent").URL("id", id)
if err == nil {
http.Redirect(w, r, url.String(), 302)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
err = db.ORM.Create(&report).Error
if err != nil {
messages.ImportFromError("errors", err)
}
}
ViewHandler(w,r)
}

Voir le fichier

@ -80,6 +80,8 @@ func CreateUserFromForm(registrationForm formStruct.RegistrationForm) (model.Use
}
user.Email = "" // unset email because it will be verified later
user.CreatedAt = time.Now()
// User settings to default
user.ToDefault()
// currently unused but needs to be set:
user.ApiToken = ""
user.ApiTokenExpiry = time.Unix(0, 0)