Skip to content

Commit 96f90fd

Browse files
authored
Merge pull request #346 from alyssaruth/fix-update
Fix update mechanism
2 parents 1d0be32 + c13c5d5 commit 96f90fd

17 files changed

Lines changed: 683 additions & 375 deletions

‎build.gradle.kts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ dependencies {
5151
testImplementation("io.kotest:kotest-assertions-core:5.5.4")
5252
testImplementation("com.github.alexburlton:swing-test:4.0.0")
5353
testImplementation("org.junit.jupiter:junit-jupiter:5.14.3")
54+
testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")
5455
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
5556
}
5657

‎src/main/kotlin/dartzee/core/util/DialogUtil.kt‎

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,10 @@ object DialogUtil {
3333
logDialogClosed("Info", null)
3434
}
3535

36-
fun showCustomMessage(message: Any, parent: Component = ScreenCache.mainScreen) {
37-
logDialogShown("CustomInfo", "Information", "?")
38-
JOptionPane.showMessageDialog(
39-
parent,
40-
message,
41-
"Information",
42-
JOptionPane.INFORMATION_MESSAGE,
43-
)
44-
logDialogClosed("CustomInfo", null)
36+
fun showCustomError(message: Any, parent: Component = ScreenCache.mainScreen) {
37+
logDialogShown("CustomError", "Error", "?")
38+
JOptionPane.showMessageDialog(parent, message, "Error", JOptionPane.ERROR_MESSAGE)
39+
logDialogClosed("CustomError", null)
4540
}
4641

4742
@Deprecated("Use showError")

‎src/main/kotlin/dartzee/logging/LogDestinationElasticsearch.kt‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,15 @@ class LogDestinationElasticsearch(
5151
}
5252

5353
fun shutDown() {
54-
scheduler.shutdown()
55-
logger.waitUntilLoggingFinished()
54+
try {
55+
scheduler.shutdown()
56+
logger.waitUntilLoggingFinished()
5657

57-
val remainingLogs = pendingLogs.toList()
58-
val entities = remainingLogs.map { PendingLogsEntity.factory(it) }
59-
BulkInserter.insert(entities)
58+
val remainingLogs = pendingLogs.toList()
59+
val entities = remainingLogs.map { PendingLogsEntity.factory(it) }
60+
BulkInserter.insert(entities)
61+
} catch (e: Exception) {
62+
logger.error(CODE_ELASTICSEARCH_ERROR, "Failed to write out pending logs", e)
63+
}
6064
}
6165
}

‎src/main/kotlin/dartzee/logging/LoggingCodes.kt‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ val CODE_DIALOG_CLOSED = LoggingCode("dialogClosed")
2929
val CODE_COMMAND_ENTERED = LoggingCode("commandEntered")
3030
val CODE_UPDATE_CHECK = LoggingCode("updateCheck")
3131
val CODE_UPDATE_CHECK_RESULT = LoggingCode("updateCheckResult")
32+
val CODE_UPDATE_STARTING = LoggingCode("updateStarting")
3233
val CODE_LOADED_RESOURCES = LoggingCode("loadedResources")
3334
val CODE_STARTING_BACKUP = LoggingCode("startingBackup")
3435
val CODE_STARTING_RESTORE = LoggingCode("startingRestore")
@@ -56,6 +57,7 @@ val CODE_PARTY_MODE = LoggingCode("partyMode")
5657
val CODE_PREFERENCE_SAVED = LoggingCode("preferenceSaved")
5758
val CODE_PREFERENCE_DELETED = LoggingCode("preferenceDeleted")
5859
val CODE_THEME_APPLIED = LoggingCode("themeApplied")
60+
val CODE_EXEC = LoggingCode("exec")
5961

