2017-05-06 10:36:37 +02:00
package router
import (
2017-05-07 06:26:09 +02:00
"fmt"
2017-05-06 10:36:37 +02:00
"net/http"
2017-05-07 15:55:34 +02:00
"os"
2017-05-07 06:26:09 +02:00
"strconv"
"time"
2017-05-06 19:01:15 +02:00
2017-05-07 11:08:44 +02:00
"github.com/ewhal/nyaa/db"
"github.com/ewhal/nyaa/model"
2017-05-07 10:25:09 +02:00
"github.com/ewhal/nyaa/service/captcha"
2017-05-06 19:01:15 +02:00
"github.com/gorilla/mux"
2017-05-06 10:36:37 +02:00
)
func UploadHandler ( w http . ResponseWriter , r * http . Request ) {
2017-05-06 13:43:24 +02:00
var err error
2017-05-06 10:36:37 +02:00
var uploadForm UploadForm
if r . Method == "POST" {
2017-05-06 13:43:24 +02:00
defer r . Body . Close ( )
2017-05-07 13:38:46 +02:00
// validation is done in ExtractInfo()
2017-05-06 13:43:24 +02:00
err = uploadForm . ExtractInfo ( r )
if err == nil {
2017-05-07 11:08:44 +02:00
if ! captcha . Authenticate ( uploadForm . Captcha ) {
// TODO: Prettier passing of mistyoed captcha errors
http . Error ( w , captcha . ErrInvalidCaptcha . Error ( ) , 403 )
2017-05-07 15:55:34 +02:00
if len ( uploadForm . Filepath ) > 0 {
os . Remove ( uploadForm . Filepath )
}
2017-05-07 11:08:44 +02:00
return
}
2017-05-06 13:43:24 +02:00
//add to db and redirect depending on result
2017-05-07 06:26:09 +02:00
torrent := model . Torrents {
Name : uploadForm . Name ,
Category : uploadForm . CategoryId ,
Sub_Category : uploadForm . SubCategoryId ,
Status : 1 ,
Hash : uploadForm . Infohash ,
Date : time . Now ( ) . Unix ( ) ,
2017-05-07 13:48:28 +02:00
Filesize : uploadForm . Filesize , // FIXME: should set to NULL instead of 0
2017-05-07 07:18:41 +02:00
Description : uploadForm . Description ,
2017-05-07 06:26:09 +02:00
Comments : [ ] byte { } }
db . ORM . Create ( & torrent )
fmt . Printf ( "%+v\n" , torrent )
url , err := Router . Get ( "view_torrent" ) . URL ( "id" , strconv . Itoa ( torrent . Id ) )
if err == nil {
http . Redirect ( w , r , url . String ( ) , 302 )
}
2017-05-06 10:36:37 +02:00
}
2017-05-06 13:43:24 +02:00
} else if r . Method == "GET" {
2017-05-07 14:55:46 +02:00
uploadForm . CaptchaID = captcha . GetID ( )
2017-05-07 01:20:13 +02:00
htv := UploadTemplateVariables { uploadForm , NewSearchForm ( ) , Navigation { } , r . URL , mux . CurrentRoute ( r ) }
2017-05-06 19:01:15 +02:00
err = uploadTemplate . ExecuteTemplate ( w , "index.html" , htv )
2017-05-06 13:43:24 +02:00
} else {
w . WriteHeader ( http . StatusMethodNotAllowed )
return
2017-05-06 10:36:37 +02:00
}
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
}
}