Skip to content
This repository has been archived by the owner on Dec 12, 2020. It is now read-only.

Commit

Permalink
Merge branch 'downloader'
Browse files Browse the repository at this point in the history
  • Loading branch information
Xerus committed Jan 20, 2019
2 parents b76e9c8 + dcdf132 commit 3bfabf5
Show file tree
Hide file tree
Showing 28 changed files with 1,147 additions and 756 deletions.
6 changes: 3 additions & 3 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,13 @@ repositories {
dependencies {
implementation(kotlin("reflect"))

implementation("com.github.Xerus2000.util", "javafx", "1d6e2ecbb181070fe64f6a180f51d2c42a801f74")
implementation("com.github.Xerus2000.util", "javafx", "766520d3a38c9188e342dba0adf643028566db01")
implementation("org.controlsfx", "controlsfx", "8.40.+")

implementation("ch.qos.logback", "logback-classic", "1.2.+")
implementation("com.github.Bluexin", "drpc4k", "16b0c60")
implementation("org.apache.httpcomponents", "httpmime", "4.5.+")
implementation("com.google.apis", "google-api-services-sheets", "v4-rev20180727-1.27.0")
implementation("com.google.apis", "google-api-services-sheets", "v4-rev20181116-1.27.0")

val junitVersion = "5.3.2"
testCompile("org.junit.jupiter", "junit-jupiter-api", junitVersion)
Expand All @@ -61,7 +61,7 @@ dependencies {
val jarFile
get() = "$name-$version.jar"

val MAIN = "_Main"
val MAIN = "_main"
tasks {

arrayOf(getByName<JavaExec>("run"), getByName<JavaExec>("runShadow")).forEach {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import javafx.scene.control.TreeItem
import org.controlsfx.control.CheckTreeView
import xerus.ktutil.javafx.ui.FilterableTreeItem

open class FilterableCheckTreeView<T : Any>(rootValue: T) : CheckTreeView<T>() {
val root = FilterableTreeItem(rootValue)
open class FilterableCheckTreeView<T : Any>(val root: FilterableTreeItem<T>) : CheckTreeView<T>() {
constructor(rootValue: T) : this(FilterableTreeItem(rootValue))

val checkedItems: ObservableList<TreeItem<T>>
get() = checkModel.checkedItems
val predicate
Expand Down
59 changes: 50 additions & 9 deletions src/main/xerus/monstercat/Logging.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,29 @@ import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.core.FileAppender
import ch.qos.logback.core.spi.ContextAwareBase
import javafx.scene.control.Alert
import javafx.scene.control.ButtonType
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import mu.KotlinLogging
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import xerus.ktutil.currentSeconds
import xerus.ktutil.getStackTraceString
import xerus.ktutil.javafx.properties.listen
import xerus.ktutil.replaceIllegalFileChars
import xerus.monstercat.tabs.TabSettings
import java.io.File
import java.util.*
import java.util.concurrent.atomic.AtomicInteger

private val logDir: File
get() = cacheDir.resolve("logs").apply { mkdirs() }
private val logFile = logDir.resolve("log${currentSeconds()}.txt")

private fun Int.padDate() = toString().padStart(2, '0')
private val logFile = logDir.resolve("log_${Calendar.getInstance().let {
"${(it.get(Calendar.MONTH) + 1).padDate()}-${it.get(Calendar.DAY_OF_MONTH).padDate()}-${it.get(Calendar.HOUR_OF_DAY).padDate()}"
}}_${currentSeconds()}.txt")
private var logLevel: Level = Level.WARN

internal fun initLogging(args: Array<String>) {
Expand All @@ -30,22 +41,52 @@ internal fun initLogging(args: Array<String>) {
return@let
}
}
Thread.setDefaultUncaughtExceptionHandler { thread, ex ->
LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME).warn("Uncaught exception in $thread: ${ex.getStackTraceString()}")
val lastPrompt = AtomicInteger(0)
var agreed = false
Thread.setDefaultUncaughtExceptionHandler { thread, e ->
val trace = "$thread: ${e.getStackTraceString()}"
val rootLogger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)
rootLogger.warn("Uncaught exception in $trace")
fun sendReport() = GlobalScope.launch {
TabSettings.sendFeedback(TabSettings.Companion.Feedback("automated report of ${e.javaClass.name.replaceIllegalFileChars()}",
"Automated log report for uncaught exception in $trace"))
}
if(agreed) {
rootLogger.info("Automatically sending report")
sendReport()
} else if(lastPrompt.getAndSet(Int.MAX_VALUE) < currentSeconds() - 30) {
doWhenReady {
rootLogger.debug("Showing prompt for submitting uncaught exception")
showAlert(Alert.AlertType.WARNING, "Internal Error", "An Internal Error has occured: $e",
"Please let me submit your logs for debugging purposes. Thanks :)", ButtonType.YES, ButtonType.NO, ButtonType("Do not ask me again this session")).resultProperty().listen {
agreed = false
when(it) {
ButtonType.YES -> {
agreed = true
sendReport()
}
ButtonType.NO -> {
}
else -> return@listen
}
rootLogger.debug("Send report response: $it")
lastPrompt.set(currentSeconds())
}
}
}
}

val logger = KotlinLogging.logger { }
logger.info("Console loglevel: $logLevel")
logger.info("Logging to $logFile")
GlobalScope.launch {
val logs = logDir.listFiles()
if (logs.size > 10) {
if(logs.size > 10) {
logs.asSequence().sortedByDescending { it.name }.drop(5).filter {
val timestamp = it.nameWithoutExtension.substring(3).toIntOrNull()
?: return@filter true
timestamp + 200_000 < currentSeconds()
it.lastModified() + 50 * 360_000 < System.currentTimeMillis()
}.also {
val count = it.count()
if (count > 0)
if(count > 0)
logger.debug("Deleting $count old logs")
}.forEach { it.delete() }
}
Expand Down Expand Up @@ -82,7 +123,7 @@ internal class LogbackConfigurator : ContextAwareBase(), Configurator {
}

val rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME)
if (logLevel.levelInt < Level.DEBUG_INT)
if(logLevel.levelInt < Level.DEBUG_INT)
rootLogger.level = logLevel
rootLogger.addAppender(consoleAppender)
rootLogger.addAppender(fileAppender)
Expand Down
16 changes: 11 additions & 5 deletions src/main/xerus/monstercat/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import kotlinx.coroutines.*
import mu.KotlinLogging
import xerus.ktutil.SystemUtils
import xerus.ktutil.getResource
import xerus.ktutil.javafx.onFx
import xerus.ktutil.javafx.ui.App
import xerus.ktutil.ui.SimpleFrame
import java.io.File
Expand Down Expand Up @@ -41,7 +42,7 @@ fun main(args: Array<String>) {
val logger = KotlinLogging.logger {}
logger.debug("Commandline arguments: ${args.joinToString(", ", "[", "]")}")

if (!SystemUtils.javaVersion.startsWith("1.8")) {
if(!SystemUtils.javaVersion.startsWith("1.8")) {
SimpleFrame { add(JTextArea("Please install and use Java 8!\nThe current version is ${SystemUtils.javaVersion}").apply { isEditable = false }) }
return
}
Expand All @@ -51,7 +52,7 @@ fun main(args: Array<String>) {
Sheets.initService("MonsterUtilities", GoogleCredential().createScoped(listOf(SheetsScopes.SPREADSHEETS_READONLY)))

val checkUpdate = !args.contains("--no-update") && Settings.AUTOUPDATE() && jarLocation.toString().endsWith(".jar")
App.launch("MonsterUtilities $VERSION", Settings.SKIN(), { stage ->
App.launch("MonsterUtilities $VERSION", Settings.THEME(), { stage ->
stage.icons.addAll(arrayOf("img/icon64.png").map {
getResource(it)?.let { Image(it.toExternalForm()) }
?: null.apply { logger.warn("Resource $it not found!") }
Expand All @@ -63,13 +64,18 @@ fun main(args: Array<String>) {
logger.info("Main has shut down!")
}

fun showErrorSafe(error: Throwable, title: String = "Error") {
fun showErrorSafe(error: Throwable, title: String = "Error") = doWhenReady { showError(error, title) }

fun doWhenReady(action: MonsterUtilities.() -> Unit) {
GlobalScope.launch {
var i = 0
while (i < 100 && !::monsterUtilities.isInitialized) {
while(i < 100 && !::monsterUtilities.isInitialized) {
delay(200)
i++
}
monsterUtilities.showError(error, title)
onFx {
action(monsterUtilities)
}
}
}

8 changes: 5 additions & 3 deletions src/main/xerus/monstercat/MonsterUtilities.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import xerus.ktutil.javafx.controlsfx.progressDialog
import xerus.ktutil.javafx.controlsfx.stage
import xerus.ktutil.javafx.properties.listen
import xerus.ktutil.javafx.ui.*
import xerus.monstercat.api.Releases
import xerus.monstercat.api.Cache
import xerus.monstercat.api.DiscordRPC
import xerus.monstercat.api.Player
import xerus.monstercat.downloader.TabDownloader
Expand Down Expand Up @@ -70,7 +70,7 @@ class MonsterUtilities(checkForUpdate: Boolean) : VBox(), JFXMessageDisplay {
Settings.LASTVERSION.put(VERSION)
} else {
GlobalScope.launch {
Releases.clear()
Cache.clear()
logger.info("New version! Now running $VERSION, previously " + Settings.LASTVERSION())
val f = Settings.DELETE()
if (f.exists()) {
Expand Down Expand Up @@ -101,12 +101,14 @@ class MonsterUtilities(checkForUpdate: Boolean) : VBox(), JFXMessageDisplay {

inline fun <reified T : BaseTab> tabsByClass() = tabs.mapNotNull { it as? T }

private fun String.devVersion() = if(startsWith("dev")) split('v', '-')[1].toInt() else null

fun checkForUpdate(userControlled: Boolean = false, unstable: Boolean = isUnstable) {
GlobalScope.launch {
try {
val latestVersion = URL("http://monsterutilities.bplaced.net/downloads/" + if (unstable) "unstable" else "latest").openConnection().getInputStream().reader().readLines().firstOrNull()
logger.info("Latest version: $latestVersion")
if (latestVersion == null || latestVersion.length > 50 || latestVersion == VERSION || (!userControlled && latestVersion == Settings.IGNOREVERSION())) {
if (latestVersion == null || latestVersion.length > 50 || latestVersion == VERSION || (!userControlled && latestVersion == Settings.IGNOREVERSION()) || latestVersion.devVersion()?.let { VERSION.devVersion()!! < it } == true) {
if (userControlled)
showMessage("No update found!", "Updater", Alert.AlertType.INFORMATION)
return@launch
Expand Down
14 changes: 7 additions & 7 deletions src/main/xerus/monstercat/Settings.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ object Settings : SettingsNode("xerus/monsterutilities") {
val VISIBLECATALOGCOLUMNS = create("catalogVisibleColumns", defaultColumns)
val GENRECOLORINTENSITY = create("genrecolors", 80)

val SKIN = create("skin", Themes.BLACK)
val THEME = create("theme", Themes.BLACK)

val LASTVERSION = create("versionLast")
val IGNOREVERSION = create("versionIgnore")
Expand All @@ -43,13 +43,13 @@ object Settings : SettingsNode("xerus/monsterutilities") {
val FILENAMEPATTERN = create("updatePattern", "MonsterUtilities-%version%.jar")

init {
Settings.ENABLECACHE.listen { selected ->
ENABLECACHE.listen { selected ->
logger.debug("Cache " + (if (selected) "en" else "dis") + "abled")
if (selected)
FetchTab.writeCache()
}

Settings.UNSTABLE.addListener(object : ChangeListener<Boolean> {
UNSTABLE.addListener(object : ChangeListener<Boolean> {
override fun changed(o: ObservableValue<out Boolean>, old: Boolean, new: Boolean) {
if (new) {
val alert = monsterUtilities.showAlert(Alert.AlertType.CONFIRMATION, title = "Are you sure?",
Expand All @@ -59,16 +59,16 @@ object Settings : SettingsNode("xerus/monsterutilities") {
if (alert.result.buttonData == ButtonBar.ButtonData.YES) {
monsterUtilities.checkForUpdate(true, true)
} else {
Settings.UNSTABLE.removeListener(this)
Settings.UNSTABLE.set(false)
Settings.UNSTABLE.addListener(this)
UNSTABLE.removeListener(this)
UNSTABLE.set(false)
UNSTABLE.addListener(this)
}
}
}
}
})

Settings.SKIN.listen { monsterUtilities.scene.applyTheme(it) }
THEME.listen { monsterUtilities.scene.applyTheme(it) }
}

}
30 changes: 0 additions & 30 deletions src/main/xerus/monstercat/api/API.kt

This file was deleted.

Loading

0 comments on commit 3bfabf5

Please sign in to comment.