6062
// Warn
6163
val CODE_UNEXPECTED_ARGUMENT = LoggingCode("unexpectedArgument")
@@ -75,7 +77,7 @@ val CODE_AUDIO_ERROR = LoggingCode("audioError")
7577
val CODE_SCREEN_LOAD_ERROR = LoggingCode("screenLoadError")
7678
val CODE_UPDATE_ERROR = LoggingCode("updateError")
7779
val CODE_PARSE_ERROR = LoggingCode("parseError")
78-
val CODE_BATCH_ERROR = LoggingCode("batchFileError")
80+
val CODE_EXEC_ERROR = LoggingCode("execError")
7981
val CODE_TEST_CONNECTION_ERROR = LoggingCode("testConnectionError")
8082
val CODE_RESOURCE_LOAD_ERROR = LoggingCode("resourceLoadError")
8183
val CODE_COMMAND_ERROR = LoggingCode("commandError")
@@ -91,5 +93,4 @@ val CODE_PULL_ERROR = LoggingCode("pullError")
9193
val CODE_BACKUP_ERROR = LoggingCode("backupError")
9294
val CODE_RESTORE_ERROR = LoggingCode("restoreError")
9395
val CODE_DELETE_ERROR = LoggingCode("deleteError")
94-
val CODE_HYPERLINK_ERROR = LoggingCode("hyperlinkError")
9596
val CODE_EDT_FROZEN = LoggingCode("edtFrozen")

