summaryrefslogtreecommitdiffstats
path: root/router/modpanel.go
blob: 8a4b1668d366528a2a1d44d4de42a6af7b93f57f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package router

import (
	"fmt"
	"html"
	"net/http"
	"strconv"
	"strings"

	"github.com/NyaaPantsu/nyaa/config"
	"github.com/NyaaPantsu/nyaa/db"
	"github.com/NyaaPantsu/nyaa/model"
	"github.com/NyaaPantsu/nyaa/service"
	"github.com/NyaaPantsu/nyaa/service/comment"
	"github.com/NyaaPantsu/nyaa/service/report"
	"github.com/NyaaPantsu/nyaa/service/torrent"
	"github.com/NyaaPantsu/nyaa/service/user"
	"github.com/NyaaPantsu/nyaa/service/user/permission"
	"github.com/NyaaPantsu/nyaa/util/log"
	msg "github.com/NyaaPantsu/nyaa/util/messages"
	"github.com/NyaaPantsu/nyaa/util/search"
	"github.com/gorilla/mux"
)

type ReassignForm struct {
	AssignTo uint
	By       string
	Data     string

	Torrents []uint
}

func (f *ReassignForm) ExtractInfo(r *http.Request) error {
	f.By = r.FormValue("by")
	if f.By != "olduser" && f.By != "torrentid" {
		return fmt.Errorf("what?")
	}

	f.Data = strings.Trim(r.FormValue("data"), " \r\n")
	if f.By == "olduser" {
		if f.Data == "" {
			return fmt.Errorf("No username given")
		} else if strings.Contains(f.Data, "\n") {
			return fmt.Errorf("More than one username given")
		}
	} else if f.By == "torrentid" {
		if f.Data == "" {
			return fmt.Errorf("No IDs given")
		}
		splitData := strings.Split(f.Data, "\n")
		for i, tmp := range splitData {
			tmp = strings.Trim(tmp, " \r")
			torrent_id, err := strconv.ParseUint(tmp, 10, 0)
			if err != nil {
				return fmt.Errorf("Couldn't parse number on line %d", i+1)
			}
			f.Torrents = append(f.Torrents, uint(torrent_id))
		}
	}

	tmp := r.FormValue("to")
	parsed, err := strconv.ParseUint(tmp, 10, 0)
	if err != nil {
		return err
	}
	f.AssignTo = uint(parsed)
	_, _, _, _, err = userService.RetrieveUser(r, tmp)
	if err != nil {
		return fmt.Errorf("User to assign to doesn't exist")
	}

	return nil
}

func (f *ReassignForm) ExecuteAction() (int, error) {
	var toBeChanged []uint
	var err error
	if f.By == "olduser" {
		toBeChanged, err = userService.RetrieveOldUploadsByUsername(f.Data)
		if err != nil {
			return 0, err
		}
	} else if f.By == "torrentid" {
		toBeChanged = f.Torrents
	}

	num := 0
	for _, torrent_id := range toBeChanged {
		torrent, err2 := torrentService.GetRawTorrentById(torrent_id)
		if err2 == nil {
			torrent.UploaderID = f.AssignTo
			db.ORM.Save(&torrent)
			num += 1
		}
	}
	return num, nil
}

// Helper that creates a search form without items/page field
// these need to be used when the templateVariables don't include `Navigation`
func NewPanelSearchForm() SearchForm {
	form := NewSearchForm()
	form.ShowItemsPerPage = false
	return form
}

func NewPanelCommonVariables(r *http.Request) CommonTemplateVariables {
	common := NewCommonVariables(r)
	common.Search = NewPanelSearchForm()
	return common
}

func IndexModPanel(w http.ResponseWriter, r *http.Request) {
	offset := 10

	torrents, _, _ := torrentService.GetAllTorrents(offset, 0)
	users, _ := userService.RetrieveUsersForAdmin(offset, 0)
	comments, _ := commentService.GetAllComments(offset, 0, "", "")
	torrentReports, _, _ := reportService.GetAllTorrentReports(offset, 0)

	htv := PanelIndexVbs{NewPanelCommonVariables(r), torrents, model.TorrentReportsToJSON(torrentReports), users, comments}
	err := panelIndex.ExecuteTemplate(w, "admin_index.html", htv)
	log.CheckError(err)
}

