ctucx.git: oeffi-web

[nimlang] oeffisearch fork that works without javascript

commit 59c8255ca0f93f338ef3bab4bbe6d6f1e0db90fc
parent 2d126b4077f63219c19dd50dc7e4e2a72826e666
Author: Leah (ctucx) <leah@ctu.cx>
Date: Thu, 21 Jan 2021 21:37:35 +0100

removed unused code
3 files changed, 89 insertions(+), 306 deletions(-)
M
oeffi.nimble
|
2
+-
M
src/oeffi.nim
|
280
+++++++++++++++++++++++++------------------------------------------------------
D
src/oeffi_nojs.nim
|
113
-------------------------------------------------------------------------------
diff --git a/oeffi.nimble b/oeffi.nimble
@@ -4,7 +4,7 @@ author        = "ctucx, petabyteboy"
 description   = "oeffi-web: public transport in your browser "
 license       = "AGPL-3.0"
 srcDir        = "src"
-bin           = @["oeffi_nojs", "oeffi"]
+bin           = @["oeffi"]
 
 
 # Dependencies
diff --git a/src/oeffi.nim b/src/oeffi.nim
@@ -1,217 +1,113 @@
-import os, json, times, options, strutils, asyncdispatch, re
-import moustachu
-import types, backend/hafas, cache, cache_types
-import endpoints/[suggestions, journeys, moreJourneys, refreshJourney]
-import utils, translations, formaters/[formaters, renderJourneys, renderJourney, formatFullResponse]
-
-if getEnv("CACHE_PATH") == "":
-  echo "CACHE_PATH not set! Bye...."
-  quit()
-else:
-  discard existsOrCreateDir(getEnv("CACHE_PATH"))
-
-settings:
-  port      = Port(5_000)
-  bindAddr  = "0.0.0.0"
-
-routes:
-  get "/":
-    let requestParams   = params(request)
-
-    var lang            = "de"
-    var templateContext = %* {
-        "DATE":  now().format("yyyy-MM-dd"),
-        "TIME":  now().format("HH:mm")
-      }
-
-    readSetLang()
-    respTemplate(Http200, "search", templateContext, lang)
-
-
-  post "/":
-    let requestParams = params(request)
-    var cacheObj:       CacheObject
-    var params:         JourneysParams
-
-    try: 
-      var products = %* {}
-      parseProduct(products, requestParams, "national")
-      parseProduct(products, requestParams, "national", "nationalExp")
-      parseProduct(products, requestParams, "regional")
-      parseProduct(products, requestParams, "regional", "regionalExp")
-      parseProduct(products, requestParams, "suburban")
-      parseProduct(products, requestParams, "subway")
-      parseProduct(products, requestParams, "tram")
-      parseProduct(products, requestParams, "bus")
-      parseProduct(products, requestParams, "ferry")
-      parseProduct(products, requestParams, "taxi")
-
-      params  = JourneysParams(
-          fromPoint: (await getPoint(requestParams["from"])),
-          toPoint:   (await getPoint(requestParams["to"])),
-        )
-
-      params.stopovers     = some(true)
-      params.polylines     = some(true)
-      params.remarks       = some(true)
-      params.tickets       = some(true)
-      params.accessibility = some(parseEnum[Accessibility](requestParams["accessibility"]))
-      params.products      = some(products.to(Products))
-
-      if requestParams.hasKey("isarr"):
-        params.arrival   = some(parseTime(requestParams["date"] & " " & requestParams["time"], "yyyy-MM-dd HH:mm", local()).toUnix)
-      else:
-        params.departure = some(parseTime(requestParams["date"] & " " & requestParams["time"], "yyyy-MM-dd HH:mm", local()).toUnix)
-
-      if formatPoint(params.fromPoint) == formatPoint(params.toPoint):
-        raise newException(errorException, "TOO_CLOSE")
-
-      cacheObj = (await saveJourneys(params, await journeys(params)))
-
-      if cacheObj.reqId != "":
-        redirect "/" & cacheObj.reqId
-      else:
-        raise newException(errorException, "NO_REQID")
-
-    except:
-      echo getCurrentExceptionMsg()
-      let exceptionMsg = getCurrentExceptionMsg().split("\n")[0]
-
-      if not requestParams.hasKey("json"):
-        case exceptionMsg:
-          of "TOO_CLOSE":
-            respError(Http500, "Fehler!", "Abfahrts- und Ankunftsbahnhof dürfen nicht gleich sein.")
-          else:
-            respError(Http500, "Unbekannter Fehler!", "Das hätte nicht passieren dürfen, versuche es doch bitte erneut.")
-      else:
-        case exceptionMsg:
-          of "TOO_CLOSE":
-            respApi(Http500, "error", "TOO_CLOSE", "")
-          else:
-            respApi(Http500, "error", "UNKNOWN_ERROR", "")        
-
-
-  post "/api":
-    let endpoint      = @"endpoint"
-    let requestParams = params(request)
-
-    try: 
-      let payload = parseJson(request.body)
-      var response: JsonNode
-
-      case requestParams["endpoint"]:
-        of "suggestions":
-          response = await suggestionsEndpoint(payload)
-        of "journeys":
-          response = await journeysEndpoint(payload)
-        of "moreJourneys":
-          response = await moreJourneysEndpoint(payload)
-        of "refreshJourney":
-          response = await refreshJourneyEndpoint(payload)
-
-      respApi(Http200, "success", "", response)
-
-    except notFoundException:
-      respApi(Http404, "error", getCurrentExceptionMsg().split("\n")[0], "")
-
-    except:
-      respApi(Http500, "error", getCurrentExceptionMsg().split("\n")[0], "")
+import json, os, posix
+import asyncWebServer
 
