<commit_before>package im.actor.server

import akka.actor._
import akka.cluster.Cluster
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import com.typesafe.config.{ Config, ConfigFactory, ConfigException }
import im.actor.config.ActorConfig
import im.actor.server.activation.gate.{ GateCodeActivation, GateConfig }
import im.actor.server.activation.internal.{ ActivationConfig, InternalCodeActivation }
import im.actor.server.api.http.{ HttpApiConfig, HttpApiFrontend }
import im.actor.server.api.rpc.RpcApiExtension
import im.actor.server.api.rpc.service.auth.AuthServiceImpl
import im.actor.server.api.rpc.service.configs.ConfigsServiceImpl
import im.actor.server.api.rpc.service.contacts.ContactsServiceImpl
import im.actor.server.api.rpc.service.device.DeviceServiceImpl
import im.actor.server.api.rpc.service.files.FilesServiceImpl
import im.actor.server.api.rpc.service.groups.{ GroupInviteConfig, GroupsServiceImpl }
import im.actor.server.api.rpc.service.messaging.{ MessagingServiceImpl, ReverseHooksListener }
import im.actor.server.api.rpc.service.profile.ProfileServiceImpl
import im.actor.server.api.rpc.service.pubgroups.PubgroupsServiceImpl
import im.actor.server.api.rpc.service.push.PushServiceImpl
import im.actor.server.api.rpc.service.sequence.{ SequenceServiceConfig, SequenceServiceImpl }
import im.actor.server.api.rpc.service.stickers.StickersServiceImpl
import im.actor.server.api.rpc.service.users.UsersServiceImpl
import im.actor.server.api.rpc.service.weak.WeakServiceImpl
import im.actor.server.api.rpc.service.webactions.WebactionsServiceImpl
import im.actor.server.api.rpc.service.webhooks.IntegrationsServiceImpl
import im.actor.server.bot.ActorBot
import im.actor.server.cli.ActorCliService
import im.actor.server.db.DbExtension
import im.actor.server.dialog.{ DialogExtension, DialogProcessor }
import im.actor.server.email.{ EmailConfig, SmtpEmailSender }
import im.actor.server.enrich.{ RichMessageConfig, RichMessageWorker }
import im.actor.server.frontend.Frontend
import im.actor.server.group._
import im.actor.server.migrations._
import im.actor.server.oauth.{ GoogleProvider, OAuth2GoogleConfig }
import im.actor.server.presences.{ GroupPresenceExtension, PresenceExtension }
import im.actor.server.sequence._
import im.actor.server.session.{ Session, SessionConfig, SessionMessage }
import im.actor.server.sms.{ TelesignCallEngine, TelesignClient, TelesignSmsEngine }
import im.actor.server.social.SocialExtension
import im.actor.server.user._

import scala.language.existentials

final case class ActorServer(system: ActorSystem)

object ActorServer {
  /**
   * Creates a new Actor Server builder
   *
   * @return
   */
  def newBuilder: ActorServerBuilder = ActorServerBuilder()
}

