├── .gitignore ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── feature_request.md │ └── bug_report.md └── workflows │ ├── maven-javadoc.yml │ ├── maven-publish.yml │ └── publish.yml ├── ServerLinksZ.iml ├── src └── main │ ├── resources │ ├── links.yml │ ├── plugin.yml │ ├── lang │ │ ├── zh-TW.yml │ │ ├── zh-CN.yml │ │ ├── en-US.yml │ │ ├── ru-RU.yml │ │ └── de-DE.yml │ └── config.yml │ └── java │ └── com │ └── zetaplugins │ └── serverlinksz │ ├── util │ ├── EventManager.java │ ├── bStats │ │ ├── CustomCharts.java │ │ └── Metrics.java │ ├── LanguageManager.java │ ├── MessageUtils.java │ ├── CommandManager.java │ └── LinkManager.java │ ├── commands │ ├── maincommand │ │ ├── subcommands │ │ │ ├── HelpSubCommand.java │ │ │ ├── ReloadSubCommand.java │ │ │ ├── RemoveSubCommand.java │ │ │ └── AddSubCommand.java │ │ ├── MainCommandHandler.java │ │ └── MainTabCompleter.java │ ├── SubCommand.java │ ├── CommandUtils.java │ └── LinkCommand.java │ └── ServerLinksZ.java ├── pom.xml ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | dependency-reduced-pom.xml 3 | .idea/ -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: true 2 | contact_links: 3 | - name: Discord Support 4 | url: https://strassburger.org/discord 5 | about: Please ask and answer questions here. 6 | -------------------------------------------------------------------------------- /ServerLinksZ.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | PAPER 8 | 9 | 1 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/main/resources/links.yml: -------------------------------------------------------------------------------- 1 | discord: 2 | name: "<#7289da>&lDiscord" 3 | url: "https://strassburger.org/discord" 4 | type: CUSTOM 5 | allowCommand: true 6 | website: 7 | name: "<#7cd770>&lWebsite" 8 | url: "https://modrinth.com/plugin/serverlinksz" 9 | type: CUSTOM 10 | allowCommand: false 11 | bugreport: 12 | name: "<#ff746c>&lReport a bug" 13 | url: "https://example.com/issues" 14 | # The type can be any of ANNOUNCEMENTS, COMMUNITY, COMMUNITY_GUIDELINES, FEEDBACK, FORUMS, NEWS, REPORT_BUG, STATUS, SUPPORT, WEBSITE, CUSTOM 15 | # CUSTOM will display the name in the links menu. Anything else will display a client side defined label. 16 | type: REPORT_BUG 17 | allowCommand: true -------------------------------------------------------------------------------- /.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 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /src/main/resources/plugin.yml: -------------------------------------------------------------------------------- 1 | name: ServerLinksZ 2 | version: '${project.version}' 3 | main: com.zetaplugins.serverlinksz.ServerLinksZ 4 | api-version: '1.21' 5 | authors: [ Kartoffelchipss ] 6 | description: A simple plugin to add Links to your server 7 | website: strassburger.org 8 | 9 | commands: 10 | serverlinksz: 11 | description: Main command for ServerLinksZ 12 | aliases: 13 | - sl 14 | - slz 15 | - serverlinks 16 | slzdebug: 17 | description: Debug command for ServerLinksZ 18 | permission: serverlinksz.admin 19 | link: 20 | description: Get a link 21 | 22 | permissions: 23 | serverlinksz.admin: 24 | default: op 25 | description: Allows the user to manage the plugin -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/util/EventManager.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.util; 2 | 3 | import org.bukkit.event.Listener; 4 | import com.zetaplugins.serverlinksz.ServerLinksZ; 5 | 6 | public class EventManager { 7 | private final ServerLinksZ plugin; 8 | 9 | public EventManager(ServerLinksZ plugin) { 10 | this.plugin = plugin; 11 | } 12 | 13 | /** 14 | * Registers all listeners 15 | */ 16 | public void registerListeners() { 17 | } 18 | 19 | /** 20 | * Registers a listener 21 | * 22 | * @param listener The listener to register 23 | */ 24 | private void registerListener(Listener listener) { 25 | plugin.getServer().getPluginManager().registerEvents(listener, plugin); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Server Setup** 27 | - Server Software: [e.g. PaperMC, SpigotMC] 28 | - Minecraft Version [e.g. 1.19.4] 29 | - Plugin Version [e.g. 1.1.22] 30 | 31 | **Additional context** 32 | Add any other context about the problem here. 33 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/commands/maincommand/subcommands/HelpSubCommand.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.commands.maincommand.subcommands; 2 | 3 | import org.bukkit.command.CommandSender; 4 | import com.zetaplugins.serverlinksz.commands.SubCommand; 5 | import com.zetaplugins.serverlinksz.util.MessageUtils; 6 | 7 | public class HelpSubCommand implements SubCommand { 8 | @Override 9 | public boolean execute(CommandSender sender, String[] args) { 10 | sender.sendMessage(MessageUtils.getAndFormatMsg(false, "help", "&7HELP")); 11 | return false; 12 | } 13 | 14 | @Override 15 | public String getUsage() { 16 | return "/serverlinksz help"; 17 | } 18 | 19 | @Override 20 | public boolean hasPermission(CommandSender sender) { 21 | return true; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/commands/SubCommand.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.commands; 2 | 3 | import org.bukkit.command.CommandSender; 4 | 5 | public interface SubCommand { 6 | /** 7 | * Execute the sub-command logic. 8 | * 9 | * @param sender Command sender 10 | * @param args Arguments passed to the command 11 | * @return true if successful, false otherwise 12 | */ 13 | boolean execute(CommandSender sender, String[] args); 14 | 15 | /** 16 | * Provides the usage description for the sub-command. 17 | * 18 | * @return A string representing command usage 19 | */ 20 | String getUsage(); 21 | 22 | /** 23 | * Checks if a sender has permission to use the sub-command. 24 | * 25 | * @param sender The command sender 26 | * @return True if the sender has permission 27 | */ 28 | boolean hasPermission(CommandSender sender); 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/util/bStats/CustomCharts.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.util.bStats; 2 | 3 | import com.zetaplugins.serverlinksz.ServerLinksZ; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import java.util.Set; 8 | 9 | public class CustomCharts { 10 | public static Metrics.CustomChart getLanguageChart(ServerLinksZ plugin) { 11 | return new Metrics.SimplePie("language", () -> plugin.getConfig().getString("lang")); 12 | } 13 | 14 | public static Metrics.CustomChart getLinksChart(ServerLinksZ plugin) { 15 | return new Metrics.AdvancedPie("links", () -> { 16 | Set links = plugin.getLinkManager().getLinkKeys(); 17 | 18 | Map optionCounts = new HashMap<>(); 19 | 20 | for (String link : links) { 21 | optionCounts.put(link, optionCounts.getOrDefault(link, 0) + 1); 22 | } 23 | 24 | return optionCounts; 25 | }); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/resources/lang/zh-TW.yml: -------------------------------------------------------------------------------- 1 | prefix: "&7[&lServerLinksZ&7]" 2 | help: "\n &8> <#00BFFF>ServerLinksZ\n\n&7你可以使用 /sl 指令來新增和移除伺服器連結,但建議你在 /plugins/ServerLinksZ/links.yml 檔案中編輯它們。\n\n <#00BFFF>支援 Discord\n" 3 | linkCommand: "&7-> %name% &r&7<-" 4 | rejoinHint: "<#E9D502>⚠ 如要更新伺服器連結,請重新加入伺服器!" 5 | moreConfigOptionsHint: "<#E9D502>⚠ 如需更多設定選項,請參考 config.yml 檔案!" 6 | invalidUrlError: "&c網址無效!" 7 | urlProtocolError: "&c網址必須以「http://」或「https://」開頭!" 8 | versionMsg: "&7你目前使用的是版本 <#00BFFF>%version%&7" 9 | noPermissionError: "&c你沒有權限使用此功能!" 10 | addLinkMsg: "&7已成功新增 ID 為 <#00BFFF>%id%&7 的連結!" 11 | removeLinkMsg: "&7已成功移除 ID 為 <#00BFFF>%id%&7 的連結!" 12 | linkCommandDisabled: "&c連結指令已停用!" 13 | linkCcommandNotAllowed: "&c你無法透過指令存取此連結!" 14 | linkNotFound: "&c找不到 ID 為 %id% 的連結!" 15 | -------------------------------------------------------------------------------- /src/main/resources/lang/zh-CN.yml: -------------------------------------------------------------------------------- 1 | prefix: "&7[&lServerLinksZ&7]" 2 | help: "\n &8> <#00BFFF>ServerLinksZ\n\n&7您可以使用 /sl 命令添加或移除服务器链接, 但建议对links.yml文件进行编辑 ,文件位于 /plugins/ServerLinksZ/links.yml 下.\n\n <#00BFFF>Support Discord\n" 3 | linkCommand: "&7-> %name% &r&7<-" 4 | rejoinHint: "<#E9D502>⚠ 为了更新服务器链接列表,请您重新进入服务器" 5 | moreConfigOptionsHint: "<#E9D502>⚠ 有关更多配置选项,请参阅config.yml文件!" 6 | invalidUrlError: "&c无效的URL!" 7 | urlProtocolError: "&cURL应该以 'http://' 或 'https://' 开头!" 8 | versionMsg: "&7你现在正使用 <#00BFFF>%version%&7版本" 9 | noPermissionError: "&c你没有权限使用这个!" 10 | addLinkMsg: "&7成功添加id为<#00BFFF>%id%&7服务器链接!" 11 | removeLinkMsg: "&7成功移除id为<#00BFFF>%id%&7服务器链接!" 12 | linkCommandDisabled: "&clink命令是禁用状态!" 13 | linkCcommandNotAllowed: "&c不允许您通过命令访问此链接!" 14 | linkNotFound: "&c未发现id为%id%&c 的链接!" -------------------------------------------------------------------------------- /.github/workflows/maven-javadoc.yml: -------------------------------------------------------------------------------- 1 | name: Deploy Maven Javadocs to GitHub Pages 2 | 3 | on: 4 | release: 5 | types: [published] 6 | workflow_dispatch: 7 | 8 | jobs: 9 | build-and-deploy: 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - name: Checkout code 14 | uses: actions/checkout@v4 15 | 16 | - name: Set up JDK 17 | uses: actions/setup-java@v4 18 | with: 19 | distribution: 'temurin' 20 | java-version: '21' 21 | 22 | - name: Cache Maven repository 23 | uses: actions/cache@v4 24 | with: 25 | path: ~/.m2 26 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 27 | restore-keys: | 28 | ${{ runner.os }}-maven- 29 | 30 | - name: Build Javadocs 31 | run: mvn clean javadoc:javadoc 32 | 33 | - name: Add CNAME file 34 | run: | 35 | echo "jd.slz.zetaplugins.com" > target/reports/apidocs/CNAME 36 | 37 | - name: Deploy to GitHub Pages 38 | uses: peaceiris/actions-gh-pages@v4 39 | with: 40 | github_token: ${{ secrets.GITHUB_TOKEN }} 41 | publish_dir: target/reports/apidocs 42 | -------------------------------------------------------------------------------- /src/main/resources/lang/en-US.yml: -------------------------------------------------------------------------------- 1 | prefix: "&7[&lServerLinksZ&7]" 2 | help: "\n &8> <#00BFFF>ServerLinksZ\n\n&7You can add and remove ServerLinks using the /sl command, tho it is recommended to edit them in the links.yml file under /plugins/ServerLinksZ/links.yml.\n\n <#00BFFF>Support Discord\n" 3 | linkCommand: "&7-> %name% &r&7<-" 4 | rejoinHint: "<#E9D502>⚠ To update the Serverlinks, please rejoin the server!" 5 | moreConfigOptionsHint: "<#E9D502>⚠ For more configuration options, please refer to the config.yml file!" 6 | invalidUrlError: "&cThe URL is invalid!" 7 | urlProtocolError: "&cThe URL must start with 'http://' or 'https://'!" 8 | versionMsg: "&7You are using version <#00BFFF>%version%&7" 9 | noPermissionError: "&cYou don't have permission to use this!" 10 | addLinkMsg: "&7Successfully added link with id <#00BFFF>%id%&7!" 11 | removeLinkMsg: "&7Successfully removed link with id <#00BFFF>%id%&7!" 12 | linkCommandDisabled: "&cThe link command is disabled!" 13 | linkCcommandNotAllowed: "&cYou are not allowed to access this link via a command!" 14 | linkNotFound: "&cLink with id %id%&c not found!" 15 | restartServerToRegisterCustomCommands: "<#E9D502>⚠ Please restart the server to register the custom commands!" -------------------------------------------------------------------------------- /src/main/resources/lang/ru-RU.yml: -------------------------------------------------------------------------------- 1 | prefix: "&7[&lServerLinksZ&7]" 2 | help: "\n &8> <#00BFFF>ServerLinksZ\n\n&7 Вы можете добавить Ссылки Сервера используя команду /sl, однако рекомендуется редактировать их в файле links.yml по пути /plugins/ServerLinksZ/links.yml.\n\n <#00BFFF>Сервер Discord\n" 3 | linkCommand: "&7-> %name% &r&7<-" 4 | rejoinHint: "<#E9D502>⚠ Для обновления Ссылок Сервера требуется перезайти на сервер!" 5 | moreConfigOptionsHint: "<#E9D502>⚠ Для более точной настройки плагина, перейдите в файл config.yml!" 6 | invalidUrlError: "&cСсылка недействительна!" 7 | urlProtocolError: "&cСсылка должна начинаться с 'http://' или 'https://'!" 8 | versionMsg: "&7Вы используете версию <#00BFFF>%version%&7" 9 | noPermissionError: "&cУ вас недостаточно прав!" 10 | addLinkMsg: "&7Успешно создана с id <#00BFFF>%id%&7!" 11 | removeLinkMsg: "&7Успешно удалена ссылка с id <#00BFFF>%id%&7!" 12 | linkCommandDisabled: "&cКоманда /link выключена!" 13 | linkCcommandNotAllowed: "&cВы не можете получить доступ к ссылке, используя команду!" 14 | linkNotFound: "&cСсылка с id %id%&c не найдена!" 15 | restartServerToRegisterCustomCommands: "<#E9D502>⚠ Пожалуйста, перезапустите сервер для зарегистрации пользовательских команд!" 16 | -------------------------------------------------------------------------------- /src/main/resources/config.yml: -------------------------------------------------------------------------------- 1 | # _____ _ _ _ ______ 2 | # / ____| | | (_) | | |___ / 3 | # | (___ ___ _ ____ _____ _ __ | | _ _ __ | | _____ / / 4 | # \___ \ / _ \ '__\ \ / / _ \ '__| | | | | '_ \| |/ / __| / / 5 | # ____) | __/ | \ V / __/ | | |____| | | | | <\__ \ / /__ 6 | # |_____/ \___|_| \_/ \___|_| |______|_|_| |_|_|\_\___/ /_____| 7 | 8 | 9 | # === COLOR CODES === 10 | 11 | # This plugin supports old color codes like: &c, &l, &o, etc. 12 | # It also supports MiniMessage, a more advanced way to format messages: 13 | # https://docs.advntr.dev/minimessage/format.html 14 | # With MiniMessage, you can add HEX colors, gradients, hover and click events, etc. 15 | 16 | 17 | # === GENERAL SETTINGS === 18 | 19 | # Set the language to any code found in the "lang" folder (don't add the .yml extension) 20 | # You can add your own language files. Use https://github.com/KartoffelChipss/ServerLinksZ/tree/main/src/main/resources/lang/en-US.yml as a template 21 | # If you want to share your language file, either create a pull request on GitHub or use GitLocalize: https://gitlocalize.com/repo/9890 22 | # | en-US | de-DE | zh-CN | ru-RU | zh-TW 23 | lang: "en-US" 24 | 25 | # Wether to show hints when using commands 26 | hints: true 27 | 28 | # Add a /link command to view the links 29 | linkCommand: true 30 | 31 | # [!!!] You can configure the links in the links.yml file! -------------------------------------------------------------------------------- /src/main/resources/lang/de-DE.yml: -------------------------------------------------------------------------------- 1 | prefix: "&7[&lServerLinksZ&7]" 2 | help: "\n &8> <#00BFFF>ServerLinksZ\n\n&7Du kannst ServerLinks mit dem /sl Befehl hinzufügen oder entfernen, es ist allerdings empfohlen die links.yml Datei unter /plugins/ServerLinksZ/links.yml zu nutzen.\n\n <#00BFFF>Support Discord\n" 3 | linkCommand: "&7-> %name% &r&7<-" 4 | rejoinHint: "<#E9D502>⚠ Um die Serverlinks zu aktualisieren, bitte den Server neu betreten!" 5 | moreConfigOptionsHint: "<#E9D502>⚠ Für mehr Konfigurationsoptionen, bitte die config.yml Datei benutzen!" 6 | invalidUrlError: "&cDie URL ist ungültig!" 7 | urlProtocolError: "&cDie URL muss mit 'http://' oder 'https://' beginnen!" 8 | versionMsg: "&7Du benutzt Version <#00BFFF>%version%&7" 9 | noPermissionError: "&cDu hast keine Berechtigung, dies zu tun!" 10 | addLinkMsg: "&7Erfolgreich Link mit der ID <#00BFFF>%id%&7 hinzugefügt!" 11 | removeLinkMsg: "&7Erfolgreich Link mit der ID <#00BFFF>%id%&7 entfernt!" 12 | linkCommandDisabled: "&cDer Link Befehl ist deaktiviert!" 13 | linkCcommandNotAllowed: "&cDu darfst nicht auf diesen Link über einen Befehl zugreifen!" 14 | linkNotFound: "&cLink mit der ID %id%&c nicht gefunden!" 15 | restartServerToRegisterCustomCommands: "<#E9D502>⚠ Bitte starte den Server neu, um die benutzerdefinierten Befehle zu registrieren!" -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/commands/maincommand/subcommands/ReloadSubCommand.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.commands.maincommand.subcommands; 2 | 3 | import org.bukkit.command.CommandSender; 4 | import com.zetaplugins.serverlinksz.ServerLinksZ; 5 | import com.zetaplugins.serverlinksz.commands.CommandUtils; 6 | import com.zetaplugins.serverlinksz.commands.SubCommand; 7 | import com.zetaplugins.serverlinksz.util.MessageUtils; 8 | 9 | public class ReloadSubCommand implements SubCommand { 10 | private final ServerLinksZ plugin; 11 | 12 | public ReloadSubCommand(ServerLinksZ plugin) { 13 | this.plugin = plugin; 14 | } 15 | 16 | @Override 17 | public boolean execute(CommandSender sender, String[] args) { 18 | if (!hasPermission(sender)) { 19 | CommandUtils.throwPermissionError(sender); 20 | return false; 21 | } 22 | 23 | boolean showHints = plugin.getConfig().getBoolean("hints"); 24 | 25 | plugin.reloadConfig(); 26 | plugin.getLanguageManager().reload(); 27 | plugin.getLinkManager().updateLinks(); 28 | sender.sendMessage(MessageUtils.getAndFormatMsg( 29 | true, 30 | "reloadMsg", 31 | "&7Successfully reloaded the plugin!" 32 | )); 33 | if (showHints) sender.sendMessage(MessageUtils.getAndFormatMsg( 34 | false, 35 | "restartServerToRegisterCustomCommands", 36 | "<#E9D502>⚠ Please restart the server to register the custom commands!" 37 | )); 38 | return false; 39 | } 40 | 41 | @Override 42 | public String getUsage() { 43 | return "/serverlinksz reload"; 44 | } 45 | 46 | @Override 47 | public boolean hasPermission(CommandSender sender) { 48 | return sender.hasPermission("serverlinksz.admin"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /.github/workflows/maven-publish.yml: -------------------------------------------------------------------------------- 1 | name: Deploy Artifact to Maven Repository 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - name: Checkout code 13 | uses: actions/checkout@v3 14 | 15 | - name: Set up JDK 16 | uses: actions/setup-java@v3 17 | with: 18 | distribution: 'temurin' 19 | java-version: '21' 20 | cache: 'maven' 21 | 22 | - name: Build plugin 23 | run: mvn clean package -DskipTests 24 | 25 | - name: Extract Maven coordinates 26 | id: meta 27 | run: | 28 | echo "groupId=$(mvn help:evaluate -Dexpression=project.groupId -q -DforceStdout)" >> $GITHUB_OUTPUT 29 | echo "artifactId=$(mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout)" >> $GITHUB_OUTPUT 30 | echo "version=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)" >> $GITHUB_OUTPUT 31 | 32 | - name: Set up SSH 33 | run: | 34 | mkdir -p ~/.ssh 35 | echo "${{ secrets.MVN_REPO_SSH_KEY }}" > ~/.ssh/id_rsa 36 | chmod 600 ~/.ssh/id_rsa 37 | ssh-keyscan -H ${{ secrets.MVN_REPO_SSH_HOST }} >> ~/.ssh/known_hosts 38 | 39 | - name: Upload artifact to VPS 40 | run: | 41 | GROUP_PATH=$(echo "${{ steps.meta.outputs.groupId }}" | sed 's/\./\//g') 42 | ARTIFACT_ID=${{ steps.meta.outputs.artifactId }} 43 | VERSION=${{ steps.meta.outputs.version }} 44 | REMOTE_DIR="${{ secrets.REMOTE_MAVEN_PATH }}/$GROUP_PATH/$ARTIFACT_ID/$VERSION" 45 | 46 | mkdir -p checksums 47 | cp target/$ARTIFACT_ID-$VERSION.jar checksums/ 48 | cp pom.xml checksums/$ARTIFACT_ID-$VERSION.pom 49 | 50 | cd checksums 51 | 52 | # Generate checksum files (hash only, no filename) 53 | for file in *.{jar,pom}; do 54 | sha1sum "$file" | awk '{print $1}' > "$file.sha1" 55 | md5sum "$file" | awk '{print $1}' > "$file.md5" 56 | done 57 | 58 | echo "Creating remote directory: $REMOTE_DIR" 59 | ssh ${{ secrets.MVN_REPO_SSH_USER }}@${{ secrets.MVN_REPO_SSH_HOST }} "mkdir -p $REMOTE_DIR" 60 | 61 | echo "Uploading JAR, POM, and checksums" 62 | scp * ${{ secrets.MVN_REPO_SSH_USER }}@${{ secrets.MVN_REPO_SSH_HOST }}:$REMOTE_DIR/ 63 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/commands/maincommand/MainCommandHandler.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.commands.maincommand; 2 | 3 | import org.bukkit.command.Command; 4 | import org.bukkit.command.CommandExecutor; 5 | import org.bukkit.command.CommandSender; 6 | import org.jetbrains.annotations.NotNull; 7 | import com.zetaplugins.serverlinksz.ServerLinksZ; 8 | import com.zetaplugins.serverlinksz.commands.SubCommand; 9 | import com.zetaplugins.serverlinksz.commands.maincommand.subcommands.AddSubCommand; 10 | import com.zetaplugins.serverlinksz.commands.maincommand.subcommands.HelpSubCommand; 11 | import com.zetaplugins.serverlinksz.commands.maincommand.subcommands.ReloadSubCommand; 12 | import com.zetaplugins.serverlinksz.commands.maincommand.subcommands.RemoveSubCommand; 13 | import com.zetaplugins.serverlinksz.util.MessageUtils; 14 | 15 | import java.util.HashMap; 16 | import java.util.Map; 17 | 18 | public class MainCommandHandler implements CommandExecutor { 19 | private final ServerLinksZ plugin; 20 | private final Map commands = new HashMap<>(); 21 | 22 | public MainCommandHandler(ServerLinksZ plugin) { 23 | this.plugin = plugin; 24 | 25 | commands.put("help", new HelpSubCommand()); 26 | commands.put("reload", new ReloadSubCommand(plugin)); 27 | commands.put("add", new AddSubCommand(plugin)); 28 | commands.put("remove", new RemoveSubCommand(plugin)); 29 | } 30 | 31 | @Override 32 | public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { 33 | if (args.length == 0) { 34 | sendVersionMessage(sender); 35 | return true; 36 | } 37 | 38 | SubCommand subCommand = commands.get(args[0]); 39 | 40 | if (subCommand == null) { 41 | sendVersionMessage(sender); 42 | return true; 43 | } 44 | 45 | return subCommand.execute(sender, args); 46 | } 47 | 48 | private void sendVersionMessage(CommandSender sender) { 49 | sender.sendMessage(MessageUtils.getAndFormatMsg( 50 | true, 51 | "versionMsg", 52 | "FALLBACK&7You are using version %version%", 53 | new MessageUtils.Replaceable( 54 | "%version%", 55 | plugin.getDescription().getVersion() 56 | ) 57 | )); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/ServerLinksZ.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz; 2 | 3 | import com.zetaplugins.serverlinksz.util.CommandManager; 4 | import com.zetaplugins.serverlinksz.util.EventManager; 5 | import com.zetaplugins.serverlinksz.util.LanguageManager; 6 | import com.zetaplugins.serverlinksz.util.LinkManager; 7 | import org.bukkit.plugin.java.JavaPlugin; 8 | import com.zetaplugins.serverlinksz.util.bStats.CustomCharts; 9 | import com.zetaplugins.serverlinksz.util.bStats.Metrics; 10 | 11 | import java.io.File; 12 | 13 | public final class ServerLinksZ extends JavaPlugin { 14 | private CommandManager commandManager; 15 | private LanguageManager languageManager; 16 | private EventManager eventManager; 17 | private LinkManager linkManager; 18 | 19 | @Override 20 | public void onEnable() { 21 | getConfig().options().copyDefaults(true); 22 | saveDefaultConfig(); 23 | 24 | languageManager = new LanguageManager(this); 25 | 26 | linkManager = new LinkManager(this); 27 | linkManager.updateLinks(); 28 | 29 | eventManager = new EventManager(this); 30 | eventManager.registerListeners(); 31 | commandManager = new CommandManager(this); 32 | commandManager.registerCommands(); 33 | 34 | initializeBStats(); 35 | 36 | getLogger().info("ServerLinksZ has been enabled!"); 37 | } 38 | 39 | @Override 40 | public void onDisable() { 41 | getLogger().info("ServerLinksZ has been disabled!"); 42 | } 43 | 44 | public static ServerLinksZ getInstance() { 45 | return JavaPlugin.getPlugin(ServerLinksZ.class); 46 | } 47 | 48 | public LanguageManager getLanguageManager() { 49 | return languageManager; 50 | } 51 | 52 | public CommandManager getCommandManager() { 53 | return commandManager; 54 | } 55 | 56 | public EventManager getEventManager() { 57 | return eventManager; 58 | } 59 | 60 | public LinkManager getLinkManager() { 61 | return linkManager; 62 | } 63 | 64 | private void initializeBStats() { 65 | final int pluginId = 22795; 66 | Metrics metrics = new Metrics(this, pluginId); 67 | 68 | metrics.addCustomChart(CustomCharts.getLanguageChart(this)); 69 | metrics.addCustomChart(CustomCharts.getLinksChart(this)); 70 | } 71 | 72 | public File getPluginFile() { 73 | return this.getFile(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/commands/maincommand/subcommands/RemoveSubCommand.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.commands.maincommand.subcommands; 2 | 3 | import org.bukkit.command.CommandSender; 4 | import com.zetaplugins.serverlinksz.ServerLinksZ; 5 | import com.zetaplugins.serverlinksz.commands.CommandUtils; 6 | import com.zetaplugins.serverlinksz.commands.SubCommand; 7 | import com.zetaplugins.serverlinksz.util.MessageUtils; 8 | 9 | public class RemoveSubCommand implements SubCommand { 10 | private final ServerLinksZ plugin; 11 | 12 | public RemoveSubCommand(ServerLinksZ plugin) { 13 | this.plugin = plugin; 14 | } 15 | 16 | @Override 17 | public boolean execute(CommandSender sender, String[] args) { 18 | if (!hasPermission(sender)) { 19 | CommandUtils.throwPermissionError(sender); 20 | return false; 21 | } 22 | 23 | if (args.length < 2) { 24 | CommandUtils.throwUsageError(sender, getUsage()); 25 | return false; 26 | } 27 | 28 | boolean showHints = plugin.getConfig().getBoolean("hints"); 29 | 30 | String id = args[1]; 31 | 32 | boolean linkExists = plugin.getLinkManager().getLinkKeys().contains(id); 33 | 34 | if (!linkExists) { 35 | sender.sendMessage(MessageUtils.getAndFormatMsg( 36 | false, 37 | "linkNotFound", 38 | "&cLink with id %id%&c not found!", 39 | new MessageUtils.Replaceable("%id%", id) 40 | )); 41 | return false; 42 | } 43 | 44 | plugin.getLinkManager().removeLink(id); 45 | sender.sendMessage(MessageUtils.getAndFormatMsg( 46 | true, 47 | "removeLinkMsg", 48 | "&7Successfully removed link with id %id%!", 49 | new MessageUtils.Replaceable("%id%", id) 50 | )); 51 | if (showHints) sender.sendMessage(MessageUtils.getAndFormatMsg( 52 | false, 53 | "rejoinHint", 54 | "<#E9D502>⚠ To update the Serverlinks, please rejoin the server!" 55 | )); 56 | return true; 57 | } 58 | 59 | @Override 60 | public String getUsage() { 61 | return "/serverlinksz remove "; 62 | } 63 | 64 | @Override 65 | public boolean hasPermission(CommandSender sender) { 66 | return sender.hasPermission("serverlinksz.admin"); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/commands/CommandUtils.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.commands; 2 | 3 | import net.kyori.adventure.text.Component; 4 | import org.bukkit.command.CommandSender; 5 | import com.zetaplugins.serverlinksz.util.MessageUtils; 6 | 7 | import java.util.List; 8 | import java.util.Set; 9 | import java.util.stream.Collectors; 10 | 11 | public class CommandUtils { 12 | /** 13 | * Throws a usage error message to the sender. 14 | * @param sender Command sender 15 | * @param usage Usage string 16 | */ 17 | public static void throwUsageError(CommandSender sender, String usage) { 18 | Component msg = MessageUtils.getAndFormatMsg(false, "usageError", "&cUsage: %usage%", new MessageUtils.Replaceable("%usage%", usage)); 19 | sender.sendMessage(msg); 20 | } 21 | 22 | /** 23 | * Throws a permission error message to the sender. 24 | * @param sender Command sender 25 | */ 26 | public static void throwPermissionError(CommandSender sender) { 27 | Component msg = MessageUtils.getAndFormatMsg(false, "noPermissionError", "&cYou don't have permission to use this!"); 28 | sender.sendMessage(msg); 29 | } 30 | 31 | /** 32 | * Gets a list of options that start with the input 33 | * @param options The list of options 34 | * @param input The input 35 | * @return A list of options that start with the input 36 | */ 37 | public static List getDisplayOptions(List options, String input) { 38 | return options.stream() 39 | .filter(option -> startsWithIgnoreCase(option, input)) 40 | .collect(Collectors.toList()); 41 | } 42 | 43 | /** 44 | * Gets a list of options that start with the input 45 | * @param options The list of options 46 | * @param input The input 47 | * @return A list of options that start with the input 48 | */ 49 | public static List getDisplayOptions(Set options, String input) { 50 | return options.stream() 51 | .filter(option -> startsWithIgnoreCase(option, input)) 52 | .collect(Collectors.toList()); 53 | } 54 | 55 | /** 56 | * Checks if a string starts with another string (case-insensitive) 57 | * @param str The string 58 | * @param prefix The prefix 59 | * @return True if the string starts with the prefix, false otherwise 60 | */ 61 | private static boolean startsWithIgnoreCase(String str, String prefix) { 62 | return str.regionMatches(true, 0, prefix, 0, prefix.length()); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to Modrinth and GitHub Releases 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | outputs: 11 | version: ${{ steps.get_version.outputs.version }} 12 | steps: 13 | - name: Checkout repository 14 | uses: actions/checkout@v4 15 | 16 | - name: Set up JDK 17 | uses: actions/setup-java@v4 18 | with: 19 | distribution: 'temurin' 20 | java-version: '21' 21 | cache: 'maven' 22 | 23 | - name: Cache Maven repository 24 | uses: actions/cache@v3 25 | with: 26 | path: ~/.m2 27 | key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} 28 | restore-keys: | 29 | ${{ runner.os }}-maven- 30 | 31 | - name: Get release version 32 | id: get_version 33 | run: echo "version=${{ github.event.release.tag_name }}" >> $GITHUB_ENV 34 | 35 | - name: Set version from release tag 36 | run: mvn -B versions:set -DnewVersion=${{ github.event.release.tag_name }} -DgenerateBackupPoms=false 37 | 38 | - name: Build with Maven 39 | run: mvn -B clean package 40 | 41 | - name: Upload build artifact 42 | uses: actions/upload-artifact@v4 43 | with: 44 | name: ServerLinksZ-jar 45 | path: target/ServerLinksZ-${{ github.event.release.tag_name }}.jar 46 | 47 | upload_release_asset: 48 | needs: build 49 | runs-on: ubuntu-latest 50 | steps: 51 | - name: Download build artifact 52 | uses: actions/download-artifact@v4 53 | with: 54 | name: ServerLinksZ-jar 55 | path: target/ 56 | 57 | - name: Upload JAR to GitHub Release 58 | uses: softprops/action-gh-release@v2 59 | with: 60 | files: target/ServerLinksZ-${{ github.event.release.tag_name }}.jar 61 | body: ${{ github.event.release.body }} 62 | 63 | publish_modrinth: 64 | needs: build 65 | runs-on: ubuntu-latest 66 | steps: 67 | - name: Download build artifact 68 | uses: actions/download-artifact@v4 69 | with: 70 | name: ServerLinksZ-jar 71 | path: target/ 72 | 73 | - name: Publish to Modrinth 74 | uses: cloudnode-pro/modrinth-publish@v2 75 | with: 76 | token: ${{ secrets.MODRINTH_TOKEN }} 77 | project: 'iR9qgF1M' 78 | version: ${{ github.event.release.tag_name }} 79 | name: 'ServerLinksZ ${{ github.event.release.tag_name }}' 80 | changelog: ${{ github.event.release.body }} 81 | files: '["target/ServerLinksZ-${{ github.event.release.tag_name }}.jar"]' 82 | loaders: |- 83 | paper 84 | purpur 85 | game-versions: |- 86 | 1.21.x 87 | status: 'listed' 88 | channel: 'release' 89 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/util/LanguageManager.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.util; 2 | 3 | import org.bukkit.configuration.file.FileConfiguration; 4 | import org.bukkit.configuration.file.YamlConfiguration; 5 | import com.zetaplugins.serverlinksz.ServerLinksZ; 6 | 7 | import java.io.File; 8 | import java.util.HashMap; 9 | import java.util.List; 10 | 11 | public class LanguageManager { 12 | private final ServerLinksZ plugin; 13 | public static final List defaultLangs = List.of("en-US", "de-DE", "zh-CN", "ru-RU", "zh-TW"); 14 | 15 | private HashMap translationMap; 16 | private FileConfiguration langConfig; 17 | 18 | public LanguageManager(ServerLinksZ plugin) { 19 | this.plugin = plugin; 20 | loadLanguageConfig(); 21 | } 22 | 23 | /** 24 | * Reloads the language configuration 25 | */ 26 | public void reload() { 27 | loadLanguageConfig(); 28 | } 29 | 30 | /** 31 | * Loads the language configuration 32 | */ 33 | private void loadLanguageConfig() { 34 | File languageDirectory = new File(plugin.getDataFolder(), "lang/"); 35 | if (!languageDirectory.exists() || !languageDirectory.isDirectory()) languageDirectory.mkdir(); 36 | 37 | for (String langString : defaultLangs) { 38 | File langFile = new File("lang/", langString + ".yml"); 39 | if (!new File(languageDirectory, langString + ".yml").exists()) { 40 | plugin.getLogger().info("Saving file " + langFile.getPath()); 41 | plugin.saveResource(langFile.getPath(), false); 42 | } 43 | } 44 | 45 | String langOption = plugin.getConfig().getString("lang") != null 46 | ? plugin.getConfig().getString("lang") 47 | : "en-US"; 48 | File selectedLangFile = new File(languageDirectory, langOption + ".yml"); 49 | 50 | if (!selectedLangFile.exists()) { 51 | selectedLangFile = new File(languageDirectory, "en-US.yml"); 52 | plugin.getLogger().warning( 53 | "Language file " + langOption + ".yml (" + selectedLangFile.getPath() + ") not found! Using fallback en-US.yml." 54 | ); 55 | } 56 | 57 | plugin.getLogger().info("Using language file: " + selectedLangFile.getPath()); 58 | langConfig = YamlConfiguration.loadConfiguration(selectedLangFile); 59 | } 60 | 61 | /** 62 | * Returns a string from the language file 63 | * @param key The key of the string 64 | * @return The string 65 | */ 66 | public String getString(String key) { 67 | return langConfig.getString(key); 68 | } 69 | 70 | /** 71 | * Returns a string from the language file 72 | * @param key The key of the string 73 | * @param fallback The fallback string 74 | * @return The string 75 | */ 76 | public String getString(String key, String fallback) { 77 | return langConfig.getString(key) != null ? langConfig.getString(key) : fallback; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/commands/maincommand/subcommands/AddSubCommand.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.commands.maincommand.subcommands; 2 | 3 | import org.bukkit.command.CommandSender; 4 | import com.zetaplugins.serverlinksz.ServerLinksZ; 5 | import com.zetaplugins.serverlinksz.commands.CommandUtils; 6 | import com.zetaplugins.serverlinksz.commands.SubCommand; 7 | import com.zetaplugins.serverlinksz.util.MessageUtils; 8 | 9 | import java.net.URI; 10 | import java.net.URISyntaxException; 11 | 12 | public class AddSubCommand implements SubCommand { 13 | private final ServerLinksZ plugin; 14 | 15 | public AddSubCommand(ServerLinksZ plugin) { 16 | this.plugin = plugin; 17 | } 18 | 19 | @Override 20 | public boolean execute(CommandSender sender, String[] args) { 21 | if (!hasPermission(sender)) { 22 | CommandUtils.throwPermissionError(sender); 23 | return false; 24 | } 25 | 26 | if (args.length < 4) { 27 | CommandUtils.throwUsageError(sender, getUsage()); 28 | return false; 29 | } 30 | 31 | boolean showHints = plugin.getConfig().getBoolean("hints"); 32 | 33 | String id = args[1]; 34 | String name = args[2]; 35 | String url = args[3]; 36 | boolean allowCommand = args.length > 4 && args[4].equals("true"); 37 | String type = args.length > 5 ? args[5] : "CUSTOM"; 38 | 39 | if (!isValidURL(url)) { 40 | sender.sendMessage(MessageUtils.getAndFormatMsg(false, "invalidUrlError", "&cThe URL is invalid!")); 41 | return false; 42 | } 43 | 44 | if (!url.startsWith("http://") && !url.startsWith("https://")) { 45 | sender.sendMessage(MessageUtils.getAndFormatMsg(false, "urlProtocolError", "&cThe URL must start with 'http://' or 'https://'!")); 46 | return false; 47 | } 48 | 49 | plugin.getLinkManager().addLink(id, name, url, allowCommand, type); 50 | sender.sendMessage(MessageUtils.getAndFormatMsg(true, "addLinkMsg", "&7Successfully added link with id %id%!", new MessageUtils.Replaceable("%id%", id))); 51 | if (showHints) { 52 | sender.sendMessage(MessageUtils.getAndFormatMsg(false, "rejoinHint", "<#E9D502>⚠ To update the Serverlinks, please rejoin the server!")); 53 | sender.sendMessage(MessageUtils.getAndFormatMsg(false, "moreConfigOptionsHint", "<#E9D502>⚠ For more configuration options, please refer to the config.yml file!")); 54 | } 55 | 56 | return true; 57 | } 58 | 59 | @Override 60 | public String getUsage() { 61 | return "/serverlinksz add "; 62 | } 63 | 64 | @Override 65 | public boolean hasPermission(CommandSender sender) { 66 | return sender.hasPermission("serverlinksz.admin"); 67 | } 68 | 69 | private boolean isValidURL(String url) { 70 | try { 71 | new URI(url); 72 | return true; 73 | } catch (URISyntaxException e) { 74 | return false; 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/commands/LinkCommand.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.commands; 2 | 3 | import org.bukkit.command.Command; 4 | import org.bukkit.command.CommandExecutor; 5 | import org.bukkit.command.CommandSender; 6 | import org.bukkit.command.TabCompleter; 7 | import org.jetbrains.annotations.NotNull; 8 | import com.zetaplugins.serverlinksz.ServerLinksZ; 9 | import com.zetaplugins.serverlinksz.util.LinkManager; 10 | import com.zetaplugins.serverlinksz.util.MessageUtils; 11 | 12 | import java.util.List; 13 | 14 | public class LinkCommand implements CommandExecutor, TabCompleter { 15 | private final ServerLinksZ plugin; 16 | 17 | public LinkCommand(ServerLinksZ plugin) { 18 | this.plugin = plugin; 19 | } 20 | 21 | @Override 22 | public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { 23 | List linkCommands = List.of( 24 | "discord", "website", "store", "teamspeak", "twitter", "youtube", "instagram", "facebook", "tiktok", "vote" 25 | ); 26 | 27 | String linkID = linkCommands.contains(command.getName()) | plugin.getLinkManager().getLinkKeys().contains(command.getName()) 28 | ? command.getName() 29 | : args.length > 0 30 | ? args[0] 31 | : null; 32 | 33 | if (linkID == null) { 34 | CommandUtils.throwUsageError(sender, "/" + command.getName() + " "); 35 | return false; 36 | } 37 | 38 | if (!plugin.getLinkManager().getLinkKeys().contains(linkID)) { 39 | sender.sendMessage(MessageUtils.getAndFormatMsg( 40 | false, 41 | "linkNotFound", 42 | "&cLink with id <#00BFFF>%id%&c not found!", 43 | new MessageUtils.Replaceable("%id%", linkID) 44 | )); 45 | return false; 46 | } 47 | 48 | LinkManager.Link link = plugin.getLinkManager().getLink(linkID); 49 | 50 | if (link == null) return false; 51 | 52 | if (!link.allowCommand()) { 53 | sender.sendMessage(MessageUtils.getAndFormatMsg( 54 | false, 55 | "linkCcommandNotAllowed", 56 | "&cYou are not allowed to access this command via a link!" 57 | )); 58 | return false; 59 | } 60 | 61 | sender.sendMessage(MessageUtils.getAndFormatMsg( 62 | false, 63 | "linkCommand", 64 | "&7-> %name% &r&7<-", 65 | new MessageUtils.Replaceable("%url%", link.url()), 66 | new MessageUtils.Replaceable("%name%", link.name()) 67 | )); 68 | return false; 69 | } 70 | 71 | @Override 72 | public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { 73 | if (args.length == 1) { 74 | return plugin.getLinkManager().getLinkKeys(LinkManager.Link::allowCommand).stream().toList(); 75 | } 76 | return null; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/util/MessageUtils.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.util; 2 | 3 | import net.kyori.adventure.text.Component; 4 | import net.kyori.adventure.text.minimessage.MiniMessage; 5 | import com.zetaplugins.serverlinksz.ServerLinksZ; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | public class MessageUtils { 11 | private MessageUtils() {} 12 | 13 | private static final Map colorMap; 14 | 15 | static { 16 | colorMap = new HashMap<>(); 17 | colorMap.put("&0", ""); 18 | colorMap.put("&1", ""); 19 | colorMap.put("&2", ""); 20 | colorMap.put("&3", ""); 21 | colorMap.put("&4", ""); 22 | colorMap.put("&5", ""); 23 | colorMap.put("&6", ""); 24 | colorMap.put("&7", ""); 25 | colorMap.put("&8", ""); 26 | colorMap.put("&9", ""); 27 | colorMap.put("&a", ""); 28 | colorMap.put("&b", ""); 29 | colorMap.put("&c", ""); 30 | colorMap.put("&d", ""); 31 | colorMap.put("&e", ""); 32 | colorMap.put("&f", ""); 33 | colorMap.put("&k", ""); 34 | colorMap.put("&l", ""); 35 | colorMap.put("&m", ""); 36 | colorMap.put("&n", ""); 37 | colorMap.put("&o", ""); 38 | colorMap.put("&r", ""); 39 | } 40 | 41 | public record Replaceable(String placeholder, String value) {} 42 | 43 | /** 44 | * Formats a message with placeholders 45 | * 46 | * @param msg The message to format 47 | * @param replaceables The placeholders to replace 48 | * @return The formatted message 49 | */ 50 | public static Component formatMsg(String msg, Replaceable... replaceables) { 51 | for (Replaceable replaceable : replaceables) { 52 | msg = msg.replace(replaceable.placeholder(), replaceable.value()); 53 | } 54 | 55 | for (Map.Entry entry : colorMap.entrySet()) { 56 | msg = msg.replace(entry.getKey(), entry.getValue()); 57 | } 58 | 59 | MiniMessage mm = MiniMessage.miniMessage(); 60 | return mm.deserialize("" + msg); 61 | } 62 | 63 | /** 64 | * Gets and formats a message from the config 65 | * 66 | * @param addPrefix Whether to add the prefix to the message 67 | * @param path The path to the message in the config 68 | * @param fallback The fallback message 69 | * @param replaceables The placeholders to replace 70 | * @return The formatted message 71 | */ 72 | public static Component getAndFormatMsg(boolean addPrefix, String path, String fallback, Replaceable... replaceables) { 73 | if (path.startsWith("messages.")) path = path.substring("messages.".length()); 74 | 75 | MiniMessage mm = MiniMessage.miniMessage(); 76 | String msg = "" + ServerLinksZ.getInstance().getLanguageManager().getString(path, fallback); 77 | String prefix = ServerLinksZ.getInstance().getLanguageManager().getString("prefix", "&8[&cServerLinksZ&8]"); 78 | if (addPrefix) { 79 | msg = prefix + " " + msg; 80 | } 81 | 82 | for (Replaceable replaceable : replaceables) { 83 | msg = msg.replace(replaceable.placeholder(), replaceable.value()); 84 | } 85 | 86 | for (Map.Entry entry : colorMap.entrySet()) { 87 | msg = msg.replace(entry.getKey(), entry.getValue()); 88 | } 89 | 90 | return mm.deserialize(msg); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/util/CommandManager.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.util; 2 | 3 | import com.zetaplugins.zetacore.debug.command.DebugCommandHandler; 4 | import org.bukkit.Bukkit; 5 | import org.bukkit.command.*; 6 | import com.zetaplugins.serverlinksz.ServerLinksZ; 7 | import com.zetaplugins.serverlinksz.commands.LinkCommand; 8 | import com.zetaplugins.serverlinksz.commands.maincommand.MainCommandHandler; 9 | import com.zetaplugins.serverlinksz.commands.maincommand.MainTabCompleter; 10 | import org.bukkit.configuration.file.FileConfiguration; 11 | import org.bukkit.configuration.file.YamlConfiguration; 12 | 13 | import java.io.File; 14 | import java.lang.reflect.Field; 15 | import java.util.HashMap; 16 | import java.util.List; 17 | import java.util.Map; 18 | 19 | public class CommandManager { 20 | private final ServerLinksZ plugin; 21 | 22 | public CommandManager(ServerLinksZ plugin) { 23 | this.plugin = plugin; 24 | } 25 | 26 | /** 27 | * Gets the command map 28 | * @return The command map 29 | */ 30 | private CommandMap getCommandMap() { 31 | try { 32 | Field field = Bukkit.getServer().getClass().getDeclaredField("commandMap"); 33 | field.setAccessible(true); 34 | return (CommandMap) field.get(Bukkit.getServer()); 35 | } catch (Exception e) { 36 | plugin.getLogger().severe("Failed to get command map: " + e.getMessage()); 37 | return null; 38 | } 39 | } 40 | 41 | /** 42 | * Registers all commands 43 | */ 44 | public void registerCommands() { 45 | registerCommand("serverlinksz", new MainCommandHandler(plugin), new MainTabCompleter(plugin)); 46 | 47 | Map configs = new HashMap<>(); 48 | configs.put("config.yml", plugin.getConfig().saveToString()); 49 | configs.put("links.yml", getLinksConfig().saveToString()); 50 | DebugCommandHandler debugCommandHandler = new DebugCommandHandler( 51 | "iR9qgF1M", 52 | plugin, 53 | plugin.getPluginFile(), 54 | "serverlinksz.admin", 55 | configs 56 | ); 57 | registerCommand("slzdebug", debugCommandHandler, debugCommandHandler); 58 | 59 | if (plugin.getConfig().getBoolean("linkCommand")) { 60 | registerCommand("link", new LinkCommand(plugin), new LinkCommand(plugin)); 61 | } 62 | 63 | CommandMap commandMap = getCommandMap(); 64 | 65 | if (commandMap == null) return; 66 | 67 | for (String linkKey : plugin.getLinkManager().getLinkKeys()) { 68 | LinkManager.Link link = plugin.getLinkManager().getLink(linkKey); 69 | if (link == null || !link.allowCommand()) continue; 70 | commandMap.register(linkKey, "slzcmd", link.getCommand()); 71 | } 72 | } 73 | 74 | /** 75 | * Registers a command 76 | * 77 | * @param name The name of the command 78 | * @param executor The executor of the command 79 | * @param tabCompleter The tab completer of the command 80 | */ 81 | private void registerCommand(String name, CommandExecutor executor, TabCompleter tabCompleter) { 82 | PluginCommand command = plugin.getCommand(name); 83 | 84 | if (command != null) { 85 | command.setExecutor(executor); 86 | command.setTabCompleter(tabCompleter); 87 | command.permissionMessage(MessageUtils.getAndFormatMsg( 88 | false, 89 | "noPermissionError", 90 | "&cYou don't have permission to use this!" 91 | )); 92 | } 93 | } 94 | 95 | private FileConfiguration getLinksConfig() { 96 | File linksFile = new File(plugin.getDataFolder(), "links.yml"); 97 | if (!linksFile.exists()) { 98 | linksFile.getParentFile().mkdirs(); 99 | plugin.saveResource("links.yml", false); 100 | } 101 | return YamlConfiguration.loadConfiguration(linksFile); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.zetaplugins 8 | ServerLinksZ 9 | 1.4.0 10 | jar 11 | 12 | ServerLinksZ 13 | 14 | 15 | 21 16 | UTF-8 17 | 18 | 19 | 20 | clean package 21 | 22 | 23 | org.apache.maven.plugins 24 | maven-compiler-plugin 25 | 3.13.0 26 | 27 | ${java.version} 28 | ${java.version} 29 | 30 | 31 | 32 | org.apache.maven.plugins 33 | maven-shade-plugin 34 | 3.6.0 35 | 36 | 37 | package 38 | 39 | shade 40 | 41 | 42 | 43 | 44 | 45 | 46 | com.zetaplugins:zetacore 47 | 48 | 49 | 50 | 52 | 54 | com.zetaplugins.serverlinksz.ServerLinksZ 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | src/main/resources 63 | true 64 | 65 | 66 | 67 | 68 | 69 | 70 | papermc 71 | https://repo.papermc.io/repository/maven-public/ 72 | 73 | 74 | sonatype 75 | https://oss.sonatype.org/content/groups/public/ 76 | 77 | 78 | zetaplugins 79 | https://maven.zetaplugins.com/ 80 | 81 | 82 | 83 | 84 | 85 | io.papermc.paper 86 | paper-api 87 | 1.21-R0.1-SNAPSHOT 88 | provided 89 | 90 | 91 | net.kyori 92 | adventure-text-minimessage 93 | 4.17.0 94 | 95 | 96 | com.zetaplugins 97 | zetacore 98 | 1.0.2 99 | 100 | 101 | 102 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/commands/maincommand/MainTabCompleter.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.commands.maincommand; 2 | 3 | import com.zetaplugins.serverlinksz.commands.CommandUtils; 4 | import org.bukkit.command.Command; 5 | import org.bukkit.command.CommandSender; 6 | import org.bukkit.command.TabCompleter; 7 | import org.jetbrains.annotations.NotNull; 8 | import org.jetbrains.annotations.Nullable; 9 | import com.zetaplugins.serverlinksz.ServerLinksZ; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | public class MainTabCompleter implements TabCompleter { 15 | private final ServerLinksZ plugin; 16 | 17 | public MainTabCompleter(ServerLinksZ plugin) { 18 | this.plugin = plugin; 19 | } 20 | 21 | @Override 22 | public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) { 23 | return switch (args.length) { 24 | case 1 -> getFirstArgOptions(sender, args); 25 | case 2 -> getSecondArgOptions(args); 26 | case 3 -> getThirdArgOptions(args); 27 | case 4 -> getFourthArgOptions(args); 28 | case 5 -> getFifthArgOptions(args); 29 | case 6 -> getSixthArgOptions(args); 30 | default -> List.of(); 31 | }; 32 | } 33 | 34 | public List getFirstArgOptions(CommandSender sender, String[] args) { 35 | List availableOptions = new ArrayList<>(); 36 | 37 | if ("help".startsWith(args[0].toLowerCase()) || args[0].equalsIgnoreCase("help")) { 38 | availableOptions.add("help"); 39 | } 40 | 41 | if (sender.hasPermission("serverlinksz.admin")) { 42 | List adminCommands = List.of("add", "remove", "reload"); 43 | for (String adminCommand : adminCommands) { 44 | if (adminCommand.startsWith(args[0].toLowerCase()) || args[0].equalsIgnoreCase(adminCommand)) { 45 | availableOptions.add(adminCommand); 46 | } 47 | } 48 | } 49 | 50 | return availableOptions; 51 | } 52 | 53 | public List getSecondArgOptions(String[] args) { 54 | if (args[0].equals("add")) { 55 | return List.of(""); 56 | } 57 | 58 | if (args[0].equals("remove")) { 59 | List linkKeys = plugin.getLinkManager().getLinkKeys().stream().toList(); 60 | List suggestions = new ArrayList<>(); 61 | for (String linkKey : linkKeys) { 62 | if (linkKey.startsWith(args[1].toLowerCase()) || args[1].equalsIgnoreCase(linkKey)) { 63 | suggestions.add(linkKey); 64 | } 65 | } 66 | return suggestions; 67 | } 68 | 69 | return List.of(); 70 | } 71 | 72 | public List getThirdArgOptions(String[] args) { 73 | if (args[0].equals("add")) { 74 | return List.of(""); 75 | } 76 | 77 | return List.of(); 78 | } 79 | 80 | public List getFourthArgOptions(String[] args) { 81 | if (args[0].equals("add")) { 82 | return List.of(""); 83 | } 84 | 85 | return List.of(); 86 | } 87 | 88 | public List getFifthArgOptions(String[] args) { 89 | if (args[0].equals("add")) { 90 | return List.of("true", "false"); 91 | } 92 | 93 | return List.of(); 94 | } 95 | 96 | public List getSixthArgOptions(String[] args) { 97 | if (args[0].equals("add")) { 98 | return CommandUtils.getDisplayOptions(List.of( 99 | "CUSTOM", 100 | "ANNOUNCEMENTS", 101 | "COMMUNITY", 102 | "COMMUNITY_GUIDELINES", 103 | "FEEDBACK", 104 | "FORUMS", 105 | "NEWS", 106 | "REPORT_BUG", 107 | "STATUS", 108 | "SUPPORT", 109 | "WEBSITE" 110 | ), args[5]); 111 | } 112 | 113 | return List.of(); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![banner](https://cdn.modrinth.com/data/cached_images/b1a659a750a37515bf4c4c767ccdfe9a7c3fe038.png) 2 | 3 | ![paper](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@3/assets/compact/supported/paper_vector.svg) 4 | ![purpur](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@3/assets/compact/supported/purpur_vector.svg) 5 | [![github](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@3/assets/compact/available/github_vector.svg)](https://github.com/KartoffelChipss/ServerLinksZ) 6 | [![modrinth](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@3/assets/compact/available/modrinth_vector.svg)](https://modrinth.com/plugin/serverlinksz) 7 | [![docs](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@3/assets/compact/documentation/gitbook_vector.svg)](https://docs.zetaplugins.com/serverlinksz) 8 | [![discord-plural](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@3/assets/compact/social/discord-plural_vector.svg)](https://strassburger.org/discord) 9 | [![generic-plural](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@3/assets/compact/translate/generic-plural_vector.svg)](https://gitlocalize.com/repo/9890) 10 | 11 | ServerLinksZ is a simple plugin, that allows you to add Links to the "Server Links" page in the pause menu. ServerLinksZ also adds a command for users to quickly look up links like /discord. 12 | 13 | ## Features 14 | - ✅ Custom links 15 | - ✅ Colored link Names 16 | - ✅ HEX Colors 17 | - ✅ Link commands (e.g. `/discord`, `/website`) 18 | - ✅ Highly customizable 19 | - ✅ Easy setup 20 | - ✅ Multiple languages 21 | 22 | ## Commands 23 | 24 | - **/sl help** - Open the help menu 25 | - **/sl add ** - Add a link to the Link page 26 | - **/sl remove ** - Remove the link with this id 27 | - **/sl reload** - Reload the plugin 28 | - **/link ** - Open a link with this id 29 | 30 | and custom link commands (e.g. `/discord`, `/website`) 31 | 32 | ## Permissions 33 | 34 | - **serverlinksz.admin** - Allows a user to manage links and do admin tasks (default: op) 35 | 36 | ## Config 37 | 38 | Here is an example of the configuration file: 39 |
40 | config.yml 41 | 42 | ```yml 43 | # _____ _ _ _ ______ 44 | # / ____| | | (_) | | |___ / 45 | # | (___ ___ _ ____ _____ _ __ | | _ _ __ | | _____ / / 46 | # \___ \ / _ \ '__\ \ / / _ \ '__| | | | | '_ \| |/ / __| / / 47 | # ____) | __/ | \ V / __/ | | |____| | | | | <\__ \ / /__ 48 | # |_____/ \___|_| \_/ \___|_| |______|_|_| |_|_|\_\___/ /_____| 49 | 50 | 51 | # === COLOR CODES === 52 | 53 | # This plugin supports old color codes like: &c, &l, &o, etc. 54 | # It also supports MiniMessage, a more advanced way to format messages: 55 | # https://docs.advntr.dev/minimessage/format.html 56 | # With MiniMessage, you can add HEX colors, gradients, hover and click events, etc. 57 | 58 | 59 | # === GENERAL SETTINGS === 60 | 61 | # Set the language to any code found in the "lang" folder (don't add the .yml extension) 62 | # You can add your own language files. Use https://github.com/KartoffelChipss/ServerLinksZ/tree/main/src/main/resources/lang/en-US.yml as a template 63 | # If you want to share your language file, either create a pull request on GitHub or use GitLocalize: https://gitlocalize.com/repo/9890 64 | # | en-US | de-DE | zh-CN | ru-RU | zh-TW 65 | lang: "en-US" 66 | 67 | # Wether to show hints when using commands 68 | hints: true 69 | 70 | # Add a /link command to view the links 71 | linkCommand: true 72 | 73 | # Instead of using the /link command, you can also use a custom command for any link (e.g. /mycoollink) 74 | # This feature is experimental and might not work as expected 75 | dynamicCommands: false 76 | 77 | # [!!!] You can configure the links in the links.yml file! 78 | ``` 79 |
80 | 81 | And here an example of the links configuration file: 82 | 83 |
84 | links.yml 85 | 86 | ```yml 87 | discord: 88 | name: "<#7289da>&lDiscord" 89 | url: "https://strassburger.org/discord" 90 | type: CUSTOM 91 | allowCommand: true 92 | website: 93 | name: "<#7cd770>&lWebsite" 94 | url: "https://modrinth.com/plugin/serverlinksz" 95 | type: CUSTOM 96 | allowCommand: false 97 | bugreport: 98 | name: "<#ff746c>&lReport a bug" 99 | url: "https://example.com/issues" 100 | # The type can be any of ANNOUNCEMENTS, COMMUNITY, COMMUNITY_GUIDELINES, FEEDBACK, FORUMS, NEWS, REPORT_BUG, STATUS, SUPPORT, WEBSITE, CUSTOM 101 | # CUSTOM will display the name in the links menu. Anything else will display a client side defined label. 102 | type: REPORT_BUG 103 | allowCommand: true 104 | ``` 105 |
106 | 107 | ## Support 108 | 109 | If you need help with the setup of the plugin, you can join my Discord: 110 | 111 | [![discord-plural](https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@3/assets/compact/social/discord-plural_vector.svg)](https://strassburger.org/discord) 112 | 113 | --- 114 | 115 | [![Usage](https://bstats.org/signatures/bukkit/ServerLinksZ.svg)](https://bstats.org/plugin/bukkit/ServerLinksZ/22795) 116 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/util/LinkManager.java: -------------------------------------------------------------------------------- 1 | package com.zetaplugins.serverlinksz.util; 2 | 3 | import org.bukkit.Bukkit; 4 | import org.bukkit.ServerLinks; 5 | import org.bukkit.command.Command; 6 | import org.bukkit.command.CommandSender; 7 | import org.bukkit.command.defaults.BukkitCommand; 8 | import org.bukkit.configuration.file.FileConfiguration; 9 | import org.bukkit.configuration.file.YamlConfiguration; 10 | import com.zetaplugins.serverlinksz.ServerLinksZ; 11 | import com.zetaplugins.serverlinksz.commands.LinkCommand; 12 | import org.jetbrains.annotations.NotNull; 13 | import org.jetbrains.annotations.Nullable; 14 | 15 | import java.io.File; 16 | import java.net.URI; 17 | import java.net.URISyntaxException; 18 | import java.util.List; 19 | import java.util.Set; 20 | import java.util.function.Predicate; 21 | import java.util.logging.Logger; 22 | import java.util.stream.Collectors; 23 | 24 | public class LinkManager { 25 | private final ServerLinksZ plugin; 26 | 27 | private final ServerLinks serverLinks = Bukkit.getServer().getServerLinks(); 28 | private final Logger logger; 29 | 30 | public LinkManager(ServerLinksZ plugin) { 31 | this.plugin = plugin; 32 | this.logger = plugin.getLogger(); 33 | } 34 | 35 | /** 36 | * Updates the links 37 | */ 38 | public void updateLinks() { 39 | final FileConfiguration config = getLinksConfig(); 40 | 41 | clearLinks(); 42 | 43 | for (String key : config.getKeys(false)) { 44 | String name = config.getString(key + ".name"); 45 | String url = config.getString(key + ".url"); 46 | String type = config.getString(key + ".type"); 47 | if (name == null || url == null) continue; 48 | 49 | registerLink(name, url, type); 50 | } 51 | } 52 | 53 | /** 54 | * Registers a link (does not update the config) 55 | * @param name The name of the link 56 | * @param url The URL of the link 57 | */ 58 | private void registerLink(String name, String url, @Nullable String typeString) { 59 | try { 60 | URI uri = new URI(url); 61 | ServerLinks.Type type = getLinkType(typeString); 62 | if (type != null) serverLinks.addLink(type, uri); 63 | else serverLinks.addLink(MessageUtils.formatMsg(name), uri); 64 | } catch (URISyntaxException e) { 65 | logger.warning("Invalid URL: " + url); 66 | throw new RuntimeException(e); 67 | } 68 | } 69 | 70 | /** 71 | * Gets the link type from the name 72 | * @param name The name of the link 73 | * @return The link type, or null if not found 74 | */ 75 | private ServerLinks.Type getLinkType(String name) { 76 | if (name == null) return null; 77 | try { 78 | return ServerLinks.Type.valueOf(name.toUpperCase()); 79 | } catch (IllegalArgumentException | NullPointerException e) { 80 | return null; 81 | } 82 | } 83 | 84 | /** 85 | * Adds a link to the config and updates the links 86 | * @param key The key of the link 87 | * @param name The name of the link 88 | * @param url The URL of the link 89 | * @param command Whether the link should allow commands 90 | * @param stringType The type of the link as a string 91 | */ 92 | public void addLink(String key, String name, String url, boolean command, String stringType) { 93 | final FileConfiguration config = getLinksConfig(); 94 | ServerLinks.Type type = getLinkType(stringType); 95 | String typeToSave = type != null ? type.toString() : "CUSTOM"; 96 | 97 | config.set(key + ".name", name); 98 | config.set(key + ".url", url); 99 | config.set(key + ".allowCommand", command); 100 | config.set(key + ".type", typeToSave); 101 | 102 | saveLinksConfig(config); 103 | updateLinks(); 104 | } 105 | 106 | /** 107 | * Removes a link from the config and updates the links 108 | * @param key The key of the link 109 | */ 110 | public void removeLink(String key) { 111 | final FileConfiguration config = getLinksConfig(); 112 | config.set(key, null); 113 | saveLinksConfig(config); 114 | updateLinks(); 115 | } 116 | 117 | /** 118 | * Clears all links from the server 119 | */ 120 | public void clearLinks() { 121 | for (ServerLinks.ServerLink link : serverLinks.getLinks()) { 122 | serverLinks.removeLink(link); 123 | } 124 | } 125 | 126 | /** 127 | * Gets a link by key 128 | * @param key The key of the link 129 | * @return The link 130 | */ 131 | @Nullable 132 | public Link getLink(String key) { 133 | final FileConfiguration config = getLinksConfig(); 134 | String name = config.getString(key + ".name"); 135 | String url = config.getString(key + ".url"); 136 | boolean allowCommand = config.getBoolean(key + ".allowCommand"); 137 | if (name == null || url == null) return null; 138 | return new Link(key, name, url, allowCommand, plugin); 139 | } 140 | 141 | /** 142 | * Gets all link keys from the config 143 | * @return All link keys 144 | */ 145 | public Set getLinkKeys() { 146 | return getLinksConfig().getKeys(false); 147 | } 148 | 149 | /** 150 | * Gets all link keys from the config that match the predicate 151 | * @param predicate The predicate to match 152 | * @return All link keys that match the predicate 153 | */ 154 | public Set getLinkKeys(Predicate predicate) { 155 | return getLinkKeys().stream().filter( 156 | key -> { 157 | Link link = getLink(key); 158 | return link != null && predicate.test(link); 159 | } 160 | ).collect(Collectors.toSet()); 161 | } 162 | 163 | private FileConfiguration getLinksConfig() { 164 | File linksFile = new File(plugin.getDataFolder(), "links.yml"); 165 | if (!linksFile.exists()) { 166 | linksFile.getParentFile().mkdirs(); 167 | plugin.saveResource("links.yml", false); 168 | } 169 | return YamlConfiguration.loadConfiguration(linksFile); 170 | } 171 | 172 | private void saveLinksConfig(FileConfiguration config) { 173 | File linksFile = new File(plugin.getDataFolder(), "links.yml"); 174 | try { 175 | config.save(linksFile); 176 | } catch (Exception e) { 177 | logger.severe("Failed to save links.yml!"); 178 | e.printStackTrace(); 179 | } 180 | } 181 | 182 | public record Link(String id, String name, String url, boolean allowCommand, ServerLinksZ plugin) { 183 | /** 184 | * Get a BukkitCommand for a link 185 | * @return The BukkitCommand 186 | */ 187 | public @NotNull Command getCommand() { 188 | LinkCommand executor = new LinkCommand(plugin); 189 | return new BukkitCommand(id()) { 190 | @Override 191 | public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, String[] args) { 192 | return executor.onCommand(sender, this, commandLabel, args); 193 | } 194 | 195 | @Override 196 | public @NotNull List tabComplete(@NotNull CommandSender sender, @NotNull String alias, String[] args) throws IllegalArgumentException { 197 | List completions = executor.onTabComplete(sender, this, alias, args); 198 | return completions == null ? List.of() : completions; 199 | } 200 | }; 201 | } 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /src/main/java/com/zetaplugins/serverlinksz/util/bStats/Metrics.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This Metrics class was auto-generated and can be copied into your project if you are 3 | * not using a build tool like Gradle or Maven for dependency management. 4 | * 5 | * IMPORTANT: You are not allowed to modify this class, except changing the package. 6 | * 7 | * Disallowed modifications include but are not limited to: 8 | * - Remove the option for users to opt-out 9 | * - Change the frequency for data submission 10 | * - Obfuscate the code (every obfuscator should allow you to make an exception for specific files) 11 | * - Reformat the code (if you use a linter, add an exception) 12 | * 13 | * Violations will result in a ban of your plugin and account from bStats. 14 | */ 15 | package com.zetaplugins.serverlinksz.util.bStats; 16 | 17 | import java.io.BufferedReader; 18 | import java.io.ByteArrayOutputStream; 19 | import java.io.DataOutputStream; 20 | import java.io.File; 21 | import java.io.IOException; 22 | import java.io.InputStreamReader; 23 | import java.lang.reflect.Method; 24 | import java.net.URL; 25 | import java.nio.charset.StandardCharsets; 26 | import java.util.Arrays; 27 | import java.util.Collection; 28 | import java.util.HashSet; 29 | import java.util.Map; 30 | import java.util.Objects; 31 | import java.util.Set; 32 | import java.util.UUID; 33 | import java.util.concurrent.Callable; 34 | import java.util.concurrent.ScheduledExecutorService; 35 | import java.util.concurrent.ScheduledThreadPoolExecutor; 36 | import java.util.concurrent.TimeUnit; 37 | import java.util.function.BiConsumer; 38 | import java.util.function.Consumer; 39 | import java.util.function.Supplier; 40 | import java.util.logging.Level; 41 | import java.util.stream.Collectors; 42 | import java.util.zip.GZIPOutputStream; 43 | import javax.net.ssl.HttpsURLConnection; 44 | import org.bukkit.Bukkit; 45 | import org.bukkit.configuration.file.YamlConfiguration; 46 | import org.bukkit.entity.Player; 47 | import org.bukkit.plugin.Plugin; 48 | import org.bukkit.plugin.java.JavaPlugin; 49 | 50 | public class Metrics { 51 | 52 | private final Plugin plugin; 53 | 54 | private final MetricsBase metricsBase; 55 | 56 | /** 57 | * Creates a new Metrics instance. 58 | * 59 | * @param plugin Your plugin instance. 60 | * @param serviceId The id of the service. It can be found at What is my plugin id? 62 | */ 63 | public Metrics(JavaPlugin plugin, int serviceId) { 64 | this.plugin = plugin; 65 | // Get the config file 66 | File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); 67 | File configFile = new File(bStatsFolder, "config.yml"); 68 | YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); 69 | if (!config.isSet("serverUuid")) { 70 | config.addDefault("enabled", true); 71 | config.addDefault("serverUuid", UUID.randomUUID().toString()); 72 | config.addDefault("logFailedRequests", false); 73 | config.addDefault("logSentData", false); 74 | config.addDefault("logResponseStatusText", false); 75 | // Inform the server owners about bStats 76 | config 77 | .options() 78 | .header( 79 | "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" 80 | + "many people use their plugin and their total player count. It's recommended to keep bStats\n" 81 | + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" 82 | + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" 83 | + "anonymous.") 84 | .copyDefaults(true); 85 | try { 86 | config.save(configFile); 87 | } catch (IOException ignored) { 88 | } 89 | } 90 | // Load the data 91 | boolean enabled = config.getBoolean("enabled", true); 92 | String serverUUID = config.getString("serverUuid"); 93 | boolean logErrors = config.getBoolean("logFailedRequests", false); 94 | boolean logSentData = config.getBoolean("logSentData", false); 95 | boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); 96 | metricsBase = 97 | new MetricsBase( 98 | "bukkit", 99 | serverUUID, 100 | serviceId, 101 | enabled, 102 | this::appendPlatformData, 103 | this::appendServiceData, 104 | submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), 105 | plugin::isEnabled, 106 | (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), 107 | (message) -> this.plugin.getLogger().log(Level.INFO, message), 108 | logErrors, 109 | logSentData, 110 | logResponseStatusText); 111 | } 112 | 113 | /** Shuts down the underlying scheduler service. */ 114 | public void shutdown() { 115 | metricsBase.shutdown(); 116 | } 117 | 118 | /** 119 | * Adds a custom chart. 120 | * 121 | * @param chart The chart to add. 122 | */ 123 | public void addCustomChart(CustomChart chart) { 124 | metricsBase.addCustomChart(chart); 125 | } 126 | 127 | private void appendPlatformData(JsonObjectBuilder builder) { 128 | builder.appendField("playerAmount", getPlayerAmount()); 129 | builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); 130 | builder.appendField("bukkitVersion", Bukkit.getVersion()); 131 | builder.appendField("bukkitName", Bukkit.getName()); 132 | builder.appendField("javaVersion", System.getProperty("java.version")); 133 | builder.appendField("osName", System.getProperty("os.name")); 134 | builder.appendField("osArch", System.getProperty("os.arch")); 135 | builder.appendField("osVersion", System.getProperty("os.version")); 136 | builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); 137 | } 138 | 139 | private void appendServiceData(JsonObjectBuilder builder) { 140 | builder.appendField("pluginVersion", plugin.getDescription().getVersion()); 141 | } 142 | 143 | private int getPlayerAmount() { 144 | try { 145 | // Around MC 1.8 the return type was changed from an array to a collection, 146 | // This fixes java.lang.NoSuchMethodError: 147 | // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; 148 | Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); 149 | return onlinePlayersMethod.getReturnType().equals(Collection.class) 150 | ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() 151 | : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; 152 | } catch (Exception e) { 153 | // Just use the new method if the reflection failed 154 | return Bukkit.getOnlinePlayers().size(); 155 | } 156 | } 157 | 158 | public static class MetricsBase { 159 | 160 | /** The version of the Metrics class. */ 161 | public static final String METRICS_VERSION = "3.0.2"; 162 | 163 | private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; 164 | 165 | private final ScheduledExecutorService scheduler; 166 | 167 | private final String platform; 168 | 169 | private final String serverUuid; 170 | 171 | private final int serviceId; 172 | 173 | private final Consumer appendPlatformDataConsumer; 174 | 175 | private final Consumer appendServiceDataConsumer; 176 | 177 | private final Consumer submitTaskConsumer; 178 | 179 | private final Supplier checkServiceEnabledSupplier; 180 | 181 | private final BiConsumer errorLogger; 182 | 183 | private final Consumer infoLogger; 184 | 185 | private final boolean logErrors; 186 | 187 | private final boolean logSentData; 188 | 189 | private final boolean logResponseStatusText; 190 | 191 | private final Set customCharts = new HashSet<>(); 192 | 193 | private final boolean enabled; 194 | 195 | /** 196 | * Creates a new MetricsBase class instance. 197 | * 198 | * @param platform The platform of the service. 199 | * @param serviceId The id of the service. 200 | * @param serverUuid The server uuid. 201 | * @param enabled Whether or not data sending is enabled. 202 | * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and 203 | * appends all platform-specific data. 204 | * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and 205 | * appends all service-specific data. 206 | * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be 207 | * used to delegate the data collection to a another thread to prevent errors caused by 208 | * concurrency. Can be {@code null}. 209 | * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. 210 | * @param errorLogger A consumer that accepts log message and an error. 211 | * @param infoLogger A consumer that accepts info log messages. 212 | * @param logErrors Whether or not errors should be logged. 213 | * @param logSentData Whether or not the sent data should be logged. 214 | * @param logResponseStatusText Whether or not the response status text should be logged. 215 | */ 216 | public MetricsBase( 217 | String platform, 218 | String serverUuid, 219 | int serviceId, 220 | boolean enabled, 221 | Consumer appendPlatformDataConsumer, 222 | Consumer appendServiceDataConsumer, 223 | Consumer submitTaskConsumer, 224 | Supplier checkServiceEnabledSupplier, 225 | BiConsumer errorLogger, 226 | Consumer infoLogger, 227 | boolean logErrors, 228 | boolean logSentData, 229 | boolean logResponseStatusText) { 230 | ScheduledThreadPoolExecutor scheduler = 231 | new ScheduledThreadPoolExecutor(1, task -> new Thread(task, "bStats-Metrics")); 232 | // We want delayed tasks (non-periodic) that will execute in the future to be 233 | // cancelled when the scheduler is shutdown. 234 | // Otherwise, we risk preventing the server from shutting down even when 235 | // MetricsBase#shutdown() is called 236 | scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); 237 | this.scheduler = scheduler; 238 | this.platform = platform; 239 | this.serverUuid = serverUuid; 240 | this.serviceId = serviceId; 241 | this.enabled = enabled; 242 | this.appendPlatformDataConsumer = appendPlatformDataConsumer; 243 | this.appendServiceDataConsumer = appendServiceDataConsumer; 244 | this.submitTaskConsumer = submitTaskConsumer; 245 | this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; 246 | this.errorLogger = errorLogger; 247 | this.infoLogger = infoLogger; 248 | this.logErrors = logErrors; 249 | this.logSentData = logSentData; 250 | this.logResponseStatusText = logResponseStatusText; 251 | checkRelocation(); 252 | if (enabled) { 253 | // WARNING: Removing the option to opt-out will get your plugin banned from 254 | // bStats 255 | startSubmitting(); 256 | } 257 | } 258 | 259 | public void addCustomChart(CustomChart chart) { 260 | this.customCharts.add(chart); 261 | } 262 | 263 | public void shutdown() { 264 | scheduler.shutdown(); 265 | } 266 | 267 | private void startSubmitting() { 268 | final Runnable submitTask = 269 | () -> { 270 | if (!enabled || !checkServiceEnabledSupplier.get()) { 271 | // Submitting data or service is disabled 272 | scheduler.shutdown(); 273 | return; 274 | } 275 | if (submitTaskConsumer != null) { 276 | submitTaskConsumer.accept(this::submitData); 277 | } else { 278 | this.submitData(); 279 | } 280 | }; 281 | // Many servers tend to restart at a fixed time at xx:00 which causes an uneven 282 | // distribution of requests on the 283 | // bStats backend. To circumvent this problem, we introduce some randomness into 284 | // the initial and second delay. 285 | // WARNING: You must not modify and part of this Metrics class, including the 286 | // submit delay or frequency! 287 | // WARNING: Modifying this code will get your plugin banned on bStats. Just 288 | // don't do it! 289 | long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); 290 | long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); 291 | scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); 292 | scheduler.scheduleAtFixedRate( 293 | submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); 294 | } 295 | 296 | private void submitData() { 297 | final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); 298 | appendPlatformDataConsumer.accept(baseJsonBuilder); 299 | final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); 300 | appendServiceDataConsumer.accept(serviceJsonBuilder); 301 | JsonObjectBuilder.JsonObject[] chartData = 302 | customCharts.stream() 303 | .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) 304 | .filter(Objects::nonNull) 305 | .toArray(JsonObjectBuilder.JsonObject[]::new); 306 | serviceJsonBuilder.appendField("id", serviceId); 307 | serviceJsonBuilder.appendField("customCharts", chartData); 308 | baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); 309 | baseJsonBuilder.appendField("serverUUID", serverUuid); 310 | baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); 311 | JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); 312 | scheduler.execute( 313 | () -> { 314 | try { 315 | // Send the data 316 | sendData(data); 317 | } catch (Exception e) { 318 | // Something went wrong! :( 319 | if (logErrors) { 320 | errorLogger.accept("Could not submit bStats metrics data", e); 321 | } 322 | } 323 | }); 324 | } 325 | 326 | private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { 327 | if (logSentData) { 328 | infoLogger.accept("Sent bStats metrics data: " + data.toString()); 329 | } 330 | String url = String.format(REPORT_URL, platform); 331 | HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); 332 | // Compress the data to save bandwidth 333 | byte[] compressedData = compress(data.toString()); 334 | connection.setRequestMethod("POST"); 335 | connection.addRequestProperty("Accept", "application/json"); 336 | connection.addRequestProperty("Connection", "close"); 337 | connection.addRequestProperty("Content-Encoding", "gzip"); 338 | connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); 339 | connection.setRequestProperty("Content-Type", "application/json"); 340 | connection.setRequestProperty("User-Agent", "Metrics-Service/1"); 341 | connection.setDoOutput(true); 342 | try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { 343 | outputStream.write(compressedData); 344 | } 345 | StringBuilder builder = new StringBuilder(); 346 | try (BufferedReader bufferedReader = 347 | new BufferedReader(new InputStreamReader(connection.getInputStream()))) { 348 | String line; 349 | while ((line = bufferedReader.readLine()) != null) { 350 | builder.append(line); 351 | } 352 | } 353 | if (logResponseStatusText) { 354 | infoLogger.accept("Sent data to bStats and received response: " + builder); 355 | } 356 | } 357 | 358 | /** Checks that the class was properly relocated. */ 359 | private void checkRelocation() { 360 | // You can use the property to disable the check in your test environment 361 | if (System.getProperty("bstats.relocatecheck") == null 362 | || !System.getProperty("bstats.relocatecheck").equals("false")) { 363 | // Maven's Relocate is clever and changes strings, too. So we have to use this 364 | // little "trick" ... :D 365 | final String defaultPackage = 366 | new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); 367 | final String examplePackage = 368 | new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); 369 | // We want to make sure no one just copy & pastes the example and uses the wrong 370 | // package names 371 | if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) 372 | || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { 373 | throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); 374 | } 375 | } 376 | } 377 | 378 | /** 379 | * Gzips the given string. 380 | * 381 | * @param str The string to gzip. 382 | * @return The gzipped string. 383 | */ 384 | private static byte[] compress(final String str) throws IOException { 385 | if (str == null) { 386 | return null; 387 | } 388 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 389 | try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { 390 | gzip.write(str.getBytes(StandardCharsets.UTF_8)); 391 | } 392 | return outputStream.toByteArray(); 393 | } 394 | } 395 | 396 | public static class SimplePie extends CustomChart { 397 | 398 | private final Callable callable; 399 | 400 | /** 401 | * Class constructor. 402 | * 403 | * @param chartId The id of the chart. 404 | * @param callable The callable which is used to request the chart data. 405 | */ 406 | public SimplePie(String chartId, Callable callable) { 407 | super(chartId); 408 | this.callable = callable; 409 | } 410 | 411 | @Override 412 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 413 | String value = callable.call(); 414 | if (value == null || value.isEmpty()) { 415 | // Null = skip the chart 416 | return null; 417 | } 418 | return new JsonObjectBuilder().appendField("value", value).build(); 419 | } 420 | } 421 | 422 | public static class MultiLineChart extends CustomChart { 423 | 424 | private final Callable> callable; 425 | 426 | /** 427 | * Class constructor. 428 | * 429 | * @param chartId The id of the chart. 430 | * @param callable The callable which is used to request the chart data. 431 | */ 432 | public MultiLineChart(String chartId, Callable> callable) { 433 | super(chartId); 434 | this.callable = callable; 435 | } 436 | 437 | @Override 438 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 439 | JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); 440 | Map map = callable.call(); 441 | if (map == null || map.isEmpty()) { 442 | // Null = skip the chart 443 | return null; 444 | } 445 | boolean allSkipped = true; 446 | for (Map.Entry entry : map.entrySet()) { 447 | if (entry.getValue() == 0) { 448 | // Skip this invalid 449 | continue; 450 | } 451 | allSkipped = false; 452 | valuesBuilder.appendField(entry.getKey(), entry.getValue()); 453 | } 454 | if (allSkipped) { 455 | // Null = skip the chart 456 | return null; 457 | } 458 | return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); 459 | } 460 | } 461 | 462 | public static class AdvancedPie extends CustomChart { 463 | 464 | private final Callable> callable; 465 | 466 | /** 467 | * Class constructor. 468 | * 469 | * @param chartId The id of the chart. 470 | * @param callable The callable which is used to request the chart data. 471 | */ 472 | public AdvancedPie(String chartId, Callable> callable) { 473 | super(chartId); 474 | this.callable = callable; 475 | } 476 | 477 | @Override 478 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 479 | JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); 480 | Map map = callable.call(); 481 | if (map == null || map.isEmpty()) { 482 | // Null = skip the chart 483 | return null; 484 | } 485 | boolean allSkipped = true; 486 | for (Map.Entry entry : map.entrySet()) { 487 | if (entry.getValue() == 0) { 488 | // Skip this invalid 489 | continue; 490 | } 491 | allSkipped = false; 492 | valuesBuilder.appendField(entry.getKey(), entry.getValue()); 493 | } 494 | if (allSkipped) { 495 | // Null = skip the chart 496 | return null; 497 | } 498 | return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); 499 | } 500 | } 501 | 502 | public static class SimpleBarChart extends CustomChart { 503 | 504 | private final Callable> callable; 505 | 506 | /** 507 | * Class constructor. 508 | * 509 | * @param chartId The id of the chart. 510 | * @param callable The callable which is used to request the chart data. 511 | */ 512 | public SimpleBarChart(String chartId, Callable> callable) { 513 | super(chartId); 514 | this.callable = callable; 515 | } 516 | 517 | @Override 518 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 519 | JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); 520 | Map map = callable.call(); 521 | if (map == null || map.isEmpty()) { 522 | // Null = skip the chart 523 | return null; 524 | } 525 | for (Map.Entry entry : map.entrySet()) { 526 | valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); 527 | } 528 | return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); 529 | } 530 | } 531 | 532 | public static class AdvancedBarChart extends CustomChart { 533 | 534 | private final Callable> callable; 535 | 536 | /** 537 | * Class constructor. 538 | * 539 | * @param chartId The id of the chart. 540 | * @param callable The callable which is used to request the chart data. 541 | */ 542 | public AdvancedBarChart(String chartId, Callable> callable) { 543 | super(chartId); 544 | this.callable = callable; 545 | } 546 | 547 | @Override 548 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 549 | JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); 550 | Map map = callable.call(); 551 | if (map == null || map.isEmpty()) { 552 | // Null = skip the chart 553 | return null; 554 | } 555 | boolean allSkipped = true; 556 | for (Map.Entry entry : map.entrySet()) { 557 | if (entry.getValue().length == 0) { 558 | // Skip this invalid 559 | continue; 560 | } 561 | allSkipped = false; 562 | valuesBuilder.appendField(entry.getKey(), entry.getValue()); 563 | } 564 | if (allSkipped) { 565 | // Null = skip the chart 566 | return null; 567 | } 568 | return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); 569 | } 570 | } 571 | 572 | public static class DrilldownPie extends CustomChart { 573 | 574 | private final Callable>> callable; 575 | 576 | /** 577 | * Class constructor. 578 | * 579 | * @param chartId The id of the chart. 580 | * @param callable The callable which is used to request the chart data. 581 | */ 582 | public DrilldownPie(String chartId, Callable>> callable) { 583 | super(chartId); 584 | this.callable = callable; 585 | } 586 | 587 | @Override 588 | public JsonObjectBuilder.JsonObject getChartData() throws Exception { 589 | JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); 590 | Map> map = callable.call(); 591 | if (map == null || map.isEmpty()) { 592 | // Null = skip the chart 593 | return null; 594 | } 595 | boolean reallyAllSkipped = true; 596 | for (Map.Entry> entryValues : map.entrySet()) { 597 | JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); 598 | boolean allSkipped = true; 599 | for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { 600 | valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); 601 | allSkipped = false; 602 | } 603 | if (!allSkipped) { 604 | reallyAllSkipped = false; 605 | valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); 606 | } 607 | } 608 | if (reallyAllSkipped) { 609 | // Null = skip the chart 610 | return null; 611 | } 612 | return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); 613 | } 614 | } 615 | 616 | public abstract static class CustomChart { 617 | 618 | private final String chartId; 619 | 620 | protected CustomChart(String chartId) { 621 | if (chartId == null) { 622 | throw new IllegalArgumentException("chartId must not be null"); 623 | } 624 | this.chartId = chartId; 625 | } 626 | 627 | public JsonObjectBuilder.JsonObject getRequestJsonObject( 628 | BiConsumer errorLogger, boolean logErrors) { 629 | JsonObjectBuilder builder = new JsonObjectBuilder(); 630 | builder.appendField("chartId", chartId); 631 | try { 632 | JsonObjectBuilder.JsonObject data = getChartData(); 633 | if (data == null) { 634 | // If the data is null we don't send the chart. 635 | return null; 636 | } 637 | builder.appendField("data", data); 638 | } catch (Throwable t) { 639 | if (logErrors) { 640 | errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); 641 | } 642 | return null; 643 | } 644 | return builder.build(); 645 | } 646 | 647 | protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; 648 | } 649 | 650 | public static class SingleLineChart extends CustomChart { 651 | 652 | private final Callable callable; 653 | 654 | /** 655 | * Class constructor. 656 | * 657 | * @param chartId The id of the chart. 658 | * @param callable The callable which is used to request the chart data. 659 | */ 660 | public SingleLineChart(String chartId, Callable callable) { 661 | super(chartId); 662 | this.callable = callable; 663 | } 664 | 665 | @Override 666 | protected JsonObjectBuilder.JsonObject getChartData() throws Exception { 667 | int value = callable.call(); 668 | if (value == 0) { 669 | // Null = skip the chart 670 | return null; 671 | } 672 | return new JsonObjectBuilder().appendField("value", value).build(); 673 | } 674 | } 675 | 676 | /** 677 | * An extremely simple JSON builder. 678 | * 679 | *

