Autoformat

This commit is contained in:
Eike Kettner 2020-09-09 00:29:32 +02:00
parent 570b7de43f
commit c658677032
34 changed files with 279 additions and 319 deletions

View File

@ -26,18 +26,17 @@ object Domain {
Tld Tld
.findTld(str) .findTld(str)
.map(tld => (str.dropRight(tld.length), tld)) .map(tld => (str.dropRight(tld.length), tld))
.map({ .map({ case (names, tld) =>
case (names, tld) => names.split('.').toList match {
names.split('.').toList match { case Nil => Left(s"Not a domain: $str")
case Nil => Left(s"Not a domain: $str") case segs
case segs if segs.forall(label =>
if segs.forall(label => label.trim.nonEmpty && label
label.trim.nonEmpty && label .forall(c => c.isLetter || c.isDigit || c == '-')
.forall(c => c.isLetter || c.isDigit || c == '-') ) =>
) => Right(Domain(NonEmptyList.fromListUnsafe(segs), tld))
Right(Domain(NonEmptyList.fromListUnsafe(segs), tld)) case _ => Left(s"Not a domain: $str")
case _ => Left(s"Not a domain: $str") }
}
}) })
.getOrElse(Left(s"Not a domain $str")) .getOrElse(Left(s"Not a domain $str"))

View File

@ -39,14 +39,14 @@ object DateFind {
} }
private object SimpleDate { private object SimpleDate {
val p0 = (readYear >> readMonth >> readDay).map { val p0 = (readYear >> readMonth >> readDay).map { case ((y, m), d) =>
case ((y, m), d) => SimpleDate(y, m, d) SimpleDate(y, m, d)
} }
val p1 = (readDay >> readMonth >> readYear).map { val p1 = (readDay >> readMonth >> readYear).map { case ((d, m), y) =>
case ((d, m), y) => SimpleDate(y, m, d) SimpleDate(y, m, d)
} }
val p2 = (readMonth >> readDay >> readYear).map { val p2 = (readMonth >> readDay >> readYear).map { case ((m, d), y) =>
case ((m, d), y) => SimpleDate(y, m, d) SimpleDate(y, m, d)
} }
// ymd , ydm, dmy , dym, myd, mdy // ymd , ydm, dmy , dym, myd, mdy

View File

@ -145,10 +145,9 @@ final class StanfordTextClassifier[F[_]: Sync: ContextShift](
def prepend(pre: String, data: Map[String, String]): Map[String, String] = def prepend(pre: String, data: Map[String, String]): Map[String, String] =
data.toList data.toList
.map({ .map({ case (k, v) =>
case (k, v) => if (k.startsWith(pre)) (k, v)
if (k.startsWith(pre)) (k, v) else (pre + k, v)
else (pre + k, v)
}) })
.toMap .toMap
} }

View File

@ -29,9 +29,8 @@ object StanfordTextClassifierSuite extends SimpleTestSuite {
.repeat .repeat
.take(10) .take(10)
) )
.flatMap({ .flatMap({ case (a, b) =>
case (a, b) => Stream.emits(Seq(a, b))
Stream.emits(Seq(a, b))
}) })
.covary[IO] .covary[IO]
@ -53,23 +52,22 @@ object StanfordTextClassifierSuite extends SimpleTestSuite {
} yield (dir, blocker) } yield (dir, blocker)
things things
.use { .use { case (dir, blocker) =>
case (dir, blocker) => val classifier = new StanfordTextClassifier[IO](cfg, blocker)
val classifier = new StanfordTextClassifier[IO](cfg, blocker)
val modelFile = dir.resolve("test.ser.gz") val modelFile = dir.resolve("test.ser.gz")
for { for {
_ <- _ <-
LenientUri LenientUri
.fromJava(getClass.getResource("/test.ser.gz")) .fromJava(getClass.getResource("/test.ser.gz"))
.readURL[IO](4096, blocker) .readURL[IO](4096, blocker)
.through(fs2.io.file.writeAll(modelFile, blocker)) .through(fs2.io.file.writeAll(modelFile, blocker))
.compile .compile
.drain .drain
model = ClassifierModel(modelFile) model = ClassifierModel(modelFile)
cat <- classifier.classify(logger, model, "there is receipt always") cat <- classifier.classify(logger, model, "there is receipt always")
_ = assertEquals(cat, Some("receipt")) _ = assertEquals(cat, Some("receipt"))
} yield () } yield ()
} }
.unsafeRunSync() .unsafeRunSync()
} }

View File