final case class ActorServerBuilder(defaultConfig: Config = ConfigFactory.empty(), httpRoutes: (ActorSystem) ⇒ Seq[Route] = _ ⇒ Seq.empty) extends ActorServerModules {
  /**
   *
   * @param config
   * @return a builder with provided default config
   */
  def withDefaultConfig(config: Config) = this.copy(defaultConfig = config)

  /**
   *
   * @param routes
   * @return
   */
  def withHttpRoutes(routes: ActorSystem ⇒ Seq[Route]) = this.copy(httpRoutes = routes)

  /**
   * Starts a server
   *
   * @return
   */
  def start(): ActorServer = {
    SessionMessage.register()
    CommonSerialization.register()
    UserProcessor.register()
    GroupProcessor.register()
    DialogProcessor.register()

    val serverConfig = ActorConfig.load(defaultConfig)

    implicit val system = ActorSystem(serverConfig.getString("actor-system-name"), serverConfig)

    try {

      // FIXME: get rid of unsafe get's
      val activationConfig = ActivationConfig.load.get
      val emailConfig = EmailConfig.fromConfig(serverConfig.getConfig("services.email")).toOption.get
      val gateConfig = GateConfig.load.get
      val groupInviteConfig = GroupInviteConfig.load(serverConfig.getConfig("modules.messaging.groups.invite"))
      val webappConfig = HttpApiConfig.load(serverConfig.getConfig("http")).toOption.get
      val oauth2GoogleConfig = OAuth2GoogleConfig.load(serverConfig.getConfig("services.google.oauth"))
      val richMessageConfig = RichMessageConfig.load(serverConfig.getConfig("modules.enricher")).get
      val sequenceConfig = SequenceServiceConfig.load().get
      implicit val sessionConfig = SessionConfig.load(serverConfig.getConfig("session"))

      if (system.settings.config.getList("akka.cluster.seed-nodes").isEmpty) {
        system.log.info("Going to a single-node cluster mode")

        Cluster(system).join(Cluster(system).selfAddress)
      }

      implicit val executor = system.dispatcher
      implicit val materializer = ActorMaterializer()

      implicit val db = DbExtension(system).db

      UserMigrator.migrate()
      GroupMigrator.migrate()
      LocalNamesMigrator.migrate()
      GroupCreatorMemberMigrator.migrate()
      HiddenGroupMigrator.migrate()
      LocalNamesFromKVMigrator.migrate()
      FillUserSequenceMigrator.migrate()
      FixUserSequenceMigrator.migrate()

      system.log.debug("Starting SeqUpdatesExtension")
      val seqUpdatesExt = SeqUpdatesExtension(system)

      system.log.debug("Starting WeakUpdatesExtension")
      val weakUpdatesExt = WeakUpdatesExtension(system)

      system.log.debug("Starting PresenceExtension")
      val presenceExt = PresenceExtension(system)

      system.log.debug("Starting GroupPresenceExtension")
      val groupPresenceExt = GroupPresenceExtension(system)

      system.log.debug("Starting DialogExtension")
      val dialogExt = DialogExtension(system)

      system.log.debug("Starting SocialExtension")
      implicit val socialManagerRegion = SocialExtension(system).region

      system.log.debug("Starting UserExtension")
      implicit val userProcessorRegion = UserExtension(system).processorRegion
      implicit val userViewRegion = UserExtension(system).viewRegion

      system.log.debug("Starting GroupExtension")
      implicit val groupProcessorRegion = GroupExtension(system).processorRegion
      implicit val groupViewRegion = GroupExtension(system).viewRegion

      system.log.debug("Starting IntegrationTokenMigrator")
      IntegrationTokenMigrator.migrate()

      system.log.debug("Starting ActivationContext")
      val activationContext = serverConfig.getString("services.activation.default-service") match {
        case "internal" ⇒
          val telesignClient = new TelesignClient(serverConfig.getConfig("services.telesign"))
          InternalCodeActivation.newContext(
            activationConfig,
            new TelesignSmsEngine(telesignClient),
            new TelesignCallEngine(telesignClient),
            new SmtpEmailSender(emailConfig)
          )
        case "actor-activation" ⇒ new GateCodeActivation(gateConfig)
        case _                  ⇒ throw new Exception("""Invalid activation.default-service value provided: valid options: "internal", actor-activation""")
      }
      system.log.warning("Starting session region")
      implicit val sessionRegion = Session.startRegion(Session.props)

      system.log.debug("Starting RichMessageWorker")
      RichMessageWorker.startWorker(richMessageConfig)
      system.log.debug("Starting ReverseHooksListener")
      ReverseHooksListener.startSingleton()

      implicit val oauth2Service = new GoogleProvider(oauth2GoogleConfig)
<commit_msg>fix(server:activation): accept both internal and telesign defatul-service<commit_after>package im.actor.server

import akka.actor._
import akka.cluster.Cluster
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import com.typesafe.config.{ Config, ConfigFactory, ConfigException }
import im.actor.config.ActorConfig
import im.actor.server.activation.gate.{ GateCodeActivation, GateConfig }
import im.actor.server.activation.internal.{ ActivationConfig, InternalCodeActivation }
import im.actor.server.api.http.{ HttpApiConfig, HttpApiFrontend }
import im.actor.server.api.rpc.RpcApiExtension
import im.actor.server.api.rpc.service.auth.AuthServiceImpl
import im.actor.server.api.rpc.service.configs.ConfigsServiceImpl
import im.actor.server.api.rpc.service.contacts.ContactsServiceImpl
import im.actor.server.api.rpc.service.device.DeviceServiceImpl
import im.actor.server.api.rpc.service.files.FilesServiceImpl
import im.actor.server.api.rpc.service.groups.{ GroupInviteConfig, GroupsServiceImpl }
import im.actor.server.api.rpc.service.messaging.{ MessagingServiceImpl, ReverseHooksListener }
import im.actor.server.api.rpc.service.profile.ProfileServiceImpl
import im.actor.server.api.rpc.service.pubgroups.PubgroupsServiceImpl
import im.actor.server.api.rpc.service.push.PushServiceImpl
import im.actor.server.api.rpc.service.sequence.{ SequenceServiceConfig, SequenceServiceImpl }
import im.actor.server.api.rpc.service.stickers.StickersServiceImpl
import im.actor.server.api.rpc.service.users.UsersServiceImpl
import im.actor.server.api.rpc.service.weak.WeakServiceImpl
import im.actor.server.api.rpc.service.webactions.WebactionsServiceImpl
import im.actor.server.api.rpc.service.webhooks.IntegrationsServiceImpl
import im.actor.server.bot.ActorBot
import im.actor.server.cli.ActorCliService
import im.actor.server.db.DbExtension
import im.actor.server.dialog.{ DialogExtension, DialogProcessor }
import im.actor.server.email.{ EmailConfig, SmtpEmailSender }
import im.actor.server.enrich.{ RichMessageConfig, RichMessageWorker }
import im.actor.server.frontend.Frontend
import im.actor.server.group._
import im.actor.server.migrations._
import im.actor.server.oauth.{ GoogleProvider, OAuth2GoogleConfig }
import im.actor.server.presences.{ GroupPresenceExtension, PresenceExtension }
import im.actor.server.sequence._
import im.actor.server.session.{ Session, SessionConfig, SessionMessage }
import im.actor.server.sms.{ TelesignCallEngine, TelesignClient, TelesignSmsEngine }
import im.actor.server.social.SocialExtension
import im.actor.server.user._

import scala.language.existentials

final case class ActorServer(system: ActorSystem)

object ActorServer {
  /**
   * Creates a new Actor Server builder
   *
   * @return
   */
  def newBuilder: ActorServerBuilder = ActorServerBuilder()
}

final case class ActorServerBuilder(defaultConfig: Config = ConfigFactory.empty(), httpRoutes: (ActorSystem) ⇒ Seq[Route] = _ ⇒ Seq.empty) extends ActorServerModules {
  /**
   *
   * @param config
   * @return a builder with provided default config
   */
  def withDefaultConfig(config: Config) = this.copy(defaultConfig = config)

  /**
   *
   * @param routes
   * @return
   */
  def withHttpRoutes(routes: ActorSystem ⇒ Seq[Route]) = this.copy(httpRoutes = routes)

  /**
   * Starts a server
   *
   * @return
   */
  def start(): ActorServer = {
    SessionMessage.register()
    CommonSerialization.register()
    UserProcessor.register()
    GroupProcessor.register()
    DialogProcessor.register()

    val serverConfig = ActorConfig.load(defaultConfig)

    implicit val system = ActorSystem(serverConfig.getString("actor-system-name"), serverConfig)

    try {

      // FIXME: get rid of unsafe get's
      val activationConfig = ActivationConfig.load.get
      val emailConfig = EmailConfig.fromConfig(serverConfig.getConfig("services.email")).toOption.get
      val gateConfig = GateConfig.load.get
      val groupInviteConfig = GroupInviteConfig.load(serverConfig.getConfig("modules.messaging.groups.invite"))
      val webappConfig = HttpApiConfig.load(serverConfig.getConfig("http")).toOption.get
      val oauth2GoogleConfig = OAuth2GoogleConfig.load(serverConfig.getConfig("services.google.oauth"))
      val richMessageConfig = RichMessageConfig.load(serverConfig.getConfig("modules.enricher")).get
      val sequenceConfig = SequenceServiceConfig.load().get
      implicit val sessionConfig = SessionConfig.load(serverConfig.getConfig("session"))

      if (system.settings.config.getList("akka.cluster.seed-nodes").isEmpty) {
        system.log.info("Going to a single-node cluster mode")

        Cluster(system).join(Cluster(system).selfAddress)
      }

      implicit val executor = system.dispatcher
      implicit val materializer = ActorMaterializer()

      implicit val db = DbExtension(system).db

      UserMigrator.migrate()
      GroupMigrator.migrate()
      LocalNamesMigrator.migrate()
      GroupCreatorMemberMigrator.migrate()
      HiddenGroupMigrator.migrate()
      LocalNamesFromKVMigrator.migrate()
      FillUserSequenceMigrator.migrate()
      FixUserSequenceMigrator.migrate()

      system.log.debug("Starting SeqUpdatesExtension")
      val seqUpdatesExt = SeqUpdatesExtension(system)

      system.log.debug("Starting WeakUpdatesExtension")
      val weakUpdatesExt = WeakUpdatesExtension(system)

      system.log.debug("Starting PresenceExtension")
      val presenceExt = PresenceExtension(system)

      system.log.debug("Starting GroupPresenceExtension")
      val groupPresenceExt = GroupPresenceExtension(system)

      system.log.debug("Starting DialogExtension")
      val dialogExt = DialogExtension(system)

      system.log.debug("Starting SocialExtension")
      implicit val socialManagerRegion = SocialExtension(system).region

      system.log.debug("Starting UserExtension")
      implicit val userProcessorRegion = UserExtension(system).processorRegion
      implicit val userViewRegion = UserExtension(system).viewRegion

      system.log.debug("Starting GroupExtension")
      implicit val groupProcessorRegion = GroupExtension(system).processorRegion
      implicit val groupViewRegion = GroupExtension(system).viewRegion

      system.log.debug("Starting IntegrationTokenMigrator")
      IntegrationTokenMigrator.migrate()

      system.log.debug("Starting ActivationContext")
      val activationContext = serverConfig.getString("services.activation.default-service") match {
        case "internal" | "telesign" ⇒
          val telesignClient = new TelesignClient(serverConfig.getConfig("services.telesign"))
          InternalCodeActivation.newContext(
            activationConfig,
            new TelesignSmsEngine(telesignClient),
            new TelesignCallEngine(telesignClient),
            new SmtpEmailSender(emailConfig)
          )
        case "actor-activation" ⇒ new GateCodeActivation(gateConfig)
        case _                  ⇒ throw new Exception("""Invalid activation.default-service value provided: valid options: "internal", actor-activation""")
      }
      system.log.warning("Starting session region")
      implicit val sessionRegion = Session.startRegion(Session.props)

      system.log.debug("Starting RichMessageWorker")
      RichMessageWorker.startWorker(richMessageConfig)
      system.log.debug("Starting ReverseHooksListener")
      ReverseHooksListener.startSingleton()

      implicit val oauth2Service = new GoogleProvider(oauth2GoogleConfig)

{'fraction_non_alphanumeric': 0.09663780954298369, 'fraction_numerical': 0.0006710958996040534, 'mean_word_length': 4.430758017492711, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2656547', 'n_tokens_mistral': 4214, 'n_tokens_neox': 4123, 'n_words': 745}