router.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. package main
  2. // todo 405
  3. import (
  4. "notabug.org/apiote/amuse/accounts"
  5. "notabug.org/apiote/amuse/config"
  6. "notabug.org/apiote/amuse/datastructure"
  7. "notabug.org/apiote/amuse/db"
  8. "notabug.org/apiote/amuse/front"
  9. "notabug.org/apiote/amuse/libamuse"
  10. "notabug.org/apiote/amuse/network"
  11. "notabug.org/apiote/amuse/tmdb"
  12. "crypto/sha256"
  13. "encoding/base64"
  14. "errors"
  15. "fmt"
  16. "golang.org/x/text/language"
  17. "io"
  18. "mime"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "strconv"
  23. "strings"
  24. "time"
  25. )
  26. func person(w http.ResponseWriter, r *http.Request) {
  27. acceptLanguages := r.Header.Get("Accept-Language")
  28. etag := r.Header.Get("Etag")
  29. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  30. auth := getAuthToken(r)
  31. defer recovery(acceptLanguages, mimetype, w)
  32. path := strings.Split(r.URL.Path[1:], "/")
  33. _, err := strconv.ParseInt(path[1], 10, 64)
  34. if err != nil {
  35. renderError(400, w, err, acceptLanguages, mimetype)
  36. return
  37. } else if len(path) > 2 {
  38. renderError(404, w, nil, acceptLanguages, mimetype)
  39. return
  40. }
  41. person, err := libamuse.ShowPerson(path[1], etag, acceptLanguages, mimetype, auth)
  42. render(person, err, w, acceptLanguages, mimetype)
  43. }
  44. func tvSerie(w http.ResponseWriter, r *http.Request) {
  45. acceptLanguages := r.Header.Get("Accept-Language")
  46. etag := r.Header.Get("Etag")
  47. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  48. auth := getAuthToken(r)
  49. defer recovery(acceptLanguages, mimetype, w)
  50. path := strings.Split(r.URL.Path[1:], "/")
  51. _, err := strconv.ParseInt(path[1], 10, 64)
  52. if err != nil {
  53. renderError(400, w, err, acceptLanguages, mimetype)
  54. return
  55. } else if len(path) > 2 {
  56. renderError(404, w, nil, acceptLanguages, mimetype)
  57. return
  58. }
  59. tvSerie, err := libamuse.ShowTvSerie(path[1], etag, acceptLanguages, mimetype, auth)
  60. render(tvSerie, err, w, acceptLanguages, mimetype)
  61. }
  62. func film(w http.ResponseWriter, r *http.Request) {
  63. acceptLanguages := r.Header.Get("Accept-Language")
  64. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  65. auth := getAuthToken(r)
  66. defer recovery(acceptLanguages, mimetype, w)
  67. path := strings.Split(r.URL.Path[1:], "/")
  68. _, err := strconv.ParseInt(path[1], 10, 64)
  69. if err != nil {
  70. renderError(400, w, err, acceptLanguages, mimetype)
  71. return
  72. } else if len(path) > 2 {
  73. renderError(404, w, nil, acceptLanguages, mimetype)
  74. return
  75. }
  76. film, err := libamuse.ShowFilm(path[1], acceptLanguages, mimetype, auth)
  77. render(film, err, w, acceptLanguages, mimetype)
  78. }
  79. func book(w http.ResponseWriter, r *http.Request) {
  80. acceptLanguages := r.Header.Get("Accept-Language")
  81. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  82. auth := getAuthToken(r)
  83. defer recovery(acceptLanguages, mimetype, w)
  84. path := strings.Split(r.URL.Path[1:], "/")
  85. if len(path) > 2 {
  86. renderError(404, w, nil, acceptLanguages, mimetype)
  87. return
  88. }
  89. book, err := libamuse.ShowBook(path[1], acceptLanguages, mimetype, auth)
  90. render(book, err, w, acceptLanguages, mimetype)
  91. }
  92. func bookSerie(w http.ResponseWriter, r *http.Request) {
  93. acceptLanguages := r.Header.Get("Accept-Language")
  94. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  95. auth := getAuthToken(r)
  96. defer recovery(acceptLanguages, mimetype, w)
  97. path := strings.Split(r.URL.Path[1:], "/")
  98. if len(path) > 2 {
  99. renderError(404, w, nil, acceptLanguages, mimetype)
  100. return
  101. }
  102. bookSerie, err := libamuse.ShowBookSerie(path[1], acceptLanguages, mimetype, auth)
  103. render(bookSerie, err, w, acceptLanguages, mimetype)
  104. }
  105. func search(w http.ResponseWriter, r *http.Request) {
  106. acceptLanguages := r.Header.Get("Accept-Language")
  107. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  108. auth := getAuthToken(r)
  109. defer recovery(acceptLanguages, mimetype, w)
  110. path := strings.Split(r.URL.Path[1:], "/")
  111. if len(path) > 2 {
  112. renderError(404, w, nil, acceptLanguages, mimetype)
  113. return
  114. }
  115. query := r.URL.Query().Get("q")
  116. page := r.URL.Query().Get("page")
  117. results, err := libamuse.PerformSearch(query, acceptLanguages, mimetype, page, auth)
  118. render(results, err, w, acceptLanguages, mimetype)
  119. }
  120. func index(w http.ResponseWriter, r *http.Request) {
  121. acceptLanguages := r.Header.Get("Accept-Language")
  122. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  123. auth := getAuthToken(r)
  124. defer recovery(acceptLanguages, mimetype, w)
  125. path := strings.Split(r.URL.Path[1:], "/")
  126. if path[0] != "" {
  127. renderError(404, w, nil, acceptLanguages, mimetype)
  128. return
  129. }
  130. index, err := libamuse.ShowIndex(acceptLanguages, mimetype, auth)
  131. render(index, err, w, acceptLanguages, mimetype)
  132. }
  133. func about(w http.ResponseWriter, r *http.Request) {
  134. acceptLanguages := r.Header.Get("Accept-Language")
  135. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  136. auth := getAuthToken(r)
  137. defer recovery(acceptLanguages, mimetype, w)
  138. about, err := libamuse.ShowAbout(acceptLanguages, mimetype, auth)
  139. render(about, err, w, acceptLanguages, mimetype)
  140. }
  141. func loginGet(w http.ResponseWriter, r *http.Request, acceptLanguages, mimetype string) {
  142. referer := r.Header.Get("Referer")
  143. target := getTarget(referer, r.Host)
  144. if target == "/signedup" {
  145. target = "/"
  146. }
  147. auth := getAuthToken(r)
  148. user, _ := libamuse.VerifyAuthToken(auth)
  149. if !user.IsEmpty() {
  150. w.Header().Add("Location", target)
  151. w.WriteHeader(303)
  152. return
  153. }
  154. login, err := libamuse.ShowLogin(acceptLanguages, mimetype, nil, target)
  155. render(login, err, w, acceptLanguages, mimetype)
  156. }
  157. func loginPost(w http.ResponseWriter, r *http.Request, acceptLanguages, mimetype string) {
  158. // todo check mimetype (html,capnproto)
  159. r.ParseForm()
  160. username := r.PostForm.Get("username")
  161. password := r.PostForm.Get("password")
  162. target := r.PostForm.Get("target")
  163. if target == "" {
  164. target = "/"
  165. }
  166. sfa := r.PostForm.Get("sfa")
  167. remember := r.PostForm.Get("remember") == "true"
  168. token, err := libamuse.DoLogin(username, password, sfa, remember)
  169. if err != nil {
  170. fmt.Println(err)
  171. if authErr, ok := err.(accounts.AuthError); ok {
  172. var login string
  173. var err error
  174. if mimetype == "text/html" {
  175. login, err = libamuse.ShowLogin(acceptLanguages, mimetype, &authErr, target)
  176. } else {
  177. // todo send capnproto not authed
  178. }
  179. render(login, err, w, acceptLanguages, mimetype)
  180. } else {
  181. render("", err, w, acceptLanguages, mimetype)
  182. }
  183. } else {
  184. if mimetype == "text/html" {
  185. setAuthCookie(remember, token, w)
  186. w.Header().Add("Location", target)
  187. w.WriteHeader(303)
  188. } else {
  189. // todo send capnproto authed
  190. }
  191. }
  192. }
  193. func login(w http.ResponseWriter, r *http.Request) {
  194. acceptLanguages := r.Header.Get("Accept-Language")
  195. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  196. defer recovery(acceptLanguages, mimetype, w)
  197. if r.Method == "" || r.Method == "GET" {
  198. loginGet(w, r, acceptLanguages, mimetype)
  199. } else if r.Method == "POST" {
  200. loginPost(w, r, acceptLanguages, mimetype)
  201. }
  202. }
  203. func signupGet(w http.ResponseWriter, r *http.Request, acceptLanguages, mimetype string) {
  204. auth := getAuthToken(r)
  205. user, _ := libamuse.VerifyAuthToken(auth)
  206. host := r.Host
  207. if !user.IsEmpty() {
  208. w.Header().Add("Location", "/")
  209. w.WriteHeader(303)
  210. return
  211. }
  212. signup, err := libamuse.ShowSignup(acceptLanguages, mimetype, nil, false, "", "", host)
  213. render(signup, err, w, acceptLanguages, mimetype)
  214. }
  215. func signupPost(w http.ResponseWriter, r *http.Request, acceptLanguages, mimetype string) {
  216. // todo check mimetype (html,capnproto)
  217. if !config.OpenRegistration {
  218. err := errors.New("423")
  219. render("", err, w, acceptLanguages, mimetype)
  220. return
  221. }
  222. r.ParseForm()
  223. username := r.PostForm.Get("username")
  224. password := r.PostForm.Get("password")
  225. passwordConfirm := r.PostForm.Get("password2")
  226. sfaEnabled := r.PostForm.Get("sfaEnabled") == "true"
  227. sfaSecret := r.PostForm.Get("sfaSecret")
  228. sfa := r.PostForm.Get("sfa")
  229. host := r.Host
  230. recoveryCodes, err := libamuse.DoSignup(username, password, passwordConfirm, sfaEnabled, sfaSecret, sfa)
  231. if err != nil {
  232. fmt.Println(err)
  233. if authErr, ok := err.(accounts.AuthError); ok {
  234. var signup string
  235. var err error
  236. if mimetype == "text/html" {
  237. signup, err = libamuse.ShowSignup(acceptLanguages, mimetype, &authErr, sfaEnabled, sfaSecret, username, host)
  238. } else {
  239. // todo send capnproto not authed
  240. }
  241. render(signup, err, w, acceptLanguages, mimetype)
  242. } else {
  243. render("", err, w, acceptLanguages, mimetype)
  244. }
  245. } else {
  246. if mimetype == "text/html" {
  247. w.Header().Add("Location", "/signedup?recoveryCodes="+recoveryCodes)
  248. w.WriteHeader(303)
  249. } else {
  250. // todo send capnproto authed
  251. }
  252. }
  253. }
  254. func signup(w http.ResponseWriter, r *http.Request) {
  255. acceptLanguages := r.Header.Get("Accept-Language")
  256. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  257. defer recovery(acceptLanguages, mimetype, w)
  258. if r.Method == "" || r.Method == "GET" {
  259. signupGet(w, r, acceptLanguages, mimetype)
  260. } else if r.Method == "POST" {
  261. signupPost(w, r, acceptLanguages, mimetype)
  262. }
  263. }
  264. func signedup(w http.ResponseWriter, r *http.Request) {
  265. acceptLanguages := r.Header.Get("Accept-Language")
  266. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  267. recoveryCodes := r.URL.Query().Get("recoveryCodes")
  268. defer recovery(acceptLanguages, mimetype, w)
  269. signedup, err := libamuse.ShowSignedup(acceptLanguages, mimetype, recoveryCodes)
  270. render(signedup, err, w, acceptLanguages, mimetype)
  271. }
  272. func static(w http.ResponseWriter, r *http.Request) {
  273. etagReq := r.Header.Get("If-None-Match")
  274. f, err := os.Open(config.DataHome + "/" + r.URL.Path[1:])
  275. if err != nil {
  276. w.WriteHeader(500)
  277. return
  278. }
  279. defer f.Close()
  280. h := sha256.New()
  281. if _, err := io.Copy(h, f); err != nil {
  282. w.WriteHeader(500)
  283. return
  284. }
  285. etag := base64.StdEncoding.EncodeToString(h.Sum(nil))
  286. mime.AddExtensionType(".woff2", "font/woff2")
  287. w.Header().Set("ETag", etag)
  288. if etagReq == etag {
  289. w.WriteHeader(304)
  290. } else {
  291. s := strings.Split(f.Name(), ".")
  292. ext := "." + s[len(s)-1]
  293. mimetype := mime.TypeByExtension(ext)
  294. w.Header().Set("Content-Type", mimetype+"; charset=utf-8")
  295. f.Seek(0, 0)
  296. if _, err := io.Copy(w, f); err != nil {
  297. w.WriteHeader(500)
  298. }
  299. }
  300. }
  301. func user(w http.ResponseWriter, r *http.Request, username string, auth accounts.Authentication, acceptLanguages, mimetype string) {
  302. // todo PUT => edit user
  303. // todo DELETE => delete user (and all data)
  304. user, err := libamuse.VerifyAuthToken(auth) // todo refactor up
  305. if err != nil {
  306. render("", err, w, acceptLanguages, mimetype)
  307. return
  308. }
  309. tags, _, err := language.ParseAcceptLanguage(acceptLanguages) // todo refactor up {
  310. if tags == nil {
  311. tags = []language.Tag{}
  312. }
  313. if len(tags) == 0 {
  314. tags = append(tags, language.Make("en-GB"))
  315. } // }
  316. if err != nil {
  317. render("", err, w, acceptLanguages, mimetype)
  318. return
  319. }
  320. if r.Method == "" || r.Method == "GET" {
  321. renderer, err := front.NewRenderer(mimetype, user)
  322. if err != nil {
  323. render("", err, w, acceptLanguages, mimetype)
  324. return
  325. }
  326. account := renderer.RenderAccount(user, tags)
  327. render(account, err, w, acceptLanguages, mimetype)
  328. }
  329. }
  330. func userAvatar(w http.ResponseWriter, r *http.Request, username string, auth accounts.Authentication, acceptLanguages string, mimetype string) {
  331. etagReq := r.Header.Get("If-None-Match")
  332. r.ParseForm()
  333. size := r.Form.Get("size")
  334. avatar, err := libamuse.ShowUserAvatar(username, etagReq, auth, size == "small")
  335. if err != nil {
  336. render("", err, w, acceptLanguages, mimetype)
  337. }
  338. if string(avatar.Data) == "" {
  339. w.WriteHeader(304)
  340. return
  341. }
  342. w.Header().Set("Content-Type", avatar.Mimetype)
  343. w.Header().Set("ETag", avatar.Etag)
  344. w.Write(avatar.Data)
  345. }
  346. func removeFromWantlist(w http.ResponseWriter, r *http.Request, username string, auth accounts.Authentication, acceptLanguages, mimetype, item string) {
  347. itemParts := strings.Split(item, ":")
  348. if len(itemParts) != 2 {
  349. renderError(400, w, fmt.Errorf("%s is not itemType:itemID", item), acceptLanguages, mimetype)
  350. return
  351. }
  352. itemType := itemParts[0]
  353. itemId := itemParts[1]
  354. target, err := libamuse.RemoveFromWantlist(username, auth, itemId, itemType, acceptLanguages, mimetype)
  355. if target == "" {
  356. target = "/" + itemType + "s/" + itemId
  357. }
  358. if err != nil {
  359. render("", err, w, acceptLanguages, mimetype)
  360. } else {
  361. w.Header().Add("Location", target)
  362. w.WriteHeader(303)
  363. }
  364. }
  365. func addToWantlist(w http.ResponseWriter, r *http.Request, username string, auth accounts.Authentication, acceptLanguages, mimetype string) {
  366. r.ParseForm()
  367. itemId := r.PostForm.Get("itemId")
  368. itemType := r.PostForm.Get("itemType")
  369. target := "/" + itemType + "s/" + itemId
  370. err := libamuse.AddToWantlist(username, auth, itemId, itemType, acceptLanguages, mimetype)
  371. if err != nil {
  372. render("", err, w, acceptLanguages, mimetype)
  373. } else {
  374. w.Header().Add("Location", target)
  375. w.WriteHeader(303)
  376. }
  377. }
  378. func userWatchlist(w http.ResponseWriter, r *http.Request, username string, auth accounts.Authentication, acceptLanguages string, mimetype string, path []string) {
  379. if len(path) == 0 || path[0] == "" {
  380. if r.Method == "" || r.Method == "GET" {
  381. var page int
  382. r.ParseForm()
  383. filter := r.Form.Get("filter")
  384. fmt.Sscanf(r.Form.Get("page"), "%d", &page)
  385. watchlist, err := libamuse.ShowWatchlist(username, auth, acceptLanguages, mimetype, filter, page)
  386. render(watchlist, err, w, acceptLanguages, mimetype)
  387. } else if r.Method == "POST" {
  388. addToWantlist(w, r, username, auth, acceptLanguages, mimetype)
  389. }
  390. } else {
  391. r.ParseForm()
  392. method := r.PostForm.Get("method")
  393. if r.Method == "DELETE" || (r.Method == "POST" && method == "DELETE") {
  394. removeFromWantlist(w, r, username, auth, acceptLanguages, mimetype, path[0])
  395. }
  396. }
  397. }
  398. func userTvQueue(w http.ResponseWriter, r *http.Request, username string, auth accounts.Authentication, acceptLanguages string, mimetype string) {
  399. if r.Method == "" || r.Method == "GET" {
  400. var page int
  401. r.ParseForm()
  402. filter := r.Form.Get("filter")
  403. fmt.Sscanf(r.Form.Get("page"), "%d", &page)
  404. tvQueue, err := libamuse.ShowTvQueue(username, auth, acceptLanguages, mimetype, filter, page)
  405. render(tvQueue, err, w, acceptLanguages, mimetype)
  406. } else if r.Method == "POST" {
  407. r.ParseForm()
  408. itemId := r.PostForm.Get("itemId")
  409. itemType := r.PostForm.Get("itemType")
  410. masterItemId := strings.Split(itemId, "/")[0]
  411. target := "/" + itemType + "s/" + masterItemId
  412. err := libamuse.AddToWantlist(username, auth, itemId, itemType, acceptLanguages, mimetype)
  413. if err != nil {
  414. render("", err, w, acceptLanguages, mimetype)
  415. } else {
  416. w.Header().Add("Location", target)
  417. w.WriteHeader(303)
  418. }
  419. }
  420. }
  421. func userReadlist(w http.ResponseWriter, r *http.Request, username string, auth accounts.Authentication, acceptLanguages string, mimetype string) {
  422. if r.Method == "" || r.Method == "GET" {
  423. var page int
  424. r.ParseForm()
  425. filter := r.Form.Get("filter")
  426. fmt.Sscanf(r.Form.Get("page"), "%d", &page)
  427. readlist, err := libamuse.ShowReadlist(username, auth, acceptLanguages, mimetype, filter, page)
  428. render(readlist, err, w, acceptLanguages, mimetype)
  429. } else if r.Method == "POST" {
  430. addToWantlist(w, r, username, auth, acceptLanguages, mimetype)
  431. }
  432. }
  433. func userExperiences(w http.ResponseWriter, r *http.Request, username string, auth accounts.Authentication, acceptLanguages string, mimetype string) {
  434. if r.Method == "" || r.Method == "GET" {
  435. var page int
  436. r.ParseForm()
  437. filter := r.Form.Get("filter")
  438. fmt.Sscanf(r.Form.Get("page"), "%d", &page)
  439. experiences, err := libamuse.ShowExperiences(username, auth, acceptLanguages, mimetype, filter, page)
  440. render(experiences, err, w, acceptLanguages, mimetype)
  441. } else if r.Method == "POST" {
  442. r.ParseForm()
  443. itemId := r.PostForm.Get("itemId")
  444. itemType := r.PostForm.Get("itemType")
  445. isOtherTime := r.PostForm.Get("isOtherTime") == "true"
  446. var datetime string
  447. if isOtherTime {
  448. date := r.PostForm.Get("experiencedDate")
  449. time := r.PostForm.Get("experiencedTime")
  450. datetime = date + "T" + time + ":00"
  451. } else {
  452. datetime = ""
  453. }
  454. masterItemId := strings.Split(itemId, "/")[0]
  455. target := "/" + itemType + "s/" + masterItemId
  456. err := libamuse.AddToExperiences(username, auth, itemId, itemType, datetime, acceptLanguages, mimetype)
  457. if err != nil {
  458. render("", err, w, acceptLanguages, mimetype)
  459. } else {
  460. w.Header().Add("Location", target)
  461. w.WriteHeader(303)
  462. }
  463. }
  464. }
  465. func sessionDelete(w http.ResponseWriter, r *http.Request, username string, auth accounts.Authentication, session, acceptLanguages, mimetype string) {
  466. err := libamuse.SessionDelete(username, auth, session, acceptLanguages, mimetype)
  467. if err != nil {
  468. render("", err, w, acceptLanguages, mimetype)
  469. } else {
  470. w.Header().Add("Location", "/loggedout")
  471. w.WriteHeader(303)
  472. }
  473. }
  474. func userSessions(w http.ResponseWriter, r *http.Request, username string, auth accounts.Authentication, acceptLanguages, mimetype string) {
  475. path := strings.Split(r.URL.Path[1:], "/")
  476. if len(path) == 3 {
  477. // todo show sessions
  478. renderError(404, w, nil, acceptLanguages, mimetype)
  479. } else if len(path) == 4 {
  480. if r.Method == "POST" {
  481. r.ParseForm()
  482. method := r.PostForm.Get("method")
  483. session := path[3]
  484. if method == "DELETE" {
  485. sessionDelete(w, r, username, auth, session, acceptLanguages, mimetype)
  486. }
  487. } else if r.Method == "DELETE" {
  488. session := path[3]
  489. sessionDelete(w, r, username, auth, session, acceptLanguages, mimetype)
  490. }
  491. }
  492. }
  493. func userCalendar(w http.ResponseWriter, r *http.Request, username, languages, mimetype string) {
  494. path := strings.Split(r.URL.Path[1:], "/")
  495. if len(path) == 3 {
  496. if r.Method == "GET" {
  497. basicUsername, basicPassword, ok := r.BasicAuth()
  498. if !ok {
  499. w.WriteHeader(403)
  500. return
  501. }
  502. token, err := libamuse.DoLogin(basicUsername, basicPassword, "", false)
  503. if err != nil {
  504. fmt.Println(err)
  505. w.WriteHeader(403)
  506. return
  507. }
  508. calendar, _ := libamuse.ShowCalendar(username, accounts.Authentication{Token: token})
  509. w.WriteHeader(200)
  510. w.Write([]byte(calendar))
  511. }
  512. }
  513. }
  514. func userRouter(w http.ResponseWriter, r *http.Request) {
  515. path := strings.Split(r.URL.Path[1:], "/")
  516. acceptLanguages := r.Header.Get("Accept-Language")
  517. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  518. auth := getAuthToken(r)
  519. defer recovery(acceptLanguages, mimetype, w)
  520. if path[1] == "" {
  521. renderError(404, w, nil, acceptLanguages, mimetype)
  522. return
  523. }
  524. username := path[1]
  525. if len(path) == 2 {
  526. user(w, r, username, auth, acceptLanguages, mimetype)
  527. } else {
  528. switch path[2] {
  529. case "avatar":
  530. userAvatar(w, r, username, auth, acceptLanguages, mimetype)
  531. case "watchlist":
  532. userWatchlist(w, r, username, auth, acceptLanguages, mimetype, path[3:])
  533. case "tvqueue":
  534. userTvQueue(w, r, username, auth, acceptLanguages, mimetype)
  535. case "readlist":
  536. userReadlist(w, r, username, auth, acceptLanguages, mimetype)
  537. case "experiences":
  538. userExperiences(w, r, username, auth, acceptLanguages, mimetype)
  539. case "sessions":
  540. userSessions(w, r, username, auth, acceptLanguages, mimetype)
  541. case "calendar":
  542. userCalendar(w, r, username, acceptLanguages, mimetype)
  543. default:
  544. renderError(404, w, nil, acceptLanguages, mimetype)
  545. }
  546. }
  547. }
  548. func loggedout(w http.ResponseWriter, r *http.Request) {
  549. acceptLanguages := r.Header.Get("Accept-Language")
  550. mimetype := strings.Split(r.Header.Get("Accept"), ",")[0]
  551. defer recovery(acceptLanguages, mimetype, w)
  552. loggedout, err := libamuse.ShowLoggedOut(acceptLanguages, mimetype)
  553. setAuthCookie(false, "", w)
  554. render(loggedout, err, w, acceptLanguages, mimetype)
  555. }
  556. func route(port uint) {
  557. address := fmt.Sprintf("%s:%d", config.Address, port)
  558. http.HandleFunc("/", index)
  559. http.HandleFunc("/static/", static)
  560. http.HandleFunc("/about", about)
  561. http.HandleFunc("/items/", search)
  562. http.HandleFunc("/films/", film)
  563. http.HandleFunc("/tvseries/", tvSerie)
  564. http.HandleFunc("/persons/", person)
  565. http.HandleFunc("/books/", book)
  566. http.HandleFunc("/bookseries/", bookSerie)
  567. http.HandleFunc("/users/", userRouter)
  568. http.HandleFunc("/login", login)
  569. http.HandleFunc("/signup", signup)
  570. http.HandleFunc("/signedup", signedup)
  571. http.HandleFunc("/loggedout", loggedout)
  572. fmt.Printf("running on %s\n", address)
  573. e := http.ListenAndServe(address, nil)
  574. if e != nil {
  575. fmt.Println(e)
  576. }
  577. }
  578. func getTarget(referer, host string) string {
  579. url, err := url.Parse(referer)
  580. if err != nil {
  581. fmt.Println(err)
  582. return "/"
  583. }
  584. target := url.EscapedPath()
  585. if target == "" || url.Host != host {
  586. target = "/"
  587. }
  588. return target
  589. }
  590. func setAuthCookie(remember bool, token string, w http.ResponseWriter) {
  591. cookie := http.Cookie{
  592. Name: "auth", Value: token, HttpOnly: true,
  593. //SameSite: http.SameSiteStrictMode, Secure: true, // note turn on in prod (https)
  594. }
  595. cookie.Expires = time.Now().Add(1000000000 * 60 * 60 * 24 * 365)
  596. http.SetCookie(w, &cookie)
  597. }
  598. func getAuthToken(r *http.Request) accounts.Authentication {
  599. cookie, err := r.Cookie("auth")
  600. if err == nil {
  601. return accounts.Authentication{
  602. Token: cookie.Value,
  603. }
  604. }
  605. return accounts.Authentication{
  606. Token: r.Header.Get("Authorization"),
  607. }
  608. }
  609. func recovery(languages, mimetype string, w http.ResponseWriter) {
  610. if r := recover(); r != nil {
  611. renderError(500, w, errors.New(r.(string)), languages, mimetype)
  612. }
  613. }
  614. func render(result string, e error, w http.ResponseWriter, languages, mimetype string) {
  615. if e != nil {
  616. if _, ok := e.(front.NoSuchRendererError); ok {
  617. renderError(406, w, e, languages, mimetype)
  618. } else if httpError, ok := e.(network.HttpError); ok {
  619. renderError(httpError.Status, w, httpError, languages, mimetype)
  620. } else if tmdbNotFoundError, ok := e.(tmdb.NotFountError); ok {
  621. renderError(404, w, tmdbNotFoundError, languages, mimetype)
  622. } else if _, ok := e.(db.EmptyError); ok {
  623. renderError(410, w, e, languages, mimetype)
  624. } else if authError, ok := e.(accounts.AuthError); ok {
  625. if authError.Err.Error() == "401" {
  626. w.Header().Add("WWW-Authenticate", "Bearer")
  627. renderError(401, w, e, languages, mimetype)
  628. } else {
  629. renderError(403, w, e, languages, mimetype)
  630. }
  631. } else if e.Error() == "423" {
  632. renderError(423, w, e, languages, mimetype)
  633. } else {
  634. renderError(500, w, e, languages, mimetype)
  635. }
  636. } else {
  637. fmt.Fprint(w, result)
  638. }
  639. }
  640. func renderError(code int, w http.ResponseWriter, e error, languages, mimetype string) {
  641. w.WriteHeader(code)
  642. var (
  643. err error
  644. errorPage string
  645. )
  646. if code != 406 {
  647. if tmdbNotFoundError, ok := e.(tmdb.NotFountError); ok {
  648. tmdbNotFoundError.IsOnWantList, err = db.IsOnWantList(tmdbNotFoundError.User, tmdbNotFoundError.ItemID, datastructure.ItemType(tmdbNotFoundError.ItemType))
  649. e = tmdbNotFoundError
  650. }
  651. errorPage, err = libamuse.ShowErrorPage(e, code, languages, mimetype)
  652. if err != nil {
  653. fmt.Fprintf(w, "Fatal error while rendering error %d.\nContact admin.", code)
  654. }
  655. fmt.Fprint(w, errorPage)
  656. }
  657. }