@ -222,12 +222,11 @@ object LenientUri {
def percentDecode(s: String): String = def percentDecode(s: String): String =
if (!s.contains("%")) s if (!s.contains("%")) s
else else
s.foldLeft(("", ByteVector.empty)) { s.foldLeft(("", ByteVector.empty)) { case ((acc, res), c) =>
case ((acc, res), c) => if (acc.length == 2) ("", res ++ ByteVector.fromValidHex(acc.drop(1) + c))
if (acc.length == 2) ("", res ++ ByteVector.fromValidHex(acc.drop(1) + c)) else if (acc.startsWith("%")) (acc :+ c, res)
else if (acc.startsWith("%")) (acc :+ c, res) else if (c == '%') ("%", res)
else if (c == '%') ("%", res) else (acc, res :+ c.toByte)
else (acc, res :+ c.toByte)
}._2 }._2
.decodeUtf8 .decodeUtf8
.fold(throw _, identity) .fold(throw _, identity)

View File

@ -20,9 +20,8 @@ object SystemCommand {
def replace(repl: Map[String, String]): Config = def replace(repl: Map[String, String]): Config =
mapArgs(s => mapArgs(s =>
repl.foldLeft(s) { repl.foldLeft(s) { case (res, (k, v)) =>
case (res, (k, v)) => res.replace(k, v)
res.replace(k, v)
} }
) )

View File

@ -126,10 +126,9 @@ object ConversionTest extends SimpleTestSuite with FileChecks {
conversion.use { conv => conversion.use { conv =>
def check(n: Long): Handler[IO, Unit] = def check(n: Long): Handler[IO, Unit] =
storePdfTxtHandler(dir.resolve(s"test-$n.pdf"), dir.resolve(s"test-$n.txt")) storePdfTxtHandler(dir.resolve(s"test-$n.pdf"), dir.resolve(s"test-$n.txt"))
.map { .map { case (p, t) =>
case (p, t) => assert(p.isNonEmpty && p.isPDF)
assert(p.isNonEmpty && p.isPDF) assert(t.isNonEmpty && t.isPlainText)
assert(t.isNonEmpty && t.isPlainText)
} }
runConversion(pdfAndTxt, check, conv).compile.drain runConversion(pdfAndTxt, check, conv).compile.drain
@ -165,12 +164,11 @@ object ConversionTest extends SimpleTestSuite with FileChecks {
.emits(uris) .emits(uris)
.covary[IO] .covary[IO]
.zipWithIndex .zipWithIndex
.evalMap({ .evalMap({ case (uri, index) =>
case (uri, index) => val load = uri.readURL[IO](8192, blocker)
val load = uri.readURL[IO](8192, blocker) val dataType = DataType.filename(uri.path.segments.last)
val dataType = DataType.filename(uri.path.segments.last) logger.info(s"Processing file ${uri.path.asString}") *>
logger.info(s"Processing file ${uri.path.asString}") *> conv.toPDF(dataType, Language.German, handler(index))(load)
conv.toPDF(dataType, Language.German, handler(index))(load)
}) })
def commandsExist: Boolean = def commandsExist: Boolean =

View File

@ -44,14 +44,14 @@ object PoiExtract {
getDocx(data) getDocx(data)
case PoiType.msoffice => case PoiType.msoffice =>
EitherT(getDoc[F](data)) EitherT(getDoc[F](data))
.recoverWith({ .recoverWith({ case _ =>
case _ => EitherT(getXls[F](data)) EitherT(getXls[F](data))
}) })
.value .value
case PoiType.ooxml => case PoiType.ooxml =>
EitherT(getDocx[F](data)) EitherT(getDocx[F](data))
.recoverWith({ .recoverWith({ case _ =>
case _ => EitherT(getXlsx[F](data)) EitherT(getXlsx[F](data))
}) })
.value .value
case mt => case mt =>

View File

@ -14,15 +14,14 @@ object OdfExtractTest extends SimpleTestSuite {
) )
test("test extract from odt") { test("test extract from odt") {
files.foreach { files.foreach { case (file, len) =>
case (file, len) => val is = file.toJavaUrl.map(_.openStream()).fold(sys.error, identity)
val is = file.toJavaUrl.map(_.openStream()).fold(sys.error, identity) val str1 = OdfExtract.get(is).fold(throw _, identity)
val str1 = OdfExtract.get(is).fold(throw _, identity) assertEquals(str1.length, len)
assertEquals(str1.length, len)
val data = file.readURL[IO](8192, blocker) val data = file.readURL[IO](8192, blocker)
val str2 = OdfExtract.get[IO](data).unsafeRunSync().fold(throw _, identity) val str2 = OdfExtract.get[IO](data).unsafeRunSync().fold(throw _, identity)
assertEquals(str2, str1) assertEquals(str2, str1)
} }
} }

View File

@ -14,24 +14,22 @@ object PdfboxExtractTest extends SimpleTestSuite {
) )
test("extract text from text PDFs by inputstream") { test("extract text from text PDFs by inputstream") {
textPDFs.foreach { textPDFs.foreach { case (file, txt) =>
case (file, txt) => val url = file.toJavaUrl.fold(sys.error, identity)
val url = file.toJavaUrl.fold(sys.error, identity) val str = PdfboxExtract.getText(url.openStream()).fold(throw _, identity)
val str = PdfboxExtract.getText(url.openStream()).fold(throw _, identity) val received = removeFormatting(str.value)
val received = removeFormatting(str.value) val expect = removeFormatting(txt)
val expect = removeFormatting(txt) assertEquals(received, expect)
assertEquals(received, expect)
} }
} }
test("extract text from text PDFs via Stream") { test("extract text from text PDFs via Stream") {
textPDFs.foreach { textPDFs.foreach { case (file, txt) =>
case (file, txt) => val data = file.readURL[IO](8192, blocker)
val data = file.readURL[IO](8192, blocker) val str = PdfboxExtract.getText(data).unsafeRunSync().fold(throw _, identity)
val str = PdfboxExtract.getText(data).unsafeRunSync().fold(throw _, identity) val received = removeFormatting(str.value)
val received = removeFormatting(str.value) val expect = removeFormatting(txt)
val expect = removeFormatting(txt) assertEquals(received, expect)
assertEquals(received, expect)
} }
} }

View File

@ -17,23 +17,22 @@ object PoiExtractTest extends SimpleTestSuite {
) )
test("extract text from ms office files") { test("extract text from ms office files") {
officeFiles.foreach { officeFiles.foreach { case (file, len) =>
case (file, len) => val str1 = PoiExtract
val str1 = PoiExtract .get[IO](file.readURL[IO](8192, blocker), MimeTypeHint.none)
.get[IO](file.readURL[IO](8192, blocker), MimeTypeHint.none) .unsafeRunSync()
.unsafeRunSync() .fold(throw _, identity)
.fold(throw _, identity)
val str2 = PoiExtract val str2 = PoiExtract
.get[IO]( .get[IO](
file.readURL[IO](8192, blocker), file.readURL[IO](8192, blocker),
MimeTypeHint(Some(file.path.segments.last), None) MimeTypeHint(Some(file.path.segments.last), None)
) )
.unsafeRunSync() .unsafeRunSync()
.fold(throw _, identity) .fold(throw _, identity)
assertEquals(str1, str2) assertEquals(str1, str2)
assertEquals(str1.length, len) assertEquals(str1.length, len)
} }
} }
} }

View File

@ -25,22 +25,20 @@ object ImageSizeTest extends SimpleTestSuite {
) )
test("get sizes from input-stream") { test("get sizes from input-stream") {
files.foreach { files.foreach { case (uri, expect) =>
case (uri, expect) => val url = uri.toJavaUrl.fold(sys.error, identity)
val url = uri.toJavaUrl.fold(sys.error, identity) Using.resource(url.openStream()) { in =>
Using.resource(url.openStream()) { in => val dim = ImageSize.get(in)
val dim = ImageSize.get(in) assertEquals(dim, expect.some)
assertEquals(dim, expect.some) }
}
} }
} }
test("get sizes from stream") { test("get sizes from stream") {
files.foreach { files.foreach { case (uri, expect) =>
case (uri, expect) => val stream = uri.readURL[IO](8192, blocker)
val stream = uri.readURL[IO](8192, blocker) val dim = ImageSize.get(stream).unsafeRunSync()
val dim = ImageSize.get(stream).unsafeRunSync() assertEquals(dim, expect.some)
assertEquals(dim, expect.some)
} }
} }
} }

