Skip to content

Commit

Permalink
Add update checker ability
Browse files Browse the repository at this point in the history
  • Loading branch information
arboriginal committed Feb 13, 2019
1 parent 823ffb3 commit a4fed95
Show file tree
Hide file tree
Showing 7 changed files with 176 additions and 49 deletions.
8 changes: 8 additions & 0 deletions lang/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ prefix: "&8[&eSimpleCompass&8] " # But you can also decide to remove the {prefi

# Message displayed when using the reload command
configuration_reloaded: "{prefix}&aConfiguration successfully reloaded"
# Message displayed when a new plugin version is found
plugin_check_update_available: "&bVersion &l{version}&b is out, &3current version: &l{current}"
# Message displayed when the plugin fail to check for an update
plugin_check_update_failed: "&6Can't check plugin update..."
# Message displayed when a new version is found for a tracker
tracker_check_update_available: "* &6Tracker {tracker}: &bversion &l{version}&b found &3(current: &l{current}&3)"
# Message displayed when the plugin fail to check for a tracker update
tracker_check_update_failed: "* &6Tracker {tracker}: &eCan't check for update"
# Message displayed when using the reload command and a tracker can't init correctly
tracker_disabled: "{prefix}&cTracker {tracker} can't be reloaded, it has been disabled."

Expand Down
8 changes: 8 additions & 0 deletions lang/fr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ prefix: "&8[&eSimpleCompass&8] " # Mais tu peux aussi le décider de retirer la

# Message affiché quand la commande reload est utilisée
configuration_reloaded: "{prefix}&aConfiguration rechargée"
# Message affiché quand une nouvelle version du plugin est trouvée
plugin_check_update_available: "&bLa version &l{version}&b est disponible, &3version actuelle : &l{current}"
# Message affiché quand le plugin ne parvient pas à vérifier ses mises à jour
plugin_check_update_failed: "&6La vérification de mise à jour du plugin a échoué"
# Message affiché quand une nouvelle version d'un tracker est trouvée
tracker_check_update_available: "* &6Tracker {tracker}: &bversion &l{version}&b trouvée &3(actuelle: &l{current}&3)"
# Message affiché quand le plugin ne parvient pas à vérifier les mises à jour d'un tracker
tracker_check_update_failed: "* &6Tracker {tracker}: &eLa recherche de mise à jour a échoué"
# Message affiché quand la commande reload est utilisée et qu'un tracker ne s'initialise pas correctement
tracker_disabled: "{prefix}&cLe tracker {tracker} n'a pas pu être rechargé, il a été désactivé."

Expand Down
4 changes: 4 additions & 0 deletions src/config.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# Choose lang file you want to use, actually, only en and fr exists, but you can set what you want...
language: en # If this lang file doesn't exist, a new one is created (copy of english, so you can edit it).

# If true, when you (re)load the plugin, it try to check if a new version is available
check_update: true

# You decide if your players can use both compass at the same time, or only one.
# In this case, you have to use « DISABLED » in one of the type's default option.
#
Expand Down Expand Up @@ -187,6 +190,7 @@ trackers_priorities:

# Advanced... Delays / cache durations (FYI: 20 ticks = 1 second if your server doesn't lag)
delays:
update_version_cache: 60 # (minute) Duration of cache of online version found (should stay large or you will reach rate limit from Github)
update_compass: 100 # (millisec) Compass datas refresh on player move, put 0 if you have predator's eyes
trackers_list: 2000 # (millisec) Active trackers list (by player) cache
death_position: 900 # (seconds) Time the last death location stays active
Expand Down
62 changes: 47 additions & 15 deletions src/me/arboriginal/SimpleCompass/plugin/AbstractTracker.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
Expand Down Expand Up @@ -39,7 +40,25 @@ public AbstractTracker(SimpleCompass plugin) {
}

// ----------------------------------------------------------------------------------------------
// Initialization methods
// Tracker methods
// ----------------------------------------------------------------------------------------------

public abstract String trackerID();

public String github() {
return null;
}

public String trackerName() {
return settings.getString("locales." + sc.config.getString("language") + ".name");
}

public String version() {
return "?";
}

// ----------------------------------------------------------------------------------------------
// Initialization and update methods
// ----------------------------------------------------------------------------------------------

