package main
import (
"fmt"
"html/template"
"net/http"
"strconv"
"strings"
"github.com/gorilla/mux"
)
// Struct for torrent entry in 'New torrents' list
type Entry struct {
Num int
Link string
}
type NewsItem struct {
NewsText template.HTML
Author string
Time string
}
// indexHandler handels index page
func indexHandler(w http.ResponseWriter, r *http.Request) {
data := struct {
User string
Password string
Title string
Items []string
Entrys []Entry
News []NewsItem
}{
User: "",
Title: "My page",
Items: []string{
"My photos",
"My blog",
"More",
},
}
session, _ := sessionsStore.Get(r, "session")
untyped, ok := session.Values["username"]
if ok {
username, ok1 := untyped.(string)
if ok1 {
data.User = username
}
}
untyped, ok2 := session.Values["password"]
if ok2 {
password, ok3 := untyped.(string)
if ok3 {
data.Password = password
}
}
// fmt.Println(data.User)
// fmt.Println(data.Password)
// tindexTemplate, err := template.New("").ParseFiles(INDEX_TEMPLATE, "ui\\templates\\placeholder.html")
tindexTemplate, err := template.New("").ParseFiles(NewIndexTemplate, TorrentEntry, TorrentList, NewsList, NewsEntry)
if err != nil {
fmt.Println("Error in templates loading")
fmt.Println(err)
w.Write([]byte("Internal server error"))
return
}
data.Entrys = append(data.Entrys, Entry{Num: 54, Link: "/files/torrents/2torrent.torrent"})
data.Entrys = append(data.Entrys, Entry{Num: 10, Link: "/files/torrents/1torrent.torrent"})
data.Entrys = append(data.Entrys, Entry{Num: 23, Link: "/files/torrents/3torrent.torrent"})
data.Entrys = append(data.Entrys, Entry{Num: 82, Link: "/files/torrents/4torrent.torrent"})
data.Entrys = append(data.Entrys, Entry{Num: 12, Link: "/files/torrents/5torrent.torrent"})
data.Entrys = append(data.Entrys, Entry{Num: 98, Link: "/files/torrents/6torrent.torrent"})
data.Entrys = append(data.Entrys, Entry{Num: 18, Link: "/files/torrents/7torrent.torrent"})
data.Entrys = append(data.Entrys, Entry{Num: 35, Link: "/files/torrents/8torrent.torrent"})
data.Entrys = append(data.Entrys, Entry{Num: 4, Link: "/files/torrents/9torrent.torrent"})
news, _, err := dBConnector.GetLastNews(3)
if err != nil {
fmt.Println(err)
}
if err == nil {
data.News = append(data.News, news...)
}
// LastTorrents, err := dBConnector.SelectTorrents(10)
// if err != nil {
// fmt.Println(err)
// }
// for _, torrent := LastTorrents {
// torrentTopic, err := dBConnector.GetTorrentTopic(torrent.Hash)
// if err != nil {
// fmt.Println(err)
// continue
// }
// torrentEntry := Entry{
// Title: torrentTopic.Title,
// Desc: torrentTopic.Desc,
// TopicLink: torrentTopic.Link,
// Endorsments: torrent.Endors,
// TorrentLink: GenTorrentLink(torrent.Hash),
// }
// data.Entrys = append(data.Entrys, torrentEntry)
// }
err = tindexTemplate.ExecuteTemplate(w, "newindex", data)
if err != nil {
fmt.Println(err)
w.Write([]byte("Internal server error"))
}
}
func indexPostHandler(w http.ResponseWriter, r *http.Request) {
fmt.Print("POST")
}
func logInGetHandler(w http.ResponseWriter, r *http.Request) {
data := struct {
Username string
Password string
Error string
}{
Username: "",
Password: "",
Error: "",
}
logInTemplate.Execute(w, data)
}
func logInPostHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username := r.PostForm.Get("username")
password := r.PostForm.Get("password")
fmt.Printf("Post from website! r.PostFrom = %v\n", r.PostForm)
if dBConnector.LogIn(username, password) {
session, _ := sessionsStore.Get(r, "session")
session.Values["username"] = username
session.Values["password"] = password
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
} else {
data := struct {
Username string
Password string
Error string
}{
Username: username,
Password: password,
Error: "Неверный логин либо пароль",
}
fmt.Printf("Login error")
logInTemplate.Execute(w, data)
// w.Write([]byte("Login error"))
}
}
func logOutGetHandler(w http.ResponseWriter, r *http.Request) {
session, _ := sessionsStore.Get(r, "session")
session.Options.MaxAge = -1
session.Save(r, w)
untyped, ok := session.Values["username"]
if ok {
username, ok1 := untyped.(string)
if ok1 {
logger.Printf("User %s loged out", username)
}
}
http.Redirect(w, r, "/", http.StatusFound)
}
func signInGetHandler(w http.ResponseWriter, r *http.Request) {
signInTemplate.Execute(w, nil)
}
func signInPostHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username := r.PostForm.Get("username")
password := r.PostForm.Get("password")
passwordRepeat := r.PostForm.Get("password-repeat")
data := struct {
Username string
Password string
PasswordRepeat string
Error string
}{
Username: username,
Password: password,
PasswordRepeat: passwordRepeat,
Error: "",
}
if dBConnector.IsNameUsed(username) {
data.Error = "Имя пользователя занято"
} else {
if password != passwordRepeat {
data.Error = "Введенные пароли не совпадают"
} else {
if dBConnector.SigInUser(username, password) {
session, _ := sessionsStore.Get(r, "session")
session.Values["username"] = username
session.Values["password"] = password
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
} else {
data.Error = "Произошла внутреняя ошибка при регистрации нового пользователя"
}
}
}
signInTemplate.Execute(w, data)
}
func gameGetHandler(w http.ResponseWriter, r *http.Request) {
gameTemplate.Execute(w, nil)
}
func gamePostHandler(w http.ResponseWriter, r *http.Request) { //TODO запись score в таблицу
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
fmt.Printf("Post from website! r.PostFrom = %v\n", r.PostForm)
score_str := r.FormValue("score")
fmt.Fprintf(w, "score = %s\n", score_str)
fmt.Printf("score = %s\n", score_str)
score_int, err := strconv.Atoi(score_str)
if err != nil {
// handle error
fmt.Println(err)
logger.Printf("Error extracting score from '%s'", score_str)
// os.Exit(2)
} else {
dBConnector.SubmitScore(score_int)
}
}
func DownloadTorrentHandler(w http.ResponseWriter, r *http.Request) {
torrentHash := mux.Vars(r)["hash"]
fmt.Println(r.URL)
torrent, err := dBConnector.TakeTorrent(torrentHash)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusOK)
w.Write([]byte("Torrent file not found"))
return
}
if torrent.Deleted {
w.WriteHeader(http.StatusOK)
w.Write([]byte("The torrent file you are looking for has been deleted"))
return
}
w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.torrent\"", torrent.Name))
http.ServeFile(w, r, fmt.Sprintf("files/torrents/%s.torrent", torrent.Hash))
}
func ForumHandler(w http.ResponseWriter, r *http.Request) {
forumPath := mux.Vars(r)["rest"]
w.Write([]byte("now at forum\n"))
folder, err := dBConnector.TakeForumFolderByPath(forumPath)
if err != nil {
// forumErrorTemplate
if strings.Contains(err.Error(), "Not found") {
w.Write([]byte(err.Error()))
return
}
w.Write([]byte("Internal server error"))
fmt.Println(err)
return
}
w.Write([]byte(fmt.Sprintf("\nType of %v is: %d\n", folder.Title, folder.Type)))
// tempIndex := strings.LastIndex(r.URL.String(), fmt.Sprintf("/%s",folder.Snake))
// if tempIndex != -1 {
// //Non root path
// backUrl := r.URL.String()[:tempIndex]
// _ = backUrl
// }
if folder.Type == 1 {
HandleForumFolder(folder, w, r)
return
}
if folder.Type == 2 {
HandleForumTopic(folder, w, r)
return
}
w.Write([]byte("Internal server error"))
fmt.Println("ERROR: Uncrecognized folder type -", folder.Type)
}
func HandleForumFolder(folder Folder, w http.ResponseWriter, r *http.Request) {
folders, err := dBConnector.TakeChildFolders(folder.Uuid, 10)
if err != nil {
w.Write([]byte("error getting folders from server"))
fmt.Println("ERROR:", err)
}
for _, folder := range folders {
w.Write([]byte(fmt.Sprintf("%s type:%d\n", (r.URL.String()+"/"+folder.Snake), folder.Title, folder.Type)))
}
return
}
func HandleForumTopic(topic Folder, w http.ResponseWriter, r *http.Request) {
messages, err := dBConnector.TakeTopicMessages(topic.Uuid, 0)
if err != nil {
w.Write([]byte("error getting messages from server"))
fmt.Println("ERROR:", err)
}
if len(messages) == 0 {
// Should be imposible
w.Write([]byte("No messages in this topic"))
return
}
for _, message := range messages {
w.Write([]byte(fmt.Sprintf("Author:\n%s\n Time:\n %s\n Text:\n %s\n\n", message.Author, message.Time, message.Text)))
}
}