View File

@ -59,9 +59,9 @@ object Migration {
s"Applying index migration ${m.version}/${m.description} failed" s"Applying index migration ${m.version}/${m.description} failed"
) *> ) *>
ctx.store.transact(RFtsMigration.deleteById(rec.id)) *> Effect[F] ctx.store.transact(RFtsMigration.deleteById(rec.id)) *> Effect[F]
.raiseError[Unit]( .raiseError[Unit](
ex ex
) )
}) })
} yield ret).getOrElseF( } yield ret).getOrElseF(
ctx.logger.info(s"Migration ${m.version}/${m.description} already applied.") ctx.logger.info(s"Migration ${m.version}/${m.description} already applied.")

View File

@ -41,20 +41,19 @@ object CreateItem {
.flatMap(f => ctx.store.bitpeace.get(f.fileMetaId.id).map(fm => (f, fm))) .flatMap(f => ctx.store.bitpeace.get(f.fileMetaId.id).map(fm => (f, fm)))
.collect({ case (f, Some(fm)) if isValidFile(fm) => f }) .collect({ case (f, Some(fm)) if isValidFile(fm) => f })
.zipWithIndex .zipWithIndex
.evalMap({ .evalMap({ case (f, index) =>
case (f, index) => Ident
Ident .randomId[F]
.randomId[F] .map(id =>
.map(id => RAttachment(
RAttachment( id,
id, itemId,
itemId, f.fileMetaId,
f.fileMetaId, index.toInt + offset,
index.toInt + offset, now,
now, f.name
f.name
)
) )
)
}) })
} }
.compile .compile

View File

@ -82,10 +82,9 @@ object FindProposal {
def removeDuplicates(labels: List[NerLabel]): List[NerLabel] = def removeDuplicates(labels: List[NerLabel]): List[NerLabel] =
labels labels
.sortBy(_.startPosition) .sortBy(_.startPosition)
.foldLeft((Set.empty[String], List.empty[NerLabel])) { .foldLeft((Set.empty[String], List.empty[NerLabel])) { case ((seen, result), el) =>
case ((seen, result), el) => if (seen.contains(el.tag.name + el.label.toLowerCase)) (seen, result)
if (seen.contains(el.tag.name + el.label.toLowerCase)) (seen, result) else (seen + (el.tag.name + el.label.toLowerCase), el :: result)
else (seen + (el.tag.name + el.label.toLowerCase), el :: result)
} }
._2 ._2

View File

@ -14,17 +14,16 @@ object InfoRoutes {
def apply[F[_]: Sync](): HttpRoutes[F] = { def apply[F[_]: Sync](): HttpRoutes[F] = {
val dsl = new Http4sDsl[F] {} val dsl = new Http4sDsl[F] {}
import dsl._ import dsl._
HttpRoutes.of[F] { HttpRoutes.of[F] { case GET -> (Root / "version") =>
case GET -> (Root / "version") => Ok(
Ok( VersionInfo(
VersionInfo( BuildInfo.version,
BuildInfo.version, BuildInfo.builtAtMillis,
BuildInfo.builtAtMillis, BuildInfo.builtAtString,
BuildInfo.builtAtString, BuildInfo.gitHeadCommit.getOrElse(""),
BuildInfo.gitHeadCommit.getOrElse(""), BuildInfo.gitDescribedVersion.getOrElse("")
BuildInfo.gitDescribedVersion.getOrElse("")
)
) )
)
} }
} }
} }