‎src/main/kotlin/dartzee/object/DartsClient.kt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ object DartsClient {
5454

5555
fun isWindowsOs() = operatingSystem.contains("windows", ignoreCase = true)
5656

57+
fun isLinux() = operatingSystem.contains("linux", ignoreCase = true)
58+
5759
fun checkForUpdatesIfRequired() {
5860
if (devMode) {
5961
logger.info(CODE_UPDATE_CHECK, "Not checking for updates: I'm in dev mode")
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package dartzee.utils
2+
3+
import dartzee.logging.CODE_EXEC
4+
import dartzee.logging.CODE_EXEC_ERROR
5+
import dartzee.`object`.DartsClient
6+
import dartzee.utils.InjectedThings.logger
7+
8+
fun launchUrl(url: String, runtime: Runtime = Runtime.getRuntime()) {
9+
runCommand(
10+
windows = arrayOf("cmd", "/c", "start", url),
11+
linux = arrayOf("xdg-open", url),
12+
runtime,
13+
)
14+
}
15+
16+
fun runCommand(
17+
windows: Array<String>,
18+
linux: Array<String>,
19+
runtime: Runtime = Runtime.getRuntime(),
20+
) =
21+
if (DartsClient.isLinux()) {
22+
execCommand(linux, runtime)
23+
} else if (DartsClient.isWindowsOs()) {
24+
execCommand(windows, runtime)
25+
} else {
26+
logger.error(
27+
CODE_EXEC_ERROR,
28+
"Operating system unsupported: ${DartsClient.operatingSystem}",
29+
)
30+
false
31+
}
32+
33+
private fun execCommand(command: Array<String>, runtime: Runtime) =
34+
try {
35+
logger.info(CODE_EXEC, "Running command: ${command.joinToString(" ")}")
36+
runtime.exec(command)
37+
true
38+
} catch (e: Exception) {
39+
logger.error(CODE_EXEC_ERROR, "Command failed: ${command.joinToString(" ")}", e)
40+
false
41+
}

‎src/main/kotlin/dartzee/utils/UpdateManager.kt‎

Lines changed: 66 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@ package dartzee.utils
22

33
import dartzee.core.bean.LinkLabel
44
import dartzee.core.util.DialogUtil
5-
import dartzee.logging.CODE_BATCH_ERROR
5+
import dartzee.core.util.FileUtil
66
import dartzee.logging.CODE_PARSE_ERROR
77
import dartzee.logging.CODE_UPDATE_CHECK
88
import dartzee.logging.CODE_UPDATE_CHECK_RESULT
99
import dartzee.logging.CODE_UPDATE_ERROR
10+
import dartzee.logging.CODE_UPDATE_STARTING
1011
import dartzee.logging.KEY_RESPONSE_BODY
1112
import dartzee.`object`.DartsClient
1213
import dartzee.utils.InjectedThings.logger
@@ -15,6 +16,7 @@ import java.io.File
1516
import javax.swing.JLabel
1617
import javax.swing.JOptionPane
1718
import javax.swing.JPanel
19+
import kong.unirest.MimeTypes
1820
import kong.unirest.Unirest
1921
import kong.unirest.json.JSONObject
2022

@@ -24,6 +26,8 @@ import kong.unirest.json.JSONObject
2426
* https://developer.github.com/v3/repos/releases/#get-the-latest-release
2527
*/
2628
object UpdateManager {
29+
private val jarDirectory = System.getProperty("user.dir")
30+
2731
fun checkForUpdates(currentVersion: String) {
2832
// Show this here, checking the CRC can take time
2933
logger.info(CODE_UPDATE_CHECK, "Checking for updates - my version is $currentVersion")
@@ -36,7 +40,7 @@ object UpdateManager {
3640
return
3741
}
3842

39-
startUpdate(metadata.getArgs(), Runtime.getRuntime())
43+
doUpdate(DARTZEE_REPOSITORY_URL, metadata, Runtime.getRuntime())
4044
}
4145

4246
fun queryLatestReleaseJson(repositoryUrl: String): JSONObject? {
@@ -74,11 +78,6 @@ object UpdateManager {
7478
// An update is available
7579
logger.info(CODE_UPDATE_CHECK_RESULT, "Newer release available - $newVersion")
7680

77-
if (!DartsClient.isWindowsOs()) {
78-
showManualDownloadMessage(newVersion)
79-
return false
80-
}
81-
8281
val answer =
8382
DialogUtil.showQuestion(
8483
"An update is available (${metadata.version}). Would you like to download it now?",
@@ -88,17 +87,18 @@ object UpdateManager {
8887
}
8988

9089
private fun showManualDownloadMessage(newVersion: String) {
90+
DialogUtil.dismissLoadingDialog()
91+
9192
val fullUrl = "$DARTZEE_MANUAL_DOWNLOAD_URL/tag/$newVersion"
9293
val panel = JPanel()
9394
panel.layout = BorderLayout(0, 0)
94-
val lblOne =
95-
JLabel("An update is available ($newVersion). You can download it manually from:")
95+
val lblOne = JLabel("Failed to download $newVersion. You can download it manually from:")
9696
val linkLabel = LinkLabel(fullUrl) { launchUrl(fullUrl) }
9797

9898
panel.add(lblOne, BorderLayout.NORTH)
9999
panel.add(linkLabel, BorderLayout.SOUTH)
100100

101-
DialogUtil.showCustomMessage(panel)
101+
DialogUtil.showCustomError(panel)
102102
}
103103

104104
fun parseUpdateMetadata(responseJson: JSONObject): UpdateMetadata? {
@@ -109,8 +109,7 @@ object UpdateManager {
109109

110110
val assetId = asset.getLong("id")
111111
val fileName = asset.getString("name")
112-
val size = asset.getLong("size")
113-
UpdateMetadata(remoteVersion, assetId, fileName, size)
112+
UpdateMetadata(remoteVersion, assetId, fileName)
114113
} catch (t: Throwable) {
115114
logger.error(
116115
CODE_PARSE_ERROR,
@@ -122,38 +121,71 @@ object UpdateManager {
122121
}
123122
}
124123

125-
fun startUpdate(args: String, runtime: Runtime) {
126-
prepareBatchFile()
124+
fun doUpdate(repositoryUrl: String, metadata: UpdateMetadata, runtime: Runtime) {
125+
if (!downloadJar(repositoryUrl, metadata)) {
126+
return
127+
}
127128

128-
try {
129-
runtime.exec("cmd /c start update.bat $args")
130-
} catch (t: Throwable) {
131-
logger.error(CODE_BATCH_ERROR, "Error running update.bat", t)
132-
val manualCommand = "update.bat $args"
129+
if (DartsClient.isWindowsOs()) {
130+
prepareUpdateFile("update.bat")
131+
} else if (DartsClient.isLinux()) {
132+
prepareUpdateFile("update.sh")
133+
}
133134

134-
val msg =
135-
"Failed to launch update.bat - call the following manually to perform the update: \n\n$manualCommand"
136-
DialogUtil.showError(msg)
137-
return
135+
val success =
136+
runCommand(
137+
windows =
138+
arrayOf("cmd", "/c", "start", "$jarDirectory/update.bat", metadata.fileName),
139+
linux = arrayOf("sh", "$jarDirectory/update.sh", metadata.fileName),
140+
runtime,
141+
)
142+
143+
if (!success) {
144+
DialogUtil.showError(
145+
"Failed to swap in updated file. \n\nDelete the old Dartzee.jar and rename ${metadata.fileName} -> Dartzee.jar"
146+
)
138147
}
139148

140149
InjectedThings.exiter.exit(0)
141150
}
142151

143-
fun prepareBatchFile() {
144-
val updateFile = File("update.bat")
152+
fun downloadJar(repositoryUrl: String, metadata: UpdateMetadata): Boolean =
153+
try {
154+
val downloadPath = "$jarDirectory/${metadata.fileName}"
155+
FileUtil.deleteFileIfExists(downloadPath)
156+
val downloadUrl = "$repositoryUrl/releases/assets/${metadata.assetId}"
157+
logger.info(CODE_UPDATE_STARTING, "Downloading from $downloadUrl to $downloadPath")
158+
159+
DialogUtil.showLoadingDialog("Downloading ${metadata.version}...")
160+
val response = Unirest.get(downloadUrl).accept(MimeTypes.EXE).asFile(downloadPath)
161+
if (response.status != 200) {
162+
logger.error(
163+
CODE_UPDATE_ERROR,
164+
"Received non-success HTTP status: ${response.status} - ${response.statusText}",
165+
KEY_RESPONSE_BODY to response.body,
166+
)
167+
168+
showManualDownloadMessage(metadata.version)
169+
false
170+
} else {
171+
true
172+
}
173+
} catch (e: Exception) {
174+
logger.error(CODE_UPDATE_ERROR, "Caught $e during download", e)
175+
showManualDownloadMessage(metadata.version)
176+
false
177+
} finally {
178+
DialogUtil.dismissLoadingDialog()
179+
}
180+
181+
fun prepareUpdateFile(filename: String) {
182+
val filePath = "$jarDirectory/$filename"
183+
val updateFile = File(filePath)
145184

146185
updateFile.delete()
147-
val updateScript = javaClass.getResource("/update/update.bat").readText()
186+
val updateScript = javaClass.getResource("/update/$filename").readText()
148187
updateFile.writeText(updateScript)
149188
}
150189
}
151190

152-
data class UpdateMetadata(
153-
val version: String,
154-
val assetId: Long,
155-
val fileName: String,
156-
val size: Long,
157-
) {
158-
fun getArgs() = "$size $version $fileName $assetId"
159-
}
191+
data class UpdateMetadata(val version: String, val assetId: Long, val fileName: String)

‎src/main/kotlin/dartzee/utils/UrlUtil.kt‎

Lines changed: 0 additions & 12 deletions
This file was deleted.
Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,13 @@
1-
@echo off
1+
@echo on
22

3-
REM %1 = noOfBytes
4-
REM %2 = version number
5-
REM %3 = filename
6-
REM %4 = assetId
3+
REM %1 = filename
74

8-
echo Performing download of %1 bytes (Version %2)
5+
timeout 2
6+
del Dartzee.jar || goto :error
7+
ren %1 Dartzee.jar || goto :error
98

10-
curl -LJO -H "Accept: application/octet-stream" https://api.github.com/repos/alyssaburlton/Dartzee/releases/assets/%4
9+
start javaw -Xms256m -Xmx512m -jar Dartzee.jar justUpdated trueLaunch || goto :error
10+
exit
1111

12-
ren Dartzee.jar Dartzee_OLD.jar
13-
ren %3 Dartzee.jar
14-
del Dartzee_OLD.jar
15-
16-
start javaw -Xms256m -Xmx512m -jar Dartzee.jar justUpdated trueLaunch
17-
exit
12+
:error
13+
echo Something went wrong! Please copy the contents of this so Alyssa can fix it :) Error level: #%errorlevel%
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#!/bin/bash
2+
set -eu
3+
4+
filename=$1
5+
6+
sleep 2
7+
mv Dartzee.jar Dartzee_OLD.jar
8+
mv $filename Dartzee.jar
9+
rm Dartzee_OLD.jar
10+
chmod +x Dartzee.jar
11+
12+
java -Xms256m -Xmx512m -jar Dartzee.jar justUpdated trueLaunch

0 commit comments

Comments
 (0)