handlers.go 6.9 KB

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