func TorrentsListPanel(w http.ResponseWriter, r *http.Request) {
	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
			}
		}

		searchParam, torrents, count, err := search.SearchByQueryWithUser(r, pagenum)
		searchForm := SearchForm{
			SearchParam:      searchParam,
			Category:         searchParam.Category.String(),
			ShowItemsPerPage: true,
		}

	messages := msg.GetMessages(r)
	common := NewCommonVariables(r)
	common.Navigation = Navigation{ count, int(searchParam.Max), pagenum, "mod_tlist_page"}
	common.Search = searchForm
	ptlv := PanelTorrentListVbs{common, torrents, messages.GetAllErrors(), messages.GetAllInfos()}
	err = panelTorrentList.ExecuteTemplate(w, "admin_index.html", ptlv)
	log.CheckError(err)
}

func TorrentReportListPanel(w http.ResponseWriter, r *http.Request) {
	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)

	reportJSON := model.TorrentReportsToJSON(torrentReports)
	common := NewCommonVariables(r)
	common.Navigation = Navigation{nbReports, offset, pagenum, "mod_trlist_page"}
	ptrlv := PanelTorrentReportListVbs{common, reportJSON}
	err = panelTorrentReportList.ExecuteTemplate(w, "admin_index.html", ptrlv)
	log.CheckError(err)
}

func UsersListPanel(w http.ResponseWriter, r *http.Request) {
	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

	users, nbUsers := userService.RetrieveUsersForAdmin(offset, (pagenum-1)*offset)
	common := NewCommonVariables(r)
	common.Navigation = Navigation{nbUsers, offset, pagenum, "mod_ulist_page"}
	htv := PanelUserListVbs{common, users}
	err = panelUserList.ExecuteTemplate(w, "admin_index.html", htv)
	log.CheckError(err)
}

func CommentsListPanel(w http.ResponseWriter, r *http.Request) {
	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
	userid := r.URL.Query().Get("userid")
	var conditions string
	var values []interface{}
	if userid != "" {
		conditions = "user_id = ?"
		values = append(values, userid)
	}

	comments, nbComments := commentService.GetAllComments(offset, (pagenum-1)*offset, conditions, values...)
	common := NewCommonVariables(r)
	common.Navigation = Navigation{nbComments, offset, pagenum, "mod_clist_page"}
	htv := PanelCommentListVbs{common, comments}
	err = panelCommentList.ExecuteTemplate(w, "admin_index.html", htv)
	log.CheckError(err)
}

func TorrentEditModPanel(w http.ResponseWriter, r *http.Request) {
	id := r.URL.Query().Get("id")
	torrent, _ := torrentService.GetTorrentById(id)
	messages:= msg.GetMessages(r)

	torrentJson := torrent.ToJSON()
	uploadForm := NewUploadForm()
	uploadForm.Name = torrentJson.Name
	uploadForm.Category = torrentJson.Category + "_" + torrentJson.SubCategory
	uploadForm.Status = torrentJson.Status
	uploadForm.WebsiteLink = string(torrentJson.WebsiteLink)
	uploadForm.Description = string(torrentJson.Description)
	htv := PanelTorrentEdVbs{NewPanelCommonVariables(r), uploadForm, messages.GetAllErrors(), messages.GetAllInfos()}
	err := panelTorrentEd.ExecuteTemplate(w, "admin_index.html", htv)
	log.CheckError(err)
}

func TorrentPostEditModPanel(w http.ResponseWriter, r *http.Request) {
	var uploadForm UploadForm
	id := r.URL.Query().Get("id")
	messages := msg.GetMessages(r)
	torrent, _ := torrentService.GetTorrentById(id)
	if torrent.ID > 0 {
		errUp := uploadForm.ExtractEditInfo(r)
		if errUp != nil {
			messages.AddError("errors", "Failed to update torrent!")
		}
		if !messages.HasErrors() {
			// update some (but not all!) values
			torrent.Name = uploadForm.Name
			torrent.Category = uploadForm.CategoryID
			torrent.SubCategory = uploadForm.SubCategoryID
			torrent.Status = uploadForm.Status
			torrent.WebsiteLink = uploadForm.WebsiteLink
			torrent.Description = uploadForm.Description
			torrent.Uploader = nil // GORM will create a new user otherwise (wtf?!)
			db.ORM.Save(&torrent)
			messages.AddInfo("infos", "Torrent details updated.")
		}
	}
	htv := PanelTorrentEdVbs{NewPanelCommonVariables(r), uploadForm, messages.GetAllErrors(), messages.GetAllInfos()}
	err_ := panelTorrentEd.ExecuteTemplate(w, "admin_index.html", htv)
	log.CheckError(err_)
}