+import types
+import options
 
-  get "/suggestions":
-    let requestParams = params(request)
-    var results       = 10
-    var suggestions:    seq[string]
+import endpoints/searchHandler
+import endpoints/journeysHandler
+import endpoints/journeyHandler
 
-    if requestParams.hasKey("results"):
-      results = parseInt(requestParams["results"])
+import endpoints/api/suggestions
+import endpoints/api/journeys
+import endpoints/api/moreJourneys
+import endpoints/api/refreshJourney
 
-    if requestParams.hasKey("query"):
-      let points = (await suggestions(SuggestionsParams(
-          query: requestParams["query"],
-          results: some(results)
-        )))
+import types, backend/hafas, formaters/formaters
 
-      for point in points:
-        suggestions.add(formatPoint(point))
-    
-    respApi(Http200, "success", "", %suggestions)
+proc removePidFile() =
+  if getEnv("PID_FILE") != "":
+    removeFile(getEnv("PID_FILE"))
 
+proc CtrlCHook() {.noconv.} =
+  echo "Ctrl+C fired! \nStopping Server now!"
+  removePidFile()
+  quit()
 
-  get re"^\/([A-Za-z0-9]+)$":
-    let reqId         = request.matches[0]
-    let requestParams = params(request)
+proc main =  # for gcsafe
+  setControlCHook(CtrlCHook)
 
-    var lang          = "de"
-    var cacheObj:       CacheObject
+  onSignal(SIGTERM):
+    echo "Got SIGTERM! \nStopping Server now!"
+    removePidFile()
+    quit()
 
-    try:
-      readSetLang()
+  var port = 5000
 
-      if not cacheExists(reqId): raise newException(notFoundException, "REQUEST_NOT_FOUND")
-      cacheObj = getCacheObject(reqId)
+  if getEnv("PORT") != "":
+    port = parseInt(getEnv("PORT"))
 
-      if requestParams.hasKey("more"):
-        var params = cacheObj.params
-        let mode   = parseEnum[moreJourneysMode](requestParams["more"])
+  if getEnv("CACHE_PATH") == "":
+    echo "CACHE_PATH not set! Bye...."
+    quit(1)
+  else:
+    discard existsOrCreateDir(getEnv("CACHE_PATH"))
 
