按工程保存前后置命令和自动启动选项,全程绑定选中设备,区分安装与后续动作失败。通过实际APK及目标设备解析Launcher入口,兼容activity-alias;增加模拟进程回归测试及0.8.0三套服务部署记录。
685 lines
45 KiB
Kotlin
685 lines
45 KiB
Kotlin
package studio.tongtong.remotecompile
|
||
|
||
import com.google.gson.Gson
|
||
import com.google.gson.JsonObject
|
||
import com.intellij.ide.passwordSafe.PasswordSafe
|
||
import com.intellij.openapi.actionSystem.AnAction
|
||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||
import com.intellij.openapi.application.ApplicationManager
|
||
import com.intellij.openapi.Disposable
|
||
import com.intellij.util.concurrency.AppExecutorUtil
|
||
import com.intellij.openapi.components.Service
|
||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||
import com.intellij.openapi.progress.ProgressIndicator
|
||
import com.intellij.openapi.progress.Task
|
||
import com.intellij.openapi.project.Project
|
||
import com.intellij.openapi.wm.ToolWindow
|
||
import com.intellij.openapi.wm.ToolWindowFactory
|
||
import com.intellij.openapi.wm.ToolWindowManager
|
||
import com.intellij.ui.content.ContentFactory
|
||
import com.intellij.util.ui.JBUI
|
||
import java.awt.BorderLayout
|
||
import java.net.URI
|
||
import java.net.URLEncoder
|
||
import java.net.http.HttpClient
|
||
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 java.util.Base64
|
||
import java.util.UUID
|
||
import java.util.concurrent.TimeUnit
|
||
import java.util.concurrent.atomic.AtomicBoolean
|
||
import javax.swing.*
|
||
|
||
@Service(Service.Level.PROJECT)
|
||
class PanelService(val project: Project) {
|
||
var panel: RemotePanel? = null
|
||
}
|
||
|
||
class RemoteToolWindow : ToolWindowFactory {
|
||
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
|
||
val panel = RemotePanel(project)
|
||
project.getService(PanelService::class.java).panel = panel
|
||
val content = ContentFactory.getInstance().createContent(panel, "构建日志", false)
|
||
content.setDisposer(panel)
|
||
toolWindow.contentManager.addContent(content)
|
||
}
|
||
}
|
||
class RemoteRunAction : AnAction() {
|
||
override fun actionPerformed(e: AnActionEvent) {
|
||
val project = e.project ?: return
|
||
ToolWindowManager.getInstance(project).getToolWindow("Remote Compilation")?.show {
|
||
project.getService(PanelService::class.java).panel?.runBuild()
|
||
}
|
||
}
|
||
}
|
||
|
||
class RemoteSettingsAction : AnAction() {
|
||
override fun actionPerformed(e: AnActionEvent) {
|
||
e.project?.let { ToolWindowManager.getInstance(it).getToolWindow("Remote Configuration")?.show() }
|
||
}
|
||
}
|
||
|
||
class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Disposable {
|
||
private val settings = project.getService(Settings::class.java)
|
||
private val taskSelector = JComboBox<String>().apply { isEditable = true; maximumRowCount = 12 }
|
||
private var updatingTasks = false
|
||
private var discoveredTasks = emptyList<String>()
|
||
private val devices = JComboBox<AdbDevice>()
|
||
private val refresh = JButton("刷新设备")
|
||
private val remoteAdb = JCheckBox("使用服务端 ADB 安装", settings.snapshot().remoteAdb).apply { toolTipText = "读取服务器设备;构建成功后由服务端直接安装 APK,同时保留本机下载" }
|
||
private val deviceStatus = JLabel("正在读取本机设备…")
|
||
private val refreshing = AtomicBoolean(false)
|
||
private var updatingDevices = false
|
||
@Volatile private var disposed = false
|
||
private val run = JButton("Remote Run")
|
||
private val cancel = JButton("取消远程构建")
|
||
private val buildIdField = JTextField().apply { minimumSize = JBUI.size(0, 24) }
|
||
private val progress = JProgressBar(0, 100).apply {
|
||
isStringPainted = false
|
||
preferredSize = JBUI.size(0, 12)
|
||
minimumSize = JBUI.size(0, 12)
|
||
}
|
||
private val progressPercent = JLabel("—")
|
||
private val progressStatus = JTextArea("就绪", 2, 0).apply {
|
||
isEditable = false; isOpaque = false; lineWrap = true; wrapStyleWord = true
|
||
font = UIManager.getFont("Label.font")
|
||
foreground = UIManager.getColor("Label.foreground")
|
||
minimumSize = JBUI.size(0, 32)
|
||
}
|
||
private val resume = JButton("恢复上次构建")
|
||
private val fetch = JButton("下载 APK")
|
||
private val log = JTextArea().apply { isEditable = false; lineWrap = true; wrapStyleWord = true }
|
||
private val logFormat = TimestampedLog()
|
||
@Volatile private var activeBuild = ""
|
||
@Volatile private var cancelRequested = false
|
||
@Volatile private var busy = false
|
||
private val gson = Gson()
|
||
private var http = ServerTls.client("")
|
||
private val polling = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay({ refreshDevices() }, 1, 5, TimeUnit.SECONDS)
|
||
init {
|
||
val configure = JButton("连接设置")
|
||
val refreshTasks = JButton("刷新变体")
|
||
taskSelector.toolTipText = "选择任务或直接输入;自动记住最近 20 个任务"
|
||
updateTaskChoices(settings.snapshot().task)
|
||
taskSelector.addActionListener {
|
||
if (!updatingTasks) {
|
||
val value = taskSelector.editor.item?.toString()?.trim().orEmpty()
|
||
if (BuildTasks.valid(value)) { settings.selectTask(value); updateTaskChoices(value) }
|
||
}
|
||
}
|
||
refreshTasks.addActionListener { refreshTaskChoices(refreshTasks) }
|
||
refreshTaskChoices(refreshTasks)
|
||
devices.prototypeDisplayValue = AdbDevice("serial", "device", "选择本机设备或模拟器")
|
||
devices.renderer = object : DefaultListCellRenderer() {
|
||
override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, selected: Boolean, focus: Boolean): java.awt.Component {
|
||
val component = super.getListCellRendererComponent(list, value ?: "请选择设备", index, selected, focus)
|
||
isEnabled = value !is AdbDevice || value.online
|
||
return component
|
||
}
|
||
}
|
||
devices.addActionListener { if (!updatingDevices) (devices.selectedItem as? AdbDevice)?.takeIf { it.online }?.let { settings.selectDevice(it.serial) } }
|
||
refresh.addActionListener { refreshDevices() }
|
||
remoteAdb.addActionListener {
|
||
if (busy) { remoteAdb.isSelected = settings.snapshot().remoteAdb; return@addActionListener }
|
||
settings.selectRemoteAdb(remoteAdb.isSelected)
|
||
updatingDevices = true; devices.removeAllItems(); updatingDevices = false
|
||
deviceStatus.text = if (remoteAdb.isSelected) "正在读取服务端设备…" else "正在读取本机设备…"
|
||
refreshDevices()
|
||
}
|
||
configure.addActionListener { ToolWindowManager.getInstance(project).getToolWindow("Remote Configuration")?.show() }
|
||
val history = JButton("构建历史").apply { addActionListener { showHistory() } }
|
||
val installLast = JButton("安装已下载 APK").apply { addActionListener { installDownloaded() } }
|
||
val environment = JButton("查看构建环境").apply { addActionListener { showEnvironment() } }
|
||
val progressArea = JPanel(BorderLayout(0, JBUI.scale(4))).apply {
|
||
border = JBUI.Borders.empty(4, 8, 6, 8)
|
||
add(JPanel(BorderLayout(JBUI.scale(6), 0)).apply {
|
||
add(progress, BorderLayout.CENTER)
|
||
add(progressPercent, BorderLayout.EAST)
|
||
}, BorderLayout.NORTH)
|
||
add(JScrollPane(progressStatus).apply {
|
||
border = BorderFactory.createEmptyBorder()
|
||
isOpaque = false; viewport.isOpaque = false
|
||
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
|
||
}, BorderLayout.CENTER)
|
||
}
|
||
devices.minimumSize = JBUI.size(0, 24)
|
||
taskSelector.minimumSize = JBUI.size(0, 24)
|
||
fun column(vararg parts: JComponent) = JPanel().apply {
|
||
layout = BoxLayout(this, BoxLayout.Y_AXIS)
|
||
parts.forEachIndexed { index, part ->
|
||
if (index > 0) add(Box.createVerticalStrut(JBUI.scale(10)))
|
||
part.alignmentX = java.awt.Component.LEFT_ALIGNMENT
|
||
part.minimumSize = JBUI.size(0, part.minimumSize.height)
|
||
part.maximumSize = java.awt.Dimension(Int.MAX_VALUE, part.preferredSize.height)
|
||
add(part)
|
||
}
|
||
}
|
||
// Both columns share the same rows, including the differently sized label/checkbox.
|
||
val headings = JPanel(java.awt.GridBagLayout()).apply {
|
||
fun cell(component: JComponent, x: Int, y: Int, gap: Int) {
|
||
component.minimumSize = JBUI.size(0, component.minimumSize.height)
|
||
component.preferredSize = java.awt.Dimension(0, component.preferredSize.height)
|
||
add(component, java.awt.GridBagConstraints().apply {
|
||
gridx = x; gridy = y; weightx = 1.0
|
||
fill = java.awt.GridBagConstraints.BOTH
|
||
insets = JBUI.insets(gap, if (x == 0) 0 else 4, 0, if (x == 0) 4 else 0)
|
||
})
|
||
}
|
||
cell(JLabel("目标设备"), 0, 0, 0)
|
||
cell(JLabel("构建 ID"), 1, 0, 0)
|
||
cell(devices, 0, 1, 6)
|
||
cell(buildIdField, 1, 1, 6)
|
||
cell(deviceStatus, 0, 2, 6)
|
||
cell(JLabel("留空找回上次构建"), 1, 2, 6)
|
||
cell(JLabel("构建变体 / Gradle 任务"), 0, 3, 10)
|
||
cell(remoteAdb, 1, 3, 10)
|
||
cell(taskSelector, 0, 4, 6)
|
||
cell(JButton("服务端安装 APK").apply { addActionListener { installServerBuild() } }, 1, 4, 6)
|
||
}
|
||
val actions = JPanel(java.awt.GridLayout(0, 2, JBUI.scale(8), JBUI.scale(6))).apply {
|
||
add(refreshTasks); add(resume)
|
||
add(run); add(fetch)
|
||
add(cancel); add(history)
|
||
add(refresh); add(installLast)
|
||
add(configure); add(environment)
|
||
}
|
||
val columns = column(headings, actions)
|
||
val sections = column(columns, progressArea)
|
||
val controls = object : JPanel(BorderLayout()), Scrollable {
|
||
override fun getPreferredScrollableViewportSize() = preferredSize
|
||
override fun getScrollableTracksViewportWidth() = true
|
||
override fun getScrollableTracksViewportHeight() = false
|
||
override fun getScrollableUnitIncrement(rect: java.awt.Rectangle, orientation: Int, direction: Int) = JBUI.scale(20)
|
||
override fun getScrollableBlockIncrement(rect: java.awt.Rectangle, orientation: Int, direction: Int) = maxOf(JBUI.scale(20), rect.height - JBUI.scale(20))
|
||
}.apply { border = JBUI.Borders.empty(10); add(sections, BorderLayout.NORTH) }
|
||
resume.addActionListener { recoverBuild(false) }
|
||
fetch.addActionListener { recoverBuild(true) }
|
||
val controlsScroll = JScrollPane(controls).apply {
|
||
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
|
||
minimumSize = JBUI.size(220, 0)
|
||
}
|
||
val logScroll = JScrollPane(log).apply {
|
||
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
|
||
minimumSize = JBUI.size(200, 0)
|
||
}
|
||
add(JSplitPane(JSplitPane.HORIZONTAL_SPLIT, controlsScroll, logScroll).apply {
|
||
isContinuousLayout = true; isOneTouchExpandable = true
|
||
resizeWeight = 0.0; dividerLocation = JBUI.scale(320)
|
||
border = BorderFactory.createEmptyBorder()
|
||
}, BorderLayout.CENTER)
|
||
run.addActionListener { runBuild() }
|
||
cancel.addActionListener { cancelRequested = true; append("已请求取消,等待当前网络操作结束…") }
|
||
}
|
||
private fun updateTaskChoices(selected: String) {
|
||
val cfg = settings.snapshot()
|
||
val choices = (listOf(selected) + cfg.taskHistory + discoveredTasks + listOf(":app:assembleDebug")).filter { it.isNotBlank() }.distinct()
|
||
updatingTasks = true
|
||
try { taskSelector.model = DefaultComboBoxModel(choices.toTypedArray()); taskSelector.selectedItem = selected }
|
||
finally { updatingTasks = false }
|
||
}
|
||
private fun refreshTaskChoices(button: JButton) {
|
||
button.isEnabled = false
|
||
ApplicationManager.getApplication().executeOnPooledThread {
|
||
val result = runCatching { project.basePath?.let { BuildTasks.discover(Path.of(it)) }.orEmpty() }
|
||
ApplicationManager.getApplication().invokeLater {
|
||
if (!disposed && !project.isDisposed) {
|
||
button.isEnabled = true
|
||
result.onSuccess { discoveredTasks = it; updateTaskChoices(taskSelector.editor.item?.toString()?.trim().orEmpty().ifEmpty { settings.snapshot().task }) }
|
||
.onFailure { append("读取变体候选失败,可直接输入任务:${it.message}") }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
override fun dispose() {
|
||
disposed = true; polling.cancel(false)
|
||
if (!project.isDisposed && project.getService(PanelService::class.java).panel === this) project.getService(PanelService::class.java).panel = null
|
||
}
|
||
fun refreshDevices() {
|
||
if (disposed || project.isDisposed || !refreshing.compareAndSet(false, true)) return
|
||
ApplicationManager.getApplication().executeOnPooledThread {
|
||
val cfg = settings.snapshot()
|
||
val result = runCatching { if (cfg.remoteAdb) ServerAdb.devices(cfg) else AdbDevices.list(AdbDevices.resolve(Path.of(project.basePath ?: error("项目路径不存在")), cfg.adb)) }
|
||
ApplicationManager.getApplication().invokeLater {
|
||
try {
|
||
if (!disposed && !project.isDisposed && settings.snapshot().let { it.remoteAdb == cfg.remoteAdb && it.url == cfg.url }) {
|
||
val found = result.getOrDefault(emptyList())
|
||
val previous = (devices.selectedItem as? AdbDevice)?.serial ?: (if (cfg.remoteAdb) cfg.remoteDevice else cfg.device)
|
||
if ((0 until devices.itemCount).map { devices.getItemAt(it) } != found) {
|
||
updatingDevices = true
|
||
try {
|
||
devices.model = DefaultComboBoxModel(found.toTypedArray())
|
||
devices.selectedItem = AdbDevices.choose(found, previous)
|
||
} finally { updatingDevices = false }
|
||
}
|
||
deviceStatus.text = result.exceptionOrNull()?.message ?: if (found.isEmpty()) "没有检测到设备;请连接手机或启动模拟器" else "${if (cfg.remoteAdb) "服务端" else "本机"} ${found.count { it.online }} 台可用设备;可自动识别插拔"
|
||
}
|
||
} finally { refreshing.set(false) }
|
||
}
|
||
}
|
||
}
|
||
private fun append(text: String) = ApplicationManager.getApplication().invokeLater {
|
||
if (!disposed && !project.isDisposed) { log.append(logFormat.message(text)); log.caretPosition = log.document.length }
|
||
}
|
||
private fun appendBuildChunk(text: String) = ApplicationManager.getApplication().invokeLater {
|
||
if (!disposed && !project.isDisposed) { log.append(logFormat.chunk(text)); log.caretPosition = log.document.length }
|
||
}
|
||
private fun hash(data: ByteArray) = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) }
|
||
private fun fileHash(path: Path): String {
|
||
val digest = MessageDigest.getInstance("SHA-256")
|
||
Files.newInputStream(path).use { input ->
|
||
val buffer = ByteArray(128 * 1024)
|
||
while (true) { val count = input.read(buffer); if (count < 0) break; digest.update(buffer, 0, count) }
|
||
}
|
||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||
}
|
||
private fun request(base: String, secret: String, method: String, route: String, body: Any? = null): ByteArray {
|
||
val publisher = if (body == null) HttpRequest.BodyPublishers.noBody() else HttpRequest.BodyPublishers.ofString(gson.toJson(body))
|
||
val req = HttpRequest.newBuilder(URI.create(base + "/api/v1" + route)).timeout(Duration.ofMinutes(5))
|
||
.header("Authorization", "Bearer $secret").header("Content-Type", "application/json").method(method, publisher).build()
|
||
val response = http.send(req, HttpResponse.BodyHandlers.ofByteArray())
|
||
check(response.statusCode() in 200..299) { ServerErrors.describe(response.statusCode(), route, String(response.body(), Charsets.UTF_8)) }
|
||
return response.body()
|
||
}
|
||
private fun json(base: String, secret: String, method: String, route: String, body: Any? = null) =
|
||
gson.fromJson(String(request(base, secret, method, route, body)), JsonObject::class.java)
|
||
fun runBuild() {
|
||
if (busy) return
|
||
busy = true; run.isEnabled = false
|
||
// ToolWindow.show callbacks in newer IDEs can run on Dispatchers.UI(RELAX).
|
||
// Application.invokeLater supplies write intent across supported IDE versions.
|
||
// Do not link WriteIntentReadAction.run: its binary signature changed in newer IDEs.
|
||
ApplicationManager.getApplication().invokeLater {
|
||
if (disposed || project.isDisposed) { busy = false; return@invokeLater }
|
||
try {
|
||
FileDocumentManager.getInstance().saveAllDocuments()
|
||
beginBuild()
|
||
} catch (e: Exception) {
|
||
busy = false; run.isEnabled = true; append("无法启动:${e.message ?: e.javaClass.simpleName}")
|
||
}
|
||
}
|
||
}
|
||
private fun beginBuild() {
|
||
val selectedTask = taskSelector.editor.item?.toString()?.trim().orEmpty()
|
||
settings.selectTask(selectedTask)
|
||
updateTaskChoices(selectedTask)
|
||
val cfg = settings.snapshot()
|
||
project.getService(PrivateFilesEditor::class.java).requirePublished(cfg)
|
||
val base = cfg.url.trim().trimEnd('/')
|
||
validateEndpoint(base)
|
||
require(cfg.remoteFolder.isNotBlank()) { "请在 Remote Configuration 中填写服务端已有工程文件夹,并点击检查远程工程" }
|
||
val selected = devices.selectedItem as? AdbDevice
|
||
val source = project.basePath?.let { Path.of(it) } ?: error("项目路径不存在")
|
||
cancelRequested = false; activeBuild = ""; log.text = ""; logFormat.reset()
|
||
object : Task.Backgroundable(project, "Remote Compilation", false) {
|
||
override fun run(indicator: ProgressIndicator) {
|
||
var secret = ""
|
||
var buildSucceeded = false
|
||
try {
|
||
http = ServerTls.client(cfg.serverCertificate)
|
||
secret = PasswordSafe.instance.getPassword(credentials(base)) ?: ""
|
||
check(secret.length >= 24) { "请在右侧 Remote Configuration 中保存服务 Token" }
|
||
append("构建任务:${cfg.task}")
|
||
append("安装位置:${if (cfg.remoteAdb) "服务端 ADB" else "本机 ADB"}")
|
||
append(if (selected?.online == true) "目标设备:$selected" else "当前没有选中的在线设备;继续远程编译并下载 APK")
|
||
val health = json(base, secret, "GET", "/health")
|
||
check(health.get("recovery")?.asBoolean == true) { "编译服务需升级到 0.2.0 才支持任务找回与环境复用" }
|
||
check(health.get("textComparison")?.asBoolean == true && health.get("jdkSelection")?.asBoolean == true) { "编译服务需升级到 0.4.0 才支持换行比较及 JDK 选择" }
|
||
check(health.get("workspaceSelection")?.asBoolean == true) { "编译服务需升级到 0.3.0 才支持工程目录与 Git 检查" }
|
||
val localGit = SourceFiles.snapshot(source)
|
||
val dedicated = localGit != null
|
||
if (dedicated) check(health.get("dedicatedGit")?.asBoolean == true) { "服务端需升级至0.5.0以支持专用Git工作区" }
|
||
val checkBody = mapOf("workspacePath" to cfg.remoteFolder, "projectId" to cfg.projectId, "git" to localGit, "javaHome" to cfg.remoteJavaHome, "dedicated" to dedicated)
|
||
val inspection = json(base, secret, "POST", "/projects/check", checkBody)
|
||
append("远程位置:${inspection.get("workspacePath").asString}")
|
||
append("Git 检查:${inspection.get("message").asString};本机=$localGit;编译工作区基线=${inspection.get("git")}")
|
||
check(inspection.get("canSync").asBoolean) { inspection.get("message").asString }
|
||
inspection.getAsJsonObject("preflight")?.let { report ->
|
||
append(PreflightChecks.describe(report))
|
||
check(report.get("ready").asBoolean) { "远程环境检查未通过,请处理上方错误后重试" }
|
||
}
|
||
val candidates = SourceFiles.collect(source, localGit)
|
||
if (cfg.projectId.isBlank() || dedicated) {
|
||
cfg.projectId = json(base, secret, "POST", "/projects", checkBody).get("id").asString
|
||
settings.projectAllocated(base, cfg.projectId, cfg.remoteFolder)
|
||
}
|
||
val remoteState = json(base, secret, "GET", "/projects/${cfg.projectId}/manifest")
|
||
if (dedicated) {
|
||
val previousHead = remoteState.getAsJsonObject("git")?.get("head")?.asString
|
||
if (previousHead != localGit!!.head) uploadGitBundle(base, secret, cfg.projectId, source, localGit.head, previousHead)
|
||
append("专用编译工作区:${remoteState.get("workspacePath").asString}")
|
||
}
|
||
val manifest = remoteState.getAsJsonObject("files")
|
||
val files = linkedMapOf<String, Map<String, String>>()
|
||
var changed = 0; var lineEndingsOnly = 0
|
||
for (path in candidates) {
|
||
val name = source.relativize(path).joinToString("/")
|
||
check(Files.size(path) <= 64L * 1024 * 1024) { "文件超过首版 64MiB 上限:$name" }
|
||
val bytes = Files.readAllBytes(path); val hash = hash(bytes)
|
||
val remote = manifest?.getAsJsonObject(name)
|
||
val remoteHash = remote?.get("hash")?.asString
|
||
val remoteTextHash = remote?.get("textHash")?.asString
|
||
files[name] = when {
|
||
remoteHash == hash -> mapOf("hash" to hash)
|
||
cfg.ignoreLineEndings && remoteTextHash != null && remoteTextHash == SyncComparison.textHash(name, bytes) -> {
|
||
lineEndingsOnly++; mapOf("hash" to checkNotNull(remoteHash))
|
||
}
|
||
else -> { changed++; mapOf("hash" to hash, "data" to Base64.getEncoder().encodeToString(bytes)) }
|
||
}
|
||
}
|
||
check(SourceFiles.snapshot(source).let { it?.head == localGit?.head && it?.branch == localGit?.branch }) { "扫描期间 Git 状态发生变化,请重新运行" }
|
||
check(!cancelRequested) { "已取消" }
|
||
val revision = UUID.randomUUID().toString()
|
||
append("同步 ${files.size} 个文件,上传 $changed 个变更文件,跳过 $lineEndingsOnly 个仅换行不同的文件…")
|
||
json(base, secret, "POST", "/projects/${cfg.projectId}/sync", mapOf("revision" to revision, "files" to files, "git" to localGit))
|
||
check(!cancelRequested) { "已取消" }
|
||
val record = LastBuild(base, cfg.projectId, revision, cfg.task, UUID.randomUUID().toString(), certificate = cfg.serverCertificate, javaHome = cfg.remoteJavaHome)
|
||
LastBuildStore.save(source, record)
|
||
activeBuild = json(base, secret, "POST", "/projects/${cfg.projectId}/builds",
|
||
mapOf("revision" to revision, "task" to cfg.task, "clientRequestId" to record.clientRequestId, "javaHome" to record.javaHome)).get("id").asString
|
||
record.buildId = activeBuild; LastBuildStore.save(source, record)
|
||
setBuildId(activeBuild)
|
||
append("构建ID:$activeBuild(已保存,断网后可恢复)")
|
||
val result = watchBuild(base, secret, activeBuild)
|
||
buildSucceeded = true
|
||
append("构建已成功,正在选择和下载 APK")
|
||
val chosen = selectArtifact(source, activeBuild, result)
|
||
if (cfg.remoteAdb) {
|
||
try { installServer(cfg, activeBuild, chosen, selected) }
|
||
catch (e: Exception) { append("构建成功,服务端安装未完成:${e.message};产物保留,可稍后点击服务端安装 APK") }
|
||
}
|
||
val output = downloadApk(base, secret, activeBuild, source, result, chosen)
|
||
check(!cancelRequested) { "已取消安装" }
|
||
if (cfg.install && !cfg.remoteAdb) {
|
||
try { installApkWhenAvailable(source, cfg, selected, output) }
|
||
catch (e: Exception) {
|
||
append("编译和下载已成功,安装未完成:${e.message ?: e.javaClass.simpleName};APK 已保留,可稍后点击安装已下载 APK")
|
||
}
|
||
}
|
||
append("远程编译和 APK 下载完成")
|
||
} catch (e: Exception) {
|
||
// Never print request headers or the token.
|
||
append((if (buildSucceeded) "构建已成功,APK 下载未完成(可恢复构建后重新选择):" else if (activeBuild.isNotEmpty()) "构建失败(记录已保留,可点击恢复上次构建):" else "同步或启动失败(尚未确认创建构建任务):") + (e.message ?: e.javaClass.simpleName).let { if (secret.isNotEmpty()) it.replace(secret, "***") else it })
|
||
} finally {
|
||
activeBuild = ""; busy = false
|
||
ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true }
|
||
}
|
||
}
|
||
}.queue()
|
||
}
|
||
private fun uploadGitBundle(base: String, secret: String, projectId: String, source: Path, head: String, previous: String?) {
|
||
fun send(baseHead: String?) {
|
||
append("正在生成提交元数据 bundle(不包含文件内容)…")
|
||
val bundle = GitBundles.create(source, head, baseHead)
|
||
try {
|
||
append("上传 Git 提交 $head,bundle ${Files.size(bundle)} 字节")
|
||
val req = HttpRequest.newBuilder(URI.create("$base/api/v1/projects/$projectId/git?head=$head"))
|
||
.header("Authorization", "Bearer $secret").header("Content-Type", "application/octet-stream")
|
||
.timeout(Duration.ofMinutes(10)).POST(HttpRequest.BodyPublishers.ofFile(bundle)).build()
|
||
val response = http.send(req, HttpResponse.BodyHandlers.ofString())
|
||
check(response.statusCode() == 200) { ServerErrors.describe(response.statusCode(), "/projects/$projectId/git", response.body()) }
|
||
} finally { GitBundles.delete(bundle) }
|
||
}
|
||
try { send(previous) } catch (e: Exception) {
|
||
if (!previous.isNullOrBlank() && e.message.orEmpty().startsWith("HTTP 400:")) { append("增量bundle不可用,重试完整提交历史"); send(null) } else throw e
|
||
}
|
||
}
|
||
private fun installApkWhenAvailable(source: Path, cfg: Settings.Data, selected: AdbDevice?, output: Path) {
|
||
val adb = AdbDevices.resolve(source, cfg.adb)
|
||
val connected = AdbDevices.list(adb)
|
||
val target = AdbDevices.choose(connected, selected?.serial ?: cfg.device, explicit = selected != null)
|
||
if (target == null) {
|
||
append("编译成功,APK 已保存;没有可安装的目标设备或尚未明确选择,跳过自动安装。连接并选择设备后可点击安装已下载 APK")
|
||
return
|
||
}
|
||
settings.selectDevice(target.serial)
|
||
append("安装目标:$target")
|
||
InstallActions.install(source, cfg, adb, target.serial, output, ::append)
|
||
}
|
||
private fun setBuildId(id: String) = ApplicationManager.getApplication().invokeLater { if (!disposed) buildIdField.text = id }
|
||
private fun showProgress(message: String, percent: Int = -1) = ApplicationManager.getApplication().invokeLater {
|
||
if (!disposed) {
|
||
progress.isIndeterminate = percent < 0
|
||
if (percent >= 0) progress.value = percent.coerceIn(0, 100)
|
||
progressPercent.text = if (percent < 0) "进行中" else "${progress.value}%"
|
||
progressStatus.text = message; progressStatus.caretPosition = 0
|
||
progressStatus.toolTipText = message; progress.toolTipText = message
|
||
}
|
||
}
|
||
private fun watchBuild(base: String, secret: String, id: String): JsonObject {
|
||
var offset = 0; var failures = 0; var environmentPrinted = false
|
||
while (true) {
|
||
check(!project.isDisposed && !disposed) { "项目已关闭,远端任务不受影响" }
|
||
if (cancelRequested) { json(base, secret, "DELETE", "/builds/$id"); error("已请求取消远程构建") }
|
||
val result = try { json(base, secret, "GET", "/builds/$id").also { failures = 0 } }
|
||
catch (e: java.io.IOException) {
|
||
failures++; showProgress("连接中断,重试 $failures/3;远端构建不会被取消")
|
||
if (failures >= 3) throw e
|
||
Thread.sleep(failures * 1500L); continue
|
||
}
|
||
val lines = result.getAsJsonArray("logs")
|
||
while (offset < lines.size()) appendBuildChunk(lines[offset++].asString)
|
||
if (!environmentPrinted && result.has("environment")) {
|
||
append("实际构建环境:" + result.get("environment")); environmentPrinted = true
|
||
}
|
||
val status = result.get("status").asString
|
||
val detail = result.getAsJsonObject("progress")
|
||
val message = detail?.get("message")?.asString.orEmpty()
|
||
val path = detail?.get("path")?.asString.orEmpty()
|
||
showProgress(if (message.isNotBlank()) "$message $path" else "构建 $id:$status", if (message.isNotBlank()) detail?.get("percent")?.asInt ?: -1 else -1)
|
||
if (status !in listOf("queued", "running")) {
|
||
showProgress("构建 $id:$status", if (status == "success") 100 else 0)
|
||
check(status == "success") { "构建状态:$status;可查看上方日志" }
|
||
return result
|
||
}
|
||
Thread.sleep(1000)
|
||
}
|
||
}
|
||
private fun selectArtifact(source: Path, id: String, result: JsonObject): ApkArtifact {
|
||
require(id.matches(Regex("[a-f0-9]{32}"))) { "无效构建 ID" }
|
||
val artifacts = ApkArtifacts.read(result)
|
||
check(artifacts.isNotEmpty()) { "成功构建没有可下载的 APK" }
|
||
val previous = LastBuildStore.load(source)?.takeIf { it.buildId == id }?.artifactName
|
||
val artifact = if (artifacts.size == 1) artifacts.single() else {
|
||
append("构建生成 ${artifacts.size} 个 APK,请选择要使用的完整安装包;其他产物保留在服务端")
|
||
var chosen: ApkArtifact? = null
|
||
ApplicationManager.getApplication().invokeAndWait {
|
||
if (!disposed && !project.isDisposed) {
|
||
chosen = JOptionPane.showInputDialog(this,
|
||
"选择要使用的 APK;不同渠道或签名包请按实际用途选择。\n拆分 APK 需成套安装,当前不支持自动安装拆分包。",
|
||
"选择构建产物", JOptionPane.QUESTION_MESSAGE, null,
|
||
artifacts.toTypedArray(), artifacts.firstOrNull { it.name == previous } ?: artifacts.first()) as? ApkArtifact
|
||
}
|
||
}
|
||
chosen ?: error("已取消选择 APK;构建已成功,产物仍保留,可点击下载 APK 重新选择")
|
||
}
|
||
append("选择 APK:$artifact")
|
||
return artifact
|
||
}
|
||
private fun downloadApk(base: String, secret: String, id: String, source: Path, result: JsonObject, selectedArtifact: ApkArtifact? = null): Path {
|
||
val artifact = selectedArtifact ?: selectArtifact(source, id, result)
|
||
val expected = artifact.hash
|
||
val size = artifact.size
|
||
val directory = source.resolve(".remotecompile"); Files.createDirectories(directory)
|
||
val part = directory.resolve("$id-$expected.apk.part")
|
||
var received = if (Files.exists(part)) Files.size(part) else 0L
|
||
if (received > size) { Files.delete(part); received = 0 }
|
||
if (received < size) {
|
||
val name = URLEncoder.encode(artifact.name, Charsets.UTF_8).replace("+", "%20")
|
||
val builder = HttpRequest.newBuilder(URI.create("$base/api/v1/builds/$id/artifacts/$name"))
|
||
.header("Authorization", "Bearer $secret").timeout(Duration.ofMinutes(5))
|
||
if (received > 0) builder.header("Range", "bytes=$received-")
|
||
val response = http.send(builder.GET().build(), HttpResponse.BodyHandlers.ofInputStream())
|
||
response.body().use { input ->
|
||
check(response.statusCode() == 200 || response.statusCode() == 206) { "下载 HTTP ${response.statusCode()}" }
|
||
if (response.statusCode() == 200) received = 0
|
||
else check(response.headers().firstValue("Content-Range").orElse("").startsWith("bytes $received-")) { "断点下载偏移不匹配" }
|
||
val options = if (received > 0) arrayOf(java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.APPEND)
|
||
else arrayOf(java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.TRUNCATE_EXISTING)
|
||
Files.newOutputStream(part, *options).use { out ->
|
||
val buffer = ByteArray(128 * 1024); var last = 0L
|
||
while (true) {
|
||
check(!cancelRequested) { "下载已停止,分片保留以便续传" }
|
||
val count = input.read(buffer); if (count < 0) break
|
||
out.write(buffer, 0, count); received += count
|
||
if (System.currentTimeMillis() - last > 300) { showProgress("APK 下载 $received / $size 字节", if (size > 0) (received * 100 / size).toInt() else -1); last = System.currentTimeMillis() }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
check(Files.size(part) == size && fileHash(part) == expected) { Files.deleteIfExists(part); "APK 校验失败,已清理损坏分片" }
|
||
val output = ApkFiles.publish(part, directory, artifact.fileName)
|
||
rememberArtifact(source, id, expected, artifact.name, output.fileName.toString())
|
||
showProgress("APK 下载完成", 100); append("APK 已保存:$output")
|
||
ApkNotifications.show(project, output, result.get("task")?.asString.orEmpty())
|
||
return output
|
||
}
|
||
private fun rememberArtifact(source: Path, id: String, expected: String, name: String, file: String) {
|
||
LastBuildStore.load(source)?.takeIf { it.buildId == id }?.let { it.artifactHash = expected; it.artifactName = name; it.artifactFile = file; LastBuildStore.save(source, it) }
|
||
}
|
||
private fun installServer(cfg: Settings.Data, id: String, artifact: ApkArtifact, device: AdbDevice?) {
|
||
if (device?.online != true) { append("未选择在线服务端设备;跳过安装,继续下载 APK"); return }
|
||
append("正在使用服务端 ADB 安装到:$device")
|
||
append(ServerAdb.install(cfg, id, artifact.name, device.serial))
|
||
append("服务端安装成功:${artifact.fileName}")
|
||
}
|
||
private fun installServerBuild() {
|
||
if (busy) return
|
||
val cfg = settings.snapshot()
|
||
if (!cfg.remoteAdb) { append("请先勾选使用服务端 ADB 安装,并选择服务端设备"); return }
|
||
val selected = devices.selectedItem as? AdbDevice
|
||
if (selected?.online != true) { append("请选择在线且已授权的服务端设备"); return }
|
||
val source = project.basePath?.let { Path.of(it) } ?: return
|
||
val id = buildIdField.text.trim().ifBlank { LastBuildStore.load(source)?.buildId.orEmpty() }
|
||
if (!id.matches(Regex("[a-f0-9]{32}"))) { append("请填写成功构建 ID 或先运行构建"); return }
|
||
busy = true; run.isEnabled = false
|
||
object : Task.Backgroundable(project, "服务端安装 APK", false) {
|
||
override fun run(indicator: ProgressIndicator) {
|
||
var secret = ""
|
||
try {
|
||
val base = cfg.url.trim().trimEnd('/')
|
||
http = ServerTls.client(cfg.serverCertificate)
|
||
secret = PasswordSafe.instance.getPassword(credentials(base)).orEmpty()
|
||
val result = json(base, secret, "GET", "/builds/$id")
|
||
check(result.get("status").asString == "success") { "该构建尚未成功" }
|
||
installServer(cfg, id, selectArtifact(source, id, result), selected)
|
||
} catch (e: Exception) { append("服务端安装失败:${e.message}".let { if (secret.isNotEmpty()) it.replace(secret, "***") else it }) }
|
||
finally { busy = false; ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true } }
|
||
}
|
||
}.queue()
|
||
}
|
||
private fun installDownloaded() {
|
||
if (busy) return
|
||
if (settings.snapshot().remoteAdb) { installServerBuild(); return }
|
||
val source = project.basePath?.let { Path.of(it) } ?: return
|
||
val record = try { LastBuildStore.load(source) ?: error("没有已下载构建记录") }
|
||
catch (e: Exception) { append(e.message ?: "读取记录失败"); return }
|
||
if (!record.buildId.matches(Regex("[a-f0-9]{32}")) || !record.artifactHash.matches(Regex("[a-f0-9]{64}")) || (buildIdField.text.isNotBlank() && buildIdField.text.trim() != record.buildId)) { append("请先下载并校验当前任务的 APK"); return }
|
||
val cfg = settings.snapshot(); val explicit = devices.selectedItem as? AdbDevice
|
||
busy = true; run.isEnabled = false
|
||
object : Task.Backgroundable(project, "安装已下载 APK", false) {
|
||
override fun run(indicator: ProgressIndicator) {
|
||
try {
|
||
val selectedOutput = source.resolve(".remotecompile/${record.buildId}-${record.artifactHash}.apk")
|
||
val recorded = record.artifactFile?.let { require(ApkFiles.validName(it)) { "保存的 APK 文件名无效" }; source.resolve(".remotecompile").resolve(it) }
|
||
val output = recorded ?: if (Files.isRegularFile(selectedOutput)) selectedOutput else source.resolve(".remotecompile/${record.buildId}.apk")
|
||
check(Files.isRegularFile(output) && fileHash(output) == record.artifactHash) { "已下载 APK 缺失或校验失败,请重新下载" }
|
||
val adb = AdbDevices.resolve(source, cfg.adb)
|
||
val target = AdbDevices.choose(AdbDevices.list(adb), explicit?.serial ?: cfg.device, explicit != null)
|
||
check(target != null) { "请选择在线且已授权的设备" }
|
||
append("安装构建 ${record.buildId} 到 $target")
|
||
InstallActions.install(source, cfg, adb, target.serial, output, ::append)
|
||
} catch (e: Exception) { append("安装失败:${e.message ?: e.javaClass.simpleName}") }
|
||
finally { busy = false; ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true } }
|
||
}
|
||
}.queue()
|
||
}
|
||
private fun recoverBuild(downloadOnly: Boolean) {
|
||
if (busy) return
|
||
val source = project.basePath?.let { Path.of(it) } ?: return
|
||
val cfg = settings.snapshot(); val overrideId = buildIdField.text.trim()
|
||
val record = try {
|
||
val last = LastBuildStore.load(source)
|
||
if (overrideId.isNotBlank() && overrideId != last?.buildId) LastBuild(cfg.url, cfg.projectId, buildId = overrideId, certificate = cfg.serverCertificate)
|
||
else last ?: if (cfg.projectId.isNotBlank()) LastBuild(cfg.url, cfg.projectId, certificate = cfg.serverCertificate) else error("本项目没有上次构建记录;可填写构建 ID")
|
||
} catch (e: Exception) { append(e.message ?: "读取构建记录失败"); return }
|
||
try { validateEndpoint(record.server) } catch (e: Exception) { append(e.message ?: "地址无效"); return }
|
||
busy = true; cancelRequested = false; run.isEnabled = false; log.text = ""; logFormat.reset()
|
||
object : Task.Backgroundable(project, "恢复远程构建", false) {
|
||
override fun run(indicator: ProgressIndicator) {
|
||
var secret = ""
|
||
try {
|
||
http = ServerTls.client(record.certificate)
|
||
secret = PasswordSafe.instance.getPassword(credentials(record.server)).orEmpty()
|
||
check(secret.isNotBlank()) { "请先保存该服务器 Token:${record.server}" }
|
||
if (record.buildId.isBlank()) {
|
||
val found = json(record.server, secret, "GET", "/projects/${record.projectId}/builds?clientRequestId=${record.clientRequestId}").getAsJsonArray("builds")
|
||
check(found.size() > 0 && (record.clientRequestId.isBlank() || found.size() == 1)) { "服务器未找到该提交,可核对网络恢复后再次查询;不要重复提交" }
|
||
record.buildId = found[0].asJsonObject.get("id").asString
|
||
}
|
||
require(record.buildId.matches(Regex("[a-f0-9]{32}"))) { "构建 ID 格式错误" }
|
||
activeBuild = record.buildId; LastBuildStore.save(source, record); setBuildId(activeBuild)
|
||
append("恢复构建:$activeBuild;服务器:${record.server}")
|
||
val result = if (downloadOnly) json(record.server, secret, "GET", "/builds/$activeBuild").also {
|
||
check(it.get("status").asString == "success") { "构建尚未成功,请点击恢复上次构建继续查看" }
|
||
} else watchBuild(record.server, secret, activeBuild)
|
||
append("源码版本:${result.get("revision").asString};任务:${result.get("task").asString}")
|
||
downloadApk(record.server, secret, activeBuild, source, result)
|
||
append("恢复操作完成;已取回 APK,未自动安装旧版本")
|
||
} catch (e: Exception) {
|
||
append("恢复失败:" + (e.message ?: e.javaClass.simpleName).let { if (secret.isNotEmpty()) it.replace(secret, "***") else it })
|
||
} finally {
|
||
activeBuild = ""; busy = false
|
||
ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true }
|
||
}
|
||
}
|
||
}.queue()
|
||
}
|
||
private fun showEnvironment() {
|
||
val cfg = settings.snapshot()
|
||
ApplicationManager.getApplication().executeOnPooledThread {
|
||
try {
|
||
val client = ServerTls.client(cfg.serverCertificate)
|
||
val secret = PasswordSafe.instance.getPassword(credentials(cfg.url)).orEmpty()
|
||
val request = HttpRequest.newBuilder(URI.create("${cfg.url}/api/v1/environment")).header("Authorization", "Bearer $secret").build()
|
||
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
|
||
append("服务端环境:HTTP ${response.statusCode()} ${response.body()}")
|
||
} catch (e: Exception) { append("读取环境失败:${e.javaClass.simpleName}") }
|
||
}
|
||
}
|
||
private fun showHistory() {
|
||
if (busy) return
|
||
val cfg = settings.snapshot()
|
||
val source = project.basePath?.let { Path.of(it) } ?: return
|
||
val projectId = cfg.projectId.ifBlank { runCatching { LastBuildStore.load(source)?.takeIf { it.server == cfg.url }?.projectId.orEmpty() }.getOrDefault("") }
|
||
if (projectId.isBlank()) { append("本项目尚未关联远程工作区;可手动填写构建 ID"); return }
|
||
ApplicationManager.getApplication().executeOnPooledThread {
|
||
try {
|
||
val client = ServerTls.client(cfg.serverCertificate)
|
||
val secret = PasswordSafe.instance.getPassword(credentials(cfg.url)).orEmpty()
|
||
val request = HttpRequest.newBuilder(URI.create("${cfg.url}/api/v1/projects/$projectId/builds")).header("Authorization", "Bearer $secret").build()
|
||
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
|
||
check(response.statusCode() == 200) { "HTTP ${response.statusCode()}" }
|
||
val builds = gson.fromJson(response.body(), JsonObject::class.java).getAsJsonArray("builds")
|
||
val choices = builds.map { item ->
|
||
val b = item.asJsonObject
|
||
"${b.get("id").asString} · ${b.get("status").asString} · ${b.get("task").asString} · 源码 ${b.get("revision").asString.take(12)}"
|
||
}.toTypedArray()
|
||
ApplicationManager.getApplication().invokeLater {
|
||
if (!disposed && !project.isDisposed && !busy) {
|
||
if (choices.isEmpty()) append("此工作区暂无构建历史")
|
||
else {
|
||
val choice = JOptionPane.showInputDialog(this, "选择任务后点击恢复或下载", "构建历史(最近50条)", JOptionPane.PLAIN_MESSAGE, null, choices, choices.first()) as? String
|
||
if (choice != null) { buildIdField.text = choice.substringBefore(" · "); append("已选择:$choice") }
|
||
}
|
||
}
|
||
}
|
||
} catch (e: Exception) { append("读取历史失败:${e.javaClass.simpleName}") }
|
||
}
|
||
}
|
||
|
||
}
|