package io.github.nafg.dialoguestate.twilio.base import scala.reflect.ClassTag import io.github.nafg.dialoguestate.CallState import zio.http.* import zio.http.codec.{BinaryCodecWithSchema, HttpContentCodec, TextBinaryCodec} import zio.http.endpoint.{AuthType, Endpoint} import zio.schema.Schema import zio.{IO, Ref, ZIO} abstract class StatusRoute[ParamsType <: StatusRoute.Params: HttpContentCodec, StateType <: CallState]( val path: Path, stateType: StatusRoute.StateType[StateType] ) { protected def handle(params: ParamsType, state: StateType): ZIO[Any, String, Boolean] private def endpoint: Endpoint[Unit, ParamsType, String, String, AuthType.None] = Endpoint(RoutePattern.POST / path.encode) .in[ParamsType] .out[String] .outError[String](Status.NotFound) /** Serves this endpoint. Each status received is passed to `handle`, along with the state of the status's call in * `callsStates`. Responds 404 with the failure message if that call is unknown, isn't in the state this endpoint * expects, or `handle` fails. */ def route(callsStates: Ref[Map[String, CallState]]): Route[Any, Nothing] = endpoint.implement { params => val sid = params.callSid for { states <- callsStates.get maybeState = states.get(sid) _ <- ZIO.logDebug(s"Call $sid state: $maybeState") callState <- ZIO.getOrFailWith(s"Call $sid not found")(maybeState) state <- stateType.extractZIO(sid, callState) updated <- handle(params, state) } yield s"updated=$updated" } } object StatusRoute { private implicit val queryParamsFromStringSchema: Schema[QueryParams] = Schema[String] .transformOrFail[Form]( s => Form.fromURLEncoded(s, Charsets.Http).left.map(_.message), form => Right(form.urlEncoded) ) .transform[QueryParams](_.toQueryParams, _.toForm) private def formCodec[A: Schema]: HttpContentCodec[A] = HttpContentCodec.from( MediaType.application.`x-www-form-urlencoded` -> BinaryCodecWithSchema .fromBinaryCodec(TextBinaryCodec.fromSchema[A]) ) private val urlSchema: Schema[URL] = Schema[String] .transformOrFail(URL.decode(_).left.map(_.getMessage), url => Right(url.encode)) private val statusSchema: Schema[Boolean] = Schema[String] .transform(_ == "completed", if (_) "completed" else "failed") /** The parameters a provider posts to a status endpoint */ sealed trait Params { def callSid: String } object Params { case class Recording(callSid: String, recordingUrl: Option[URL]) extends Params object Recording { implicit def schema(implicit queryParamsSchema: Schema[QueryParams]): Schema[Recording] = queryParamsSchema.transformOrFail[Recording]( params => (for { callSid <- params.query[String]("CallSid") succeeded <- params.query("RecordingStatus")(using statusSchema) recordingUrl <- if (succeeded) params.query("RecordingUrl")(using urlSchema).map(Some(_)) else Right(None) } yield Recording(callSid, recordingUrl)).left.map(_.message), { case Recording(callSid, None) => Right(QueryParams("CallSid" -> callSid, "RecordingStatus" -> "failed")) case Recording(callSid, Some(recordingUrl)) => Right( QueryParams( "CallSid" -> callSid, "RecordingStatus" -> "completed", "RecordingUrl" -> recordingUrl.encode ) ) } ) implicit val httpContentCodec: HttpContentCodec[Recording] = formCodec[Recording] } case class Transcription(callSid: String, recordingUrl: URL, transcriptionText: Option[String]) extends Params object Transcription { implicit def schema(implicit queryParamsSchema: Schema[QueryParams]): Schema[Transcription] = queryParamsSchema.transformOrFail[Transcription]( params => (for { callSid <- params.query[String]("CallSid") url <- params.query("RecordingUrl")(using urlSchema) succeeded <- params.query("TranscriptionStatus")(using statusSchema) transcriptionText <- if (succeeded) params.query[String]("TranscriptionText").map(Some(_)) else Right(None) } yield Transcription(callSid, url, transcriptionText)).left.map(_.message), { case Transcription(callSid, recordingUrl, None) => Right( QueryParams( "CallSid" -> callSid, "RecordingUrl" -> recordingUrl.encode, "TranscriptionStatus" -> "failed" ) ) case Transcription(callSid, recordingUrl, Some(transcriptionText)) => Right( QueryParams( "CallSid" -> callSid, "RecordingUrl" -> recordingUrl.encode, "TranscriptionStatus" -> "completed", "TranscriptionText" -> transcriptionText ) ) } ) implicit val httpContentCodec: HttpContentCodec[Transcription] = formCodec[Transcription] } } /** The state a call must be awaiting, for a status endpoint to handle a status about it */ sealed abstract class StateType[A <: CallState: ClassTag](val noun: String) { def extractZIO(sid: String, callState: CallState): IO[String, A] = callState match { case state: A => ZIO.succeed(state) case _ => ZIO.fail(s"Call $sid was not awaiting a $noun") } } object StateType { case object Recording extends StateType[CallState.AwaitingRecording]("recording") case object TranscribedRecording extends StateType[CallState.AwaitingTranscribedRecording]("transcribed recording") } }