aboutsummaryrefslogtreecommitdiff
path: root/server/src/net/usebox/gemini/server/handlers/ProtocolHandler.scala
blob: b89d040e8b4d8c59620e18a811e8504b3e7a4003 (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
39
40
41
package net.usebox.gemini.server.handlers

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

import scala.util.Try

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

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(Option(Files.probeContentType(path))).toOption.flatten match {
            case Some(mime) => 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
}