View File

@ -46,9 +46,8 @@ object Config {
pattern == ip || (inet.isLoopbackAddress && pattern == "127.0.0.1") || (pattern pattern == ip || (inet.isLoopbackAddress && pattern == "127.0.0.1") || (pattern
.split('.') .split('.')
.zip(ipParts) .zip(ipParts)
.foldLeft(true) { .foldLeft(true) { case (r, (a, b)) =>
case (r, (a, b)) => r && (a == "*" || a == b)
r && (a == "*" || a == b)
}) })
ips.exists(checkSingle) ips.exists(checkSingle)

View File

@ -99,13 +99,12 @@ object RestServer {
val dsl = new Http4sDsl[F] {} val dsl = new Http4sDsl[F] {}
import dsl._ import dsl._
HttpRoutes.of { HttpRoutes.of { case GET -> Root =>
case GET -> Root => Response[F](
Response[F]( Status.SeeOther,
Status.SeeOther, body = Stream.empty,
body = Stream.empty, headers = Headers.of(Location(Uri(path = path)))
headers = Headers.of(Location(Uri(path = path))) ).pure[F]
).pure[F]
} }
} }
} }

View File

@ -441,9 +441,8 @@ trait Conversions {
oid: Option[Ident], oid: Option[Ident],
pid: Option[Ident] pid: Option[Ident]
): F[RContact] = ): F[RContact] =
timeId.map { timeId.map { case (id, now) =>
case (id, now) => RContact(id, c.value, c.kind, pid, oid, now)
RContact(id, c.value, c.kind, pid, oid, now)
} }
// users // users
@ -460,19 +459,18 @@ trait Conversions {
) )
def newUser[F[_]: Sync](u: User, cid: Ident): F[RUser] = def newUser[F[_]: Sync](u: User, cid: Ident): F[RUser] =
timeId.map { timeId.map { case (id, now) =>
case (id, now) => RUser(
RUser( id,
id, u.login,
u.login, cid,
cid, u.password.getOrElse(Password.empty),
u.password.getOrElse(Password.empty), u.state,
u.state, u.email,
u.email, 0,
0, None,
None, now
now )
)
} }
def changeUser(u: User, cid: Ident): RUser = def changeUser(u: User, cid: Ident): RUser =
@ -494,9 +492,8 @@ trait Conversions {
Tag(rt.tagId, rt.name, rt.category, rt.created) Tag(rt.tagId, rt.name, rt.category, rt.created)
def newTag[F[_]: Sync](t: Tag, cid: Ident): F[RTag] = def newTag[F[_]: Sync](t: Tag, cid: Ident): F[RTag] =
timeId.map { timeId.map { case (id, now) =>
case (id, now) => RTag(id, cid, t.name, t.category, now)
RTag(id, cid, t.name, t.category, now)
} }
def changeTag(t: Tag, cid: Ident): RTag = def changeTag(t: Tag, cid: Ident): RTag =
@ -517,9 +514,8 @@ trait Conversions {
) )
def newSource[F[_]: Sync](s: Source, cid: Ident): F[RSource] = def newSource[F[_]: Sync](s: Source, cid: Ident): F[RSource] =
timeId.map({ timeId.map({ case (id, now) =>
case (id, now) => RSource(id, cid, s.abbrev, s.description, 0, s.enabled, s.priority, now, s.folder)
RSource(id, cid, s.abbrev, s.description, 0, s.enabled, s.priority, now, s.folder)
}) })
def changeSource[F[_]: Sync](s: Source, coll: Ident): RSource = def changeSource[F[_]: Sync](s: Source, coll: Ident): RSource =
@ -540,9 +536,8 @@ trait Conversions {
Equipment(re.eid, re.name, re.created) Equipment(re.eid, re.name, re.created)
def newEquipment[F[_]: Sync](e: Equipment, cid: Ident): F[REquipment] = def newEquipment[F[_]: Sync](e: Equipment, cid: Ident): F[REquipment] =
timeId.map({ timeId.map({ case (id, now) =>
case (id, now) => REquipment(id, cid, e.name, now, now)
REquipment(id, cid, e.name, now, now)
}) })
def changeEquipment[F[_]: Sync](e: Equipment, cid: Ident): F[REquipment] = def changeEquipment[F[_]: Sync](e: Equipment, cid: Ident): F[REquipment] =

View File

@ -18,13 +18,12 @@ object CalEventCheckRoutes {
val dsl = new Http4sDsl[F] {} val dsl = new Http4sDsl[F] {}
import dsl._ import dsl._
HttpRoutes.of { HttpRoutes.of { case req @ POST -> Root =>
case req @ POST -> Root => for {
for { data <- req.as[CalEventCheck]
data <- req.as[CalEventCheck] res <- testEvent(data.event)
res <- testEvent(data.event) resp <- Ok(res)
resp <- Ok(res) } yield resp
} yield resp
} }
} }

