EN · DE · RU · FR · ES

#2329: SipgateSyncService.kt

projectforge-rest/src/main/kotlin/org/projectforge/rest/sipgate/SipgateSyncService.kt Tipo: Kotlin · Rol: Endpoint REST · Fuente: projectforge-rest/src/main/kotlin/org/projectforge/rest/sipgate/SipgateSyncService.kt 132 líneas · 86 código · 36 comentarios · 10 en blanco
Servicio Spring para SipgateSync. Proporciona lógica de negocio entre los controladores/endpoints REST y la capa de acceso a datos.

Estructura del código

Anotaciones: param, micromata, Service, author, Autowired

Clases: SipgateSyncService

Funciones (4): getStorage, readStorage, readFromFileOrGetFromRemote, remoteRead

Propiedades (8): sipgateService, privateStorage, ps, newStorage, newStorage, userDevices, devices, storageFile

Importaciones: 8 paquetes

Paquete: org.projectforge.rest.sipgate

Código fuente (resumido)

package org.projectforge.rest.sipgate

import mu.KotlinLogging
import org.projectforge.business.sipgate.SipgateUserDevices
import org.projectforge.framework.configuration.ConfigXml
import org.projectforge.framework.json.JsonUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.io.File
import kotlin.concurrent.thread

private val log = KotlinLogging.logger {}

/**
 * Lee números, dispositivos, usuarios, etc. del servidor remoto Sipgate.
 * @author K. Reinhard (k.reinhard@micromata.de)
 */
@Service
open class SipgateSyncService {
  @Autowired
  internal lateinit var sipgateService: SipgateService

  private var privateStorage: SipgateDataStorage? = null

  /**
   * Obtiene el almacenamiento, si existe. Si no, el almacenamiento se leerá del servidor remoto Sipgate.
   * Si el almacenamiento existente está desactualizado, se devuelve el almacenamiento desactualizado,
   * pero se inicia un trabajo asíncrono para obtener nuevos datos de almacenamiento.
   */
  open fun getStorage(): SipgateDataStorage {
    privateStorage?.let {
      thread(start = true) {
        readStorage() // Vuelve a leer si está desactualizado.
      }
      return it
    }
    return readStorage()
  }

  /**
   * Obtiene los datos del servidor remoto Sipgate. Se almacenarán en caché como archivo (work/sipgateStorage.json). Los datos se
   * volverán a leer automáticamente después de un día.
   * @param Si forceSync se establece en true, la configuración se obtendrá del servidor remoto Sipgate. El valor predeterminado es false.
   */
  open fun readStorage(forceSync: Boolean = false): SipgateDataStorage {
    val ps = privateStorage
    if (forceSync || ps == null || !ps.uptodate) {
      if (forceSync) {
        log.info { "La lectura de la configuración de Sipgate es forzada." }
      } else if (ps == null) {
        log.info { "La configuración de Sipgate aún no existe.." }
      } else {
        log.info { "La configuración de Sipgate está desactualizada." }
      }
      readFromFileOrGetFromRemote(forceSync)
    }
    return privateStorage!!
  }

  private fun readFromFileOrGetFromRemote(forceSync: Boolean = false) {
    synchronized(this) {
      try {
        if (!forceSync && storageFile.canRead()) {
          val json = storageFile.readText()
          log.info { "Leyendo datos de Sipgate desde '${storageFile.absolutePath}'..." }
          val newStorage = JsonUtils.fromJson(json, SipgateDataStorage::class.java)
          if (newStorage?.uptodate == true) {
            privateStorage = newStorage
            return
          }
          log.info { "El almacenamiento de Sipgate está desactualizado (más de un día), releyendo..." }
        }
      } catch (ex: Exception) {
        log.error("Error al analizar el almacenamiento de sipgate desde '${storageFile.absolutePath}': ${ex.message}", ex)
      }
      remoteRead()
    }
  }

  private fun remoteRead() {
    log.info { "Leyendo datos de Sipgate (usuarios, dispositivos, etc.)..." }
    val newStorage = SipgateDataStorage()
    newStorage.users = sipgateService.getUsers()
    try {
      newStorage.numbers = sipgateService.getNumbers()
    } catch (ex: Exception) {
      log.error("No se pueden leer los números (puede que no tenga acceso): ${ex.message}", ex)
    }
    val userDevices = mutableListOf<SipgateUserDevices>()
    newStorage.users?.forEach { user ->
      val devices = sipgateService.getDevices(user)
      if (devices.isNotEmpty()) {
        devices.forEach { it.deleteSecrets() }
        userDevices.add(SipgateUserDevices(user.id, devices))
      }
    }
    newStorage.userDevices = userDevices
    newStorage.addresses = sipgateService.getAddresses()
    privateStorage = newStorage
    log.info { "Escribiendo datos de Sipgate en '${storageFile.absolutePath}'..." }
    storageFile.writeText(privateStorage.toString())
  }

  companion object {
    private val storageFile by lazy {
      File(ConfigXml.getInstance().workingDirectory, "sipgateStorage.json")
    }
  }
}

Historial de Git

868d6abb7 2025 -> 2026
63081666f Encabezados de archivos fuente: 2024-> 2025.
5bafe7941 @Repository -> @Service. Anotaciones @Transactional eliminadas.
b6092df09 Copyright 2023 -> 2024
031eb26c3 WIP: llamadas telefónicas para Sipgate