├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ ├── auto-assign-to-project.yml │ ├── build.yml │ ├── release.yml │ └── test.yml ├── .gitignore ├── .run ├── build.run.xml └── run.run.xml ├── LICENSE ├── README.md ├── docs ├── AutoPlug-Client.jar.conf ├── FAQ.md ├── How To - Install AP Client on a Server.md ├── file-manager.gif ├── online-console.gif └── tasks.gif ├── pom.xml └── src ├── main ├── java │ ├── JPM.java │ └── com │ │ └── osiris │ │ └── autoplug │ │ └── client │ │ ├── Main.java │ │ ├── SelfInstaller.java │ │ ├── Server.java │ │ ├── SystemChecker.java │ │ ├── Target.java │ │ ├── configs │ │ ├── BackupConfig.java │ │ ├── GeneralConfig.java │ │ ├── LoggerConfig.java │ │ ├── ModsConfig.java │ │ ├── MyYaml.java │ │ ├── PluginsConfig.java │ │ ├── RestarterConfig.java │ │ ├── SSHConfig.java │ │ ├── SharedFilesConfig.java │ │ ├── SystemConfig.java │ │ ├── UpdaterConfig.java │ │ └── WebConfig.java │ │ ├── console │ │ ├── Commands.java │ │ └── ThreadUserInput.java │ │ ├── managers │ │ ├── DownloadManager.java │ │ ├── DownloaderHtmlunit.java │ │ ├── DownloaderSpiget.java │ │ ├── FileManager.java │ │ ├── IDownloader.java │ │ ├── Pack.java │ │ ├── PackManager.java │ │ ├── SyncFilesManager.java │ │ └── UtilsWebClient.java │ │ ├── network │ │ ├── local │ │ │ ├── ConPluginCommandReceive.java │ │ │ ├── LocalConnectionValidator.java │ │ │ └── LocalTaskReceivePlugins.java │ │ └── online │ │ │ ├── ConMain.java │ │ │ ├── DefaultConnection.java │ │ │ ├── OnlineTaskUpdatePlugins.java │ │ │ ├── RunnableWithException.java │ │ │ └── connections │ │ │ ├── ConAutoPlugConsoleReceive.java │ │ │ ├── ConAutoPlugConsoleSend.java │ │ │ ├── ConFileManager.java │ │ │ ├── ConPluginsUpdateResult.java │ │ │ ├── ConSendPrivateDetails.java │ │ │ ├── ConSendPublicDetails.java │ │ │ ├── ConSystemConsoleReceive.java │ │ │ ├── ConSystemConsoleSend.java │ │ │ ├── SSHServerConsoleReceive.java │ │ │ └── SSHServerSetup.java │ │ ├── tasks │ │ ├── BeforeServerStartupTasks.java │ │ ├── SSHManager.java │ │ ├── SerialBThreadPrinter.java │ │ ├── TaskGeneral.java │ │ ├── backup │ │ │ ├── TaskBackup.java │ │ │ └── Upload.java │ │ ├── scheduler │ │ │ ├── CustomRestartJob.java │ │ │ ├── RestartJob.java │ │ │ ├── TaskCustomRestarter.java │ │ │ └── TaskDailyRestarter.java │ │ └── updater │ │ │ ├── TaskDownload.java │ │ │ ├── java │ │ │ ├── AdoptV3API.java │ │ │ ├── TaskJavaDownload.java │ │ │ └── TaskJavaUpdater.java │ │ │ ├── mods │ │ │ ├── CurseForgeAPI.java │ │ │ ├── CurseForgeJson.java │ │ │ ├── InstalledModLoader.java │ │ │ ├── MinecraftMod.java │ │ │ ├── ModrinthAPI.java │ │ │ ├── TaskModDownload.java │ │ │ └── TaskModsUpdater.java │ │ │ ├── plugins │ │ │ ├── MinecraftPlugin.java │ │ │ ├── ResourceFinder.java │ │ │ ├── TaskPluginDownload.java │ │ │ └── TaskPluginsUpdater.java │ │ │ ├── search │ │ │ ├── CustomCheckURL.java │ │ │ ├── GithubSearch.java │ │ │ ├── JenkinsSearch.java │ │ │ ├── SearchResult.java │ │ │ ├── bukkit │ │ │ │ ├── Bukkit.java │ │ │ │ └── BukkitSearchById.java │ │ │ └── spigot │ │ │ │ ├── SpigetAPI.java │ │ │ │ ├── SpigotSearchByAuthor.java │ │ │ │ ├── SpigotSearchById.java │ │ │ │ └── SpigotSearchByName.java │ │ │ ├── self │ │ │ └── TaskSelfUpdater.java │ │ │ └── server │ │ │ └── TaskServerUpdater.java │ │ ├── ui │ │ ├── HomePanel.java │ │ ├── MainWindow.java │ │ ├── MindustryModsPanel.java │ │ ├── MinecraftModsPanel.java │ │ ├── MinecraftPluginsPanel.java │ │ ├── SettingsPanel.java │ │ └── utils │ │ │ ├── HintTextField.java │ │ │ └── MyMouseListener.java │ │ └── utils │ │ ├── ConsoleOutputCapturer.java │ │ ├── GD.java │ │ ├── MineStat.java │ │ ├── SteamCMD.java │ │ ├── Streams.java │ │ ├── StringComparator.java │ │ ├── UpdateCheckerThread.java │ │ ├── UtilsByte.java │ │ ├── UtilsConfig.java │ │ ├── UtilsCrypto.java │ │ ├── UtilsFile.java │ │ ├── UtilsJar.java │ │ ├── UtilsLists.java │ │ ├── UtilsLogger.java │ │ ├── UtilsMap.java │ │ ├── UtilsMinecraft.java │ │ ├── UtilsNative.java │ │ ├── UtilsRandom.java │ │ ├── UtilsString.java │ │ ├── UtilsURL.java │ │ ├── io │ │ ├── AsyncInputStream.java │ │ ├── AsyncReader.java │ │ ├── MyTeeOutputStream.java │ │ ├── NonBlockingPipedInputStream.java │ │ ├── UFDataIn.java │ │ └── UFDataOut.java │ │ ├── tasks │ │ ├── CoolDownReport.java │ │ ├── MyBThreadManager.java │ │ ├── MyDate.java │ │ └── UtilsTasks.java │ │ └── terminal │ │ ├── AsyncTerminal.java │ │ └── Terminal.java └── resources │ ├── autoplug-icon.png │ ├── log4j.xml │ ├── log4j2.xml │ └── quartz.properties └── test └── java └── com └── osiris └── autoplug └── client ├── SystemCheckerTest.java ├── UtilsTest.java ├── bugs └── VersionBugs.java ├── tasks └── updater │ ├── TaskPluginDownloadTest.java │ ├── TestPluginUpdaters.java │ └── server │ └── TaskServerUpdaterTest.java └── utils ├── SteamCMDTest.java ├── UtilsFileTest.java ├── UtilsLoggerTest.java ├── UtilsMapTest.java └── UtilsStringTest.java /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Help making AutoPlug better. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 |
11 | Show log 12 | 13 | ```log 14 | Extract relevant information from your log and insert it here. Logs are usually located at /autoplug/logs. 15 | The log contains your system details at some point. If possible you should insert them here too. 16 | It also contains warnings with stack traces. Insert relevant warnings and other messages here. 17 | ``` 18 |
19 | 20 | **Expected** 21 | What did you expect to happen. 22 | 23 | **Actual** 24 | What did actually happen. 25 | 26 | **Steps** 27 | (Optional) Steps to reproduce the behaviour. 28 | 29 | **Screenshots** 30 | (Optional) Screenshots to help explain your problem. You can copy and paste them here. 31 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Importance:** 0/10 11 | 12 | **Problem:** 13 | Describe why you are writing this feature request. 14 | 15 | **Solution:** 16 | Describe your solution to the problem and any alternative solutions. 17 | -------------------------------------------------------------------------------- /.github/workflows/auto-assign-to-project.yml: -------------------------------------------------------------------------------- 1 | name: Auto Assign to Project(s) 2 | 3 | on: 4 | issues: 5 | types: [opened, labeled] 6 | pull_request: 7 | types: [opened, labeled] 8 | env: 9 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 10 | 11 | jobs: 12 | assign_one_project: 13 | runs-on: ubuntu-latest 14 | name: Assign to One Project 15 | steps: 16 | - name: Assign NEW issues and NEW pull requests to project 1 17 | uses: srggrs/assign-one-project-github-action@1.2.1 18 | if: github.event.action == 'opened' 19 | with: 20 | project: 'https://github.com/Osiris-Team/AutoPlug-Client/projects/1' 21 | column_name: '🔍 Evaluating...' 22 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Gradle 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle 3 | 4 | name: Build 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | types: [ opened, labeled ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | permissions: write-all 17 | 18 | steps: 19 | - uses: actions/checkout@v4 20 | - name: Set up Oracle GraalVM for JDK 17 21 | uses: graalvm/setup-graalvm@v1 22 | with: 23 | java-version: '17' 24 | distribution: 'graalvm' 25 | - name: Build with 1JPM 26 | run: java ./src/main/java/JPM.java 27 | - name: Upload Artifact 28 | uses: actions/upload-artifact@v4 29 | with: 30 | name: AutoPlug-Client 31 | path: AP-TEST-SERVER/AutoPlug-Client.jar 32 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Gradle, and cache/restore any dependencies to improve the workflow execution time 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle 3 | 4 | name: Release 5 | 6 | on: 7 | workflow_dispatch: 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: windows-latest 13 | 14 | steps: 15 | 16 | - uses: actions/checkout@v4 17 | - name: Set up JDK 17 18 | uses: actions/setup-graalvm@v1 19 | with: 20 | java-version: '17' 21 | distribution: 'graalvm' 22 | cache: 'gradle' 23 | 24 | - name: Build with 1JPM 25 | run: java ./src/main/java/JPM.java 26 | 27 | - name: Show files. 28 | run: | 29 | echo Showing current directory: 30 | ls 31 | echo Showing ./build directory: 32 | ls ./build 33 | 34 | - uses: "marvinpinto/action-automatic-releases@latest" 35 | with: 36 | repo_token: "${{ secrets.GITHUB_TOKEN }}" 37 | automatic_release_tag: "latest" 38 | prerelease: false 39 | title: "Release" 40 | files: | 41 | ./build/*.tar.gz 42 | ./build/*.zip 43 | ./build/*.jar 44 | ./build/libs/*.exe 45 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Gradle 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle 3 | 4 | name: Test 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | types: [ opened, labeled ] 11 | 12 | jobs: 13 | test: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v4 19 | - name: Set up Oracle GraalVM for JDK 17 20 | uses: graalvm/setup-graalvm@v1 21 | with: 22 | java-version: '17' 23 | distribution: 'graalvm' 24 | - name: Build with 1JPM 25 | run: java ./src/main/java/JPM.java test 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/AP-TEST-SERVER/ 2 | /autoplug 3 | /test 4 | /target/ 5 | 6 | # IDEA 7 | **/.idea/ 8 | **/*.iml 9 | 10 | # Visual Studio Code 11 | **/.vscode/ 12 | 13 | # MacOS 14 | .DS_Store 15 | 16 | # Eclipse 17 | .settings 18 | .classpath 19 | .project 20 | /.mvn/ 21 | mvnw.cmd 22 | mvnw 23 | -------------------------------------------------------------------------------- /.run/build.run.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 17 | -------------------------------------------------------------------------------- /.run/run.run.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Osiris Team 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /docs/AutoPlug-Client.jar.conf: -------------------------------------------------------------------------------- 1 | # You can directly download this single file 2 | # from GitHub, here is how: https://www.howtogeek.com/devops/how-to-download-single-files-from-a-github-repository/ 3 | [config] 4 | name = AutoPlug-Client for Multicraft 5 | source = https://github.com/Osiris-Team/AutoPlug-Releases/raw/master/stable-builds/AutoPlug-Client.jar 6 | configSource = https://raw.githubusercontent.com/Osiris-Team/AutoPlug-Client/master/docs/AutoPlug-Client.jar.conf 7 | 8 | [encoding] 9 | #encode = system 10 | #decode = system 11 | #fileEncoding = latin-1 12 | 13 | [start] 14 | command = "{JAVA}" -jar "{JAR}" 15 | -------------------------------------------------------------------------------- /docs/How To - Install AP Client on a Server.md: -------------------------------------------------------------------------------- 1 | # How To: Install AutoPlug Client on a Server Host 2 | 3 | ### **Can I use AutoPlug Client with my host?** 4 | Yes! AutoPlug Client is designed to work ready out-of-the-box and should be compatible with the majority of Minecraft server hosts. 5 | 6 | ### **How can I install AutoPlug Client on my host?** 7 | The overall process is very simple and straightforward. 8 | This guide will explain everything from start to finish and works whether you have an existing server or are starting fresh. 9 | 10 | 1. Go to the AutoPlug Client [installer page](https://autoplug.one/installer) and make sure these options are set: 11 | * Target-OS: `Linux/MacOS (or distro)` 12 | > *Majority of Minecraft server hosts operate off of a Linux distro of some kind due to their lightweight structure* 13 | * Add screen support: ***`Unless you know what you're doing, leave this unchecked`*** 14 | * Mode: `Server-Wrapper` 15 | * Start on boot: `Unchecked` 16 | * System-Tray: `Unchecked` 17 | 2. Click `Generate Files` and download the generated `AutoPlug-Files.zip` file 18 | 3. Extract the files from `AutoPlug-Files.zip` somewhere easy for you to find 19 | 4. Using an FTP client (i.e. FileZilla) or your host's built-in file manager, upload the extracted files to the root directory of your host so that it looks similar to this: 20 | ```text 21 | ./autoplug/... 22 | ... 23 | ./AutoPlug-Client.jar 24 | ... 25 | ./server.jar 26 | ./server.properties 27 | ... 28 | ./start.sh 29 | ... 30 | ``` 31 | > *If you're not sure how to upload files to your host, search their support pages on how to do so.* 32 | > *Almost every single Minecraft server host should have this function available.* 33 | 34 | 5. In your host's server settings, change your server type to `Custom Server`, `Custom Server Jar`, or something else that is similarly worded 35 | > *Almost all hosts should offer the option to let you use a custom server jar in your instance.* 36 | > *If you're not sure how to find this setting, search your host's support pages on `How to use a custom server/jar` and follow their instructions.* 37 | 38 | 6. In the `Custom Jar`/`Jar Name`/`File Name` field, type in "`AutoPlug-Client.jar`" 39 | 40 | 7. Save your new settings 41 | 42 | 8. Start the server using your host's dashboard 43 | 44 | 9. Go through AutoPlug's first-time setup in your host's server console 45 | 46 | 10. You're done! 47 | 48 | ### **I'm having problems installing AutoPlug Client on my host!** 49 | Please make either a Github Issue or a post in the Discord's #help channel including the host you're using and the problems you're having. -------------------------------------------------------------------------------- /docs/file-manager.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Osiris-Team/AutoPlug-Client/b23647c9ad705775c6ca38a011279af23c57eaf4/docs/file-manager.gif -------------------------------------------------------------------------------- /docs/online-console.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Osiris-Team/AutoPlug-Client/b23647c9ad705775c6ca38a011279af23c57eaf4/docs/online-console.gif -------------------------------------------------------------------------------- /docs/tasks.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Osiris-Team/AutoPlug-Client/b23647c9ad705775c6ca38a011279af23c57eaf4/docs/tasks.gif -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/SystemChecker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client; 10 | 11 | import com.osiris.autoplug.client.tasks.SSHManager; 12 | import com.osiris.jlib.logger.AL; 13 | 14 | import java.io.*; 15 | import java.net.HttpURLConnection; 16 | import java.net.InetAddress; 17 | import java.net.URL; 18 | 19 | public class SystemChecker { 20 | 21 | 22 | public void checkReadWritePermissions() throws Exception { 23 | try { 24 | File test = new File(System.getProperty("user.dir") + "/read-write-test.txt"); 25 | if (!test.exists()) { 26 | test.createNewFile(); 27 | } 28 | 29 | // Test writing to file 30 | try (BufferedWriter writer = new BufferedWriter(new FileWriter(test))) { 31 | writer.write("Writing some random stuff, to test write permissions!"); 32 | writer.flush(); 33 | } 34 | 35 | // Test reading the file 36 | try (BufferedReader reader = new BufferedReader(new FileReader(test))) { 37 | reader.readLine(); 38 | } 39 | 40 | test.delete(); 41 | } catch (Exception e) { 42 | System.err.println("Make sure that this jar has read/write permissions!"); 43 | throw e; 44 | } 45 | } 46 | 47 | public void checkInternetAccess() throws Exception { 48 | try { 49 | boolean reachable = InetAddress.getByName("www.google.com").isReachable(10000); 50 | if (!reachable) throw new Exception("Failed to reach www.google.com!"); 51 | } catch (Exception e) { 52 | try { 53 | HttpURLConnection connection = (HttpURLConnection) new URL("https://www.google.com").openConnection(); 54 | connection.connect(); 55 | connection.disconnect(); 56 | } catch (Exception ex) { 57 | System.err.println("Make sure that you have an internet connection!"); 58 | throw ex; 59 | } 60 | } 61 | } 62 | 63 | /** 64 | * This enables AutoPlug to securely 65 | * shutdown and closes all open things. 66 | */ 67 | public void addShutDownHook() { 68 | Runtime.getRuntime().addShutdownHook(new Thread(() -> { 69 | try { 70 | if (Server.isRunning()) Server.stop(); 71 | } catch (Exception e) { 72 | System.err.println("Error during shutdown, related to stopping the server!"); 73 | e.printStackTrace(); 74 | System.err.println("Error during shutdown, related to stopping the server!"); 75 | } 76 | 77 | try { 78 | if (AL.isStarted) 79 | SSHManager.stop(); 80 | } catch (Exception e) { 81 | System.out.println("Error during shutdown, related to stopping the SSH server!"); 82 | e.printStackTrace(); 83 | System.out.println("Error during shutdown, related to stopping the SSH server!"); 84 | } 85 | 86 | // Stop Logger last 87 | try { 88 | if (AL.isStarted) { 89 | AL.info("See you soon!"); 90 | AL.stop(); 91 | } else { 92 | System.out.println("See you soon!"); 93 | } 94 | } catch (Exception e) { 95 | System.err.println("Error during shutdown, related to the AutoPlug-Logger!"); 96 | e.printStackTrace(); 97 | System.err.println("Error during shutdown, related to the AutoPlug-Logger!"); 98 | } 99 | }, "Shutdown-Thread")); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/Target.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client; 10 | 11 | public enum Target { 12 | MINECRAFT_CLIENT, 13 | MINECRAFT_SERVER, 14 | MINDUSTRY_SERVER, 15 | MINDUSTRY_CLIENT, 16 | OTHER; 17 | 18 | public static Target fromString(String s) { 19 | switch (s) { 20 | case "MINECRAFT_CLIENT": 21 | return Target.MINECRAFT_CLIENT; 22 | case "MINECRAFT_SERVER": 23 | return Target.MINECRAFT_SERVER; 24 | case "MINDUSTRY_SERVER": 25 | return Target.MINDUSTRY_SERVER; 26 | case "MINDUSTRY_CLIENT": 27 | return Target.MINDUSTRY_CLIENT; 28 | case "OTHER": 29 | return Target.OTHER; 30 | default: 31 | return null; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/configs/SharedFilesConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.configs; 10 | 11 | import com.osiris.autoplug.client.managers.SyncFilesManager; 12 | import com.osiris.dyml.Yaml; 13 | import com.osiris.dyml.YamlSection; 14 | import com.osiris.dyml.exceptions.*; 15 | import com.osiris.jlib.logger.AL; 16 | 17 | import java.io.IOException; 18 | 19 | public class SharedFilesConfig extends MyYaml { 20 | 21 | public YamlSection enable; 22 | public YamlSection copy_from; 23 | public YamlSection send_to; 24 | 25 | 26 | public SharedFilesConfig() throws IOException, DuplicateKeyException, YamlReaderException, IllegalListException, NotLoadedException, IllegalKeyException, YamlWriterException { 27 | super(System.getProperty("user.dir") + "/autoplug/shared-files.yml"); 28 | 29 | addSingletonConfigFileEventListener(e -> { 30 | try { 31 | this.load(); 32 | 33 | if (enable.asBoolean()) 34 | new SyncFilesManager(this); 35 | } catch (Exception ex) { 36 | AL.warn(ex); 37 | } 38 | }); 39 | 40 | lockFile(); 41 | load(); 42 | String name = getFileNameWithoutExt(); 43 | put(name).setComments( 44 | "#######################################################################################################################\n" + 45 | " ___ __ ___ __\n" + 46 | " / _ |__ __/ /____ / _ \\/ /_ _____ _\n" + 47 | " / __ / // / __/ _ \\/ ___/ / // / _ `/\n" + 48 | " /_/ |_\\_,_/\\__/\\___/_/ /_/\\_,_/\\_, /\n" + 49 | " /___/ Shared-Files-Config\n" + 50 | "Thank you for using AutoPlug!\n" + 51 | "You can find detailed installation instructions here: https://autoplug.one/installer\n" + 52 | "If there are any questions or you just want chat, join our Discord: https://discord.gg/GGNmtCC\n" + 53 | "\n" + 54 | "#######################################################################################################################"); 55 | 56 | enable = put(name, "enable").setDefValues("false").setComments("Enable/Disable sharing folders from this server to other servers.\n" + 57 | "NOTE: CHANGES TO THIS FILE REQUIRE A AUTOPLUG RESTART TO TAKE AFFECT!\n"); 58 | 59 | //TODO "More control is in TODO.\n" + 60 | copy_from = put(name, "copy-from").setDefValues("./plugins", "./server.jar") 61 | .setComments("List of folders to watch. Once a file event happens, that event/change gets shared/sent to the servers in the 'send-to' list.\n" + 62 | "All folders must be sub-folders of the server root and thus start with './' (the servers root directory).\n" + 63 | "If you want to watch all files from your server simply add './' below.\n" + 64 | "Note that sub-folders of the added folders below are also watched. \n" 65 | ); 66 | 67 | send_to = put(name, "send-to").addDefValues("C:\\User\\Peter\\servers\\my-second-server") 68 | .addDefSideComments("Example for absolute path") 69 | .addDefValues("./servers/another-server") 70 | .addDefSideComments("Example for relative path") 71 | .setComments("List of server root folders of the servers which receive the file changes.\n" + 72 | // TODO "NOT WORKING/IN TODO: Note that if the server is not on the same machine (you enter an ip), then you will need to have AutoPlug installed on that server too.\n" + 73 | // "Otherwise if the server is on the same machine (you enter its path to its server root directory), then you don't need AutoPlug installed on it.\n" + 74 | //TODO "Note that if you enter a folder that contains multiple servers, AutoPlug detects those individual servers automatically.\n" + 75 | "Note that absolute and relative paths" + 76 | //TODO ", as well as ipv4 and ipv6 addresses" + 77 | " are supported.\n"); 78 | 79 | save(); 80 | unlockFile(); 81 | } 82 | 83 | @Override 84 | public Yaml validateValues() { 85 | return this; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/configs/SystemConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.configs; 10 | 11 | import com.osiris.autoplug.client.utils.UtilsRandom; 12 | import com.osiris.dyml.Yaml; 13 | import com.osiris.dyml.YamlSection; 14 | import com.osiris.dyml.exceptions.*; 15 | 16 | import java.io.IOException; 17 | 18 | public class SystemConfig extends MyYaml { 19 | 20 | public YamlSection timestamp_last_backup; 21 | 22 | public YamlSection timestamp_last_updater_tasks; // Only matters if global cooldown for updaters is enabled 23 | public YamlSection autoplug_web_ssl; 24 | public YamlSection autoplug_web_ip; 25 | public YamlSection autoplug_web_port; 26 | public YamlSection autoplug_plugin_key; 27 | public YamlSection is_autostart_registered; 28 | 29 | 30 | public SystemConfig() throws IOException, DuplicateKeyException, YamlReaderException, IllegalListException, NotLoadedException, IllegalKeyException, YamlWriterException { 31 | super(System.getProperty("user.dir") + "/autoplug/system/config.yml"); 32 | 33 | addSingletonConfigFileEventListener(e -> { 34 | }); 35 | 36 | lockFile(); 37 | load(); 38 | String name = getFileNameWithoutExt(); 39 | put(name).setComments( 40 | "#######################################################################################################################\n" + 41 | " ___ __ ___ __\n" + 42 | " / _ |__ __/ /____ / _ \\/ /_ _____ _\n" + 43 | " / __ / // / __/ _ \\/ ___/ / // / _ `/\n" + 44 | " /_/ |_\\_,_/\\__/\\___/_/ /_/\\_,_/\\_, /\n" + 45 | " /___/ System-Config\n" + 46 | "DO NOT CHANGE ANYTHING IN HERE, UNLESS YOU KNOW WHAT YOU ARE DOING!\n" + 47 | "\n" + 48 | "#######################################################################################################################"); 49 | is_autostart_registered = put(name, "is-autostart-registered").setDefValues("false"); 50 | timestamp_last_updater_tasks = put(name, "timestamp-last-updater-tasks"); 51 | 52 | timestamp_last_backup = put(name, "timestamp-last-backup-task"); 53 | 54 | autoplug_web_ssl = put(name, "autoplug-web-ssl").setDefValues("true").setComments("If localhost is used below, remember to set this to false too!"); 55 | autoplug_web_ip = put(name, "autoplug-web-ip").setDefValues("144.91.78.158").setComments("Set to localhost to test on the local server.", 56 | "Otherwise set to 144.91.78.158 or autoplug.one to connect with the default production server (remember to enable autoplug-web-ssl in this case too)."); 57 | autoplug_web_port = put(name, "autoplug-web-port").setDefValues("35555"); 58 | 59 | autoplug_plugin_key = put(name, "autoplug-plugin-key"); 60 | if (autoplug_plugin_key.asString() == null) 61 | autoplug_plugin_key.setValues(new UtilsRandom().generateNewKey(500)); 62 | 63 | save(); 64 | unlockFile(); 65 | } 66 | 67 | @Override 68 | public Yaml validateValues() { 69 | return this; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/console/ThreadUserInput.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.console; 10 | 11 | import com.osiris.autoplug.client.Main; 12 | import com.osiris.autoplug.client.Server; 13 | import com.osiris.autoplug.client.network.online.connections.ConAutoPlugConsoleSend; 14 | import com.osiris.jlib.logger.AL; 15 | import com.osiris.jlib.logger.LogFileWriter; 16 | import org.jline.reader.EndOfFileException; 17 | import org.jline.reader.LineReader; 18 | import org.jline.reader.LineReaderBuilder; 19 | import org.jline.reader.UserInterruptException; 20 | 21 | import java.util.concurrent.CopyOnWriteArrayList; 22 | import java.util.function.Consumer; 23 | 24 | import static com.osiris.betterthread.Constants.TERMINAL; 25 | 26 | public class ThreadUserInput extends Thread { 27 | 28 | public static CopyOnWriteArrayList> onReadLine = new CopyOnWriteArrayList<>(); 29 | 30 | public ThreadUserInput() { 31 | setName("AutoPlug-UserInputListenerThread"); 32 | } 33 | 34 | @Override 35 | public void run() { 36 | super.run(); 37 | try { 38 | //Scanner scanner = new Scanner(System.in); // Old 39 | LineReader lineReader = LineReaderBuilder.builder() 40 | .terminal(TERMINAL) 41 | .build(); 42 | 43 | while (true) { 44 | String user_input = null; 45 | try { 46 | user_input = lineReader.readLine(); 47 | for (Consumer code : onReadLine) { 48 | code.accept(user_input); 49 | } 50 | 51 | // Send to online console 52 | if (Main.CON.CON_CONSOLE_SEND.isAlive()) 53 | try { 54 | ConAutoPlugConsoleSend.send(user_input); 55 | } catch (Exception e) { 56 | AL.warn(e); 57 | } 58 | 59 | //Check if user input is autoplug command or not 60 | if (Commands.execute(user_input)) { 61 | 62 | //Do nothing else if it is a client command, just save it to log file 63 | try { 64 | LogFileWriter.writeToLog("\n\n" + user_input + "\n\n"); 65 | } catch (Exception e) { 66 | AL.warn(e, "Failed to write command to log file."); 67 | } 68 | 69 | } else 70 | Server.submitCommand(user_input); 71 | 72 | } catch (UserInterruptException e) { 73 | // Ignore 74 | } catch (EndOfFileException e) { 75 | return; 76 | } 77 | } 78 | } catch (Exception e) { 79 | AL.warn(e); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/managers/DownloaderSpiget.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.managers; 10 | 11 | import org.jetbrains.annotations.Nullable; 12 | 13 | import java.io.InputStream; 14 | 15 | @Deprecated 16 | public class DownloaderSpiget implements IDownloader { 17 | 18 | @Nullable 19 | @Override 20 | public InputStream getInputStreamFromDownload(String download_url) throws Exception { 21 | return null; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/managers/IDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.managers; 10 | 11 | import java.io.InputStream; 12 | 13 | @Deprecated 14 | public interface IDownloader { 15 | 16 | /** 17 | * This is used to get the InputStream of an online file. 18 | * The download_url must point directly to that file. 19 | * 20 | * @return null if the download wasn't successful. 21 | */ 22 | InputStream getInputStreamFromDownload(String download_url) throws Exception; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/managers/Pack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.managers; 10 | 11 | import com.google.gson.annotations.SerializedName; 12 | 13 | public class Pack { 14 | public String name; 15 | public Type type; 16 | 17 | public enum Type { 18 | 19 | @SerializedName("0") 20 | MINECRAFT_PLUGINS(0), 21 | 22 | @SerializedName("1") 23 | MINECRAFT_MODS(1); 24 | 25 | private final int value; 26 | 27 | Type(int value) { 28 | this.value = value; 29 | } 30 | 31 | public int getValue() { 32 | return value; 33 | } 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/managers/PackManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.managers; 10 | 11 | import com.google.gson.Gson; 12 | import com.google.gson.GsonBuilder; 13 | import com.osiris.autoplug.client.utils.GD; 14 | import com.osiris.autoplug.client.utils.UtilsFile; 15 | import com.osiris.autoplug.client.utils.UtilsMinecraft; 16 | import com.osiris.jlib.logger.AL; 17 | 18 | import java.io.File; 19 | import java.io.IOException; 20 | import java.nio.charset.StandardCharsets; 21 | import java.nio.file.Files; 22 | import java.nio.file.StandardOpenOption; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | 26 | public class PackManager { 27 | public File systemPacksDir = new File(GD.WORKING_DIR + "/autoplug/system/packs"); 28 | public List installedPacks = new ArrayList<>(); 29 | 30 | public PackManager() { 31 | systemPacksDir.mkdirs(); 32 | for (File packDir : systemPacksDir.listFiles()) { 33 | if (packDir.isDirectory()) { 34 | File packJson = new File(packDir + "/autoplug-pack.json"); 35 | if (packJson.exists()) { 36 | try { 37 | installedPacks.add(load(packJson)); 38 | } catch (IOException e) { 39 | AL.warn(e); 40 | } 41 | } 42 | } 43 | } 44 | } 45 | 46 | public void save(File file, Pack pack) throws IOException { 47 | file.createNewFile(); 48 | Gson gson = new GsonBuilder() 49 | .setPrettyPrinting() 50 | .create(); 51 | Files.write(file.toPath(), gson.toJson(pack).getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE); 52 | } 53 | 54 | public Pack load(File file) throws IOException { 55 | Gson gson = new GsonBuilder() 56 | .create(); 57 | return gson.fromJson(new String(Files.readAllBytes(file.toPath())), Pack.class); 58 | } 59 | 60 | /** 61 | * Copies/Installs the contents of the provided folder 62 | * into /autoplug/system/packs and handles pack name conflicts. 63 | * 64 | * @param packDir the pack directory containing the plugins/mods to install. 65 | */ 66 | public void installPack(File packDir) throws IOException { 67 | File[] files = packDir.listFiles(); 68 | Pack pack = null; 69 | for (File file : files) { 70 | if (file.getName().equals("autoplug-pack.json")) { 71 | pack = load(file); 72 | } 73 | } 74 | if (pack == null) { 75 | pack = new Pack(); 76 | pack.name = getDefaultPackName(); 77 | int modsCount = new UtilsMinecraft().getMods(packDir).size(); 78 | int pluginsCount = new UtilsMinecraft().getMods(packDir).size(); 79 | pack.type = (modsCount > pluginsCount ? Pack.Type.MINECRAFT_MODS : Pack.Type.MINECRAFT_PLUGINS); 80 | save(new File(packDir + "/autoplug-pack.json"), pack); 81 | } 82 | int i = 0; 83 | while (isPackNameTaken(pack.name)) { 84 | pack.name = pack.name + "-" + i; 85 | i++; 86 | } 87 | save(new File(packDir + "/autoplug-pack.json"), pack); 88 | new UtilsFile().copyDirectoryContent(packDir, new File(systemPacksDir + "/" + pack.name)); 89 | } 90 | 91 | public boolean isPackNameTaken(String name) { 92 | for (Pack installedPack : installedPacks) { 93 | if (installedPack.name.equals(name)) return true; 94 | } 95 | return false; 96 | } 97 | 98 | public String getDefaultPackName() { 99 | int i = 0; 100 | for (Pack installedPack : installedPacks) { 101 | if (installedPack.name.startsWith("default-")) { 102 | i++; 103 | } 104 | } 105 | return "default-" + i; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/managers/SyncFilesManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.managers; 10 | 11 | import com.osiris.autoplug.client.Main; 12 | import com.osiris.autoplug.client.configs.SharedFilesConfig; 13 | import com.osiris.dyml.watcher.DirWatcher; 14 | import com.osiris.dyml.watcher.FileEvent; 15 | import com.osiris.jlib.logger.AL; 16 | 17 | import java.io.File; 18 | import java.nio.file.Files; 19 | import java.nio.file.StandardCopyOption; 20 | import java.nio.file.StandardWatchEventKinds; 21 | import java.util.ArrayList; 22 | import java.util.List; 23 | import java.util.function.Consumer; 24 | 25 | import static com.osiris.autoplug.client.utils.GD.WORKING_DIR; 26 | 27 | public class SyncFilesManager { 28 | private static List lastFoldersToWatch = new ArrayList<>(); 29 | public SyncFilesManager(SharedFilesConfig sharedFilesConfig) throws Exception { 30 | for (File folder : lastFoldersToWatch) { 31 | DirWatcher dirWatcher = DirWatcher.get(folder, false); 32 | dirWatcher.removeAllListeners(true); 33 | dirWatcher.close(); 34 | } 35 | 36 | List foldersToWatch = new ArrayList<>(); 37 | for (String pathAsString : 38 | sharedFilesConfig.copy_from.asStringList()) { 39 | if (pathAsString.startsWith("./")) 40 | foldersToWatch.add(FileManager.convertRelativeToAbsolutePath(pathAsString)); 41 | else 42 | throw new Exception("Wrongly formatted or absolute path: " + pathAsString); 43 | } 44 | 45 | List filesToSendTo = new ArrayList<>(); 46 | //List ipsToSendTo = new ArrayList<>(); 47 | for (String value : 48 | sharedFilesConfig.send_to.asStringList()) { 49 | if (value.startsWith("./")) 50 | filesToSendTo.add(FileManager.convertRelativeToAbsolutePath(value)); 51 | else if (value.contains("/") || value.contains("\\")) 52 | filesToSendTo.add(new File(value)); 53 | // TODO else if (value.contains(".")) 54 | // ipsToSendTo.add(value); 55 | else 56 | throw new Exception("Failed to determine if '" + value + "' is absolute/relative path address."); //TODO or ipv4/ipv6 57 | } 58 | 59 | Consumer onFileChangeEvent = event -> { 60 | // Determine relative path from file to server root 61 | // Example: C:/Users/Server/plugins/AutoPlug.jar -> /plugins/AutoPlug.jar 62 | String relPath = event.file.getAbsolutePath().replace(WORKING_DIR.getAbsolutePath(), ""); 63 | if (event.getWatchEventKind().equals(StandardWatchEventKinds.ENTRY_DELETE)) { 64 | for (File receivingServerRootDir : 65 | filesToSendTo) { 66 | new File(receivingServerRootDir + relPath) 67 | .delete(); 68 | } 69 | } else if (event.getWatchEventKind().equals(StandardWatchEventKinds.ENTRY_MODIFY) 70 | || event.getWatchEventKind().equals(StandardWatchEventKinds.ENTRY_CREATE)) { 71 | for (File receivingServerRootDir : 72 | filesToSendTo) { 73 | try { 74 | File f = new File(receivingServerRootDir + relPath); 75 | if (!f.getParentFile().exists()) f.getParentFile().mkdirs(); 76 | if (!f.exists()) f.createNewFile(); 77 | Files.copy(event.path, f.toPath(), StandardCopyOption.REPLACE_EXISTING); 78 | } catch (Exception e) { 79 | AL.warn(e); 80 | } 81 | } 82 | } else 83 | AL.warn("Failed to execute 'send-to' for event type '" + event.getWatchEventKind().name() + "' for file '" + event.file + "'!"); 84 | }; 85 | 86 | for (File folder : 87 | foldersToWatch) { 88 | DirWatcher.get(folder, true).addListeners(onFileChangeEvent); 89 | AL.debug(Main.class, "Watching 'copy-from' folder and sub-folders from: " + folder); 90 | } 91 | lastFoldersToWatch = foldersToWatch; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/managers/UtilsWebClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.managers; 10 | 11 | /* 12 | import com.gargoylesoftware.htmlunit.BrowserVersion; 13 | import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController; 14 | import com.gargoylesoftware.htmlunit.WebClient; 15 | import org.jetbrains.annotations.NotNull; 16 | 17 | import java.util.Random; 18 | import java.util.logging.Level; 19 | 20 | */ 21 | 22 | @Deprecated 23 | public class UtilsWebClient { 24 | /* 25 | @NotNull 26 | public static String buildUniqueUserAgent() { 27 | StringBuilder b = new StringBuilder(); 28 | b.append("Mozilla/5.0 " + 29 | "(Windows NT 10.0; Win64; x64) " + 30 | "AppleWebKit/537." + new Random().nextInt(250) + " " + 31 | "(KHTML, like Gecko) " + 32 | "Chrome/87.0.4280." + new Random().nextInt(250) + " " + 33 | "Safari/537." + new Random().nextInt(250)); 34 | return b.toString(); 35 | } 36 | 37 | */ 38 | 39 | /** 40 | * Provided by: https://github.com/HtmlUnit/htmlunit/issues/249 41 | */ 42 | /* 43 | @NotNull 44 | public static WebClient getNewCustomClient(int pageTimeout, int jsTimeout, String UserAgent) { 45 | java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); 46 | java.util.logging.Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.OFF); 47 | 48 | BrowserVersion ua = new BrowserVersion.BrowserVersionBuilder(BrowserVersion.CHROME).setUserAgent(UserAgent).build(); 49 | WebClient client = new WebClient(ua); 50 | 51 | client.getOptions().setUseInsecureSSL(true); 52 | 53 | client.getOptions().setJavaScriptEnabled(true); 54 | client.getOptions().setCssEnabled(true); 55 | client.getOptions().setDownloadImages(false); 56 | client.getOptions().setRedirectEnabled(true); 57 | client.getOptions().setPopupBlockerEnabled(true); 58 | client.getOptions().setDoNotTrackEnabled(true); 59 | client.getOptions().setThrowExceptionOnFailingStatusCode(false); 60 | client.getOptions().setThrowExceptionOnScriptError(false); 61 | client.getOptions().setGeolocationEnabled(false); 62 | client.getOptions().setTimeout(pageTimeout); 63 | client.getOptions().setActiveXNative(true); 64 | client.getOptions().setAppletEnabled(true); 65 | client.getOptions().setScreenHeight(768); 66 | client.getOptions().setScreenWidth(1366); 67 | 68 | client.setAjaxController(new NicelyResynchronizingAjaxController()); 69 | client.setAlertHandler((page, message) -> System.err.println("[alert] " + message)); // to be changed 70 | client.setJavaScriptTimeout(jsTimeout); 71 | client.getCookieManager().setCookiesEnabled(true); 72 | client.getCache().setMaxSize(1); 73 | 74 | return client; 75 | } 76 | 77 | 78 | */ 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/network/local/ConPluginCommandReceive.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.network.local; 10 | 11 | 12 | import com.osiris.autoplug.client.Server; 13 | import com.osiris.autoplug.client.configs.SystemConfig; 14 | import com.osiris.autoplug.client.console.Commands; 15 | import com.osiris.dyml.exceptions.*; 16 | import com.osiris.jlib.logger.AL; 17 | 18 | import java.io.*; 19 | import java.net.ServerSocket; 20 | import java.net.Socket; 21 | 22 | /** 23 | * Listens on a port for commands sent by the AutoPlug-Plugin.
24 | * Each received command gets validated, before being executed.
25 | */ 26 | public class ConPluginCommandReceive { 27 | 28 | /** 29 | * Class execution order is like this: 30 | * LocalListener -> 31 | * LocalConnectionValidator -> 32 | * LocalTaskReceivePlugins -> 33 | * OnlineConnection -> 34 | * OnlineTaskUpdatePlugins 35 | */ 36 | public ConPluginCommandReceive() { 37 | 38 | Thread newThread = new Thread(() -> { 39 | 40 | try { 41 | ServerSocket local_server_socket = null; 42 | //Search for a free port starting at 35565 and connect to it 43 | int port = 35565; 44 | while (local_server_socket == null) { 45 | try { 46 | AL.debug(this.getClass(), "Binding on localhost:" + port + " for AutoPlug-Plugin..."); 47 | local_server_socket = new ServerSocket(port); 48 | AL.debug(this.getClass(), "Success!"); 49 | } catch (IOException e) { 50 | AL.debug(this.getClass(), "Failed to bind on port " + port + "! " + e.getMessage()); 51 | local_server_socket = null; 52 | port++; 53 | } 54 | if (port == 35665) { 55 | AL.warn("Failed to bind on a port. Tried 100 ports between 35565 and 35665."); 56 | return; 57 | } 58 | } 59 | 60 | while (true) { 61 | 62 | //This blocks the thread till a client connects 63 | AL.debug(this.getClass(), "Waiting for AutoPlug-Plugin to connect..."); 64 | Socket socket = local_server_socket.accept(); 65 | 66 | DataInputStream dis = new DataInputStream(socket.getInputStream()); 67 | DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); 68 | 69 | String key = new SystemConfig().autoplug_plugin_key.asString(); 70 | dos.writeUTF(key); 71 | if (!dis.readUTF().equals(key)) { 72 | socket.close(); 73 | } else { 74 | socket.setSoTimeout(0); 75 | AL.info("AutoPlug-Plugin with matching private plugin key connected."); 76 | 77 | Thread thread = new Thread(() -> { 78 | try { 79 | InputStream in = socket.getInputStream(); 80 | try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { 81 | String line; 82 | while (!socket.isClosed() && (line = reader.readLine()) != null) { 83 | AL.info("Received Plugin-Command: " + line); 84 | if (!Commands.execute(line)) 85 | Server.submitCommand(line); 86 | } 87 | } 88 | } catch (Exception e) { 89 | AL.warn(this.getClass(), e); 90 | } 91 | 92 | }); 93 | thread.start(); 94 | } 95 | } 96 | } catch (IOException | YamlWriterException | NotLoadedException | IllegalKeyException | 97 | DuplicateKeyException | YamlReaderException | IllegalListException e) { 98 | e.printStackTrace(); 99 | } 100 | 101 | }); 102 | newThread.start(); 103 | 104 | } 105 | 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/network/local/LocalConnectionValidator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.network.local; 10 | 11 | import com.osiris.autoplug.client.configs.GeneralConfig; 12 | import com.osiris.dyml.exceptions.*; 13 | import com.osiris.jlib.logger.AL; 14 | import org.jetbrains.annotations.NotNull; 15 | 16 | import java.io.DataInputStream; 17 | import java.io.DataOutputStream; 18 | import java.io.IOException; 19 | import java.net.Socket; 20 | 21 | @Deprecated 22 | public class LocalConnectionValidator { 23 | 24 | 25 | LocalConnectionValidator(Socket local_socket, @NotNull DataInputStream local_dis, @NotNull DataOutputStream local_dos) { 26 | 27 | Thread newThread = new Thread(() -> { 28 | 29 | try { 30 | 31 | AL.info("Validating current AutoPlugPlugin connection..."); 32 | 33 | boolean matches = local_dis.readUTF().equals(new GeneralConfig().server_key.asString()); 34 | 35 | if (matches) { 36 | local_dos.writeUTF("true"); 37 | AL.info("Keys match!"); 38 | 39 | new LocalTaskReceivePlugins(local_socket, local_dis, local_dos); 40 | } else { 41 | local_dos.writeUTF("false"); 42 | AL.info("Wrong AutoPlugPlugin! Validation failed!"); 43 | } 44 | 45 | } catch (@NotNull 46 | IOException | DuplicateKeyException | YamlReaderException | IllegalListException | YamlWriterException | 47 | NotLoadedException | IllegalKeyException e) { 48 | e.printStackTrace(); 49 | } 50 | 51 | }); 52 | newThread.start(); 53 | } 54 | 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/network/local/LocalTaskReceivePlugins.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.network.local; 10 | 11 | import com.osiris.jlib.logger.AL; 12 | import org.jetbrains.annotations.NotNull; 13 | 14 | import java.io.DataInputStream; 15 | import java.io.DataOutputStream; 16 | import java.io.IOException; 17 | import java.net.Socket; 18 | 19 | @Deprecated 20 | public class LocalTaskReceivePlugins { 21 | 22 | 23 | public LocalTaskReceivePlugins(Socket local_socket, @NotNull DataInputStream local_dis, DataOutputStream local_dos) { 24 | 25 | 26 | Thread newThread = new Thread(() -> { 27 | 28 | try { 29 | 30 | AL.info("Waiting for plugins..."); 31 | int amount = local_dis.readInt(); 32 | 33 | String[] pl_names = new String[amount]; 34 | String[] pl_authors = new String[amount]; 35 | String[] pl_versions = new String[amount]; 36 | 37 | for (int i = 0; i < amount; i++) { 38 | 39 | pl_names[i] = local_dis.readUTF(); 40 | pl_authors[i] = local_dis.readUTF(); 41 | pl_versions[i] = local_dis.readUTF(); 42 | 43 | } 44 | AL.info("Received " + amount + " plugins!"); 45 | 46 | //new MainConnection(local_socket, local_dis, local_dos, pl_names, pl_authors, pl_versions, amount); 47 | 48 | } catch (IOException e) { 49 | e.printStackTrace(); 50 | AL.warn(" [!] Error receiving plugin information [!]"); 51 | } 52 | 53 | }); 54 | newThread.start(); 55 | 56 | 57 | } 58 | 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/network/online/RunnableWithException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.network.online; 10 | 11 | public interface RunnableWithException { 12 | void run() throws Exception; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/network/online/connections/ConAutoPlugConsoleReceive.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.network.online.connections; 10 | 11 | import com.osiris.autoplug.client.Main; 12 | import com.osiris.autoplug.client.Server; 13 | import com.osiris.autoplug.client.configs.WebConfig; 14 | import com.osiris.autoplug.client.console.Commands; 15 | import com.osiris.autoplug.client.network.online.DefaultConnection; 16 | import com.osiris.jlib.logger.AL; 17 | 18 | import java.io.BufferedReader; 19 | import java.io.InputStream; 20 | import java.io.InputStreamReader; 21 | import java.net.Socket; 22 | 23 | /** 24 | * The user can send commands through the online console.
25 | * For that we got this connection, which listens for the user 26 | * input at the online console and executes it. 27 | */ 28 | public class ConAutoPlugConsoleReceive extends DefaultConnection { 29 | 30 | public ConAutoPlugConsoleReceive() { 31 | super((byte) 1); 32 | } 33 | 34 | @Override 35 | public boolean open() throws Exception { 36 | if (new WebConfig().online_console.asBoolean()) { 37 | super.open(); 38 | setAndStartAsync(() -> { 39 | try { 40 | Socket socket = getSocket(); 41 | socket.setSoTimeout(0); 42 | InputStream in = getSocket().getInputStream(); 43 | try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { 44 | String line; 45 | while (!socket.isClosed() && (line = reader.readLine()) != null) { 46 | AL.info("Received Web-Command for Console: " + line); 47 | if (!Commands.execute(line)) 48 | Server.submitCommand(line); 49 | } 50 | } 51 | } catch (Exception e) { 52 | if (!Main.CON.isUserActive.get()) return; // Ignore after logout 53 | throw e; 54 | } 55 | }); 56 | AL.debug(this.getClass(), "Connection '" + this.getClass().getSimpleName() + "' connected."); 57 | return true; 58 | } else { 59 | AL.debug(this.getClass(), "Connection '" + this.getClass().getSimpleName() + "' not connected, because not enabled in the web-config."); 60 | return false; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/network/online/connections/ConSendPrivateDetails.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.network.online.connections; 10 | 11 | import com.osiris.autoplug.client.Main; 12 | import com.osiris.autoplug.client.configs.WebConfig; 13 | import com.osiris.autoplug.client.network.online.DefaultConnection; 14 | import com.osiris.autoplug.client.utils.io.UFDataOut; 15 | import com.osiris.jlib.logger.AL; 16 | import oshi.SystemInfo; 17 | import oshi.hardware.CentralProcessor; 18 | import oshi.hardware.GlobalMemory; 19 | import oshi.hardware.HardwareAbstractionLayer; 20 | 21 | 22 | /** 23 | * Sends private details to AutoPlug-Web like 24 | * CPU speeds and memory used/total. Should only 25 | * be active when user is logged in. 26 | */ 27 | public class ConSendPrivateDetails extends DefaultConnection { 28 | public float cpuSpeed; 29 | public float cpuMaxSpeed; 30 | /** 31 | * Value between 0 and 100%. 32 | */ 33 | public byte cpuUsage; 34 | public float memAvailable; 35 | public float memUsed; 36 | public float memTotal; 37 | private Thread thread; 38 | 39 | public ConSendPrivateDetails() { 40 | super((byte) 6); // Each connection has its own auth_id. 41 | } 42 | 43 | @Override 44 | public boolean open() throws Exception { 45 | if (new WebConfig().send_private_details.asBoolean()) { 46 | super.open(); 47 | getSocket().setSoTimeout(0); 48 | UFDataOut dos = new UFDataOut(getOut()); 49 | float oneGigaByteInBytes = 1073741824.0f; 50 | float oneGigaHertzInHertz = 1000000000.0f; 51 | SystemInfo si = new SystemInfo(); 52 | setAndStartAsync(() -> { 53 | try { 54 | while (true) { 55 | // Hardware info: 56 | HardwareAbstractionLayer hal = si.getHardware(); 57 | CentralProcessor cpu = hal.getProcessor(); 58 | GlobalMemory memory = hal.getMemory(); 59 | // Calc average frequency in mhz 60 | long currentFrq = 0; 61 | int i = 0; 62 | if (cpu != null) { 63 | for (long frq : 64 | cpu.getCurrentFreq()) { 65 | currentFrq = currentFrq + frq; 66 | i++; 67 | } 68 | currentFrq = currentFrq / i; 69 | } 70 | 71 | if (cpu != null) { 72 | dos.writeFloat((cpuSpeed = (currentFrq / oneGigaHertzInHertz))); 73 | cpuMaxSpeed = (cpu.getMaxFreq() / oneGigaHertzInHertz); 74 | dos.writeFloat(Math.max(cpuMaxSpeed, cpuSpeed)); // Support for overclocking 75 | dos.writeByte((cpuUsage = (byte) Math.round(cpu.getSystemCpuLoad(1000) * 100))); 76 | } else { 77 | dos.writeFloat(0); 78 | dos.writeFloat(0); 79 | dos.writeByte((byte) 0); 80 | } 81 | 82 | 83 | if (memory != null) { 84 | dos.writeFloat((memAvailable = (memory.getAvailable() / oneGigaByteInBytes))); 85 | dos.writeFloat((memUsed = ((memory.getTotal() - memory.getAvailable()) / oneGigaByteInBytes))); 86 | dos.writeFloat((memTotal = (memory.getTotal() / oneGigaByteInBytes))); 87 | } else { 88 | dos.writeFloat(0); 89 | dos.writeFloat(0); 90 | dos.writeFloat(0); 91 | } 92 | 93 | Thread.sleep(5000); 94 | } 95 | } catch (Exception e) { 96 | if (!Main.CON.isUserActive.get()) return; // Ignore after logout 97 | throw e; 98 | } 99 | }); 100 | AL.debug(this.getClass(), "Connection '" + this.getClass().getSimpleName() + "' connected."); 101 | return true; 102 | } else { 103 | AL.debug(this.getClass(), "Connection '" + this.getClass().getSimpleName() + "' not connected, because not enabled in the web-config."); 104 | return false; 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/network/online/connections/ConSystemConsoleReceive.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.network.online.connections; 10 | 11 | import com.osiris.autoplug.client.Main; 12 | import com.osiris.autoplug.client.configs.WebConfig; 13 | import com.osiris.autoplug.client.network.online.DefaultConnection; 14 | import com.osiris.jlib.logger.AL; 15 | 16 | import java.io.BufferedReader; 17 | import java.io.InputStream; 18 | import java.io.InputStreamReader; 19 | import java.net.Socket; 20 | 21 | /** 22 | * The user can send commands through the online console.
23 | * For that we got this connection, which listens for the user 24 | * input at the online console and executes it. 25 | */ 26 | public class ConSystemConsoleReceive extends DefaultConnection { 27 | public ConSystemConsoleReceive() { 28 | super((byte) 8); 29 | } 30 | 31 | @Override 32 | public boolean open() throws Exception { 33 | if (new WebConfig().online_system_console.asBoolean()) { 34 | super.open(); 35 | setAndStartAsync(() -> { 36 | try { 37 | Socket socket = getSocket(); 38 | socket.setSoTimeout(0); 39 | InputStream in = getSocket().getInputStream(); 40 | try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { 41 | String line; 42 | while (!socket.isClosed() && (line = reader.readLine()) != null) { 43 | AL.info("Received Web-Command for S-Console: " + line); 44 | if (ConSystemConsoleSend.asyncTerminal == null) { 45 | AL.warn("Failed to execute '" + line + "' because there is no system terminal active."); 46 | continue; 47 | } 48 | ConSystemConsoleSend.asyncTerminal.sendCommands(line); 49 | } 50 | } 51 | } catch (Exception e) { 52 | if (!Main.CON.isUserActive.get()) return; // Ignore after logout 53 | throw e; 54 | } 55 | 56 | }); 57 | AL.debug(this.getClass(), "Connection '" + this.getClass().getSimpleName() + "' connected."); 58 | return true; 59 | } else { 60 | AL.debug(this.getClass(), "Connection '" + this.getClass().getSimpleName() + "' not connected, because not enabled in the web-config."); 61 | return false; 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/network/online/connections/ConSystemConsoleSend.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.network.online.connections; 10 | 11 | import com.osiris.autoplug.client.Main; 12 | import com.osiris.autoplug.client.configs.WebConfig; 13 | import com.osiris.autoplug.client.network.online.DefaultConnection; 14 | import com.osiris.autoplug.client.utils.GD; 15 | import com.osiris.autoplug.client.utils.terminal.AsyncTerminal; 16 | import com.osiris.jlib.logger.AL; 17 | import org.jetbrains.annotations.NotNull; 18 | import org.jetbrains.annotations.Nullable; 19 | 20 | import java.io.BufferedWriter; 21 | import java.io.FileWriter; 22 | import java.io.IOException; 23 | import java.io.OutputStreamWriter; 24 | import java.util.Date; 25 | 26 | 27 | /** 28 | * Read the InputStreams of AutoPlug and the Minecraft server and 29 | * send it to the AutoPlug server when the user is online. 30 | * Note that 31 | */ 32 | public class ConSystemConsoleSend extends DefaultConnection { 33 | public static AsyncTerminal asyncTerminal; 34 | public static BufferedWriter asyncTerminalLogWriter; 35 | 36 | @Nullable 37 | private static BufferedWriter out; 38 | 39 | public ConSystemConsoleSend() { 40 | super((byte) 7); // Each connection has its own auth_id. 41 | } 42 | 43 | public static void send(@NotNull String message) { 44 | try { 45 | asyncTerminalLogWriter.write(message + "\n"); 46 | asyncTerminalLogWriter.flush(); 47 | } catch (Exception e) { 48 | AL.warn("Failed to write to " + GD.SYSTEM_LATEST_LOG, e); 49 | } 50 | try { 51 | if (out != null) { 52 | if (!message.contains(System.lineSeparator())) { 53 | out.write(message + "\n"); 54 | } else { 55 | out.write(message); 56 | } 57 | } 58 | out.flush(); 59 | } catch (Exception e) { // Do not use AL.warn because that would cause an infinite loop 60 | } 61 | } 62 | 63 | @Override 64 | public boolean open() throws Exception { 65 | if (new WebConfig().online_system_console.asBoolean()) { 66 | super.open(); 67 | getSocket().setSoTimeout(0); 68 | out = new BufferedWriter(new OutputStreamWriter(getOut())); 69 | 70 | if (asyncTerminal != null) asyncTerminal.close(); 71 | if (asyncTerminalLogWriter != null) asyncTerminalLogWriter.close(); 72 | if (GD.SYSTEM_LATEST_LOG.exists()) GD.SYSTEM_LATEST_LOG.delete(); 73 | GD.SYSTEM_LATEST_LOG.getParentFile().mkdirs(); 74 | GD.SYSTEM_LATEST_LOG.createNewFile(); 75 | asyncTerminalLogWriter = new BufferedWriter(new FileWriter(GD.SYSTEM_LATEST_LOG)); 76 | send("Connected to AutoPlug-Web at " + new Date()); 77 | send("Current working directory: " + GD.WORKING_DIR); 78 | asyncTerminal = new AsyncTerminal(null, line -> { 79 | try { 80 | send(line); 81 | } catch (Exception e) { 82 | if (!Main.CON.isUserActive.get()) return; // Ignore after logout 83 | AL.warn("Failed to send message to online console!", e); 84 | } 85 | }, errLine -> { 86 | try { 87 | send(errLine); 88 | } catch (Exception e) { 89 | if (!Main.CON.isUserActive.get()) return; // Ignore after logout 90 | AL.warn("Failed to send message to online console!", e); 91 | } 92 | }); 93 | 94 | AL.debug(this.getClass(), "Connection '" + this.getClass().getSimpleName() + "' connected."); 95 | return true; 96 | } else { 97 | AL.debug(this.getClass(), "Connection '" + this.getClass().getSimpleName() + "' not connected, because not enabled in the web-config."); 98 | return false; 99 | } 100 | } 101 | 102 | @Override 103 | public void close() throws IOException { 104 | 105 | try { 106 | if (asyncTerminal != null) asyncTerminal.close(); 107 | if (asyncTerminalLogWriter != null) asyncTerminalLogWriter.close(); 108 | } catch (Exception ignored) { 109 | } 110 | 111 | try { 112 | super.close(); 113 | } catch (Exception e) { 114 | AL.warn("Failed to close connection.", e); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/SSHManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks; 10 | 11 | import com.osiris.autoplug.client.configs.SSHConfig; 12 | import com.osiris.autoplug.client.network.online.connections.SSHServerConsoleReceive; 13 | import com.osiris.autoplug.client.network.online.connections.SSHServerSetup; 14 | import com.osiris.autoplug.client.utils.ConsoleOutputCapturer; 15 | import com.osiris.jlib.logger.AL; 16 | import org.jetbrains.annotations.Nullable; 17 | 18 | import java.io.IOException; 19 | 20 | public class SSHManager { 21 | @Nullable 22 | private static Thread sshThread; 23 | @Nullable 24 | private static Thread consoleCaptureThread; 25 | @Nullable 26 | private static ConsoleOutputCapturer capturer; 27 | 28 | private static void createSSHThread() { 29 | sshThread = new Thread(() -> { 30 | try { 31 | SSHServerSetup.start(); 32 | } catch (IOException e) { 33 | AL.warn("IOException occurred while starting SSH server", e); 34 | } catch (Exception e) { 35 | AL.warn("Failed to start SSH server", e); 36 | } 37 | }); 38 | } 39 | 40 | private static void createConsoleCaptureThread() { 41 | consoleCaptureThread = new Thread(() -> { 42 | capturer.start(); 43 | while (!Thread.currentThread().isInterrupted()) { 44 | try { 45 | String newOutput = capturer.getNewOutput(); 46 | if (!newOutput.isEmpty()) { 47 | SSHServerConsoleReceive.broadcastToAll(newOutput); 48 | } 49 | Thread.sleep(500); 50 | } catch (InterruptedException e) { 51 | Thread.currentThread().interrupt(); 52 | } 53 | } 54 | }); 55 | } 56 | 57 | public static synchronized boolean start(boolean force) { 58 | if (isRunning()) { 59 | AL.info("SSH Server is already running!"); 60 | return true; 61 | } 62 | 63 | SSHConfig sshConfig; 64 | try { 65 | sshConfig = new SSHConfig(); 66 | capturer = new ConsoleOutputCapturer(); 67 | } catch (Exception e) { 68 | AL.warn("Failed to initialize components", e); 69 | return false; 70 | } 71 | 72 | try { 73 | if (sshConfig.enabled.asBoolean() || force) { 74 | createSSHThread(); 75 | createConsoleCaptureThread(); 76 | sshThread.start(); 77 | consoleCaptureThread.start(); 78 | return true; 79 | } else { 80 | return false; 81 | } 82 | } catch (Exception e) { 83 | AL.warn("Exception during SSH Server start!", e); 84 | return false; 85 | } 86 | } 87 | 88 | public static boolean stop() { 89 | return stop(false); 90 | } 91 | 92 | public static synchronized boolean stop(boolean printInfo) { 93 | if (!isRunning()) { 94 | if(printInfo) AL.info("SSH Server is not running!"); 95 | return true; 96 | } 97 | try { 98 | capturer.stop(); 99 | SSHServerSetup.stop(); 100 | sshThread.join(); 101 | consoleCaptureThread.interrupt(); 102 | consoleCaptureThread.join(); 103 | return true; 104 | } catch (InterruptedException e) { 105 | Thread.currentThread().interrupt(); 106 | AL.warn("Thread interrupted while stopping SSH Server!", e); 107 | } catch (Exception e) { 108 | AL.warn("Failed to stop SSH Server!", e); 109 | } 110 | return false; 111 | } 112 | 113 | public static boolean isRunning() { 114 | return SSHServerSetup.isRunning(); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/SerialBThreadPrinter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks; 10 | 11 | import com.osiris.betterthread.BThreadManager; 12 | import com.osiris.betterthread.BThreadPrinter; 13 | import com.osiris.betterthread.exceptions.JLineLinkException; 14 | import com.osiris.betterthread.modules.BThreadPrinterModule; 15 | import com.osiris.jlib.logger.AL; 16 | import org.jline.utils.AttributedString; 17 | 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | 21 | public class SerialBThreadPrinter extends BThreadPrinter { 22 | 23 | public SerialBThreadPrinter(BThreadManager manager) throws JLineLinkException { 24 | super(manager, null, 5000, false); 25 | hideRegularOutput = false; 26 | printMissedRegularOutput = false; 27 | } 28 | 29 | @Override 30 | public boolean printAll() { 31 | List linesToPrint = new ArrayList<>(); // Fill this list with threads details and update the console after this 32 | manager.getAll().forEach(thread -> { // Build a line for each thread. 33 | StringBuilder builder = new StringBuilder(); 34 | if (thread.printerModules == null || thread.printerModules.isEmpty()) 35 | thread.printerModules = defaultPrinterModules; 36 | for (BThreadPrinterModule m : thread.printerModules) { 37 | m.append(manager, null, thread, builder); 38 | } 39 | linesToPrint.add(AttributedString.fromAnsi(builder.toString())); 40 | }); 41 | 42 | if (manager.getAll().isEmpty()) { 43 | linesToPrint.add(AttributedString.fromAnsi("No threads! Waiting...")); 44 | } else { 45 | if (manager.isFinished()) { 46 | // Print one last time 47 | for (AttributedString printString : linesToPrint) { 48 | AL.info(printString.toString()); 49 | } 50 | AL.info(""); 51 | return false; 52 | } 53 | } 54 | 55 | for (AttributedString printString : linesToPrint) { 56 | AL.info(printString.toString()); 57 | } 58 | AL.info(""); 59 | return true; 60 | } 61 | 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/TaskGeneral.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks; 10 | 11 | import com.osiris.autoplug.client.configs.GeneralConfig; 12 | import com.osiris.autoplug.client.managers.FileManager; 13 | import com.osiris.autoplug.client.utils.GD; 14 | import com.osiris.betterthread.BThread; 15 | import com.osiris.betterthread.BThreadManager; 16 | import com.osiris.betterthread.BWarning; 17 | 18 | import java.io.File; 19 | import java.io.FileWriter; 20 | 21 | public class TaskGeneral extends BThread { 22 | private GeneralConfig generalConfig; 23 | private int countDeletedFiles = 0; 24 | 25 | public TaskGeneral(String name, BThreadManager manager) { 26 | super(name, manager); 27 | } 28 | 29 | 30 | @Override 31 | public void runAtStart() throws Exception { 32 | super.runAtStart(); 33 | generalConfig = new GeneralConfig(); 34 | if (generalConfig.server_auto_eula.asBoolean()) { 35 | setStatus("Searching for eula.txt file..."); 36 | File eula = new File(GD.WORKING_DIR + "/eula.txt"); 37 | if (!eula.exists()) eula.createNewFile(); 38 | try (FileWriter fw = new FileWriter(eula)) { 39 | fw.write("eula=true\n"); 40 | fw.flush(); 41 | } 42 | setStatus("File 'eula.txt' created successfully."); 43 | } 44 | try { 45 | if (!generalConfig.directory_cleaner.asBoolean()) { 46 | setStatus("Skipped directory-cleaner, because disabled."); 47 | } else { 48 | setStatus("Cleaning selected directories..."); 49 | for (String s : 50 | generalConfig.directory_cleaner_files.asStringList()) { 51 | boolean cleanSubDirs = s.startsWith("true "); 52 | if (cleanSubDirs) { 53 | s = s.replaceFirst("true ", ""); 54 | } 55 | File dir = null; 56 | if (s.startsWith("./")) 57 | dir = FileManager.convertRelativeToAbsolutePath(s); 58 | else 59 | new File(s); 60 | if (!dir.isDirectory()) { 61 | addWarning("Provided path '" + s + "' in " + generalConfig.directory_cleaner_files.getKeys() + " is a file and not a directory!"); 62 | continue; 63 | } 64 | long minLastModifiedTime = System.currentTimeMillis() - (generalConfig.directory_cleaner_max_days.asInt() * 86400000L); // * 86400000 (1day in ms) to convert days to milliseconds 65 | cleanDirectory(dir, cleanSubDirs, minLastModifiedTime); 66 | if (countDeletedFiles > 0) { 67 | addInfo("Directory cleaner removed " + countDeletedFiles + " files, from directory " + s); 68 | countDeletedFiles = 0; 69 | } 70 | } 71 | } 72 | } catch (Exception e) { 73 | addWarning(new BWarning(this, e)); 74 | } 75 | finish("Finished."); 76 | } 77 | 78 | private void cleanDirectory(File dir, boolean cleanSubDirs, long minLastModifiedTime) { 79 | if (cleanSubDirs) { 80 | for (File f : 81 | dir.listFiles()) { 82 | if (f.isDirectory()) { 83 | cleanDirectory(f, cleanSubDirs, minLastModifiedTime); 84 | if (f.listFiles() == null || f.listFiles().length == 0) { 85 | f.delete(); 86 | countDeletedFiles++; 87 | } 88 | } else { 89 | if (f.lastModified() < minLastModifiedTime) { 90 | f.delete(); 91 | countDeletedFiles++; 92 | } 93 | } 94 | } 95 | } else { 96 | for (File f : 97 | dir.listFiles()) { 98 | if (!f.isDirectory()) { 99 | if (f.lastModified() < minLastModifiedTime) { 100 | f.delete(); 101 | countDeletedFiles++; 102 | } 103 | } 104 | } 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/backup/Upload.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.backup; 10 | 11 | import com.jcraft.jsch.*; 12 | import org.apache.commons.net.PrintCommandListener; 13 | import org.apache.commons.net.ftp.FTP; 14 | import org.apache.commons.net.ftp.FTPReply; 15 | import org.apache.commons.net.ftp.FTPSClient; 16 | 17 | import java.io.File; 18 | import java.io.FileInputStream; 19 | import java.io.IOException; 20 | import java.io.PrintWriter; 21 | 22 | /** 23 | * Handles file uploads via SFTP and FTPS. 24 | * 25 | * Usage: 26 | * - To upload via SFTP, call the {@link #sftp(String)} method with the RSA key path. 27 | * - To upload via FTPS, call the {@link #ftps()} method. 28 | * 29 | * Ensure that the host, port, user, password, path, and zipFile are properly set via the constructor. 30 | * 31 | * Note: Password handling in this code is basic and should be improved for production use. 32 | * 33 | * Author: kastenklicker 34 | */ 35 | public class Upload { 36 | private final String host, user, password, path; 37 | private final int port; 38 | private final File zipFile; 39 | 40 | public Upload(String host, int port, String user, String password, String path, File zipFile) { 41 | this.host = host; 42 | this.port = port; 43 | this.user = user; 44 | this.password = password; 45 | if (!path.endsWith("/")) path += "/"; 46 | this.path = path; 47 | this.zipFile = zipFile; 48 | } 49 | 50 | public void sftp(String rsaKeyPath) throws JSchException, SftpException, IOException { 51 | JSch jsch = new JSch(); 52 | 53 | // Load the private key from the file 54 | jsch.addIdentity(rsaKeyPath); 55 | 56 | // HostKey verification 57 | // This is a basic implementation. Improve as needed. 58 | //jsch.setKnownHosts("/path/to/known_hosts"); 59 | 60 | // Connect 61 | Session session = jsch.getSession(user, host, port); 62 | session.setConfig("StrictHostKeyChecking", "no"); 63 | session.setPassword(password); 64 | session.connect(); 65 | ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); 66 | channel.connect(); 67 | 68 | try { 69 | // Upload 70 | channel.put(zipFile.getPath(), path + zipFile.getName()); 71 | } catch (SftpException e) { 72 | throw e; 73 | } finally { 74 | // Disconnect 75 | channel.disconnect(); 76 | session.disconnect(); 77 | } 78 | } 79 | 80 | public void ftps() throws IOException { 81 | FTPSClient ftps = new FTPSClient(); 82 | ftps.setConnectTimeout(5000); 83 | 84 | // Connect 85 | ftps.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); 86 | ftps.connect(host, port); 87 | ftps.execPBSZ(0); 88 | ftps.execPROT("P"); 89 | int reply = ftps.getReplyCode(); 90 | if (!FTPReply.isPositiveCompletion(reply)) { 91 | ftps.disconnect(); 92 | throw new IOException("Exception in connecting to FTPS Server."); 93 | } 94 | ftps.login(user, password); 95 | ftps.setFileType(FTP.BINARY_FILE_TYPE); 96 | ftps.enterLocalPassiveMode(); 97 | 98 | try (FileInputStream zipFileStream = new FileInputStream(zipFile)) { 99 | // Upload 100 | if (!ftps.storeFile(path + zipFile.getName(), zipFileStream)) { 101 | throw new IOException("Exception in uploading to FTPS Server."); 102 | } 103 | 104 | } catch (IOException e) { 105 | throw e; 106 | } finally { 107 | ftps.logout(); 108 | ftps.disconnect(); 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/scheduler/CustomRestartJob.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.scheduler; 10 | 11 | import com.osiris.autoplug.client.Server; 12 | import com.osiris.autoplug.client.configs.RestarterConfig; 13 | import com.osiris.dyml.YamlSection; 14 | import com.osiris.jlib.logger.AL; 15 | import org.jetbrains.annotations.NotNull; 16 | import org.quartz.Job; 17 | import org.quartz.JobExecutionContext; 18 | import org.quartz.JobExecutionException; 19 | 20 | import java.util.ArrayList; 21 | import java.util.Arrays; 22 | import java.util.Collections; 23 | import java.util.List; 24 | 25 | public class CustomRestartJob implements Job { 26 | 27 | public void execute(JobExecutionContext context) throws JobExecutionException { 28 | try { 29 | if (!Server.isRunning()) 30 | throw new Exception("Server is not running. Restart not possible."); 31 | 32 | // Before restarting execute commands 33 | RestarterConfig config = new RestarterConfig(); 34 | List modules = config.c_restarter_commands.getChildSections(); 35 | 36 | // Sort the stuff 37 | List keysAsIntsList = new ArrayList<>(); 38 | for (YamlSection m : 39 | modules) { 40 | keysAsIntsList.add(Integer.parseInt(m.getLastKey())); 41 | } 42 | 43 | // Normally sorts from lowest, to highest value. 44 | // But we want it the other way: 45 | Integer[] keysAsIntsArray = keysAsIntsList.toArray(new Integer[0]); 46 | Arrays.sort(keysAsIntsArray, Collections.reverseOrder()); 47 | 48 | AL.info("Executing scheduled restart in " + keysAsIntsArray[0] + "sec(s)..."); 49 | for (int i = keysAsIntsArray[0]; i >= 0; i--) { // The first int, has the highest value, bc of the sorting 50 | for (YamlSection m : 51 | modules) { 52 | if (Integer.parseInt(m.getLastKey()) == i) { 53 | AL.debug(this.getClass(), "Executing command(s): " + m.getValues().toString()); 54 | for (String command : m.asStringList()) { 55 | try { 56 | if (command == null) 57 | AL.debug(this.getClass(), "Command for second '" + i + "' is null."); 58 | else 59 | Server.submitCommand(command); 60 | } catch (Exception e) { 61 | AL.warn(e, "Error executing '" + command + "' command!"); 62 | } 63 | } 64 | } 65 | } 66 | Thread.sleep(1000); 67 | } 68 | 69 | //Restart the server 70 | Server.restart(); 71 | 72 | } catch (@NotNull Exception e) { 73 | AL.warn("Error while executing restart!", e); 74 | } 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/scheduler/RestartJob.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.scheduler; 10 | 11 | import com.osiris.autoplug.client.Server; 12 | import com.osiris.autoplug.client.configs.RestarterConfig; 13 | import com.osiris.dyml.YamlSection; 14 | import com.osiris.jlib.logger.AL; 15 | import org.jetbrains.annotations.NotNull; 16 | import org.quartz.Job; 17 | import org.quartz.JobExecutionContext; 18 | import org.quartz.JobExecutionException; 19 | 20 | import java.util.ArrayList; 21 | import java.util.Arrays; 22 | import java.util.Collections; 23 | import java.util.List; 24 | 25 | public class RestartJob implements Job { 26 | 27 | public void execute(JobExecutionContext context) throws JobExecutionException { 28 | try { 29 | 30 | if (!Server.isRunning()) 31 | throw new Exception("Server is not running. Restart not possible."); 32 | 33 | // Before restarting execute commands 34 | RestarterConfig config = new RestarterConfig(); 35 | List modules = config.restarter_commands.getChildSections(); 36 | 37 | // Sort the stuff 38 | List keysAsIntsList = new ArrayList<>(); 39 | for (YamlSection m : 40 | modules) { 41 | keysAsIntsList.add(Integer.parseInt(m.getLastKey())); 42 | } 43 | 44 | // Normally sorts from lowest, to highest value. 45 | // But we want it the other way: 46 | Integer[] keysAsIntsArray = keysAsIntsList.toArray(new Integer[0]); 47 | Arrays.sort(keysAsIntsArray, Collections.reverseOrder()); 48 | 49 | AL.info("Executing scheduled restart in " + keysAsIntsArray[0] + "sec(s)..."); 50 | for (int i = keysAsIntsArray[0]; i >= 0; i--) { // The first int, has the highest value, bc of the sorting 51 | for (YamlSection m : 52 | modules) { 53 | if (Integer.parseInt(m.getLastKey()) == i) { 54 | for (String command : m.asStringList()) { 55 | try { 56 | if (command == null) 57 | AL.debug(this.getClass(), "Command for second '" + i + "' is null."); 58 | else 59 | Server.submitCommand(command); 60 | } catch (Exception e) { 61 | AL.warn(e, "Error executing '" + command + "' command!"); 62 | } 63 | } 64 | } 65 | } 66 | Thread.sleep(1000); 67 | } 68 | 69 | //Restart the server 70 | Server.restart(); 71 | 72 | } catch (@NotNull Exception e) { 73 | AL.warn("Error while executing restart!", e); 74 | } 75 | 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/scheduler/TaskCustomRestarter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.scheduler; 10 | 11 | import com.osiris.autoplug.client.configs.RestarterConfig; 12 | import com.osiris.betterthread.BThread; 13 | import com.osiris.betterthread.BThreadManager; 14 | import com.osiris.jlib.logger.AL; 15 | import org.jetbrains.annotations.NotNull; 16 | import org.quartz.CronTrigger; 17 | import org.quartz.JobDetail; 18 | import org.quartz.Scheduler; 19 | import org.quartz.impl.StdSchedulerFactory; 20 | 21 | import java.util.Collections; 22 | 23 | import static org.quartz.CronScheduleBuilder.cronSchedule; 24 | import static org.quartz.JobBuilder.newJob; 25 | import static org.quartz.TriggerBuilder.newTrigger; 26 | 27 | public class TaskCustomRestarter extends BThread { 28 | 29 | private static Scheduler scheduler; 30 | 31 | public TaskCustomRestarter(String name, BThreadManager manager) { 32 | super(name, manager); 33 | } 34 | 35 | 36 | @Override 37 | public void runAtStart() throws Exception { 38 | super.runAtStart(); 39 | createAllJobs(); 40 | } 41 | 42 | //Is created in config if enabled 43 | private void createAllJobs() throws Exception { 44 | 45 | RestarterConfig config = new RestarterConfig(); 46 | 47 | if (config.c_restarter_enabled.asBoolean()) { 48 | 49 | scheduler = StdSchedulerFactory.getDefaultScheduler(); 50 | 51 | if (scheduler.isStarted()) { 52 | setStatus("Scheduler already running. Put into standby."); 53 | scheduler.standby(); 54 | } 55 | setNow(50); 56 | Thread.sleep(1000); 57 | 58 | String cron = config.c_restarter_cron.asString(); 59 | createOrReplaceJob("customRestartJob", "customRestartTrigger", cron); 60 | setStatus("Restart at cron: " + cron); 61 | 62 | scheduler.start(); // Create all jobs before starting the scheduler 63 | finish(true); 64 | } else { 65 | skip(); 66 | } 67 | 68 | } 69 | 70 | //Creates jobs and links them to the scheduler 71 | private void createOrReplaceJob(String jobName, String triggerName, @NotNull String cron) throws Exception { 72 | 73 | AL.debug(this.getClass(), "Creating job with name: " + jobName + " trigger:" + triggerName + " cron:" + cron); 74 | 75 | //Specify scheduler details 76 | JobDetail job = newJob(CustomRestartJob.class) 77 | .withIdentity(jobName, "restartGroup") 78 | .build(); 79 | 80 | CronTrigger trigger = newTrigger() 81 | .withIdentity(triggerName, "restartGroup") 82 | .withSchedule(cronSchedule(cron)) 83 | .build(); 84 | 85 | //Add details to the scheduler 86 | scheduler.scheduleJob(job, Collections.singleton(trigger), true); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/scheduler/TaskDailyRestarter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.scheduler; 10 | 11 | import com.osiris.autoplug.client.configs.RestarterConfig; 12 | import com.osiris.betterthread.BThread; 13 | import com.osiris.betterthread.BThreadManager; 14 | import com.osiris.betterthread.BWarning; 15 | import com.osiris.jlib.logger.AL; 16 | import org.quartz.CronTrigger; 17 | import org.quartz.JobDetail; 18 | import org.quartz.Scheduler; 19 | import org.quartz.SchedulerException; 20 | import org.quartz.impl.StdSchedulerFactory; 21 | 22 | import java.util.Collections; 23 | 24 | import static org.quartz.CronScheduleBuilder.cronSchedule; 25 | import static org.quartz.JobBuilder.newJob; 26 | import static org.quartz.TriggerBuilder.newTrigger; 27 | 28 | public class TaskDailyRestarter extends BThread { 29 | 30 | private static Scheduler scheduler; 31 | 32 | public TaskDailyRestarter(String name, BThreadManager manager) { 33 | super(name, manager); 34 | } 35 | 36 | 37 | @Override 38 | public void runAtStart() throws Exception { 39 | super.runAtStart(); 40 | createAllJobs(); 41 | } 42 | 43 | //Is created in config if enabled 44 | private void createAllJobs() throws Exception { 45 | 46 | RestarterConfig config = new RestarterConfig(); 47 | 48 | if (config.restarter_enabled.asBoolean()) { 49 | 50 | scheduler = StdSchedulerFactory.getDefaultScheduler(); 51 | 52 | if (scheduler.isStarted()) { 53 | setStatus("Scheduler already running. Put into standby."); 54 | scheduler.standby(); 55 | } 56 | sleep(1000); 57 | 58 | int size = config.restarter_times_hours.size(); 59 | setMax(size); 60 | 61 | String jobName; 62 | String triggerName; 63 | String min; 64 | String h; 65 | 66 | StringBuilder stringJobs = new StringBuilder("Restarts at: "); 67 | 68 | for (int i = 0; i < size; i++) { 69 | 70 | //Get values 71 | jobName = "restartJob" + i; 72 | triggerName = "restartTrigger" + i; 73 | 74 | min = String.valueOf(config.restarter_times_minutes.get(i)); 75 | h = String.valueOf(config.restarter_times_hours.get(i)); 76 | 77 | //Create job 78 | createOrReplaceJob(jobName, triggerName, min, h); 79 | setStatus("Created job: " + jobName + " at " + h + ":" + min); 80 | stringJobs.append("[" + h + ":" + min + "]"); 81 | step(); 82 | } 83 | 84 | scheduler.start(); // Create all jobs before starting the scheduler 85 | finish(stringJobs.toString(), true); 86 | } else { 87 | skip(); 88 | } 89 | } 90 | 91 | //Creates jobs and links them to the scheduler 92 | private void createOrReplaceJob(String jobName, String triggerName, String min, String h) { 93 | 94 | try { 95 | AL.debug(this.getClass(), "Creating job with name: " + jobName + " trigger:" + triggerName + " min:" + min + " hour:" + h); 96 | 97 | //Specify scheduler details 98 | JobDetail job = newJob(RestartJob.class) 99 | .withIdentity(jobName, "restartGroup") 100 | .build(); 101 | 102 | CronTrigger trigger = newTrigger() 103 | .withIdentity(triggerName, "restartGroup") 104 | .withSchedule(cronSchedule("0 " + min + " " + h + " * * ? *")) 105 | .build(); 106 | 107 | //Add details to the scheduler 108 | scheduler.scheduleJob(job, Collections.singleton(trigger), true); 109 | 110 | } catch (SchedulerException e) { 111 | setSuccess(false); 112 | getWarnings().add(new BWarning(this, e)); 113 | } 114 | 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/updater/mods/CurseForgeJson.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater.mods; 10 | 11 | import com.google.gson.JsonArray; 12 | import com.google.gson.JsonElement; 13 | import com.google.gson.JsonObject; 14 | import com.google.gson.JsonParser; 15 | import com.osiris.autoplug.client.utils.GD; 16 | import com.osiris.jlib.json.exceptions.HttpErrorException; 17 | import com.osiris.jlib.json.exceptions.WrongJsonTypeException; 18 | 19 | import java.io.IOException; 20 | import java.io.InputStreamReader; 21 | import java.net.HttpURLConnection; 22 | import java.net.URL; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | 26 | public class CurseForgeJson { 27 | public final String key = "$2a$10$7exv4HBW5Glx9ELBT3i3seB5jXto3m1baXQXwtA/kEMGv3TYfBUWK"; 28 | 29 | 30 | /** 31 | * Returns the json-element. This can be a json-array or a json-object. 32 | * 33 | * @param input_url The url which leads to the json file. 34 | * @return JsonElement 35 | * @throws Exception When status code other than 200. 36 | */ 37 | public JsonElement getJsonElement(String input_url) throws IOException, HttpErrorException { 38 | 39 | HttpURLConnection con = null; 40 | JsonElement element; 41 | try { 42 | con = (HttpURLConnection) new URL(input_url).openConnection(); 43 | con.addRequestProperty("User-Agent", "AutoPlug-Client - Contact: " + GD.OFFICIAL_WEBSITE); 44 | con.addRequestProperty("x-api-key", key); 45 | con.setConnectTimeout(1000); 46 | con.connect(); 47 | 48 | if (con.getResponseCode() == 200) { 49 | try (InputStreamReader inr = new InputStreamReader(con.getInputStream())) { 50 | element = JsonParser.parseReader(inr); 51 | } 52 | } else { 53 | throw new HttpErrorException(con.getResponseCode(), con.getResponseMessage(), "Couldn't get the json file from: " + input_url); 54 | } 55 | } catch (IOException | HttpErrorException e) { 56 | if (con != null) con.disconnect(); 57 | throw e; 58 | } finally { 59 | if (con != null) con.disconnect(); 60 | } 61 | return element; 62 | } 63 | 64 | public JsonArray getJsonArray(String url) throws IOException, HttpErrorException, WrongJsonTypeException { 65 | JsonElement element = getJsonElement(url); 66 | if (element != null && element.isJsonArray()) { 67 | return element.getAsJsonArray(); 68 | } else { 69 | throw new WrongJsonTypeException("Its not a json array! Check it out -> " + url); 70 | } 71 | } 72 | 73 | /** 74 | * Turns a JsonArray with its objects into a list. 75 | * 76 | * @param url The url where to find the json file. 77 | * @return A list with JsonObjects or null if there was a error with the url. 78 | */ 79 | public List getJsonArrayAsList(String url) throws IOException, HttpErrorException, WrongJsonTypeException { 80 | List objectList = new ArrayList<>(); 81 | JsonElement element = getJsonElement(url); 82 | if (element != null && element.isJsonArray()) { 83 | final JsonArray ja = element.getAsJsonArray(); 84 | for (int i = 0; i < ja.size(); i++) { 85 | JsonObject jo = ja.get(i).getAsJsonObject(); 86 | objectList.add(jo); 87 | } 88 | return objectList; 89 | } else { 90 | throw new WrongJsonTypeException("Its not a json array! Check it out -> " + url); 91 | } 92 | } 93 | 94 | /** 95 | * Gets a single JsonObject. 96 | * 97 | * @param url The url where to find the json file. 98 | * @return A JsonObject or null if there was a error with the url. 99 | */ 100 | public JsonObject getJsonObject(String url) throws IOException, HttpErrorException, WrongJsonTypeException { 101 | JsonElement element = getJsonElement(url); 102 | if (element != null && element.isJsonObject()) { 103 | return element.getAsJsonObject(); 104 | } else { 105 | throw new WrongJsonTypeException("Its not a json object! Check it out -> " + url); 106 | } 107 | } 108 | 109 | } 110 | 111 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/updater/mods/InstalledModLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater.mods; 10 | 11 | import com.osiris.jlib.logger.AL; 12 | 13 | import java.io.File; 14 | 15 | public class InstalledModLoader { 16 | public boolean isForge, isFabric, isQuilt; 17 | 18 | public InstalledModLoader() { 19 | try { 20 | for (File f : 21 | new File(System.getProperty("user.dir")).listFiles()) { 22 | if (f.getName().equals(".fabric")) { 23 | isFabric = true; 24 | break; 25 | } 26 | if (f.getName().equals(".quilt")) { 27 | isQuilt = true; 28 | break; 29 | } 30 | } 31 | } catch (Exception e) { 32 | AL.warn("Failed to determine installed Minecraft mod loader, fallback to forge.", e); 33 | isForge = true; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/updater/mods/MinecraftMod.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater.mods; 10 | 11 | public class MinecraftMod { 12 | public String installationPath, modrinthId, curseforgeId, customDownloadURL; 13 | public boolean ignoreContentType; 14 | public String githubRepoName, githubAssetName; 15 | public String jenkinsProjectUrl, jenkinsArtifactName; 16 | public int jenkinsBuildId; 17 | public boolean forceLatest; 18 | public String customCheckURL; 19 | public boolean forceUpdate; 20 | private String name, author, version; 21 | 22 | public MinecraftMod(String installationPath, String name, String version, 23 | String author, String modrinthId, String curseforgeId, 24 | String customDownloadURL) { 25 | this.installationPath = installationPath; 26 | setName(name); 27 | setAuthor(author); 28 | setVersion(version); 29 | this.modrinthId = modrinthId; 30 | this.curseforgeId = curseforgeId; 31 | this.customDownloadURL = customDownloadURL; 32 | } 33 | 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public void setName(String name) { 39 | if (name != null) 40 | this.name = name.replaceAll(":", ""); // Before passing over remove : numbers and dots 41 | } 42 | 43 | public String getVersion() { 44 | return version; 45 | } 46 | 47 | public void setVersion(String version) { 48 | if (version != null) 49 | this.version = version.replaceAll("[^0-9.]", ""); // Before passing over remove everything except numbers and dots 50 | } 51 | 52 | public String getAuthor() { 53 | return author; 54 | } 55 | 56 | public void setAuthor(String author) { 57 | if (author != null) 58 | this.author = author.replaceAll("[^\\w]", ""); // Before passing over remove everything except chars and numbers 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/updater/mods/ModrinthAPI.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater.mods; 10 | 11 | import com.google.gson.JsonObject; 12 | import com.osiris.autoplug.client.tasks.updater.plugins.MinecraftPlugin; 13 | import com.osiris.autoplug.client.tasks.updater.search.SearchResult; 14 | import com.osiris.autoplug.client.utils.UtilsURL; 15 | import com.osiris.jlib.json.Json; 16 | import com.osiris.jlib.logger.AL; 17 | 18 | import java.io.File; 19 | import java.time.Instant; 20 | 21 | 22 | public class ModrinthAPI { 23 | private final String baseUrl = "https://api.modrinth.com/v2"; 24 | 25 | private boolean isInt(String s) { 26 | try { 27 | Integer.parseInt(s); 28 | return true; 29 | } catch (Exception e) { 30 | return false; 31 | } 32 | } 33 | 34 | 35 | /** 36 | * Requires a modrithId (chars or number), or curseforgeId (no number, but chars). 37 | * If the id contains chars its usually the mods slugs. 38 | */ 39 | public SearchResult searchUpdateMod(InstalledModLoader modLoader, MinecraftMod mod, String mcVersion) { 40 | if (mod.modrinthId == null && !isInt(mod.curseforgeId)) mod.modrinthId = mod.curseforgeId; // Slug 41 | SearchResult res = searchUpdate((modLoader.isFabric || modLoader.isQuilt ? "fabric" : "forge"),mod.modrinthId,mcVersion, mod.installationPath, mod.forceLatest); 42 | res.mod = mod; 43 | return res; 44 | } 45 | public SearchResult searchUpdatePlugin(MinecraftPlugin plugin, String mcVersion) { //TODO: probably don't hardcode spigot and papermc 46 | return searchUpdate("spigot\",\"paper", plugin.getModrinthId(), mcVersion, plugin.getInstallationPath(), false); 47 | } 48 | private SearchResult searchUpdate(String loader, String id, String mcVersion, String installPath, boolean forceLatest) { 49 | 50 | String url = baseUrl + "/project/" + id + "/version?loaders=[\"" + loader + "\"]&game_versions=[\"" + mcVersion + "\"]"; 51 | url = new UtilsURL().clean(url); 52 | Exception exception = null; 53 | String latest = null; 54 | String type = ".jar"; 55 | String downloadUrl = null; 56 | SearchResult.Type resultType = SearchResult.Type.UP_TO_DATE; 57 | try { 58 | if (id == null) 59 | throw new Exception("Modrinth-id is null!"); // Modrinth id can be slug or actual id 60 | 61 | AL.debug(this.getClass(), url); 62 | JsonObject release; 63 | try { 64 | release = Json.getAsJsonArray(url) 65 | .get(0).getAsJsonObject(); 66 | } catch (Exception e) { 67 | if (!isInt(id)) { // Try another url, with slug replaced _ with - 68 | url = baseUrl + "/project/" + id.replace("_", "-") 69 | + "/version?loaders=[\"" + 70 | loader + "\"]" + (forceLatest ? "" : "&game_versions=[\"" + mcVersion + "\"]"); 71 | AL.debug(this.getClass(), url); 72 | release = Json.getAsJsonArray(url) 73 | .get(0).getAsJsonObject(); 74 | } else 75 | throw e; 76 | } 77 | 78 | latest = release.get("version_number").getAsString().replaceAll("[^0-9.]", ""); // Before passing over remove everything except numbers and dots 79 | if (new File(installPath).lastModified() < Instant.parse(release.get("date_published").getAsString()).toEpochMilli()) 80 | resultType = SearchResult.Type.UPDATE_AVAILABLE; 81 | JsonObject releaseDownload = release.getAsJsonArray("files").get(0).getAsJsonObject(); 82 | downloadUrl = releaseDownload.get("url").getAsString(); 83 | try { 84 | String fileName = releaseDownload.get("filename").getAsString(); 85 | type = fileName.substring(fileName.lastIndexOf(".")); 86 | } catch (Exception e) { 87 | } 88 | } catch (Exception e) { 89 | exception = e; 90 | resultType = SearchResult.Type.API_ERROR; 91 | } 92 | SearchResult result = new SearchResult(null, resultType, latest, downloadUrl, type, null, null, false); 93 | result.setException(exception); 94 | return result; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/updater/search/CustomCheckURL.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater.search; 10 | 11 | import com.google.gson.JsonArray; 12 | import com.google.gson.JsonElement; 13 | import com.google.gson.JsonObject; 14 | import com.osiris.autoplug.client.utils.UtilsURL; 15 | import com.osiris.jlib.json.Json; 16 | import com.osiris.jlib.search.Version; 17 | 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | import java.util.Map; 21 | import java.util.function.BiConsumer; 22 | 23 | 24 | public class CustomCheckURL { 25 | 26 | public CustomCheckURL(){} 27 | 28 | public SearchResult doCustomCheck(String url, String currentVersion) { 29 | url = new UtilsURL().clean(url); 30 | Exception exception = null; 31 | String latest = null; 32 | String type = ".jar"; 33 | String downloadUrl = null; 34 | SearchResult.Type code = SearchResult.Type.UP_TO_DATE; 35 | try { 36 | JsonElement response = Json.get(url); 37 | List latestVersions = new ArrayList<>(); 38 | List downloadUrls = new ArrayList<>(); 39 | traverseJson("", response, (key, value) -> { 40 | String s1 = getLatestVersionIfValid(key, value); 41 | if (!s1.isEmpty()) latestVersions.add(s1); 42 | 43 | String s2 = getDownloadUrlIfValid(key, value); 44 | if (!s2.isEmpty()) downloadUrls.add(s2); 45 | }); 46 | 47 | if (!latestVersions.isEmpty()) latest = latestVersions.get(0); 48 | if (!downloadUrls.isEmpty()) downloadUrl = downloadUrls.get(0); 49 | 50 | if(latest == null) latest = ""; 51 | if(Version.isFirstBigger(latest, currentVersion)) code = SearchResult.Type.UPDATE_AVAILABLE; 52 | 53 | } catch (Exception e) { 54 | exception = e; 55 | code = SearchResult.Type.API_ERROR; 56 | } 57 | 58 | if (downloadUrl == null && url == null) 59 | code = SearchResult.Type.API_ERROR; 60 | SearchResult result = new SearchResult(null, code, latest, downloadUrl, type, null, null, false); 61 | result.setException(exception); 62 | return result; 63 | } 64 | 65 | /** 66 | * Returns empty string if not valid. 67 | */ 68 | private String getLatestVersionIfValid(String key, String value) { 69 | if (key.equals("version_number") || key.equals("version")) 70 | return value.replaceAll("[^0-9.]", ""); 71 | else return ""; 72 | } 73 | 74 | /** 75 | * Returns empty string if not valid. 76 | */ 77 | private String getDownloadUrlIfValid(String key, String value) { 78 | if (key.equals("download_url") || key.equals("download") || key.equals("file") || key.equals("download_file")) 79 | return value; 80 | else return ""; 81 | } 82 | 83 | public static void traverseJson(String key, JsonElement element, BiConsumer code) { 84 | if (element.isJsonObject()) { 85 | JsonObject obj = element.getAsJsonObject(); 86 | for (Map.Entry entry : obj.entrySet()) { 87 | traverseJson(entry.getKey(), entry.getValue(), code); 88 | } 89 | } else if (element.isJsonArray()) { 90 | JsonArray array = element.getAsJsonArray(); 91 | for (JsonElement item : array) { 92 | traverseJson(key, item, code); 93 | } 94 | } else if (element.isJsonNull()) { 95 | code.accept(key, ""); 96 | } else if (element.isJsonPrimitive()) { 97 | code.accept(key, element.getAsString()); 98 | } else 99 | throw new IllegalArgumentException("Invalid JSON response format"); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/updater/search/GithubSearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater.search; 10 | 11 | import com.google.gson.JsonElement; 12 | import com.google.gson.JsonObject; 13 | import com.osiris.jlib.json.Json; 14 | import com.osiris.jlib.search.Version; 15 | 16 | import java.util.ArrayList; 17 | import java.util.Arrays; 18 | import java.util.List; 19 | 20 | public class GithubSearch { 21 | 22 | public SearchResult search(String githubRepoName, String githubAssetName, String version) { 23 | 24 | 25 | Exception exception = null; 26 | SearchResult.Type resultType = SearchResult.Type.UP_TO_DATE; 27 | String downloadUrl = null; 28 | String downloadType = ".jar"; 29 | String latestVersion = null; 30 | String fileName = null; 31 | try { 32 | JsonObject latestRelease = Json.getAsObject("https://api.github.com/repos/" + githubRepoName + "/releases/latest"); 33 | latestVersion = latestRelease.get("tag_name").getAsString(); 34 | if (latestVersion != null) 35 | latestVersion = latestVersion.replaceAll("[^0-9.]", ""); // Before passing over remove everything except numbers and dots 36 | 37 | if(latestVersion == null) latestVersion = ""; 38 | if (Version.isLatestBigger(version, latestVersion == null ? "0" : latestVersion)) 39 | resultType = SearchResult.Type.UPDATE_AVAILABLE; 40 | 41 | // Contains JsonObjects sorted by their asset-names lengths, from smallest to longest. 42 | // The following does that sorting. 43 | List sortedArtifactObjects = new ArrayList<>(); 44 | for (JsonElement e : 45 | latestRelease.getAsJsonArray("assets")) { 46 | JsonObject obj = e.getAsJsonObject(); 47 | String name = obj.get("name").getAsString(); 48 | if (sortedArtifactObjects.size() == 0) sortedArtifactObjects.add(obj); 49 | else { 50 | int finalIndex = 0; 51 | boolean isSmaller = false; 52 | for (int i = 0; i < sortedArtifactObjects.size(); i++) { 53 | String n = sortedArtifactObjects.get(i).get("name").getAsString(); 54 | if (name.length() < n.length()) { 55 | isSmaller = true; 56 | finalIndex = i; 57 | break; 58 | } 59 | } 60 | if (!isSmaller) sortedArtifactObjects.add(obj); 61 | else sortedArtifactObjects.add(finalIndex, obj); 62 | } 63 | } 64 | 65 | // Find asset-name containing our provided asset-name 66 | for (JsonObject obj : sortedArtifactObjects) { 67 | String n = obj.get("name").getAsString(); 68 | if (n.contains(githubAssetName)) { 69 | fileName = n; 70 | downloadUrl = obj.get("browser_download_url").getAsString(); 71 | if (fileName.contains(".")) 72 | downloadType = fileName.substring(fileName.lastIndexOf(".")); 73 | break; 74 | } 75 | } 76 | 77 | if (downloadUrl == null) { 78 | List names = new ArrayList<>(); 79 | for (JsonObject obj : 80 | sortedArtifactObjects) { 81 | String n = obj.get("name").getAsString(); 82 | names.add(n); 83 | } 84 | throw new Exception("Failed to find an asset-name containing '" + githubAssetName + "' inside of " + Arrays.toString(names.toArray())); 85 | } 86 | } catch (Exception e) { 87 | exception = e; 88 | resultType = SearchResult.Type.API_ERROR; 89 | } 90 | 91 | SearchResult rs = new SearchResult(null, resultType, latestVersion, downloadUrl, downloadType, null, null, false); 92 | rs.setException(exception); 93 | rs.fileName = fileName; 94 | return rs; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/updater/search/bukkit/BukkitSearchById.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater.search.bukkit; 10 | 11 | import com.google.gson.JsonArray; 12 | import com.google.gson.JsonObject; 13 | import com.osiris.autoplug.client.tasks.updater.plugins.MinecraftPlugin; 14 | import com.osiris.autoplug.client.tasks.updater.search.SearchResult; 15 | import com.osiris.jlib.json.Json; 16 | import com.osiris.jlib.logger.AL; 17 | import com.osiris.jlib.search.Version; 18 | 19 | import java.util.regex.Matcher; 20 | import java.util.regex.Pattern; 21 | 22 | public class BukkitSearchById { 23 | 24 | public SearchResult search(MinecraftPlugin plugin) { 25 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Performing bukkit search by id"); 26 | int bukkitId = plugin.getBukkitId(); 27 | 28 | String url = "https://api.curseforge.com/servermods/files?projectIds=" + bukkitId; 29 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Fetching latest release... (" + url + ")"); 30 | 31 | Exception exception = null; 32 | JsonArray versions = null; 33 | JsonObject json = null; 34 | String latest = null; 35 | String downloadUrl = null; 36 | String downloadType = "unknown"; 37 | SearchResult.Type code = SearchResult.Type.UP_TO_DATE; 38 | try { 39 | versions = Json.getAsJsonArray(url); 40 | json = versions.get(versions.size() - 1).getAsJsonObject(); 41 | latest = json.get("name").getAsString(); 42 | if (latest != null) 43 | latest = latest.replaceAll("[^0-9.]", ""); // Before passing over remove everything except numbers and dots 44 | 45 | if(latest == null) latest = ""; 46 | if (Version.isLatestBigger(plugin.getVersion(), latest)) 47 | code = SearchResult.Type.UPDATE_AVAILABLE; 48 | 49 | downloadUrl = json.get("downloadUrl").getAsString(); 50 | Matcher m = Pattern.compile("[.][^.]+$") 51 | .matcher(json.get("fileName").getAsString()); 52 | if (m.find()) { 53 | downloadType = m.group(0); 54 | } else 55 | throw new Exception("[" + plugin.getName() + "] Couldn't find a downloadType in fileName: " + json.get("fileName").getAsString()); 56 | } catch (Exception e) { 57 | exception = e; 58 | code = SearchResult.Type.API_ERROR; 59 | } 60 | 61 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Finished check with results: code:" + code + " latest:" + latest + " downloadURL:" + downloadUrl + " type:" + downloadType + " "); 62 | SearchResult result = new SearchResult(plugin, code, latest, downloadUrl, downloadType, null, String.valueOf(bukkitId), false); 63 | result.setException(exception); 64 | return result; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/updater/search/spigot/SpigotSearchByAuthor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater.search.spigot; 10 | 11 | import com.google.gson.JsonArray; 12 | import com.google.gson.JsonObject; 13 | import com.osiris.autoplug.client.tasks.updater.plugins.MinecraftPlugin; 14 | import com.osiris.autoplug.client.tasks.updater.search.SearchResult; 15 | import com.osiris.autoplug.client.utils.StringComparator; 16 | import com.osiris.jlib.logger.AL; 17 | 18 | public class SpigotSearchByAuthor { 19 | 20 | 21 | /** 22 | * This will search for the author and scan his resources for a matching Plugin 23 | */ 24 | public SearchResult search(MinecraftPlugin plugin) { 25 | String plName = plugin.getName(); 26 | String plAuthor = plugin.getAuthor(); 27 | String plVersion = plugin.getVersion(); 28 | 29 | Exception exception = null; 30 | try { 31 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Searching for author " + plAuthor + "(" + plName + ")..."); 32 | JsonArray jsonAuthors = new SpigetAPI().getAuthors(plAuthor); 33 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Found " + jsonAuthors.size() + " similar authors..."); 34 | 35 | for (int i = 0; i < jsonAuthors.size(); i++) { 36 | JsonObject jAuthor = jsonAuthors.get(i).getAsJsonObject(); 37 | String jAuthorName = jAuthor.get("name").getAsString(); 38 | 39 | double similarity = StringComparator.similarity(jAuthorName, plAuthor); 40 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Similarity between -> " + plAuthor + " and " + jAuthorName + " is: " + similarity); 41 | 42 | if (similarity > 0.6) { 43 | String jAuthorId = jAuthor.get("id").getAsString(); 44 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Author matches! Continuing with " + jAuthorName + " ID: " + jAuthorId); 45 | JsonArray jsonAuthorPlugins = new SpigetAPI().getAuthorResources(jAuthorId); 46 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Found " + jsonAuthorPlugins.size() + " resources of this author..."); 47 | 48 | for (int j = 0; j < jsonAuthorPlugins.size(); j++) { 49 | JsonObject jPL = jsonAuthorPlugins.get(j).getAsJsonObject(); 50 | String jPLName = jPL.get("name").getAsString(); 51 | String jPLID = jPL.get("id").getAsString(); 52 | double similarity2 = StringComparator.similarity(jPLName, plName); 53 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Similarity between -> " + plName + " and " + jPLName + " is: " + similarity2); 54 | if (similarity2 > 0.5) { 55 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Plugin found!: " + jPLName); 56 | plugin.setSpigotId(Integer.parseInt(jPLID)); 57 | return new SpigotSearchById().search(plugin); 58 | } 59 | } 60 | } 61 | } 62 | } catch (Exception ex) { 63 | exception = ex; 64 | } 65 | AL.debug(this.getClass(), "[" + plugin.getName() + "] No match found for " + plName + "!"); 66 | SearchResult result; 67 | if (exception != null) 68 | result = new SearchResult(plugin, SearchResult.Type.API_ERROR, null, null, null, null, null, false); 69 | else 70 | result = new SearchResult(plugin, SearchResult.Type.RESOURCE_NOT_FOUND, null, null, null, null, null, false); 71 | result.setException(exception); 72 | return result; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/updater/search/spigot/SpigotSearchById.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater.search.spigot; 10 | 11 | import com.google.gson.JsonObject; 12 | import com.osiris.autoplug.client.tasks.updater.plugins.MinecraftPlugin; 13 | import com.osiris.autoplug.client.tasks.updater.search.SearchResult; 14 | import com.osiris.jlib.json.Json; 15 | import com.osiris.jlib.logger.AL; 16 | import com.osiris.jlib.search.Version; 17 | 18 | public class SpigotSearchById { 19 | 20 | public SearchResult search(MinecraftPlugin plugin) { 21 | int spigotId = plugin.getSpigotId(); 22 | Exception exception = null; 23 | 24 | String url = "https://api.spiget.org/v2/resources/" + spigotId + 25 | "/versions?size=1&sort=-releaseDate"; 26 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Fetching latest release... (" + url + ")"); 27 | String latest = null; 28 | String type = null; 29 | String downloadUrl = null; 30 | SearchResult.Type code = SearchResult.Type.UP_TO_DATE; 31 | boolean isPremium = false; 32 | try { 33 | // Get the latest version 34 | latest = Json.getAsJsonArray(url).get(0).getAsJsonObject().get("name").getAsString(); 35 | if (latest != null) 36 | latest = latest.replaceAll("[^0-9.]", ""); // Before passing over remove everything except numbers and dots 37 | 38 | // Get the file type and downloadUrl 39 | String url1 = "https://api.spiget.org/v2/resources/" + spigotId; 40 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Fetching resource details... (" + url1 + ")"); 41 | JsonObject json = Json.getAsObject(url1).getAsJsonObject("file"); 42 | isPremium = Boolean.parseBoolean(Json.getAsObject(url1).get("premium").getAsString()); 43 | type = json.get("type").getAsString(); 44 | downloadUrl = "https://www.spigotmc.org/" + json.get("url").getAsString(); 45 | 46 | // If not external download over the spiget api 47 | downloadUrl = "https://api.spiget.org/v2/resources/" + spigotId + "/download"; 48 | 49 | if (Version.isLatestBigger(plugin.getVersion(), latest == null ? "0" : latest)) 50 | code = SearchResult.Type.UPDATE_AVAILABLE; 51 | } catch (Exception e) { 52 | exception = e; 53 | code = SearchResult.Type.API_ERROR; 54 | } 55 | 56 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Finished check with results: code:" + code + " latest:" + latest + " downloadURL:" + downloadUrl + " type:" + type + " "); 57 | SearchResult result = new SearchResult(plugin, code, latest, downloadUrl, type, String.valueOf(spigotId), null, isPremium); 58 | result.setException(exception); 59 | return result; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/tasks/updater/search/spigot/SpigotSearchByName.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater.search.spigot; 10 | 11 | import com.google.gson.JsonArray; 12 | import com.google.gson.JsonObject; 13 | import com.osiris.autoplug.client.tasks.updater.plugins.MinecraftPlugin; 14 | import com.osiris.autoplug.client.tasks.updater.search.SearchResult; 15 | import com.osiris.autoplug.client.utils.StringComparator; 16 | import com.osiris.jlib.logger.AL; 17 | 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | 21 | public class SpigotSearchByName { 22 | 23 | /** 24 | * This will search by the Plugins name for matching resources 25 | * 26 | * @return an Array containing the download-url or error-code in 0 27 | * and the latest version in 1 28 | */ 29 | public SearchResult search(MinecraftPlugin plugin) { 30 | String plName = plugin.getName(); 31 | String plAuthor = plugin.getAuthor(); 32 | String plVersion = plugin.getVersion(); 33 | Exception exception = null; 34 | List similarPlugins = new ArrayList<>(); 35 | try { 36 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Searching for plugin " + plName + "(" + plAuthor + ")..."); 37 | JsonArray queryPlugins = new SpigetAPI().getPlugins(plName); 38 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Found " + queryPlugins.size() + " similar plugins!"); 39 | 40 | for (int i = 0; i < queryPlugins.size(); i++) { 41 | 42 | JsonObject jsonPlugin = queryPlugins.get(i).getAsJsonObject(); 43 | JsonObject jsonAuthor = null; 44 | try { 45 | jsonAuthor = new SpigetAPI().getAuthorDetails(jsonPlugin.get("author").getAsJsonObject().get("id").getAsString()); 46 | } catch (Exception ignore) { 47 | } 48 | 49 | if (jsonAuthor != null) { 50 | String queryAuthor = jsonAuthor.get("name").getAsString(); 51 | 52 | //Remove any symbols and spaces to exactly compare both strings, but keep numbers 53 | queryAuthor = queryAuthor.replaceAll("[^a-zA-Z]", ""); 54 | plAuthor = plAuthor.replaceAll("[^a-zA-Z]", ""); 55 | int plId = Integer.parseInt(jsonPlugin.get("id").getAsString()); 56 | 57 | similarPlugins.add(new MinecraftPlugin(null, plName, plVersion, queryAuthor, plId, 0, null)); 58 | 59 | double similarity = StringComparator.similarity(queryAuthor, plAuthor); 60 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Similarity between -> " + plAuthor + " and " + queryAuthor + " is: " + similarity); 61 | if (similarity > 0.5) { 62 | AL.debug(this.getClass(), "[" + plugin.getName() + "] Found plugin " + plName + " with matching author: " + queryAuthor + ")"); 63 | plugin.setSpigotId(plId); 64 | return new SpigotSearchById().search(plugin); 65 | } 66 | } 67 | 68 | } 69 | } catch (Exception e) { 70 | exception = e; 71 | } 72 | AL.debug(this.getClass(), "[" + plugin.getName() + "] No match found for " + plName + "!"); 73 | SearchResult result; 74 | if (exception != null) 75 | result = new SearchResult(plugin, SearchResult.Type.API_ERROR, null, null, null, null, null, false); 76 | else 77 | result = new SearchResult(plugin, SearchResult.Type.RESOURCE_NOT_FOUND, null, null, null, null, null, false); 78 | result.similarPlugins = similarPlugins; 79 | result.setException(exception); 80 | return result; 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/ui/HomePanel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.ui; 10 | 11 | import com.osiris.autoplug.client.console.Commands; 12 | import com.osiris.autoplug.client.ui.utils.HintTextField; 13 | import com.osiris.autoplug.client.ui.utils.MyMouseListener; 14 | import com.osiris.betterlayout.BLayout; 15 | import com.osiris.jlib.logger.AL; 16 | import com.osiris.jlib.logger.MessageFormatter; 17 | 18 | import javax.swing.*; 19 | import java.awt.*; 20 | import java.awt.event.KeyEvent; 21 | import java.awt.event.KeyListener; 22 | import java.util.ArrayList; 23 | 24 | public class HomePanel extends BLayout { 25 | 26 | public JLabel labelConsole = new JLabel("Console"); 27 | public BLayout txtConsole; 28 | public HintTextField txtSendCommand = new HintTextField("Send command..."); 29 | private final JButton execute; 30 | 31 | public HomePanel(Container parent) { 32 | super(parent); 33 | 34 | execute = new JButton("Execute"); 35 | BLayout jPanel = new BLayout(this, 100, 30); 36 | // jPanel.setLayout(new FlowLayout()); 37 | jPanel.addH(txtSendCommand); 38 | jPanel.addH(execute); 39 | 40 | //TODO this.addV(getBtnMinecraftLaunch()); 41 | 42 | txtConsole = new BLayout(this, 100, 80); 43 | txtConsole.defaultCompStyles.delPadding(); 44 | txtConsole.makeScrollable(); 45 | //TODO txtConsole.getScrollPane().getVerticalScrollBar().setUnitIncrement(16); 46 | 47 | this.addV(txtSendCommand); 48 | this.addV(jPanel); 49 | 50 | AL.actionsOnMessageEvent.add(msg -> { 51 | txtConsole.access(() -> { 52 | for (JLabel jLabel : toLabel(MessageFormatter.formatForFile(msg))) { 53 | txtConsole.addV(jLabel); 54 | } 55 | //txtConsole.setText(txtConsole.getText() + + "\n"); 56 | }); 57 | txtConsole.scrollToEndV(); 58 | }); 59 | txtSendCommand.addKeyListener(new KeyListener() { 60 | @Override 61 | public void keyTyped(KeyEvent e) { 62 | if (e.getKeyChar() == KeyEvent.VK_ENTER) { 63 | txtConsole.access(() -> { 64 | txtConsole.addV(new JLabel(txtSendCommand.getText())); 65 | }); 66 | txtConsole.scrollToEndV(); 67 | AL.info("Received System-Tray command: '" + txtSendCommand.getText() + "'"); 68 | Commands.execute(txtSendCommand.getText()); 69 | txtSendCommand.setText(""); 70 | } 71 | } 72 | 73 | @Override 74 | public void keyPressed(KeyEvent e) { 75 | 76 | } 77 | 78 | @Override 79 | public void keyReleased(KeyEvent e) { 80 | 81 | } 82 | }); 83 | 84 | execute.addActionListener(e -> { 85 | txtConsole.access(() -> { 86 | txtConsole.addV(new JLabel(txtSendCommand.getText())); 87 | }); 88 | txtConsole.scrollToEndV(); 89 | AL.info("Received System-Tray command: '" + txtSendCommand.getText() + "'"); 90 | Commands.execute(txtSendCommand.getText()); 91 | txtSendCommand.setText(""); 92 | }); 93 | } 94 | 95 | private JButton getBtnMinecraftLaunch() { 96 | JButton btn = new JButton("Launch Minecraft"); 97 | btn.addMouseListener(new MyMouseListener().onClick(event -> { 98 | 99 | })); 100 | return btn; 101 | } 102 | 103 | private java.util.List toLabel(String ansi) { 104 | // TODO convert ansi colors to awt 105 | String[] lines = ansi.split("\n"); 106 | java.util.List list = new ArrayList<>(); 107 | for (String line : lines) { 108 | list.add(new JLabel(line)); 109 | } 110 | return list; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/ui/MindustryModsPanel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.ui; 10 | 11 | import com.osiris.betterlayout.BLayout; 12 | 13 | import java.awt.*; 14 | 15 | public class MindustryModsPanel extends BLayout { 16 | public MindustryModsPanel(Container parent) { 17 | super(parent); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/ui/MinecraftModsPanel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.ui; 10 | 11 | import com.osiris.autoplug.client.ui.utils.MyMouseListener; 12 | import com.osiris.betterlayout.BLayout; 13 | import com.osiris.dyml.Yaml; 14 | import com.osiris.dyml.YamlSection; 15 | import com.osiris.dyml.exceptions.DuplicateKeyException; 16 | import com.osiris.dyml.exceptions.IllegalListException; 17 | import com.osiris.dyml.exceptions.YamlReaderException; 18 | import com.osiris.jlib.logger.AL; 19 | 20 | import javax.swing.*; 21 | import java.awt.*; 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.util.List; 25 | import java.util.Objects; 26 | 27 | public class MinecraftModsPanel extends BLayout { 28 | public JButton btnRefreshData = new JButton("Refresh"); 29 | public JTable table = new JTable(); 30 | 31 | public MinecraftModsPanel(Container parent) throws Exception { 32 | super(parent); 33 | this.addV(btnRefreshData); 34 | this.addV(table); 35 | updateData(); 36 | btnRefreshData.addMouseListener(new MyMouseListener().onClick(click -> { 37 | try { 38 | updateData(); 39 | } catch (Exception e) { 40 | AL.warn(e); 41 | } 42 | })); 43 | } 44 | 45 | public void updateData() throws YamlReaderException, IOException, DuplicateKeyException, IllegalListException { 46 | // Fetch data 47 | int columnsCount = 4; 48 | String[] columnNames = {"Name", "Version", "Latest", "Author"}; 49 | Object[][] data = null; 50 | File yamlFile = new File(System.getProperty("user.dir") + "/autoplug/mods.yml"); 51 | if (!yamlFile.exists()) { 52 | data = new Object[][]{ 53 | {"-", "-", "-", "-"} 54 | }; 55 | } else { 56 | Yaml modsConfig = new Yaml(yamlFile); 57 | modsConfig.load(); 58 | List sections = Objects.requireNonNull(modsConfig.get("mods")).getChildSections(); 59 | sections.remove(0); // To skip first child, since that's no mod data 60 | data = new Object[sections.size()][columnsCount]; 61 | for (int i = 0; i < sections.size(); i++) { 62 | YamlSection sec = sections.get(i); 63 | String modName = sec.getLastKey(); 64 | data[i][0] = modName; 65 | data[i][1] = modsConfig.get("mods", modName, "version").asString(); 66 | data[i][2] = modsConfig.get("mods", modName, "latest-version").asString(); 67 | data[i][3] = modsConfig.get("mods", modName, "author").asString(); 68 | } 69 | } 70 | 71 | // Update UI 72 | this.remove(table); 73 | table = new JTable(data, columnNames); 74 | this.addV(table); 75 | table.setBackground(new Color(0, true)); // transparent 76 | table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/ui/MinecraftPluginsPanel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.ui; 10 | 11 | import com.osiris.autoplug.client.ui.utils.MyMouseListener; 12 | import com.osiris.betterlayout.BLayout; 13 | import com.osiris.dyml.Yaml; 14 | import com.osiris.dyml.YamlSection; 15 | import com.osiris.dyml.exceptions.DuplicateKeyException; 16 | import com.osiris.dyml.exceptions.IllegalListException; 17 | import com.osiris.dyml.exceptions.YamlReaderException; 18 | import com.osiris.jlib.logger.AL; 19 | 20 | import javax.swing.*; 21 | import java.awt.*; 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.util.List; 25 | import java.util.Objects; 26 | 27 | public class MinecraftPluginsPanel extends BLayout { 28 | public JButton btnRefreshData = new JButton("Refresh"); 29 | public JTable table = new JTable(); 30 | 31 | public MinecraftPluginsPanel(Container parent) throws Exception { 32 | super(parent); 33 | this.addV(btnRefreshData); 34 | this.addV(table); 35 | updateData(); 36 | btnRefreshData.addMouseListener(new MyMouseListener().onClick(click -> { 37 | try { 38 | updateData(); 39 | } catch (Exception e) { 40 | AL.warn(e); 41 | } 42 | })); 43 | } 44 | 45 | public void updateData() throws YamlReaderException, IOException, DuplicateKeyException, IllegalListException { 46 | // Fetch data 47 | int columnsCount = 4; 48 | String[] columnNames = {"Name", "Version", "Latest", "Author"}; 49 | Object[][] data = null; 50 | File yamlFile = new File(System.getProperty("user.dir") + "/autoplug/plugins.yml"); 51 | if (!yamlFile.exists()) { 52 | data = new Object[][]{ 53 | {"-", "-", "-", "-"} 54 | }; 55 | } else { 56 | Yaml plConfig = new Yaml(yamlFile); 57 | plConfig.load(); 58 | List sections = Objects.requireNonNull(plConfig.get("plugins")).getChildSections(); 59 | sections.remove(0); // To skip first child, since that's no plugin data 60 | data = new Object[sections.size()][columnsCount]; 61 | for (int i = 0; i < sections.size(); i++) { 62 | YamlSection sec = sections.get(i); 63 | String modName = sec.getLastKey(); 64 | data[i][0] = modName; 65 | data[i][1] = plConfig.get("plugins", modName, "version").asString(); 66 | data[i][2] = plConfig.get("plugins", modName, "latest-version").asString(); 67 | data[i][3] = plConfig.get("plugins", modName, "author").asString(); 68 | } 69 | } 70 | 71 | // Update UI 72 | Object[][] finalData = data; 73 | this.access(() -> { 74 | this.remove(table); 75 | table = new JTable(finalData, columnNames); 76 | this.addV(table); 77 | table.setBackground(new Color(0, true)); // transparent 78 | table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); 79 | }); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/ui/SettingsPanel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.ui; 10 | 11 | import com.osiris.autoplug.client.ui.utils.MyMouseListener; 12 | import com.osiris.betterlayout.BLayout; 13 | import com.osiris.betterlayout.utils.UIDebugWindow; 14 | import com.osiris.jlib.logger.AL; 15 | 16 | import javax.swing.*; 17 | import java.awt.*; 18 | 19 | public class SettingsPanel extends BLayout { 20 | public SettingsPanel(Container parent) throws Exception { 21 | super(parent); 22 | JButton btnOpenUIDebug = new JButton("Open UI-Debug"); 23 | this.addV(btnOpenUIDebug); 24 | btnOpenUIDebug.addMouseListener(new MyMouseListener().onClick(click -> { 25 | try { 26 | new UIDebugWindow(MainWindow.GET); 27 | } catch (Exception e) { 28 | AL.warn(e); 29 | } 30 | })); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/ui/utils/HintTextField.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.ui.utils; 10 | 11 | import javax.swing.*; 12 | import java.awt.*; 13 | import java.awt.event.FocusEvent; 14 | import java.awt.event.FocusListener; 15 | 16 | /** 17 | * @author Bart Kiers https://stackoverflow.com/a/1739037/13600212 18 | */ 19 | public class HintTextField extends JTextField implements FocusListener { 20 | 21 | private final String hint; 22 | private boolean showingHint; 23 | 24 | public HintTextField(final String hint) { 25 | super(hint); 26 | this.hint = hint; 27 | this.showingHint = true; 28 | super.addFocusListener(this); 29 | super.setForeground(Color.GRAY); 30 | } 31 | 32 | @Override 33 | public void focusGained(FocusEvent e) { 34 | if (this.getText().isEmpty()) { 35 | super.setText(""); 36 | super.setForeground(Color.BLACK); 37 | showingHint = false; 38 | } 39 | } 40 | 41 | @Override 42 | public void focusLost(FocusEvent e) { 43 | if (this.getText().isEmpty()) { 44 | super.setText(hint); 45 | super.setForeground(Color.GRAY); 46 | showingHint = true; 47 | } 48 | } 49 | 50 | @Override 51 | public String getText() { 52 | return showingHint ? "" : super.getText(); 53 | } 54 | } -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/ui/utils/MyMouseListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.ui.utils; 10 | 11 | import java.awt.event.MouseEvent; 12 | import java.util.function.Consumer; 13 | 14 | /** 15 | * Wrapper around {@link java.awt.event.MouseListener} 16 | * which provides Java 8 style listener and results 17 | * in cleaner/less code. 18 | */ 19 | public class MyMouseListener implements java.awt.event.MouseListener { 20 | private Consumer onClick, onPressed, onReleased, onEntered, onExited; 21 | 22 | public MyMouseListener onClick(Consumer event) { 23 | this.onClick = event; 24 | return this; 25 | } 26 | 27 | @Override 28 | public void mouseClicked(MouseEvent e) { 29 | if (onClick != null) onClick.accept(e); 30 | } 31 | 32 | 33 | public MyMouseListener onPress(Consumer event) { 34 | this.onPressed = event; 35 | return this; 36 | } 37 | 38 | @Override 39 | public void mousePressed(MouseEvent e) { 40 | if (onPressed != null) onPressed.accept(e); 41 | } 42 | 43 | 44 | public MyMouseListener onRelease(Consumer event) { 45 | this.onReleased = event; 46 | return this; 47 | } 48 | 49 | @Override 50 | public void mouseReleased(MouseEvent e) { 51 | if (onReleased != null) onReleased.accept(e); 52 | } 53 | 54 | 55 | public MyMouseListener onEnter(Consumer event) { 56 | this.onEntered = event; 57 | return this; 58 | } 59 | 60 | @Override 61 | public void mouseEntered(MouseEvent e) { 62 | if (onEntered != null) onEntered.accept(e); 63 | } 64 | 65 | 66 | public MyMouseListener onExit(Consumer event) { 67 | this.onExited = event; 68 | return this; 69 | } 70 | 71 | @Override 72 | public void mouseExited(MouseEvent e) { 73 | if (onExited != null) onExited.accept(e); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/ConsoleOutputCapturer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | package com.osiris.autoplug.client.utils; 9 | 10 | import java.io.ByteArrayOutputStream; 11 | import java.io.OutputStream; 12 | import java.io.PrintStream; 13 | import java.io.UnsupportedEncodingException; 14 | import java.nio.charset.StandardCharsets; 15 | 16 | public class ConsoleOutputCapturer { 17 | private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); 18 | private final PrintStream ps = new PrintStream(baos); 19 | private final PrintStream oldOut = System.out; 20 | private final PrintStream oldErr = System.err; 21 | 22 | public void start() { 23 | System.setOut(new PrintStream(new OutputStream() { 24 | @Override 25 | public void write(int b) { 26 | ps.write(b); 27 | oldOut.write(b); 28 | } 29 | 30 | @Override 31 | public void write(byte[] b, int off, int len) { 32 | ps.write(b, off, len); 33 | oldOut.write(b, off, len); 34 | } 35 | })); 36 | 37 | System.setErr(new PrintStream(new OutputStream() { 38 | @Override 39 | public void write(int b) { 40 | ps.write(b); 41 | oldErr.write(b); 42 | } 43 | 44 | @Override 45 | public void write(byte[] b, int off, int len) { 46 | ps.write(b, off, len); 47 | oldErr.write(b, off, len); 48 | } 49 | })); 50 | } 51 | 52 | public void stop() { 53 | System.setOut(oldOut); 54 | System.setErr(oldErr); 55 | } 56 | 57 | public String getNewOutput() { 58 | String newOutput = null; 59 | try { 60 | newOutput = baos.toString(StandardCharsets.UTF_8.name()); 61 | } catch (UnsupportedEncodingException e) { 62 | throw new RuntimeException(e); // Never should be thrown 63 | } 64 | baos.reset(); 65 | return newOutput; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/GD.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import com.osiris.autoplug.client.Target; 12 | import com.osiris.autoplug.client.configs.GeneralConfig; 13 | import com.osiris.dyml.exceptions.DuplicateKeyException; 14 | import com.osiris.dyml.exceptions.IllegalListException; 15 | import com.osiris.dyml.exceptions.YamlReaderException; 16 | import com.osiris.dyml.exceptions.YamlWriterException; 17 | import com.osiris.jlib.logger.AL; 18 | import org.jetbrains.annotations.NotNull; 19 | 20 | import java.io.File; 21 | import java.io.IOException; 22 | import java.util.Scanner; 23 | 24 | /** 25 | * GlobalData, which is always static and used frequently in this project 26 | */ 27 | public class GD { 28 | public static final String AUTHOR = "Osiris-Team"; 29 | public static final File FILE_ERR_OUT = new File(System.getProperty("user.dir") + "/autoplug/logs/console-mirror-err.log"); 30 | // TODO make all of these not static and deprecate this class 31 | public static String OFFICIAL_WEBSITE = "https://autoplug.one/"; 32 | public static boolean IS_TEST_MODE = false; 33 | @NotNull 34 | public static String VERSION = "AutoPlug-Client (ERROR RETRIEVING VERSION)"; 35 | public static File WORKING_DIR; 36 | public static File PLUGINS_DIR; 37 | public static File DOWNLOADS_DIR; 38 | public static File AP_LATEST_LOG = new File(System.getProperty("user.dir") + "/autoplug/logs/latest.log"); 39 | public static File SYSTEM_LATEST_LOG = new File(System.getProperty("user.dir") + "/autoplug/logs/system-latest.log"); 40 | public static File FILE_OUT = new File(System.getProperty("user.dir") + "/autoplug/logs/console-mirror.log"); 41 | public static Target TARGET = null; 42 | 43 | static { 44 | WORKING_DIR = new File(System.getProperty("user.dir")); 45 | PLUGINS_DIR = new File(System.getProperty("user.dir") + "/plugins"); 46 | DOWNLOADS_DIR = new File(System.getProperty("user.dir") + "/autoplug/downloads"); 47 | try { 48 | VERSION = "AutoPlug-Client " + new UtilsJar().getThisJarsAutoPlugProperties().getProperty("version"); 49 | } catch (Exception e) { 50 | System.err.println("Failed to determine AutoPlug-Client version. More details below. Keep in mind that" + 51 | " the exception is ignored and does not further affect the application."); 52 | e.printStackTrace(); 53 | } 54 | } 55 | 56 | public static String errorMsgFailedToGetMCVersion() { 57 | return "Failed to determine Minecraft version. Make sure the server jar exists or the version is provided in general.yml or updater.yml."; 58 | } 59 | 60 | public static void determineTarget(GeneralConfig generalConfig) throws YamlReaderException, YamlWriterException, IOException, DuplicateKeyException, IllegalListException { 61 | String target = generalConfig.autoplug_target_software.asString(); 62 | while (true) { 63 | if (target == null) { 64 | for (String comment : generalConfig.autoplug_target_software.getComments()) { 65 | AL.info(comment); 66 | } 67 | AL.info("Please enter a valid option and press enter:"); 68 | target = new Scanner(System.in).nextLine(); 69 | generalConfig.autoplug_target_software.setValues(target); 70 | generalConfig.save(); 71 | } else { 72 | TARGET = Target.fromString(target); 73 | if (TARGET != null) break; 74 | for (String comment : generalConfig.autoplug_target_software.getComments()) { 75 | AL.info(comment); 76 | } 77 | AL.info("The selected target software '" + target + "' is not a valid option."); 78 | AL.info("Please enter a valid option and press enter:"); 79 | target = new Scanner(System.in).nextLine(); 80 | generalConfig.autoplug_target_software.setValues(target); 81 | generalConfig.save(); 82 | } 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/Streams.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import java.io.BufferedReader; 12 | import java.io.IOException; 13 | import java.io.InputStream; 14 | import java.io.InputStreamReader; 15 | 16 | public class Streams { 17 | public String read(InputStream in) throws IOException { 18 | if (in == null) return null; 19 | StringBuilder s = new StringBuilder(); 20 | try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { 21 | String l = null; 22 | while ((l = reader.readLine()) != null) { 23 | s.append(l + "\n"); 24 | } 25 | } 26 | return s.toString(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/StringComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | public class StringComparator { 12 | 13 | /** 14 | * Calculates the similarity (a number within 0 and 1) between two strings. 15 | */ 16 | public static synchronized double similarity(String s1, String s2) { 17 | String longer = s1, shorter = s2; 18 | if (s1.length() < s2.length()) { // longer should always have greater length 19 | longer = s2; 20 | shorter = s1; 21 | } 22 | int longerLength = longer.length(); 23 | if (longerLength == 0) { 24 | return 1.0; /* both strings are zero length */ 25 | } 26 | /* // If you have StringUtils, you can use it to calculate the edit distance: 27 | return (longerLength - StringUtils.getLevenshteinDistance(longer, shorter)) / 28 | (double) longerLength; */ 29 | return (longerLength - editDistance(longer, shorter)) / (double) longerLength; 30 | 31 | } 32 | 33 | // Example implementation of the Levenshtein Edit Distance 34 | // See http://r...content-available-to-author-only...e.org/wiki/Levenshtein_distance#Java 35 | public static synchronized int editDistance(String s1, String s2) { 36 | s1 = s1.toLowerCase(); 37 | s2 = s2.toLowerCase(); 38 | 39 | int[] costs = new int[s2.length() + 1]; 40 | for (int i = 0; i <= s1.length(); i++) { 41 | int lastValue = i; 42 | for (int j = 0; j <= s2.length(); j++) { 43 | if (i == 0) 44 | costs[j] = j; 45 | else { 46 | if (j > 0) { 47 | int newValue = costs[j - 1]; 48 | if (s1.charAt(i - 1) != s2.charAt(j - 1)) 49 | newValue = Math.min(Math.min(newValue, lastValue), 50 | costs[j]) + 1; 51 | costs[j - 1] = lastValue; 52 | lastValue = newValue; 53 | } 54 | } 55 | } 56 | if (i > 0) 57 | costs[s2.length()] = lastValue; 58 | } 59 | return costs[s2.length()]; 60 | } 61 | 62 | //You can use this to print out the similarity 63 | public static void printSimilarity(String s, String t) { 64 | System.out.printf("%.3f is the similarity between \"%s\" and \"%s\"%n", similarity(s, t), s, t); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/UpdateCheckerThread.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import com.osiris.autoplug.client.configs.SystemConfig; 12 | import com.osiris.autoplug.client.configs.UpdaterConfig; 13 | import com.osiris.autoplug.client.tasks.updater.java.TaskJavaUpdater; 14 | import com.osiris.autoplug.client.tasks.updater.mods.TaskModsUpdater; 15 | import com.osiris.autoplug.client.tasks.updater.plugins.TaskPluginsUpdater; 16 | import com.osiris.autoplug.client.tasks.updater.self.TaskSelfUpdater; 17 | import com.osiris.autoplug.client.tasks.updater.server.TaskServerUpdater; 18 | import com.osiris.autoplug.client.utils.tasks.MyBThreadManager; 19 | import com.osiris.autoplug.client.utils.tasks.UtilsTasks; 20 | import com.osiris.jlib.logger.AL; 21 | 22 | import java.text.SimpleDateFormat; 23 | 24 | public class UpdateCheckerThread extends Thread { 25 | public boolean isRunning = false; 26 | 27 | @Override 28 | public void run() { 29 | try { 30 | isRunning = true; 31 | while (isRunning) { 32 | long last = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss") 33 | .parse(new SystemConfig().timestamp_last_updater_tasks.asString()) 34 | .getTime(); 35 | long now1 = System.currentTimeMillis(); 36 | long msSinceLast = now1 - last; 37 | long msLeft = (new UpdaterConfig().global_recurring_checks_intervall.asInt() * 3600000L) // 1h in ms 38 | - msSinceLast; 39 | if (msLeft > 0) Thread.sleep(msLeft); 40 | AL.info("Running tasks from recurring update-checker thread."); 41 | MyBThreadManager man = new UtilsTasks().createManagerAndPrinter(); 42 | TaskSelfUpdater selfUpdater = new TaskSelfUpdater("SelfUpdater", man.manager); 43 | TaskJavaUpdater taskJavaUpdater = new TaskJavaUpdater("JavaUpdater", man.manager); 44 | TaskServerUpdater taskServerUpdater = new TaskServerUpdater("ServerUpdater", man.manager); 45 | TaskPluginsUpdater taskPluginsUpdater = new TaskPluginsUpdater("PluginsUpdater", man.manager); 46 | TaskModsUpdater taskModsUpdater = new TaskModsUpdater("ModsUpdater", man.manager); 47 | selfUpdater.start(); 48 | while (!selfUpdater.isFinished()) // Wait until the self updater finishes 49 | Thread.sleep(1000); 50 | taskJavaUpdater.start(); 51 | taskServerUpdater.start(); 52 | taskPluginsUpdater.start(); 53 | taskModsUpdater.start(); 54 | while (!man.manager.isFinished()) 55 | Thread.sleep(1000); 56 | } 57 | } catch (Exception e) { 58 | AL.warn(e); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/UtilsByte.java: -------------------------------------------------------------------------------- 1 | package com.osiris.autoplug.client.utils; 2 | 3 | /* 4 | * Copyright (c) Cedar Software, LLC 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); you 7 | * may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | public final class UtilsByte { 20 | private static final char[] _hex = 21 | { 22 | '0', '1', '2', '3', '4', '5', '6', '7', 23 | '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 24 | }; 25 | 26 | 27 | /** 28 | *

29 | * {@code StringUtilities} instances should NOT be constructed in standard 30 | * programming. Instead, the class should be used statically as 31 | * {@code StringUtilities.trim();}. 32 | *

33 | */ 34 | private UtilsByte() { 35 | super(); 36 | } 37 | 38 | // Turn hex String into byte[] 39 | // If string is not even length, return null. 40 | 41 | public static byte[] decode(final String s) { 42 | final int len = s.length(); 43 | if (len % 2 != 0) { 44 | return null; 45 | } 46 | 47 | byte[] bytes = new byte[len / 2]; 48 | int pos = 0; 49 | 50 | for (int i = 0; i < len; i += 2) { 51 | byte hi = (byte) Character.digit(s.charAt(i), 16); 52 | byte lo = (byte) Character.digit(s.charAt(i + 1), 16); 53 | bytes[pos++] = (byte) (hi * 16 + lo); 54 | } 55 | 56 | return bytes; 57 | } 58 | 59 | /** 60 | * Convert a byte array into a printable format containing a String of hex 61 | * digit characters (two per byte). 62 | * 63 | * @param bytes array representation 64 | * @return String hex digits 65 | */ 66 | public static String encode(final byte[] bytes) { 67 | StringBuilder sb = new StringBuilder(bytes.length << 1); 68 | for (byte aByte : bytes) { 69 | sb.append(convertDigit(aByte >> 4)); 70 | sb.append(convertDigit(aByte & 0x0f)); 71 | } 72 | return sb.toString(); 73 | } 74 | 75 | /** 76 | * Convert the specified value (0 .. 15) to the corresponding hex digit. 77 | * 78 | * @param value to be converted 79 | * @return '0'..'F' in char format. 80 | */ 81 | private static char convertDigit(final int value) { 82 | return _hex[value & 0x0f]; 83 | } 84 | 85 | /** 86 | * @param bytes byte[] of bytes to test 87 | * @return true if bytes are gzip compressed, false otherwise. 88 | */ 89 | public static boolean isGzipped(byte[] bytes) { 90 | return bytes[0] == (byte) 0x1f && bytes[1] == (byte) 0x8b; 91 | } 92 | } 93 | 94 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/UtilsFile.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import java.io.File; 12 | import java.io.IOException; 13 | import java.nio.file.Files; 14 | 15 | public class UtilsFile { 16 | 17 | public String getFileName(String s) { 18 | return new File(s).getName(); 19 | } 20 | 21 | /** 22 | * Removes unsupported chars like control chars 23 | * and specific printable chars like \ or / from the provided string and returns it.
24 | * Works for all operating systems. 25 | */ 26 | public String getValidFileName(String fileName) { 27 | return fileName.replaceAll("\\p{Cc}", "") // First remove control/not-printable chars 28 | .replaceAll("[/\\\\<>:\"'|*?]", ""); // Then remove invalid printable chars 29 | } 30 | 31 | public void copyDirectoryContent(File sourceDir, File targetDir) throws IOException { 32 | targetDir.mkdirs(); 33 | for (File sourceFile : sourceDir.listFiles()) { 34 | File targetFile = new File(targetDir + "/" + sourceFile.getName()); 35 | targetFile.createNewFile(); 36 | Files.copy(sourceFile.toPath(), targetFile.toPath()); 37 | } 38 | } 39 | 40 | public File renameFile(File file, String newName) { 41 | File newFile = new File(file.getParentFile() + "/" + newName); 42 | if (newFile.exists()) newFile.delete(); // Replace existing 43 | file.renameTo(newFile); 44 | file.delete(); // Delete old 45 | return newFile; 46 | } 47 | 48 | public File pathToFile(String path) { 49 | File file = null; 50 | if (path.contains("./")) 51 | path = path.replace("./", GD.WORKING_DIR.getAbsolutePath() + File.separator); 52 | if (path.contains(".\\")) 53 | path = path.replace(".\\", GD.WORKING_DIR.getAbsolutePath() + File.separator); 54 | if (!path.contains("/") && !path.contains("\\")) 55 | path = GD.WORKING_DIR.getAbsolutePath() + File.separator + path; 56 | 57 | return new File(path); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/UtilsJar.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import com.osiris.autoplug.client.Main; 12 | import com.osiris.autoplug.client.configs.GeneralConfig; 13 | import com.osiris.dyml.exceptions.*; 14 | import org.jetbrains.annotations.NotNull; 15 | 16 | import java.io.File; 17 | import java.io.IOException; 18 | import java.net.URISyntaxException; 19 | import java.net.URL; 20 | import java.net.URLClassLoader; 21 | import java.util.ArrayList; 22 | import java.util.Collection; 23 | import java.util.Properties; 24 | 25 | public class UtilsJar { 26 | 27 | public File determineServerJar() throws YamlWriterException, NotLoadedException, IOException, IllegalKeyException, DuplicateKeyException, YamlReaderException, IllegalListException { 28 | GeneralConfig generalConfig = new GeneralConfig(); 29 | String path = generalConfig.server_start_command.asString(); 30 | if (path == null) return null; 31 | if (path.contains("-jar ")) { // jar file 32 | path = path.substring(path.indexOf("-jar ")); 33 | if (path.codePointAt(5) == '"') { 34 | for (int i = 6; i < path.length(); i++) { 35 | char c = (char) path.codePointAt(i); 36 | if (c == '\"') return new File(path.substring(6, i)); 37 | } 38 | throw new RuntimeException("Server jar path started with \" but didn't finish with another \"!" + path); 39 | } else { 40 | return new File(path.split(" ")[1]); 41 | } 42 | } else { // probably exe file 43 | if (path.startsWith("\"")) { 44 | for (int i = 1; i < path.length(); i++) { 45 | char c = (char) path.codePointAt(i); 46 | if (c == '\"') return new File(path.substring(1, i)); 47 | } 48 | throw new RuntimeException("Server jar path started with \" but didn't finish with another \"! " + path); 49 | } else { 50 | return new File(path.split(" ")[0]); 51 | } 52 | } 53 | } 54 | 55 | /** 56 | * Returns the currently running jar file. 57 | */ 58 | public File getThisJar() throws URISyntaxException { 59 | String path = Main.class 60 | .getProtectionDomain() 61 | .getCodeSource() 62 | .getLocation() 63 | .toURI() 64 | .getPath(); 65 | return new File(path); 66 | } 67 | 68 | @NotNull 69 | public Properties getThisJarsAutoPlugProperties() throws Exception { 70 | return getAutoPlugPropertiesFromJar(Main.class 71 | .getProtectionDomain() 72 | .getCodeSource() 73 | .getLocation() 74 | .toURI() 75 | .getPath()); 76 | } 77 | 78 | @NotNull 79 | public Properties getAutoPlugPropertiesFromJar(@NotNull String path) throws Exception { 80 | return getPropertiesFromJar(path, "autoplug"); 81 | } 82 | 83 | /** 84 | * This creates an URLClassLoader so we can access the autoplug.properties file inside the jar and then returns the properties file. 85 | * 86 | * @param path The jars path 87 | * @param propertiesFileName Properties file name without its .properties extension. 88 | * @return autoplug.properties 89 | * @throws Exception 90 | */ 91 | @NotNull 92 | public Properties getPropertiesFromJar(@NotNull String path, String propertiesFileName) throws Exception { 93 | File file = new File(path); // The properties file 94 | if (file.exists()) { 95 | Collection urls = new ArrayList(); 96 | urls.add(file.toURI().toURL()); 97 | URLClassLoader fileClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()])); 98 | 99 | java.io.InputStream is = fileClassLoader.getResourceAsStream(propertiesFileName + ".properties"); 100 | java.util.Properties p = new java.util.Properties(); 101 | p.load(is); 102 | return p; 103 | } else 104 | throw new Exception("Couldn't find the properties file at: " + path); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/UtilsLists.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import java.util.Arrays; 12 | import java.util.List; 13 | 14 | public class UtilsLists { 15 | public String toString(List list) { 16 | return Arrays.toString(list.toArray()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/UtilsLogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import com.osiris.jlib.logger.AL; 12 | 13 | import java.util.Arrays; 14 | import java.util.Scanner; 15 | import java.util.concurrent.atomic.AtomicBoolean; 16 | 17 | 18 | public class UtilsLogger { 19 | 20 | public void animatedPrintln(String s) throws InterruptedException { 21 | System.out.print(" > "); 22 | AtomicBoolean skip = new AtomicBoolean(false); 23 | Scanner scanner = new Scanner(System.in); 24 | Thread t = new Thread(() -> { 25 | scanner.nextLine(); 26 | skip.set(true); 27 | }); 28 | t.start(); 29 | 30 | for (int i = 0; i < s.length(); i++) { 31 | if (skip.get()) { 32 | for (int j = i; j < s.length(); j++) { 33 | System.out.print(s.charAt(j)); 34 | } 35 | System.out.flush(); 36 | break; 37 | } 38 | System.out.print(s.charAt(i)); 39 | System.out.flush(); 40 | Thread.sleep(50); 41 | } 42 | System.out.println(); 43 | t.interrupt(); 44 | } 45 | 46 | public String expectInput(String... expectedInput) { 47 | String line; 48 | Scanner scanner = new Scanner(System.in); 49 | while (true) { 50 | line = scanner.nextLine(); 51 | if (expectedInput == null || expectedInput.length == 0) { 52 | return line; 53 | } 54 | boolean equals = false; 55 | for (String s : 56 | expectedInput) { 57 | if (line.equals(s)) { 58 | equals = true; 59 | break; 60 | } 61 | } 62 | if (equals) { 63 | return line; 64 | } else AL.warn("Your input was wrong. Please try again. Expected: " + Arrays.toString(expectedInput)); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/UtilsMap.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import java.util.ArrayList; 12 | import java.util.LinkedHashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | public class UtilsMap { 17 | 18 | public void printStringMap(Map map) { 19 | System.out.println(getStringMapFormatted(map)); 20 | } 21 | 22 | /** 23 | * Returns a formatted String representation of the map object. 24 | */ 25 | public String getStringMapFormatted(Map map) { 26 | String result = ""; 27 | for (K key : 28 | map.keySet()) { 29 | result = result + "key: " + key + " value: " + map.get(key) + "\n"; 30 | } 31 | return result; 32 | } 33 | 34 | /** 35 | * Returns a new sorted entries list that is sorted by value in ascending (small to big) order. 36 | */ 37 | public > List> getEntriesListSortedByValue(Map map) { 38 | List> list = new ArrayList<>(map.entrySet()); 39 | list.sort(Map.Entry.comparingByValue()); 40 | 41 | return new ArrayList<>(list); 42 | } 43 | 44 | /** 45 | * Returns a new sorted map that is sorted by value in ascending (small to big) order. 46 | */ 47 | public > Map getSortedByValue(Map map) { 48 | List> list = new ArrayList<>(map.entrySet()); 49 | list.sort(Map.Entry.comparingByValue()); 50 | 51 | Map result = new LinkedHashMap<>(); 52 | for (Map.Entry entry : list) { 53 | result.put(entry.getKey(), entry.getValue()); 54 | } 55 | return result; 56 | } 57 | 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/UtilsRandom.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | public class UtilsRandom { 12 | public String generateNewKey(int length) { 13 | // chose a Character random from this String 14 | String AlphaNumericString = 15 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 16 | + "0123456789" 17 | + "abcdefghijklmnopqrstuvxyz"; 18 | 19 | // create StringBuffer size of AlphaNumericString 20 | StringBuilder sb = new StringBuilder(length); 21 | 22 | for (int i = 0; i < length; i++) { 23 | 24 | // generate a random number between 25 | // 0 to AlphaNumericString variable length 26 | int index 27 | = (int) (AlphaNumericString.length() 28 | * Math.random()); 29 | 30 | // add Character one by one in end of sb 31 | sb.append(AlphaNumericString 32 | .charAt(index)); 33 | } 34 | 35 | return sb.toString(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/UtilsString.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import java.util.ArrayList; 12 | import java.util.Arrays; 13 | import java.util.List; 14 | 15 | public class UtilsString { 16 | 17 | /** 18 | * Input: "Hello there" my "friend"
19 | * Output list: ["Hello there", my, "friend"]
20 | * Spaces inside quotes are ignored.
21 | */ 22 | public List splitBySpacesAndQuotes(String s) throws Exception { 23 | List list = new ArrayList<>(); 24 | int countQuotes = 0; 25 | for (int i = 0; i < s.length(); i++) { 26 | char c = (char) s.codePointAt(i); 27 | if (c == '\"') countQuotes++; 28 | } 29 | if (countQuotes == 0) { 30 | list.addAll(Arrays.asList(s.split(" "))); 31 | return list; 32 | } 33 | if (countQuotes % 2 == 1) throw new Exception("Open quote found! Please close the quote in: " + s); 34 | // "bla""bla" 35 | // "bla" "bla" 36 | // bla "bla" 37 | // "bla" bla 38 | // "bla" bla "bla" 39 | boolean isInQuote = false; 40 | int iLastOpenQuote = 0; 41 | int iLastSpace = 0; 42 | for (int i = 0; i < s.length(); i++) { 43 | char c = (char) s.codePointAt(i); 44 | if (c == ' ') { 45 | if (!isInQuote) { 46 | if (iLastSpace != -1) 47 | list.add(s.substring(iLastSpace, i).trim()); 48 | } 49 | iLastSpace = i; 50 | } 51 | if (c == '\"') 52 | if (!isInQuote) { 53 | iLastOpenQuote = i; 54 | isInQuote = true; 55 | } else { 56 | list.add(s.substring(iLastOpenQuote, i + 1).trim()); 57 | isInQuote = false; 58 | iLastSpace = -1; 59 | } 60 | } 61 | if (iLastSpace != -1) list.add(s.substring(iLastSpace).trim()); // Add last one if there is 62 | return list; 63 | } 64 | 65 | /** 66 | * Checks each char from the source (left to right) 67 | * string with the provided query char.
68 | * If there is a match exits the loop and returns it.
69 | * If loopCount is bigger than one continues until the last char of the string. 70 | */ 71 | public int indexOf(String source, char query, int loopCount) { 72 | int lastMatch = 0; 73 | for (int j = 0; j < loopCount; j++) { 74 | for (int i = lastMatch; i < source.length(); i++) { 75 | if (source.charAt(i) == query) { 76 | lastMatch = i; 77 | break; 78 | } 79 | } 80 | } 81 | return lastMatch; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/UtilsURL.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | public class UtilsURL { 12 | 13 | public String clean(String url) { 14 | return url.replaceAll("\"", "%22"); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/io/AsyncInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils.io; 10 | 11 | import java.io.BufferedReader; 12 | import java.io.IOException; 13 | import java.io.InputStream; 14 | import java.io.InputStreamReader; 15 | import java.util.List; 16 | import java.util.concurrent.CopyOnWriteArrayList; 17 | import java.util.function.Consumer; 18 | 19 | public class AsyncInputStream { 20 | private final InputStream inputStream; 21 | private final Thread thread; 22 | public List> listeners = new CopyOnWriteArrayList<>(); 23 | 24 | public AsyncInputStream(InputStream inputStream) { 25 | this.inputStream = inputStream; 26 | 27 | Object o = this; 28 | thread = new Thread(() -> { 29 | String line = ""; 30 | try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { 31 | while ((line = br.readLine()) != null) { 32 | for (Consumer listener : 33 | listeners) { 34 | listener.accept(line); 35 | } 36 | } 37 | } catch (IOException e) { 38 | System.err.println("Error in thread for object '" + o + "' Details:"); 39 | e.printStackTrace(); 40 | } 41 | }); 42 | thread.start(); 43 | } 44 | 45 | public InputStream getInputStream() { 46 | return inputStream; 47 | } 48 | 49 | public Thread getThread() { 50 | return thread; 51 | } 52 | 53 | /** 54 | * Returns the list of listeners.
55 | * Each listener listens for write line events.
56 | */ 57 | public List> getListeners() { 58 | return listeners; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/io/AsyncReader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils.io; 10 | 11 | import java.io.BufferedReader; 12 | import java.io.IOException; 13 | import java.io.InputStream; 14 | import java.io.InputStreamReader; 15 | import java.util.Arrays; 16 | import java.util.List; 17 | import java.util.concurrent.CopyOnWriteArrayList; 18 | import java.util.function.Consumer; 19 | 20 | public class AsyncReader { 21 | public final InputStream inputStream; 22 | public final Thread thread; 23 | public List> listeners = new CopyOnWriteArrayList<>(); 24 | 25 | @SafeVarargs 26 | public AsyncReader(InputStream inputStream, Consumer... listeners) { 27 | this.inputStream = inputStream; 28 | if (listeners != null && listeners.length != 0) this.listeners.addAll(Arrays.asList(listeners)); 29 | Object o = this; 30 | thread = new Thread(() -> { 31 | String line = ""; 32 | try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { 33 | while ((line = br.readLine()) != null) { 34 | for (Consumer listener : 35 | this.listeners) { 36 | listener.accept(line); 37 | } 38 | } 39 | } catch (IOException e) { 40 | System.out.println("Error in thread for object '" + o + "' Details:"); 41 | e.printStackTrace(); 42 | } 43 | }); 44 | thread.start(); 45 | } 46 | } -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/io/MyTeeOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils.io; 10 | 11 | import org.jetbrains.annotations.NotNull; 12 | import org.jetbrains.annotations.Nullable; 13 | 14 | import java.io.IOException; 15 | import java.io.OutputStream; 16 | 17 | /** 18 | * Only used for testing. 19 | * Original TeeOutputStream seems to be more performant. 20 | */ 21 | public final class MyTeeOutputStream extends OutputStream { 22 | 23 | @Nullable 24 | private final OutputStream out; 25 | @Nullable 26 | private final OutputStream tee; 27 | 28 | public MyTeeOutputStream(@Nullable OutputStream out, @Nullable OutputStream tee) { 29 | if (out == null) 30 | throw new NullPointerException(); 31 | else if (tee == null) 32 | throw new NullPointerException(); 33 | 34 | this.out = out; 35 | this.tee = tee; 36 | } 37 | 38 | 39 | @Override 40 | public void write(int b) throws IOException { 41 | out.write(b); 42 | tee.write(b); 43 | } 44 | 45 | @Override 46 | public void write(@NotNull byte[] b) throws IOException { 47 | out.write(b); 48 | tee.write(b); 49 | } 50 | 51 | @Override 52 | public void write(@NotNull byte[] b, int off, int len) throws IOException { 53 | out.write(b, off, len); 54 | tee.write(b, off, len); 55 | } 56 | 57 | @Override 58 | public void flush() throws IOException { 59 | out.flush(); 60 | tee.flush(); 61 | } 62 | 63 | @Override 64 | public void close() throws IOException { 65 | try { 66 | out.close(); 67 | } finally { 68 | tee.close(); 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/io/NonBlockingPipedInputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils.io; 10 | 11 | import com.osiris.jlib.logger.AL; 12 | import org.jetbrains.annotations.NotNull; 13 | 14 | import java.io.BufferedReader; 15 | import java.io.InputStreamReader; 16 | import java.io.PipedInputStream; 17 | import java.util.List; 18 | import java.util.concurrent.CopyOnWriteArrayList; 19 | 20 | public class NonBlockingPipedInputStream extends PipedInputStream { // PipedInputStream 21 | @NotNull 22 | private final Thread thread; 23 | /** 24 | * Add actions to this list, which get run after a line has been written. 25 | * Contains the line as parameter. 26 | */ 27 | @NotNull 28 | public List> actionsOnWriteLineEvent = new CopyOnWriteArrayList<>(); 29 | 30 | /** 31 | * Creates and starts a new {@link Thread}, that reads the {@link PipedInputStream} 32 | * and fires an event every time a full line was written to it. 33 | * To listen for those events, add the action that should be run to the {@link #actionsOnWriteLineEvent} list. 34 | */ 35 | public NonBlockingPipedInputStream() { 36 | thread = new Thread(() -> { 37 | try { 38 | BufferedReader reader = new BufferedReader(new InputStreamReader(this)); 39 | String line; 40 | while ((line = reader.readLine()) != null) { 41 | String finalLine = line; 42 | actionsOnWriteLineEvent.forEach(action -> action.executeOnEvent(finalLine)); 43 | } 44 | } catch (Exception e) { 45 | AL.warn(e); 46 | } 47 | }); 48 | thread.start(); 49 | 50 | } 51 | 52 | @NotNull 53 | public Thread getThread() { 54 | return thread; 55 | } 56 | 57 | public interface WriteLineEvent { 58 | void executeOnEvent(L l); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/io/UFDataIn.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils.io; 10 | 11 | import com.osiris.jlib.logger.AL; 12 | import com.osiris.jlib.network.UFDataOut; 13 | 14 | import javax.naming.LimitExceededException; 15 | import java.io.*; 16 | import java.nio.charset.StandardCharsets; 17 | import java.util.Base64; 18 | 19 | /** 20 | * ULTRA FAST DATA INPUTSTREAM! 21 | */ 22 | public class UFDataIn { 23 | private final DataInputStream dis; 24 | 25 | public UFDataIn(InputStream inputStream) { 26 | this.dis = new DataInputStream(inputStream); 27 | } 28 | 29 | public String readLine() throws IOException { 30 | return dis.readUTF(); 31 | } 32 | 33 | public boolean readBoolean() throws IOException { 34 | return dis.readBoolean(); 35 | } 36 | 37 | /** 38 | * @param file write receiving data to this file. 39 | */ 40 | public void readFile(File file) throws IOException { 41 | try (FileOutputStream out = new FileOutputStream(file)) { 42 | readStream(out); 43 | } 44 | } 45 | 46 | /** 47 | * @param file write receiving data to this file. 48 | * @param maxBytes set to -1 if no limit wanted. 49 | */ 50 | public void readFile(File file, long maxBytes) throws IOException, LimitExceededException { 51 | try (FileOutputStream out = new FileOutputStream(file)) { 52 | readStream(out, maxBytes); 53 | } 54 | } 55 | 56 | /** 57 | * @param out write receiving data to this stream. 58 | */ 59 | public void readStream(OutputStream out) throws IOException { 60 | try{ 61 | readStream(out, -1); 62 | } catch (LimitExceededException e) { // Not excepted to happen since no limit 63 | throw new RuntimeException(e); 64 | } 65 | } 66 | 67 | /** 68 | * @param out write receiving data to this stream. 69 | * @param maxBytes set to -1 if no limit wanted. 70 | */ 71 | public void readStream(OutputStream out, long maxBytes) throws IOException, LimitExceededException { 72 | /* 73 | * Handling Non-Text Data: If the input stream 74 | * contains binary data (like images or other non-text files), 75 | * Base64 encoding allows this data to be represented as text, 76 | * which can then be safely written using writeUTF. 77 | * By using Base64 encoding, we ensure that the binary data is first converted 78 | * to a string representation that can be safely written using writeUTF. 79 | */ 80 | Base64.Decoder decoder = Base64.getDecoder(); 81 | long countBytesRead = 0; 82 | int count; 83 | byte[] buffer = new byte[8192]; // or 4096, or more 84 | String buffer_s = ""; 85 | while (!(buffer_s = dis.readUTF()).equals(UFDataOut.EOF)) { 86 | buffer = decoder.decode(buffer_s.getBytes(StandardCharsets.UTF_8)); 87 | count = buffer.length; 88 | 89 | countBytesRead += count; 90 | if (maxBytes >= 0 && countBytesRead > maxBytes) { 91 | throw new LimitExceededException("Exceeded the maximum allowed bytes: " + maxBytes); 92 | } 93 | out.write(buffer, 0, count); 94 | out.flush(); 95 | } 96 | AL.debug(this.getClass(), "Bytes read: " + countBytesRead); 97 | //read("\u001a") // Not needed here since already read above by read() 98 | } 99 | 100 | public byte readByte() throws IOException { 101 | return dis.readByte(); 102 | } 103 | 104 | public short readShort() throws IOException { 105 | return dis.readShort(); 106 | } 107 | 108 | public int readInt() throws IOException { 109 | return dis.readInt(); 110 | } 111 | 112 | public long readLong() throws IOException { 113 | return dis.readLong(); 114 | } 115 | 116 | public float readFloat() throws IOException { 117 | return dis.readFloat(); 118 | } 119 | 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/io/UFDataOut.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils.io; 10 | 11 | import com.osiris.jlib.logger.AL; 12 | 13 | import java.io.*; 14 | import java.nio.charset.StandardCharsets; 15 | import java.util.Arrays; 16 | import java.util.Base64; 17 | 18 | /** 19 | * ULTRA FAST DATA OUTPUTSTREAM! 20 | */ 21 | public class UFDataOut extends DataOutputStream { 22 | 23 | public UFDataOut(OutputStream outputStream) { 24 | super(outputStream); 25 | } 26 | 27 | public void writeLine(String s) throws IOException { 28 | writeUTF(s); 29 | } 30 | 31 | public static final String EOF = new String("EOF_MARKER_1714941978".getBytes(StandardCharsets.UTF_8), 32 | StandardCharsets.UTF_8); 33 | 34 | /** 35 | * @param file read data from this file and send it. 36 | */ 37 | public void writeFile(File file) throws IOException { 38 | try (FileInputStream in = new FileInputStream(file)) { 39 | writeStream(in); 40 | } 41 | } 42 | 43 | /** 44 | * @param in read data from this stream and send it. 45 | */ 46 | public void writeStream(InputStream in) throws IOException { 47 | /* 48 | * Handling Non-Text Data: If the input stream 49 | * contains binary data (like images or other non-text files), 50 | * Base64 encoding allows this data to be represented as text, 51 | * which can then be safely written using writeUTF. 52 | * It converts binary data into a set of 64 characters that are safe for text-based transmission. 53 | * By using Base64 encoding, we ensure that the binary data is first converted 54 | * to a string representation that can be safely written using writeUTF. 55 | */ 56 | Base64.Encoder encoder = Base64.getEncoder(); 57 | long totalCount = 0; 58 | int count; 59 | byte[] buffer = new byte[8192]; // or 4096, or more 60 | while ((count = in.read(buffer)) > 0) { 61 | if (count == buffer.length) writeUTF(new String(encoder.encode(buffer), StandardCharsets.UTF_8)); 62 | else writeUTF(new String(encoder.encode(Arrays.copyOf(buffer, count)), StandardCharsets.UTF_8)); 63 | flush(); 64 | totalCount += count; 65 | } 66 | writeUTF(EOF); // Write since not included above 67 | AL.debug(this.getClass(), "Bytes sent: " + totalCount); 68 | flush(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/tasks/CoolDownReport.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils.tasks; 10 | 11 | public class CoolDownReport { 12 | private long msPassedSinceLast; 13 | private long msCoolDown; 14 | 15 | public CoolDownReport(long msPassedSinceLast, long msCoolDown) { 16 | this.msPassedSinceLast = msPassedSinceLast; 17 | this.msCoolDown = msCoolDown; 18 | } 19 | 20 | public long getMsRemaining() { 21 | return msCoolDown - msPassedSinceLast; 22 | } 23 | 24 | public boolean isInCoolDown() { 25 | return msPassedSinceLast < msCoolDown; 26 | } 27 | 28 | public long getMsPassedSinceLast() { 29 | return msPassedSinceLast; 30 | } 31 | 32 | public void setMsPassedSinceLast(long msPassedSinceLast) { 33 | this.msPassedSinceLast = msPassedSinceLast; 34 | } 35 | 36 | public long getMsCoolDown() { 37 | return msCoolDown; 38 | } 39 | 40 | public void setMsCoolDown(long msCoolDown) { 41 | this.msCoolDown = msCoolDown; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/tasks/MyBThreadManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils.tasks; 10 | 11 | import com.osiris.betterthread.BThreadManager; 12 | import com.osiris.betterthread.BThreadPrinter; 13 | 14 | import java.util.concurrent.atomic.AtomicReference; 15 | 16 | 17 | public class MyBThreadManager { 18 | public static final AtomicReference lastCreatedPrinter = new AtomicReference<>(); 19 | public BThreadManager manager; 20 | public BThreadPrinter printer; 21 | 22 | public MyBThreadManager(BThreadManager manager, BThreadPrinter printer) { 23 | this.manager = manager; 24 | this.printer = printer; 25 | lastCreatedPrinter.set(printer); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/tasks/MyDate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils.tasks; 10 | 11 | import com.osiris.betterthread.BThread; 12 | import com.osiris.betterthread.BThreadManager; 13 | import com.osiris.betterthread.BThreadPrinter; 14 | import com.osiris.betterthread.modules.Date; 15 | import org.fusesource.jansi.Ansi; 16 | 17 | import java.time.LocalDateTime; 18 | 19 | import static org.fusesource.jansi.Ansi.ansi; 20 | 21 | public class MyDate extends Date { 22 | @Override 23 | public void append(BThreadManager manager, BThreadPrinter printer, BThread thread, StringBuilder line) { 24 | line.append(ansi().bg(Ansi.Color.WHITE).fgBlack().a("[" + dateFormatter.format(LocalDateTime.now()) + "]") 25 | .reset()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/terminal/AsyncTerminal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils.terminal; 10 | 11 | import com.osiris.autoplug.client.utils.io.AsyncReader; 12 | import org.jline.utils.OSUtils; 13 | 14 | import java.io.File; 15 | import java.io.IOException; 16 | import java.io.InputStream; 17 | import java.io.OutputStream; 18 | import java.nio.charset.StandardCharsets; 19 | import java.util.function.Consumer; 20 | 21 | public class AsyncTerminal implements AutoCloseable { 22 | public Process process; 23 | public AsyncReader readerLines; 24 | public AsyncReader readerErrLines; 25 | public OutputStream out; 26 | 27 | public AsyncTerminal(File workingDir, Consumer onLineReceived, 28 | Consumer onErrorLineReceived, String... commands) throws IOException { 29 | if (workingDir == null) workingDir = new File(System.getProperty("user.dir")); 30 | Process p; 31 | if (OSUtils.IS_WINDOWS) { 32 | try { // Try powershell first, use cmd as fallback 33 | p = new ProcessBuilder("powershell").directory(workingDir).start(); 34 | if (!p.isAlive()) throw new Exception(); 35 | } catch (Exception e) { 36 | p = new ProcessBuilder("cmd").directory(workingDir).start(); 37 | } 38 | } else { // Unix based system, like Linux, Mac etc... 39 | try { // Try bash first, use sh as fallback 40 | p = new ProcessBuilder("/bin/bash").directory(workingDir).start(); 41 | if (!p.isAlive()) throw new Exception(); 42 | } catch (Exception e) { 43 | p = new ProcessBuilder("/bin/sh").directory(workingDir).start(); 44 | } 45 | } 46 | this.process = p; 47 | InputStream in = process.getInputStream(); 48 | InputStream inErr = process.getErrorStream(); 49 | this.out = process.getOutputStream(); 50 | this.readerLines = new AsyncReader(in, onLineReceived); 51 | this.readerErrLines = new AsyncReader(inErr, onErrorLineReceived); 52 | sendCommands(commands); 53 | } 54 | 55 | public void sendCommands(String... commands) throws IOException { 56 | if (commands != null) 57 | for (String command : 58 | commands) { 59 | out.write((command + "\n").getBytes(StandardCharsets.UTF_8)); 60 | out.flush(); 61 | } 62 | } 63 | 64 | @Override 65 | public void close() { 66 | process.destroy(); 67 | process.destroyForcibly(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/osiris/autoplug/client/utils/terminal/Terminal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils.terminal; 10 | 11 | import org.jline.utils.OSUtils; 12 | 13 | import java.io.File; 14 | import java.io.IOException; 15 | import java.io.OutputStream; 16 | import java.nio.charset.StandardCharsets; 17 | 18 | public class Terminal { 19 | public Process process; 20 | 21 | public Terminal(File workingDir, String... commands) throws IOException { 22 | if (workingDir == null) workingDir = new File(System.getProperty("user.dir")); 23 | Process p; 24 | if (OSUtils.IS_WINDOWS) { 25 | try { // Try powershell first, use cmd as fallback 26 | p = new ProcessBuilder("powershell").directory(workingDir).start(); 27 | if (!p.isAlive()) throw new Exception(); 28 | } catch (Exception e) { 29 | p = new ProcessBuilder("cmd").directory(workingDir).start(); 30 | } 31 | } else { // Unix based system, like Linux, Mac etc... 32 | try { // Try bash first, use sh as fallback 33 | p = new ProcessBuilder("/bin/bash").directory(workingDir).start(); 34 | if (!p.isAlive()) throw new Exception(); 35 | } catch (Exception e) { 36 | p = new ProcessBuilder("/bin/sh").directory(workingDir).start(); 37 | } 38 | } 39 | this.process = p; 40 | OutputStream out = process.getOutputStream(); 41 | if (commands != null) 42 | for (String command : 43 | commands) { 44 | out.write((command + "\n").getBytes(StandardCharsets.UTF_8)); 45 | out.flush(); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/resources/autoplug-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Osiris-Team/AutoPlug-Client/b23647c9ad705775c6ca38a011279af23c57eaf4/src/main/resources/autoplug-icon.png -------------------------------------------------------------------------------- /src/main/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/main/resources/quartz.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (c) 2021 Osiris-Team. 3 | # All rights reserved. 4 | # 5 | # This software is copyrighted work, licensed under the terms 6 | # of the MIT-License. Consult the "LICENSE" file for details. 7 | # 8 | org.quartz.scheduler.instanceName=TaskScheduler 9 | org.quartz.threadPool.threadCount=10 10 | org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore -------------------------------------------------------------------------------- /src/test/java/com/osiris/autoplug/client/SystemCheckerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client; 10 | 11 | import org.junit.jupiter.api.Test; 12 | 13 | import java.net.HttpURLConnection; 14 | import java.net.InetAddress; 15 | import java.net.URL; 16 | 17 | class SystemCheckerTest { 18 | 19 | @Test 20 | void checkInternetAccessMethod1() throws Exception { 21 | boolean reachable = InetAddress.getByName("www.google.com").isReachable(10000); 22 | if (!reachable) throw new Exception("Failed to reach www.google.com!"); 23 | } 24 | 25 | @Test 26 | void checkInternetAccessMethod2() throws Exception { 27 | HttpURLConnection connection = (HttpURLConnection) new URL("https://www.google.com").openConnection(); 28 | connection.connect(); 29 | connection.disconnect(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/com/osiris/autoplug/client/UtilsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client; 10 | 11 | import com.osiris.autoplug.client.configs.GeneralConfig; 12 | import com.osiris.autoplug.client.utils.GD; 13 | import com.osiris.autoplug.client.utils.tasks.MyBThreadManager; 14 | import com.osiris.autoplug.client.utils.tasks.UtilsTasks; 15 | import com.osiris.betterthread.exceptions.JLineLinkException; 16 | import com.osiris.dyml.exceptions.*; 17 | import com.osiris.jlib.logger.AL; 18 | 19 | import java.io.File; 20 | import java.io.IOException; 21 | 22 | /** 23 | * Utils for tests. 24 | */ 25 | public class UtilsTest { 26 | public static MyBThreadManager createManagerWithDisplayer() throws JLineLinkException, NotLoadedException, YamlReaderException, YamlWriterException, IOException, IllegalKeyException, DuplicateKeyException, IllegalListException { 27 | return new UtilsTasks().createManagerAndPrinter(); 28 | } 29 | 30 | public static void init() throws IOException { 31 | initLogger(); 32 | initDefaults(); 33 | } 34 | 35 | private static void initDefaults() throws IOException { 36 | GD.VERSION = "AutoPlug-Client Test-Version"; 37 | GD.WORKING_DIR = new File(System.getProperty("user.dir") + "/test"); 38 | System.setProperty("user.dir", GD.WORKING_DIR.getAbsolutePath()); 39 | GD.DOWNLOADS_DIR = new File(GD.WORKING_DIR + "/downloads"); 40 | GD.DOWNLOADS_DIR.mkdirs(); 41 | 42 | File serverJar = new File(GD.WORKING_DIR + "/server.jar"); 43 | GeneralConfig config = null; 44 | try { 45 | config = new GeneralConfig(); 46 | config.lockFile(); 47 | config.load(); 48 | config.server_start_command.setValues("java -jar \"" + serverJar + "\""); 49 | config.save(); 50 | } catch (Exception e) { 51 | if (config != null) config.unlockFile(); 52 | throw new RuntimeException(e); 53 | } finally { 54 | if (config != null) config.unlockFile(); 55 | } 56 | 57 | if (!serverJar.exists()) serverJar.createNewFile(); 58 | } 59 | 60 | private static void initLogger() { 61 | File logFile = new File(System.getProperty("user.dir") + "/logs/latest.log"); 62 | logFile.getParentFile().mkdirs(); 63 | new AL().start("AL", true, logFile, false, false); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/test/java/com/osiris/autoplug/client/bugs/VersionBugs.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.bugs; 10 | 11 | import com.osiris.autoplug.client.UtilsTest; 12 | import com.osiris.jlib.search.Version; 13 | import org.junit.jupiter.api.Test; 14 | 15 | import java.io.IOException; 16 | 17 | public class VersionBugs { 18 | 19 | @Test 20 | void test() throws IOException { 21 | UtilsTest.init(); 22 | Version.isLatestBigger("0", "10000000000000000000000000000000000"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/osiris/autoplug/client/tasks/updater/TaskPluginDownloadTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2021-2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater; 10 | 11 | import com.osiris.autoplug.client.UtilsTest; 12 | import com.osiris.autoplug.client.tasks.updater.plugins.TaskPluginDownload; 13 | import com.osiris.autoplug.client.tasks.updater.plugins.TaskPluginsUpdater; 14 | import com.osiris.betterthread.BThreadManager; 15 | import com.osiris.betterthread.BThreadPrinter; 16 | import com.osiris.dyml.utils.UtilsTimeStopper; 17 | import com.osiris.jlib.logger.AL; 18 | 19 | import java.io.File; 20 | 21 | class TaskPluginDownloadTest { 22 | 23 | @org.junit.jupiter.api.Test 24 | void pluginDownloadTest() throws Exception { 25 | UtilsTest.init(); 26 | BThreadManager man = new BThreadManager(); 27 | BThreadPrinter printer = new BThreadPrinter(man); 28 | printer.start(); 29 | 30 | UtilsTimeStopper timeStopper = new UtilsTimeStopper(); 31 | timeStopper.start(); 32 | TaskPluginDownload download = new TaskPluginDownload("Downloader", man, 33 | "Autorank", 34 | "LATEST", "https://api.spiget.org/v2/resources/3239/download", "MANUAL", 35 | new File("" + System.getProperty("user.dir") + "/src/main/test/TestPlugin.jar")); 36 | download.start(); 37 | 38 | TaskPluginDownload download1 = new TaskPluginDownload("Downloader", man, 39 | "UltimateChat", 40 | "LATEST", "https://api.spiget.org/v2/resources/23767/download", "MANUAL", 41 | new File("" + System.getProperty("user.dir") + "/src/main/test/TestPlugin.jar")); 42 | download1.start(); 43 | 44 | TaskPluginDownload download2 = new TaskPluginDownload("Downloader", man, 45 | "ViaRewind", 46 | "LATEST", "https://api.spiget.org/v2/resources/52109/download", "MANUAL", 47 | new File("" + System.getProperty("user.dir") + "/src/main/test/TestPlugin.jar")); 48 | download2.start(); 49 | 50 | TaskPluginsUpdater taskPluginsUpdater = new TaskPluginsUpdater("PluginsUpdater", man); 51 | taskPluginsUpdater.start(); 52 | 53 | while (!download.isFinished() || !download1.isFinished() || !download2.isFinished()) 54 | Thread.sleep(100); 55 | timeStopper.stop(); 56 | AL.info("Time took to finish download tasks: " + timeStopper.getFormattedSeconds() + " seconds!"); 57 | } 58 | } -------------------------------------------------------------------------------- /src/test/java/com/osiris/autoplug/client/tasks/updater/TestPluginUpdaters.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater; 10 | 11 | import com.osiris.autoplug.client.UtilsTest; 12 | import com.osiris.autoplug.client.tasks.updater.mods.ModrinthAPI; 13 | import com.osiris.autoplug.client.tasks.updater.plugins.MinecraftPlugin; 14 | import com.osiris.autoplug.client.tasks.updater.search.CustomCheckURL; 15 | import com.osiris.autoplug.client.tasks.updater.search.SearchResult; 16 | import org.junit.jupiter.api.Test; 17 | 18 | import java.io.IOException; 19 | 20 | import static org.junit.jupiter.api.Assertions.assertSame; 21 | 22 | 23 | class TestPluginUpdaters { 24 | @Test 25 | void testCustom() throws IOException { 26 | UtilsTest.init(); 27 | MinecraftPlugin pl = new MinecraftPlugin("./plugins/", "Chunky", "0.0.0", "pop4959", 0, 0, null); 28 | pl.customCheckURL = "https://api.modrinth.com/v2/project/chunky/version"; 29 | pl.customDownloadURL = "https://cdn.modrinth.com/data/fALzjamp/versions/dPliWter/Chunky-1.4.16.jar"; 30 | SearchResult sr = new CustomCheckURL().doCustomCheck(pl.customCheckURL, pl.getVersion()); 31 | assertSame(SearchResult.Type.UPDATE_AVAILABLE, sr.type); 32 | } 33 | 34 | @Test 35 | void testModrinth() throws IOException { 36 | UtilsTest.init(); 37 | MinecraftPlugin pl = new MinecraftPlugin("./plugins/", "BMMarker", "0.0.0", "Miraculixx", 0, 0, null); 38 | pl.modrinthId = "a8UoyV2h"; 39 | SearchResult sr = new ModrinthAPI().searchUpdatePlugin(pl, "1.21.1"); 40 | assertSame(SearchResult.Type.UPDATE_AVAILABLE, sr.type); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/com/osiris/autoplug/client/tasks/updater/server/TaskServerUpdaterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022-2024 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.tasks.updater.server; 10 | 11 | import com.osiris.autoplug.client.UtilsTest; 12 | import com.osiris.autoplug.client.configs.UpdaterConfig; 13 | import com.osiris.autoplug.client.utils.tasks.MyBThreadManager; 14 | import com.osiris.betterthread.BWarning; 15 | import com.osiris.jlib.logger.AL; 16 | 17 | import java.util.List; 18 | 19 | import static org.junit.jupiter.api.Assertions.assertEquals; 20 | import static org.junit.jupiter.api.Assertions.assertTrue; 21 | 22 | class TaskServerUpdaterTest { 23 | 24 | private void defaultTest(String serverSoftware) throws Exception { 25 | defaultTest(serverSoftware, null); 26 | } 27 | 28 | private void defaultTest(String serverSoftware, String version) throws Exception { 29 | if (true) return; // TODO RE-ENABLE TESTS 30 | if (version == null) version = "1.18.2"; 31 | UtilsTest.init(); 32 | MyBThreadManager maMan = UtilsTest.createManagerWithDisplayer(); 33 | UpdaterConfig updaterConfig = new UpdaterConfig(); 34 | updaterConfig.load(); 35 | updaterConfig.server_updater.setValues("true"); 36 | updaterConfig.server_updater_profile.setValues("AUTOMATIC"); 37 | updaterConfig.server_software.setValues(serverSoftware); 38 | updaterConfig.server_updater_version.setValues(version); 39 | updaterConfig.server_build_id.setValues(""); 40 | updaterConfig.save(); 41 | new TaskServerUpdater("ServerUpdater", maMan.manager) 42 | .start(); // Do not run too often because of rest API limits 43 | maMan.printer.join(); // Wait for completion 44 | List warnings = maMan.manager.getAllWarnings(); 45 | for (BWarning warning : warnings) { 46 | AL.warn(warning.getExtraInfo(), warning.getException()); 47 | } 48 | assertEquals(0, warnings.size()); 49 | assertTrue(maMan.manager.getAll().get(0).isSuccess()); 50 | } 51 | 52 | @org.junit.jupiter.api.Test 53 | void testSpigot() throws Exception { 54 | defaultTest("spigot", "1.16.5"); 55 | } 56 | 57 | @org.junit.jupiter.api.Test 58 | void testWindSpigot() throws Exception { 59 | defaultTest("windspigot"); 60 | } 61 | 62 | @org.junit.jupiter.api.Test 63 | void testBungeeCord() throws Exception { 64 | defaultTest("bungeecord"); 65 | } 66 | 67 | @org.junit.jupiter.api.Test 68 | void testPaper() throws Exception { 69 | defaultTest("paper"); 70 | } 71 | 72 | @org.junit.jupiter.api.Test 73 | void testWaterfall() throws Exception { 74 | defaultTest("waterfall", "1.18"); 75 | } 76 | 77 | @org.junit.jupiter.api.Test 78 | void testVelocity() throws Exception { 79 | defaultTest("velocity", "3.1.1"); 80 | } 81 | 82 | @org.junit.jupiter.api.Test 83 | void testTravertine() throws Exception { 84 | defaultTest("travertine", "1.16"); 85 | } 86 | 87 | @org.junit.jupiter.api.Test 88 | void testPurpur() throws Exception { 89 | defaultTest("purpur"); 90 | } 91 | 92 | @org.junit.jupiter.api.Test 93 | void testFabric() throws Exception { 94 | defaultTest("fabric"); 95 | } 96 | 97 | @org.junit.jupiter.api.Test 98 | void testSpongeVanilla() throws Exception { 99 | defaultTest("spongevanilla"); 100 | } 101 | 102 | @org.junit.jupiter.api.Test 103 | void testSpongeForge() throws Exception { 104 | defaultTest("spongeforge", "1.16.5"); 105 | } 106 | 107 | @org.junit.jupiter.api.Test 108 | void testPatina() throws Exception { 109 | defaultTest("patina"); 110 | } 111 | 112 | @org.junit.jupiter.api.Test 113 | void testPufferfish() throws Exception { 114 | defaultTest("pufferfish"); 115 | } 116 | 117 | @org.junit.jupiter.api.Test 118 | void testMirai() throws Exception { 119 | defaultTest("mirai"); 120 | } 121 | 122 | @org.junit.jupiter.api.Test 123 | void testPearl() throws Exception { 124 | defaultTest("pearl"); 125 | } 126 | 127 | 128 | } -------------------------------------------------------------------------------- /src/test/java/com/osiris/autoplug/client/utils/SteamCMDTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import com.osiris.autoplug.client.UtilsTest; 12 | import org.junit.jupiter.api.Test; 13 | 14 | import java.io.IOException; 15 | 16 | class SteamCMDTest { 17 | 18 | @Test 19 | void installSteamcmd() throws IOException { 20 | UtilsTest.init(); 21 | new SteamCMD().installIfNeeded(); 22 | } 23 | } -------------------------------------------------------------------------------- /src/test/java/com/osiris/autoplug/client/utils/UtilsFileTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import org.junit.jupiter.api.Test; 12 | 13 | import static org.junit.jupiter.api.Assertions.assertEquals; 14 | 15 | class UtilsFileTest { 16 | 17 | @Test 18 | void getSafeFileName() { 19 | assertEquals("", new UtilsFile().getValidFileName("/\\\\<>:\"'|*?\u0000\u0001\u0002\u0010\n")); 20 | } 21 | } -------------------------------------------------------------------------------- /src/test/java/com/osiris/autoplug/client/utils/UtilsLoggerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import org.junit.jupiter.api.Test; 12 | 13 | import java.io.IOException; 14 | 15 | class UtilsLoggerTest { 16 | 17 | @Test 18 | void animatedPrintln() throws InterruptedException, IOException { 19 | UtilsLogger uLog = new UtilsLogger(); 20 | uLog.animatedPrintln("Thank you for installing AutoPlug!"); 21 | // DOESNT WORK IN INTELLIJ CONSOLE 22 | } 23 | } -------------------------------------------------------------------------------- /src/test/java/com/osiris/autoplug/client/utils/UtilsMapTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import org.junit.jupiter.api.Test; 12 | 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | class UtilsMapTest { 17 | @Test 18 | void sortByValue() { 19 | UtilsMap utilsMap = new UtilsMap(); 20 | Map map = new HashMap<>(); 21 | map.put("fifty", 50); 22 | map.put("null", 0); 23 | map.put("ten", 10); 24 | utilsMap.printStringMap(utilsMap.getSortedByValue(map)); 25 | } 26 | } -------------------------------------------------------------------------------- /src/test/java/com/osiris/autoplug/client/utils/UtilsStringTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022 Osiris-Team. 3 | * All rights reserved. 4 | * 5 | * This software is copyrighted work, licensed under the terms 6 | * of the MIT-License. Consult the "LICENSE" file for details. 7 | */ 8 | 9 | package com.osiris.autoplug.client.utils; 10 | 11 | import org.junit.jupiter.api.Test; 12 | 13 | import java.util.List; 14 | 15 | import static org.junit.jupiter.api.Assertions.assertEquals; 16 | 17 | class UtilsStringTest { 18 | 19 | @Test 20 | void splitBySpacesAndQuotes() throws Exception { 21 | List l; 22 | l = new UtilsString().splitBySpacesAndQuotes("hello there"); 23 | assertEquals(2, l.size()); 24 | l = new UtilsString().splitBySpacesAndQuotes("\"Hello there\" my friend \"!\""); 25 | assertEquals(4, l.size()); 26 | l = new UtilsString().splitBySpacesAndQuotes("hello there \"mate\""); 27 | assertEquals(3, l.size()); 28 | assertEquals("hello", l.get(0)); 29 | assertEquals("there", l.get(1)); 30 | assertEquals("\"mate\"", l.get(2)); 31 | l = new UtilsString().splitBySpacesAndQuotes("" + 32 | "\"D:\\Coding\\JAVA\\AutoPlug-Client\\AP-TEST-SERVER\\autoplug\\system\\jre\\jdk-17.0.1+12\\bin\\java.exe\"" + 33 | " -Xms2G" + 34 | " -Xmx2G" + 35 | " -jar" + 36 | " D:\\Coding\\JAVA\\AutoPlug-Client\\AP-TEST-SERVER\\fabric-server-mc.1.18.2-loader.0.13.3-launcher.0.10.2.jar" + 37 | " nogui"); 38 | assertEquals(6, l.size()); 39 | } 40 | } --------------------------------------------------------------------------------