View File

@ -20,13 +20,12 @@ object CheckFileRoutes {
val dsl = new Http4sDsl[F] with ResponseGenerator[F] {} val dsl = new Http4sDsl[F] with ResponseGenerator[F] {}
import dsl._ import dsl._
HttpRoutes.of { HttpRoutes.of { case GET -> Root / checksum =>
case GET -> Root / checksum => for {
for { items <-
items <- backend.itemSearch.findByFileCollective(checksum, user.account.collective)
backend.itemSearch.findByFileCollective(checksum, user.account.collective) resp <- Ok(convert(items))
resp <- Ok(convert(items)) } yield resp
} yield resp
} }
} }
@ -35,12 +34,11 @@ object CheckFileRoutes {
val dsl = new Http4sDsl[F] with ResponseGenerator[F] {} val dsl = new Http4sDsl[F] with ResponseGenerator[F] {}
import dsl._ import dsl._
HttpRoutes.of { HttpRoutes.of { case GET -> Root / Ident(id) / checksum =>
case GET -> Root / Ident(id) / checksum => for {
for { items <- backend.itemSearch.findByFileSource(checksum, id)
items <- backend.itemSearch.findByFileSource(checksum, id) resp <- Ok(convert(items))
resp <- Ok(convert(items)) } yield resp
} yield resp
} }
} }

View File

@ -26,13 +26,11 @@ object FullTextIndexRoutes {
val dsl = Http4sDsl[F] val dsl = Http4sDsl[F]
import dsl._ import dsl._
HttpRoutes.of { HttpRoutes.of { case POST -> Root / "reIndex" =>
case POST -> Root / "reIndex" => for {
for { res <- backend.fulltext.reindexCollective(user.account).attempt
res <- backend.fulltext.reindexCollective(user.account).attempt resp <- Ok(Conversions.basicResult(res, "Full-text index will be re-created."))
resp <- } yield resp
Ok(Conversions.basicResult(res, "Full-text index will be re-created."))
} yield resp
} }
} }
@ -42,16 +40,14 @@ object FullTextIndexRoutes {
val dsl = Http4sDsl[F] val dsl = Http4sDsl[F]
import dsl._ import dsl._
HttpRoutes.of { HttpRoutes.of { case POST -> Root / "reIndexAll" / Ident(id) =>
case POST -> Root / "reIndexAll" / Ident(id) => for {
for { res <-
res <- if (id.nonEmpty && id == cfg.fullTextSearch.recreateKey)
if (id.nonEmpty && id == cfg.fullTextSearch.recreateKey) backend.fulltext.reindexAll.attempt
backend.fulltext.reindexAll.attempt else Left(new Exception("The provided key is invalid.")).pure[F]
else Left(new Exception("The provided key is invalid.")).pure[F] resp <- Ok(Conversions.basicResult(res, "Full-text index will be re-created."))
resp <- } yield resp
Ok(Conversions.basicResult(res, "Full-text index will be re-created."))
} yield resp
} }
} }

View File

@ -14,17 +14,16 @@ object InfoRoutes {
def apply[F[_]: Sync](): HttpRoutes[F] = { def apply[F[_]: Sync](): HttpRoutes[F] = {
val dsl = new Http4sDsl[F] {} val dsl = new Http4sDsl[F] {}
import dsl._ import dsl._
HttpRoutes.of[F] { HttpRoutes.of[F] { case GET -> (Root / "version") =>
case GET -> (Root / "version") => Ok(
Ok( VersionInfo(
VersionInfo( BuildInfo.version,
BuildInfo.version, BuildInfo.builtAtMillis,
BuildInfo.builtAtMillis, BuildInfo.builtAtString,
BuildInfo.builtAtString, BuildInfo.gitHeadCommit.getOrElse(""),
BuildInfo.gitHeadCommit.getOrElse(""), BuildInfo.gitDescribedVersion.getOrElse("")
BuildInfo.gitDescribedVersion.getOrElse("")
)
) )
)
} }
} }
} }

View File

@ -19,13 +19,12 @@ object LoginRoutes {
val dsl: Http4sDsl[F] = new Http4sDsl[F] {} val dsl: Http4sDsl[F] = new Http4sDsl[F] {}
import dsl._ import dsl._
HttpRoutes.of[F] { HttpRoutes.of[F] { case req @ POST -> Root / "login" =>
case req @ POST -> Root / "login" => for {
for { up <- req.as[UserPass]
up <- req.as[UserPass] res <- S.loginUserPass(cfg.auth)(Login.UserPass(up.account, up.password))
res <- S.loginUserPass(cfg.auth)(Login.UserPass(up.account, up.password)) resp <- makeResponse(dsl, cfg, res, up.account)
resp <- makeResponse(dsl, cfg, res, up.account) } yield resp
} yield resp
} }
} }

View File