/**
Expand All @@ -65,18 +84,41 @@ public boolean init() {
return true;
}

public void checkUpdate(CommandSender sender) {
if (!settings.getBoolean("settings.check_update", true)) return;

String github = github();

if (github == null) {
sendMessage(sender, "tracker_check_update_available",
ImmutableMap.of("tracker", trackerName(), "version", "new", "current", version()));
return;
}

String version = sc.githubVersion(github);

if (version == null)
sendMessage(sender, "tracker_check_update_failed", ImmutableMap.of("tracker", trackerName()));
else {
String current = version();
if (!version.equals(current))
sendMessage(sender, "tracker_check_update_available",
ImmutableMap.of("tracker", trackerName(), "version", version, "current", current));
}
}

// ----------------------------------------------------------------------------------------------
// Utils methods
// ----------------------------------------------------------------------------------------------

public void sendMessage(Player player, String key) {
sendMessage(player, key, null);
public void sendMessage(CommandSender sender, String key) {
sendMessage(sender, key, null);
}

public void sendMessage(Player player, String key, Map<String, String> placeholders) {
public void sendMessage(CommandSender sender, String key, Map<String, String> placeholders) {
if (key.isEmpty()) return;
String message = prepareMessage(key, placeholders);
if (!message.isEmpty()) player.sendMessage(message);
if (!message.isEmpty()) sender.sendMessage(message);
}

public String prepareMessage(String key) {
Expand Down Expand Up @@ -159,16 +201,6 @@ public TargetSelector requireTarget(TrackingActions action) {
}
}

// ----------------------------------------------------------------------------------------------
// Tracker methods
// ----------------------------------------------------------------------------------------------

public abstract String trackerID();

public String trackerName() {
return settings.getString("locales." + sc.config.getString("language") + ".name");
}

// ----------------------------------------------------------------------------------------------
// Targets methods
// ----------------------------------------------------------------------------------------------
Expand Down
95 changes: 67 additions & 28 deletions src/me/arboriginal/SimpleCompass/plugin/SimpleCompass.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package me.arboriginal.SimpleCompass.plugin;

import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
Expand All @@ -17,6 +19,8 @@
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import me.arboriginal.SimpleCompass.commands.InterfaceCommand;
import me.arboriginal.SimpleCompass.commands.OptionCommand;
import me.arboriginal.SimpleCompass.commands.TrackCommand;
Expand Down Expand Up @@ -73,6 +77,7 @@ public void onEnable() {

loadTrackers();
reloadConfig();
checkUpdate(getServer().getConsoleSender());

if (!trackers.isEmpty()) getCommand("scompass-track").setExecutor(new TrackCommand(this));

Expand Down Expand Up @@ -137,16 +142,44 @@ public boolean onCommand(CommandSender sender, Command command, String label, St
}

sendMessage(sender, "configuration_reloaded");
checkUpdate(sender);
return true;
}

return super.onCommand(sender, command, label, args);
}

// ----------------------------------------------------------------------------------------------
// Package methods: Helper methods for messages
// Public methods
// ----------------------------------------------------------------------------------------------

public TextComponent createClickableMessage(String text, Map<String, Map<String, String>> commands) {
TextComponent textComponent = new TextComponent();

for (String command : commands.keySet()) text = text.replace(command, "§k" + command + "§r");

for (BaseComponent component : TextComponent.fromLegacyText(text)) {
if (component instanceof TextComponent) {
Map<String, String> command = commands.get(((TextComponent) component).getText().trim());

if (command != null) {
if (command.containsKey("text")) ((TextComponent) component).setText("§r" + command.get("text"));

if (command.containsKey("click"))
component.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command.get("click")));

if (command.containsKey("hover"))
component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,
TextComponent.fromLegacyText(command.get("hover"))));
}
}

textComponent.addExtra(component);
}

return textComponent;
}

public String formatMessage(String message) {
return ChatColor.translateAlternateColorCodes('&', message);
}
Expand Down Expand Up @@ -174,6 +207,25 @@ public String formatTime(long time) {
return human.replaceFirst("^0+(?!$)", "");
}

public String githubVersion(String repository) {
String version = (String) cache.versionGet(repository);
if (version != null) return version;

String url = "https://api.github.com/repos/" + repository + "/releases";

try {
HttpURLConnection connexion = (HttpURLConnection) new URL(url).openConnection();
connexion.addRequestProperty("User-Agent", "SimpleCompass");
JsonElement element = new JsonParser().parse(new InputStreamReader(connexion.getInputStream()));

version = element.getAsJsonArray().get(0).getAsJsonObject().get("tag_name").getAsString();
}
catch (Exception e) {}

cache.versionSet(repository, version, config.getInt("delays.update_version_cache"));
return version;
}

public String prepareMessage(String key) {
return prepareMessage(key, null);
}
Expand Down Expand Up @@ -205,40 +257,27 @@ public void sendMessage(CommandSender sender, String key, Map<String, String> pl
}

// ----------------------------------------------------------------------------------------------
// Package methods: Helper methods for advanced messages
// Private methods
// ----------------------------------------------------------------------------------------------

public TextComponent createClickableMessage(String text, Map<String, Map<String, String>> commands) {
TextComponent textComponent = new TextComponent();

for (String command : commands.keySet()) text = text.replace(command, "§k" + command + "§r");

for (BaseComponent component : TextComponent.fromLegacyText(text)) {
if (component instanceof TextComponent) {
Map<String, String> command = commands.get(((TextComponent) component).getText().trim());

if (command != null) {
if (command.containsKey("text")) ((TextComponent) component).setText("§r" + command.get("text"));

if (command.containsKey("click"))
component.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command.get("click")));

if (command.containsKey("hover"))
component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,
TextComponent.fromLegacyText(command.get("hover"))));
}
}
private void checkUpdate(CommandSender sender) {
if (!config.getBoolean("check_update")) return;
String version = githubVersion("arboriginal/SimpleCompass");

textComponent.addExtra(component);
if (version == null)
sendMessage(sender, "plugin_check_update_failed");
else {
String current = getDescription().getVersion();
if (!version.equals(current))
sendMessage(sender, "plugin_check_update_available", ImmutableMap.of("version", version, "current", current));
}

return textComponent;
if (trackers.isEmpty()) return;
trackers.forEach((trackerID, tracker) -> {
tracker.checkUpdate(sender);
});
}

// ----------------------------------------------------------------------------------------------
// Private methods
// ----------------------------------------------------------------------------------------------

private void loadTrackers() {
File dir = new File(getDataFolder(), "trackers");
if (!dir.exists()) dir.mkdirs();
Expand Down
46 changes: 41 additions & 5 deletions src/me/arboriginal/SimpleCompass/utils/CacheUtil.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package me.arboriginal.SimpleCompass.utils;

import java.io.File;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import me.arboriginal.SimpleCompass.plugin.SimpleCompass;

public class CacheUtil {
private SimpleCompass sc;
private File vcf;
private FileConfiguration vcc;
private HashMap<UUID, HashMap<String, Data>> datas;

public static final int PERMANENT = -1;
Expand All @@ -16,19 +21,30 @@ public class CacheUtil {
// ----------------------------------------------------------------------------------------------

public CacheUtil(SimpleCompass plugin) {
sc = plugin;
sc = plugin;
vcf = new File(sc.getDataFolder(), "versionCache.yml");

if (!vcf.exists())
try {
vcf.createNewFile();
}
catch (Exception e) {
sc.getLogger().warning("Can't write to version cache file");
}

vcc = YamlConfiguration.loadConfiguration(vcf);
reset();
}

//-----------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------
// Static methods
// ----------------------------------------------------------------------------------------------

public static long now() {
return System.currentTimeMillis();
}

//-----------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------
// Public methods
// ----------------------------------------------------------------------------------------------

Expand All @@ -42,7 +58,6 @@ public void clear(UUID uid, String key) {

public Object get(UUID uid, String key) {
Data data = datas.get(uid).get(key);

return (data != null && (data.expire == PERMANENT || data.expire > now())) ? data.value : null;
}

Expand All @@ -60,7 +75,28 @@ public void set(UUID uid, String key, Object value, int duration) {
datas.get(uid).put(key, new Data((duration == PERMANENT) ? PERMANENT : now() + duration, value));
}

//-----------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------
// Public methods: Version update check cache
// ----------------------------------------------------------------------------------------------

public Object versionGet(String key) {
long expire = vcc.getLong("version." + key + ".expire", 0);
return (expire > now()) ? vcc.get("version." + key + ".value", null) : null;
}

public void versionSet(String key, Object value, int duration) {
vcc.set("version." + key + ".expire", now() + duration * 600000);
vcc.set("version." + key + ".value", value);

try {
vcc.save(vcf);
}
catch (Exception e) {
sc.getLogger().warning("Can't write to version cache file");
}
}

// ----------------------------------------------------------------------------------------------
// Private classes
// ----------------------------------------------------------------------------------------------

Expand Down
2 changes: 1 addition & 1 deletion src/plugin.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: SimpleCompass
description: Simple compass to help player who don't have sense of direction.
version: 0.9.1
version: 0.9.2

author: arboriginal
website: https://www.spigotmc.org/resources/simplecompass.63140/
Expand Down

0 comments on commit a4fed95

Please sign in to comment.