search functionality, kinda hacky

This commit is contained in:
Will Freeman
2024-10-04 15:09:41 -05:00
parent 64da95d76a
commit 0f432e724f
4 changed files with 150 additions and 5 deletions
@@ -13,8 +13,9 @@ import pekko.http.scaladsl.server.Directives.{path, _}
import org.apache.pekko.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import org.apache.pekko.http.scaladsl.server.RejectionHandler
import scala.concurrent.{Await, ExecutionContextExecutor, Future}
import scala.concurrent.duration._
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import scala.concurrent.ExecutionContextExecutor
import scala.io.StdIn
object ShotgunServer {
@@ -26,6 +27,7 @@ object ShotgunServer {
val logging = Logging(system, getClass)
val client = new services.OverpassClient()
val nominatim = new services.NominatimClient()
// CORS
val allowedOrigins = List(
@@ -60,6 +62,16 @@ object ShotgunServer {
}
}
},
path("geocode") {
get {
parameters("query".as[String]) { query =>
val encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8.toString)
onSuccess(nominatim.geocodePhrase(encodedQuery)) { json =>
complete(json)
}
}
}
},
path("oauth2" / "callback") {
get {
parameters(Symbol("code").?) { (code) =>
@@ -0,0 +1,32 @@
package services
import org.apache.pekko
import org.apache.pekko.actor.ActorSystem
import pekko.http.scaladsl.Http
import pekko.http.scaladsl.model._
import pekko.http.scaladsl.unmarshalling.Unmarshal
import spray.json._
import scala.concurrent.{ExecutionContextExecutor, Future}
class NominatimClient(implicit val system: ActorSystem, implicit val executionContext: ExecutionContextExecutor) {
val baseUrl = "https://nominatim.openstreetmap.org/search"
def geocodePhrase(query: String): Future[JsValue] = {
val request = HttpRequest(
uri = s"$baseUrl?q=$query&format=json",
headers = List(headers.`User-Agent`("DeFlock/1.0"))
)
Http().singleRequest(request).flatMap { response =>
response.status match {
case StatusCodes.OK =>
Unmarshal(response.entity).to[String].map { jsonString =>
jsonString.parseJson
}
case _ =>
response.discardEntityBytes()
Future.failed(new Exception(s"Failed to geocode phrase: ${response.status}"))
}
}
}
}