@ -23,17 +23,16 @@ object MailSendRoutes {
val dsl = new Http4sDsl[F] {} val dsl = new Http4sDsl[F] {}
import dsl._ import dsl._
HttpRoutes.of { HttpRoutes.of { case req @ POST -> Root / Ident(name) / Ident(id) =>
case req @ POST -> Root / Ident(name) / Ident(id) => for {
for { in <- req.as[SimpleMail]
in <- req.as[SimpleMail] mail = convertIn(id, in)
mail = convertIn(id, in) res <- mail.traverse(m => backend.mail.sendMail(user.account, name, m))
res <- mail.traverse(m => backend.mail.sendMail(user.account, name, m)) resp <- res.fold(
resp <- res.fold( err => Ok(BasicResult(false, s"Invalid mail data: $err")),
err => Ok(BasicResult(false, s"Invalid mail data: $err")), res => Ok(convertOut(res))
res => Ok(convertOut(res)) )
) } yield resp
} yield resp
} }
} }

View File

@ -40,20 +40,18 @@ object TemplateRoutes {
import dsl._ import dsl._
new InnerRoutes[F] { new InnerRoutes[F] {
def doc = def doc =
HttpRoutes.of[F] { HttpRoutes.of[F] { case GET -> Root =>
case GET -> Root => for {
for { templ <- docTemplate
templ <- docTemplate resp <- Ok(DocData().render(templ), `Content-Type`(`text/html`))
resp <- Ok(DocData().render(templ), `Content-Type`(`text/html`)) } yield resp
} yield resp
} }
def app = def app =
HttpRoutes.of[F] { HttpRoutes.of[F] { case GET -> _ =>
case GET -> _ => for {
for { templ <- indexTemplate
templ <- indexTemplate resp <- Ok(IndexData(cfg).render(templ), `Content-Type`(`text/html`))
resp <- Ok(IndexData(cfg).render(templ), `Content-Type`(`text/html`)) } yield resp
} yield resp
} }
} }
} }

View File

@ -56,8 +56,8 @@ trait DoobieSyntax {
def insertRows(table: Fragment, cols: List[Column], vals: List[Fragment]): Fragment = def insertRows(table: Fragment, cols: List[Column], vals: List[Fragment]): Fragment =
Fragment.const("INSERT INTO ") ++ table ++ Fragment.const(" (") ++ Fragment.const("INSERT INTO ") ++ table ++ Fragment.const(" (") ++
commas(cols.map(_.f)) ++ Fragment.const(") VALUES ") ++ commas( commas(cols.map(_.f)) ++ Fragment.const(") VALUES ") ++ commas(
vals.map(f => sql"(" ++ f ++ sql")") vals.map(f => sql"(" ++ f ++ sql")")
) )
def selectSimple(cols: Seq[Column], table: Fragment, where: Fragment): Fragment = def selectSimple(cols: Seq[Column], table: Fragment, where: Fragment): Fragment =
selectSimple(commas(cols.map(_.f)), table, where) selectSimple(commas(cols.map(_.f)), table, where)

View File

@ -103,11 +103,11 @@ object QAttachment {
.prefix("m") .prefix("m")
.f ++ fr"FROM" ++ RAttachmentMeta.table ++ fr"m" ++ .f ++ fr"FROM" ++ RAttachmentMeta.table ++ fr"m" ++
fr"INNER JOIN" ++ RAttachment.table ++ fr"a ON" ++ AC.id fr"INNER JOIN" ++ RAttachment.table ++ fr"a ON" ++ AC.id
.prefix("a") .prefix("a")
.is(MC.id.prefix("m")) ++ .is(MC.id.prefix("m")) ++
fr"INNER JOIN" ++ RItem.table ++ fr"i ON" ++ AC.itemId fr"INNER JOIN" ++ RItem.table ++ fr"i ON" ++ AC.itemId
.prefix("a") .prefix("a")
.is(IC.id.prefix("i")) ++ .is(IC.id.prefix("i")) ++
fr"WHERE" ++ and(AC.itemId.prefix("a").is(itemId), IC.cid.prefix("i").is(coll)) fr"WHERE" ++ and(AC.itemId.prefix("a").is(itemId), IC.cid.prefix("i").is(coll))
for { for {
@ -128,15 +128,15 @@ object QAttachment {
MC.all.map(_.prefix("m").f) MC.all.map(_.prefix("m").f)
) ++ fr"FROM" ++ RItem.table ++ fr"i" ++ ) ++ fr"FROM" ++ RItem.table ++ fr"i" ++
fr"INNER JOIN" ++ RAttachment.table ++ fr"a ON" ++ IC.id fr"INNER JOIN" ++ RAttachment.table ++ fr"a ON" ++ IC.id
.prefix("i") .prefix("i")
.is(AC.itemId.prefix("a")) ++ .is(AC.itemId.prefix("a")) ++
fr"INNER JOIN" ++ RAttachmentMeta.table ++ fr"m ON" ++ AC.id fr"INNER JOIN" ++ RAttachmentMeta.table ++ fr"m ON" ++ AC.id
.prefix("a") .prefix("a")
.is(MC.id.prefix("m")) ++ .is(MC.id.prefix("m")) ++
fr"WHERE" ++ and( fr"WHERE" ++ and(
AC.id.prefix("a").is(attachId), AC.id.prefix("a").is(attachId),
IC.cid.prefix("i").is(collective) IC.cid.prefix("i").is(collective)
) )
q.query[RAttachmentMeta].option q.query[RAttachmentMeta].option
} }

View File

@ -82,14 +82,14 @@ object QCollective {
) ++ ) ++
fr"FROM" ++ RTagItem.table ++ fr"r" ++ fr"FROM" ++ RTagItem.table ++ fr"r" ++
fr"INNER JOIN" ++ RTag.table ++ fr"t ON" ++ RC.tagId fr"INNER JOIN" ++ RTag.table ++ fr"t ON" ++ RC.tagId
.prefix("r") .prefix("r")
.is(TC.tid.prefix("t")) ++ .is(TC.tid.prefix("t")) ++
fr"WHERE" ++ TC.cid.prefix("t").is(coll) ++ fr"WHERE" ++ TC.cid.prefix("t").is(coll) ++
fr"GROUP BY" ++ commas( fr"GROUP BY" ++ commas(
TC.name.prefix("t").f, TC.name.prefix("t").f,
TC.tid.prefix("t").f, TC.tid.prefix("t").f,
TC.category.prefix("t").f TC.category.prefix("t").f
) )
q3.query[TagCount].to[List] q3.query[TagCount].to[List]
} }

