aboutsummaryrefslogtreecommitdiff
path: root/server/src/net/usebox/gemini/server/handlers/ProtocolHandler.scala
blob: f36dc7fc5062149f71afad67c036e9ff1016d2d4 (plain)
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
package net.usebox.gemini.server.handlers

import java.net.URI
import java.nio.file.{Path, Files}

import scala.util.Try

import net.usebox.gemini.server.{ServiceConf, Response}

abstract class ProtocolHandler(conf: ServiceConf) {

  private val defaultMimeType = conf.defaultMimeType
  val vHosts = conf.virtualHosts

  def guessMimeType(path: Path, params: Option[String]): String =
    conf.mimeTypes.fold {
      List(".gmi", ".gemini")
        .find(path.toString().endsWith(_))
        .fold {
          Try(Files.probeContentType(path)).toOption match {
            case Some(mime) if mime != null => mime
            case _                          => defaultMimeType
          }
        }(_ => "text/gemini")
    } { types =>
      types
        .find {
          case (t, exts) => exts.exists(path.toString().endsWith(_))
        }
        .fold(defaultMimeType) { case (t, _) => t }
    } match {
      case mime @ "text/gemini" =>
        params.fold(mime)(p => s"$mime; ${p.stripMargin(';').trim()}")
      case mime => mime
    }

  def handle(req: String, uri: URI, remoteAddr: String): Response
}