handlers.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package main
  2. import (
  3. "fmt"
  4. "html/template"
  5. "net/http"
  6. "strconv"
  7. "github.com/gorilla/mux"
  8. )
  9. // Struct for torrent entry in 'New torrents' list
  10. type Entry struct {
  11. Num int
  12. Link string
  13. }
  14. // indexHandler handels index page
  15. func indexHandler(w http.ResponseWriter, r *http.Request) {
  16. data := struct {
  17. User string
  18. Password string
  19. Title string
  20. Items []string
  21. Entrys []Entry
  22. }{
  23. User: "",
  24. Title: "My page",
  25. Items: []string{
  26. "My photos",
  27. "My blog",
  28. "More",
  29. },
  30. }
  31. session, _ := sessionsStore.Get(r, "session")
  32. untyped, ok := session.Values["username"]
  33. if ok {
  34. username, ok1 := untyped.(string)
  35. if ok1 {
  36. data.User = username
  37. }
  38. }
  39. untyped, ok2 := session.Values["password"]
  40. if ok2 {
  41. password, ok3 := untyped.(string)
  42. if ok3 {
  43. data.Password = password
  44. }
  45. }
  46. // fmt.Println(data.User)
  47. // fmt.Println(data.Password)
  48. // tindexTemplate, err := template.New("").ParseFiles(INDEX_TEMPLATE, "ui\\templates\\placeholder.html")
  49. tindexTemplate, err := template.New("").ParseFiles(NewIndexTemplate, TorrentEntry, TorrentList)
  50. if err != nil {
  51. fmt.Println("Error in templates loading")
  52. fmt.Println(err)
  53. w.Write([]byte("Internal server error"))
  54. return
  55. }
  56. data.Entrys = append(data.Entrys, Entry{Num: 54, Link: "/files/torrents/2torrent.torrent"})
  57. data.Entrys = append(data.Entrys, Entry{Num: 10, Link: "/files/torrents/1torrent.torrent"})
  58. data.Entrys = append(data.Entrys, Entry{Num: 23, Link: "/files/torrents/3torrent.torrent"})
  59. data.Entrys = append(data.Entrys, Entry{Num: 82, Link: "/files/torrents/4torrent.torrent"})
  60. data.Entrys = append(data.Entrys, Entry{Num: 12, Link: "/files/torrents/5torrent.torrent"})
  61. data.Entrys = append(data.Entrys, Entry{Num: 98, Link: "/files/torrents/6torrent.torrent"})
  62. data.Entrys = append(data.Entrys, Entry{Num: 18, Link: "/files/torrents/7torrent.torrent"})
  63. data.Entrys = append(data.Entrys, Entry{Num: 35, Link: "/files/torrents/8torrent.torrent"})
  64. data.Entrys = append(data.Entrys, Entry{Num: 4, Link: "/files/torrents/9torrent.torrent"})
  65. // LastTorrents, err := dBConnector.SelectTorrents(10)
  66. // if err != nil {
  67. // fmt.Println(err)
  68. // }
  69. // for _, torrent := LastTorrents {
  70. // torrentTopic, err := dBConnector.GetTorrentTopic(torrent.Hash)
  71. // if err != nil {
  72. // fmt.Println(err)
  73. // continue
  74. // }
  75. // torrentEntry := Entry{
  76. // Title: torrentTopic.Title,
  77. // Desc: torrentTopic.Desc,
  78. // TopicLink: torrentTopic.Link,
  79. // Endorsments: torrent.Endors,
  80. // TorrentLink: GenTorrentLink(torrent.Hash),
  81. // }
  82. // data.Entrys = append(data.Entrys, torrentEntry)
  83. // }
  84. err = tindexTemplate.ExecuteTemplate(w, "newindex", data)
  85. if err != nil {
  86. fmt.Println(err)
  87. w.Write([]byte("Internal server error"))
  88. }
  89. }
  90. func indexPostHandler(w http.ResponseWriter, r *http.Request) {
  91. fmt.Print("POST")
  92. }
  93. func logInGetHandler(w http.ResponseWriter, r *http.Request) {
  94. data := struct {
  95. Username string
  96. Password string
  97. Error string
  98. }{
  99. Username: "",
  100. Password: "",
  101. Error: "",
  102. }
  103. logInTemplate.Execute(w, data)
  104. }
  105. func logInPostHandler(w http.ResponseWriter, r *http.Request) {
  106. r.ParseForm()
  107. username := r.PostForm.Get("username")
  108. password := r.PostForm.Get("password")
  109. fmt.Printf("Post from website! r.PostFrom = %v\n", r.PostForm)
  110. if dBConnector.LogIn(username, password) {
  111. session, _ := sessionsStore.Get(r, "session")
  112. session.Values["username"] = username
  113. session.Values["password"] = password
  114. session.Save(r, w)
  115. http.Redirect(w, r, "/", http.StatusFound)
  116. } else {
  117. data := struct {
  118. Username string
  119. Password string
  120. Error string
  121. }{
  122. Username: username,
  123. Password: password,
  124. Error: "Неверный логин либо пароль",
  125. }
  126. fmt.Printf("Login error")
  127. logInTemplate.Execute(w, data)
  128. // w.Write([]byte("Login error"))
  129. }
  130. }
  131. func logOutGetHandler(w http.ResponseWriter, r *http.Request) {
  132. session, _ := sessionsStore.Get(r, "session")
  133. session.Options.MaxAge = -1
  134. session.Save(r, w)
  135. untyped, ok := session.Values["username"]
  136. if ok {
  137. username, ok1 := untyped.(string)
  138. if ok1 {
  139. logger.Printf("User %s loged out", username)
  140. }
  141. }
  142. http.Redirect(w, r, "/", http.StatusFound)
  143. }
  144. func signInGetHandler(w http.ResponseWriter, r *http.Request) {
  145. signInTemplate.Execute(w, nil)
  146. }
  147. func signInPostHandler(w http.ResponseWriter, r *http.Request) {
  148. r.ParseForm()
  149. username := r.PostForm.Get("username")
  150. password := r.PostForm.Get("password")
  151. passwordRepeat := r.PostForm.Get("password-repeat")
  152. data := struct {
  153. Username string
  154. Password string
  155. PasswordRepeat string
  156. Error string
  157. }{
  158. Username: username,
  159. Password: password,
  160. PasswordRepeat: passwordRepeat,
  161. Error: "",
  162. }
  163. if dBConnector.IsNameUsed(username) {
  164. data.Error = "Имя пользователя занято"
  165. } else {
  166. if password != passwordRepeat {
  167. data.Error = "Введенные пароли не совпадают"
  168. } else {
  169. if dBConnector.SigInUser(username, password) {
  170. session, _ := sessionsStore.Get(r, "session")
  171. session.Values["username"] = username
  172. session.Values["password"] = password
  173. session.Save(r, w)
  174. http.Redirect(w, r, "/", http.StatusFound)
  175. } else {
  176. data.Error = "Произошла внутреняя ошибка при регистрации нового пользователя"
  177. }
  178. }
  179. }
  180. signInTemplate.Execute(w, data)
  181. }
  182. func gameGetHandler(w http.ResponseWriter, r *http.Request) {
  183. gameTemplate.Execute(w, nil)
  184. }
  185. func gamePostHandler(w http.ResponseWriter, r *http.Request) { //TODO запись score в таблицу
  186. if err := r.ParseForm(); err != nil {
  187. fmt.Fprintf(w, "ParseForm() err: %v", err)
  188. return
  189. }
  190. fmt.Printf("Post from website! r.PostFrom = %v\n", r.PostForm)
  191. score_str := r.FormValue("score")
  192. fmt.Fprintf(w, "score = %s\n", score_str)
  193. fmt.Printf("score = %s\n", score_str)
  194. score_int, err := strconv.Atoi(score_str)
  195. if err != nil {
  196. // handle error
  197. fmt.Println(err)
  198. logger.Printf("Error extracting score from '%s'", score_str)
  199. // os.Exit(2)
  200. } else {
  201. dBConnector.SubmitScore(score_int)
  202. }
  203. }
  204. func DownloadTorrentHandler(w http.ResponseWriter, r *http.Request) {
  205. torrentHash := mux.Vars(r)["hash"]
  206. fmt.Println(r.URL)
  207. torrent, err := dBConnector.TakeTorrent(torrentHash)
  208. if err != nil {
  209. fmt.Println(err)
  210. w.WriteHeader(http.StatusOK)
  211. w.Write([]byte("Torrent file not found"))
  212. return
  213. }
  214. if torrent.Deleted {
  215. w.WriteHeader(http.StatusOK)
  216. w.Write([]byte("The torrent file you are looking for has been deleted"))
  217. return
  218. }
  219. w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.torrent\"", torrent.Name))
  220. http.ServeFile(w, r, fmt.Sprintf("files/torrents/%s.torrent", torrent.Hash))
  221. }