View File

@ -94,23 +94,23 @@ object QItem {
Fragment.empty Fragment.empty
) ++ ) ++
fr"LEFT JOIN" ++ ROrganization.table ++ fr"o ON" ++ RItem.Columns.corrOrg fr"LEFT JOIN" ++ ROrganization.table ++ fr"o ON" ++ RItem.Columns.corrOrg
.prefix("i") .prefix("i")
.is(ROrganization.Columns.oid.prefix("o")) ++ .is(ROrganization.Columns.oid.prefix("o")) ++
fr"LEFT JOIN" ++ RPerson.table ++ fr"p0 ON" ++ RItem.Columns.corrPerson fr"LEFT JOIN" ++ RPerson.table ++ fr"p0 ON" ++ RItem.Columns.corrPerson
.prefix("i") .prefix("i")
.is(RPerson.Columns.pid.prefix("p0")) ++ .is(RPerson.Columns.pid.prefix("p0")) ++
fr"LEFT JOIN" ++ RPerson.table ++ fr"p1 ON" ++ RItem.Columns.concPerson fr"LEFT JOIN" ++ RPerson.table ++ fr"p1 ON" ++ RItem.Columns.concPerson
.prefix("i") .prefix("i")
.is(RPerson.Columns.pid.prefix("p1")) ++ .is(RPerson.Columns.pid.prefix("p1")) ++
fr"LEFT JOIN" ++ REquipment.table ++ fr"e ON" ++ RItem.Columns.concEquipment fr"LEFT JOIN" ++ REquipment.table ++ fr"e ON" ++ RItem.Columns.concEquipment
.prefix("i") .prefix("i")
.is(REquipment.Columns.eid.prefix("e")) ++ .is(REquipment.Columns.eid.prefix("e")) ++
fr"LEFT JOIN" ++ RItem.table ++ fr"ref ON" ++ RItem.Columns.inReplyTo fr"LEFT JOIN" ++ RItem.table ++ fr"ref ON" ++ RItem.Columns.inReplyTo
.prefix("i") .prefix("i")
.is(RItem.Columns.id.prefix("ref")) ++ .is(RItem.Columns.id.prefix("ref")) ++
fr"LEFT JOIN" ++ RFolder.table ++ fr"f ON" ++ RItem.Columns.folder fr"LEFT JOIN" ++ RFolder.table ++ fr"f ON" ++ RItem.Columns.folder
.prefix("i") .prefix("i")
.is(RFolder.Columns.id.prefix("f")) ++ .is(RFolder.Columns.id.prefix("f")) ++
fr"WHERE" ++ RItem.Columns.id.prefix("i").is(id) fr"WHERE" ++ RItem.Columns.id.prefix("i").is(id)
val q = cq val q = cq
@ -312,8 +312,8 @@ object QItem {
fr"LEFT JOIN orgs o0 ON" ++ IC.corrOrg.prefix("i").is(OC.oid.prefix("o0")) ++ fr"LEFT JOIN orgs o0 ON" ++ IC.corrOrg.prefix("i").is(OC.oid.prefix("o0")) ++
fr"LEFT JOIN persons p1 ON" ++ IC.concPerson.prefix("i").is(PC.pid.prefix("p1")) ++ fr"LEFT JOIN persons p1 ON" ++ IC.concPerson.prefix("i").is(PC.pid.prefix("p1")) ++
fr"LEFT JOIN equips e1 ON" ++ IC.concEquipment fr"LEFT JOIN equips e1 ON" ++ IC.concEquipment
.prefix("i") .prefix("i")
.is(EC.eid.prefix("e1")) ++ .is(EC.eid.prefix("e1")) ++
fr"LEFT JOIN folders f1 ON" ++ IC.folder.prefix("i").is(FC.id.prefix("f1")) fr"LEFT JOIN folders f1 ON" ++ IC.folder.prefix("i").is(FC.id.prefix("f1"))
} }

View File

