ctucx.git: oeffi-web

[nimlang] oeffisearch fork that works without javascript

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
import json, os, posix, options
import asyncWebServer

import endpoints/searchHandler
import endpoints/journeysHandler
import endpoints/journeyHandler

import endpoints/api/suggestions
import endpoints/api/journeys
import endpoints/api/moreJourneys
import endpoints/api/refreshJourney

import nimhafas

import types, assets, formaters/formaters

const
  templateError    = staticRead "templates/error.tpl"
  templateSearch   = staticRead "templates/search.tpl"
  templateJourney  = staticRead "templates/journey.tpl"
  templateJourneys = staticRead "templates/journeys.tpl"


proc removePidFile() =
  if getEnv("PID_FILE") != "":
    removeFile(getEnv("PID_FILE"))

proc CtrlCHook() {.noconv.} =
  echo "Ctrl+C fired! \nStopping Server now!"
  removePidFile()
  quit()

proc main =  # for gcsafe
  setControlCHook(CtrlCHook)

  onSignal(SIGTERM):
    echo "Got SIGTERM! \nStopping Server now!"
    removePidFile()
    quit()

  var port = 5000

  if getEnv("PORT") != "":
    port = parseInt(getEnv("PORT"))

  if getEnv("CACHE_PATH") == "":
    echo "CACHE_PATH not set! Bye...."
    quit(1)
  else:
    discard existsOrCreateDir(getEnv("CACHE_PATH"))

  if getEnv("PID_FILE") != "":
    try:
      writeFile(getEnv("PID_FILE"), $getpid() & "\n")
      echo "pid-file \"" & getEnv("PID_FILE") & "\" crated"
    except:
      echo "Can't write pid file!"
      quit(1)

  var server = newServer("0.0.0.0", port)  # launch on http://localhost:5000

  server.pages:
    equals("/"):
      await searchHandler(request, server)

    startsWith("/api/"):
      try:
        let query = parseJson(decodeUrl(request.url.query))
        var response: JsonNode

        if   url == "suggestions":
          response = await suggestionsEndpoint(query)
        elif url == "journeys":
          response = await journeysEndpoint(query)
        elif url == "moreJourneys":
          response = await moreJourneysEndpoint(query)
        elif url == "refreshJourney":
          response = await refreshJourneyEndpoint(query)
        else:
          await request.respondJson(Http404, "error", "ENDPOINT_NOT_FOUND", newJObject())

        await request.respondJson(Http200, "success", "", response)

      except notFoundException:
        await request.respondJson(Http404, "error", getCurrentExceptionMsg().split("\n")[0], newJObject())

      except:
        await request.respondJson(Http500, "error", getCurrentExceptionMsg().split("\n")[0], newJObject())

    startsWith("/suggestions"):
      let requestParams = parseQuery(request.url.query)
      var results       = 10
      var suggestions:    seq[string]

      if requestParams.hasKey("results"):
        results = parseInt(requestParams["results"])

      if requestParams.hasKey("query"):
        let points = (await suggestions(SuggestionsParams(
            query: requestParams["query"],
            results: some(results)
          )))

        for point in points:
          suggestions.add(formatPoint(point))
    
      var json = %* {"suggestions": suggestions}
      await request.respondJson(Http200, "success", "", json["suggestions"])

    startsWith("/assets/"):
      if url == "style.css":
        await request.respond(Http200, assetStyleCss, newHttpHeaders([("Content-Type", "text/css; charset=UTF-8")]))

      elif url == "manifest.json":
        await request.respond(Http200, assetManifestJson, newHttpHeaders([("Content-Type", "application/json; charset=UTF-8")]))

      elif url == "favicon-512x512.png":
        await request.respond(Http200, assetFavicon512, newHttpHeaders([("Content-Type", "image/png")]))

      elif url == "favicon-64x64.png":
        await request.respond(Http200, assetFavicon64, newHttpHeaders([("Content-Type", "image/png")]))

      elif url == "js/lit-html.js":
        await request.respond(Http200, assetLitHtmlJs, newHttpHeaders([("Content-Type", "text/javascript; charset=UTF-8")]))

      elif url == "js/helpers.js":
        await request.respond(Http200, assetHelpersJs, newHttpHeaders([("Content-Type", "text/javascript; charset=UTF-8")]))

      elif url == "js/search.js":
        await request.respond(Http200, assetSearchJs, newHttpHeaders([("Content-Type", "text/javascript; charset=UTF-8")]))

      elif url == "js/journeys.js":
        await request.respond(Http200, assetJourneysJs, newHttpHeaders([("Content-Type", "text/javascript; charset=UTF-8")]))

      elif url == "js/journey.js":
        await request.respond(Http200, assetJourneyJs, newHttpHeaders([("Content-Type", "text/javascript; charset=UTF-8")]))

      else:
        await request.respond(Http404, "404 - Not found", newHttpHeaders([("Content-Type", "text/plain")]))


    regex(re"^\/([A-Za-z0-9]+)$"):
      await journeysHandler(request, server)


    regex(re"^\/([A-Za-z0-9]+)\/([0-9-]+)$"):
      await journeyHandler(request, server)

  server.start()

main()