handlers.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package main
  2. import (
  3. "fmt"
  4. "html/template"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "github.com/gorilla/mux"
  9. )
  10. // Struct for torrent entry in 'New torrents' list
  11. type Entry struct {
  12. Num int
  13. Link string
  14. }
  15. type NewsItem struct {
  16. NewsText template.HTML
  17. Author string
  18. Time string
  19. }
  20. // indexHandler handels index page
  21. func indexHandler(w http.ResponseWriter, r *http.Request) {
  22. data := struct {
  23. User string
  24. Password string
  25. Title string
  26. Items []string
  27. Entrys []Entry
  28. News []NewsItem
  29. }{
  30. User: "",
  31. Title: "My page",
  32. Items: []string{
  33. "My photos",
  34. "My blog",
  35. "More",
  36. },
  37. }
  38. session, _ := sessionsStore.Get(r, "session")
  39. untyped, ok := session.Values["username"]
  40. if ok {
  41. username, ok1 := untyped.(string)
  42. if ok1 {
  43. data.User = username
  44. }
  45. }
  46. untyped, ok2 := session.Values["password"]
  47. if ok2 {
  48. password, ok3 := untyped.(string)
  49. if ok3 {
  50. data.Password = password
  51. }
  52. }
  53. // fmt.Println(data.User)
  54. // fmt.Println(data.Password)
  55. // tindexTemplate, err := template.New("").ParseFiles(INDEX_TEMPLATE, "ui\\templates\\placeholder.html")
  56. tindexTemplate, err := template.New("").ParseFiles(NewIndexTemplate, TorrentEntry, TorrentList, NewsList, NewsEntry)
  57. if err != nil {
  58. fmt.Println("Error in templates loading")
  59. fmt.Println(err)
  60. w.Write([]byte("Internal server error"))
  61. return
  62. }
  63. data.Entrys = append(data.Entrys, Entry{Num: 54, Link: "/files/torrents/2torrent.torrent"})
  64. data.Entrys = append(data.Entrys, Entry{Num: 10, Link: "/files/torrents/1torrent.torrent"})
  65. data.Entrys = append(data.Entrys, Entry{Num: 23, Link: "/files/torrents/3torrent.torrent"})
  66. data.Entrys = append(data.Entrys, Entry{Num: 82, Link: "/files/torrents/4torrent.torrent"})
  67. data.Entrys = append(data.Entrys, Entry{Num: 12, Link: "/files/torrents/5torrent.torrent"})
  68. data.Entrys = append(data.Entrys, Entry{Num: 98, Link: "/files/torrents/6torrent.torrent"})
  69. data.Entrys = append(data.Entrys, Entry{Num: 18, Link: "/files/torrents/7torrent.torrent"})
  70. data.Entrys = append(data.Entrys, Entry{Num: 35, Link: "/files/torrents/8torrent.torrent"})
  71. data.Entrys = append(data.Entrys, Entry{Num: 4, Link: "/files/torrents/9torrent.torrent"})
  72. news, _, err := dBConnector.GetLastNews(3)
  73. if err != nil {
  74. fmt.Println(err)
  75. }
  76. if err == nil {
  77. data.News = append(data.News, news...)
  78. }
  79. // LastTorrents, err := dBConnector.SelectTorrents(10)
  80. // if err != nil {
  81. // fmt.Println(err)
  82. // }
  83. // for _, torrent := LastTorrents {
  84. // torrentTopic, err := dBConnector.GetTorrentTopic(torrent.Hash)
  85. // if err != nil {
  86. // fmt.Println(err)
  87. // continue
  88. // }
  89. // torrentEntry := Entry{
  90. // Title: torrentTopic.Title,
  91. // Desc: torrentTopic.Desc,
  92. // TopicLink: torrentTopic.Link,
  93. // Endorsments: torrent.Endors,
  94. // TorrentLink: GenTorrentLink(torrent.Hash),
  95. // }
  96. // data.Entrys = append(data.Entrys, torrentEntry)
  97. // }
  98. err = tindexTemplate.ExecuteTemplate(w, "newindex", data)
  99. if err != nil {
  100. fmt.Println(err)
  101. w.Write([]byte("Internal server error"))
  102. }
  103. }
  104. func indexPostHandler(w http.ResponseWriter, r *http.Request) {
  105. fmt.Print("POST")
  106. }
  107. func logInGetHandler(w http.ResponseWriter, r *http.Request) {
  108. data := struct {
  109. Username string
  110. Password string
  111. Error string
  112. }{
  113. Username: "",
  114. Password: "",
  115. Error: "",
  116. }
  117. logInTemplate.Execute(w, data)
  118. }
  119. func logInPostHandler(w http.ResponseWriter, r *http.Request) {
  120. r.ParseForm()
  121. username := r.PostForm.Get("username")
  122. password := r.PostForm.Get("password")
  123. fmt.Printf("Post from website! r.PostFrom = %v\n", r.PostForm)
  124. if dBConnector.LogIn(username, password) {
  125. session, _ := sessionsStore.Get(r, "session")
  126. session.Values["username"] = username
  127. session.Values["password"] = password
  128. session.Save(r, w)
  129. http.Redirect(w, r, "/", http.StatusFound)
  130. } else {
  131. data := struct {
  132. Username string
  133. Password string
  134. Error string
  135. }{
  136. Username: username,
  137. Password: password,
  138. Error: "Неверный логин либо пароль",
  139. }
  140. fmt.Printf("Login error")
  141. logInTemplate.Execute(w, data)
  142. // w.Write([]byte("Login error"))
  143. }
  144. }
  145. func logOutGetHandler(w http.ResponseWriter, r *http.Request) {
  146. session, _ := sessionsStore.Get(r, "session")
  147. session.Options.MaxAge = -1
  148. session.Save(r, w)
  149. untyped, ok := session.Values["username"]
  150. if ok {
  151. username, ok1 := untyped.(string)
  152. if ok1 {
  153. logger.Printf("User %s loged out", username)
  154. }
  155. }
  156. http.Redirect(w, r, "/", http.StatusFound)
  157. }
  158. func signInGetHandler(w http.ResponseWriter, r *http.Request) {
  159. signInTemplate.Execute(w, nil)
  160. }
  161. func signInPostHandler(w http.ResponseWriter, r *http.Request) {
  162. r.ParseForm()
  163. username := r.PostForm.Get("username")
  164. password := r.PostForm.Get("password")
  165. passwordRepeat := r.PostForm.Get("password-repeat")
  166. data := struct {
  167. Username string
  168. Password string
  169. PasswordRepeat string
  170. Error string
  171. }{
  172. Username: username,
  173. Password: password,
  174. PasswordRepeat: passwordRepeat,
  175. Error: "",
  176. }
  177. if dBConnector.IsNameUsed(username) {
  178. data.Error = "Имя пользователя занято"
  179. } else {
  180. if password != passwordRepeat {
  181. data.Error = "Введенные пароли не совпадают"
  182. } else {
  183. if dBConnector.SigInUser(username, password) {
  184. session, _ := sessionsStore.Get(r, "session")
  185. session.Values["username"] = username
  186. session.Values["password"] = password
  187. session.Save(r, w)
  188. http.Redirect(w, r, "/", http.StatusFound)
  189. } else {
  190. data.Error = "Произошла внутреняя ошибка при регистрации нового пользователя"
  191. }
  192. }
  193. }
  194. signInTemplate.Execute(w, data)
  195. }
  196. func gameGetHandler(w http.ResponseWriter, r *http.Request) {
  197. gameTemplate.Execute(w, nil)
  198. }
  199. func gamePostHandler(w http.ResponseWriter, r *http.Request) { //TODO запись score в таблицу
  200. if err := r.ParseForm(); err != nil {
  201. fmt.Fprintf(w, "ParseForm() err: %v", err)
  202. return
  203. }
  204. fmt.Printf("Post from website! r.PostFrom = %v\n", r.PostForm)
  205. score_str := r.FormValue("score")
  206. fmt.Fprintf(w, "score = %s\n", score_str)
  207. fmt.Printf("score = %s\n", score_str)
  208. score_int, err := strconv.Atoi(score_str)
  209. if err != nil {
  210. // handle error
  211. fmt.Println(err)
  212. logger.Printf("Error extracting score from '%s'", score_str)
  213. // os.Exit(2)
  214. } else {
  215. dBConnector.SubmitScore(score_int)
  216. }
  217. }
  218. func DownloadTorrentHandler(w http.ResponseWriter, r *http.Request) {
  219. torrentHash := mux.Vars(r)["hash"]
  220. fmt.Println(r.URL)
  221. torrent, err := dBConnector.TakeTorrent(torrentHash)
  222. if err != nil {
  223. fmt.Println(err)
  224. w.WriteHeader(http.StatusOK)
  225. w.Write([]byte("Torrent file not found"))
  226. return
  227. }
  228. if torrent.Deleted {
  229. w.WriteHeader(http.StatusOK)
  230. w.Write([]byte("The torrent file you are looking for has been deleted"))
  231. return
  232. }
  233. w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.torrent\"", torrent.Name))
  234. http.ServeFile(w, r, fmt.Sprintf("files/torrents/%s.torrent", torrent.Hash))
  235. }
  236. func ForumHandler(w http.ResponseWriter, r *http.Request) {
  237. forumpath := mux.Vars(r)["rest"]
  238. w.Write([]byte("now at forum\n"))
  239. fmt.Println(len(forumpath))
  240. if len(forumpath) == 0 {
  241. // Serve forum root
  242. w.Write([]byte("forum root\n"))
  243. rootUuid := "7e92ebbd-750f-4a34-ad62-bc6a4f47cbfa"
  244. folders, err := dBConnector.TakeChildFolders(rootUuid, 10)
  245. if err != nil {
  246. w.Write([]byte("error getting folders from server"))
  247. fmt.Println("ERROR:", err)
  248. }
  249. for _, folder := range folders {
  250. w.Write([]byte(fmt.Sprintf("<a href=%s>%s</a>\n", (r.URL.String()+"/"+folder.Snake), folder.Title)))
  251. }
  252. return
  253. }
  254. if len(forumpath) > 0 {
  255. // Serve subfolders
  256. dirs := strings.Split(forumpath,"/")
  257. //var currentUuid string
  258. var parentUuid string
  259. parentUuid = "7e92ebbd-750f-4a34-ad62-bc6a4f47cbfa"
  260. var folder Folder
  261. for _, dir :=range dirs {
  262. var err error
  263. folder, err = dBConnector.TakeChildFolderBySnake(parentUuid, dir)
  264. if err != nil {
  265. fmt.Println("ERROR:", err)
  266. return
  267. }
  268. if folder == (Folder{}) {
  269. // Child not found
  270. w.Write([]byte(fmt.Sprintf("\nNot found %v", dir)))
  271. return
  272. }
  273. parentUuid = folder.Uuid
  274. w.Write([]byte(fmt.Sprintf("/%v", dir)))
  275. }
  276. w.Write([]byte(fmt.Sprintf("\nType of %v is: %d\n", folder.Title, folder.Type)))
  277. if folder.Type == 1 {
  278. // Load subfolders
  279. folders, err := dBConnector.TakeChildFolders(folder.Uuid, 10)
  280. if err != nil {
  281. w.Write([]byte("error getting folders from server"))
  282. fmt.Println("ERROR:", err)
  283. }
  284. for _, folder := range folders {
  285. w.Write([]byte(fmt.Sprintf("<a href=%s>%s type:%d</a>\n", (r.URL.String()+"/"+folder.Snake), folder.Title, folder.Type)))
  286. }
  287. }
  288. if folder.Type == 2 {
  289. // Load messages
  290. messages, err := dBConnector.TakeTopicMessages(folder.Uuid, 0)
  291. if err != nil {
  292. w.Write([]byte("error getting messages from server"))
  293. fmt.Println("ERROR:", err)
  294. }
  295. if len(messages) == 0 {
  296. // Should be imposible
  297. w.Write([]byte("No messages in this topic"))
  298. return
  299. }
  300. for _, message := range messages {
  301. w.Write([]byte(fmt.Sprintf("Author:\n%s\n Time:\n %s\n Text:\n %s\n\n", message.Author, message.Time, message.Text)))
  302. }
  303. }
  304. return
  305. }
  306. }