@ -45,10 +45,9 @@ object QOrganization {
.query[(ROrganization, Option[RContact])] .query[(ROrganization, Option[RContact])]
.stream .stream
.groupAdjacentBy(_._1) .groupAdjacentBy(_._1)
.map({ .map({ case (ro, chunk) =>
case (ro, chunk) => val cs = chunk.toVector.flatMap(_._2)
val cs = chunk.toVector.flatMap(_._2) (ro, cs)
(ro, cs)
}) })
} }
@ -71,10 +70,9 @@ object QOrganization {
.query[(ROrganization, Option[RContact])] .query[(ROrganization, Option[RContact])]
.stream .stream
.groupAdjacentBy(_._1) .groupAdjacentBy(_._1)
.map({ .map({ case (ro, chunk) =>
case (ro, chunk) => val cs = chunk.toVector.flatMap(_._2)
val cs = chunk.toVector.flatMap(_._2) (ro, cs)
(ro, cs)
}) })
.compile .compile
.last .last
@ -109,10 +107,9 @@ object QOrganization {
.query[(RPerson, Option[RContact])] .query[(RPerson, Option[RContact])]
.stream .stream
.groupAdjacentBy(_._1) .groupAdjacentBy(_._1)
.map({ .map({ case (ro, chunk) =>
case (ro, chunk) => val cs = chunk.toVector.flatMap(_._2)
val cs = chunk.toVector.flatMap(_._2) (ro, cs)
(ro, cs)
}) })
} }
@ -135,10 +132,9 @@ object QOrganization {
.query[(RPerson, Option[RContact])] .query[(RPerson, Option[RContact])]
.stream .stream
.groupAdjacentBy(_._1) .groupAdjacentBy(_._1)
.map({ .map({ case (ro, chunk) =>
case (ro, chunk) => val cs = chunk.toVector.flatMap(_._2)
val cs = chunk.toVector.flatMap(_._2) (ro, cs)
(ro, cs)
}) })
.compile .compile
.last .last

View File

@ -152,8 +152,8 @@ object RAttachment {
): ConnectionIO[Vector[RAttachment]] = { ): ConnectionIO[Vector[RAttachment]] = {
val q = selectSimple(all.map(_.prefix("a")), table ++ fr"a", Fragment.empty) ++ val q = selectSimple(all.map(_.prefix("a")), table ++ fr"a", Fragment.empty) ++
fr"INNER JOIN" ++ RItem.table ++ fr"i ON" ++ RItem.Columns.id fr"INNER JOIN" ++ RItem.table ++ fr"i ON" ++ RItem.Columns.id
.prefix("i") .prefix("i")
.is(itemId.prefix("a")) ++ .is(itemId.prefix("a")) ++
fr"WHERE" ++ and(itemId.prefix("a").is(id), RItem.Columns.cid.prefix("i").is(coll)) fr"WHERE" ++ and(itemId.prefix("a").is(id), RItem.Columns.cid.prefix("i").is(coll))
q.query[RAttachment].to[Vector] q.query[RAttachment].to[Vector]
} }

View File

@ -106,13 +106,13 @@ object ROrganization {
val q = fr"SELECT DISTINCT" ++ commas(oid.prefix("o").f, name.prefix("o").f) ++ val q = fr"SELECT DISTINCT" ++ commas(oid.prefix("o").f, name.prefix("o").f) ++
fr"FROM" ++ table ++ fr"o" ++ fr"FROM" ++ table ++ fr"o" ++
fr"INNER JOIN" ++ RContact.table ++ fr"c ON" ++ CC.orgId fr"INNER JOIN" ++ RContact.table ++ fr"c ON" ++ CC.orgId
.prefix("c") .prefix("c")
.is(oid.prefix("o")) ++ .is(oid.prefix("o")) ++
fr"WHERE" ++ and( fr"WHERE" ++ and(
cid.prefix("o").is(coll), cid.prefix("o").is(coll),
CC.kind.prefix("c").is(contactKind), CC.kind.prefix("c").is(contactKind),
CC.value.prefix("c").lowerLike(value) CC.value.prefix("c").lowerLike(value)
) )
q.query[IdRef].to[Vector] q.query[IdRef].to[Vector]
} }

View File

@ -128,14 +128,14 @@ object RPerson {
val q = fr"SELECT DISTINCT" ++ commas(pid.prefix("p").f, name.prefix("p").f) ++ val q = fr"SELECT DISTINCT" ++ commas(pid.prefix("p").f, name.prefix("p").f) ++
fr"FROM" ++ table ++ fr"p" ++ fr"FROM" ++ table ++ fr"p" ++
fr"INNER JOIN" ++ RContact.table ++ fr"c ON" ++ CC.personId fr"INNER JOIN" ++ RContact.table ++ fr"c ON" ++ CC.personId
.prefix("c") .prefix("c")
.is(pid.prefix("p")) ++ .is(pid.prefix("p")) ++
fr"WHERE" ++ and( fr"WHERE" ++ and(
cid.prefix("p").is(coll), cid.prefix("p").is(coll),
CC.kind.prefix("c").is(contactKind), CC.kind.prefix("c").is(contactKind),
concerning.prefix("p").is(concerningOnly), concerning.prefix("p").is(concerningOnly),
CC.value.prefix("c").lowerLike(value) CC.value.prefix("c").lowerLike(value)
) )
q.query[IdRef].to[Vector] q.query[IdRef].to[Vector]
} }