package studio.tongtong.remotecompile import com.google.gson.Gson import com.google.gson.JsonObject import com.intellij.ide.passwordSafe.PasswordSafe import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.components.Service import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.util.Computable import java.net.URI import java.net.URLEncoder import java.net.http.HttpRequest import java.net.http.HttpResponse import java.nio.file.Files import java.nio.file.Path import java.security.MessageDigest import java.time.Duration import javax.swing.JOptionPane @Service(Service.Level.PROJECT) class PrivateFilesEditor(private val project: Project) { private data class Session(val file: VirtualFile, var hash: String, var content: String) private val sessions = mutableMapOf() private val active = mutableSetOf() private fun key(cfg: Settings.Data) = cfg.url.trim().trimEnd('/') + "\n" + cfg.remoteFolder.trim() private fun call(cfg: Settings.Data, content: String? = null, hash: String = ""): JsonObject { val base = cfg.url.trim().trimEnd('/') validateEndpoint(base) require(cfg.remoteFolder.isNotBlank()) { "请先填写并保存服务端工程来源目录" } val secret = PasswordSafe.instance.getPassword(credentials(base)).orEmpty() check(secret.isNotBlank()) { "请先保存服务器Token" } val route = "/private-files" + if (content == null) "?workspacePath=" + URLEncoder.encode(cfg.remoteFolder.trim(), Charsets.UTF_8) else "" val builder = HttpRequest.newBuilder(URI.create(base + "/api/v1" + route)).timeout(Duration.ofSeconds(60)) .header("Authorization", "Bearer $secret").header("Content-Type", "application/json") val req = if (content == null) builder.GET().build() else builder.PUT(HttpRequest.BodyPublishers.ofString(Gson().toJson( mapOf("workspacePath" to cfg.remoteFolder.trim(), "content" to content, "baseHash" to hash)))).build() val response = ServerTls.client(cfg.serverCertificate).send(req, HttpResponse.BodyHandlers.ofString()) check(response.statusCode() in 200..299) { if (response.statusCode() == 404) "服务端需升级至0.7.0以支持私有文件清单" else response.body().replace(secret, "***") } return Gson().fromJson(response.body(), JsonObject::class.java) } private fun describe(data: JsonObject): String = buildString { append(data.get("message").asString) append("\n清单位置:").append(data.get("manifestPath").asString) data.getAsJsonArray("entries").forEach { val entry = it.asJsonObject append("\n[").append(entry.get("status").asString).append("] ") .append(entry.get("path").asString).append(":").append(entry.get("message").asString) } } fun check(cfg: Settings.Data, status: (String) -> Unit) = execute(cfg, status, { call(cfg) }) { status(describe(it)) } // Network requests run on a worker; model reads hold a read action. private fun documentText(file: VirtualFile): String? = ApplicationManager.getApplication().runReadAction(Computable { FileDocumentManager.getInstance().getDocument(file)?.text }) private fun onEditorThread(status: (String) -> Unit, action: () -> Unit) { // invokeLater supplies write intent on modern IDEs; avoid linking the changing // WriteIntentReadAction.run binary signature across Android Studio versions. ApplicationManager.getApplication().invokeLater { if (project.isDisposed) return@invokeLater try { action() } catch (e: Exception) { status("清单编辑失败:${e.message}") } } } fun edit(cfg: Settings.Data, status: (String) -> Unit, reload: Boolean = false) = onEditorThread(status) { editOnEditorThread(cfg, status, reload) } private fun editOnEditorThread(cfg: Settings.Data, status: (String) -> Unit, reload: Boolean) { val key = key(cfg) val existing = sessions[key] if (existing != null && !reload) { FileEditorManager.getInstance(project).openFile(existing.file, true) status("已打开本地清单。修改后点击侧边栏“保存清单到服务端”;Ctrl+S只保存本地编辑副本。") return } if (existing != null && reload) { val current = documentText(existing.file) if (current != existing.content && JOptionPane.showConfirmDialog(null, "重新读取会替换本地清单修改,是否继续?", "重新读取私有文件清单", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return } execute(cfg, status, { call(cfg) }) { data -> val text = data.get("content").asString.replace("\r\n", "\n").replace('\r', '\n') val id = MessageDigest.getInstance("SHA-256").digest(key.toByteArray()).joinToString("") { "%02x".format(it) } val directory = Path.of(PathManager.getSystemPath(), "remotecompile-private-lists") Files.createDirectories(directory) val folder = directory.resolve(id) Files.createDirectories(folder) val path = folder.resolve("私有文件清单.txt") // Keep a recoverable local draft when reopening after IDE restart. if (existing == null && Files.exists(path) && Files.readString(path) != text) { Files.copy(path, folder.resolve("私有文件清单.draft-${System.currentTimeMillis()}.txt")) } val initial = text.ifBlank { "# 每行一个相对于服务端工程来源目录的文件路径,使用 /\n# config.gradle\n# app/keystore/example.jks\n" } ApplicationManager.getApplication().runWriteAction { if (existing == null) Files.writeString(path, initial) val file = existing?.file ?: LocalFileSystem.getInstance().refreshAndFindFileByIoFile(path.toFile()) ?: error("无法创建清单编辑副本") file.charset = Charsets.UTF_8 val document = FileDocumentManager.getInstance().getDocument(file) ?: error("无法打开清单文档") document.setText(initial) FileDocumentManager.getInstance().saveDocument(document) sessions[key] = Session(file, data.get("hash").asString, initial) FileEditorManager.getInstance(project).openFile(file, true) } status(describe(data) + "\n已在IDE打开;编辑后请点击“保存清单到服务端”。本地副本只包含路径,不包含签名文件内容。") } } fun save(cfg: Settings.Data, status: (String) -> Unit) = onEditorThread(status) { saveOnEditorThread(cfg, status) } private fun saveOnEditorThread(cfg: Settings.Data, status: (String) -> Unit) { val session = sessions[key(cfg)] ?: run { status("请先点击编辑私有文件清单"); return } val document = ApplicationManager.getApplication().runReadAction(Computable { FileDocumentManager.getInstance().getDocument(session.file) }) ?: run { status("清单文档不可用,请重新编辑"); return } FileDocumentManager.getInstance().saveDocument(document) // IDE save actions may strip trailing spaces or add a final newline. // Publish the document after those changes, never a pre-save snapshot. val content = documentText(session.file) ?: run { status("清单文档不可用,请重新编辑"); return } execute(cfg, status, { call(cfg, content, session.hash) }) { data -> session.hash = data.get("hash").asString; session.content = data.get("content").asString status("已保存到服务端;构建前会按清单复制文件。\n" + describe(data)) } } fun requirePublished(cfg: Settings.Data) { val key = key(cfg) check(key !in active) { "私有文件清单操作仍在进行,请完成后再构建" } sessions[key]?.let { session -> val text = documentText(session.file) check(text == null || PrivateListText.entries(text) == PrivateListText.entries(session.content)) { "私有文件清单已在IDE修改,请先点击侧边栏“保存清单到服务端”" } } } private fun execute(cfg: Settings.Data, status: (String) -> Unit, work: () -> JsonObject, done: (JsonObject) -> Unit) { val key = key(cfg) if (!active.add(key)) { status("清单操作正在进行,请稍后"); return } status("正在处理服务端私有文件清单…") ApplicationManager.getApplication().executeOnPooledThread { val result = runCatching(work) ApplicationManager.getApplication().invokeLater { active.remove(key) if (project.isDisposed) return@invokeLater try { result.fold(done) { status("私有文件清单操作失败:${it.message}") } } catch (e: Exception) { status("清单编辑失败:${e.message}") } } } } }