While this class is neither feature-rich nor the most performant one, it's sufficient enough 680 | * for its use-case. 681 | */ 682 | public static class JsonObjectBuilder { 683 | 684 | private StringBuilder builder = new StringBuilder(); 685 | 686 | private boolean hasAtLeastOneField = false; 687 | 688 | public JsonObjectBuilder() { 689 | builder.append("{"); 690 | } 691 | 692 | /** 693 | * Appends a null field to the JSON. 694 | * 695 | * @param key The key of the field. 696 | * @return A reference to this object. 697 | */ 698 | public JsonObjectBuilder appendNull(String key) { 699 | appendFieldUnescaped(key, "null"); 700 | return this; 701 | } 702 | 703 | /** 704 | * Appends a string field to the JSON. 705 | * 706 | * @param key The key of the field. 707 | * @param value The value of the field. 708 | * @return A reference to this object. 709 | */ 710 | public JsonObjectBuilder appendField(String key, String value) { 711 | if (value == null) { 712 | throw new IllegalArgumentException("JSON value must not be null"); 713 | } 714 | appendFieldUnescaped(key, "\"" + escape(value) + "\""); 715 | return this; 716 | } 717 | 718 | /** 719 | * Appends an integer field to the JSON. 720 | * 721 | * @param key The key of the field. 722 | * @param value The value of the field. 723 | * @return A reference to this object. 724 | */ 725 | public JsonObjectBuilder appendField(String key, int value) { 726 | appendFieldUnescaped(key, String.valueOf(value)); 727 | return this; 728 | } 729 | 730 | /** 731 | * Appends an object to the JSON. 732 | * 733 | * @param key The key of the field. 734 | * @param object The object. 735 | * @return A reference to this object. 736 | */ 737 | public JsonObjectBuilder appendField(String key, JsonObject object) { 738 | if (object == null) { 739 | throw new IllegalArgumentException("JSON object must not be null"); 740 | } 741 | appendFieldUnescaped(key, object.toString()); 742 | return this; 743 | } 744 | 745 | /** 746 | * Appends a string array to the JSON. 747 | * 748 | * @param key The key of the field. 749 | * @param values The string array. 750 | * @return A reference to this object. 751 | */ 752 | public JsonObjectBuilder appendField(String key, String[] values) { 753 | if (values == null) { 754 | throw new IllegalArgumentException("JSON values must not be null"); 755 | } 756 | String escapedValues = 757 | Arrays.stream(values) 758 | .map(value -> "\"" + escape(value) + "\"") 759 | .collect(Collectors.joining(",")); 760 | appendFieldUnescaped(key, "[" + escapedValues + "]"); 761 | return this; 762 | } 763 | 764 | /** 765 | * Appends an integer array to the JSON. 766 | * 767 | * @param key The key of the field. 768 | * @param values The integer array. 769 | * @return A reference to this object. 770 | */ 771 | public JsonObjectBuilder appendField(String key, int[] values) { 772 | if (values == null) { 773 | throw new IllegalArgumentException("JSON values must not be null"); 774 | } 775 | String escapedValues = 776 | Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); 777 | appendFieldUnescaped(key, "[" + escapedValues + "]"); 778 | return this; 779 | } 780 | 781 | /** 782 | * Appends an object array to the JSON. 783 | * 784 | * @param key The key of the field. 785 | * @param values The integer array. 786 | * @return A reference to this object. 787 | */ 788 | public JsonObjectBuilder appendField(String key, JsonObject[] values) { 789 | if (values == null) { 790 | throw new IllegalArgumentException("JSON values must not be null"); 791 | } 792 | String escapedValues = 793 | Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); 794 | appendFieldUnescaped(key, "[" + escapedValues + "]"); 795 | return this; 796 | } 797 | 798 | /** 799 | * Appends a field to the object. 800 | * 801 | * @param key The key of the field. 802 | * @param escapedValue The escaped value of the field. 803 | */ 804 | private void appendFieldUnescaped(String key, String escapedValue) { 805 | if (builder == null) { 806 | throw new IllegalStateException("JSON has already been built"); 807 | } 808 | if (key == null) { 809 | throw new IllegalArgumentException("JSON key must not be null"); 810 | } 811 | if (hasAtLeastOneField) { 812 | builder.append(","); 813 | } 814 | builder.append("\"").append(escape(key)).append("\":").append(escapedValue); 815 | hasAtLeastOneField = true; 816 | } 817 | 818 | /** 819 | * Builds the JSON string and invalidates this builder. 820 | * 821 | * @return The built JSON string. 822 | */ 823 | public JsonObject build() { 824 | if (builder == null) { 825 | throw new IllegalStateException("JSON has already been built"); 826 | } 827 | JsonObject object = new JsonObject(builder.append("}").toString()); 828 | builder = null; 829 | return object; 830 | } 831 | 832 | /** 833 | * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. 834 | * 835 | *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. 836 | * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). 837 | * 838 | * @param value The value to escape. 839 | * @return The escaped value. 840 | */ 841 | private static String escape(String value) { 842 | final StringBuilder builder = new StringBuilder(); 843 | for (int i = 0; i < value.length(); i++) { 844 | char c = value.charAt(i); 845 | if (c == '"') { 846 | builder.append("\\\""); 847 | } else if (c == '\\') { 848 | builder.append("\\\\"); 849 | } else if (c <= '\u000F') { 850 | builder.append("\\u000").append(Integer.toHexString(c)); 851 | } else if (c <= '\u001F') { 852 | builder.append("\\u00").append(Integer.toHexString(c)); 853 | } else { 854 | builder.append(c); 855 | } 856 | } 857 | return builder.toString(); 858 | } 859 | 860 | /** 861 | * A super simple representation of a JSON object. 862 | * 863 | *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not 864 | * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, 865 | * JsonObject)}. 866 | */ 867 | public static class JsonObject { 868 | 869 | private final String value; 870 | 871 | private JsonObject(String value) { 872 | this.value = value; 873 | } 874 | 875 | @Override 876 | public String toString() { 877 | return value; 878 | } 879 | } 880 | } 881 | } --------------------------------------------------------------------------------