summaryrefslogtreecommitdiff
path: root/crashbox-server/src/main/scala/io/crashbox/ci/StreamStore.scala
blob: bba3cdf35f4a56296cbe75b899febc682ad273b1 (plain) (blame)
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 io.crashbox.ci

import java.io.{
  File,
  FileInputStream,
  FileOutputStream,
  InputStream,
  OutputStream
}
import java.security.MessageDigest

trait StreamStore { self: Core =>

  val streamsDirectory: File = new File(
    config.getString("crashbox.streams.directory"))

  private def logFile(id: String): File = {
    val bytes = MessageDigest.getInstance("SHA-256").digest(id.getBytes)
    val str = bytes.map { byte =>
      Integer.toString((byte & 0xff) + 0x100, 16)
    }.mkString
    val (head, tail) = str.splitAt(2)
    new File(streamsDirectory, s"$head/$tail")
  }

  def saveStream(id: String): OutputStream = {
    val file = logFile(id)
    file.getParentFile.mkdirs()
    file.createNewFile()
    file.setWritable(true)
    new FileOutputStream(file)
  }

  def readStream(id: String): InputStream = {
    new FileInputStream(logFile(id))
  }

}