mirror of
https://github.com/dyrkin/luxmed-bot.git
synced 2025-12-24 06:28:37 +01:00
Use scala-logging
This commit is contained in:
committed by
Yevhen Zadyra
parent
07172866d9
commit
de3c2ad9b1
@@ -6,14 +6,13 @@ import cats.implicits._
|
||||
import com.lbs.api.exception._
|
||||
import com.lbs.api.json.JsonSerializer.extensions._
|
||||
import com.lbs.api.json.model._
|
||||
import com.lbs.common.Logger
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
import scalaj.http.{HttpRequest, HttpResponse}
|
||||
|
||||
import java.net.{HttpCookie, HttpURLConnection}
|
||||
import scala.language.higherKinds
|
||||
import scala.util.{Failure, Success, Try}
|
||||
|
||||
package object http extends Logger {
|
||||
package object http extends StrictLogging {
|
||||
|
||||
case class Session(accessToken: String, tokenType: String, cookies: Seq[HttpCookie])
|
||||
|
||||
@@ -37,9 +36,9 @@ package object http extends Logger {
|
||||
implicit class ExtendedHttpRequest[F[_] : ThrowableMonad](httpRequest: HttpRequest) {
|
||||
def invoke: F[HttpResponse[String]] = {
|
||||
val me = MonadError[F, Throwable]
|
||||
debug(s"Sending request:\n${hideSensitive(httpRequest)}")
|
||||
logger.debug(s"Sending request:\n${hideSensitive(httpRequest)}")
|
||||
val httpResponse = me.pure(httpRequest.asString)
|
||||
debug(s"Received response:\n${hideSensitive(httpResponse)}")
|
||||
logger.debug(s"Received response:\n${hideSensitive(httpResponse)}")
|
||||
|
||||
httpResponse.flatMap { response =>
|
||||
val errorMaybe = extractLuxmedError(response)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
package com.lbs.api.json
|
||||
|
||||
import com.lbs.api.json.model.{LuxmedFunnyDateTime, SerializableJsonObject}
|
||||
import com.lbs.common.Logger
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
import org.json4s._
|
||||
import org.json4s.jackson.JsonMethods._
|
||||
|
||||
@@ -11,7 +11,7 @@ import java.time.{LocalDateTime, LocalTime, ZonedDateTime}
|
||||
import scala.util.Try
|
||||
|
||||
|
||||
object JsonSerializer extends Logger {
|
||||
object JsonSerializer extends StrictLogging {
|
||||
|
||||
private val zonedDateTimeSerializer = new CustomSerializer[ZonedDateTime](_ => ( {
|
||||
case JString(str) => ZonedDateTime.parse(str, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
|
||||
@@ -54,7 +54,7 @@ object JsonSerializer extends Logger {
|
||||
|
||||
def write[T](jsonObject: T): String = {
|
||||
val json = pretty(render(Extraction.decompose(jsonObject)))
|
||||
info(json)
|
||||
logger.info(json)
|
||||
json
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ package com.lbs.bot
|
||||
|
||||
import com.lbs.bot.model._
|
||||
import com.lbs.bot.telegram.TelegramBot
|
||||
import com.lbs.common.Logger
|
||||
import com.typesafe.scalalogging.LazyLogging
|
||||
|
||||
class Bot(telegram: TelegramBot /* other bots */) extends Logger {
|
||||
class Bot(telegram: TelegramBot /* other bots */) extends LazyLogging {
|
||||
def sendMessage(source: MessageSource, text: String): Unit =
|
||||
resolveAdapter(source).sendMessage(source.chatId, text)
|
||||
|
||||
|
||||
@@ -8,11 +8,11 @@ import com.bot4s.telegram.clients.AkkaHttpClient
|
||||
import com.bot4s.telegram.future.{Polling, TelegramBot => TelegramBoT}
|
||||
import com.bot4s.telegram.methods._
|
||||
import com.bot4s.telegram.models.{InlineKeyboardMarkup, InputFile, Message}
|
||||
import com.lbs.common.Logger
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
|
||||
import scala.concurrent.Future
|
||||
|
||||
class TelegramClient(onReceive: TelegramEvent => Unit, botToken: String) extends AkkaTelegramBot with TelegramBoT with Polling with Commands[Future] with Callbacks[Future] with Logger {
|
||||
class TelegramClient(onReceive: TelegramEvent => Unit, botToken: String) extends AkkaTelegramBot with TelegramBoT with Polling with Commands[Future] with Callbacks[Future] with StrictLogging {
|
||||
|
||||
override val client: RequestHandler[Future] = new AkkaHttpClient(botToken)
|
||||
|
||||
@@ -32,18 +32,18 @@ class TelegramClient(onReceive: TelegramEvent => Unit, botToken: String) extends
|
||||
loggingRequest(SendDocument(chatId, InputFile(filename, contents), caption = caption))
|
||||
|
||||
private def loggingRequest[R: Manifest](req: Request[R]): Future[R] = {
|
||||
debug(s"Sending telegram request: $req")
|
||||
logger.debug(s"Sending telegram request: $req")
|
||||
request(req)
|
||||
}
|
||||
|
||||
|
||||
override def receiveMessage(msg: Message): Future[Unit] = {
|
||||
debug(s"Received telegram message: $msg")
|
||||
logger.debug(s"Received telegram message: $msg")
|
||||
Future.successful(onReceive(TelegramEvent(msg, None)))
|
||||
}
|
||||
|
||||
onCallbackWithTag(TagPrefix) { implicit cbq =>
|
||||
debug(s"Received telegram callback: $cbq")
|
||||
logger.debug(s"Received telegram callback: $cbq")
|
||||
val ack = ackCallback()
|
||||
val maybeOnReceive = for {
|
||||
data <- cbq.data.map(_.stripPrefix(TagPrefix))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
dependencies {
|
||||
api "ch.qos.logback:logback-classic:1.2.11"
|
||||
api "org.typelevel:cats-core_$scala:2.8.0"
|
||||
api "com.typesafe.scala-logging:scala-logging_$scala:3.9.5"
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
|
||||
package com.lbs.common
|
||||
|
||||
import org.slf4j
|
||||
import org.slf4j.LoggerFactory
|
||||
|
||||
trait Logger {
|
||||
private val log: slf4j.Logger = LoggerFactory.getLogger(this.getClass)
|
||||
|
||||
protected def debug(msg: => String): Unit = {
|
||||
if (log.isDebugEnabled)
|
||||
log.debug(msg)
|
||||
}
|
||||
|
||||
protected def warn(msg: => String): Unit = {
|
||||
if (log.isWarnEnabled)
|
||||
log.warn(msg)
|
||||
}
|
||||
|
||||
protected def warn(msg: => String, throwable: Throwable): Unit = {
|
||||
if (log.isWarnEnabled)
|
||||
log.warn(msg, throwable)
|
||||
}
|
||||
|
||||
protected def error(msg: => String): Unit = {
|
||||
if (log.isErrorEnabled)
|
||||
log.error(msg)
|
||||
}
|
||||
|
||||
protected def error(msg: => String, throwable: Throwable): Unit = {
|
||||
if (log.isErrorEnabled)
|
||||
log.error(msg, throwable)
|
||||
}
|
||||
|
||||
protected def info(msg: => String): Unit = {
|
||||
if (log.isInfoEnabled)
|
||||
log.info(msg)
|
||||
}
|
||||
|
||||
protected def trace(msg: => String): Unit = {
|
||||
if (log.isTraceEnabled)
|
||||
log.trace(msg)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
|
||||
package com.lbs.common
|
||||
|
||||
import com.typesafe.scalalogging.LazyLogging
|
||||
|
||||
import java.util.concurrent.{Executors, ScheduledFuture}
|
||||
import scala.concurrent.duration.FiniteDuration
|
||||
|
||||
class Scheduler(poolSize: Int) extends Logger {
|
||||
class Scheduler(poolSize: Int) extends LazyLogging {
|
||||
private val scheduledThreadPool = Executors.newScheduledThreadPool(poolSize)
|
||||
|
||||
def schedule(fn: => Unit, period: FiniteDuration): ScheduledFuture[_] = {
|
||||
@@ -22,7 +24,7 @@ class Scheduler(poolSize: Int) extends Logger {
|
||||
fn
|
||||
} catch {
|
||||
case ex: Exception =>
|
||||
error(s"Unable to execute scheduler task", ex)
|
||||
logger.error(s"Unable to execute scheduler task", ex)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
package com.lbs.server
|
||||
|
||||
import com.lbs.common.Logger
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
import org.springframework.boot.SpringApplication
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
|
||||
@@ -9,10 +9,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
@SpringBootApplication
|
||||
class Boot
|
||||
|
||||
object Boot extends App with Logger {
|
||||
object Boot extends App with StrictLogging {
|
||||
|
||||
def printInfo(): Unit = {
|
||||
info(s"Num processors: ${Runtime.getRuntime.availableProcessors}")
|
||||
logger.info(s"Num processors: ${Runtime.getRuntime.availableProcessors}")
|
||||
}
|
||||
|
||||
printInfo()
|
||||
|
||||
@@ -46,7 +46,7 @@ class Account(val userId: UserId, bot: Bot, dataService: DataService, val locali
|
||||
bot.sendMessage(userId.source, lang.accountSwitched(account.username))
|
||||
}
|
||||
case None =>
|
||||
error(s"This is not user [#${userId.userId}] account [#$accountId]")
|
||||
logger.error(s"This is not user [#${userId.userId}] account [#$accountId]")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,14 +3,14 @@ package com.lbs.server.conversation
|
||||
|
||||
import akka.actor.ActorSystem
|
||||
import com.lbs.bot.model.{Command, MessageSource}
|
||||
import com.lbs.common.Logger
|
||||
import com.lbs.server.conversation.Login.{LoggedIn, UserId}
|
||||
import com.lbs.server.conversation.base.Conversation
|
||||
import com.lbs.server.service.DataService
|
||||
import com.lbs.server.util.MessageExtractors._
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
|
||||
class Auth(val source: MessageSource, dataService: DataService, unauthorizedHelpFactory: MessageSourceTo[UnauthorizedHelp],
|
||||
loginFactory: MessageSourceWithOriginatorTo[Login], chatFactory: UserIdTo[Chat])(val actorSystem: ActorSystem) extends Conversation[Unit] with Logger {
|
||||
loginFactory: MessageSourceWithOriginatorTo[Login], chatFactory: UserIdTo[Chat])(val actorSystem: ActorSystem) extends Conversation[Unit] with StrictLogging {
|
||||
|
||||
private val login = loginFactory(source, self)
|
||||
private val unauthorizedHelp = unauthorizedHelpFactory(source)
|
||||
|
||||
@@ -151,12 +151,12 @@ class Book(val userId: UserId, bot: Bot, apiService: ApiService, dataService: Da
|
||||
} yield (lockTermResponse, xsrfToken)
|
||||
response match {
|
||||
case Left(ex) =>
|
||||
error("Can not lock term", ex)
|
||||
logger.error("Can not lock term", ex)
|
||||
bot.sendMessage(userId.source, ex.getMessage)
|
||||
end()
|
||||
case Right((reservationLocktermResponse, xsrfToken)) =>
|
||||
if (reservationLocktermResponse.value.changeTermAvailable) {
|
||||
warn(s"Service [${bookingData.serviceId.name}] is already booked. Ask to update term")
|
||||
logger.warn(s"Service [${bookingData.serviceId.name}] is already booked. Ask to update term")
|
||||
bot.sendMessage(userId.source, lang.visitAlreadyExists,
|
||||
inlineKeyboard = createInlineKeyboard(Seq(Button(lang.no, Tags.No), Button(lang.yes, Tags.Yes))))
|
||||
goto(awaitRebookDecision) using bookingData.copy(term = Some(term), xsrfToken = Some(xsrfToken), reservationLocktermResponse = Some(reservationLocktermResponse))
|
||||
@@ -195,15 +195,15 @@ class Book(val userId: UserId, bot: Bot, apiService: ApiService, dataService: Da
|
||||
apiService.reservationChangeTerm(userId.accountId, bookingData.xsrfToken.get,
|
||||
(bookingData.reservationLocktermResponse.get, bookingData.term.get).mapTo[ReservationChangetermRequest]) match {
|
||||
case Right(success) =>
|
||||
debug(s"Successfully confirmed: $success")
|
||||
logger.debug(s"Successfully confirmed: $success")
|
||||
bot.sendMessage(userId.source, lang.appointmentIsConfirmed)
|
||||
case Left(ex) =>
|
||||
error("Error during reservation", ex)
|
||||
logger.error("Error during reservation", ex)
|
||||
bot.sendMessage(userId.source, ex.getMessage)
|
||||
}
|
||||
end()
|
||||
case Msg(CallbackCommand(Tags.No), _) =>
|
||||
info("User doesn't want to change term")
|
||||
logger.info("User doesn't want to change term")
|
||||
end()
|
||||
}
|
||||
|
||||
@@ -227,10 +227,10 @@ class Book(val userId: UserId, bot: Bot, apiService: ApiService, dataService: Da
|
||||
case Some(reservationRequest) =>
|
||||
apiService.reservationConfirm(userId.accountId, bookingData.xsrfToken.get, reservationRequest) match {
|
||||
case Left(ex) =>
|
||||
error("Error during reservation", ex)
|
||||
logger.error("Error during reservation", ex)
|
||||
bot.sendMessage(userId.source, ex.getMessage)
|
||||
case Right(success) =>
|
||||
debug(s"Successfully confirmed: $success")
|
||||
logger.debug(s"Successfully confirmed: $success")
|
||||
bot.sendMessage(userId.source, lang.appointmentIsConfirmed)
|
||||
}
|
||||
case _ => sys.error(s"Can not prepare reservation request using booking data $bookingData")
|
||||
@@ -270,13 +270,13 @@ class Book(val userId: UserId, bot: Bot, apiService: ApiService, dataService: Da
|
||||
|
||||
private def createMonitoring: Step =
|
||||
process { bookingData =>
|
||||
debug(s"Creating monitoring for $bookingData")
|
||||
logger.debug(s"Creating monitoring for $bookingData")
|
||||
try {
|
||||
monitoringService.createMonitoring((userId -> bookingData).mapTo[Monitoring])
|
||||
bot.sendMessage(userId.source, lang.monitoringHasBeenCreated)
|
||||
} catch {
|
||||
case ex: Exception =>
|
||||
error("Unable to create monitoring", ex)
|
||||
logger.error("Unable to create monitoring", ex)
|
||||
bot.sendMessage(userId.source, lang.unableToCreateMonitoring(ex.getMessage))
|
||||
}
|
||||
end()
|
||||
|
||||
@@ -130,7 +130,7 @@ class BookWithTemplate(val userId: UserId, bot: Bot, apiService: ApiService, dat
|
||||
} yield (lockTermResponse, xsrfToken)
|
||||
response match {
|
||||
case Left(ex) =>
|
||||
warn(s"Service [${bookingData.serviceId.name}] is already booked. Ask to update term", ex)
|
||||
logger.warn(s"Service [${bookingData.serviceId.name}] is already booked. Ask to update term", ex)
|
||||
bot.sendMessage(userId.source, lang.visitAlreadyExists,
|
||||
inlineKeyboard = createInlineKeyboard(Seq(Button(lang.no, Tags.No), Button(lang.yes, Tags.Yes))))
|
||||
goto(awaitRebookDecision) using bookingData.copy(term = Some(term))
|
||||
@@ -167,15 +167,15 @@ class BookWithTemplate(val userId: UserId, bot: Bot, apiService: ApiService, dat
|
||||
case Msg(CallbackCommand(Tags.Yes), bookingData: BookingData) =>
|
||||
apiService.reservationChangeTerm(userId.accountId, bookingData.xsrfToken.get, (bookingData.reservationLocktermResponse.get, bookingData.term.get).mapTo[ReservationChangetermRequest]) match {
|
||||
case Right(success) =>
|
||||
debug(s"Successfully confirmed: $success")
|
||||
logger.debug(s"Successfully confirmed: $success")
|
||||
bot.sendMessage(userId.source, lang.appointmentIsConfirmed)
|
||||
case Left(ex) =>
|
||||
error("Error during reservation", ex)
|
||||
logger.error("Error during reservation", ex)
|
||||
bot.sendMessage(userId.source, ex.getMessage)
|
||||
}
|
||||
end()
|
||||
case Msg(CallbackCommand(Tags.No), _) =>
|
||||
info("User doesn't want to change term")
|
||||
logger.info("User doesn't want to change term")
|
||||
end()
|
||||
}
|
||||
|
||||
@@ -199,10 +199,10 @@ class BookWithTemplate(val userId: UserId, bot: Bot, apiService: ApiService, dat
|
||||
case Some(reservationRequest) =>
|
||||
apiService.reservationConfirm(userId.accountId, bookingData.xsrfToken.get, reservationRequest) match {
|
||||
case Left(ex) =>
|
||||
error("Error during reservation", ex)
|
||||
logger.error("Error during reservation", ex)
|
||||
bot.sendMessage(userId.source, ex.getMessage)
|
||||
case Right(success) =>
|
||||
debug(s"Successfully confirmed: $success")
|
||||
logger.debug(s"Successfully confirmed: $success")
|
||||
bot.sendMessage(userId.source, lang.appointmentIsConfirmed)
|
||||
}
|
||||
case _ => sys.error(s"Can not prepare reservation request using booking data $bookingData")
|
||||
@@ -242,13 +242,13 @@ class BookWithTemplate(val userId: UserId, bot: Bot, apiService: ApiService, dat
|
||||
|
||||
private def createMonitoring: Step =
|
||||
process { bookingData =>
|
||||
debug(s"Creating monitoring for $bookingData")
|
||||
logger.debug(s"Creating monitoring for $bookingData")
|
||||
try {
|
||||
monitoringService.createMonitoring((userId -> bookingData).mapTo[Monitoring])
|
||||
bot.sendMessage(userId.source, lang.monitoringHasBeenCreated)
|
||||
} catch {
|
||||
case ex: Exception =>
|
||||
error("Unable to create monitoring", ex)
|
||||
logger.error("Unable to create monitoring", ex)
|
||||
bot.sendMessage(userId.source, lang.unableToCreateMonitoring(ex.getMessage))
|
||||
}
|
||||
end()
|
||||
|
||||
@@ -3,18 +3,18 @@ package com.lbs.server.conversation
|
||||
|
||||
import akka.actor.ActorSystem
|
||||
import com.lbs.bot.model.Command
|
||||
import com.lbs.common.Logger
|
||||
import com.lbs.server.conversation.Chat._
|
||||
import com.lbs.server.conversation.Login.UserId
|
||||
import com.lbs.server.conversation.base.{Conversation, Interactional}
|
||||
import com.lbs.server.service.{DataService, MonitoringService}
|
||||
import com.lbs.server.util.MessageExtractors._
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
|
||||
import scala.util.matching.Regex
|
||||
|
||||
class Chat(val userId: UserId, dataService: DataService, monitoringService: MonitoringService, bookingFactory: UserIdTo[Book],
|
||||
helpFactory: UserIdTo[Help], monitoringsFactory: UserIdTo[Monitorings], monitoringsHistoryFactory: UserIdTo[MonitoringsHistory], historyFactory: UserIdTo[HistoryViewer],
|
||||
visitsFactory: UserIdTo[ReservedVisitsViewer], settingsFactory: UserIdTo[Settings], accountFactory: UserIdTo[Account])(val actorSystem: ActorSystem) extends Conversation[Unit] with Logger {
|
||||
visitsFactory: UserIdTo[ReservedVisitsViewer], settingsFactory: UserIdTo[Settings], accountFactory: UserIdTo[Account])(val actorSystem: ActorSystem) extends Conversation[Unit] with StrictLogging {
|
||||
|
||||
private val book = bookingFactory(userId)
|
||||
private val help = helpFactory(userId)
|
||||
|
||||
@@ -74,7 +74,7 @@ class DatePicker(val userId: UserId, val bot: Bot, val localization: Localizatio
|
||||
end()
|
||||
} catch {
|
||||
case NonFatal(ex) =>
|
||||
error("Unable to parse date", ex)
|
||||
logger.error("Unable to parse date", ex)
|
||||
bot.sendMessage(userId.source, "Incorrect date. Please use format dd-MM")
|
||||
goto(requestDate)
|
||||
}
|
||||
|
||||
@@ -3,18 +3,18 @@ package com.lbs.server.conversation
|
||||
|
||||
import akka.actor.ActorSystem
|
||||
import com.lbs.bot.model.{Button, Command}
|
||||
import com.lbs.bot.{Bot, _}
|
||||
import com.lbs.common.Logger
|
||||
import com.lbs.bot._
|
||||
import com.lbs.server.conversation.Login.UserId
|
||||
import com.lbs.server.conversation.Pager.{Tags, _}
|
||||
import com.lbs.server.conversation.Pager._
|
||||
import com.lbs.server.conversation.base.{Conversation, Interactional}
|
||||
import com.lbs.server.lang.{Localizable, Localization}
|
||||
import com.lbs.server.util.MessageExtractors
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
|
||||
class Pager[Data](val userId: UserId, bot: Bot, makeMessage: (Data, Int, Int) => String,
|
||||
makeHeader: (Int, Int) => String, selectionPrefix: Option[String],
|
||||
val localization: Localization, originator: Interactional)(val actorSystem: ActorSystem)
|
||||
extends Conversation[(ItemsProvider[Data], Option[String])] with Localizable with Logger {
|
||||
extends Conversation[(ItemsProvider[Data], Option[String])] with Localizable with StrictLogging {
|
||||
|
||||
private val Selection = s"/${selectionPrefix.getOrElse("")}_(\\d+)".r
|
||||
|
||||
|
||||
@@ -3,15 +3,15 @@ package com.lbs.server.conversation
|
||||
|
||||
import akka.actor.{ActorSystem, Cancellable}
|
||||
import com.lbs.bot.model.{Command, MessageSource}
|
||||
import com.lbs.common.Logger
|
||||
import com.lbs.server.conversation.Account.SwitchAccount
|
||||
import com.lbs.server.conversation.base.Conversation
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
|
||||
import scala.collection.mutable
|
||||
import scala.concurrent.ExecutionContextExecutor
|
||||
import scala.concurrent.duration.DurationLong
|
||||
|
||||
class Router(authFactory: MessageSourceTo[Auth])(val actorSystem: ActorSystem) extends Conversation[Unit] with Logger {
|
||||
class Router(authFactory: MessageSourceTo[Auth])(val actorSystem: ActorSystem) extends Conversation[Unit] with StrictLogging {
|
||||
|
||||
private case class DestroyChat(source: MessageSource)
|
||||
|
||||
@@ -32,14 +32,14 @@ class Router(authFactory: MessageSourceTo[Auth])(val actorSystem: ActorSystem) e
|
||||
chat ! cmd
|
||||
stay()
|
||||
case Msg(DestroyChat(source), _) =>
|
||||
info(s"Destroying chat for $source due to $idleTimeout of inactivity")
|
||||
logger.info(s"Destroying chat for $source due to $idleTimeout of inactivity")
|
||||
destroyChat(source)
|
||||
stay()
|
||||
case Msg(SwitchAccount(userId), _) =>
|
||||
switchAccount(userId)
|
||||
stay()
|
||||
case msg: Msg =>
|
||||
info(s"Unknown message received: $msg")
|
||||
logger.info(s"Unknown message received: $msg")
|
||||
stay()
|
||||
}
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ class TimePicker(val userId: UserId, val bot: Bot, val localization: Localizatio
|
||||
end()
|
||||
} catch {
|
||||
case NonFatal(ex) =>
|
||||
error("Unable to parse time", ex)
|
||||
logger.error("Unable to parse time", ex)
|
||||
bot.sendMessage(userId.source, "Incorrect time. Please use format HH:mm")
|
||||
goto(requestTime)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package com.lbs.server.conversation.base
|
||||
|
||||
import com.lbs.common.Logger
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
|
||||
import scala.util.control.NonFatal
|
||||
|
||||
trait Conversation[D] extends Domain[D] with Interactional with Logger {
|
||||
trait Conversation[D] extends Domain[D] with Interactional with StrictLogging {
|
||||
|
||||
private var currentData: D = _
|
||||
|
||||
@@ -16,7 +16,7 @@ trait Conversation[D] extends Domain[D] with Interactional with Logger {
|
||||
|
||||
private val defaultMsgHandler: MessageProcessorFn = {
|
||||
case Msg(any, data) =>
|
||||
warn(s"Unhandled message received in step '${currentStep.name}'. Message: [$any]. Data: [$data]")
|
||||
logger.warn(s"Unhandled message received in step '${currentStep.name}'. Message: [$any]. Data: [$data]")
|
||||
NextStep(currentStep, Some(data))
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ trait Conversation[D] extends Domain[D] with Interactional with Logger {
|
||||
case _ => //do nothing
|
||||
}
|
||||
} catch {
|
||||
case NonFatal(ex) => error("Step execution failed", ex)
|
||||
case NonFatal(ex) => logger.error("Step execution failed", ex)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ trait Conversation[D] extends Domain[D] with Interactional with Logger {
|
||||
val nextStep = if (fn.isDefinedAt(unit)) fn(unit) else defaultFn(unit)
|
||||
moveToNextStep(nextStep)
|
||||
} catch {
|
||||
case NonFatal(ex) => error("Step transition failed", ex)
|
||||
case NonFatal(ex) => logger.error("Step transition failed", ex)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ trait Conversation[D] extends Domain[D] with Interactional with Logger {
|
||||
}
|
||||
|
||||
private def moveToNextStep(nextStep: NextStep): Unit = {
|
||||
trace(s"Moving from step '${currentStep.name}' to step '${nextStep.step.name}'")
|
||||
logger.trace(s"Moving from step '${currentStep.name}' to step '${nextStep.step.name}'")
|
||||
currentStep = nextStep.step
|
||||
nextStep.data.foreach { data =>
|
||||
currentData = data
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package com.lbs.server.conversation.base
|
||||
|
||||
import akka.actor.{Actor, ActorRef, ActorSystem, PoisonPill, Props}
|
||||
import com.lbs.common.Logger
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
|
||||
import scala.concurrent.ExecutionContextExecutor
|
||||
|
||||
trait Interactional extends Logger {
|
||||
trait Interactional extends StrictLogging {
|
||||
|
||||
private[base] object StartConversation
|
||||
|
||||
|
||||
@@ -5,11 +5,12 @@ import com.lbs.api.exception.InvalidLoginOrPasswordException
|
||||
import com.lbs.api.json.model._
|
||||
import com.lbs.bot.Bot
|
||||
import com.lbs.bot.model.{MessageSource, MessageSourceSystem}
|
||||
import com.lbs.common.{Logger, Scheduler}
|
||||
import com.lbs.common.Scheduler
|
||||
import com.lbs.server.lang.Localization
|
||||
import com.lbs.server.repository.model._
|
||||
import com.lbs.server.util.DateTimeUtil._
|
||||
import com.lbs.server.util.ServerModelConverters._
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.stereotype.Service
|
||||
|
||||
@@ -21,7 +22,7 @@ import scala.concurrent.duration._
|
||||
import scala.util.Random
|
||||
|
||||
@Service
|
||||
class MonitoringService extends Logger {
|
||||
class MonitoringService extends StrictLogging {
|
||||
|
||||
@Autowired
|
||||
private var bot: Bot = _
|
||||
@@ -65,14 +66,14 @@ class MonitoringService extends Logger {
|
||||
}
|
||||
|
||||
private def monitor(monitoring: Monitoring): Unit = {
|
||||
debug(s"Looking for available terms. Monitoring [#${monitoring.recordId}]")
|
||||
logger.debug(s"Looking for available terms. Monitoring [#${monitoring.recordId}]")
|
||||
val dateFrom = optimizeDateFrom(monitoring.dateFrom.toLocalDateTime, monitoring.offset)
|
||||
val termsEither = apiService.getAvailableTerms(monitoring.accountId, monitoring.cityId, monitoring.clinicId, monitoring.serviceId,
|
||||
monitoring.doctorId, dateFrom, monitoring.dateTo.toLocalDateTime, timeFrom = monitoring.timeFrom, timeTo = monitoring.timeTo)
|
||||
termsEither match {
|
||||
case Right(terms) =>
|
||||
if (terms.nonEmpty) {
|
||||
debug(s"Found ${terms.length} terms by monitoring [#${monitoring.recordId}]")
|
||||
logger.debug(s"Found ${terms.length} terms by monitoring [#${monitoring.recordId}]")
|
||||
if (monitoring.autobook) {
|
||||
val term = terms.head
|
||||
bookAppointment(term, monitoring, monitoring.rebookIfExists)
|
||||
@@ -80,16 +81,16 @@ class MonitoringService extends Logger {
|
||||
notifyUserAboutTerms(terms, monitoring)
|
||||
}
|
||||
} else {
|
||||
debug(s"No new terms found for monitoring [#${monitoring.recordId}]")
|
||||
logger.debug(s"No new terms found for monitoring [#${monitoring.recordId}]")
|
||||
}
|
||||
case Left(ex: InvalidLoginOrPasswordException) =>
|
||||
error(s"User entered invalid name or password. Monitoring will be disabled", ex)
|
||||
logger.error(s"User entered invalid name or password. Monitoring will be disabled", ex)
|
||||
bot.sendMessage(monitoring.source, lang(monitoring.userId).invalidLoginOrPassword)
|
||||
val activeUserMonitorings = dataService.getActiveMonitorings(monitoring.accountId)
|
||||
activeUserMonitorings.foreach { m =>
|
||||
deactivateMonitoring(m.accountId, m.recordId)
|
||||
}
|
||||
case Left(ex) => error(s"Unable to receive terms by monitoring [#${monitoring.recordId}]", ex)
|
||||
case Left(ex) => logger.error(s"Unable to receive terms by monitoring [#${monitoring.recordId}]", ex)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,18 +105,18 @@ class MonitoringService extends Logger {
|
||||
val delaySnapshot = delay
|
||||
val periodSnapshot = period
|
||||
val future = monitoringExecutor.schedule(monitor(monitoring), delaySnapshot, periodSnapshot)
|
||||
debug(s"Scheduled monitoring: [#${monitoring.recordId}] with delay: $delaySnapshot and period: $periodSnapshot")
|
||||
logger.debug(s"Scheduled monitoring: [#${monitoring.recordId}] with delay: $delaySnapshot and period: $periodSnapshot")
|
||||
activeMonitorings += (monitoring.recordId -> (monitoring -> future))
|
||||
}
|
||||
}
|
||||
debug(s"Number of active monitorings: ${activeMonitorings.size}")
|
||||
logger.debug(s"Number of active monitorings: ${activeMonitorings.size}")
|
||||
}
|
||||
|
||||
private def initializeNewMonitorings(): Unit = {
|
||||
debug(s"Looking for new monitorings created since $checkedOn")
|
||||
logger.debug(s"Looking for new monitorings created since $checkedOn")
|
||||
val currentTime = ZonedDateTime.now()
|
||||
val monitorings = dataService.getActiveMonitoringsSince(checkedOn)
|
||||
debug(s"New monitorings found: ${monitorings.length}")
|
||||
logger.debug(s"New monitorings found: ${monitorings.length}")
|
||||
checkedOn = currentTime
|
||||
initializeMonitorings(monitorings)
|
||||
}
|
||||
@@ -131,7 +132,7 @@ class MonitoringService extends Logger {
|
||||
}
|
||||
|
||||
toDisable.foreach { case (id, monitoring) =>
|
||||
debug(s"Monitoring [#$id] is going to be disable as outdated")
|
||||
logger.debug(s"Monitoring [#$id] is going to be disable as outdated")
|
||||
notifyChatAboutDisabledMonitoring(monitoring)
|
||||
deactivateMonitoring(monitoring.accountId, id)
|
||||
}
|
||||
@@ -152,7 +153,7 @@ class MonitoringService extends Logger {
|
||||
reservationLocktermResponse <- apiService.reservationLockterm(monitoring.accountId, xsrfToken, term.mapTo[ReservationLocktermRequest])
|
||||
temporaryReservationId = reservationLocktermResponse.value.temporaryReservationId
|
||||
response <- if (reservationLocktermResponse.value.changeTermAvailable && rebookIfExists) {
|
||||
info(s"Service [${monitoring.serviceName}] is already booked. Trying to update term")
|
||||
logger.info(s"Service [${monitoring.serviceName}] is already booked. Trying to update term")
|
||||
bookOrUnlockTerm(monitoring.accountId, xsrfToken, temporaryReservationId, apiService.reservationChangeTerm(_, xsrfToken, (reservationLocktermResponse, term).mapTo[ReservationChangetermRequest]))
|
||||
} else {
|
||||
bookOrUnlockTerm(monitoring.accountId, xsrfToken, temporaryReservationId, apiService.reservationConfirm(_, xsrfToken, (reservationLocktermResponse, term).mapTo[ReservationConfirmRequest]))
|
||||
@@ -163,7 +164,7 @@ class MonitoringService extends Logger {
|
||||
bot.sendMessage(monitoring.source, lang(monitoring.userId).appointmentIsBooked(term, monitoring))
|
||||
deactivateMonitoring(monitoring.accountId, monitoring.recordId)
|
||||
case Left(ex) =>
|
||||
error(s"Unable to book appointment by monitoring [${monitoring.recordId}]", ex)
|
||||
logger.error(s"Unable to book appointment by monitoring [${monitoring.recordId}]", ex)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,14 +181,14 @@ class MonitoringService extends Logger {
|
||||
val activeMonitoringMaybe = activeMonitorings.remove(monitoringId)
|
||||
activeMonitoringMaybe match {
|
||||
case Some((monitoring, future)) =>
|
||||
debug(s"Deactivating scheduled monitoring [#$monitoringId]")
|
||||
logger.debug(s"Deactivating scheduled monitoring [#$monitoringId]")
|
||||
if (!future.isCancelled) {
|
||||
future.cancel(true)
|
||||
}
|
||||
monitoring.active = false
|
||||
dataService.saveMonitoring(monitoring)
|
||||
case None =>
|
||||
debug(s"Deactivating unscheduled monitoring [#$monitoringId]")
|
||||
logger.debug(s"Deactivating unscheduled monitoring [#$monitoringId]")
|
||||
dataService.findMonitoring(accountId, monitoringId).foreach { monitoring =>
|
||||
monitoring.active = false
|
||||
dataService.saveMonitoring(monitoring)
|
||||
@@ -229,12 +230,12 @@ class MonitoringService extends Logger {
|
||||
bot.sendMessage(monitoring.source, lang(monitoring.userId).termIsOutdated)
|
||||
}
|
||||
case Left(ex: InvalidLoginOrPasswordException) =>
|
||||
error(s"User entered invalid name or password. Monitoring will be disabled", ex)
|
||||
logger.error(s"User entered invalid name or password. Monitoring will be disabled", ex)
|
||||
bot.sendMessage(monitoring.source, lang(monitoring.userId).loginHasChangedOrWrong)
|
||||
case Left(ex) => error(s"Error occurred during receiving terms for monitoring [#${monitoring.recordId}]", ex)
|
||||
case Left(ex) => logger.error(s"Error occurred during receiving terms for monitoring [#${monitoring.recordId}]", ex)
|
||||
}
|
||||
case None =>
|
||||
debug(s"Monitoring [#$monitoringId] not found in db")
|
||||
logger.debug(s"Monitoring [#$monitoringId] not found in db")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,7 +251,7 @@ class MonitoringService extends Logger {
|
||||
private def initialize(): Unit = {
|
||||
checkedOn = ZonedDateTime.now()
|
||||
val monitorings = dataService.getActiveMonitorings
|
||||
debug(s"Active monitorings found: ${monitorings.length}")
|
||||
logger.debug(s"Active monitorings found: ${monitorings.length}")
|
||||
initializeMonitorings(monitorings)
|
||||
disableOutdated()
|
||||
initializeDbChecker()
|
||||
|
||||
@@ -3,13 +3,14 @@ package com.lbs.server.service
|
||||
|
||||
import com.lbs.api.exception.SessionExpiredException
|
||||
import com.lbs.api.http.Session
|
||||
import com.lbs.common.{Logger, ParametrizedLock}
|
||||
import com.lbs.common.ParametrizedLock
|
||||
import com.lbs.server.ThrowableOr
|
||||
import com.lbs.server.exception.UserNotFoundException
|
||||
import com.typesafe.scalalogging.StrictLogging
|
||||
|
||||
import scala.collection.mutable
|
||||
|
||||
trait SessionSupport extends Logger {
|
||||
trait SessionSupport extends StrictLogging {
|
||||
|
||||
def fullLogin(username: String, password: String): ThrowableOr[Session]
|
||||
|
||||
@@ -53,11 +54,11 @@ trait SessionSupport extends Logger {
|
||||
for {
|
||||
result <- doApiCall match {
|
||||
case Left(_: SessionExpiredException) =>
|
||||
debug(s"The session for account [#$accountId] has expired. Try to relogin")
|
||||
logger.debug(s"The session for account [#$accountId] has expired. Try to relogin")
|
||||
sessions.remove(accountId)
|
||||
doApiCall
|
||||
case another =>
|
||||
debug(s"Call to remote api function has completed with result:\n$another")
|
||||
logger.debug(s"Call to remote api function has completed with result:\n$another")
|
||||
another
|
||||
}
|
||||
} yield result
|
||||
|
||||
Reference in New Issue
Block a user