-        if mode != later:
-          params.earlierRef = some(cacheObj.earlierRef)
+  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:
-          params.laterRef   = some(cacheObj.laterRef)
-
-        cacheObj = (await updateJourneys(reqId, mode, (await journeys(params))))
-
-      var templateContext = renderJourneys(cacheObj)
+          await request.respondJson(Http404, "error", "ENDPOINT_NOT_FOUND", newJObject())
 
-      if not requestParams.hasKey("json"):
-        respTemplate(Http200, "journeys", templateContext, lang)
-      else:
-        respApi(Http200, "success", "", templateContext)
+        await request.respondJson(Http200, "success", "", response)
 
-    except notFoundException:
-      if not requestParams.hasKey("json"):
-        respError(Http404, "Nichts gefunden!", "Für diese Anfrage gibts nix.")
-      else:
-        respApi(Http404, "error", getCurrentExceptionMsg().split("\n")[0], "")
+      except notFoundException:
+        await request.respondJson(Http404, "error", getCurrentExceptionMsg().split("\n")[0], newJObject())
 
+      except:
+        await request.respondJson(Http500, "error", getCurrentExceptionMsg().split("\n")[0], newJObject())
 
-  get re"^\/([A-Za-z0-9]+)\/([0-9-]+)$":
-    let reqId         = request.matches[0]
-    let journeyId     = request.matches[1]
-    let requestParams = params(request)
+    startsWith("/suggestions"):
+      let requestParams = parseQuery(request.url.query)
+      var results       = 10
+      var suggestions:    seq[string]
 
-    var lang          = "de"
-    var cacheObj:       CacheObject
+      if requestParams.hasKey("results"):
+        results = parseInt(requestParams["results"])
 
-    try:
-      readSetLang()
-
-      if not cacheExists(reqId): raise newException(notFoundException, "REQUEST_NOT_FOUND")
+      if requestParams.hasKey("query"):
+        let points = (await suggestions(SuggestionsParams(
+            query: requestParams["query"],
+            results: some(results)
+          )))
 
-      cacheObj = getCacheObject(reqId)
-
-      if not cacheObj.journeys.hasKey(journeyId): raise newException(notFoundException, "JOURNEY_NOT_FOUND")
+        for point in points:
+          suggestions.add(formatPoint(point))
+    
+      var json = %* {"suggestions": suggestions}
+      await request.respondJson(Http200, "success", "", json["suggestions"])
 
+    regex(re"^\/([A-Za-z0-9]+)$"):
+      await journeysHandler(request, server)
 
-      if requestParams.hasKey("refresh"):
-        let journey = await refreshJourney(RefreshJourneyParams(
-            refreshToken: cacheObj.journeys[journeyId].refreshToken,
-            stopovers:    some(true),
-            polylines:    some(true),
-            tickets:      some(true)
-          ))
 
-        cacheObj = await updateJourney(reqId, journeyId, journey)
+    regex(re"^\/([A-Za-z0-9]+)\/([0-9-]+)$"):
+      await journeyHandler(request, server)
 
-      var templateContext = renderJourney(cacheObj, journeyId)
-      if not requestParams.hasKey("json"):
-        respTemplate(Http200, "journey", templateContext, lang)
-      else:
-        respApi(Http200, "success", "", templateContext)
+  server.start()
 
-    except notFoundException:
-      if not requestParams.hasKey("json"):
-        respError(Http404, "Nichts gefunden!", "Für diese Anfrage gibts nix.")
-      else:
-        respApi(Http404, "error", getCurrentExceptionMsg().split("\n")[0], "")
+main()
diff --git a/src/oeffi_nojs.nim b/src/oeffi_nojs.nim
@@ -1,113 +0,0 @@
-import json, os, posix
-import asyncWebServer
-
-import types
-import options
-
-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 types, backend/hafas, formaters/formaters
-
-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"])
-
-    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()