feat: 初始化跨平台远程编译服务与 Android Studio 插件
This commit is contained in:
commit
9eba4556db
44 files changed
+2802
No files matched your search
@@ -0,0 +1,256 @@
|
||||
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 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 devices = JComboBox<AdbDevice>()
|
||||
private val refresh = JButton("刷新设备")
|
||||
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 log = JTextArea().apply { isEditable = false }
|
||||
@Volatile private var activeBuild = ""
|
||||
@Volatile private var cancelRequested = false
|
||||
@Volatile private var busy = false
|
||||
private val gson = Gson()
|
||||
private val http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(15)).build()
|
||||
private val polling = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay({ refreshDevices() }, 1, 5, TimeUnit.SECONDS)
|
||||
init {
|
||||
val configure = JButton("连接设置")
|
||||
val buttons = JPanel().apply { add(JLabel("目标设备")); add(devices); add(refresh); add(run); add(cancel); add(configure) }
|
||||
val top = JPanel(BorderLayout()).apply { add(buttons, BorderLayout.CENTER); add(deviceStatus, BorderLayout.SOUTH) }
|
||||
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() }
|
||||
configure.addActionListener { ToolWindowManager.getInstance(project).getToolWindow("Remote Configuration")?.show() }
|
||||
add(top, BorderLayout.NORTH); add(JScrollPane(log), BorderLayout.CENTER)
|
||||
run.addActionListener { runBuild() }
|
||||
cancel.addActionListener { cancelRequested = true; append("已请求取消,等待当前网络操作结束…") }
|
||||
}
|
||||
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 { AdbDevices.list(AdbDevices.resolve(Path.of(project.basePath ?: error("项目路径不存在")), cfg.adb)) }
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
try {
|
||||
if (!disposed && !project.isDisposed) {
|
||||
val found = result.getOrDefault(emptyList())
|
||||
val previous = (devices.selectedItem as? AdbDevice)?.serial ?: settings.snapshot().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 "${found.count { it.online }} 台可用设备;可自动识别插拔"
|
||||
}
|
||||
} finally { refreshing.set(false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun append(text: String) = ApplicationManager.getApplication().invokeLater {
|
||||
if (!disposed && !project.isDisposed) { log.append(text + "\n"); log.caretPosition = log.document.length }
|
||||
}
|
||||
private fun hash(data: ByteArray) = MessageDigest.getInstance("SHA-256").digest(data).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) { "HTTP ${response.statusCode()}: ${String(response.body()).take(500)}" }
|
||||
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 cfg = settings.snapshot()
|
||||
val base = cfg.url.trim().trimEnd('/')
|
||||
validateEndpoint(base)
|
||||
val selected = devices.selectedItem as? AdbDevice
|
||||
if (cfg.install) {
|
||||
require(selected == null || selected.online) { "请选择已连接且已授权的设备" }
|
||||
if (selected != null) cfg.device = selected.serial
|
||||
}
|
||||
val source = project.basePath?.let { Path.of(it) } ?: error("项目路径不存在")
|
||||
cancelRequested = false; activeBuild = ""; log.text = ""
|
||||
object : Task.Backgroundable(project, "Remote Compilation", false) {
|
||||
override fun run(indicator: ProgressIndicator) {
|
||||
var secret = ""
|
||||
try {
|
||||
secret = PasswordSafe.instance.getPassword(credentials(base)) ?: ""
|
||||
check(secret.length >= 24) { "请在右侧 Remote Configuration 中保存服务 Token" }
|
||||
if (cfg.install) {
|
||||
val connected = AdbDevices.list(AdbDevices.resolve(source, cfg.adb)).filter { it.online }
|
||||
val target = AdbDevices.choose(connected, selected?.serial ?: cfg.device, explicit = selected != null)
|
||||
check(target != null) { "请从设备列表选择已连接且已授权的设备" }
|
||||
cfg.device = target.serial
|
||||
settings.selectDevice(target.serial)
|
||||
refreshDevices()
|
||||
append("目标设备:$target")
|
||||
}
|
||||
json(base, secret, "GET", "/health")
|
||||
if (cfg.projectId.isBlank()) {
|
||||
cfg.projectId = json(base, secret, "POST", "/projects").get("id").asString
|
||||
settings.projectAllocated(base, cfg.projectId)
|
||||
}
|
||||
val manifest = json(base, secret, "GET", "/projects/${cfg.projectId}/manifest").getAsJsonObject("files")
|
||||
val files = linkedMapOf<String, Map<String, String>>()
|
||||
val excludes = setOf(".git", ".gradle", ".idea", "build", ".remotecompile", "node_modules", ".kotlin")
|
||||
var changed = 0
|
||||
Files.walk(source).use { paths -> paths.filter { path ->
|
||||
val rel = source.relativize(path)
|
||||
rel.none { it.toString() in excludes } && !Files.isDirectory(path)
|
||||
}.forEach { path ->
|
||||
check(!Files.isSymbolicLink(path)) { "暂不支持符号链接:$path" }
|
||||
val name = source.relativize(path).joinToString("/")
|
||||
val leaf = path.fileName.toString()
|
||||
if (leaf == "local.properties" || leaf.endsWith(".jks") || leaf.endsWith(".keystore") || leaf.startsWith(".env") || leaf in setOf("key.properties", "keystore.properties")) return@forEach
|
||||
check(Files.size(path) <= 64L * 1024 * 1024) { "文件超过首版 64MiB 上限:$name" }
|
||||
val bytes = Files.readAllBytes(path); val hash = hash(bytes)
|
||||
files[name] = if (manifest?.getAsJsonObject(name)?.get("hash")?.asString == hash) mapOf("hash" to hash)
|
||||
else { changed++; mapOf("hash" to hash, "data" to Base64.getEncoder().encodeToString(bytes)) }
|
||||
} }
|
||||
check(!cancelRequested) { "已取消" }
|
||||
val revision = UUID.randomUUID().toString()
|
||||
append("同步 ${files.size} 个文件,上传 $changed 个变更文件…")
|
||||
json(base, secret, "POST", "/projects/${cfg.projectId}/sync", mapOf("revision" to revision, "files" to files))
|
||||
check(!cancelRequested) { "已取消" }
|
||||
activeBuild = json(base, secret, "POST", "/projects/${cfg.projectId}/builds", mapOf("revision" to revision, "task" to cfg.task)).get("id").asString
|
||||
var offset = 0
|
||||
var result: JsonObject
|
||||
while (true) {
|
||||
if (cancelRequested) { json(base, secret, "DELETE", "/builds/$activeBuild"); error("已请求取消远程构建") }
|
||||
result = json(base, secret, "GET", "/builds/$activeBuild")
|
||||
val lines = result.getAsJsonArray("logs")
|
||||
while (offset < lines.size()) append(lines[offset++].asString)
|
||||
if (result.get("status").asString !in listOf("queued", "running")) break
|
||||
Thread.sleep(700)
|
||||
}
|
||||
check(result.get("status").asString == "success") { "构建状态:${result.get("status").asString}" }
|
||||
val artifacts = result.getAsJsonArray("artifacts")
|
||||
check(artifacts.size() == 1) { "首版要求恰好一个 APK,实际 ${artifacts.size()} 个;请调整构建任务" }
|
||||
val artifact = artifacts[0].asJsonObject
|
||||
val name = artifact.get("name").asString
|
||||
val encodedName = URLEncoder.encode(name, Charsets.UTF_8).replace("+", "%20")
|
||||
val bytes = request(base, secret, "GET", "/builds/$activeBuild/artifacts/$encodedName")
|
||||
check(hash(bytes) == artifact.get("hash").asString) { "APK 校验失败" }
|
||||
val output = source.resolve(".remotecompile").resolve("$activeBuild.apk")
|
||||
Files.createDirectories(output.parent); Files.write(output, bytes)
|
||||
append("APK 已保存:$output")
|
||||
check(!cancelRequested) { "已取消安装" }
|
||||
if (cfg.install) {
|
||||
val adb = AdbDevices.resolve(source, cfg.adb)
|
||||
check(AdbDevices.list(adb).any { it.serial == cfg.device && it.online }) { "目标设备已断开或未授权,已保留 APK" }
|
||||
val pb = ProcessBuilder(adb, "-s", cfg.device, "install", "-r", output.toString()).redirectErrorStream(true)
|
||||
val outputLog = Files.createTempFile("remotecompile-adb-", ".log")
|
||||
try {
|
||||
val process = pb.redirectOutput(outputLog.toFile()).start()
|
||||
if (!process.waitFor(120, TimeUnit.SECONDS)) { process.destroyForcibly(); error("adb 安装超时") }
|
||||
append(Files.readString(outputLog)); check(process.exitValue() == 0) { "adb 安装失败" }
|
||||
} finally { Files.deleteIfExists(outputLog) }
|
||||
}
|
||||
append("Remote Run 完成")
|
||||
} catch (e: Exception) {
|
||||
// Never print request headers or the token.
|
||||
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()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user