func CommentDeleteModPanel(w http.ResponseWriter, r *http.Request) {
	id := r.URL.Query().Get("id")

	_, _ = userService.DeleteComment(id)
	url, _ := Router.Get("mod_clist").URL()
	http.Redirect(w, r, url.String()+"?deleted", http.StatusSeeOther)
}

func TorrentDeleteModPanel(w http.ResponseWriter, r *http.Request) {
	id := r.URL.Query().Get("id")
	_, _ = torrentService.DeleteTorrent(id)

	//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("mod_tlist").URL()
	http.Redirect(w, r, url.String()+"?deleted", http.StatusSeeOther)
}

func TorrentReportDeleteModPanel(w http.ResponseWriter, r *http.Request) {
	id := r.URL.Query().Get("id")
	fmt.Println(id)
	idNum, _ := strconv.ParseUint(id, 10, 64)
	_, _ = reportService.DeleteTorrentReport(uint(idNum))

	url, _ := Router.Get("mod_trlist").URL()
	http.Redirect(w, r, url.String()+"?deleted", http.StatusSeeOther)
}

func TorrentReassignModPanel(w http.ResponseWriter, r *http.Request) {
	messages := msg.GetMessages(r)
	htv := PanelTorrentReassignVbs{NewPanelCommonVariables(r), ReassignForm{}, messages.GetAllErrors(), messages.GetAllInfos()}
	err := panelTorrentReassign.ExecuteTemplate(w, "admin_index.html", htv)
	log.CheckError(err)
}

func TorrentPostReassignModPanel(w http.ResponseWriter, r *http.Request) {
	var rForm ReassignForm
	messages := msg.GetMessages(r)

	err2 := rForm.ExtractInfo(r)
	if err2 != nil {
		messages.ImportFromError("errors", err2)
	} else {
		count, err2 := rForm.ExecuteAction()
		if err2 != nil {
			messages.AddError("errors", "Something went wrong")
		} else {
			messages.AddInfof("infos", "%d torrents updated.", count)
		}
	}

	htv := PanelTorrentReassignVbs{NewPanelCommonVariables(r), rForm, messages.GetAllErrors(), messages.GetAllInfos()}
	err_ := panelTorrentReassign.ExecuteTemplate(w, "admin_index.html", htv)
	log.CheckError(err_)
}

func TorrentsPostListPanel(w http.ResponseWriter, r *http.Request) {
	torrentManyAction(r)
	TorrentsListPanel(w, r)
}



/*
 * Controller to modify multiple torrents and can be used by the owner of the torrent or admin
 */

func torrentManyAction(r *http.Request) {
	currentUser := GetUser(r)
	r.ParseForm()
	torrentsSelected := r.Form["torrent_id"] // should be []string
	action := r.FormValue("action")
	moveTo, _ := strconv.Atoi(r.FormValue("moveto"))
	messages := msg.GetMessages(r) // new util for errors and infos

	if action == "" {
		messages.AddError("errors", "You have to tell what you want to do with your selection!")
	}
	if action == "move" && r.FormValue("moveto") == "" { // We need to check the form value, not the int one because hidden is 0
		messages.AddError("errors", "Thou has't to telleth whither thee wanteth to moveth thy selection!")
	}
	if len(torrentsSelected) == 0 {
		messages.AddError("errors", "You need to select at least 1 element!")
	}
	if !messages.HasErrors() {
		for _, torrent_id := range torrentsSelected {
			torrent, _ := torrentService.GetTorrentById(torrent_id)
			if torrent.ID > 0 && userPermission.CurrentOrAdmin(currentUser, torrent.UploaderID) {
				switch action {
				case "move":
					if config.TorrentStatus[moveTo] {
						torrent.Status = moveTo
						db.ORM.Save(&torrent)
						messages.AddInfof("infos", "Torrent %s moved!", torrent.Name)
					} else { 
						messages.AddErrorf("errors", "No such status %d exist!", moveTo)
					}
				case "delete":
					_, err := torrentService.DeleteTorrent(torrent_id)
					if err != nil {
						messages.ImportFromError("errors", err)
					} else {
						messages.AddInfof("infos", "Torrent %s deleted!", torrent.Name)
					}
				default:
					messages.AddErrorf("errors", "No such action %s exist!", action)
				}
			} else {
				messages.AddErrorf("errors", "Torrent with ID %s doesn't exist!", torrent_id)
			} 
		}
	}
}