PlantumlDecodingService.kt

/*
  Copyright (C) 2026 Sber

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.sber.seaf.plantuml.plantumlserver.rendering

import net.sourceforge.plantuml.code.ArobaseStringCompressor2
import net.sourceforge.plantuml.code.CompressionZlib
import net.sourceforge.plantuml.code.StringCompressor
import net.sourceforge.plantuml.code.TranscoderUtil
import org.springframework.stereotype.Service
import ru.sber.seaf.plantuml.plantumlserver.helper.RequestBodyHelper
import ru.sber.seaf.plantuml.plantumlserver.helper.PlantumlSourceHelper
import java.net.URLDecoder
import java.nio.charset.StandardCharsets

@Service
class PlantumlDecodingService {

    private val urlTranscoder = TranscoderUtil.getDefaultTranscoder()
    private val stringCompressor: StringCompressor = ArobaseStringCompressor2()

    fun decodeUrlPayload(payload: String): PlantumlSourceHelper =
        decodePlantumlUrl(payload).normalized()

    fun decodeBodyPayload(mode: String?, body: RequestBodyHelper): PlantumlSourceHelper {
        return when (mode) {
            "compressed" -> decodeUrlPayload(body.text())

            "zopfli" -> decodeSafely {
                val unzipped = CompressionZlib()
                    .decompress(body.bytes())
                    .toUTF8String()

                PlantumlSourceHelper(stringCompressor.decompress(unzipped))
            }.normalized()

            else -> decodeSafely {
                PlantumlSourceHelper(stringCompressor.decompress(body.text()))
            }.normalized()
        }
    }

    private fun decodePlantumlUrl(payload: String): PlantumlSourceHelper {
        val urlDecoded = decodeSafely {
            PlantumlSourceHelper(
                URLDecoder.decode(payload, StandardCharsets.UTF_8)
            )
        }.text

        return decodeSafely {
            PlantumlSourceHelper(urlTranscoder.decode(urlDecoded))
        }
    }

    private fun decodeSafely(block: () -> PlantumlSourceHelper): PlantumlSourceHelper =
        runCatching(block).getOrElse { PlantumlSourceHelper.error() }
}