123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358 |
- 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"))
- fmt.Println(len(forumpath))
- if len(forumpath) == 0 {
- // Serve forum root
- w.Write([]byte("forum root\n"))
- rootUuid := "7e92ebbd-750f-4a34-ad62-bc6a4f47cbfa"
- folders, err := dBConnector.TakeChildFolders(rootUuid, 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("<a href=%s>%s</a>\n", (r.URL.String()+"/"+folder.Snake), folder.Title)))
- }
- return
- }
- if len(forumpath) > 0 {
- // Serve subfolders
- dirs := strings.Split(forumpath,"/")
- //var currentUuid string
- var parentUuid string
- parentUuid = "7e92ebbd-750f-4a34-ad62-bc6a4f47cbfa"
- var folder Folder
- for _, dir :=range dirs {
- var err error
- folder, err = dBConnector.TakeChildFolderBySnake(parentUuid, dir)
- if err != nil {
- fmt.Println("ERROR:", err)
- return
- }
- if folder == (Folder{}) {
- // Child not found
- w.Write([]byte(fmt.Sprintf("\nNot found %v", dir)))
- return
- }
- parentUuid = folder.Uuid
- w.Write([]byte(fmt.Sprintf("/%v", dir)))
- }
- w.Write([]byte(fmt.Sprintf("\nType of %v is: %d\n", folder.Title, folder.Type)))
- if folder.Type == 1 {
- // Load subfolders
- 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("<a href=%s>%s type:%d</a>\n", (r.URL.String()+"/"+folder.Snake), folder.Title, folder.Type)))
- }
- }
- if folder.Type == 2 {
- // Load messages
- messages, err := dBConnector.TakeTopicMessages(folder.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)))
- }
- }
- return
- }
- }
|