diff --git a/change_log.txt b/change_log.txt new file mode 100644 index 0000000..dfebc4a --- /dev/null +++ b/change_log.txt @@ -0,0 +1,51 @@ +2.13.51 +D1 +2.13.50 +D1 Added a config option for when a nickname is not set to use displayname or username. +D2 Added debug logs for previous changes. +D3 Added more debug code, and changed some defaults. +D4 Switched to i18n language files, reworked update checker. +2.13.49 +D1- Added support for Bloodmoon Advanced. +D2- Added a check for DisplayName when Essentials nick is returned as null. +D3- Added color formatter for displayNames when Essentials/VentureChat/HexNicks returns null +D4- Changed method for formatting displayNames in re: above. +D5 Added debug checks on nickname getter. +D6 Fixed issue with chars in HexNicks nicknames. +1.13_2.13.48 +D1- Added HexNicks support. +D2-3 Fixed HexNicks formatting. +D4- Finally fixed HexNicks json formatting. +D5- Minor changes to UpdateChecker Notifications. +1.13_2.13.47 +Added permission debug logging, "/sps check", and "/sps check playername" commands. +Anyone can check their own permissions, but only people with sps.op can check permissions of others. +Fixed an issue with update command causing a NPE. +Fixed an issue with the /sleep command always using world 0 as the Night/Storm check world. +Changed reloading method, added simplified Chinese(zh_CN) translation from (NagaseYami) +Added new config option "reset_insomnia" to reset the stat "time_since_rest" for all players in the sleeping player's world to prevent phantom spawning +Fixed text formatting with nicknames. +Added Japanese (ja_JP) translation from (mtmtyu) +1.13_2.13.46 +Fixed issue of broadcasting to world's not where sleep, cancel, dayskip were initiated. +Added config option for per world broadcasting. +Fixed issue of a floating bracket. +Fixed a minor bug involving an exception and a possible console spam. +Players with sps.unrestricted permission will have color sleepmsgs. +Fixed incomplete text issue. +Added new config option. exitbedcancel: false +Added tab complete for commands. +1.13_2.13.45 +UpdateChecker update, should no longer say there is an update when using a Dev version. +/sps update, now runs Asynchronously, which should not cause server freeze. +Add configs for Blacklist sleep/dayskip +Fix for issue reported by @nickly +Fixed config. +1.13_2.13.44 +Added color support in sleepmsgs. +Added RGB Color support in sleepmsgs. +Added color codes both and §xRRGGBB to sleepmsgs +Added Color and RGB Color support to the dayskipmsg (Edited via lang files.) +Changed getDisplayName to getName to remove prefixes added by other plugins. +Added Quotation marks around playername in the tellraw command of sendJson. (Added by ImDaBigBoss) +sleepmsgcolor and playernamecolor will be obsolete in the next version, but are needed for now. \ No newline at end of file diff --git a/config.yml b/config.yml index 9bd91ec..44683ce 100644 --- a/config.yml +++ b/config.yml @@ -1,11 +1,98 @@ -# change to false to stop auto-update-check -auto-update-check: default -# color of [CANCEL] -cancelcolor: default -# set to true to broadcast " canceled sleep." -# set to false not to broadcast that msg. -cancelbroadcast: default -# set to true before sending a log about an issue. -#logs trace data required to pinpoint where errors are. -debug: default -lang: default \ No newline at end of file +# DO NOT CHANGE VERSION +version: 1.0.7 +# +# Change to false to stop auto-update-check. +auto_update_check: true +# +# Set to true before sending a log about an issue. +# Logs trace data required to pinpoint where errors are. +debug: false +# +# Set the language to use, en_US, nl_NL, lol_US, fr_FR, de_DE, zh_CN, cs-CZ, pt_BR +lang: en_US +# +# Set Blacklist worlds, Names are Case Sensitive, World does not equal world +blacklist: + sleep: world_nether, world_the_end + dayskip: world_nether, world_the_end +# +# Should broadcasts be per world, or server wide? (Should be true for multiverse) +broadcast_per_world: true +# +# Should SPS reset the time_since_rest stat for all players in the world that the sleeping player is in? +reset_insomnia: false +# +# Enables fancy ANSI colors in console. +colorful_console: true +# +# Set whether to allow player to stop rain when it is not night. +clearrain_enabled: false +# +# If true this will disable all broadcast messages and allow anyone to sleep. +unrestrictedsleep: false +# +# Set wake time, Early (23000) or Normal (24000) +waketime: NORMAL +# +# Delay between sleep, and change to day, in seconds. Minimum 1, recommend 10. +sleepdelay: 10 +# +# Enable(true) or Disable(false) dayskipper +enabledayskipper: false +# Delay between request for DaySkip, and change to night, in seconds. Minimum 1, recommend 10. +dayskipdelay: 10 +# If true this will disable ability of players to cancel DaySkipper +unrestricteddayskipper: false +# Require DaySkipper item +dayskipperitemrequired: true +# +# Set the color of the [CANCEL] link text in broadcast messages. Format RED +# Colors: AQUA, BLACK, GOLD, GRAY, BLUE, GREEN, RED, YELLOW, WHITE +# DARK_AQUA, DARK_BLUE, DARK_GRAY, DARK_GREEN, DARK_RED, DARK_PURPLE, LIGHT_PURPLE +# MAGIC, BOLD, STRIKETHROUGH, UNDERLINE, ITALIC, RESET +cancelcolor: RED +cancelbracketcolor: YELLOW +# Sleep message color, see above +sleepmsgcolor: WHITE +# Player name color, see above +playernamecolor: WHITE +# +# Set to true to have SPS cancel sleep if the player exits their bed. +exitbedcancel: false +# Set if cancel is shown or not. +display_cancel: true +# Set to true to broadcast " canceled sleep." +# Set to false not to broadcast that message. +cancelbroadcast: true +# +# Set the time limit in seconds which a player must wait between attempting to sleep again. +# This prevents a user from spamming chat with sleep messages. +# Set to 0 to disable. +sleeplimit: 60 +# Set the time limit in seconds which a player must wait between attempting to cancel again. +# This prevents a user from spamming chat with cancel messages. +# Set to 0 to disable. +cancellimit: 60 +# +# Set whether the player should be told it must be night to use. +notifymustbenight: false +# +# Should SPS use the Player's DisplayName(true) or UserName(false), if they have no set Nickname? +nickname: + usedisplayname: true +# +# Set to true to use random sleep msgs. +randomsleepmsgs: true +# +# Set to the number of sleep msgs +numberofsleepmsgs: 5 +# Set msgs for random sleep msgs here "sleepmsg#: msg here" +# Don't forget the space between : and the start of the message. +# Color codes are now usable in sleepmsgs, Example: BlackReset +# RGB format is §xFF00FF (§xFFFFFF §x000000i§x999999s §x111111s§x888888l§x222222e§x777777e§x333333p§x666666i§x444444n§x555555g) +# THERE MUST BE A COLOR CODE IN FRONT +sleepmsg1: §xFFFFFF §xFF0000is §xFF7F00s§xFFFF00l§x00FF00ee§x0000FFpi§x4b0082n§x9400D3g +sleepmsg2: §xFFFFFF §x00FFFFwent to bed. Sweet Dreams +sleepmsg3: Shhh! §xFFFFFF §xFF0000is §xFF00FFtrying §x0000FFto §x00FF00sleep! +sleepmsg4: §xFFFFFF §xFF00FFis asleep at the wheel +sleepmsg5: §xFFFFFFNO ONE ...\n§xFFFFFF §xFFFF00go to bed. \ No newline at end of file diff --git a/lang/lang.properties b/lang/lang.properties new file mode 100644 index 0000000..5763799 --- /dev/null +++ b/lang/lang.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Cancels Single Player Sleep. Does not change to day. +sps.command.spshelp=Shows SinglePlayerSleep help. +sps.command.spsreload=Reload config file. +sps.command.spsupdate=Check for update. +sps.command.toggledebug=Temporarily toggles debug. +sps.message.bloodmoon=You can not sleep during a bloodmoon. +sps.message.boolean.true=TRUE +sps.message.boolean.false=FALSE +sps.message.cancel=CANCEL +sps.message.canceledsleep= canceled sleeping. +sps.message.cancelunrestricted=Canceling is disabled. +sps.message.clickcancel=Click to cancel sleep +sps.message.dayskipblackbed=Bed must be black to use DaySkipper. +sps.message.dayskipcancel=CANCEL +sps.message.dayskipcanceled= canceled DaySkip. +sps.message.dayskipclickcancel=Click to cancel DaySkip +sps.message.dayskipmsg= wants to sleep the day away... +sps.message.dayskipmsgcommand= wants to sleep the day away... +sps.message.dayskipsettime=Setting time to night. +sps.message.debugtrue=Debug set to . +sps.message.issleep= is sleeping. +sps.message.mustbeday=It must be day to use. +sps.message.mustbenight=It must be night to use. +sps.message.nightorstorm=It must be night or storming to sleep. +sps.message.nocancel=You cannot cancel this sleep or there is nothing to cancel. +sps.message.noperm=You do not have permission to use +sps.message.notop=You are not OP, or auto-update-check is set to false in config.yml +sps.message.reloaded=SinglePlayerSleep has been reloaded. +sps.message.respawnpointmsg=Respawn point set. +sps.message.setdownfall=Clearing downfall +sps.message.setthunder=Clearing thunderstorm +sps.message.settime=Setting time to day +sps.message.sleepcommand= is sleeping +sps.message.sleephelp=subject to server admin approval +sps.message.sleeplimit=You can not do that for seconds +sps.message.touse=Sleep in bed to use. +sps.message.update.current=auto-update-check has been set to +sps.message.update.will=will check for updates! +sps.message.update.wont=will not check for updates! +sps.variable.boolean=Argument must be boolean. Usage +sps.version.curvers=Version is up to date! +sps.version.donate.message=Donate to the plugin maker. +sps.version.donate=Donate +sps.version.download=Download +sps.version.message=There is a new version of available! +sps.version.new_vers=Latest version +sps.version.new_version=New version available! +sps.version.notes.message=View the Notes. +sps.version.notes=Notes +sps.version.old_vers= Your version +sps.version.please_update=Please update to the newest version. +sps.version.update.error=Could not process update check \ No newline at end of file diff --git a/lang/lang_cs_CZ.properties b/lang/lang_cs_CZ.properties new file mode 100644 index 0000000..fd98f1e --- /dev/null +++ b/lang/lang_cs_CZ.properties @@ -0,0 +1,49 @@ +sps.command.cancelhelp=Zruší spánek pro jednoho hráce. Nemení se na den. +sps.command.spshelp=Zobrazuje nápovedu SinglePlayerSleep. +sps.command.spsreload=Znovu nactete konfiguracní soubor. +sps.command.spsupdate=Zkontrolovat aktualizace. +sps.message.bloodmoon=Během krevního Měsíce nemůžete spát. +sps.message.boolean.true=PRÁVDA +sps.message.boolean.false=NEPRAVDA +sps.message.cancel=ZRUŠIT +sps.message.canceledsleep= zrušil spánek. +sps.message.cancelunrestricted=Zrušení je deaktivováno. +sps.message.clickcancel=Klepnutím zrušíte spánek +sps.message.dayskipblackbed=Aby bylo možné používat DaySkipper, musí být postel černá. +sps.message.dayskipcancel=ZRUŠIT +sps.message.dayskipcanceled= zrušil DaySkip. +sps.message.dayskipclickcancel=Klepnutím zrušíte DaySkip +sps.message.dayskipmsg= chce přeskočit den... +sps.message.dayskipmsgcommand= chce přeskočit den... +sps.message.dayskipsettime=Nastavení času na noc. +sps.message.issleep= spí. +sps.message.mustbeday=To musí být den k použití. +sps.message.mustbenight=Musí to být noc. +sps.message.nightorstorm=spát, musí to být noc nebo boure +sps.message.nocancel=Tento spánek nelze zrušit nebo není co zrušit. +sps.message.noperm=Nemáte oprávnení k použití +sps.message.notop=Nejste OP nebo je v config.yml nastavena automatická aktualizace na false +sps.message.reloaded=SinglePlayerSleep byl znovu načten. +sps.message.respawnpointmsg=Místo oživení nastaveno +sps.message.setdownfall=Zastavuje se déšt +sps.message.setthunder=Vymazání bourky +sps.message.settime=Nastavení casu na den +sps.message.sleepcommand= spí +sps.message.sleephelp=podléhá schválení správcem serveru +sps.message.sleeplimit=Nemužete to udelat tak brzy. +sps.message.touse=Spát v posteli k použití. +sps.message.update.current=automatická aktualizace byla nastavena na +sps.message.update.will=zkontroluje aktualizace! +sps.message.update.wont=nebude kontrolovat aktualizace! +sps.variable.boolean=Argument musí být booleovský. Používání +sps.version.donate=Darujte +sps.version.donate.message=Podpořte tvůrce pluginu. +sps.version.download=Stažení +sps.version.update.error=Nepodařilo se zpracovat kontrolu aktualizace. +sps.version.message=K dispozici je nová verze ! +sps.version.new_vers=Nejnovější verze +sps.version.new_version=K dispozici nová verze! +sps.version.notes=Poznámky +sps.version.notes.message=Zobrazit poznámky. +sps.version.old_vers= Vaše verze +sps.version.please_update=Aktualizujte prosím na nejnovější verzi. \ No newline at end of file diff --git a/lang/lang_de_DE.properties b/lang/lang_de_DE.properties new file mode 100644 index 0000000..dfd92e5 --- /dev/null +++ b/lang/lang_de_DE.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Bricht Single Player Sleep . Ist nicht zu Tag ändern. +sps.command.spshelp=Zeigt SinglePlayerSleep Hilfe. +sps.command.spsreload=Reload Config-Datei. +sps.command.spsupdate=Auf Update überprüfen. +sps.command.toggledebug=Schaltet das Debugging vorübergehend um. +sps.message.bloodmoon=Sie können während eines Blutmondes nicht schlafen. +sps.message.boolean.true=WAHR +sps.message.boolean.false=FALSE +sps.message.cancel=STORNIEREN +sps.message.canceledsleep= storniert schlafen. +sps.message.cancelunrestricted=Das Abbrechen des ist deaktiviert. +sps.message.clickcancel=Klicken Sie Schlaf abbrechen +sps.message.dayskipblackbed=Das Bett muss schwarz sein, um DaySkipper nutzen zu können. +sps.message.dayskipcancel=STORNIEREN +sps.message.dayskipcanceled= hat DaySkip abgesagt. +sps.message.dayskipclickcancel=Klicken Sie hier, um DaySkip abzubrechen +sps.message.dayskipmsg= möchte den ganzen Tag schlafen... +sps.message.dayskipmsgcommand= möchte den ganzen Tag schlafen... +sps.message.dayskipsettime=Zeit auf Nacht stellen. +sps.message.debugtrue=Debug auf boolean gesetzt. +sps.message.issleep= schläft. +sps.message.mustbeday=Es muss Tag sein, um zu verwenden. +sps.message.mustbenight=Es muss nachts zu schlafen verwenden. +sps.message.nightorstorm=Es muss Nacht oder Sturm sein, um zu schlafen. +sps.message.nocancel=Sie können diesen Schlaf nicht abbrechen oder es gibt nichts zu annullieren. +sps.message.noperm=Sie haben keine Berechtigung +sps.message.notop=Sie sind nicht OP , oder Auto-Update-Check auf false gesetzt ist in config.yml +sps.message.reloaded=SinglePlayerSleep wurde neu geladen. +sps.message.respawnpointmsg=Wiedereinstiegspunkt gesetzt +sps.message.setdownfall=Clearing regen +sps.message.setthunder=Clearing Gewitter +sps.message.settime=Abbindezeit zu Tag +sps.message.sleepcommand= schläft +sps.message.sleephelp=vorbehaltlich Serveradministrator Genehmigung +sps.message.sleeplimit=Das kann man so schnell nicht mehr machen. +sps.message.touse=Schlafen im Bett zu benutzen. +sps.message.update.current=auto-update-check wurde eingestellt +sps.message.update.will=wird nach Updates gesucht! +sps.message.update.wont=wird nicht nach Updates suchen! +sps.variable.boolean=Argument muss boolean sein . Verwendung +sps.version.curvers=Version ist auf dem neuesten Stand! +sps.version.donate=Spenden +sps.version.donate.message=Spenden Sie dem Plugin-Hersteller. +sps.version.download=Herunterladen +sps.version.update.error=Aktualisierungsprüfung konnte nicht durchgeführt werden. +sps.version.message=Es ist eine neue Version von verfügbar! +sps.version.new_vers=Neueste Version +sps.version.new_version=Neue Version verfügbar! +sps.version.notes=Notizen +sps.version.notes.message=Hinweise anzeigen. +sps.version.old_vers= Deine Version +sps.version.please_update=Bitte aktualisieren Sie auf die neueste Version. \ No newline at end of file diff --git a/lang/lang_en_US.properties b/lang/lang_en_US.properties new file mode 100644 index 0000000..5763799 --- /dev/null +++ b/lang/lang_en_US.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Cancels Single Player Sleep. Does not change to day. +sps.command.spshelp=Shows SinglePlayerSleep help. +sps.command.spsreload=Reload config file. +sps.command.spsupdate=Check for update. +sps.command.toggledebug=Temporarily toggles debug. +sps.message.bloodmoon=You can not sleep during a bloodmoon. +sps.message.boolean.true=TRUE +sps.message.boolean.false=FALSE +sps.message.cancel=CANCEL +sps.message.canceledsleep= canceled sleeping. +sps.message.cancelunrestricted=Canceling is disabled. +sps.message.clickcancel=Click to cancel sleep +sps.message.dayskipblackbed=Bed must be black to use DaySkipper. +sps.message.dayskipcancel=CANCEL +sps.message.dayskipcanceled= canceled DaySkip. +sps.message.dayskipclickcancel=Click to cancel DaySkip +sps.message.dayskipmsg= wants to sleep the day away... +sps.message.dayskipmsgcommand= wants to sleep the day away... +sps.message.dayskipsettime=Setting time to night. +sps.message.debugtrue=Debug set to . +sps.message.issleep= is sleeping. +sps.message.mustbeday=It must be day to use. +sps.message.mustbenight=It must be night to use. +sps.message.nightorstorm=It must be night or storming to sleep. +sps.message.nocancel=You cannot cancel this sleep or there is nothing to cancel. +sps.message.noperm=You do not have permission to use +sps.message.notop=You are not OP, or auto-update-check is set to false in config.yml +sps.message.reloaded=SinglePlayerSleep has been reloaded. +sps.message.respawnpointmsg=Respawn point set. +sps.message.setdownfall=Clearing downfall +sps.message.setthunder=Clearing thunderstorm +sps.message.settime=Setting time to day +sps.message.sleepcommand= is sleeping +sps.message.sleephelp=subject to server admin approval +sps.message.sleeplimit=You can not do that for seconds +sps.message.touse=Sleep in bed to use. +sps.message.update.current=auto-update-check has been set to +sps.message.update.will=will check for updates! +sps.message.update.wont=will not check for updates! +sps.variable.boolean=Argument must be boolean. Usage +sps.version.curvers=Version is up to date! +sps.version.donate.message=Donate to the plugin maker. +sps.version.donate=Donate +sps.version.download=Download +sps.version.message=There is a new version of available! +sps.version.new_vers=Latest version +sps.version.new_version=New version available! +sps.version.notes.message=View the Notes. +sps.version.notes=Notes +sps.version.old_vers= Your version +sps.version.please_update=Please update to the newest version. +sps.version.update.error=Could not process update check \ No newline at end of file diff --git a/lang/lang_es_ES.properties b/lang/lang_es_ES.properties new file mode 100644 index 0000000..588fad9 --- /dev/null +++ b/lang/lang_es_ES.properties @@ -0,0 +1,51 @@ +sps.command.cancelhelp=Cancela Single Player Sleep. No cambia al día. +sps.command.spshelp=Muestra la ayuda de SinglePlayerSleep. +sps.command.spsreload=Racargar el archivo de configuración. +sps.command.spsupdate=Comprobar si hay actualizaciones. +sps.command.toggledebug=Activa o desactiva temporalmente la depuración. +sps.message.bloodmoon=No puedes dormir durante una luna de sangre. +sps.message.boolean.true=VERDADERO +sps.message.boolean.false=FALSO +sps.message.cancel=CANCELAR +sps.message.canceledsleep= no quiere dormir. +sps.message.cancelunrestricted=Cancelar está deshabilitado. +sps.message.clickcancel=Haz click para no dormir +sps.message.dayskipblackbed=La cama debe ser negra para usar DaySkipper. +sps.message.dayskipcancel=CANCELAR +sps.message.dayskipcanceled= no quiere saltarse el dia. +sps.message.dayskipclickcancel=Click para cancelar el salto de dia +sps.message.dayskipmsg= quiere dormir todo el día ... +sps.message.dayskipmsgcommand= quiere dormir todo el día ... +sps.message.dayskipsettime=Fijando la hora a de noche. +sps.message.debugtrue=Debug establecido en boolean. +sps.message.issleep= está dormido. +sps.message.mustbeday=Debe ser de día para usar eso. +sps.message.mustbenight=Debe ser de noche para usar eso. +sps.message.nightorstorm=Solo puedes dormir de noche o durante tormentas eléctricas. +sps.message.nocancel=No puedes cancelar esto, o no hay nada que cancelar. +sps.message.noperm=No tienes permisos para usar eso +sps.message.notop=No eres operador, o el auto-update-check esta desactivado [false] en config.yml +sps.message.reloaded=Se ha recargado SinglePlayerSleep. +sps.message.respawnpointmsg=Punto de reaparición fijado. +sps.message.setdownfall=Despejando el cielo +sps.message.setthunder=Despejando el cielo +sps.message.settime=Haciendo de día +sps.message.sleepcommand= está durmiendo +sps.message.sleephelp=sujeto a la aprobación del administrador del servidor +sps.message.sleeplimit=No puedes hacer esto todavía. +sps.message.touse=Duerme en una cama para utilizarlo. +sps.message.update.current=auto-update-check ha sido fijado a +sps.message.update.will=se comprobará si hay actualizaciones! +sps.message.update.wont=no se comprobará si hay actualizaciones! +sps.variable.boolean=El argumento debe ser booleano. Uso +sps.version.donate=Donar +sps.version.donate.message=Done a la creadora del plugin. +sps.version.download=Descargar +sps.version.update.error=No se pudo procesar la comprobación de actualización. +sps.version.message=¡Hay una nueva versión de disponible! +sps.version.new_vers=Última versión +sps.version.new_version=¡Hay una nueva versión disponible! +sps.version.notes=Notas +sps.version.notes.message=Ver las notas. +sps.version.old_vers= Tu versión +sps.version.please_update=Por favor, actualiza a la versión más reciente. \ No newline at end of file diff --git a/lang/lang_es_MX.properties b/lang/lang_es_MX.properties new file mode 100644 index 0000000..588fad9 --- /dev/null +++ b/lang/lang_es_MX.properties @@ -0,0 +1,51 @@ +sps.command.cancelhelp=Cancela Single Player Sleep. No cambia al día. +sps.command.spshelp=Muestra la ayuda de SinglePlayerSleep. +sps.command.spsreload=Racargar el archivo de configuración. +sps.command.spsupdate=Comprobar si hay actualizaciones. +sps.command.toggledebug=Activa o desactiva temporalmente la depuración. +sps.message.bloodmoon=No puedes dormir durante una luna de sangre. +sps.message.boolean.true=VERDADERO +sps.message.boolean.false=FALSO +sps.message.cancel=CANCELAR +sps.message.canceledsleep= no quiere dormir. +sps.message.cancelunrestricted=Cancelar está deshabilitado. +sps.message.clickcancel=Haz click para no dormir +sps.message.dayskipblackbed=La cama debe ser negra para usar DaySkipper. +sps.message.dayskipcancel=CANCELAR +sps.message.dayskipcanceled= no quiere saltarse el dia. +sps.message.dayskipclickcancel=Click para cancelar el salto de dia +sps.message.dayskipmsg= quiere dormir todo el día ... +sps.message.dayskipmsgcommand= quiere dormir todo el día ... +sps.message.dayskipsettime=Fijando la hora a de noche. +sps.message.debugtrue=Debug establecido en boolean. +sps.message.issleep= está dormido. +sps.message.mustbeday=Debe ser de día para usar eso. +sps.message.mustbenight=Debe ser de noche para usar eso. +sps.message.nightorstorm=Solo puedes dormir de noche o durante tormentas eléctricas. +sps.message.nocancel=No puedes cancelar esto, o no hay nada que cancelar. +sps.message.noperm=No tienes permisos para usar eso +sps.message.notop=No eres operador, o el auto-update-check esta desactivado [false] en config.yml +sps.message.reloaded=Se ha recargado SinglePlayerSleep. +sps.message.respawnpointmsg=Punto de reaparición fijado. +sps.message.setdownfall=Despejando el cielo +sps.message.setthunder=Despejando el cielo +sps.message.settime=Haciendo de día +sps.message.sleepcommand= está durmiendo +sps.message.sleephelp=sujeto a la aprobación del administrador del servidor +sps.message.sleeplimit=No puedes hacer esto todavía. +sps.message.touse=Duerme en una cama para utilizarlo. +sps.message.update.current=auto-update-check ha sido fijado a +sps.message.update.will=se comprobará si hay actualizaciones! +sps.message.update.wont=no se comprobará si hay actualizaciones! +sps.variable.boolean=El argumento debe ser booleano. Uso +sps.version.donate=Donar +sps.version.donate.message=Done a la creadora del plugin. +sps.version.download=Descargar +sps.version.update.error=No se pudo procesar la comprobación de actualización. +sps.version.message=¡Hay una nueva versión de disponible! +sps.version.new_vers=Última versión +sps.version.new_version=¡Hay una nueva versión disponible! +sps.version.notes=Notas +sps.version.notes.message=Ver las notas. +sps.version.old_vers= Tu versión +sps.version.please_update=Por favor, actualiza a la versión más reciente. \ No newline at end of file diff --git a/lang/lang_fr_FR.properties b/lang/lang_fr_FR.properties new file mode 100644 index 0000000..e5092b7 --- /dev/null +++ b/lang/lang_fr_FR.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Annule Single Player Sleep. Ne change pas le jour. +sps.command.spshelp=Montre SinglePlayerSleep aide. +sps.command.spsreload=Recharger fichier config. +sps.command.spsupdate=Vérifier la mise à jour. +sps.command.toggledebug=Bascule temporairement le débogage. +sps.message.bloodmoon=Vous ne pouvez pas dormir pendant une lune de sang. +sps.message.boolean.true=VRAI +sps.message.boolean.false=FAUX +sps.message.cancel=ANNULER +sps.message.canceledsleep= couchage annulé. +sps.message.cancelunrestricted=L'annulation du est désactivée. +sps.message.clickcancel=Cliquez pour annuler le sommeil +sps.message.dayskipblackbed=Le lit doit être noir pour utiliser DaySkipper. +sps.message.dayskipcancel=ANNULER +sps.message.dayskipcanceled= a annulé DaySkip. +sps.message.dayskipclickcancel=Cliquez pour annuler DaySkip +sps.message.dayskipmsg= veut dormir toute la journée... +sps.message.dayskipmsgcommand= veut dormir toute la journée... +sps.message.dayskipsettime=Réglage de l'heure de la nuit. +sps.message.debugtrue=Debug défini sur boolean. +sps.message.issleep= dort. +sps.message.mustbeday=Il doit être jour à utiliser. +sps.message.mustbenight=Il doit être la nuit pour utilisation. +sps.message.nightorstorm=Ce doit être la nuit ou la prise de sommeil. +sps.message.nocancel=Vous ne pouvez pas annuler ce sommeil ou il n'y a rien à canCel. +sps.message.noperm=Vous n'êtes pas autorisé à utiliser +sps.message.notop=Vous n'êtes pas OP , ou auto-update-check est définie sur false dans config.yml +sps.message.reloaded=SinglePlayerSleep a été rechargé. +sps.message.respawnpointmsg=Point de réapparition défini +sps.message.setdownfall=Effacement de pluie +sps.message.setthunder=Clearing orage +sps.message.settime=Réglage de l'heure à jour +sps.message.sleepcommand= dort +sps.message.sleephelp=sous réserve de serveur approbation de l'administrateur +sps.message.sleeplimit=Vous ne pouvez plus le faire si tôt. +sps.message.touse=Dormir dans un lit à utiliser. +sps.message.update.current=auto-update-check a été mis à +sps.message.update.will=va vérifier les mises à jour! +sps.message.update.wont=ne seront pas les mises à jour! +sps.variable.boolean=L'argument doit être booléen . Usage +sps.version.curvers=Version actuelle est! +sps.version.donate=Faire un don +sps.version.donate.message=Faites un don au créateur du plugin. +sps.version.download=Télécharger +sps.version.update.error=Impossible de traiter la vérification de mise à jour. +sps.version.message=Une nouvelle version de est disponible! +sps.version.new_vers=Version la plus récente +sps.version.new_version=Nouvelle version disponible! +sps.version.notes=Remarques +sps.version.notes.message=Afficher les notes. +sps.version.old_vers= Ta version +sps.version.please_update=Veuillez mettre à jour vers la version la plus récente. \ No newline at end of file diff --git a/lang/lang_hu_HU.properties b/lang/lang_hu_HU.properties new file mode 100644 index 0000000..89a26a1 --- /dev/null +++ b/lang/lang_hu_HU.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Megszakítja az alvást. A napszak nem fog nappalra váltani. +sps.command.spshelp=SinglePlayerSleep segítség. +sps.command.spsreload=Config fájl újratöltése. +sps.command.spsupdate=Frissítés keresése. +sps.command.toggledebug=Ideiglenesen átkapcsolja a debug-ot. +sps.message.bloodmoon=Nem alhatsz vérhold idején. +sps.message.boolean.true=IGAZ +sps.message.boolean.false=HAMIS +sps.message.cancel=MEGSZAKÍTÁS +sps.message.canceledsleep= megszakította az alvást. +sps.message.cancelunrestricted=A megszakítás ki van kapcsolva. +sps.message.clickcancel=Kattints ide az alvás megszakításához +sps.message.dayskipblackbed=Átalvást csak fekete színű ággyal lehet használni. +sps.message.dayskipcancel=MEGSZAKÍTÁS +sps.message.dayskipcanceled= megszakította a nap átalvását. +sps.message.dayskipclickcancel=Kattints az átalvás megszakításához +sps.message.dayskipmsg= szeretné átaludni az egész hátralevő napot... +sps.message.dayskipmsgcommand= szeretné átaludni az egész hátralevő napot... +sps.message.dayskipsettime=A napszak éjszakára vált. +sps.message.debugtrue=Debug true értékre állítva. +sps.message.issleep= alszik. +sps.message.mustbeday=Csak nappal használható. +sps.message.mustbenight=Csak éjjel használható. +sps.message.nightorstorm=Csak éjjel vagy viharban lehet aludni. +sps.message.nocancel=Ezt az alvást nem szakíthatod meg vagy nincs is mit megszakítani. +sps.message.noperm=Nincs rá engedélyed, hogy használd +sps.message.notop=Nem vagy OP, vagy az auto-update-check false-ra van állítva a config.yml-ben +sps.message.reloaded=A SinglePlayerSleep újraindult. +sps.message.respawnpointmsg=Újraszületési pont beállítva. +sps.message.setdownfall=Napszak törlése +sps.message.setthunder=Vihar törlése +sps.message.settime=Napszak nappalra állítása +sps.message.sleepcommand= alszik +sps.message.sleephelp=a szerver adminja hagyhatja jóvá +sps.message.sleeplimit=Ezt nem csinálhatod még másodpercig +sps.message.touse=A használathoz ágyban kell aludnod. +sps.message.update.current=auto-update-check értéke +sps.message.update.will=frissítéseket fog keresni! +sps.message.update.wont=nem fog frissítéseket keresni! +sps.variable.boolean=Az érték csak true vagy false lehet. Használat +sps.version.curvers=Verzió naprakész! +sps.version.donate.message=Adományozz a plugin készítőjének. +sps.version.donate=Adományozás +sps.version.download=Letöltés +sps.version.message= új verziója elérhető! +sps.version.new_vers=Legfrissebb verzió +sps.version.new_version=Új verzió elérhető! +sps.version.notes.message=Megjegyzések megtekintése. +sps.version.notes=Megjegyzések +sps.version.old_vers= Az Ön verziója +sps.version.please_update=Kérjük, frissítse a legújabb verzióra. +sps.version.update.error=Nem sikerült feldolgozni az frissítés ellenőrzést. \ No newline at end of file diff --git a/lang/lang_it_IT.properties b/lang/lang_it_IT.properties new file mode 100644 index 0000000..a1c408f --- /dev/null +++ b/lang/lang_it_IT.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Annulla il sonno singolo del player. Non cambia il tempo in giorno. +sps.command.spshelp=Mostra l'aiuto di SinglePlayerSleep. +sps.command.spsreload=Ricarica il file di configurazione. +sps.command.spsupdate=Verifica la presenza di aggiornamenti. +sps.command.toggledebug=Attiva/disattiva temporaneamente la modalità debug. +sps.message.bloodmoon=Non puoi dormire durante una luna di sangue. +sps.message.boolean.true=VERO +sps.message.boolean.false=FALSO +sps.message.cancel=ANNULLA +sps.message.canceledsleep= ha annullato il sonno. +sps.message.cancelunrestricted=L'annullamento è disattivato. +sps.message.clickcancel=Clicca per annullare il sonno +sps.message.dayskipblackbed=Il letto deve essere nero per usare il DaySkipper. +sps.message.dayskipcancel=ANNULLA +sps.message.dayskipcanceled= ha annullato il DaySkip. +sps.message.dayskipclickcancel=Clicca per annullare il DaySkip +sps.message.dayskipmsg= vuole dormire il giorno via... +sps.message.dayskipmsgcommand= vuole dormire il giorno via... +sps.message.dayskipsettime=Impostando il tempo sulla notte. +sps.message.debugtrue=Debug impostato su . +sps.message.issleep= sta dormendo. +sps.message.mustbeday=Deve essere giorno per usare. +sps.message.mustbenight=Deve essere notte per usare. +sps.message.nightorstorm=Deve essere notte o in una tempesta per poter dormire. +sps.message.nocancel=Non puoi interrompere il sonno o non c'è nulla da interrompere. +sps.message.noperm=Non hai il permesso di utilizzare +sps.message.notop=Non sei OP, oppure l'auto-update-check è impostato su false nel file config.yml +sps.message.reloaded=SinglePlayerSleep è stato ricaricato. +sps.message.respawnpointmsg=Punto di ripartenza impostato. +sps.message.setdownfall=Rimuovendo la pioggia +sps.message.setthunder=Rimuovendo la tempesta +sps.message.settime=Impostazione del tempo su giorno +sps.message.sleepcommand= sta dormendo +sps.message.sleephelp=soggetto all'approvazione dell'amministratore del server +sps.message.sleeplimit=Non puoi farlo per secondi +sps.message.touse=Dormi nel letto per poter utilizzare questa funzione. +sps.message.update.current=auto-update-check è stato impostato su +sps.message.update.will=verificherà la presenza di aggiornamenti! +sps.message.update.wont=non verificherà gli aggiornamenti! +sps.variable.boolean=L'argomento deve essere booleano. Utilizzo +sps.version.curvers=La versione è aggiornata! +sps.version.donate=Fai una donazione +sps.version.donate.message=Fai una donazione al creatore della plugin. +sps.version.download=Scarica +sps.version.update.error=Impossibile elaborare il controllo dell'aggiornamento. +sps.version.message=C'è una nuova versione di disponibile! +sps.version.new_vers=Ultima versione +sps.version.new_version=Nuova versione disponibile! +sps.version.notes=Note +sps.version.notes.message=Visualizza le note. +sps.version.old_vers= La tua versione +sps.version.please_update=Aggiornati alla versione più recente. \ No newline at end of file diff --git a/lang/lang_ja_JP.properties b/lang/lang_ja_JP.properties new file mode 100644 index 0000000..441012d --- /dev/null +++ b/lang/lang_ja_JP.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=スリープをキャンセルします。 日は変わりません。 +sps.command.spshelp=SinglePlayerSleepヘルプを表示します。 +sps.command.spsreload=設定ファイルをリロードします。 +sps.command.spsupdate=更新を確認します。 +sps.command.toggledebug=一時的にデバッグに切り替えます。 +sps.message.bloodmoon=bloodmoonの間は眠れません。 +sps.message.boolean.true=TRUE +sps.message.boolean.false=FALSE +sps.message.cancel=キャンセル +sps.message.canceledsleep= が寝るのをキャンセルしました。 +sps.message.cancelunrestricted=キャンセルは無効になっています。 +sps.message.clickcancel=クリックしてスリープをキャンセル +sps.message.dayskipblackbed=DaySkipperを使用するには、ベッドを黒にする必要があります。 +sps.message.dayskipcancel=キャンセル +sps.message.dayskipcanceled= が日をスキップするのをキャンセルしました。 +sps.message.dayskipclickcancel=日をスキップするのをキャンセルするにはクリックしてください +sps.message.dayskipmsg= wants to sleep the day away... +sps.message.dayskipmsgcommand= は一日寝たい... +sps.message.dayskipsettime=夜に時間を設定します。 +sps.message.debugtrue=デバッグはブール値に設定されています。 +sps.message.issleep= が寝ています...zzz +sps.message.mustbeday=使用する日でなければなりません。 +sps.message.mustbenight=使用するのは夜でなければなりません。 +sps.message.nightorstorm=寝れるのは夜か嵐です。 +sps.message.nocancel=このスリープをキャンセルできないか、キャンセルするものがありません。 +sps.message.noperm=使用する権限がありません +sps.message.notop=OPではないか、config.ymlでauto-update-checkがfalseに設定されています +sps.message.reloaded=SinglePlayerSleepがリロードされました。 +sps.message.respawnpointmsg=リスポーンの場所を設定しました。 +sps.message.setdownfall=落ち込みを解消する +sps.message.setthunder=雷雨をクリアする +sps.message.settime=毎日の時間を設定する +sps.message.sleepcommand= が寝ています。 +sps.message.sleephelp=サーバー管理者の承認が必要です +sps.message.sleeplimit=あなたはそれを 秒行うことができません。 +sps.message.touse=使用するためにベッドで寝る。 +sps.message.update.current=auto-update-checkが に設定されています +sps.message.update.will=アップデートをチェックします! +sps.message.update.wont=アップデートをチェックしません! +sps.variable.boolean=引数はブールでなければなりません。 使用法 +sps.version.curvers=バージョンが最新です! +sps.version.donate=寄付する +sps.version.donate.message=プラグインメーカーに寄付する。 +sps.version.download=ダウンロード +sps.version.update.error=更新チェックを処理できませんでした。 +sps.version.message= の新しいバージョンがあります! +sps.version.new_vers=最新バージョン +sps.version.new_version=新しいバージョンがあります! +sps.version.notes=注釈 +sps.version.notes.message=ノートを表示する。 +sps.version.old_vers= 現在のバージョン +sps.version.please_update=最新バージョンに更新してください。 \ No newline at end of file diff --git a/lang/lang_key.properties b/lang/lang_key.properties new file mode 100644 index 0000000..cb2d115 --- /dev/null +++ b/lang/lang_key.properties @@ -0,0 +1,50 @@ +keyPathTranslations["langversion"] := "" +keyPathTranslations["bloodmoon"] := "sps.message.bloodmoon" +keyPathTranslations["boolean"] := "sps.variable.boolean" +keyPathTranslations["cancel"] := "sps.message.cancel" +keyPathTranslations["canceledsleep"] := "sps.message.canceledsleep" +keyPathTranslations["cancelhelp"] := "sps.command.cancelhelp" +keyPathTranslations["cancelunrestricted"] := "sps.message.cancelunrestricted" +keyPathTranslations["checkset"] := "sps.message.update.current" +keyPathTranslations["clickcancel"] := "sps.message.clickcancel" +keyPathTranslations["curvers"] := "sps.version.curvers" +keyPathTranslations["dayskipblackbed"] := "sps.message.dayskipblackbed" +keyPathTranslations["dayskipcancel"] := "sps.message.dayskipcancel" +keyPathTranslations["dayskipcanceled"] := "sps.message.dayskipcanceled" +keyPathTranslations["dayskipclickcancel"] := "sps.message.dayskipclickcancel" +keyPathTranslations["dayskipmsg"] := "sps.message.dayskipmsg" +keyPathTranslations["dayskipmsgcommand"] := "sps.message.dayskipmsgcommand" +keyPathTranslations["dayskipsettime"] := "sps.message.dayskipsettime" +keyPathTranslations["debugtrue"] := "sps.message.debugtrue" +keyPathTranslations["issleep"] := "sps.message.issleep" +keyPathTranslations["mustbeday"] := "sps.message.mustbeday" +keyPathTranslations["mustbenight"] := "sps.message.mustbenight" +keyPathTranslations["newvers.message"] := "sps.version.message" +keyPathTranslations["newvers.old_vers"] := "sps.version.old_vers" +keyPathTranslations["newvers.new_vers"] := "sps.version.new_vers" +keyPathTranslations["newvers.please_update"] := "sps.version.please_update" +keyPathTranslations["newvers.download"] := "sps.version.download" +keyPathTranslations["newvers.donate"] := "sps.version.donate" +keyPathTranslations["nightorstorm"] := "sps.message.nightorstorm" +keyPathTranslations["nocancel"] := "sps.message.nocancel" +keyPathTranslations["nocheck"] := "sps.message.update.wont" +keyPathTranslations["noperm"] := "sps.message.noperm" +keyPathTranslations["notop"] := "sps.message.notop" +keyPathTranslations["reloaded"] := "sps.message.reloaded" +keyPathTranslations["respawnpointmsg"] := "sps.message.respawnpointmsg" +keyPathTranslations["setdownfall"] := "sps.message.setdownfall" +keyPathTranslations["setthunder"] := "sps.message.setthunder" +keyPathTranslations["settime"] := "sps.message.settime" +keyPathTranslations["sleepcommand"] := "sps.message.sleepcommand" +keyPathTranslations["sleephelp"] := "sps.message.sleephelp" +keyPathTranslations["sleeplimit"] := "sps.message.sleeplimit" +keyPathTranslations["spscheck"] := "" +keyPathTranslations["spshelp"] := "sps.command.spshelp" +keyPathTranslations["spsreload"] := "sps.command.spsreload" +keyPathTranslations["spsupdate"] := "sps.command.spsupdate" +keyPathTranslations["toggledebug"] := "sps.command.toggledebug" +keyPathTranslations["touse"] := "sps.message.touse" +keyPathTranslations["yescheck"] := "sps.message.update.will" +keyPathTranslations["newvers2.notes"] := "sps.version.notes" +keyPathTranslations["boolean.true"] := "sps.message.boolean.true" +keyPathTranslations["boolean.false"] := "sps.message.boolean.false" \ No newline at end of file diff --git a/lang/lang_ko_KR.properties b/lang/lang_ko_KR.properties new file mode 100644 index 0000000..a607e04 --- /dev/null +++ b/lang/lang_ko_KR.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=싱글 플레이어 잠자기를 취소합니다. 낮으로 변경하지 않습니다. +sps.command.spshelp=SinglePlayerSleep 도움말을 표시합니다. +sps.command.spsreload=구성 파일을 다시로드합니다. +sps.command.spsupdate=업데이트 확인. +sps.command.toggledebug=임시로 디버그를 토글합니다. +sps.message.bloodmoon=혈달에는 잠을 잘 수 없습니다. +sps.message.boolean.true=참 +sps.message.boolean.false=거짓 +sps.message.cancel=취소 +sps.message.canceledsleep=님이 잠자기를 취소했습니다. +sps.message.cancelunrestricted=취소가 비제한적으로 설정되어 있습니다. +sps.message.clickcancel=클릭하여 잠자기를 취소합니다. +sps.message.dayskipblackbed=DaySkipper를 사용하려면 침대가 검은색이어야 합니다. +sps.message.dayskipcancel=취소 +sps.message.dayskipcanceled=님이 DaySkip을 취소했습니다. +sps.message.dayskipclickcancel=클릭하여 DaySkip을 취소합니다. +sps.message.dayskipmsg=님이 낮을 잠자리로 가고자 합니다... +sps.message.dayskipmsgcommand=님이 낮을 잠자리로 가고자 합니다... +sps.message.dayskipsettime=시간이 밤으로 설정되었습니다. +sps.message.debugtrue=디버그가 으로 설정되었습니다. +sps.message.issleep=님이 잠을 자고 있습니다. +sps.message.mustbeday=이 기능을 사용하려면 낮이어야 합니다. +sps.message.mustbenight=이 기능을 사용하려면 밤이어야 합니다. +sps.message.nightorstorm=밤이거나 폭풍우가 일어나야 잠을 잘 수 있습니다. +sps.message.nocancel=잠을 깰 수 없거나 취소할 게 없습니다. +sps.message.noperm=이 명령어를 사용할 권한이 없습니다. +sps.message.notop=OP 권한이 없거나 config.yml 파일의 auto-update-check 항목이 false로 설정되어 있습니다. +sps.message.reloaded=SinglePlayerSleep가 다시 로드되었습니다. +sps.message.respawnpointmsg=리스폰 위치가 설정되었습니다. +sps.message.setdownfall=강수량을 초기화합니다. +sps.message.setthunder=번개를 초기화합니다. +sps.message.settime=시간을 낮으로 설정합니다. +sps.message.sleepcommand=이(가) 잠자는 중입니다. +sps.message.sleephelp=서버 관리자의 승인이 필요합니다. +sps.message.sleeplimit=초 동안 그것을 할 수 없습니다. +sps.message.touse=사용하려면 침대에서 잠자십니다. +sps.message.update.current=auto-update-check가 설정되었습니다. +sps.message.update.will=업데이트를 확인합니다! +sps.message.update.wont=업데이트를 확인하지 않습니다! +sps.variable.boolean=인수는 boolean이어야 합니다. 사용법 +sps.version.curvers=버전이 최신입니다! +sps.version.donate=기부하기 +sps.version.donate.message=플러그인 제작자에게 기부하세요. +sps.version.download=다운로드 +sps.version.update.error=업데이트 확인을 처리할 수 없습니다. +sps.version.message=에 새 버전이 있습니다! +sps.version.new_vers=최신 버전 +sps.version.new_version=새 버전을 사용할 수 있습니다! +sps.version.notes=노트(Note) +sps.version.notes.message=노트 보기. +sps.version.old_vers= 현재 버전 +sps.version.please_update=최신 버전으로 업데이트해주세요. \ No newline at end of file diff --git a/lang/lang_lol_US.properties b/lang/lang_lol_US.properties new file mode 100644 index 0000000..30bd3ae --- /dev/null +++ b/lang/lang_lol_US.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Cancels Single Player Sleep. Doez not change 2 dai. +sps.command.spshelp=Shows SinglePlayerSleep halp. +sps.command.spsreload=Reload config file. +sps.command.spsupdate=Check 4 updatez. +sps.command.toggledebug=Tmpor harily toggles dbug. +sps.message.bloodmoon=U kant nap durin a blodmun. +sps.message.boolean.true=TRU +sps.message.boolean.false=FOLS +sps.message.cancel=CANCEL +sps.message.canceledsleep= no cat nap. +sps.message.cancelunrestricted=Cancelin iz disabled. +sps.message.clickcancel=Klik 2 stop nap +sps.message.dayskipblackbed=Bed must b black 2 uz daiskip. +sps.message.dayskipcancel=CANCEL +sps.message.dayskipcanceled= stopd daiskip. +sps.message.dayskipclickcancel=Klik 2 cancl daiskip +sps.message.dayskipmsg= wantz 2 nap all day... +sps.message.dayskipmsgcommand= wantz 2 nap all day... +sps.message.dayskipsettime=Sit tyme 2 naptime. +sps.message.debugtrue=Dbug sit 2 boolean. +sps.message.issleep= iz nappin +sps.message.mustbeday=It must b dai 2 uz. +sps.message.mustbenight=It must be nite 2 uz. +sps.message.nightorstorm=It must b nite or stormin 2 nap. +sps.message.nocancel=U cant cancel dis nap OR thar iz nothin 2 cancel. +sps.message.noperm=U do not has permishun to uz +sps.message.notop=U R not OP, or auto-update-check iz set 2 false in config.yml +sps.message.reloaded=SinglePlayerSleep haz ben awoken. +sps.message.respawnpointmsg=hear is new kat home!! +sps.message.setdownfall=Clearin downfall +sps.message.setthunder=Clearin thunderstorm +sps.message.settime=Settin tiem 2 dai +sps.message.sleepcommand= iz nappin +sps.message.sleephelp=subject 2 server admin approval +sps.message.sleeplimit=U cant do dat agin so soon. +sps.message.touse=Sleep in bed 2 use. +sps.message.update.current=auto-update-check has been set 2 +sps.message.update.will=will check 4 updatez! +sps.message.update.wont=will not check 4 updatez! +sps.variable.boolean=Argument must be boolean. Usage +sps.version.curvers=Vershun iz up 2 date! +sps.version.donate=Give treats? +sps.version.donate.message=Donatez to teh plugin makerz. +sps.version.download=Dwnlode +sps.version.update.error=Cud not process updatez check. +sps.version.message=Thar iz nu vershun 4 available! +sps.version.new_vers=Newr vershun +sps.version.new_version=Nu vershun available! +sps.version.notes=Noatz +sps.version.notes.message=Vew teh Notez. +sps.version.old_vers= Ur vershun +sps.version.please_update=pleez updat 2 teh nEwEsT vershun. \ No newline at end of file diff --git a/lang/lang_my_MY.properties b/lang/lang_my_MY.properties new file mode 100644 index 0000000..bac25cb --- /dev/null +++ b/lang/lang_my_MY.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Membatalkan Tidur Pemain Tunggal. Tidak menukar ke siang. +sps.command.spshelp=Menunjukkan bantuan SinglePlayerSleep. +sps.command.spsreload=Memuat semula fail tetapan. +sps.command.spsupdate=Periksa kemas kini. +sps.command.toggledebug=Toggle debug sementara. +sps.message.bloodmoon=Anda tidak boleh tidur semasa bulan darah. +sps.message.boolean.true=BENAR +sps.message.boolean.false=SALAH +sps.message.cancel=BATAL +sps.message.canceledsleep= membatalkan tidurnya. +sps.message.cancelunrestricted=Pembatalan dinonaktifkan. +sps.message.clickcancel=Klik untuk membatalkan tidur +sps.message.dayskipblackbed=Katil harus hitam untuk menggunakan DaySkipper. +sps.message.dayskipcancel=BATAL +sps.message.dayskipcanceled= membatalkan DaySkip. +sps.message.dayskipclickcancel=Klik untuk membatalkan DaySkip +sps.message.dayskipmsg= mahu tidur selama hari ... +sps.message.dayskipmsgcommand= mahu tidur sepanjang hari... +sps.message.dayskipsettime=Mentakrifkan masa untuk malam. +sps.message.debugtrue=Debug ditetapkan ke . +sps.message.issleep= sedang tidur. +sps.message.mustbeday=Mesti siang untuk digunakan. +sps.message.mustbenight=Mesti malam untuk digunakan. +sps.message.nightorstorm=Mesti malam atau ribut untuk tidur. +sps.message.nocancel=Anda tidak boleh membatalkan tidur ini atau tidak ada apa-apa yang perlu dibatalkan. +sps.message.noperm=Anda tidak mempunyai kebenaran untuk menggunakan +sps.message.notop=Anda bukan OP, atau semakan kemas kini automatik ditetapkan kepada palsu dalam config.yml +sps.message.reloaded=SinglePlayerSleep telah dimuat semula. +sps.message.respawnpointmsg=Titik respawn ditetapkan. +sps.message.setdownfall=Membersihkan hujan +sps.message.setthunder=Membersihkan ribut petir +sps.message.settime=Menetapkan waktu ke siang +sps.message.sleepcommand= sedang tidur +sps.message.sleephelp=subjek kepada kelulusan admin server +sps.message.sleeplimit=Anda tidak boleh melakukan itu selama saat +sps.message.touse=Tidur di katil untuk menggunakan. +sps.message.update.current=semakan kemas kini automatik telah ditetapkan kepada +sps.message.update.will=akan memeriksa kemas kini! +sps.message.update.wont=tidak akan memeriksa kemas kini! +sps.variable.boolean=Argumen mestilah boolean. Penggunaan +sps.version.curvers=Versi adalah terkini! +sps.version.donate=Sumbang +sps.version.donate.message=Sumbang kepada pembuat plugin. +sps.version.download=Muat turun +sps.version.update.error=Tidak dapat memproses semakan kemas kini +sps.version.message=Terdapat versi baru untuk ! +sps.version.new_vers=Versi terbaru +sps.version.new_version=Versi baru tersedia! +sps.version.notes=Catatan +sps.version.notes.message=Lihat catatan. +sps.version.old_vers= Versi anda +sps.version.please_update=Sila kemaskini ke versi terbaru. \ No newline at end of file diff --git a/lang/lang_nl_NL.properties b/lang/lang_nl_NL.properties new file mode 100644 index 0000000..4f87da7 --- /dev/null +++ b/lang/lang_nl_NL.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Annuleert Single Player Sleep. Veranderd het niet naar dag. +sps.command.spshelp=Toont SinglePlayerSleep hulp. +sps.command.spsreload=Herladen configuratie bestand. +sps.command.spsupdate=Controleer op updates. +sps.command.toggledebug=Schakelt tijdelijk debug in. +sps.message.bloodmoon=Je kunt niet slapen tijdens een bloedmaan. +sps.message.boolean.true=WAAR +sps.message.boolean.false=ONWAAR +sps.message.cancel=ANNULEREN +sps.message.canceledsleep= heeft slapen geannuleerd. +sps.message.cancelunrestricted=annuleren is uitgeschakeld. +sps.message.clickcancel=Klik hier om het slapen te annuleren +sps.message.dayskipblackbed=Bed moet zwart zijn om DaySkipper te gebruiken. +sps.message.dayskipcancel=ANNULEREN +sps.message.dayskipcanceled= geannuleerd DaySkip. +sps.message.dayskipclickcancel=Klik om Dag overslaan te annuleren +sps.message.dayskipmsg= wil de hele dag slapen... +sps.message.dayskipmsgcommand= wil de hele dag slapen... +sps.message.dayskipsettime=Tijd tot nacht instellen. +sps.message.debugtrue=Foutopsporing ingesteld op boolean. +sps.message.issleep= is gaan slapen. +sps.message.mustbeday=Het moet een dag zijn om te gebruiken. +sps.message.mustbenight=Het moet nacht zijn om te gebruik. +sps.message.nightorstorm=Het moet nacht zijn of in slaap vallen. +sps.message.nocancel=U kunt deze slaap niet annuleren of er is niets aan Cancel. +sps.message.noperm=Je hebt geen toestemming om te gebruiken +sps.message.notop=U bent niet Operator of auto-update-check is ingesteld op false in config.yml +sps.message.reloaded=SinglePlayerSleep is opnieuw geladen. +sps.message.respawnpointmsg=Respawnpunt ingesteld +sps.message.setdownfall=Regenbui opklaren +sps.message.setthunder=Onweersbui opklaren +sps.message.settime=Tijd instellen tot dag +sps.message.sleepcommand= is gaan slapen +sps.message.sleephelp=onder voorbehoud van goedkeuring server admin +sps.message.sleeplimit=Dat kun je niet zo snel meer doen. +sps.message.touse=Slaap in een bed om te gebruiken. +sps.message.update.current=auto-update-check is ingesteld op +sps.message.update.will=zal controleren op updates! +sps.message.update.wont=zal niet controleren voor updates! +sps.variable.boolean=Argument moet boolean zijn. Gebruik +sps.version.curvers=Versie is up-to-date! +sps.version.donate=Doneren +sps.version.donate.message=Doneer aan de pluginmaker. +sps.version.download=Downloaden +sps.version.update.error=Kan updatecontrole niet verwerken. +sps.version.message=Er is een nieuwe versie van beschikbaar! +sps.version.new_vers=Nieuwste versie +sps.version.new_version=Nieuwe versie beschikbaar! +sps.version.notes=Notities +sps.version.notes.message=Bekijk de notities. +sps.version.old_vers= Jouw versie +sps.version.please_update=Gelieve te updaten naar de nieuwste versie. \ No newline at end of file diff --git a/lang/lang_pl_PL.properties b/lang/lang_pl_PL.properties new file mode 100644 index 0000000..30104c5 --- /dev/null +++ b/lang/lang_pl_PL.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Umożliwia anulowanie pominięcia nocy. +sps.command.spshelp=Shows SinglePlayerSleep help. +sps.command.spsreload=Przeładowuje konfiguracje pluginu. +sps.command.spsupdate=Sprawdza dostępne aktualizacje pluginu. +sps.command.toggledebug=Tymczasowo włącza opcje debug. +sps.message.bloodmoon=Nie możesz pójść spać podczas krwawego księżyca. +sps.message.boolean.true=PRAWDA +sps.message.boolean.false=FAŁSZ +sps.message.cancel=ANULUJ +sps.message.canceledsleep= nie jest śpiący/a +sps.message.cancelunrestricted=Anulowanie pominięcia nocy jest wyłączone. +sps.message.clickcancel=Kliknij aby anulować +sps.message.dayskipblackbed=Łóżko musi być czarne aby użyć „dayskipper” +sps.message.dayskipcancel=ANULUJ +sps.message.dayskipcanceled= nie jest śpiący/a +sps.message.dayskipclickcancel=Kliknij aby anulować +sps.message.dayskipmsg= wants to sleep the day away... +sps.message.dayskipmsgcommand= wants to sleep the day away... +sps.message.dayskipsettime=Ustawianie czasu na noc +sps.message.debugtrue=Debugowanie ustawione na wartość logiczną. +sps.message.issleep= śpi. +sps.message.mustbeday=Aby tego użyć, musi być dzień. +sps.message.mustbenight=Aby tego użyć, musi być noc. +sps.message.nightorstorm=Musi być noc lub burza, by pominąć noc. +sps.message.nocancel=Niestety nie możesz anulować pominięcia nocy. +sps.message.noperm=Nie masz wystarczających permisji. +sps.message.notop=Nie jesteś operatorem lub auto-update-check jest wyłączony w config.yml +sps.message.reloaded=został przeładowany. +sps.message.respawnpointmsg=Ustawiono punkt odradzania. +sps.message.setdownfall=Złagodzenie upadku +sps.message.setthunder=Usunięcie burzy +sps.message.settime=Ustawianie czasu na dzień +sps.message.sleepcommand= śpi +sps.message.sleephelp=podlega zatwierdzeniu przez administratora serwera. +sps.message.sleeplimit=Nie możesz tego zrobić przez sekund. +sps.message.touse=Aby pominąć noc połóż się w łóżku, poczekaj chwilkę i gotowe! +sps.message.update.current=auto-update-check zostało ustawione na +sps.message.update.will=będzie sprawdzać dostępne aktualizacje. +sps.message.update.wont=nie będzie sprawdzać aktualizacji. +sps.variable.boolean=Zła komenda, poprawne użycie +sps.version.curvers=Wersja jest aktualna! +sps.version.donate=Wesprzyj +sps.version.donate.message=Wesprzyj twórcę wtyczki. +sps.version.download=Pobierz +sps.version.update.error=Nie można przetworzyć sprawdzenia aktualizacji. +sps.version.message=Jest dostępna nowa wersja pluginu ! +sps.version.new_vers=Najnowsza wersja +sps.version.new_version=Nowa wersja jest dostępna! +sps.version.notes=Notatki +sps.version.notes.message=Wyświetl notatki. +sps.version.old_vers= Twoja wersja +sps.version.please_update=Prosimy zaktualizuj do najnowszej wersji. \ No newline at end of file diff --git a/lang/lang_pt_BR.properties b/lang/lang_pt_BR.properties new file mode 100644 index 0000000..903be3c --- /dev/null +++ b/lang/lang_pt_BR.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Cancela Single Player Sleep. Nao muda para dia. +sps.command.spshelp=Mostra ajuda do SinglePlayerSleep. +sps.command.spsreload=Recarregar aquivo de config. +sps.command.spsupdate=Checar por atualizacoes. +sps.command.toggledebug=Alterna temporariamente a depuração. +sps.message.bloodmoon=Você não pode dormir durante uma lua de sangue. +sps.message.boolean.true=VERDADEIRO +sps.message.boolean.false=FALSO +sps.message.cancel=CANCELAR +sps.message.canceledsleep= cancelou dormir. +sps.message.cancelunrestricted=Cancelar esta desabilitado. +sps.message.clickcancel=Clique para cancelar dormir +sps.message.dayskipblackbed=A cama deve ser preta para usar o DaySkipper. +sps.message.dayskipcancel=CANCELAR +sps.message.dayskipcanceled= cancelou o DaySkip. +sps.message.dayskipclickcancel=Clique para cancelar o DaySkip +sps.message.dayskipmsg= quer dormir o dia inteiro ... +sps.message.dayskipmsgcommand= quer dormir o dia inteiro... +sps.message.dayskipsettime=Ajustando a hora para a noite. +sps.message.debugtrue=Depuração definida como boolean. +sps.message.issleep= esta dormindo. +sps.message.mustbeday=Deve ser dia para usar isso +sps.message.mustbenight=Deve estar de noite para usar. +sps.message.nightorstorm=Deve estar de noite ou tempestade para dormir. +sps.message.nocancel=Voce nao pode cancelar ou nao ha nada para cancelar. +sps.message.noperm=Voce nao tem permissao para usar +sps.message.notop=Voce nao e OP, ou check de update automatico esta definido para false na config.yml +sps.message.reloaded=SinglePlayerSleep foi recarregado. +sps.message.respawnpointmsg=O local de renascimento foi definido +sps.message.setdownfall=Encerrando tempestade +sps.message.setthunder=Encerrando tempestade +sps.message.settime=Setando hora para dia +sps.message.sleepcommand= esta dormindo +sps.message.sleephelp=sujeito a aprovacao do admin +sps.message.sleeplimit=Voce nao pode fazer isso de novo tao cedo. +sps.message.touse=Durma na cama para usar. +sps.message.update.current=checagem de update automatico foi alterado para +sps.message.update.will=irei checar por updates! +sps.message.update.wont=nao irei checar por updates! +sps.variable.boolean=Argumento deve ser booleano. Uso +sps.version.curvers=Versao esta atualizada! +sps.version.donate=Doar +sps.version.donate.message=Faça uma doação ao criador do plugin. +sps.version.download=Download +sps.version.update.error=Não foi possível processar a verificação de atualização. +sps.version.message=Há uma nova versão do disponível! +sps.version.new_vers=Versão mais recente +sps.version.new_version=Nova versao disponivel! +sps.version.notes=Notas +sps.version.notes.message=Ver as notas. +sps.version.old_vers= Sua versão +sps.version.please_update=Por favor, atualize para a versão mais recente. \ No newline at end of file diff --git a/lang/lang_ru_RU.properties b/lang/lang_ru_RU.properties new file mode 100644 index 0000000..1455ad1 --- /dev/null +++ b/lang/lang_ru_RU.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Отменяет Сон Одиночного Игрока. Не переводит время на день. +sps.command.spshelp=Показывает помощь по SinglePlayerSleep. +sps.command.spsreload=Перезагрузка файла конфигурации. +sps.command.spsupdate=Проверить наличие обновления. +sps.command.toggledebug=Временно переключает режим отладки. +sps.message.bloodmoon=Вы не можете спать во время Кровавой Луны. +sps.message.boolean.true=TRUE +sps.message.boolean.false=FALSE +sps.message.cancel=ОТМЕНА +sps.message.canceledsleep= отменил сон. +sps.message.cancelunrestricted=Отмена отключена. +sps.message.clickcancel=Нажмите, чтобы отменить сон +sps.message.dayskipblackbed=Кровать должна быть черной, чтобы использовать DaySkipper. +sps.message.dayskipcancel=ОТМЕНА +sps.message.dayskipcanceled= отменил DaySkip. +sps.message.dayskipclickcancel=Нажмите, чтобы отменить DaySkip +sps.message.dayskipmsg= хочет спать весь день ... +sps.message.dayskipmsgcommand= хочет спать весь день... +sps.message.dayskipsettime=Устанавливается время ночи. +sps.message.debugtrue=Режим отладки установлен на . +sps.message.issleep= спит. +sps.message.mustbeday=Должен быть день, чтобы использовать. +sps.message.mustbenight=Должна быть ночь, чтобы использовать. +sps.message.nightorstorm=Должна быть ночь или буря, чтобы спать. +sps.message.nocancel=Вы не можете отменить этот сон или нет ничего, чтобы отменить. +sps.message.noperm=У вас нет разрешения на использование +sps.message.notop=Вы не являетесь OP или автоматическая проверка обновлений в config.yml отключена +sps.message.reloaded=SinglePlayerSleep был перезагружен. +sps.message.respawnpointmsg=Точка возрождения установлена. +sps.message.setdownfall=Остановка дождя +sps.message.setthunder=Остановка грозы +sps.message.settime=Установка времени на день +sps.message.sleepcommand= спит. +sps.message.sleephelp=требуется одобрение администратора сервера +sps.message.sleeplimit=Вы не можете сделать это в течение секунд. +sps.message.touse=Спать в кровати, чтобы использовать. +sps.message.update.current=Автоматическая проверка обновлений включена +sps.message.update.will=будет проверять обновления! +sps.message.update.wont=не будет проверять обновления! +sps.variable.boolean=Аргумент должен быть булевым. Использование +sps.version.curvers=Версия программы обновлена! +sps.version.donate=Пожертвовать +sps.version.donate.message=Пожертвовать автору плагина. +sps.version.download=Скачать +sps.version.update.error=Не удалось проверить наличие обновления. +sps.version.message=Доступна новая версия ! +sps.version.new_vers=Последняя версия +sps.version.new_version=Доступна новая версия! +sps.version.notes=Заметки +sps.version.notes.message=Просмотреть заметки. +sps.version.old_vers= Ваша версия +sps.version.please_update=Обновитесь до новой версии. \ No newline at end of file diff --git a/lang/lang_sv_SV.properties b/lang/lang_sv_SV.properties new file mode 100644 index 0000000..63d8b9a --- /dev/null +++ b/lang/lang_sv_SV.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Avbryt personens sömn. Det kommer inte bli dag. +sps.command.spshelp=visar SinglePlayerSleep hjälp. +sps.command.spsreload=Laddar om config filen. +sps.command.spsupdate=Letar efter uppdateringar. +sps.command.toggledebug=Växlar tillfälligt felsökning. +sps.message.bloodmoon=Du Kan inte sova under Bloodmånen. +sps.message.boolean.true=SANT +sps.message.boolean.false=FALSKT +sps.message.cancel=Avbryt! +sps.message.canceledsleep= Avbröt sovandet. +sps.message.cancelunrestricted=Det går inte att stoppa!. +sps.message.clickcancel=Klicka för att avbryta +sps.message.dayskipblackbed=Sängen måste vara svart för att använda day skipper +sps.message.dayskipcancel=AVBRYT +sps.message.dayskipcanceled= AVBRÖT DaySkip. +sps.message.dayskipclickcancel=klicka för att avbryta DaySkip +sps.message.dayskipmsg= vill sova hela dagen lång... +sps.message.dayskipmsgcommand= Vill sova bort hela dagen... +sps.message.dayskipsettime=Inställning för dag/natt. +sps.message.debugtrue=Debug set to boolean. +sps.message.issleep= Sooover ZZZzzz. +sps.message.mustbeday=Det måste vara dag för att använda. +sps.message.mustbenight=Det måste vara natt för att använda. +sps.message.nightorstorm=Det måste vara natt eller vara en storm för att sova! +sps.message.nocancel=Du kan itne avbryta denna för det finns inget att avbryta!. +sps.message.noperm=Du har inte rättigheterna att andvända +sps.message.notop=Du är inte OP, eller så är auto-update-chek avstängt i config.yml +sps.message.reloaded=SinglePlayerSleep Har laddats om. +sps.message.respawnpointmsg=Återskapelseplats skapad!. +sps.message.setdownfall=Tar bort regnet +sps.message.setthunder=Tar bort stormen +sps.message.settime=Sätter tiden till dag +sps.message.sleepcommand= Sooover ZZZzzz +sps.message.sleephelp=måste godkännas av serveradministratören +sps.message.sleeplimit=Du kan inte göra det på sekunder +sps.message.touse=Sov i sängen för att använda. +sps.message.update.current=auto-update-check Har blivigt satt till +sps.message.update.will=kommer att söka efter uppdateringar! +sps.message.update.wont=Kommer inte leta efter uppdateringar! +sps.variable.boolean=Argumentet måste vara booleskt. Användande +sps.version.curvers=Versionen är uppdaterad! +sps.version.donate=Donera +sps.version.donate.message=Donera till plugin-skaparen. +sps.version.download=Nedladdning +sps.version.update.error=Kunde inte genomföra uppdateringskontroll. +sps.version.message=Det finns en ny version av tillgänglig! +sps.version.new_vers=Senaste versionen +sps.version.new_version=Ny version tillgänglig! +sps.version.notes=Noteringar +sps.version.notes.message=Visa noteringarna. +sps.version.old_vers=Din version +sps.version.please_update=Uppdatera till den senaste versionen. \ No newline at end of file diff --git a/lang/lang_tr_TR.properties b/lang/lang_tr_TR.properties new file mode 100644 index 0000000..9f442fc --- /dev/null +++ b/lang/lang_tr_TR.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=Uyuyanı uyandırır, günü değiştirmez. +sps.command.spshelp=SinglePlayerSleep yardım sayfasını gösterir. +sps.command.spsreload=Plugini yeniden yükler. +sps.command.spsupdate=Güncellemeleri kontrol eder. +sps.command.toggledebug=Hata ayıklamayı geçici olarak değiştirir. +sps.message.bloodmoon=Kanlı Ay varken uyuyamazsın. +sps.message.boolean.true=DOĞRU +sps.message.boolean.false=YANLIŞ +sps.message.cancel=Uyandır +sps.message.canceledsleep= uyuyanı uyandırdı. +sps.message.cancelunrestricted=Uyandırma devredışı. +sps.message.clickcancel=Uyandırmak için tıkla! +sps.message.dayskipblackbed=Gün boyu uyumak için yatağın siyah olması gerek. +sps.message.dayskipcancel=Uyandır +sps.message.dayskipcanceled=, gün boyu uyumayı iptal etti. +sps.message.dayskipclickcancel=Gün boyu uyumayı iptal etmek için tıkla! +sps.message.dayskipmsg= gün boyu uyumak istiyor... +sps.message.dayskipmsgcommand= gün boyu uyumak istiyor... +sps.message.dayskipsettime=Zaman gece olarak ayarlandı. +sps.message.debugtrue=Hata ayıklama boolean olarak ayarlandı. +sps.message.issleep= uyuyor! +sps.message.mustbeday=Kullanmak için gündüz olmalı. +sps.message.mustbenight=Kullanmak için gece olmalı. +sps.message.nightorstorm=Uyumak için fırtına yada gece olmalı. +sps.message.nocancel=Uyuyanı uyandıramazsın yada uyandırılacak kimse yok. +sps.message.noperm=Bunu kullanmak için yetkin yok. +sps.message.notop=Operatör değilsin, yada auto-update-check, config.yml içinde false olarak ayarlanmış. +sps.message.reloaded=Plugin yeniden yüklendi. +sps.message.respawnpointmsg=Yeniden doğma noktası ayarlandı. +sps.message.setdownfall=Yağmur dindiriliyor. +sps.message.setthunder=Fırtına dindiriliyor. +sps.message.settime=Zaman gündüz olarak ayarlandı. +sps.message.sleepcommand= uyuyor. +sps.message.sleephelp=Sunucu yöneticisinin onayına tabi. +sps.message.sleeplimit=Bunu saniye boyunca yapamazsın. +sps.message.touse=Kullanmak için yatakta uyuyun. +sps.message.update.current=Otomatik güncelleme kontrolü ayarlandı - +sps.message.update.will=Güncellemeler kontrol edilecek! +sps.message.update.wont=Güncellemeler kontrol edilmeyecek! +sps.variable.boolean=Argüman boolean tipinde olmalı. +sps.version.curvers=Sürüm güncel! +sps.version.donate=Bağış Yap +sps.version.donate.message=Yapımcıya bağış yapın. +sps.version.download=İndir +sps.version.update.error=Güncelleme kontrolü işlenemedi. +sps.version.message= için yeni bir sürüm mevcut! +sps.version.new_vers=En son sürüm +sps.version.new_version=Yeni sürüm mevcut! +sps.version.notes=Notlar +sps.version.notes.message=Notları görüntüle. +sps.version.old_vers= Sizin sürümünüz +sps.version.please_update=Lütfen en son sürüme güncelleyin. \ No newline at end of file diff --git a/lang/lang_zh_CN.properties b/lang/lang_zh_CN.properties new file mode 100644 index 0000000..45dec57 --- /dev/null +++ b/lang/lang_zh_CN.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=拒绝睡觉跳过晚上 +sps.command.spshelp=显示SinglePlayerSleep的帮助信息 +sps.command.spsreload=重新加载配置文件 +sps.command.spsupdate=检查更新 +sps.command.toggledebug=临时切换调试模式 +sps.message.bloodmoon=你无法在血月之夜睡觉 +sps.message.boolean.true=真 +sps.message.boolean.false=假 +sps.message.cancel=点击此处取消 +sps.message.canceledsleep=取消了睡觉 +sps.message.cancelunrestricted=取消被禁用 +sps.message.clickcancel=点击取消睡眠 +sps.message.dayskipblackbed=必须使用黑色的床才能跳过白天 +sps.message.dayskipcancel=点击此处取消 +sps.message.dayskipcanceled=取消了跳过白天 +sps.message.dayskipclickcancel=强制取消 DaySkip. +sps.message.dayskipmsg= 希望跳过这一天... +sps.message.dayskipmsgcommand= 希望跳过这一天... +sps.message.dayskipsettime=将时间设定为晚上. +sps.message.debugtrue=调试模式设置为boolean +sps.message.issleep=正在睡觉 +sps.message.mustbeday=必须是白天才能使用 +sps.message.mustbenight=必须是晚上才能使用 +sps.message.nightorstorm=必须是晚上或者雷暴才能使用 +sps.message.nocancel=您无法取消此睡眠或者没有要取消的睡眠 +sps.message.noperm=你没有权限使用 +sps.message.notop=你不是OP,或 config.Yml 中的 auto-update-check 设置为 false +sps.message.reloaded=已重新加载 +sps.message.respawnpointmsg=已设置重生点 +sps.message.setdownfall=停止下雨 +sps.message.setthunder=停止雷暴 +sps.message.settime=设置为早上 +sps.message.sleepcommand=正在睡觉 +sps.message.sleephelp=需要服务器管理员许可 +sps.message.sleeplimit=还在冷却中,请等待秒 +sps.message.touse=睡在床上使用 +sps.message.update.current=自动更新被设置为 +sps.message.update.will=将会检查更新! +sps.message.update.wont=不会检查更新! +sps.variable.boolean=参数必须为true或者false。例如 +sps.version.curvers=版本已经是最新的! +sps.version.donate=捐赠 +sps.version.donate.message=向插件制作者捐赠。 +sps.version.download=下载 +sps.version.update.error=无法处理更新检查。 +sps.version.message= 有新版本发布! +sps.version.new_vers=最新版本 +sps.version.new_version=有新版本! +sps.version.notes=更新说明 +sps.version.notes.message=查看注释。 +sps.version.old_vers= 当前版本 +sps.version.please_update=请更新到最新版本。 \ No newline at end of file diff --git a/lang/lang_zh_TW.properties b/lang/lang_zh_TW.properties new file mode 100644 index 0000000..7b6bcc9 --- /dev/null +++ b/lang/lang_zh_TW.properties @@ -0,0 +1,52 @@ +sps.command.cancelhelp=取消單人睡眠不會更改為早上 +sps.command.spshelp=顯示 SinglePlayerSleep 幫助. +sps.command.spsreload=重新加載設定文件. +sps.command.spsupdate=檢查更新. +sps.command.toggledebug=臨時切換調試。 +sps.message.bloodmoon=血月期間您無法入睡。 +sps.message.boolean.true=真 +sps.message.boolean.false=假 +sps.message.cancel=取消 +sps.message.canceledsleep= 取消了睡眠. +sps.message.cancelunrestricted=取消被禁用 +sps.message.clickcancel=點擊取消睡眠 +sps.message.dayskipblackbed=床必須為黑色才能使用 DaySkipper. +sps.message.dayskipcancel=取消 +sps.message.dayskipcanceled=取消了 DaySkip. +sps.message.dayskipclickcancel=強制取消 DaySkip. +sps.message.dayskipmsg= 希望跳過這一天... +sps.message.dayskipmsgcommand= 希望跳過這一天... +sps.message.dayskipsettime=將時間設定為晚上. +sps.message.debugtrue=調試設置為boolean。 +sps.message.issleep= 在睡覺. +sps.message.mustbeday=必須在白天才能使用 +sps.message.mustbenight=晚上才能使用. +sps.message.nightorstorm=一定要是晚上或雷暴才能睡覺 +sps.message.nocancel=您無法取消此睡眠或者沒有要取消的睡眠 +sps.message.noperm=你沒有權限使用 +sps.message.notop=你不是OP,或 config.Yml 中的 auto-update-check 設置為 false +sps.message.reloaded=SinglePlayerSleep已重新加載。 +sps.message.respawnpointmsg=已設置重生點 +sps.message.setdownfall=停止下雨 +sps.message.setthunder=停止雷暴 +sps.message.settime=設置為早上 +sps.message.sleepcommand= 在睡覺 +sps.message.sleephelp=需要伺服器管理員許可 +sps.message.sleeplimit=你不能夠這麼快就再次這樣做. +sps.message.touse=睡在床上使用. +sps.message.update.current=自動更新檢查已設置為 +sps.message.update.will=將會檢查更新! +sps.message.update.wont=不會檢查更新! +sps.variable.boolean=參數必須為布爾值。用法 +sps.version.curvers=版本已經是最新的! +sps.version.donate=捐贈 +sps.version.donate.message=捐款給插件作者。 +sps.version.download=下載 +sps.version.update.error=無法處理更新檢查。 +sps.version.message= 有新版本可用! +sps.version.new_vers=最新版本 +sps.version.new_version=有新版本可用! +sps.version.notes=註記 +sps.version.notes.message=查看註釋。 +sps.version.old_vers= 您的版本 +sps.version.please_update=請更新到最新版本。 \ No newline at end of file diff --git a/permissions.yml b/permissions.yml new file mode 100644 index 0000000..0f66bb2 --- /dev/null +++ b/permissions.yml @@ -0,0 +1,34 @@ +# This is a sample permissions.yml file. +groups: + Member: + default: true + permissions: + - -essentials.sleepingignored + - sps.hermits + - sps.cancel + inheritance: [] + info: + prefix: '&f' + build: false + suffix: '' + Admin: + default: false + permissions: + - -essentials.sleepingignored + - sps.update + - sps.showUpdateAvailable + inheritance: + - Member + - Ops + info: + prefix: '&6Admin' + build: false + suffix: '' + Ops: + default: op + permissions: + - -essentials.sleepingignored + - -sps.unrestricted + - sps.command + inheriteance: + - Member \ No newline at end of file diff --git a/plugin.yml b/plugin.yml index 15030f9..b3f055f 100644 --- a/plugin.yml +++ b/plugin.yml @@ -1,35 +1,62 @@ name: SinglePlayerSleep -main: com.github.joelgodofwar.sps.PluginBase -version: 2.13.9 -author: JoelGodOfWar +main: com.github.joelgodofwar.sps.SinglePlayerSleep +version: 1.13_2.13.50 +author: JoelGodOfWar(JoelYahwehOfWar) +api-version: 1.13 +softdepend: [BloodMoon, bloodmoon-advanced, VentureChat, Essentials, EssentialsX, HexNicks] commands: - cancel: + spscancel: description: Cancels Single Player Sleep. Does not change to day. usage: / sleep: description: Notifies players that player wishes to sleep. usage: / + dayskip: + description: Notifies players that player wishes to dayskip. + usage: / sps: description: Shows SinglePlayerSleep help. usage: / + spsbloodmoon: + description: Disables sleep during a blood moon, console only. + usage: / + clearrain: + description: Clears rain, when it is not night and there is a rain storm. + usage: / permissions: sps.hermits: - description: Allows one player to sleep to change to day. Without clearing local difficulty. + description: Allows one player to change the time to day when using a bed. Without clearing local difficulty. default: true + sps.unrestricted: + description: Allows the player to sleep uninterrupted. Other players will not be able to cancel it. + default: false sps.downfall: description: Clears Downfall upon SPS sleep. - default: true + default: false sps.thunder: description: Clears Thunderstorm upon SPS sleep - default: true + default: false sps.cancel: description: Allows canceling Single Player Sleep. default: true sps.command: - description: Allows player to use /sleep command, instead of a bed. + description: Allows player to use the /sleep command, instead of a bed. + default: op + sps.update: + description: Allows the player to check for updates. default: op sps.op: description: Overrides all permissions. - default: false \ No newline at end of file + default: false + sps.showUpdateAvailable: + description: Shows player that there is a version update. + default: op + sps.dayskipper: + description: Allows one player to change the time to night when using a bed. Without clearing local difficulty. + default: false + sps.dayskipcommand: + sps.command: + description: Allows player to use the /dayskip command, instead of a bed. + default: op \ No newline at end of file diff --git a/src/com/github/joelgodofwar/sps/SinglePlayerSleep.java b/src/com/github/joelgodofwar/sps/SinglePlayerSleep.java new file mode 100644 index 0000000..dc79f5a --- /dev/null +++ b/src/com/github/joelgodofwar/sps/SinglePlayerSleep.java @@ -0,0 +1,2325 @@ +package com.github.joelgodofwar.sps; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.nio.file.CopyOption; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import java.util.logging.Logger; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.data.type.Bed; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerBedEnterEvent; +import org.bukkit.event.player.PlayerBedEnterEvent.BedEnterResult; +import org.bukkit.event.player.PlayerBedLeaveEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitTask; +import org.jetbrains.annotations.NotNull; +import org.spectralmemories.bloodmoon.BloodmoonActuator; + +import com.earth2me.essentials.Essentials; +import com.github.joelgodofwar.sps.api.ChatColorUtils; +import com.github.joelgodofwar.sps.api.Metrics; +import com.github.joelgodofwar.sps.api.StrUtils; +import com.github.joelgodofwar.sps.api.YmlConfiguration; +import com.github.joelgodofwar.sps.i18n.Translator; +import com.github.joelgodofwar.sps.util.Ansi; +import com.github.joelgodofwar.sps.util.Format; +import com.github.joelgodofwar.sps.util.UpdateChecker; +import com.github.joelgodofwar.sps.util.Utils; +import com.github.joelgodofwar.sps.util.VersionChecker; + +import dev.majek.hexnicks.Nicks; +import dev.majek.relocations.net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import me.mrgeneralq.bloodmoon.api.BloodmoonAPI; +import mineverse.Aust1n46.chat.api.MineverseChatAPI; +import mineverse.Aust1n46.chat.api.MineverseChatPlayer; +/** + * @author JoelGodOfWar(JoelYahwehOfWar) + * some code added by ColdCode(coldcode69) + */ + +@SuppressWarnings("unused") +public class SinglePlayerSleep extends JavaPlugin implements Listener{ + /** Languages: čeština (cs_CZ), Deutsch (de_DE), English (en_US), Español (es_ES), Español (es_MX), Français (fr_FR), Italiano (it_IT), Magyar (hu_HU), 日本語 (ja_JP), 한국어 (ko_KR), Lolcat (lol_US), Melayu (my_MY), Nederlands (nl_NL), Polski (pl_PL), Português (pt_BR), Русский (ru_RU), Svenska (sv_SV), Türkçe (tr_TR), 中文(简体) (zh_CN), 中文(繁體) (zh_TW) */ + public final static Logger logger = Logger.getLogger("Minecraft"); + static String THIS_NAME; + static String THIS_VERSION; + /** update checker variables */ + public int projectID = 68139; // https://spigotmc.org/resources/71236 + public String githubURL = "https://github.com/JoelGodOfwar/SinglePlayerSleep/raw/master/versioncheck/1.13/versions.xml"; + boolean UpdateAvailable = false; + public String UColdVers; + public String UCnewVers; + public static boolean UpdateCheck; + public String DownloadLink = "https://www.spigotmc.org/resources/singleplayersleep.68139"; + /** end update checker variables */ + + public static boolean cancelbroadcast; + public static boolean debug; + public static String daLang; + //private boolean UpdateAviable = false; + + public boolean isCanceled = false; + public boolean isDSCanceled = false; + public int transitionTask = 0; + public int dayskipTask = 0; + public int transitionTaskUnrestricted = 1; + public long pTime = 0; + public Map playersCancelled = new HashMap(); + private URL url; + private static long mobSpawningStartTime = 12541;//12600; + //mobs stop spawning at: 22813 + //mobs start to burn at: 23600 + private static long mobSpawningStopTime = 23600; + File langFile; + FileConfiguration lang; + Translator lang2; + public static boolean displaycancel; + public HashMap sleeplimit = new HashMap(); + public HashMap cancellimit = new HashMap(); + YmlConfiguration config = new YmlConfiguration(); + YamlConfiguration oldconfig = new YamlConfiguration(); + public boolean isBloodMoon = false; + public String jsonColorString = "\"},{\"text\":\"\",\"color\":\"\"},{\"text\":\""; + public boolean is116 = false; + String blacklist_sleep; + String blacklist_dayskip; + boolean colorful_console; + String configVersion = "1.0.7"; + String pluginName = THIS_NAME; + private Set triggeredPlayers = new HashSet<>(); + + @Override // TODO: onEnable + public void onEnable(){ + long startTime = System.currentTimeMillis(); + UpdateCheck = getConfig().getBoolean("auto_update_check", true); + debug = getConfig().getBoolean("debug", false); + daLang = getConfig().getString("lang", "en_US"); + displaycancel = getConfig().getBoolean("display_cancel", true); + //log("displaycancel=" + displaycancel); + config = new YmlConfiguration(); + oldconfig = new YamlConfiguration(); + blacklist_sleep = config.getString("blacklist.sleep", ""); + blacklist_dayskip = config.getString("blacklist.dayskip", ""); + colorful_console = getConfig().getBoolean("colorful_console", true); + THIS_NAME = this.getDescription().getName(); + THIS_VERSION = this.getDescription().getVersion(); + if(!getConfig().getBoolean("console.longpluginname", true)) { + pluginName = "SPS"; + }else { + pluginName = THIS_NAME; + } + lang2 = new Translator(daLang, getDataFolder().toString()); + + + + SinglePlayerSleep.logger.info(Ansi.GREEN + "**************************************" + Ansi.RESET); + SinglePlayerSleep.logger.info(Ansi.YELLOW + THIS_NAME + " v" + THIS_VERSION + Ansi.RESET + " Loading..."); + /** DEV check **/ + File jarfile = this.getFile().getAbsoluteFile(); + if(jarfile.toString().contains("-DEV")){ + debug = true; + logDebug("Jar file contains -DEV, debug set to true"); + //log("jarfile contains dev, debug set to true."); + } + if(debug){logDebug("datafolder=" + getDataFolder());} + /**langFile = new File(getDataFolder() + "" + File.separatorChar + "lang" + File.separatorChar, daLang + ".yml");//\ + if(debug){logDebug("langFilePath=" + langFile.getPath());} + if(!langFile.exists()){ // checks if the yaml does not exist + langFile.getParentFile().mkdirs(); // creates the /plugins// directory if not found + saveResource("lang" + File.separatorChar + "cs_CZ.yml", true); + saveResource("lang" + File.separatorChar + "de_DE.yml", true); + saveResource("lang" + File.separatorChar + "en_US.yml", true); + saveResource("lang" + File.separatorChar + "es_MX.yml", true); + saveResource("lang" + File.separatorChar + "fr_FR.yml", true); + saveResource("lang" + File.separatorChar + "ja_JP.yml", true); + saveResource("lang" + File.separatorChar + "lol_US.yml", true); + saveResource("lang" + File.separatorChar + "nl_NL.yml", true); + saveResource("lang" + File.separatorChar + "pl_PL.yml", true); + saveResource("lang" + File.separatorChar + "pt_BR.yml", true); + saveResource("lang" + File.separatorChar + "sv_SV.yml", true); + saveResource("lang" + File.separatorChar + "tr_TR.yml", true); + saveResource("lang" + File.separatorChar + "zh_CN.yml", true); + saveResource("lang" + File.separatorChar + "zh_TW.yml", true); + log("lang file not found! copied cs_CZ.yml, de_DE.yml, en_US.yml, es_MX.yml, fr_FR.yml, ja_JP, lol_US.yml, nl_NL.yml, pl_PL.yml, pt_BR.yml, sv_SV.yml,tr_TR.yml, zh_TW.yml, and zh_CN.yml to " + getDataFolder() + "" + File.separatorChar + "lang"); + //ConfigAPI.copy(getResource("lang.yml"), langFile); // copies the yaml from your jar to the folder /plugin/ + } + lang = new YamlConfiguration(); + try { + lang.load(langFile); + } catch (IOException | InvalidConfigurationException e1) { + e1.printStackTrace(); + } + String checklangversion = getString("langversion"); + if(checklangversion != null&&checklangversion.contains("2.13.48")){ + //Up to date do nothing + }else{ + // outdated, update them then + if(debug){logDebug("checklangversion='" + checklangversion + "'");} + saveResource("lang" + File.separatorChar + "cs_CZ.yml", true); + saveResource("lang" + File.separatorChar + "de_DE.yml", true); + saveResource("lang" + File.separatorChar + "en_US.yml", true); + saveResource("lang" + File.separatorChar + "es_MX.yml", true); + saveResource("lang" + File.separatorChar + "fr_FR.yml", true); + saveResource("lang" + File.separatorChar + "ja_JP.yml", true); + saveResource("lang" + File.separatorChar + "lol_US.yml", true); + saveResource("lang" + File.separatorChar + "nl_NL.yml", true); + saveResource("lang" + File.separatorChar + "pl_PL.yml", true); + saveResource("lang" + File.separatorChar + "pt_BR.yml", true); + saveResource("lang" + File.separatorChar + "sv_SV.yml", true); + saveResource("lang" + File.separatorChar + "tr_TR.yml", true); + saveResource("lang" + File.separatorChar + "zh_CN.yml", true); + saveResource("lang" + File.separatorChar + "zh_TW.yml", true); + log("Updating lang files! copied cs_CZ.yml, de_DE.yml, en_US.yml, es_MX.yml, fr_FR.yml, ja_JP, lol_US.yml, nl_NL.yml, pl_PL.yml, pt_BR.yml, sv_SV.yml,tr_TR.yml, zh_TW.yml, and zh_CN.yml to " + getDataFolder() + "" + File.separatorChar + "lang"); + } + File oldlangFile = new File(getDataFolder() + "" + File.separatorChar + "lang.yml"); + if(oldlangFile.exists()){ + oldlangFile.delete(); + log("Old lang.yml file deleted."); + }//*/ + + /** update checker variable */ + //newVerMsg = ChatColor.YELLOW + thisName + ChatColor.RED + " v{oVer}" + ChatColor.RESET + " " + get("newvers") + ChatColor.GREEN + " v{nVer}" + ChatColor.RESET; + /** end update checker variable */ + + /** Check for config */ + try{ + if(!getDataFolder().exists()){ + log("Data Folder doesn't exist"); + log("Creating Data Folder"); + getDataFolder().mkdirs(); + log("Data Folder Created at " + getDataFolder()); + } + File file = new File(getDataFolder(), "config.yml"); + log("" + file); + if(!file.exists()){ + log("config.yml not found, creating!"); + saveResource("config.yml", true); + } + }catch(Exception e){ + e.printStackTrace(); + } + /** end config check */ + /** Check if config.yml is up to date.*/ + boolean needConfigUpdate = false; + String oldConfig = new File(getDataFolder(), "config.yml").getPath().toString(); + try { + oldconfig.load(new File(getDataFolder() + "" + File.separatorChar + "config.yml")); + } catch (Exception e2) { + logWarn("Could not load config.yml"); + e2.printStackTrace(); + } + String checkconfigversion = oldconfig.getString("version", "1.0.0"); + if(checkconfigversion != null){ + if(!checkconfigversion.equalsIgnoreCase(configVersion)){ + needConfigUpdate = true; + } + } + if(needConfigUpdate){ + try { + copyFile_Java7(getDataFolder() + "" + File.separatorChar + "config.yml",getDataFolder() + "" + File.separatorChar + "old_config.yml"); + } catch (IOException e) { + e.printStackTrace(); + } + try { + oldconfig.load(new File(getDataFolder(), "config.yml")); + } catch (IOException | InvalidConfigurationException e2) { + logWarn("Could not load config.yml"); + e2.printStackTrace(); + } + saveResource("config.yml", true); + try { + config.load(new File(getDataFolder(), "config.yml")); + } catch (IOException | InvalidConfigurationException e1) { + logWarn("Could not load config.yml"); + e1.printStackTrace(); + } + try { + oldconfig.load(new File(getDataFolder(), "old_config.yml")); + } catch (IOException | InvalidConfigurationException e1) { + e1.printStackTrace(); + } + config.set("auto_update_check", oldconfig.get("auto_update_check", true)); + config.set("debug", oldconfig.get("debug", false)); + config.set("lang", oldconfig.get("lang", "en_US")); + config.set("blacklist.sleep", oldconfig.get("blacklist.sleep", "world_nether, world_the_end")); + config.set("blacklist.dayskip", oldconfig.get("blacklist.dayskip", "world_nether, world_the_end")); + config.set("broadcast_per_world", oldconfig.get("broadcast_per_world", true)); + config.set("reset_insomnia", oldconfig.get("reset_insomnia", false)); + config.set("colorful_console", oldconfig.get("colorful_console", true)); + config.set("clearrain_enabled", oldconfig.get("clearrain_enabled", false)); + config.set("unrestrictedsleep", oldconfig.get("unrestrictedsleep", false)); + config.set("waketime", oldconfig.get("waketime", "NORMAL")); + config.set("sleepdelay", oldconfig.get("sleepdelay", 10)); + config.set("enabledayskipper", oldconfig.get("enabledayskipper", false)); + config.set("dayskipdelay", oldconfig.get("dayskipdelay", 10)); + config.set("unrestricteddayskipper", oldconfig.get("unrestricteddayskipper", false)); + config.set("dayskipperitemrequired", oldconfig.get("dayskipperitemrequired", true)); + config.set("cancelcolor", oldconfig.get("cancelcolor", "RED")); + config.set("cancelbracketcolor", oldconfig.get("cancelbracketcolor", "YELLOW")); + config.set("sleepmsgcolor", oldconfig.get("sleepmsgcolor", "STRIKETHROUGHYELLOW")); + config.set("playernamecolor", oldconfig.get("playernamecolor", "WHITE")); + config.set("exitbedcancel", oldconfig.get("exitbedcancel", false)); + config.set("display_cancel", oldconfig.get("display_cancel", true)); + config.set("cancelbroadcast", oldconfig.get("cancelbroadcast", true)); + config.set("sleeplimit", oldconfig.get("sleeplimit", 60)); + config.set("cancellimit", oldconfig.get("cancellimit", 60)); + config.set("notifymustbenight", oldconfig.get("notifymustbenight", false)); + config.set("nickname.usedisplayname", oldconfig.get("nickname.usedisplayname", true)); + config.set("randomsleepmsgs", oldconfig.get("randomsleepmsgs", true)); + config.set("numberofsleepmsgs", oldconfig.get("numberofsleepmsgs", 4)); + for (int i = 1; i < (getConfig().getInt("numberofsleepmsgs") + 1); i++) { + config.set("sleepmsg" + i, oldconfig.get("sleepmsg" + i, " is sleeping")); + } + try { + config.save(new File(getDataFolder(), "config.yml")); + } catch (IOException e) { + logWarn("Could not save old settings to config.yml"); + e.printStackTrace(); + } + log("config.yml has been updated"); + }else{ + //log("" + "not found"); + } + /** End Config update check */ + // End config.yml check. + + /** Update Checker */ + if(UpdateCheck){ + try { + Bukkit.getConsoleSender().sendMessage("Checking for updates..."); + VersionChecker updater = new VersionChecker(this, projectID, githubURL); + if(updater.checkForUpdates()) { + /** Update available */ + UpdateAvailable = true; // TODO: Update Checker + UColdVers = updater.oldVersion(); + UCnewVers = updater.newVersion(); + + logWarn("*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*"); + logWarn("* " + get("sps.version.message").toString().replace("", THIS_NAME) ); + logWarn("* " + get("sps.version.old_vers") + ChatColor.RED + UColdVers ); + logWarn("* " + get("sps.version.new_vers") + ChatColor.GREEN + UCnewVers ); + logWarn("*"); + logWarn("* " + get("sps.version.please_update") ); + logWarn("*"); + logWarn("* " + get("sps.version.download") + ": " + DownloadLink + "/history"); + logWarn("* " + get("sps.version.donate.message") + ": https://ko-fi.com/joelgodofwar"); + logWarn("*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*"); + }else{ + /** Up to date */ + log("*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*"); + log("* " + get("sps.version.curvers")); + log("* " + get("sps.version.donate") + ": https://ko-fi.com/joelgodofwar"); + log("*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*"); + UpdateAvailable = false; + } + }catch(Exception e) { + /** Error */ + logWarn( get("sps.version.update.error")); + e.printStackTrace(); + } + }else { + /** auto_update_check is false so nag. */ + logWarn("*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*"); + logWarn( "* " + get("sps.version.donate.message") + ": https://ko-fi.com/joelgodofwar"); + logWarn("*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*"); + } + /** end update checker */ + + File file = new File(getDataFolder(), "permissions.yml"); + log("" + file); + if(!file.exists()){ + log("permissions.yml not found, creating! This is a sample only!"); + saveResource("permissions.yml", true); + } + getServer().getPluginManager().registerEvents(this, this); + + log("This server is running " + Bukkit.getName() + " version " + Bukkit.getVersion() + " (Implementing API version " + Bukkit.getBukkitVersion() + ")"); + log("vardebug=" + debug + " debug=" + getConfig().get("debug","error") + " in " + this.getDataFolder() + "/config.yml"); + log("jarfilename=" + this.getFile().getAbsoluteFile()); + + if(getConfig().getBoolean("debug")==true&&!(jarfile.toString().contains("-DEV"))){ + logDebug("Config.yml dump"); + logDebug("auto_update_check=" + getConfig().getBoolean("auto_update_check")); + logDebug("debug=" + getConfig().getBoolean("debug")); + logDebug("lang=" + getConfig().getString("lang")); + logDebug("unrestrictedsleep=" + getConfig().getBoolean("unrestrictedsleep")); + logDebug("waketime=" + getConfig().getString("waketime")); + logDebug("sleepdelay=" + getConfig().getString("sleepdelay")); + logDebug("enabledayskipper=" + getConfig().getString("enabledayskipper")); + logDebug("dayskipdelay=" + getConfig().getString("dayskipdelay")); + logDebug("unrestricteddayskipper=" + getConfig().getBoolean("unrestricteddayskipper")); + logDebug("dayskipperitemrequired=" + getConfig().getBoolean("dayskipperitemrequired")); + logDebug("cancelcolor=" + getConfig().getString("cancelcolor")); + logDebug("sleepmsgcolor=" + getConfig().getString("sleepmsgcolor")); + logDebug("playernamecolor=" + getConfig().getString("playernamecolor")); + logDebug("exitbedcancel=" + getConfig().getBoolean("exitbedcancel")); + logDebug("display_cancel=" + getConfig().getBoolean("display_cancel")); + logDebug("cancelbroadcast=" + getConfig().getBoolean("cancelbroadcast")); + logDebug("sleeplimit=" + getConfig().getInt("sleeplimit")); + logDebug("cancellimit=" + getConfig().getInt("cancellimit")); + logDebug("notifymustbenight=" + getConfig().getInt("notifymustbenight")); + logDebug("randomsleepmsgs=" + getConfig().getBoolean("randomsleepmsgs")); + logDebug("numberofsleepmsgs=" + getConfig().getString("numberofsleepmsgs")); + } + String[] serverversion; + serverversion = getVersion().split("\\."); + if(debug){logDebug("getVersion = " + getVersion());} + if(debug){logDebug("serverversion = " + serverversion.length);} + for (int i = 0; i < serverversion.length; i++) + if(debug){logDebug(serverversion[i] + " i=" + i);} + if (!(Integer.parseInt(serverversion[1]) >= 16)){ + is116 = false; + }else{ + is116 = true; + } + if(debug){logDebug(Ansi.BOLD + "" + Ansi.RED + "is116=" + is116 + Ansi.RESET);} + consoleInfo("ENABLED - Loading took " + LoadTime(startTime)); + try { + //PluginBase plugin = this; + Metrics metrics = new Metrics(this, 5934); + // New chart here + // myPlugins() + metrics.addCustomChart(new Metrics.AdvancedPie("my_other_plugins", new Callable>() { + @Override + public Map call() throws Exception { + Map valueMap = new HashMap<>(); + + if(getServer().getPluginManager().getPlugin("DragonDropElytra") != null){valueMap.put("DragonDropElytra", 1);} + if(getServer().getPluginManager().getPlugin("NoEndermanGrief") != null){valueMap.put("NoEndermanGrief", 1);} + if(getServer().getPluginManager().getPlugin("PortalHelper") != null){valueMap.put("PortalHelper", 1);} + if(getServer().getPluginManager().getPlugin("ShulkerRespawner") != null){valueMap.put("ShulkerRespawner", 1);} + if(getServer().getPluginManager().getPlugin("MoreMobHeads") != null){valueMap.put("MoreMobHeads", 1);} + if(getServer().getPluginManager().getPlugin("SilenceMobs") != null){valueMap.put("SilenceMobs", 1);} + //if(getServer().getPluginManager().getPlugin("SinglePlayerSleep") != null){valueMap.put("SinglePlayerSleep", 1);} + if(getServer().getPluginManager().getPlugin("VillagerWorkstationHighlights") != null){valueMap.put("VillagerWorkstationHighlights", 1);} + if(getServer().getPluginManager().getPlugin("RotationalWrench") != null){valueMap.put("RotationalWrench", 1);} + return valueMap; + } + })); + metrics.addCustomChart(new Metrics.SimplePie("auto_update_check", new Callable() { + @Override + public String call() throws Exception { + return "" + getConfig().getString("auto_update_check").toUpperCase(); + } + })); + // add to site + metrics.addCustomChart(new Metrics.SimplePie("unrestrictedsleep", new Callable() { + @Override + public String call() throws Exception { + return "" + getConfig().getString("unrestrictedsleep").toUpperCase(); + } + })); + metrics.addCustomChart(new Metrics.SimplePie("var_waketime", new Callable() { + @Override + public String call() throws Exception { + return "" + getConfig().getString("waketime").toUpperCase(); + } + })); + metrics.addCustomChart(new Metrics.SimplePie("var_sleepdelay", new Callable() { + @Override + public String call() throws Exception { + return "" + getConfig().getInt("sleepdelay"); + } + })); + metrics.addCustomChart(new Metrics.SimplePie("cancelbroadcast", new Callable() { + @Override + public String call() throws Exception { + return "" + getConfig().getString("cancelbroadcast").toUpperCase(); + } + })); + metrics.addCustomChart(new Metrics.SimplePie("var_debug", new Callable() { + @Override + public String call() throws Exception { + return "" + getConfig().getString("debug").toUpperCase(); + } + })); + metrics.addCustomChart(new Metrics.SimplePie("var_lang", new Callable() { + @Override + public String call() throws Exception { + return "" + getConfig().getString("lang").toUpperCase(); + } + })); + metrics.addCustomChart(new Metrics.SimplePie("numberofsleepmsgs", new Callable() { + @Override + public String call() throws Exception { + return "" + getConfig().getInt("numberofsleepmsgs"); + } + })); + metrics.addCustomChart(new Metrics.SimplePie("dayskipdelay", new Callable() { + @Override + public String call() throws Exception { + return "" + getConfig().getInt("dayskipdelay"); + } + })); + metrics.addCustomChart(new Metrics.SimplePie("unrestricteddayskipper", new Callable() { + @Override + public String call() throws Exception { + return "" + getConfig().getBoolean("unrestricteddayskipper"); + } + })); + metrics.addCustomChart(new Metrics.SimplePie("enabledayskipper", new Callable() { + @Override + public String call() throws Exception { + return "" + getConfig().getBoolean("enabledayskipper"); + } + })); + }catch (Exception e){ + // Failed to submit the stats + } + + } + + @Override // TODO: onDisable + public void onDisable() { + consoleInfo("DISABLED"); + } + + public void consoleInfo(String state) { + + SinglePlayerSleep.logger.info(Ansi.GREEN + "**************************************" + Ansi.RESET); + SinglePlayerSleep.logger.info(Ansi.YELLOW + THIS_NAME + " v" + THIS_VERSION + Ansi.RESET + " is " + state); + SinglePlayerSleep.logger.info(Ansi.GREEN + "**************************************" + Ansi.RESET); + } + + public String nameColor() { + //Only change name colours if one is set + if (!getConfig().getString("namecolor").contains("NONE")) { + String nameColor = ChatColorUtils.setColors(getConfig().getString("namecolor")); + return nameColor; + } else { + return ""; + } + } + + + /** + * @param event + * @throws InterruptedException + */ + @EventHandler + public void PlayerIsSleeping(PlayerBedEnterEvent event) throws InterruptedException{ + if(debug){logDebug(ChatColor.RED + "** Start PlayerBedEnterEvent **");} + List worlds = Bukkit.getWorlds(); + //boolean debug = getConfig().getBoolean("debug"); + final Player player = event.getPlayer(); + if(debug){logDebug("PIS player set. ...");} + final World world = player.getWorld(); + if(debug){logDebug(" PIS world set. ...");} + int sleepdelay = getConfig().getInt("sleepdelay", 10); + int dayskipdelay = getConfig().getInt("dayskipdelay", 10); + event.getBedEnterResult(); + /** Debug info */ + if(debug){logDebug(ChatColor.RED + "**************************************************");} + if(debug){logDebug(ChatColor.RED + "DEBUG LOG SHOULD CONTAIN THIS");} + if(debug){logDebug("PIS 12786-23031 = Night, worldTime=" + world.getFullTime());} + if(debug){logDebug("PIS isNight=" + IsNight(player.getWorld()) + " , isDay=" + IsDay(player.getWorld()));} + if(debug){logDebug("PIS isOP=" + player.isOp() + ", is116=" + is116);} + if(debug){logDebug("PIS sps.Hermits=" + player.hasPermission("sps.hermits"));} + if(debug){logDebug("PIS sps.unrestricted=" + player.hasPermission("sps.unrestricted"));} + if(debug){logDebug("PIS sps.op=" + player.hasPermission("sps.op"));} + if(debug){logDebug("PIS unrestrictedsleep=" + getConfig().getBoolean("unrestrictedsleep"));} + if(debug){logDebug("PIS BedEnterResult=" + event.getBedEnterResult().toString());} + if(debug){logDebug("PIS isRaining=" + event.getPlayer().getWorld().hasStorm());} + if(debug){logDebug("PIS isThunderstorm=" + event.getPlayer().getWorld().isThundering());} + if(debug){logDebug("PIS Permission List:");} + if(debug){logDebug("PIS sps.hermits=" + player.hasPermission("sps.hermits"));} + if(debug){logDebug("PIS sps.cancel=" + player.hasPermission("sps.cancel"));} + if(debug){logDebug("PIS sps.unrestricted=" + player.hasPermission("sps.unrestricted"));} + if(debug){logDebug("PIS sps.downfall=" + player.hasPermission("sps.downfall"));} + if(debug){logDebug("PIS sps.thunder=" + player.hasPermission("sps.thunder"));} + if(debug){logDebug("PIS sps.command=" + player.hasPermission("sps.command"));} + if(debug){logDebug("PIS sps.update=" + player.hasPermission("sps.update"));} + if(debug){logDebug("PIS sps.op=" + player.hasPermission("sps.op"));} + if(debug){logDebug("PIS sps.showUpdateAvailable=" + player.hasPermission("sps.showUpdateAvailable"));} + if(debug){logDebug("PIS sps.dayskipper=" + player.hasPermission("sps.dayskipper"));} + if(debug){logDebug("PIS sps.dayskipcommand=" + player.hasPermission("sps.dayskipcommand"));} + if(debug){logDebug(ChatColor.RED + "**************************************************");} + + if(getServer().getPluginManager().getPlugin("EssentialsX") != null||getServer().getPluginManager().getPlugin("Essentials") != null){ + if(debug){logDebug("perm essentials.sleepingignored=" + player.hasPermission("essentials.sleepingignored"));} + if(player.hasPermission("essentials.sleepingignored") && !player.isOp()){ + player.sendMessage(ChatColor.RED + "WARNING! " + ChatColor.YELLOW + " you have the permission (" + ChatColor.GOLD + + "essentials.sleepingignored" + ChatColor.YELLOW + + ") which is conflicting with SinglePlaySleep. Please ask for it to be removed. " + ChatColor.RED + "WARNING! "); + logWarn("Player " + player.getName() + "has the permission " + "essentials.sleepingignored" + " which is known to conflict with SinglePlayerSleep."); + return; + } + } + if(getConfig().getBoolean("enabledayskipper", false)){ // TODO: Dayskip + /* Check if it's Day for DaySkipper */ + if(IsDay(player.getWorld())){ + if(debug){logDebug(" DS it is Day");} + /* OK it's day check if it's a Black bed. */ + if(!player.hasPermission("sps.op")){ // TODO: Dayskip blacklist Check + if(blacklist_dayskip != null&&!blacklist_dayskip.isEmpty()){ + if(StrUtils.stringContains(blacklist_dayskip, world.getName().toString())){ + log("EDE - World - On blacklist."); + return; + } + } + } + /* OK it is a Black bed, now check if they have the DaySkipper item. */ + /*String daMainHand = player.getInventory().getItemInMainHand().getItemMeta().getDisplayName(); + log("daMainHand=" + daMainHand); + String daOffHand = player.getInventory().getItemInOffHand().getItemMeta().getDisplayName(); + log("daOffHand=" + daOffHand);*/ + ItemStack[] inv = player.getInventory().getContents(); + if(debug){logDebug("passed itemstack");} + boolean itmDaySkipper = false; + if(debug){logDebug("itemdayskipper initilized");} + for(ItemStack item:inv){ + + if(!(item == null)){ + if(debug){logDebug("item=" + item.getType().name());} + if(item.getItemMeta().getDisplayName().equalsIgnoreCase("DaySkipper")){ + itmDaySkipper = true; + if(debug){logDebug("found the item");} + break; + } + } + } + if(debug){logDebug("inventory iterator finished.");} + if(!getConfig().getBoolean("dayskipperitemrequired", true)){itmDaySkipper = true;} + if(itmDaySkipper){ //daMainHand.contentEquals("DaySkipper")||daOffHand.contentEquals("DaySkipper")|| + if(debug){logDebug(" DS item DaySkipper is in inventory.");} + + Block block = event.getBed(); + if (((Bed)block.getBlockData()).getMaterial().equals(Material.BLACK_BED)){ + if(debug){logDebug(" DS the bed is Black");} + /* OK they have the DaySkipper item, now check for the permission*/ + if(player.hasPermission("sps.dayskipper")||player.hasPermission("sps.op")||player.hasPermission("sps.*")){ + if(debug){logDebug(" DS Has perm or is op. ...");} + String CancelBracketColor = ChatColorUtils.setColorsByName(getConfig().getString("cancelbracketcolor", "YELLOW")); + /* OK they have the perm, now lets notify the server and schedule the runnable */ + String canmsg = CancelBracketColor + "[\"},{\"text\":\"dacancel\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/spscancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"tooltip\"}},{\"text\":\"" + CancelBracketColor + "]\"}"; + String damsg = "[\"\",{\"text\":\"sleepmsg " + canmsg + "]"; + String msgcolor = ChatColorUtils.setColorsByName(getConfig().getString("sleepmsgcolor", "YELLOW")); + if(debug){logDebug(" DS ... msgcolor=" + msgcolor);} + String sleepmsg = "" + get("sps.message.dayskipmsg"," wants to sleep the day away..."); + if(is116){ + sleepmsg = ChatColorUtils.setNametoRGB(sleepmsg); + sleepmsg = StrUtils.parseRGBNameColors(sleepmsg); + }else{ + sleepmsg = StrUtils.stripRGBColors(sleepmsg);// strip RGBHEX + sleepmsg = ChatColorUtils.setColors(sleepmsg);// SetColorsByName + } + + damsg = damsg.replace("sleepmsg", sleepmsg).replace("\"]\"", "\"" + msgcolor + "]\""); + //damsg = ChatColorUtils.setColors(damsg); + //damsg = StrUtils.parseRGBNameColors(damsg); + /** nickname parser */ + String nickName = getNickname(player); + String playercolor = ""; + if(!nickName.contains("§")){ + //logWarn("nickName ! contain SS"); + playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + }else{ + nickName = StrUtils.parseRGBNameColors(nickName); + } + /** end nickname parser */ + if(debug){logDebug(" DS ... playercolor=" + playercolor);} + damsg = damsg.replace("", /**playercolor +*/ nickName /**+ msgcolor*/); + String cancelcolor = ChatColorUtils.setColorsByName(getConfig().getString("cancelcolor")); + if(debug){logDebug(" DS ... cancelcolor=" + cancelcolor);} + damsg = damsg.replace("dacancel", cancelcolor + get("dayskipcancel") + msgcolor); + //change cancel color based on config + damsg = damsg.replace("tooltip", "" + get("dayskipclickcancel")); + if(debug){logDebug(" DS string processed. ...");} + if(debug){logDebug(" DS damsg=" + damsg);} + + if(getConfig().getBoolean("broadcast_per_world", true)){ + sendJson(player.getWorld(), damsg, canmsg); + }else{ + sendJson(damsg, canmsg); + } + if(debug){logDebug(" DS SendAllJsonMessage. ...");} + //player.sendMessage("The item in your main hand is named: " + daName); + if(!isDSCanceled){ + if(debug){logDebug(" DS !isDSCanceled. ...");} + dayskipTask = this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + + public void run() { + setDStime(player, world); + if(debug){logDebug(" DS setDStime has run. ...");} + } + + }, dayskipdelay * 20); + + }else{ + + isDSCanceled = false; + } + return; + }else{ + player.sendMessage(ChatColor.YELLOW + "" + get("sps.message.noperm")); + //player.sendTitle("", ChatColor.YELLOW + "" + get("sps.message.noperm"), 0, 0, 5); + } + }else{ + player.sendMessage(ChatColor.YELLOW + "" + get("sps.message.dayskipblackbed"));/* NOT A BLACK BED */ + } + } + }else{ + if(debug){logDebug("PIS isDay=false");} + } + }else{ + if(debug){logDebug("PIS enabledayskipper=false");} + } + //if(debug){logDebug("PIS getBedEnterResult=" + event.getBedEnterResult().toString());} + if(!isBloodmoonInprogress(player.getWorld())){//isBloodmoonInprogress//isBloodMoon + if(event.getBedEnterResult() == BedEnterResult.OK){ + //Check it's night or if storm + if (IsNight(player.getWorld())||player.getWorld().isThundering()) { + if(!player.hasPermission("sps.op")){ // TODO: Sleep Blacklist Check + if(blacklist_sleep != null&&!blacklist_sleep.isEmpty()){ + if(StrUtils.stringContains(blacklist_sleep, world.getName().toString())){ + log("EDE - World - On blacklist."); + return; + } + } + } + //Set default timer for when the player has never slept before + long timer = 0; + if(debug){logDebug("PIS IN... " + player.getName() + " is sleeping.");} + long time = System.currentTimeMillis() / 1000; + if(sleeplimit.get(player.getUniqueId()) == null){ + if(debug){logDebug("PIS sleeplimit UUID=null");} + // Check if player has sps.unrestricted + if (!player.hasPermission("sps.unrestricted")) { + // Set player's time in HashMap + sleeplimit.put(player.getUniqueId(), time); + if(debug){logDebug("PIS IN... " + player.getDisplayName() + " added to playersSlept");} + } + }else{ + if(debug){logDebug("PIS sleeplimit UUID !null");} + // Player is on the list. + timer = sleeplimit.get(player.getUniqueId()); + if(debug){logDebug("time=" + time);} + if(debug){logDebug("timer=" + timer);} + if(debug){logDebug("time - timer=" + (time - timer));} + if(debug){logDebug("sleeplimit=" + getConfig().getLong("sleeplimit", 60));} + // if !time - timer > limit + if(!((time - timer) > getConfig().getLong("sleeplimit", 60))){ + long length = getConfig().getLong("sleeplimit", 60) - (time - timer) ; + String sleeplimit = "" + get("sps.message.sleeplimit").toString().replace("", "" + length); + player.sendMessage(ChatColor.YELLOW + sleeplimit); + if(debug){logDebug("PIS IN... sleeplimit: " + sleeplimit);} + //player.sendMessage("You can not do that for " + length + " seconds"); + event.setCancelled(true); + return; + }else if((time - timer) > getConfig().getLong("sleeplimit", 60)){ + if(debug){logDebug("time - timer > sleeplimit");} + sleeplimit.replace(player.getUniqueId(), time); + } + } + + /** /check if player has already tried sleeping to prevent spam + if (getConfig().getInt("sleeplimit") > 0) { + timer = time - pTime; + } + + //Tell the player why they can't sleep + if (timer < getConfig().getInt("sleeplimit")) { + String sleeplimit = "" + get("sps.message.sleeplimit").toString(); + player.sendMessage(ChatColor.YELLOW + sleeplimit); + log("PIS IN... sleeplimit: " + sleeplimit); + } else { + + //Save the time the player last tried to sleep, skip if player has unrestricted sleep since it will always be successful + if (!player.hasPermission("sps.unrestricted")) { + pTime = (int) time; + }// */ + + //Check if players can sleep without the ability for others to cancel it + if (getConfig().getBoolean("unrestrictedsleep")) { + if(debug){logDebug("PIS unrestrictedsleep=true");} + String dastring = "" + get("sps.message.issleep"); + dastring = dastring.replace("", getNickname(player)); + this.broadcast(dastring, world); + transitionTaskUnrestricted = this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + public void run() { + setDatime(player, world); + resetPlayersRestStat(world); + } + }, sleepdelay * 20); + } else { + + //Don't show cancel option if player has unrestricted sleep perm + if (player.hasPermission("sps.unrestricted")) { //TODO: Unrestricted Broadcast, use random msgs, and colorization + + if(debug){logDebug(" PIS Has unrestricted perm. ...");} + + //Broadcast to Server + String dastring = "" + get("sps.message.issleep"); + + dastring = dastring.replace("", ""); + String msgcolor = ChatColorUtils.setColorsByName(getConfig().getString("sleepmsgcolor", "YELLOW")); + if(debug){logDebug(" PIS ... msgcolor=" + msgcolor);} + String CancelBracketColor = ChatColorUtils.setColorsByName(getConfig().getString("cancelbracketcolor", "YELLOW")); + if(debug){logDebug(" PIS ... CancelBracketColor=" + CancelBracketColor);} + //String damsg = "[\"\",{\"text\":\"player\"},{\"text\":\" is sleeping [\"},{\"text\":\"dacancel\",\"color\":\"red\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/cancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"tooltip\"}]}}},{\"text\":\"]\",\"color\":\"none\",\"bold\":false}]"; + //String damsg = "[\"\",{\"text\":\"sleepmsg [\"},{\"text\":\"dacancel\",\"color\":\"red\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/cancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"tooltip\"}},{\"text\":\"]\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/cancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"tooltip\"}}]"; + String canmsg = "";//CancelBracketColor + "[\"},{\"text\":\"dacancel\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/spscancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"tooltip\"}},{\"text\":\"" + CancelBracketColor + "]\""; + String damsg = "[\"\",{\"text\":\"sleepmsg " + canmsg + "\"}]"; + String sleepmsg; + if (getConfig().getBoolean("randomsleepmsgs")){ + int maxmsgs = getConfig().getInt("numberofsleepmsgs"); + int randomnumber = RandomNumber(maxmsgs); + sleepmsg = getConfig().getString("sleepmsg" + randomnumber, ChatColor.WHITE + " is sleeping"); + sleepmsg = sleepmsg.replace("", ":"); + if(debug){logDebug(" PIS ... maxmsgs=" + maxmsgs);} + if(debug){logDebug(" PIS ... randomnumber=" + randomnumber);} + }else{ + sleepmsg = (ChatColor.WHITE + " is sleeping"); + if(debug){logDebug(" PIS ... randomsleepmsgs=false");} + } + if(is116){ + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + sleepmsg = ChatColorUtils.setNametoRGB(sleepmsg); + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + sleepmsg = StrUtils.parseRGBNameColors(sleepmsg); + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + }else{ + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + sleepmsg = StrUtils.stripRGBColors(sleepmsg);// strip RGBHEX TODO: stripRGBColors + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + sleepmsg = ChatColorUtils.setColors(sleepmsg);// SetColorsByName + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + } + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + //sleepmsg = " Has passed Go, Collected their $200, and checked in at Old Kent Road!"; + + /**if(sleepmsg.length() > 54){ + sleepmsg = addChar(sleepmsg, msgcolor, 55); + }*/ + damsg = damsg.replace("sleepmsg", sleepmsg); + damsg = ChatColorUtils.setColors(damsg); + //damsg = StrUtils.parseRGBNameColors(damsg); + /** nickname parser */ + String nickName = getNickname(player); + String playercolor = ""; + if(!nickName.contains("§")){ + //logWarn("nickName ! contain SS"); + playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + }else{ + nickName = StrUtils.parseRGBNameColors(nickName); + } + /** end nickname parser */ + + //String playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + if(debug){logDebug(" PIS ... playercolor=" + playercolor);} + damsg = damsg.replace("", /**playercolor +*/ nickName); + //String cancelcolor = ChatColorUtils.setColorsByName(getConfig().getString("cancelcolor")); + //if(debug){logDebug(" PIS ... cancelcolor=" + cancelcolor);} + //damsg = damsg.replace("dacancel", cancelcolor + get("cancel") + msgcolor); + //change cancel color based on config + //damsg = damsg.replace("tooltip", "" + get("clickcancel")); + if(debug){logDebug(" PIS string processed. ...");} + //String oldString = cancelcolor + get("cancel") + msgcolor; + //damsg = damsg.replace(oldString, "").replace(" [\"", " \"").replace("]\"", "\"").replace(",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/cancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Click to cancel sleep\"}", ""); + + if(getConfig().getBoolean("broadcast_per_world", true)){ + sendJson(player.getWorld(), damsg, canmsg); + }else{ + sendJson(damsg, canmsg); + } + + //SendJsonMessages.SendAllJsonMessage(damsg, cancelcolor + get("cancel") + msgcolor, world); + if(debug){logDebug(" PIS SendAllJsonMessage. ...");} + + transitionTaskUnrestricted = this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + public void run() { + setDatime(player, world); + resetPlayersRestStat(world); + } + }, sleepdelay * 20); + + } else { + if(!isCanceled&&!event.isCancelled()){ + if(player.hasPermission("sps.hermits")||player.hasPermission("sps.op")){ + if(debug){logDebug(" PIS Has perm or is op. ...");} + + //Broadcast to Server + String dastring = "" + get("sps.message.issleep"); + + dastring = dastring.replace("", ""); + String msgcolor = ChatColorUtils.setColorsByName(getConfig().getString("sleepmsgcolor", "YELLOW")); + if(debug){logDebug(" PIS ... msgcolor=" + msgcolor);} + String CancelBracketColor = ChatColorUtils.setColorsByName(getConfig().getString("cancelbracketcolor", "YELLOW")); + if(debug){logDebug(" PIS ... CancelBracketColor=" + CancelBracketColor);} + //String damsg = "[\"\",{\"text\":\"player\"},{\"text\":\" is sleeping [\"},{\"text\":\"dacancel\",\"color\":\"red\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/cancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"tooltip\"}]}}},{\"text\":\"]\",\"color\":\"none\",\"bold\":false}]"; + //String damsg = "[\"\",{\"text\":\"sleepmsg [\"},{\"text\":\"dacancel\",\"color\":\"red\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/cancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"tooltip\"}},{\"text\":\"]\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/cancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"tooltip\"}}]"; + String canmsg = CancelBracketColor + "[\"},{\"text\":\"dacancel\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/spscancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"tooltip\"}},{\"text\":\"" + CancelBracketColor + "]\""; + String damsg = "[\"\",{\"text\":\"sleepmsg " + canmsg + "}]"; + String sleepmsg; + if (getConfig().getBoolean("randomsleepmsgs")){ + int maxmsgs = getConfig().getInt("numberofsleepmsgs"); + int randomnumber = RandomNumber(maxmsgs); + sleepmsg = getConfig().getString("sleepmsg" + randomnumber, ChatColor.WHITE + " is sleeping"); + sleepmsg = sleepmsg.replace("", ":"); + if(debug){logDebug(" PIS ... maxmsgs=" + maxmsgs);} + if(debug){logDebug(" PIS ... randomnumber=" + randomnumber);} + }else{ + sleepmsg = (ChatColor.WHITE + " is sleeping"); + if(debug){logDebug(" PIS ... randomsleepmsgs=false");} + } + if(is116){ + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + sleepmsg = ChatColorUtils.setNametoRGB(sleepmsg); + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + sleepmsg = StrUtils.parseRGBNameColors(sleepmsg); + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + }else{ + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + sleepmsg = StrUtils.stripRGBColors(sleepmsg);// strip RGBHEX TODO: stripRGBColors + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + sleepmsg = ChatColorUtils.setColors(sleepmsg);// SetColorsByName + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + } + if(debug){logDebug(" PIS sleepmsg=" + sleepmsg);} + //sleepmsg = " Has passed Go, Collected their $200, and checked in at Old Kent Road!"; + + /**if(sleepmsg.length() > 54){ + sleepmsg = addChar(sleepmsg, msgcolor, 55); + }*/ + damsg = damsg.replace("sleepmsg", sleepmsg).replace("\"]\"", "\"" + msgcolor + "]\""); + damsg = ChatColorUtils.setColors(damsg); + //damsg = StrUtils.parseRGBNameColors(damsg); + /** nickname parser */ + String nickName = getNickname(player); + String playercolor = ""; + if(!nickName.contains("§")){ + //logWarn("nickName ! contain SS"); + playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + }else{ + nickName = StrUtils.parseRGBNameColors(nickName); + } + /** end nickname parser */ + + //String playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + if(debug){logDebug(" PIS ... playercolor=" + playercolor);} + damsg = damsg.replace("", /**playercolor +*/ nickName); + String cancelcolor = ChatColorUtils.setColorsByName(getConfig().getString("cancelcolor")); + if(debug){logDebug(" PIS ... cancelcolor=" + cancelcolor);} + damsg = damsg.replace("dacancel", cancelcolor + get("sps.message.cancel") + msgcolor); + //change cancel color based on config + damsg = damsg.replace("tooltip", "" + get("sps.message.clickcancel")); + if(debug){logDebug(" PIS string processed. ...");} + //String oldString = cancelcolor + get("cancel") + msgcolor; + //damsg = damsg.replace(oldString, "").replace(" [\"", " \"").replace("]\"", "\"").replace(",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/cancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Click to cancel sleep\"}", ""); + + if(getConfig().getBoolean("broadcast_per_world", true)){ + sendJson(player.getWorld(), damsg, canmsg); + }else{ + sendJson(damsg, canmsg); + } + + //SendJsonMessages.SendAllJsonMessage(damsg, cancelcolor + get("cancel") + msgcolor, world); + if(debug){logDebug(" PIS SendAllJsonMessage. ...");} + + //Thread.sleep(10000); + if(!isCanceled&&!event.isCancelled()){ + if(debug){logDebug(" PIS !isCanceled. ...");} + transitionTask = this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + + public void run() { + setDatime(player, world); + resetPlayersRestStat(world); + if(debug){logDebug(" PIS setDatime has run. ...");} + } + + }, sleepdelay * 20); + + }else{ + if(isCanceled){if(debug){logDebug("PIS isCanceled=" + isCanceled);}} + if(event.isCancelled()){if(debug){logDebug("PIS event.isCanceled=" + event.isCancelled());}} + isCanceled = false; + } + //player.sendMessage(ChatColor.RED + "isCanceled=" + isCanceled); + }else{ //Player doesn't have permission so tell them + player.sendMessage(ChatColor.YELLOW + "" + get("sps.message.noperm")); + } + }else{ + isCanceled = false; + if(isCanceled){if(debug){logDebug("PIS isCanceled=" + isCanceled);}} + if(event.isCancelled()){if(debug){logDebug("PIS event.isCanceled=" + event.isCancelled());}} + } + } + } + //}// + }else{ //It is not Night or Storming so tell the player + if(getConfig().getBoolean("notifymustbenight")){ + player.sendMessage(ChatColorUtils.setColors("" + get("sps.message.nightorstorm"))); + if(debug){logDebug(" it was not night and player was notified. ...");} + } + //if(debug){logDebug("getBedSpawnLocation=" + player.getBedSpawnLocation());} + //if(debug){logDebug("getBed=" + event.getBed().getLocation());} + //player.getBedSpawnLocation().equals(event.getBed().getLocation() + String sv = serverVersion(); + if(!(Integer.parseInt(sv) >= 15)){ + Block bed = event.getBed(); + Location bedSpawn = player.getBedSpawnLocation(); + if(bedSpawn != null){ + boolean isSameBed = checkradius(bedSpawn, event.getBed().getLocation(), 5); + if (!isSameBed||player.getBedSpawnLocation().equals(null)) { + if(player.getBedSpawnLocation().equals(null)){ + if(debug){logDebug("bedspawn=null");} + }else if(!isSameBed){ + if(debug){logDebug("bedspawn!=bed");} + } + player.setBedSpawnLocation(event.getBed().getLocation()); + player.sendMessage(ChatColor.YELLOW + "SPS: " + ChatColor.RESET + get("sps.message.respawnpointmsg").toString().replace("", "" + bed.getX()).replace("", "" + bed.getZ())); + if(debug){logDebug(" bedspawn was set for player " + ChatColor.GREEN + player.getDisplayName() + ChatColor.RESET + " ...");} + } + }else{ + player.setBedSpawnLocation(event.getBed().getLocation()); + player.sendMessage(ChatColor.YELLOW + "SPS: " + ChatColor.RESET + get("sps.message.respawnpointmsg").toString().replace("", "" + bed.getX()).replace("", "" + bed.getZ())); + if(debug){logDebug(" bedspawn was set for player " + ChatColor.GREEN + player.getDisplayName() + ChatColor.RESET + " ...");} + } + }else{ + if(debug){logDebug("Server is 1.15+");} + } + } + } + }else{ + player.sendMessage(ChatColor.YELLOW + "SPS: " + ChatColor.RESET + get("sps.message.bloodmoon", "You can not sleep during a bloodmoon.").toString()); + event.setCancelled(true); + } + if(debug){logDebug(ChatColor.RED + "** End PlayerBedEnterEvent **");} + isCanceled = false; + } + + public boolean checkradius(Location player, Location event, int radius){ + double distance = player.distance(event); + if(distance <= radius) { + if(debug){logDebug("truedistance=" + distance);} + return true; + //shulker.teleport(block.getLocation()); + } + if(debug){logDebug("falsedistance=" + distance);} + return false; + } + + public String serverVersion(){ + String v = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + String v2 = v.split("_")[1]; + return v2; + } + + public void setDatime(Player player, World world){ + if(world.hasStorm()){ + if(player.hasPermission("sps.downfall")){ + world.setStorm(false); + if(debug){logDebug("" + get("sps.message.setdownfall") + "...");} + }else{ + if(debug){logDebug("" + getNickname(player) + " Does not have permission sps.downfall ...");} + } + } + if(world.isThundering()){ + if(player.hasPermission("sps.thunder")){ + world.setThundering(false); + if(debug){logDebug("" + get("sps.message.setthunder") + "...");} + }else{ + if(debug){logDebug("" + getNickname(player) + " Does not have permission sps.thunder ...");} + } + } + String waketime = getConfig().getString("waketime", "NORMAL"); + long timeoffset = 0; + if(waketime.equalsIgnoreCase("early")||waketime.equalsIgnoreCase("23000")){ + timeoffset = 1000; + }else{timeoffset = 0;} + long Relative_Time = (24000 - world.getTime()) - timeoffset; + long daFullTime = world.getFullTime(); + world.setFullTime(daFullTime + Relative_Time); + /** for dumdan and mueks sync all three worlds time. + World Lodestar = Bukkit.getWorld("Lodestar_the_end"); + Lodestar.setFullTime(daFullTime + Relative_Time); + World Lodestar2 = Bukkit.getWorld("Lodestar_nether"); + Lodestar2.setFullTime(daFullTime + Relative_Time); + */ + if(debug){logDebug("" + get("sps.message.settime") + "...");} + } + + public void setDStime(Player player, World world){ + int timeoffset = 10000; + long Relative_Time = (24000 - world.getTime()) - timeoffset; + world.setFullTime(world.getFullTime() + Relative_Time); + if(debug){logDebug("" + get("sps.message.dayskipsettime") + "...");} + } + + @Override + public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { // TODO: Tab Complete + if (command.getName().equalsIgnoreCase("sps")) { + List autoCompletes = new ArrayList<>(); //create a new string list for tab completion + if (args.length == 1) { // reload, toggledebug, playerheads, customtrader, headfix + autoCompletes.add("reload"); + autoCompletes.add("toggledebug"); + autoCompletes.add("update"); + autoCompletes.add("check"); + return autoCompletes; // then return the list + } + if(args[0].equalsIgnoreCase("check")) { + return null; + } + } + return null; + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args){ + if (command.getName().equalsIgnoreCase("SPS")){ + if (args.length == 0){ + sender.sendMessage(ChatColor.GREEN + "[]===============[" + ChatColor.YELLOW + "SinglePlayerSleep" + ChatColor.GREEN + "]===============[]"); + sender.sendMessage(ChatColor.YELLOW + " " + get("sps.message.touse"));//Sleep in a bed to use."); + sender.sendMessage(ChatColor.WHITE + " "); + sender.sendMessage(ChatColor.WHITE + " /Sleep - " + get("sps.message.sleephelp"));//subject to server admin approval"); + sender.sendMessage(ChatColor.WHITE + " /spscancel - " + get("sps.command.cancelhelp"));//Cancels SinglePlayerSleep"); + sender.sendMessage(ChatColor.WHITE + " "); + if(sender.isOp()||sender.hasPermission("sps.op")){ + sender.sendMessage(ChatColor.GOLD + " OP Commands"); + sender.sendMessage(ChatColor.GOLD + " /SPS Reload - " + get("sps.command.spsreload"));//Reload config file."); + sender.sendMessage(ChatColor.GOLD + " /SPS Toggledebug - " + get("sps.command.toggledebug"));//Check for update."); + sender.sendMessage(ChatColor.GOLD + " /SPS Update - " + get("sps.command.spsupdate"));//Check for update."); + //sender.sendMessage(ChatColor.GOLD + " /SPS check true/false - " + get("spscheck"));//set auto-update-check to true or false."); + } + sender.sendMessage(ChatColor.GOLD + " /SPS Check - Check your Permissions."); + sender.sendMessage(ChatColor.GREEN + "[]===============[" + ChatColor.YELLOW + "SinglePlayerSleep" + ChatColor.GREEN + "]===============[]"); + return true; + } + + if(args[0].equalsIgnoreCase("check")){ + // /sps check + // /sps check @p + // /cmd 0 1 + if(args.length == 1){ + String damsg = "sps.hermits=" + sender.hasPermission("sps.hermits") + ", " + "sps.cancel=" + sender.hasPermission("sps.cancel") + ", " + + "sps.unrestricted=" + sender.hasPermission("sps.unrestricted") + ", " + "sps.downfall=" + sender.hasPermission("sps.downfall") + ", " + + "sps.thunder=" + sender.hasPermission("sps.thunder") + ", " + "sps.command=" + sender.hasPermission("sps.command") + ", " + + "sps.update=" + sender.hasPermission("sps.update") + ", " + "sps.op=" + sender.hasPermission("sps.op") + ", " + + "sps.showUpdateAvailable=" + sender.hasPermission("sps.showUpdateAvailable") + ", " + + "sps.dayskipper=" + sender.hasPermission("sps.dayskipper") + ", " + "sps.dayskipcommand=" + sender.hasPermission("sps.dayskipcommand") ; + sender.sendMessage(damsg.replace("=true,", "=" + ChatColor.GREEN + "true" + ChatColor.RESET + ",").replace("=false,", "=" + ChatColor.RED + "false" + ChatColor.RESET + ",")); + return true; + }else if(args.length > 1){ + if(!(sender instanceof Player)||sender.hasPermission("sps.op")) { + try { + Player player = Bukkit.getPlayer(args[1]); + String damsg = "Player \"" + player.getName() + "\" has the following permissions: sps.hermits=" + player.hasPermission("sps.hermits") + ", " + "sps.cancel=" + player.hasPermission("sps.cancel") + ", " + + "sps.unrestricted=" + player.hasPermission("sps.unrestricted") + ", " + "sps.downfall=" + player.hasPermission("sps.downfall") + ", " + + "sps.thunder=" + player.hasPermission("sps.thunder") + ", " + "sps.command=" + player.hasPermission("sps.command") + ", " + + "sps.update=" + player.hasPermission("sps.update") + ", " + "sps.op=" + player.hasPermission("sps.op") + ", " + + "sps.showUpdateAvailable=" + player.hasPermission("sps.showUpdateAvailable") + ", " + + "sps.dayskipper=" + player.hasPermission("sps.dayskipper") + ", " + "sps.dayskipcommand=" + player.hasPermission("sps.dayskipcommand") ; + sender.sendMessage(damsg.replace("=true,", "=" + ChatColor.GREEN + "true" + ChatColor.RESET + ",").replace("=false,", "=" + ChatColor.RED + "false" + ChatColor.RESET + ",")); + return true; + }catch(Exception e) { + sender.sendMessage("Error Player Not found"); + e.printStackTrace(); + return false; + } + }else { + sender.sendMessage(ChatColor.YELLOW + THIS_NAME + ChatColor.RED + " " + get("sps.message.noperm")); + return false; + } + } + } + + if(args[0].equalsIgnoreCase("toggledebug")||args[0].equalsIgnoreCase("td")){ + if(sender.isOp()||sender.hasPermission("sps.op")||!(sender instanceof Player)){ + debug = !debug; + sender.sendMessage(ChatColor.YELLOW + THIS_NAME + ChatColor.RED + " " + get("sps.message.debugtrue").toString().replace("", get("sps.message.boolean." + debug) )); + return true; + }else if(!sender.hasPermission("sps.op")){ + sender.sendMessage(ChatColor.YELLOW + THIS_NAME + ChatColor.RED + " " + get("sps.message.noperm")); + return false; + } + } + if(args[0].equalsIgnoreCase("reload")){ // TODO: Command Reload + if(sender.isOp()||sender.hasPermission("sps.op")||!(sender instanceof Player)||sender.hasPermission("sps.*")){ + //ConfigAPI.Reloadconfig(this, p); + config = new YmlConfiguration(); + try { + config.load(new File(getDataFolder(), "config.yml")); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + } + /**this.reloadConfig(); + SinglePlayerSleep plugin = this; + getServer().getPluginManager().disablePlugin(plugin); + getServer().getPluginManager().enablePlugin(plugin);//*/ + reloadConfig(); + blacklist_sleep = config.getString("blacklist.sleep", ""); + blacklist_dayskip = config.getString("blacklist.dayskip", ""); + colorful_console = getConfig().getBoolean("colorful_console", true); + lang = new YamlConfiguration(); + try { + lang.load(langFile); + } catch (IOException | InvalidConfigurationException e1) { + e1.printStackTrace(); + } + sender.sendMessage(ChatColor.YELLOW + THIS_NAME + ChatColor.RED + " " + get("sps.message.reloaded")); + }else if(!sender.hasPermission("sps.op")){ + sender.sendMessage(ChatColor.YELLOW + THIS_NAME + ChatColor.RED + " " + get("sps.message.noperm")); + } + } + if(args[0].equalsIgnoreCase("update")){ // TODO: Command update + if(!(sender instanceof Player)) { + /** Console */ + try { + Bukkit.getConsoleSender().sendMessage("Checking for updates..."); + VersionChecker updater = new VersionChecker(this, projectID, githubURL); + if(updater.checkForUpdates()) { + /** Update available */ + UpdateAvailable = true; // TODO: Update Checker + UColdVers = updater.oldVersion(); + UCnewVers = updater.newVersion(); + + log("*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*"); + log("* " + get("sps.version.message").toString().replace("", THIS_NAME) ); + log("* " + get("sps.version.old_vers") + ChatColor.RED + UColdVers ); + log("* " + get("sps.version.new_vers") + ChatColor.GREEN + UCnewVers ); + log("*"); + log("* " + get("sps.version.please_update") ); + log("*"); + log("* " + get("sps.version.download") + ": " + DownloadLink + "/history"); + log("* " + get("sps.version.donate.message") + ": https://ko-fi.com/joelgodofwar"); + log("*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*"); + //Bukkit.getConsoleSender().sendMessage(newVerMsg.replace("{oVer}", UColdVers).replace("{nVer}", UCnewVers)); + //Bukkit.getConsoleSender().sendMessage(Ansi.GREEN + UpdateChecker.getResourceUrl() + Ansi.RESET); + }else{ + /** Up to date */ + UpdateAvailable = false; + log("*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*"); + log("* " + ChatColor.YELLOW + THIS_NAME + ChatColor.RESET + " " + get("sps.version.curvers") + ChatColor.RESET ); + log("* " + get("sps.version.donate.message") + ": https://ko-fi.com/joelgodofwar"); + log("*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*"); + } + }catch(Exception e) { + /** Error */ + Bukkit.getConsoleSender().sendMessage(ChatColor.RED + get("sps.version.update.error")); + e.printStackTrace(); + } + /** end update checker */ + return true; + } + if((sender.isOp()||sender.hasPermission("sps.op")||sender.hasPermission("sps.showUpdateAvailable"))){ + BukkitTask updateTask = this.getServer().getScheduler().runTaskAsynchronously(this, new Runnable() { + public void run() { + try { + Bukkit.getConsoleSender().sendMessage("Checking for updates..."); + VersionChecker updater = new VersionChecker(THIS_VERSION, projectID, githubURL); + if(updater.checkForUpdates()) { + UpdateAvailable = true; + UColdVers = updater.oldVersion(); + UCnewVers = updater.newVersion(); + String links = "[\"\",{\"text\":\"\",\"bold\":true,\"color\":\"gold\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"/history\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":\"\"}},{\"text\":\" \",\"hoverEvent\":{\"action\":\"show_text\",\"contents\":\"\"}},{\"text\":\"| \"},{\"text\":\"\",\"bold\":true,\"color\":\"gold\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"https://ko-fi.com/joelgodofwar\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":\"\"}},{\"text\":\" | \"},{\"text\":\"\",\"bold\":true,\"color\":\"gold\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"/updates\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":\".\"}}]"; + links = links.replace("", DownloadLink).replace("", get("sps.version.download")) + .replace("", get("sps.version.donate")).replace("", get("sps.version.please_update")) + .replace("", get("sps.version.donate.message")).replace("", get("sps.version.notes")) + .replace("", get("sps.version.notes.message")); + String versions = "" + ChatColor.GRAY + get("sps.version.new_vers") + ": " + ChatColor.GREEN + "{nVers} | " + get("sps.version.old_vers") + ": " + ChatColor.RED + "{oVers}"; + sender.sendMessage("" + ChatColor.GRAY + get("sps.version.message").toString().replace("", ChatColor.GOLD + THIS_NAME + ChatColor.GRAY) ); + Utils.sendJson(sender, links); + sender.sendMessage(versions.replace("{nVers}", UCnewVers).replace("{oVers}", UColdVers)); + }else{ + String links = "{\"text\":\"\",\"bold\":true,\"color\":\"gold\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"https://ko-fi.com/joelgodofwar\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":\"\"}}"; + links = links.replace("", get("sps.version.donate")).replace("", get("sps.version.donate.message")); + Utils.sendJson(sender, links); + sender.sendMessage(ChatColor.YELLOW + THIS_NAME + ChatColor.RED + " v" + THIS_VERSION + ChatColor.RESET + " " + get("sps.version.curvers") + ChatColor.RESET); + UpdateAvailable = false; + } + }catch(Exception e) { + sender.sendMessage(ChatColor.RED + get("sps.version.update.error")); + e.printStackTrace(); + } + } + }); + return true; + }else{ + sender.sendMessage(ChatColor.YELLOW + THIS_NAME + " " + get("sps.message.notop")); + return false; + } + } + } + + if(command.getName().equalsIgnoreCase("spsbloodmoon")){ + if (sender instanceof ConsoleCommandSender) { + isBloodMoon = !isBloodMoon; + if(debug){logDebug("isBloodMoon=" + isBloodMoon);} + return true; + }else{ + sender.sendMessage("Console only command."); + return false; + } + } + + if(command.getName().equalsIgnoreCase("spscancel")){ //command.getName().equalsIgnoreCase("cancel") // TODO: Command spscancel + if(debug){logDebug("command Can command cancel selected");} + World world; + Player player; + List worlds = Bukkit.getWorlds(); + + if(sender.hasPermission("sps.cancel") || sender.hasPermission("sps.op")) { + if(sender.hasPermission("sps.cancel")){if(debug){logDebug("command Can " + sender.getName() + " has sps.cancel");}} + if(sender.hasPermission("sps.op")){if(debug){logDebug("command Can " + sender.getName() + " has sps.op");}} + if(sender instanceof Player){ + player = (Player) sender; + world = player.getWorld(); + + //Set default timer for when the player has never slept before + long timer = 0; + if(debug){logDebug("command Can... " + player.getName() + " is sleeping.");} + long time = System.currentTimeMillis() / 1000; + if(cancellimit.get(player.getUniqueId()) == null){ + if(debug){logDebug("null - player is not in cancellimit");} + // Check if player has sps.unrestricted + if (!player.hasPermission("sps.unrestricted")) { + // Set player's time in HashMap + cancellimit.put(player.getUniqueId(), time); + if(debug){logDebug("command Can " + player.getName() + " added to playersCancelled");} + } + }else{ + if(debug){logDebug("not null - player is in cancellimit");} + // Player is on the list. + timer = cancellimit.get(player.getUniqueId()); + if(debug){logDebug("time=" + time);} + if(debug){logDebug("timer=" + timer);} + if(debug){logDebug("time - timer=" + (time - timer));} + if(debug){logDebug("cancellimit=" + getConfig().getLong("cancellimit", 60));} + // if !time - timer > limit + if(!((time - timer) > getConfig().getLong("cancellimit", 60))){ + long length = getConfig().getLong("cancellimit", 60) - (time - timer) ; + String sleeplimit = "" + get("sps.message.sleeplimit").toString().replace("", "" + length); + player.sendMessage(ChatColor.YELLOW + sleeplimit); + if(debug){logDebug("command Can... cancellimit: " + sleeplimit);} + //player.sendMessage("You can not do that for " + length + " seconds"); + return false; + }else if((time - timer) > getConfig().getLong("cancellimit", 60)){ + if(debug){logDebug("time - timer > cancellimit");} + cancellimit.replace(player.getUniqueId(), time); + } + } + }else{ + world = Bukkit.getWorlds().get(0); + } + + /* Check if it's Day */ + if(IsDay(world)){ + if(debug){logDebug("command Can It is Day");} + if (!getConfig().getBoolean("unrestricteddayskipper")) { + if(debug){logDebug("command Can !unrestricted DaySkipper");} + if (Bukkit.getScheduler().isCurrentlyRunning((dayskipTask)) || Bukkit.getScheduler().isQueued((dayskipTask))) { + if(debug){logDebug("command Can DS runnable is scheduled");} + /** + long time = System.currentTimeMillis() / 1000; + //Set default timer + long timer = 0; + long pTimeCancel = 0; + if (playersCancelled.get(sender.getName()) != null) { + pTimeCancel = playersCancelled.get(sender.getName()); + if(debug){logDebug("command Can DS playerscancelled is not null");} + } + //check if player has already tried cancelling to prevent spam + if (getConfig().getInt("sleeplimit") > 0) { + timer = time - pTimeCancel; + if(debug){logDebug("command Can DS timer is: " + timer);} + } + //Tell the player why they can't sleep + if (timer < getConfig().getInt("sleeplimit")) { + String sleeplimit = "" + get("sps.message.sleeplimit").toString(); + sender.sendMessage(ChatColor.YELLOW + sleeplimit); + if(debug){logDebug("command Can DS tell player why they cant sleep");} + } else {/ */ + if(debug){logDebug("command Can DS sleeplimit not reached");} + //Set the time this player cancelled to prevent spam + //playersCancelled.put(sender.getName().toString(), time); + //if(debug){logDebug("command Can DS added to playersCancelled");} + //cancel the runnable task + Bukkit.getScheduler().cancelTask(dayskipTask); + if(debug){logDebug("command Can DS task cancelled");} + //Broadcast to Server + if(debug){logDebug("cancelbroadcast=" + getConfig().getBoolean("cancelbroadcast", false));} + if (!(getConfig().getBoolean("cancelbroadcast", false) == false)) { + if(debug){logDebug("command Can DS is it here?");} + String damsg = "[\"\",{\"text\":\"cancelmsg\"}]"; + //String playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + String msgcolor1 = ChatColorUtils.setColorsByName(getConfig().getString("sleepmsgcolor", "YELLOW")); + damsg = damsg.replace("cancelmsg", get("sps.message.dayskipcanceled").toString()); + /** nickname parser */ + String nickName = getNickname(sender); + String playercolor = ""; + if(!nickName.contains("§")){ + //logWarn("nickName ! contain SS"); + playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + }else{ + nickName = StrUtils.parseRGBNameColors(nickName); + } + /** end nickname parser */ + damsg = damsg.replace("", /**playercolor +*/ nickName + msgcolor1); + if(debug){logDebug("command Can DS damsg=" + damsg);} + + if(getConfig().getBoolean("broadcast_per_world", true)){ + sendJson(world, damsg, ""); + }else{ + sendJson(damsg, ""); + } + + //SendJsonMessages.SendAllJsonMessage(damsg, "", world); + if(debug){logDebug("command Can DS broadcast sent");} + }else if (getConfig().getBoolean("cancelbroadcast", false) == false){ + if(debug){logDebug("command Can DS broadcast = false");} + } + isCanceled = true; + return true; + //}// + } else { //tell player they can't cancel sleep + sender.sendMessage(ChatColor.YELLOW + "" + get("sps.message.nocancel")); + } + + } else { //unrestricted sleep is on tell the player + sender.sendMessage(ChatColor.YELLOW + "" + get("sps.message.cancelunrestricted")); + } + + }else { //it's not night tell player + //sender.sendMessage(ChatColor.YELLOW + "" + get("mustbeday")); + } + + //Check it's night + if (IsNight(world)||world.hasStorm()) { + if(debug){if(IsNight(worlds.get(0))){logDebug("command Can It is night");}} + if(debug){if(worlds.get(0).hasStorm()){logDebug("command Can it is storming");}} + //Bukkit.getServer().getWorld(""); + //Prevent cancelling if unrestricted sleep is enabled + if (!getConfig().getBoolean("unrestrictedsleep")) { + if(debug){logDebug("command Can !unrestricted sleep");} + + //Check if this is an unrestricted sleep or not + if (Bukkit.getScheduler().isCurrentlyRunning((transitionTask)) || Bukkit.getScheduler().isQueued((transitionTask))) { + if(debug){logDebug("command Can sleep runnable is scheduled");} + + + /** / + long time = System.currentTimeMillis() / 1000; + //Set default timer + long timer = 0; + long pTimeCancel = 0; + if (playersCancelled.get(sender.getName()) != null) { + pTimeCancel = playersCancelled.get(sender.getName()); + if(debug){logDebug("command Can playerscancelled is not null");} + } + //check if player has already tried cancelling to prevent spam + if (getConfig().getInt("sleeplimit") > 0) { + timer = time - pTimeCancel; + if(debug){logDebug("command Can timer is: " + timer);} + } + //Tell the player why they can't sleep + if (timer < getConfig().getInt("sleeplimit")) { + String sleeplimit = "" + get("sps.message.sleeplimit").toString(); + sender.sendMessage(ChatColor.YELLOW + sleeplimit); + if(debug){logDebug("command Can tell player why they cant sleep");} + } else {/ */ + if(debug){logDebug("command Can sleeplimit not reached");} + //Set the time this player cancelled to prevent spam + //playersCancelled.put(sender.getName().toString(), time); + + //cancel the runnable task + Bukkit.getScheduler().cancelTask(transitionTask); + isCanceled = false; + if(debug){logDebug("command Can task cancelled");} + //Broadcast to Server + + if (!(getConfig().getBoolean("cancelbroadcast", false) == false)) { + if(debug){logDebug("command Can is it here?");} + String damsg = "[\"\",{\"text\":\" canceled sleeping.\"}]"; + //String playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + String msgcolor1 = ChatColorUtils.setColorsByName(getConfig().getString("sleepmsgcolor", "YELLOW")); + damsg = damsg.replace(" canceled sleeping.", get("sps.message.canceledsleep").toString()); + /** nickname parser */ + String nickName = getNickname(sender); + String playercolor = ""; + if(!nickName.contains("§")){ + //logWarn("nickName ! contain SS"); + playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + }else{ + nickName = StrUtils.parseRGBNameColors(nickName); + } + /** end nickname parser */ + damsg = damsg.replace("", /**playercolor +*/ nickName + msgcolor1); + if(debug){logDebug("command Can damsg=" + damsg);} + + if(getConfig().getBoolean("broadcast_per_world", true)){ + sendJson(world, damsg, ""); + }else{ + sendJson(damsg, ""); + } + + //SendJsonMessages.SendAllJsonMessage(damsg, "", world); + if(debug){logDebug("command Can broadcast sent");} + }else if (getConfig().getBoolean("cancelbroadcast", false) == false){ + if(debug){logDebug("command Can broadcast = false");} + } + isCanceled = true; + // + double oldHealth; + GameMode oldGamemode; + Location location; + Location bedspawn; + + //Sleep canceled so kick players from beds. + for (Player p: Bukkit.getOnlinePlayers()){ + player = p;// ((CraftPlayer)p); + if(debug){logDebug("command Can cycling player " + player.getName());} + + //if(debug){logDebug("command Can cancel player=" + player.getDisplayName());} + + try { + bedspawn = player.getBedSpawnLocation(); + bedspawn = new Location(bedspawn.getWorld(), bedspawn.getBlockX(),bedspawn.getBlockY(),bedspawn.getBlockZ(),0,0); + if(debug){logDebug("command Can bedspawn=" + bedspawn);} + location = player.getLocation(); + location = new Location(location.getWorld(), location.getBlockX(),location.getBlockY(),location.getBlockZ(),0,0); + if(debug){logDebug("command Can location=" + location);} + boolean inbed = false; + + if (location.equals(bedspawn)){ + inbed = true; + } + else{ + if(bedspawn.distance(player.getLocation()) < 2){ + if(debug){logDebug("command Can distance < 2 - inbed=true");} + inbed = true; + } + location.add(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location1=" + location);} + inbed = true; + } + location.add(0, 0, 1); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=2" + location);} + inbed = true; + } + location.subtract(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=3" + location);} + inbed = true; + } + location.subtract(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=4" + location);} + inbed = true; + } + location.subtract(0, 0, 1); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=5" + location);} + inbed = true; + } + location.subtract(0, 0, 1); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=6" + location);} + inbed = true; + } + location.add(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=7" + location);} + inbed = true; + } + location.add(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location8=" + location);} + inbed = true; + } + location.add(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location9=" + location);} + inbed = true; + } + location.add(0, 0, 1); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=10" + location);} + inbed = true; + } + location.add(0, 0, 1); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=11" + location);} + inbed = true; + } + location.add(0, 0, 1); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=12" + location);} + inbed = true; + } + location.subtract(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=13" + location);} + inbed = true; + } + location.subtract(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=14" + location);} + inbed = true; + } + location.subtract(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=15" + location);} + inbed = true; + } + location.subtract(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=16" + location);} + inbed = true; + } + location.subtract(0, 0, 1); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=17" + location);} + inbed = true; + } + location.subtract(0, 0, 1); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=18" + location);} + inbed = true; + } + location.subtract(0, 0, 1); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=19" + location);} + inbed = true; + } + location.subtract(0, 0, 1); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=20" + location);} + inbed = true; + } + location.add(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=21" + location);} + inbed = true; + } + location.add(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location22=" + location);} + inbed = true; + } + location.add(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location=23" + location);} + inbed = true; + } + location.add(1, 0, 0); + if(location.equals(bedspawn)&&inbed != true){ + if(debug){logDebug("command Can location24=" + location);} + inbed = true; + } + + } + + if(inbed){ + oldGamemode = player.getGameMode(); + oldHealth = player.getHealth(); + if(debug){logDebug("command Can oldHEalth=" + oldHealth);} + if(debug){logDebug("command Can GameMode=" + oldGamemode.toString());} + if(oldGamemode != GameMode.SURVIVAL){ + player.setGameMode(GameMode.SURVIVAL); + if(debug){logDebug("command Can GameMode set to SURVIVAL");} + //log("survival"); + } + if(!(oldHealth <= 1)){ + player.damage(1);//.getHandle().a(true,DamageSource.CACTUS); + if(debug){logDebug("command Can damage=" + player.getHealth());} + player.setHealth(oldHealth); + //player.wakeup(true); + }else{ + player.setHealth(oldHealth + 1); + player.damage(1);//.getHandle().a(true,DamageSource.CACTUS); + if(debug){logDebug("command Can damage=" + player.getHealth());} + player.setHealth(oldHealth); + //player.wakeup(true); + } + player.setGameMode(oldGamemode); + if(debug){logDebug("command Can GameMode set to " + oldGamemode.toString());} + //if(player.isSleeping()){ + //player.wakeup(true); + //} + } + }catch (Exception e){ + if(debug){logWarn("[Exception] " + player.getDisplayName() + " has never slept before.");} + // Failed to submit the stats + } + + } + if(isCanceled){ + if(debug){logDebug("command Can... isCanceled set to false");} + isCanceled = false; + } + return true; + //}// + + } else { //tell player they can't cancel sleep + sender.sendMessage(ChatColor.YELLOW + "" + get("sps.message.nocancel")); + if(debug){logDebug("command Can sleep runnable is NOT scheduled");} + } + + } else { //unrestricted sleep is on tell the player + sender.sendMessage(ChatColor.YELLOW + "" + get("sps.message.cancelunrestricted")); + } + + }else { //it's not night tell player + if(getConfig().getBoolean("notifymustbenight")){ + sender.sendMessage(ChatColor.YELLOW + "" + get("sps.message.mustbenight")); + } + } + }else { //Player doesn't have permission so let's tell them + sender.sendMessage(ChatColor.RED + "" + get("sps.message.noperm")); + } + if(isCanceled){ + isCanceled = false; + } + } + if(command.getName().equalsIgnoreCase("sleep")){ // TODO: Command Sleep + //Player player = (Player) sender; + List worlds = Bukkit.getWorlds(); + //World w = ((Entity) sender).getWorld(); + + if(sender.hasPermission("sps.command")||sender.hasPermission("sps.op")) { + if(sender instanceof Player){ + if(!sender.hasPermission("sps.op")){ + Player player = (Player) sender; + if(blacklist_sleep != null&&!blacklist_sleep.isEmpty()){ + if(StrUtils.stringContains(blacklist_sleep, player.getWorld().getName().toString())){ + log("EDE - World - On blacklist."); + return false; + } + } + } + } + //final Player player1 = (Player) sender; + final CommandSender daSender = sender; + World world; + Player player; + if(sender instanceof Player){ + player = (Player) sender; + world = player.getWorld(); + if(!IsNight(world) && !world.hasStorm()){ + sender.sendMessage(ChatColorUtils.setColors("" + get("sps.message.nightorstorm"))); + return false; + } + //Set default timer for when the player has never slept before + long timer = 0; + if(debug){logDebug("SC " + player.getName() + " is sleeping.");} + long time = System.currentTimeMillis() / 1000; + if(sleeplimit.get(player.getUniqueId()) == null){ + if(debug){logDebug("SC null - player not in sleeplimit");} + // Check if player has sps.unrestricted + if (!player.hasPermission("sps.unrestricted")) { + // Set player's time in HashMap + sleeplimit.put(player.getUniqueId(), time); + if(debug){logDebug("SC " + player.getName() + " added to playersSlept");} + } + }else{ + if(debug){logDebug("SC not null - player in sleeplimit");} + // Player is on the list. + timer = sleeplimit.get(player.getUniqueId()); + if(debug){logDebug("SC time=" + time);} + if(debug){logDebug("SC timer=" + timer);} + if(debug){logDebug("SC time - timer=" + (time - timer));} + if(debug){logDebug("SC sleeplimit=" + getConfig().getLong("sleeplimit", 60));} + // if !time - timer > limit + if(!((time - timer) > getConfig().getLong("sleeplimit", 60))){ + long length = getConfig().getLong("sleeplimit", 60) - (time - timer) ; + String sleeplimit = "" + get("sps.message.sleeplimit").toString().replace("", "" + length); + player.sendMessage(ChatColor.YELLOW + sleeplimit); + if(debug){logDebug("SC sleeplimit: " + sleeplimit);} + //player.sendMessage("You can not do that for " + length + " seconds"); + + return false; + }else if((time - timer) > getConfig().getLong("sleeplimit", 60)){ + if(debug){logDebug("SC time - timer > sleeplimit");} + sleeplimit.replace(player.getUniqueId(), time); + } + } + if(!isBloodmoonInprogress(player.getWorld())){//isBloodmoonInprogress(player.getWorld())//isBloodMoon + if(debug){logDebug("SC isbloodmoon=false");} + }else{ + player.sendMessage(ChatColor.YELLOW + "SPS: " + ChatColor.RESET + get("sps.message.bloodmoon", "You can not sleep during a bloodmoon.").toString()); + return false; + } + }else{ + world = Bukkit.getWorlds().get(0); + if(!IsNight(world) && !world.hasStorm()){ + sender.sendMessage(ChatColorUtils.setColors("" + get("sps.message.nightorstorm"))); + return false; + } + } + + //Broadcast to Server + String sleepmsg; + if (getConfig().getBoolean("randomsleepmsgs")){ + int maxmsgs = getConfig().getInt("numberofsleepmsgs"); + int randomnumber = RandomNumber(maxmsgs); + sleepmsg = getConfig().getString("sleepmsg" + randomnumber, ChatColor.WHITE + " is sleeping"); + sleepmsg = sleepmsg.replace("", ":"); + }else{ + sleepmsg = getConfig().getString(ChatColor.WHITE + " is sleeping"); + } + if(is116){ + sleepmsg = ChatColorUtils.setNametoRGB(sleepmsg); + sleepmsg = StrUtils.parseRGBNameColors(sleepmsg); + }else{ + sleepmsg = StrUtils.stripRGBColors(sleepmsg);// strip RGBHEX TODO: stripRGBColors + sleepmsg = ChatColorUtils.setColors(sleepmsg);// SetColorsByName + } + String msgcolor = ChatColorUtils.setColorsByName(getConfig().getString("sleepmsgcolor", "YELLOW")); + //String dastring = "" + get("sleepcommand"); + //dastring = dastring.replace("", ""); + //String damsg = "[\"\",{\"text\":\"player\"},{\"text\":\" is sleeping [\"},{\"text\":\"dacancel\",\"color\":\"red\",\"bold\":true,\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/cancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[{\"text\":\"tooltip\"}]}}},{\"text\":\"]\",\"color\":\"none\",\"bold\":false}]"; + String CancelBracketColor = ChatColorUtils.setColorsByName(getConfig().getString("cancelbracketcolor", "YELLOW")); + String canmsg = CancelBracketColor + "[\"},{\"text\":\"dacancel\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/spscancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"tooltip\"}},{\"text\":\"" + CancelBracketColor + "]\"}"; + String damsg = "[\"\",{\"text\":\"sleepmsg " + canmsg + "]"; + String msgcolor1 = ChatColorUtils.setColorsByName(getConfig().getString("sleepmsgcolor", "YELLOW")); + damsg = damsg.replace("sleepmsg", sleepmsg); + damsg = ChatColorUtils.setColors(damsg); + + //String playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + /** nickname parser */ + String nickName = getNickname(sender); + String playercolor = ""; + if(!nickName.contains("§")){ + //logWarn("nickName ! contain SS"); + playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + }else{ + nickName = StrUtils.parseRGBNameColors(nickName); + } + /** end nickname parser */ + damsg = damsg.replace("", /**playercolor +*/ nickName); + String cancelcolor = ChatColorUtils.setColorsByName(getConfig().getString("cancelcolor")); + damsg = damsg.replace("dacancel", cancelcolor + get("sps.message.cancel") + msgcolor1); + damsg = damsg.replace("tooltip", "" + get("sps.message.clickcancel")).replace("\"]\"", "\"" + msgcolor + "]\""); + + if(getConfig().getBoolean("broadcast_per_world", true)){ + sendJson(world, damsg, canmsg); + }else{ + sendJson(damsg, canmsg); + } + + boolean worldhasstorm = world.hasStorm(); + //SendJsonMessages.SendAllJsonMessage(damsg, "", world); + if(sender.hasPermission("sps.hermits")||sender.hasPermission("sps.*")){ + //Thread.sleep(10000); + + if(!isCanceled){ + int sleepdelay = getConfig().getInt("sleepdelay", 10); + transitionTask = this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + + public void run() { + //getLogger().info("runnable"); + //setDatime(sender, world); + if(world.hasStorm()){ + if(daSender.hasPermission("sps.downfall")||daSender.hasPermission("sps.op")||daSender.hasPermission("sps.*")){ + world.setStorm(false); + if(debug){logDebug("" + get("sps.message.setdownfall") + "...");} + } + } + if(world.isThundering()){ + if(daSender.hasPermission("sps.thunder")||daSender.hasPermission("sps.op")||daSender.hasPermission("sps.*")){ + world.setThundering(false); + if(debug){logDebug("" + get("sps.message.setthunder") + "...");} + } + } + long Relative_Time = 24000 - world.getTime(); + world.setFullTime(world.getFullTime() + Relative_Time); + if(debug){logDebug("" + get("sps.message.settime") + "...");} + resetPlayersRestStat(world); + } + + }, sleepdelay * 20); + + }else{ + + isCanceled = false; + } + //player.sendMessage(ChatColor.RED + "isCanceled=" + isCanceled); + }else{ + sender.sendMessage(ChatColor.RED + "" + get("sps.message.noperm")); + } + }else{ + sender.sendMessage(ChatColor.RED + "" + get("sps.message.noperm")); + } + } + if(command.getName().equalsIgnoreCase("dayskip")){ // TODO: Command DaySkip + if(getConfig().getBoolean("enabledayskipper", false)){ + World world; + if(sender instanceof Player){ + Player player = (Player) sender; + world = player.getWorld(); + if(!sender.hasPermission("sps.op")){ // TODO: DaySkip Command Blacklist Check + if(blacklist_dayskip != null&&!blacklist_dayskip.isEmpty()){ + if(StrUtils.stringContains(blacklist_dayskip, world.getName().toString())){ + log("EDE - World - On blacklist."); + return false; + } + } + } + }else{ + world = Bukkit.getWorlds().get(0); + } + List worlds = Bukkit.getWorlds(); + //World w = ((Entity) sender).getWorld(); + if(!IsDay(worlds.get(0))){ + sender.sendMessage(ChatColorUtils.setColors("" + get("sps.message.mustbeday"))); + return false; + } + if(sender.hasPermission("sps.dayskipcommand")||sender.hasPermission("sps.op")){ + if(debug){logDebug(" DS Has perm or is op. ...");} + String CancelBracketColor = ChatColorUtils.setColorsByName(getConfig().getString("cancelbracketcolor", "YELLOW")); + /* OK they have the perm, now lets notify the server and schedule the runnable */ + String damsg = "[\"\",{\"text\":\"sleepmsg " + CancelBracketColor + "[\"},{\"text\":\"dacancel\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/spscancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"tooltip\"}},{\"text\":\"" + CancelBracketColor + "]\"}]"; + String msgcolor = ChatColorUtils.setColorsByName(getConfig().getString("sleepmsgcolor", "YELLOW")); + if(debug){logDebug(" DS ... msgcolor=" + msgcolor);} + String sleepmsg = "" + get("sps.message.dayskipmsgcommand"," wants to sleep the day away..."); + if(is116){ + sleepmsg = ChatColorUtils.setNametoRGB(sleepmsg); + sleepmsg = StrUtils.parseRGBNameColors(sleepmsg); + }else{ + sleepmsg = StrUtils.stripRGBColors(sleepmsg);// strip RGBHEX TODO: stripRGBColors + sleepmsg = ChatColorUtils.setColors(sleepmsg);// SetColorsByName + } + damsg = damsg.replace("sleepmsg", sleepmsg); + //damsg = ChatColorUtils.setColors(damsg); + + //String playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + /** nickname parser */ + String nickName = getNickname(sender); + String playercolor = ""; + if(!nickName.contains("§")){ + //logWarn("nickName ! contain SS"); + playercolor = ChatColorUtils.setColorsByName(getConfig().getString("playernamecolor")); + }else{ + nickName = StrUtils.parseRGBNameColors(nickName); + } + /** end nickname parser */ + if(debug){logDebug(" DS ... playercolor=" + playercolor);} + damsg = damsg.replace("", /**playercolor +*/ nickName); + String cancelcolor = ChatColorUtils.setColorsByName(getConfig().getString("cancelcolor")); + if(debug){logDebug(" DS ... cancelcolor=" + cancelcolor);} + damsg = damsg.replace("dacancel", cancelcolor + get("sps.message.dayskipcancel")); + //change cancel color based on config + damsg = damsg.replace("tooltip", "" + get("sps.message.dayskipclickcancel")).replace("\"]\"", "\"" + msgcolor + "]\""); + if(debug){logDebug(" DS string processed. ...");} + + if(getConfig().getBoolean("broadcast_per_world", true)){ + sendJson(world, damsg, ""); + }else{ + sendJson(damsg, ""); + } + + //SendJsonMessages.SendAllJsonMessage(damsg, "", world); + if(debug){logDebug(" DS SendAllJsonMessage. ...");} + if(!isDSCanceled){ + //final World world = worlds.get(0); + int dayskipdelay = getConfig().getInt("dayskipdelay", 10); + if(debug){logDebug(" DS !isDSCanceled. ...");} + dayskipTask = this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + + public void run() { + int timeoffset = 10000; + long Relative_Time = (24000 - world.getTime()) - timeoffset; + world.setFullTime(world.getFullTime() + Relative_Time); + if(debug){logDebug("" + get("sps.message.dayskipsettime") + "...");} + } + + }, dayskipdelay * 20); + + }else{ + + isDSCanceled = false; + } + } + } + } + + if (command.getName().equalsIgnoreCase("clearrain")){ // TODO: Command ClearRain + if(config.getBoolean("clearrain_enabled", false)){ + if(sender instanceof Player){ + Player player = (Player) sender; + World world = player.getWorld(); + if (!IsNight(player.getWorld())&&player.getWorld().hasStorm()) { + world.setStorm(false); + player.sendMessage("Rain stopped."); + }else{ + sender.sendMessage("Must not be Night, and a rainstorm must be present"); + } + }else{ + sender.sendMessage("Must be a player to use this command."); + } + }else{ + sender.sendMessage("clearrain is not enabled."); + } + } + + return true; + } + + public void log(String dalog){// TODO: Log + SinglePlayerSleep.logger.info(Ansi.YELLOW + pluginName + " v" + THIS_VERSION + Ansi.RESET + " " + dalog); + } + public void logDebug(String dalog){ + log(Ansi.RED + " [DEBUG] " + Ansi.RESET + dalog); + } + public void logWarn(String dalog){ + SinglePlayerSleep.logger.warning(dalog); + } + public void broadcast(String message, World world){ + String damsg = "{\"text\":\"broadcastString\"}"; + String msgcolor1 = ChatColorUtils.setColorsByName(getConfig().getString("sleepmsgcolor", "YELLOW")); + damsg = damsg.replace("broadcastString", message); + sendJson(world, damsg, ""); + //SendJsonMessages.SendAllJsonMessage(damsg, "", world); + + //getServer().broadcastMessage("" + message); + } + + @EventHandler + public void onPlayerJoinEvent(PlayerJoinEvent event) // TODO: OnPlayerJoin + { + Player player = event.getPlayer(); + //if(p.isOp() && UpdateCheck||p.hasPermission("sps.showUpdateAvailable")){ + /** Notify Ops */ + if(UpdateAvailable&&(player.isOp()||player.hasPermission("sps.showUpdateAvailable"))){ + String links = "[\"\",{\"text\":\"\",\"bold\":true,\"color\":\"gold\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"/history\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":\"\"}},{\"text\":\" \",\"hoverEvent\":{\"action\":\"show_text\",\"contents\":\"\"}},{\"text\":\"| \"},{\"text\":\"\",\"bold\":true,\"color\":\"gold\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"https://ko-fi.com/joelgodofwar\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":\"\"}},{\"text\":\" | \"},{\"text\":\"\",\"bold\":true,\"color\":\"gold\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"/updates\"},\"hoverEvent\":{\"action\":\"show_text\",\"contents\":\"\"}}]"; + links = links.replace("", DownloadLink).replace("", get("sps.version.download")) + .replace("", get("sps.version.donate")).replace("", get("sps.version.please_update")) + .replace("", get("sps.version.donate.message")).replace("", get("sps.version.notes")) + .replace("", get("sps.version.notes.message")); + String versions = "" + ChatColor.GRAY + get("sps.version.new_vers") + ": " + ChatColor.GREEN + "{nVers} | " + get("sps.version.old_vers") + ": " + ChatColor.RED + "{oVers}"; + player.sendMessage("" + ChatColor.GRAY + get("sps.version.message").toString().replace("", ChatColor.GOLD + THIS_NAME + ChatColor.GRAY) ); + Utils.sendJson(player, links); + player.sendMessage(versions.replace("{nVers}", UCnewVers).replace("{oVers}", UColdVers)); + //p.sendMessage(ChatColor.YELLOW + this.getName() + ChatColor.RED + " v" + UColdVers + ChatColor.RESET + " " + get("newvers") + ChatColor.GREEN + " v" + UCnewVers + ChatColor.RESET + "\n" + ChatColor.GREEN + UpdateChecker.getResourceUrl() + ChatColor.RESET); + } + + DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd"); + LocalDate localDate = LocalDate.now(); + String daDay = dtf.format(localDate); + + if (daDay.equals("04/16")) { + String playerId = player.getUniqueId().toString(); + if (!triggeredPlayers.contains(playerId)) { + if (isPluginRequired(THIS_NAME)) { + player.sendTitle("Happy Birthday Mom", "I miss you - 4/16/1954-12/23/2022", 10, 70, 20); + } + triggeredPlayers.add(playerId); + } + } + + if(player.getName().equals("JoelYahwehOfWar")||player.getName().equals("JoelGodOfWar")){ + player.sendMessage(THIS_NAME + " " + THIS_VERSION + " Hello father!"); + //p.sendMessage("seed=" + p.getWorld().getSeed()); + } + } + + + public static boolean IsNight(World w){ + long time = (w.getFullTime()) % 24000; + return time >= mobSpawningStartTime && time < mobSpawningStopTime; + } + + public static boolean IsDay(World w){ + long time = (w.getFullTime()) % 24000; + return time > 0 && time < 12300; + //return time >= mobSpawningStartTime && time < mobSpawningStopTime; + } + + public int RandomNumber(int maxnum){ + Random rand = new Random(); + int min = 1; + int max = maxnum; + // nextInt as provided by Random is exclusive of the top value so you need to add 1 + int randomNum = rand.nextInt((max - min) + 1) + min; + return randomNum; + } + + public boolean fileContains(String filePath, String searchQuery) throws IOException{ + searchQuery = searchQuery.trim(); + BufferedReader br = null; + + try{ + br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath))); + String line; + while ((line = br.readLine()) != null){ + if (line.contains(searchQuery)){ + //log("findstring found"); + return true; + }else{ + } + } + } + finally{ + try{ + if (br != null) + br.close(); + } + catch (Exception e){ + System.err.println("Exception while closing bufferedreader " + e.toString()); + } + } + //log("findstring failed"); + return false; + } + public String addChar(String str, String ch, int position) { + StringBuilder sb = new StringBuilder(str); + sb.insert(position, ch); + return sb.toString(); + } + public int myPlugins(){ + //Plugin[] daPlugins = getServer().getPluginManager().getPlugins(); + int dacount = 1; + if(getServer().getPluginManager().getPlugin("DragonDropElytra") != null){dacount++;} + if(getServer().getPluginManager().getPlugin("NoEndermanGrief") != null){dacount++;} + if(getServer().getPluginManager().getPlugin("PortalHelper") != null){dacount++;} + return dacount; + } + + public static void copyFile_Java7(String origin, String destination) throws IOException { + Path FROM = Paths.get(origin); + Path TO = Paths.get(destination); + //overwrite the destination file if it exists, and copy + // the file attributes, including the rwx permissions + CopyOption[] options = new CopyOption[]{ + StandardCopyOption.REPLACE_EXISTING, + StandardCopyOption.COPY_ATTRIBUTES + }; + Files.copy(FROM, TO, options); + } + + public boolean isBloodmoonInprogress(World world){ + if(getServer().getPluginManager().getPlugin("BloodMoon") != null){ + BloodmoonActuator getactuator = BloodmoonActuator.GetActuator(world); + if(getactuator != null){ + return getactuator.isInProgress(); + }else{return false;} + } + if(getServer().getPluginManager().getPlugin("bloodmoon-advanced") != null){ + return BloodmoonAPI.bloodmoonIsRunning(world); + } + return false; + } + + @SuppressWarnings("deprecation") + public String getNickname(Player player){ + String playerName = null; + if(getConfig().getBoolean("nickname.usedisplayname", false)) { + playerName = ChatColorUtils.setColorsByCode(player.getDisplayName()); + }else if(!getConfig().getBoolean("nickname.usedisplayname", false)) { + playerName = player.getName(); + } + if(debug){logDebug("player.getDisplayName()=" + player.getDisplayName());} + if(debug){logDebug("player.getName()=" + player.getName());} + if(debug){logDebug("nickname.usedisplayname=" + getConfig().getBoolean("nickname.usedisplayname"));} + if(getServer().getPluginManager().getPlugin("VentureChat") != null){ + MineverseChatPlayer mcp = MineverseChatAPI.getMineverseChatPlayer(player); + String nick = mcp.getNickname(); + if(nick != null){ + if(debug){logDebug("mcp.getNickname()=" + mcp.getNickname());} + if(debug){logDebug("ChatColor.translateAlternateColorCodes('&', nick)=" + ChatColor.translateAlternateColorCodes('&', nick));} + //ChatColor.translateAlternateColorCodes('&', nick); + //nick = nick.replaceAll("§", "&"); + nick = ChatColorUtils.setColorsByCode(nick); + if(debug){logDebug("VentureChat Format.color(nick)=" + nick);} + return nick; + } + if(debug){logDebug("VentureChat Nick=null using " + playerName);} + return Format.color(playerName); + }else if(getServer().getPluginManager().getPlugin("Essentials") != null){ + Essentials ess = (Essentials) Bukkit.getServer().getPluginManager().getPlugin("Essentials"); + //User user = ess.getUserMap().getUser(player.getName()); + //if(debug){logDebug("Essnetials Nick=" + ess.getUserMap().getUser(player.getName()).getNickname());} + String nick = ess.getUserMap().getUser(player.getName()).getNickname(); + if(nick != null){ + if(debug){logDebug("Essentials Nick=" + nick);} + return ChatColor.translateAlternateColorCodes('&', nick); + } + if(debug){logDebug("Essentials Nick=null using: " + playerName );} + return ChatColorUtils.setColorsByCode(playerName); + }else if(getServer().getPluginManager().getPlugin("HexNicks") != null){ + String nick = GsonComponentSerializer.gson().serialize(Nicks.api().getNick(player)); + if(nick != null){ + if(debug){logDebug("HexNick Nick=" + nick);} + if(nick.contains("[")) nick = nick.substring(nick.indexOf("[") + 1); + if(nick.contains("]"))nick = nick.substring(0, nick.indexOf("]")); + return "\"}," + ChatColor.translateAlternateColorCodes('&', nick) + ",{\"text\": \""; + } + if(debug){logDebug("HexNick Nick=null using " + playerName);} + return ChatColorUtils.setColorsByCode(playerName); + }else{ + if(debug){logDebug("No nickname found using=" + playerName);} + return playerName; + } + } + + public String getNickname(CommandSender sender){ + if(sender instanceof Player){ + return getNickname((Player)sender); + }else{ + return "Console"; + } + } + + public void sendJson(String string, String OldString){ + String string2; + String string3 = OldString; + for (Player player: Bukkit.getOnlinePlayers()){ // for (Player player: Bukkit.getOnlinePlayers()){ + if(player.hasPermission("sps.cancel")&&displaycancel){ + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw \"" + player.getName() + + "\" " + string); + //player.spigot().sendMessage(string); + if(debug){logDebug("SAJM - string=" + string);} + if(debug){logDebug("SAJM - perm & display - Broadcast");} + }else{ + if(debug){logDebug("SAJM - string3.toString()=" + string3.toString());} + string2 = string.toString(); + if(debug){logDebug("SAJM - string2=" + string2);} + string2 = string2.substring(0, string2.lastIndexOf("[")) + "\"}]"; + if(debug){logDebug("SAJM - string2=" + string2);} + + String msgcolor = ChatColorUtils.setColorsByName(getConfig().getString("sleepmsgcolor", "YELLOW")); + String cancelcolor = ChatColorUtils.setColorsByName(getConfig().getString("cancelcolor")); + string2 = string2.replace(cancelcolor + get("sps.message.cancel") + msgcolor, ""); + if(debug){logDebug("SAJM - string2=" + string2);} + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw \"" + player.getName() + + "\" " + string2); /** Quatation marks around name for non alphanumeric player names. (Added by ImDaBigBoss) */ + if(debug){logDebug("SAJM - !perm & display - Broadcast");} + //player.sendRawMessage(string2); + //player.spigot().sendMessage(ComponentSerializer.parse(string2)); + } + } + } + + public void sendJson(World world, String string, String OldString){ + String string2; + String string3 = OldString; + for (Player player: world.getPlayers()){ // for (Player player: Bukkit.getOnlinePlayers()){ + if(player.hasPermission("sps.cancel")&&displaycancel){ + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw \"" + player.getName() + + "\" " + string); + //player.spigot().sendMessage(string); + if(debug){logDebug("SAJM - string=" + string);} + if(debug){logDebug("SAJM - perm & display - Broadcast");} + }else{ + if(debug){logDebug("SAJM - string3.toString()=" + string3.toString());} + string2 = string.toString(); + if(debug){logDebug("SAJM - string2=" + string2);} + string2 = string2.substring(0, string2.lastIndexOf("[")) + "\"}]"; + if(debug){logDebug("SAJM - string2=" + string2);} + + String msgcolor = ChatColorUtils.setColorsByName(getConfig().getString("sleepmsgcolor", "YELLOW")); + String cancelcolor = ChatColorUtils.setColorsByName(getConfig().getString("cancelcolor")); + string2 = string2.replace(cancelcolor + get("sps.message.cancel") + msgcolor, ""); + if(debug){logDebug("SAJM - string2=" + string2);} + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw \"" + player.getName() + + "\" " + string2); /** Quatation marks around name for non alphanumeric player names. (Added by ImDaBigBoss) */ + Bukkit.getServer().broadcastMessage(string3); + if(debug){logDebug("SAJM - !perm & display - Broadcast");} + //player.sendRawMessage(string2); + //player.spigot().sendMessage(ComponentSerializer.parse(string2)); + } + } + } + + public void resetPlayersRestStat(World world) { + if(getConfig().getBoolean("reset_insomnia", false)) { + List players = world.getPlayers(); + for(Player player: players) { + if(player.getStatistic(Statistic.TIME_SINCE_REST) > 0) { + player.setStatistic(Statistic.TIME_SINCE_REST, 0); + } + } + } + } + + public static String getVersion() { + String strVersion = Bukkit.getVersion(); + strVersion = strVersion.substring(strVersion.indexOf("MC: "), strVersion.length()); + strVersion = strVersion.replace("MC: ", "").replace(")", ""); + return strVersion; + } + + @EventHandler + public void PlayerIsSleeping(PlayerBedLeaveEvent event) throws InterruptedException{ + Player player = event.getPlayer(); + if( getConfig().getBoolean("exitbedcancel", false) ) { + Bukkit.dispatchCommand(player, "spscancel"); + } + } + + public String LoadTime(long startTime) { + long elapsedTime = System.currentTimeMillis() - startTime; + long minutes = TimeUnit.MILLISECONDS.toMinutes(elapsedTime); + long seconds = TimeUnit.MILLISECONDS.toSeconds(elapsedTime) % 60; + long milliseconds = elapsedTime % 1000; + + if (minutes > 0) { + return String.format("%d min %d s %d ms.", minutes, seconds, milliseconds); + } else if (seconds > 0) { + return String.format("%d s %d ms.", seconds, milliseconds); + } else { + return String.format("%d ms.", elapsedTime); + } + } + + @SuppressWarnings("static-access") + public String get(String key, String... defaultValue) { + return lang2.get(key, defaultValue); + } + + public boolean isPluginRequired(String pluginName) { + String[] requiredPlugins = {"SinglePlayerSleep", "MoreMobHeads", "NoEndermanGrief", "ShulkerRespawner", "DragonDropElytra", "RotationalWrench", "SilenceMobs", "VillagerWorkstationHighlights"}; + for (String requiredPlugin : requiredPlugins) { + if (getServer().getPluginManager().getPlugin(requiredPlugin) != null && getServer().getPluginManager().isPluginEnabled(requiredPlugin)) { + if (requiredPlugin.equals(pluginName)) { + return true; + } else { + return false; + } + } + } + return true; + } + +} diff --git a/src/com/github/joelgodofwar/sps/api/ChatColorUtils.java b/src/com/github/joelgodofwar/sps/api/ChatColorUtils.java new file mode 100644 index 0000000..0672f31 --- /dev/null +++ b/src/com/github/joelgodofwar/sps/api/ChatColorUtils.java @@ -0,0 +1,83 @@ +package com.github.joelgodofwar.sps.api; + +import org.bukkit.ChatColor; + +public class ChatColorUtils +{ + public static String setNametoRGB(String s){ + String prefix = "§x"; + return s.replace("", prefix + "000000").replace("", prefix + "0000AA") + .replace("", prefix + "00AA00").replace("", prefix + "00AAAA") + .replace("", prefix + "AA0000").replace("", prefix + "AA00AA") + .replace("", prefix + "FFAA00").replace("", prefix + "AAAAAA") + .replace("", prefix + "555555").replace("", prefix + "5555FF") + .replace("", prefix + "55FF55").replace("", prefix + "55FFFF") + .replace("", prefix + "FF5555").replace("", prefix + "FF55FF") + .replace("", prefix + "FFFF55").replace("", prefix + "FFFFFF"); + } + + public static String setColorsByCode(String s) + { + return s.replace("&0", "" + ChatColor.BLACK).replace("&1", "" + ChatColor.DARK_BLUE) + .replace("&2", "" + ChatColor.DARK_GREEN).replace("&3", "" + ChatColor.DARK_AQUA) + .replace("&4", "" + ChatColor.DARK_RED).replace("&5", "" + ChatColor.DARK_PURPLE) + .replace("&6", "" + ChatColor.GOLD).replace("&7", "" + ChatColor.GRAY) + .replace("&8", "" + ChatColor.DARK_GRAY).replace("&9", "" + ChatColor.BLUE) + .replace("&a", "" + ChatColor.GREEN).replace("&b", "" + ChatColor.AQUA) + .replace("&c", "" + ChatColor.RED).replace("&d", "" + ChatColor.LIGHT_PURPLE) + .replace("&e", "" + ChatColor.YELLOW).replace("&f", "" + ChatColor.WHITE) + .replace("&k", "" + ChatColor.MAGIC).replace("&l", "" + ChatColor.BOLD) + .replace("&m", "" + ChatColor.STRIKETHROUGH).replace("&n", "" + ChatColor.UNDERLINE) + .replace("&o", "" + ChatColor.ITALIC).replace("&r", "" + ChatColor.RESET) + .replace("&A", "" + ChatColor.GREEN).replace("&B", "" + ChatColor.AQUA) + .replace("&C", "" + ChatColor.RED).replace("&D", "" + ChatColor.LIGHT_PURPLE) + .replace("&E", "" + ChatColor.YELLOW).replace("&F", "" + ChatColor.WHITE) + .replace("&K", "" + ChatColor.MAGIC).replace("&L", "" + ChatColor.BOLD) + .replace("&M", "" + ChatColor.STRIKETHROUGH).replace("&N", "" + ChatColor.UNDERLINE) + .replace("&O", "" + ChatColor.ITALIC).replace("&R", "" + ChatColor.RESET); + } + public static String setColorsByName(String s){ + return s.replace("BLACK", "" + ChatColor.BLACK).replace("DARK_BLUE", "" + ChatColor.DARK_BLUE) + .replace("DARK_GREEN", "" + ChatColor.DARK_GREEN).replace("DARK_AQUA", "" + ChatColor.DARK_AQUA) + .replace("DARK_RED", "" + ChatColor.DARK_RED).replace("DARK_PURPLE", "" + ChatColor.DARK_PURPLE) + .replace("GOLD", "" + ChatColor.GOLD).replace("GRAY", "" + ChatColor.GRAY) + .replace("DARK_GRAY", "" + ChatColor.DARK_GRAY).replace("BLUE", "" + ChatColor.BLUE) + .replace("GREEN", "" + ChatColor.GREEN).replace("AQUA", "" + ChatColor.AQUA) + .replace("RED", "" + ChatColor.RED).replace("LIGHT_PURPLE", "" + ChatColor.LIGHT_PURPLE) + .replace("YELLOW", "" + ChatColor.YELLOW).replace("WHITE", "" + ChatColor.WHITE) + .replace("MAGIC", "" + ChatColor.MAGIC).replace("BOLD", "" + ChatColor.BOLD) + .replace("STRIKETHROUGH", "" + ChatColor.STRIKETHROUGH).replace("UNDERLINE", "" + ChatColor.UNDERLINE) + .replace("ITALIC", "" + ChatColor.ITALIC).replace("RESET", "" + ChatColor.RESET); + } + public static String setColors(String s) + { + return s.replace("&0", "" + ChatColor.BLACK).replace("&1", "" + ChatColor.DARK_BLUE) + .replace("&2", "" + ChatColor.DARK_GREEN).replace("&3", "" + ChatColor.DARK_AQUA) + .replace("&4", "" + ChatColor.DARK_RED).replace("&5", "" + ChatColor.DARK_PURPLE) + .replace("&6", "" + ChatColor.GOLD).replace("&7", "" + ChatColor.GRAY) + .replace("&8", "" + ChatColor.DARK_GRAY).replace("&9", "" + ChatColor.BLUE) + .replace("&a", "" + ChatColor.GREEN).replace("&b", "" + ChatColor.AQUA) + .replace("&c", "" + ChatColor.RED).replace("&d", "" + ChatColor.LIGHT_PURPLE) + .replace("&e", "" + ChatColor.YELLOW).replace("&f", "" + ChatColor.WHITE) + .replace("&k", "" + ChatColor.MAGIC).replace("&l", "" + ChatColor.BOLD) + .replace("&m", "" + ChatColor.STRIKETHROUGH).replace("&n", "" + ChatColor.UNDERLINE) + .replace("&o", "" + ChatColor.ITALIC).replace("&r", "" + ChatColor.RESET) + .replace("&A", "" + ChatColor.GREEN).replace("&B", "" + ChatColor.AQUA) + .replace("&C", "" + ChatColor.RED).replace("&D", "" + ChatColor.LIGHT_PURPLE) + .replace("&E", "" + ChatColor.YELLOW).replace("&F", "" + ChatColor.WHITE) + .replace("&K", "" + ChatColor.MAGIC).replace("&L", "" + ChatColor.BOLD) + .replace("&M", "" + ChatColor.STRIKETHROUGH).replace("&N", "" + ChatColor.UNDERLINE) + .replace("&O", "" + ChatColor.ITALIC).replace("&R", "" + ChatColor.RESET) + .replace("", "" + ChatColor.BLACK).replace("", "" + ChatColor.DARK_BLUE) + .replace("", "" + ChatColor.DARK_GREEN).replace("", "" + ChatColor.DARK_AQUA) + .replace("", "" + ChatColor.DARK_RED).replace("", "" + ChatColor.DARK_PURPLE) + .replace("", "" + ChatColor.GOLD).replace("", "" + ChatColor.GRAY) + .replace("", "" + ChatColor.DARK_GRAY).replace("", "" + ChatColor.BLUE) + .replace("", "" + ChatColor.GREEN).replace("", "" + ChatColor.AQUA) + .replace("", "" + ChatColor.RED).replace("", "" + ChatColor.LIGHT_PURPLE) + .replace("", "" + ChatColor.YELLOW).replace("", "" + ChatColor.WHITE) + .replace("", "" + ChatColor.MAGIC).replace("", "" + ChatColor.BOLD) + .replace("", "" + ChatColor.STRIKETHROUGH).replace("", "" + ChatColor.UNDERLINE) + .replace("", "" + ChatColor.ITALIC).replace("", "" + ChatColor.RESET); + } +} \ No newline at end of file diff --git a/src/com/github/joelgodofwar/sps/api/ConfigAPI.java b/src/com/github/joelgodofwar/sps/api/ConfigAPI.java new file mode 100644 index 0000000..ed756af --- /dev/null +++ b/src/com/github/joelgodofwar/sps/api/ConfigAPI.java @@ -0,0 +1,99 @@ +package com.github.joelgodofwar.sps.api; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +import org.bukkit.ChatColor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; + +import com.github.joelgodofwar.sps.SinglePlayerSleep; + +public class ConfigAPI { + + public static void CheckForConfig(Plugin plugin){ + try{ + PluginDescriptionFile pdfFile = plugin.getDescription(); + if(!plugin.getDataFolder().exists()){ + plugin.getLogger().info(pdfFile.getName() + ": Data Folder doesn't exist"); + plugin.getLogger().info(pdfFile.getName() + ": Creating Data Folder"); + plugin.getDataFolder().mkdirs(); + plugin.getLogger().info(pdfFile.getName() + ": Data Folder Created at " + plugin.getDataFolder()); + } + File file = new File(plugin.getDataFolder(), "config.yml"); + plugin.getLogger().info("" + file); + if(!file.exists()){ + plugin.getLogger().info(pdfFile.getName() + ": config.yml not found, creating!"); + //plugin.saveDefaultConfig(); + plugin.saveResource("config.yml", true); + //copy(plugin.getConfig().getCurrentPath(), file); + FileConfiguration config = plugin.getConfig(); + + config.options().copyDefaults(true); + //plugin.saveConfig(); + } + }catch(Exception e){ + e.printStackTrace(); + } + } + + public static void Reloadconfig(Plugin plugin, Player player){ + // Load config. + FileConfiguration config = plugin.getConfig(); + String daString = config.getString("debug").replace("'", "") + ","; + + if(daString.contains("true")){ + SinglePlayerSleep.debug = true; + if(SinglePlayerSleep.debug){logDebug("debug=true", plugin);} + }else{ + SinglePlayerSleep.debug = false; + //logDebug("debug=false", plugin); + } + String daString2 = config.getString("auto_update_check").replace("'", "") + ","; + if(daString2.contains("true")){ + SinglePlayerSleep.UpdateCheck = true; + }else{ + SinglePlayerSleep.UpdateCheck = false; + } + String daString3 = config.getString("cancelbroadcast").replace("'", "") + ","; + if(daString3.contains("true")){ + SinglePlayerSleep.cancelbroadcast = true; + }else{ + SinglePlayerSleep.cancelbroadcast = false; + } + String daString4 = config.getString("lang", "en_US").replace("'", ""); + SinglePlayerSleep.daLang = daString4; + if(SinglePlayerSleep.debug){log("UpdateCheck = " + SinglePlayerSleep.UpdateCheck, plugin);} //TODO: Logger + if(player != null){ + player.sendMessage(ChatColor.YELLOW + plugin.getName() + ChatColor.WHITE + " Configs Reloaded"); + } + } + public static void log(String dalog, Plugin plugin){ + SinglePlayerSleep.logger.info(plugin.getName() + " " + dalog); + } + public static void logDebug(String dalog, Plugin plugin){ + SinglePlayerSleep.logger.info("[DEBUG] " + plugin.getName() + " " + dalog); + } + /* + * this copy(); method copies the specified file from your jar + * to your /plugins// folder + */ + public static void copy(InputStream in, File file) { + try { + OutputStream out = new FileOutputStream(file); + byte[] buf = new byte[1024]; + int len; + while((len=in.read(buf))>0){ + out.write(buf,0,len); + } + out.close(); + in.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/com/github/joelgodofwar/sps/api/JsonMessages.java b/src/com/github/joelgodofwar/sps/api/JsonMessages.java new file mode 100644 index 0000000..f80265d --- /dev/null +++ b/src/com/github/joelgodofwar/sps/api/JsonMessages.java @@ -0,0 +1,34 @@ +package com.github.joelgodofwar.sps.api; + + +import net.minecraft.server.v1_16_R1.ChatMessageType; +import net.minecraft.server.v1_16_R1.IChatBaseComponent.ChatSerializer; +import net.minecraft.server.v1_16_R1.PacketPlayOutChat; + +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.v1_16_R1.entity.CraftPlayer; +import org.bukkit.entity.Player; + +//made by Gamecube762 +//Simple way to send Json Chat messages to players +//V1.0 + +public class JsonMessages { + + public static PacketPlayOutChat createPacketPlayOutChat(String s){return new PacketPlayOutChat(ChatSerializer.a(s), ChatMessageType.CHAT, null);} + + public static void SendJsonMessage(Player p, String s){( (CraftPlayer)p ).getHandle().playerConnection.sendPacket( createPacketPlayOutChat(s) );} + + public static void SendPlayerListJsonMessage(Player[] players, String s){ + PacketPlayOutChat a = createPacketPlayOutChat(s); + for (Player p: players) + ((CraftPlayer)p).getHandle().playerConnection.sendPacket(a); + } + + public static void SendAllJsonMessage(String s){ + PacketPlayOutChat a = createPacketPlayOutChat(s); + for (Player p: Bukkit.getOnlinePlayers()) + ((CraftPlayer)p).getHandle().playerConnection.sendPacket(a); + } + +} \ No newline at end of file diff --git a/src/com/github/joelgodofwar/sps/api/Metrics.java b/src/com/github/joelgodofwar/sps/api/Metrics.java new file mode 100644 index 0000000..fd181e4 --- /dev/null +++ b/src/com/github/joelgodofwar/sps/api/Metrics.java @@ -0,0 +1,848 @@ +package com.github.joelgodofwar.sps.api; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.stream.Collectors; +import java.util.zip.GZIPOutputStream; +import javax.net.ssl.HttpsURLConnection; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +public class Metrics { + + private final Plugin plugin; + + private final MetricsBase metricsBase; + + /** + * Creates a new Metrics instance. + * + * @param plugin Your plugin instance. + * @param serviceId The id of the service. It can be found at What is my plugin id? + */ + public Metrics(JavaPlugin plugin, int serviceId) { + this.plugin = plugin; + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (!config.isSet("serverUuid")) { + config.addDefault("enabled", true); + config.addDefault("serverUuid", UUID.randomUUID().toString()); + config.addDefault("logFailedRequests", false); + config.addDefault("logSentData", false); + config.addDefault("logResponseStatusText", false); + // Inform the server owners about bStats + config + .options() + .header( + "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" + + "many people use their plugin and their total player count. It's recommended to keep bStats\n" + + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" + + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" + + "anonymous.") + .copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + // Load the data + boolean enabled = config.getBoolean("enabled", true); + String serverUUID = config.getString("serverUuid"); + boolean logErrors = config.getBoolean("logFailedRequests", false); + boolean logSentData = config.getBoolean("logSentData", false); + boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); + metricsBase = + new MetricsBase( + "bukkit", + serverUUID, + serviceId, + enabled, + this::appendPlatformData, + this::appendServiceData, + submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), + plugin::isEnabled, + (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), + (message) -> this.plugin.getLogger().log(Level.INFO, message), + logErrors, + logSentData, + logResponseStatusText); + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + metricsBase.addCustomChart(chart); + } + + private void appendPlatformData(JsonObjectBuilder builder) { + builder.appendField("playerAmount", getPlayerAmount()); + builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); + builder.appendField("bukkitVersion", Bukkit.getVersion()); + builder.appendField("bukkitName", Bukkit.getName()); + builder.appendField("javaVersion", System.getProperty("java.version")); + builder.appendField("osName", System.getProperty("os.name")); + builder.appendField("osArch", System.getProperty("os.arch")); + builder.appendField("osVersion", System.getProperty("os.version")); + builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); + } + + private void appendServiceData(JsonObjectBuilder builder) { + builder.appendField("pluginVersion", plugin.getDescription().getVersion()); + } + + private int getPlayerAmount() { + try { + // Around MC 1.8 the return type was changed from an array to a collection, + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + return onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + // Just use the new method if the reflection failed + return Bukkit.getOnlinePlayers().size(); + } + } + + public static class MetricsBase { + + /** The version of the Metrics class. */ + public static final String METRICS_VERSION = "2.2.1"; + + private static final ScheduledExecutorService scheduler = + Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics")); + + private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; + + private final String platform; + + private final String serverUuid; + + private final int serviceId; + + private final Consumer appendPlatformDataConsumer; + + private final Consumer appendServiceDataConsumer; + + private final Consumer submitTaskConsumer; + + private final Supplier checkServiceEnabledSupplier; + + private final BiConsumer errorLogger; + + private final Consumer infoLogger; + + private final boolean logErrors; + + private final boolean logSentData; + + private final boolean logResponseStatusText; + + private final Set customCharts = new HashSet<>(); + + private final boolean enabled; + + /** + * Creates a new MetricsBase class instance. + * + * @param platform The platform of the service. + * @param serviceId The id of the service. + * @param serverUuid The server uuid. + * @param enabled Whether or not data sending is enabled. + * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all platform-specific data. + * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all service-specific data. + * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be + * used to delegate the data collection to a another thread to prevent errors caused by + * concurrency. Can be {@code null}. + * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. + * @param errorLogger A consumer that accepts log message and an error. + * @param infoLogger A consumer that accepts info log messages. + * @param logErrors Whether or not errors should be logged. + * @param logSentData Whether or not the sent data should be logged. + * @param logResponseStatusText Whether or not the response status text should be logged. + */ + public MetricsBase( + String platform, + String serverUuid, + int serviceId, + boolean enabled, + Consumer appendPlatformDataConsumer, + Consumer appendServiceDataConsumer, + Consumer submitTaskConsumer, + Supplier checkServiceEnabledSupplier, + BiConsumer errorLogger, + Consumer infoLogger, + boolean logErrors, + boolean logSentData, + boolean logResponseStatusText) { + this.platform = platform; + this.serverUuid = serverUuid; + this.serviceId = serviceId; + this.enabled = enabled; + this.appendPlatformDataConsumer = appendPlatformDataConsumer; + this.appendServiceDataConsumer = appendServiceDataConsumer; + this.submitTaskConsumer = submitTaskConsumer; + this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; + this.errorLogger = errorLogger; + this.infoLogger = infoLogger; + this.logErrors = logErrors; + this.logSentData = logSentData; + this.logResponseStatusText = logResponseStatusText; + checkRelocation(); + if (enabled) { + startSubmitting(); + } + } + + public void addCustomChart(CustomChart chart) { + this.customCharts.add(chart); + } + + private void startSubmitting() { + final Runnable submitTask = + () -> { + if (!enabled || !checkServiceEnabledSupplier.get()) { + // Submitting data or service is disabled + scheduler.shutdown(); + return; + } + if (submitTaskConsumer != null) { + submitTaskConsumer.accept(this::submitData); + } else { + this.submitData(); + } + }; + // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution + // of requests on the + // bStats backend. To circumvent this problem, we introduce some randomness into the initial + // and second delay. + // WARNING: You must not modify and part of this Metrics class, including the submit delay or + // frequency! + // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it! + long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); + long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); + scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); + scheduler.scheduleAtFixedRate( + submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); + } + + private void submitData() { + final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); + appendPlatformDataConsumer.accept(baseJsonBuilder); + final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); + appendServiceDataConsumer.accept(serviceJsonBuilder); + JsonObjectBuilder.JsonObject[] chartData = + customCharts.stream() + .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) + .filter(Objects::nonNull) + .toArray(JsonObjectBuilder.JsonObject[]::new); + serviceJsonBuilder.appendField("id", serviceId); + serviceJsonBuilder.appendField("customCharts", chartData); + baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); + baseJsonBuilder.appendField("serverUUID", serverUuid); + baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); + JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); + scheduler.execute( + () -> { + try { + // Send the data + sendData(data); + } catch (Exception e) { + // Something went wrong! :( + if (logErrors) { + errorLogger.accept("Could not submit bStats metrics data", e); + } + } + }); + } + + private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { + if (logSentData) { + infoLogger.accept("Sent bStats metrics data: " + data.toString()); + } + String url = String.format(REPORT_URL, platform); + HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("User-Agent", "Metrics-Service/1"); + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = + new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + if (logResponseStatusText) { + infoLogger.accept("Sent data to bStats and received response: " + builder); + } + } + + /** Checks that the class was properly relocated. */ + private void checkRelocation() { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null + || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little + // "trick" ... :D + final String defaultPackage = + new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); + final String examplePackage = + new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure no one just copy & pastes the example and uses the wrong package + // names + if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) + || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + /** + * Gzips the given string. + * + * @param str The string to gzip. + * @return The gzipped string. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + } + + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + public abstract static class CustomChart { + + private final String chartId; + + protected CustomChart(String chartId) { + if (chartId == null) { + throw new IllegalArgumentException("chartId must not be null"); + } + this.chartId = chartId; + } + + public JsonObjectBuilder.JsonObject getRequestJsonObject( + BiConsumer errorLogger, boolean logErrors) { + JsonObjectBuilder builder = new JsonObjectBuilder(); + builder.appendField("chartId", chartId); + try { + JsonObjectBuilder.JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + builder.appendField("data", data); + } catch (Throwable t) { + if (logErrors) { + errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return builder.build(); + } + + protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; + } + + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } + } + + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } + } + + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } + } + + /** + * An extremely simple JSON builder. + * + *

While this class is neither feature-rich nor the most performant one, it's sufficient enough + * for its use-case. + */ + public static class JsonObjectBuilder { + + private StringBuilder builder = new StringBuilder(); + + private boolean hasAtLeastOneField = false; + + public JsonObjectBuilder() { + builder.append("{"); + } + + /** + * Appends a null field to the JSON. + * + * @param key The key of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendNull(String key) { + appendFieldUnescaped(key, "null"); + return this; + } + + /** + * Appends a string field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String value) { + if (value == null) { + throw new IllegalArgumentException("JSON value must not be null"); + } + appendFieldUnescaped(key, "\"" + escape(value) + "\""); + return this; + } + + /** + * Appends an integer field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int value) { + appendFieldUnescaped(key, String.valueOf(value)); + return this; + } + + /** + * Appends an object to the JSON. + * + * @param key The key of the field. + * @param object The object. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject object) { + if (object == null) { + throw new IllegalArgumentException("JSON object must not be null"); + } + appendFieldUnescaped(key, object.toString()); + return this; + } + + /** + * Appends a string array to the JSON. + * + * @param key The key of the field. + * @param values The string array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values) + .map(value -> "\"" + escape(value) + "\"") + .collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an integer array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an object array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends a field to the object. + * + * @param key The key of the field. + * @param escapedValue The escaped value of the field. + */ + private void appendFieldUnescaped(String key, String escapedValue) { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + if (key == null) { + throw new IllegalArgumentException("JSON key must not be null"); + } + if (hasAtLeastOneField) { + builder.append(","); + } + builder.append("\"").append(escape(key)).append("\":").append(escapedValue); + hasAtLeastOneField = true; + } + + /** + * Builds the JSON string and invalidates this builder. + * + * @return The built JSON string. + */ + public JsonObject build() { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + JsonObject object = new JsonObject(builder.append("}").toString()); + builder = null; + return object; + } + + /** + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ + private static String escape(String value) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"') { + builder.append("\\\""); + } else if (c == '\\') { + builder.append("\\\\"); + } else if (c <= '\u000F') { + builder.append("\\u000").append(Integer.toHexString(c)); + } else if (c <= '\u001F') { + builder.append("\\u00").append(Integer.toHexString(c)); + } else { + builder.append(c); + } + } + return builder.toString(); + } + + /** + * A super simple representation of a JSON object. + * + *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not + * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, + * JsonObject)}. + */ + public static class JsonObject { + + private final String value; + + private JsonObject(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + } + } +} \ No newline at end of file diff --git a/src/com/github/joelgodofwar/sps/api/SendJsonMessages.java b/src/com/github/joelgodofwar/sps/api/SendJsonMessages.java new file mode 100644 index 0000000..6a402dc --- /dev/null +++ b/src/com/github/joelgodofwar/sps/api/SendJsonMessages.java @@ -0,0 +1,49 @@ +package com.github.joelgodofwar.sps.api; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.World; +import org.bukkit.entity.Player; + +import com.github.joelgodofwar.sps.SinglePlayerSleep; + + +public class SendJsonMessages { + public static void SendJsonMessage(Player player, String string){ + /** Some code taken from AutoMessage by ELCHILEN0 */ + String v = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + try { + // Parse the message + Object parsedMessage = Class.forName("net.minecraft.server." + v + ".IChatBaseComponent$ChatSerializer").getMethod("a", String.class).invoke(null, ChatColor.translateAlternateColorCodes("&".charAt(0), string)); + Object packetPlayOutChat = Class.forName("net.minecraft.server." + v + ".PacketPlayOutChat").getConstructor(Class.forName("net.minecraft.server." + v + ".IChatBaseComponent")).newInstance(parsedMessage); + + // Drill down to the playerConnection which calls the sendPacket method + Object craftPlayer = Class.forName("org.bukkit.craftbukkit." + v + ".entity.CraftPlayer").cast(player); + Object craftHandle = Class.forName("org.bukkit.craftbukkit." + v + ".entity.CraftPlayer").getMethod("getHandle").invoke(craftPlayer); + Object playerConnection = Class.forName("net.minecraft.server." + v + ".EntityPlayer").getField("playerConnection").get(craftHandle); + + // Send the message packet + Class.forName("net.minecraft.server." + v + ".PlayerConnection").getMethod("sendPacket", Class.forName("net.minecraft.server." + v + ".Packet")).invoke(playerConnection, packetPlayOutChat); + } catch (Exception ignore) { + ignore.printStackTrace(); + } + } + public static void SendAllJsonMessage(String s, String oldS, World world){ + String s2; + for (Player player: Bukkit.getOnlinePlayers()){ + if(player.getWorld().equals(world)){ + if(player.hasPermission("sps.cancel")&&SinglePlayerSleep.displaycancel){ + SendJsonMessage(player, s); + if(SinglePlayerSleep.debug){SinglePlayerSleep.logger.info("SinglePlayerSleep - SAJM - perm & display");} + }else{ + s2 = s; + s2 = s2.replace(oldS, "").replace(" [\"", " \"").replace("]\"", "\"").replace(",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/cancel\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"Click to cancel sleep\"}", ""); + SendJsonMessage(player, s2); + //PluginBase.logger.info("S=" + s); + //PluginBase.logger.info("s2=" + s2); + //PluginBase.logger.info("no perm"); + } + } + } + } +} diff --git a/src/com/github/joelgodofwar/sps/api/StrUtils.java b/src/com/github/joelgodofwar/sps/api/StrUtils.java new file mode 100644 index 0000000..95da0b6 --- /dev/null +++ b/src/com/github/joelgodofwar/sps/api/StrUtils.java @@ -0,0 +1,141 @@ +package com.github.joelgodofwar.sps.api; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang.StringUtils; + +public class StrUtils { + /** StringRight */ + public static String Right(String input, int chars){ + if (input.length() > chars){ + //System.out.println("Right input=" + input); + return input.substring(input.length() - chars); + } + else{ + return input; + } + } + + /** StringLeft */ + public static String Left(String input, int chars){ + if (input.length() > chars){ + //System.out.println("Left input=" + input); + //System.out.println("Left chars=" + chars); + return input.substring(0, chars); + } + else{ + return input; + } + } + + public static boolean stringContains(String string, String string2){ + String[] string3 = string.split(", "); + for(int i = 0; i < string3.length; i++){ + if(string3[i].equals(string2)){ + return true; + } + } + return false; + } + + // §x§1§1§1§1§1§1D§x§2§2§2§2§2§2e§x§3§3§3§3§3§3M§x§4§4§4§4§4§4o§x§5§5§5§5§5§5N + @SuppressWarnings("unused") + public static String parseRGBNameColors(String string){ + String nickPrefix = "\"}"; + String nickString = ",{\"text\":\"\",\"color\":\"\"}"; + String nickString2 = ",{\"text\":\"\",\"bold\":,\"obfuscated\":,\"italic\":,\"underlined\":,\"strikethrough\":,\"color\":\"\"}"; + String nickSuffix = ",{\"text\":\""; + //String[] string2 = null; + List string2 = new ArrayList(); + String string3 = ""; + String string4 = ""; + String color; + String text; // #FF00FF + boolean bold,obfus,italic,under,strike; + //int counter = 0; // SxSFSFS0S0SFSF + int index; + if(string.contains("§x")){ + int count = StringUtils.countMatches(string, "§x"); + //System.out.println("count=" + count); + for(int i = 0; i < count; i++){//while(string.length() > 0){ + index = string.indexOf("§x"); + //System.out.println("i=" + i); + //System.out.println("index=" + index); + //System.out.println("index2=" + string.indexOf("§x", index + 1)); + int index2 = string.indexOf("§x", index + 1); + if(index2 <= 1){ + string2.add(Left(string, string.length())); + }else{ + string2.add(Left(string, index2)); // §x§1§1§1§1§1§1D + } + string = string.replace(string2.get(i), ""); + } + for(int i = 0; i < count; i++){ + string4 = string2.get(i).replace("§x", "#"); + if(string4.toLowerCase().contains("§l")) { bold = true; }else { bold = false; } + if(string4.toLowerCase().contains("§k")) { obfus = true; }else { obfus = false; } + if(string4.toLowerCase().contains("§o")) { italic = true; }else { italic = false; } + if(string4.toLowerCase().contains("§n")) { under = true; }else { under = false; } + if(string4.toLowerCase().contains("§m")) { strike = true; }else { strike = false; } + string4 = string4.replace("§l", "").replace("§k", "").replace("§o", "").replace("§n", "").replace("§m", "") + .replace("§L", "").replace("§K", "").replace("§O", "").replace("§N", "").replace("§M", ""); + string4 = string4.replace("§", ""); + //System.out.println("String4=" + string4); + color = Left(string4, 7).replace("§x", "#").replace("§", ""); + //System.out.println("color=" + color); + text = Right(string4, string4.length() - 7); + //System.out.println("text=" + text); + if (bold||obfus||italic||under||strike) { + string3 = string3 + nickString2.replace("", color).replace("", text) + .replace("", "" + bold).replace("", "" + obfus).replace("", "" + italic) + .replace("", "" + under).replace("", "" + strike); + }else { + string3 = string3 + nickString.replace("", color).replace("", text); + } + + } + return nickPrefix + string3 + nickSuffix; + } + return string; + } + + public static String stripRGBColors(String string){ + List string2 = new ArrayList(); + String string3 = ""; + String string4 = ""; + //String color; + String text; // #FF00FF + //int counter = 0; // SxSFSFS0S0SFSF + int index; + if(string.contains("§x")){ + int count = StringUtils.countMatches(string, "§x"); + //System.out.println("count=" + count); + for(int i = 0; i < count; i++){//while(string.length() > 0){ + index = string.indexOf("§x"); + //System.out.println("i=" + i); + //System.out.println("index=" + index); + //System.out.println("index2=" + string.indexOf("§x", index + 1)); + int index2 = string.indexOf("§x", index + 1); + if(index2 <= 1){ + string2.add(Left(string, string.length())); + }else{ + string2.add(Left(string, index2)); // §x§1§1§1§1§1§1D + } + string = string.replace(string2.get(i), ""); + } + for(int i = 0; i < count; i++){ + string4 = string2.get(i).replace("§x", "#"); + string4 = string4.replace("§", ""); + //System.out.println("String4=" + string4); + //color = Left(string4, 7).replace("§x", "#").replace("§", ""); + //System.out.println("color=" + color); + text = Right(string4, string4.length() - 7); + //System.out.println("text=" + text); + string3 = string3 + text; + } + return string3; + } + return string; + } +} diff --git a/src/com/github/joelgodofwar/sps/api/UpdateChecker.java b/src/com/github/joelgodofwar/sps/api/UpdateChecker.java new file mode 100644 index 0000000..ca8395e --- /dev/null +++ b/src/com/github/joelgodofwar/sps/api/UpdateChecker.java @@ -0,0 +1,186 @@ +package com.github.joelgodofwar.sps.api; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; + +import org.apache.commons.lang.math.NumberUtils; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +import com.github.joelgodofwar.sps.util.Ansi; + +public class UpdateChecker { + private static int project; + private URL checkURL; + private String newVersion; + private String newMinVers; + private String oldVersion; + private String oldMinVers; + @SuppressWarnings("unused") + private JavaPlugin plugin; + String[] strVersionNew; // [0]=1.14 [1]=1.0.0.? + String[] strVersionCurrent; // [0]=1.14 [1]=1.0.0.? + String URLString = "https://github.com/JoelGodOfwar/SinglePlayerSleep/raw/master/versioncheck/"; + String URLFile = "/version.txt"; + + + public UpdateChecker(JavaPlugin plugin, int projectID) { + this.plugin = plugin; + project = projectID; + oldVersion = plugin.getDescription().getVersion(); + try { + checkURL = new URL(URLString + oldVersion.substring(0, 4) + URLFile); + }catch(MalformedURLException e) { + Bukkit.getLogger().warning(Ansi.RED + "Could not connect to update server."); + //Bukkit.getPluginManager().disablePlugin(plugin); + } + } + public UpdateChecker(String plugin, int projectID){ + //this.plugin = plugin; + project = projectID; + oldVersion = plugin; + try { + checkURL = new URL(URLString + oldVersion.substring(0, 4) + URLFile); + }catch(MalformedURLException e) { + Bukkit.getLogger().warning(Ansi.RED + "Could not connect to update server."); + //Bukkit.getPluginManager().disablePlugin(plugin); + } + } + public static String getResourceUrl() {return "https://spigotmc.org/resources/" + project;} + public boolean checkForUpdates() throws Exception { + boolean isOutdated = false; + URLConnection con = checkURL.openConnection(); + newVersion = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine(); + strVersionNew = newVersion.split("_"); // Split into minimum MC version and version + + newMinVers = strVersionNew[0]; + newVersion = strVersionNew[1]; + //System.out.println("newVersion=" + newVersion); + Version newVers = new Version(newVersion); + + strVersionCurrent = oldVersion.split("_"); + + oldMinVers = strVersionCurrent[0]; + oldVersion = strVersionCurrent[1]; + //System.out.println("oldVersion=" + oldVersion); + Version oldVers = new Version(oldVersion); + + if(oldVers.isDev()){ /** If currently on Dev version, ignore build -1 from Patch */ + if(newVers.Major() > oldVers.Major()){isOutdated = true;} + if(newVers.Major() == oldVers.Major()){/** same do nothing */} + if(newVers.Minor() > oldVers.Minor()){isOutdated = true;} + else if(newVers.Minor() == oldVers.Minor()){/** same do nothing */} + if(newVers.Patch() > (oldVers.Patch() - 1)){isOutdated = true;} + else if(newVers.Patch() == (oldVers.Patch() - 1)){/** same do nothing */} + /**if(newVers.Build() > oldVers.Build()){isOutdated = true;} + else if(newVers.Build() == oldVers.Build()){/** same do nothing }*/ + }else { + if(newVers.Major() > oldVers.Major()){isOutdated = true;} + if(newVers.Major() == oldVers.Major()){/** same do nothing */} + if(newVers.Minor() > oldVers.Minor()){isOutdated = true;} + else if(newVers.Minor() == oldVers.Minor()){/** same do nothing */} + if(newVers.Patch() > oldVers.Patch()){isOutdated = true;} + else if(newVers.Patch() == oldVers.Patch()){/** same do nothing */} + if(newVers.Build() > oldVers.Build()){isOutdated = true;} + else if(newVers.Build() == oldVers.Build()){/** same do nothing */} + } + return isOutdated; //plugin.getDescription().getVersion().equals(newVersion); TODO: + } + public String newVersion(){ + return newMinVers + "_" + newVersion; + } + public String oldVersion(){ + return oldMinVers + "_" + oldVersion; + } + + public class Version{ + private int Major; // 1 + private int Minor; // 16 + private int Patch; // 1 + private int Build; // ? + private boolean isDev = false; + private String[] string2 = {"0","0","0","0"}; + public Version(String string){ + //System.out.println("string=" + string); + string2 = string.split("\\."); + //for (String a : string2) + //System.out.println(a); + //System.out.println("string2=" + string2.toString()); + //System.out.println("string2.length=" + string2.length); + this.Major = NumberUtils.toInt(string2[0]); + this.Minor = NumberUtils.toInt(string2[1]); + this.Patch = NumberUtils.toInt(string2[2]); + if(string2.length >= 4){ + if(string2[3].toUpperCase().contains("D")){ + isDev = true; + string2[3] = string2[3].toUpperCase().replace("D", ""); + } + this.Build = NumberUtils.toInt(string2[3]); + }else{ + this.Build = 0; + } + } + public int Major(){return Major;} + public int Minor(){return Minor;} + public int Patch(){return Patch;} + public int Build(){return Build;} + public boolean isDev(){return isDev;} + } + /** + public static boolean UpdateCheck; + public String UColdVers; + public String UCnewVers; + public String thisName = this.getName(); + public String thisVersion = this.getDescription().getVersion(); + +for onEnable use + if(UpdateCheck){ + try { + Bukkit.getConsoleSender().sendMessage("Checking for updates..."); + UpdateChecker updater = new UpdateChecker(this, 68139); + if(updater.checkForUpdates()) { + UpdateAvailable = true; // TODO: Update Checker + UColdVers = updater.oldVersion(); + UCnewVers = updater.newVersion(); + Bukkit.getConsoleSender().sendMessage(this.getName() + Ansi.RED + " v" + UColdVers + Ansi.RESET +" " + lang.get("newvers") + Ansi.GREEN + " v" + UCnewVers + Ansi.RESET); + Bukkit.getConsoleSender().sendMessage(UpdateChecker.getResourceUrl()); + }else{ + UpdateAvailable = false; + } + }catch(Exception e) { + Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Could not process update check"); + e.printStackTrace(); + } + } + +for update command use + @NotNull + BukkitTask updateTask = this.getServer().getScheduler().runTaskAsynchronously(this, new Runnable() { + + public void run() { + try { + Bukkit.getConsoleSender().sendMessage("Checking for updates..."); + UpdateChecker updater = new UpdateChecker(thisVersion, 68139); + if(updater.checkForUpdates()) { + UpdateAvailable = true; + UColdVers = updater.oldVersion(); + UCnewVers = updater.newVersion(); + sender.sendMessage(ChatColor.YELLOW + thisName + ChatColor.RED + " v" + UColdVers + ChatColor.RESET + " " + lang.get("newvers") + ChatColor.GREEN + " v" + UCnewVers + ChatColor.RESET); + sender.sendMessage(UpdateChecker.getResourceUrl()); + }else{ + sender.sendMessage(ChatColor.YELLOW + thisName + ChatColor.RED + " v" + thisVersion + ChatColor.RESET + " Up to date." + ChatColor.RESET); + UpdateAvailable = false; + } + }catch(Exception e) { + sender.sendMessage(ChatColor.RED + "Could not process update check"); + Bukkit.getConsoleSender().sendMessage(Ansi.RED + "Could not process update check"); + e.printStackTrace(); + } + } + + }); + */ +} \ No newline at end of file diff --git a/src/com/github/joelgodofwar/sps/api/Version.java b/src/com/github/joelgodofwar/sps/api/Version.java new file mode 100644 index 0000000..c97ac5c --- /dev/null +++ b/src/com/github/joelgodofwar/sps/api/Version.java @@ -0,0 +1,45 @@ +package com.github.joelgodofwar.sps.api; + +import org.apache.commons.lang.math.NumberUtils; + + +public class Version{ + private int Major; // 1 + private int Minor; // 16 + private int Patch; // 1 + private int Build; // ? + private boolean isDev = false; + public Version(String string){ + String[] string2 = string.split("."); + this.Major = NumberUtils.toInt(string2[0]); + this.Minor = NumberUtils.toInt(string2[1]); + this.Patch = NumberUtils.toInt(string2[2]); + if(string2[3] != null){ + if(string2[3].toUpperCase().contains("D")){ + isDev = true; + string2[3] = string2[3].toUpperCase().replace("D", ""); + } + this.Build = NumberUtils.toInt(string2[3]); + }else{ + this.Build = 0; + } + } + public int Major(){ + return Major; + } + public int Minor(){ + return Minor; + + } + public int Patch(){ + return Patch; + + } + public int Build(){ + return Build; + + } + public boolean isDev(){ + return isDev; + } +} diff --git a/src/com/github/joelgodofwar/sps/api/YmlConfiguration.java b/src/com/github/joelgodofwar/sps/api/YmlConfiguration.java new file mode 100644 index 0000000..c479338 --- /dev/null +++ b/src/com/github/joelgodofwar/sps/api/YmlConfiguration.java @@ -0,0 +1,123 @@ +package com.github.joelgodofwar.sps.api; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.Writer; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; + +import jdk.internal.joptsimple.internal.Strings; + +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.configuration.file.YamlConstructor; +import org.bukkit.configuration.file.YamlRepresenter; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.representer.Representer; + +import com.google.common.base.Charsets; + +/* + * @author: Aoife (Josh) + * @date: 2020-04-25 + * @project: WarpConverter + */ + +public class YmlConfiguration extends YamlConfiguration { + + private final DumperOptions yamlOptions = new DumperOptions(); + private final Representer yamlRepresenter = new YamlRepresenter(); + private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); + private Map commentContainer = new HashMap<>(); + + public void save(File file) throws IOException { + Validate.notNull(file); + + try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)) { + writer.write(saveToString()); + } + + } + + public static void saveConfig(File file, YmlConfiguration config) { + try { + config.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public String saveToString(){ + yamlOptions.setIndent(options().indent()); + yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + + String header = "";//buildHeader(); + String dump = yaml.dump(getValues(false)); + + if (dump.equals(BLANK_CONFIG)) { + dump = Strings.EMPTY; + } else { + StringBuilder sb = new StringBuilder(); + int line = 0; + for(String s : dump.split("\n")) { + line++; + while (commentContainer.containsKey(line)) { + sb.append(commentContainer.get(line)).append("\n"); + line++; + } + sb.append(s).append("\n"); + } + + dump = sb.toString(); + } + + return header.length() > 0 ? header + dump : dump; + } + + @Override + public void load(Reader reader) throws IOException, InvalidConfigurationException { + BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); + + StringBuilder builder = new StringBuilder(); + + try { + String line; + int count = 0; + while ((line = input.readLine()) != null) { + count++; + if (line.contains(COMMENT_PREFIX)|| line.isEmpty()) + commentContainer.put(count, line); + builder.append(line).append('\n'); + } + } finally { + input.close(); + } + + loadFromString(builder.toString()); + } + + public static YamlConfiguration loadConfiguration(File file, YmlConfiguration config) { + Validate.notNull(file, "File cannot be null"); + + try { + config.load(file); + } catch (FileNotFoundException ex) { + } catch (IOException | InvalidConfigurationException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Cannot load " + file, ex); + } + + return config; + } + +} \ No newline at end of file diff --git a/src/com/github/joelgodofwar/sps/i18n/Translator.java b/src/com/github/joelgodofwar/sps/i18n/Translator.java new file mode 100644 index 0000000..c0df7a2 --- /dev/null +++ b/src/com/github/joelgodofwar/sps/i18n/Translator.java @@ -0,0 +1,84 @@ +package com.github.joelgodofwar.sps.i18n; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Arrays; +import java.util.Locale; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.Properties; +import java.util.ResourceBundle; +import java.util.TreeMap; + + +public class Translator { + private static String lang; + private static String dataFolder; + @SuppressWarnings("static-access") + public Translator(String lang, String dataFolder){ + this.lang = formatLanguageCode(lang); + this.dataFolder = dataFolder; + } + public static String get(String key, String... defaultValue) { + Translator language = new Translator(lang, dataFolder); + return language.get(lang, key, defaultValue); + } + public String get(String lang, String key, String... defaultValue) { + String value = Arrays.stream(defaultValue).findFirst().orElse(null); + ResourceBundle bundle = ResourceBundle.getBundle("lang/lang", new Locale(lang)); + //ResourceBundle bundle = ResourceBundle.getBundle("lang/" + lang); + + try { + value = bundle.getString(key); + } catch (MissingResourceException e) { + // Key not found in bundle + } + File langFile = new File(dataFolder + File.separatorChar + "lang" + File.separatorChar + "" + lang + ".properties"); + Properties props = new Properties(); + try { + if (langFile.exists()) { + FileInputStream inputStream = new FileInputStream(langFile); + props.load(inputStream); + inputStream.close(); + if (!props.containsKey(key)) { + props.setProperty(key, value); + sortPropertiesFile(langFile, props); + } + } else { + // File doesn't exist, use default value from bundle or null if defaultValue is not present + return value; + } + } catch (IOException e) { + e.printStackTrace(); + } + // Get value from properties file (either updated or existing) + value = props.getProperty(key); + return value; + } + public void sortPropertiesFile(File file, Properties props) throws IOException { + // Create a TreeMap to store the sorted properties + Map sortedProps = new TreeMap<>(); + // Iterate over the Properties object and add each key-value pair to the TreeMap + for (String key : props.stringPropertyNames()) { + sortedProps.put(key, props.getProperty(key)); + } + // Clear the properties file + try (FileOutputStream outputStream = new FileOutputStream(file)) { + outputStream.getChannel().truncate(0); + } + // Write sorted properties to file + try (FileWriter writer = new FileWriter(file)) { + for (Map.Entry entry : sortedProps.entrySet()) { + writer.write(entry.getKey() + "=" + entry.getValue() + "\n"); + } + } + } + public String formatLanguageCode(String lang) { + String[] parts = lang.split("_"); + return parts[0].toLowerCase() + "_" + parts[1].toUpperCase(); + } + +} \ No newline at end of file diff --git a/src/com/github/joelgodofwar/sps/util/Ansi.java b/src/com/github/joelgodofwar/sps/util/Ansi.java new file mode 100644 index 0000000..50fe7c4 --- /dev/null +++ b/src/com/github/joelgodofwar/sps/util/Ansi.java @@ -0,0 +1,32 @@ +package com.github.joelgodofwar.sps.util; + +import org.bukkit.ChatColor; + +public class Ansi { + public static final ChatColor AQUA = ChatColor.AQUA; + public static final ChatColor BLACK = ChatColor.BLACK; + public static final ChatColor BLUE = ChatColor.BLUE; + public static final ChatColor DARK_AQUA = ChatColor.DARK_AQUA; + public static final ChatColor DARK_BLUE = ChatColor.DARK_BLUE; + public static final ChatColor DARK_GRAY = ChatColor.DARK_GRAY; + public static final ChatColor DARK_GREEN = ChatColor.DARK_GREEN; + public static final ChatColor DARK_PURPLE = ChatColor.DARK_PURPLE; + public static final ChatColor DARK_RED = ChatColor.DARK_RED; + public static final ChatColor GOLD = ChatColor.GOLD; + public static final ChatColor GRAY = ChatColor.GRAY; + public static final ChatColor GREEN = ChatColor.GREEN; + public static final ChatColor MAGENTA = ChatColor.LIGHT_PURPLE; + public static final ChatColor RED = ChatColor.RED; + public static final ChatColor WHITE = ChatColor.WHITE; + public static final ChatColor YELLOW = ChatColor.YELLOW; + + public static final ChatColor BOLD = ChatColor.BOLD; + public static final ChatColor ITALIC = ChatColor.ITALIC; + public static final ChatColor MAGIC = ChatColor.MAGIC; + public static final ChatColor RESET = ChatColor.RESET; + public static final ChatColor STRIKETHROUGH = ChatColor.STRIKETHROUGH; + public static final ChatColor UNDERLINE = ChatColor.UNDERLINE; + + + +} \ No newline at end of file diff --git a/src/com/github/joelgodofwar/sps/util/Format.java b/src/com/github/joelgodofwar/sps/util/Format.java new file mode 100644 index 0000000..6b6b631 --- /dev/null +++ b/src/com/github/joelgodofwar/sps/util/Format.java @@ -0,0 +1,558 @@ +package com.github.joelgodofwar.sps.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.bukkit.ChatColor; + +//This class is where all formatting methods are stored. +@SuppressWarnings("unused") +public class Format { + //private static MineverseChat plugin = MineverseChat.getInstance(); + + public static final int LEGACY_COLOR_CODE_LENGTH = 2; + public static final int HEX_COLOR_CODE_LENGTH = 14; + public static final String DEFAULT_COLOR_CODE = String.valueOf(ChatColor.WHITE); + public static final String HEX_COLOR_CODE_PREFIX = "#"; + public static final String BUKKIT_COLOR_CODE_PREFIX = "�"; + public static final String BUKKIT_HEX_COLOR_CODE_PREFIX = "x"; + + /**public static String convertToJson(MineverseChatPlayer sender, String format, String chat) { + JsonFormat JSONformat = MineverseChat.jfInfo.getJsonFormat(sender.getJsonFormat()); + String f = format.replace("\\", "\\\\").replace("\"", "\\\""); + String c = chat.replace("\\", "\\\\").replace("\"", "\\\""); + String json = "[\"\",{\"text\":\"\",\"extra\":["; + String prefix = ""; + String suffix = ""; + try { + prefix = FormatStringAll(MineverseChat.chat.getPlayerPrefix(sender.getPlayer())); + suffix = FormatStringAll(MineverseChat.chat.getPlayerSuffix(sender.getPlayer())); + if(suffix.equals("")) { + suffix = "venturechat_no_suffix_code"; + } + if(prefix.equals("")) { + prefix = "venturechat_no_prefix_code"; + } + } + catch(Exception e) { + System.out.println("Exception?" + e.getLocalizedMessage()); + if(plugin.getConfig().getString("loglevel", "info").equals("debug")) { + Bukkit.getConsoleSender().sendMessage(Format.FormatStringAll("&8[&eVentureChat&8]&e - Prefix and / or suffix don't exist, setting to nothing.")); + } + suffix = "venturechat_no_suffix_code"; + prefix = "venturechat_no_prefix_code"; + } + String nickname = ""; + if(sender.getPlayer() != null) { + nickname = FormatStringAll(sender.getPlayer().getDisplayName()); + } + json += convertPlaceholders(f, JSONformat, prefix, nickname, suffix, sender); + json += "]}"; + json += "," + convertLinks(c); + json += "]"; + if(plugin.getConfig().getString("loglevel", "info").equals("debug")) { + System.out.println(json); + System.out.println("END OF JSON"); + System.out.println("END OF JSON"); + System.out.println("END OF JSON"); + System.out.println("END OF JSON"); + System.out.println("END OF JSON"); + } + return json; + }*/ + + /**private static String convertPlaceholders(String s, JsonFormat format, String prefix, String nickname, String suffix, MineverseChatPlayer icp) { + String remaining = s; + String temp = ""; + int indexStart = -1; + int indexEnd = -1; + String placeholder = ""; + String lastCode = "�f"; + do { + Pattern pattern = Pattern.compile("(" + escapeAllRegex(prefix) + "|" + escapeAllRegex(nickname) + "|" + escapeAllRegex(suffix) + ")"); + Matcher matcher = pattern.matcher(remaining); + if(matcher.find()) { + indexStart = matcher.start(); + indexEnd = matcher.end(); + placeholder = remaining.substring(indexStart, indexEnd); + temp += convertToJsonColors(lastCode + remaining.substring(0, indexStart)) + ","; + lastCode = getLastCode(lastCode + remaining.substring(0, indexStart)); + String action = ""; + String text = ""; + String hover = ""; + if(placeholder.contains(prefix)) { + action = format.getClickPrefix(); + text = PlaceholderAPI.setBracketPlaceholders(icp.getPlayer(), format.getClickPrefixText()); + for(String st : format.getHoverTextPrefix()) { + hover += Format.FormatStringAll(st) + "\n"; + } + } + if(placeholder.contains(nickname)) { + action = format.getClickName(); + text = PlaceholderAPI.setBracketPlaceholders(icp.getPlayer(), format.getClickNameText()); + for(String st : format.getHoverTextName()) { + hover += Format.FormatStringAll(st) + "\n"; + } + } + if(placeholder.contains(suffix)) { + action = format.getClickSuffix(); + text = PlaceholderAPI.setBracketPlaceholders(icp.getPlayer(), format.getClickSuffixText()); + for(String st : format.getHoverTextSuffix()) { + hover += Format.FormatStringAll(st) + "\n"; + } + } + hover = PlaceholderAPI.setBracketPlaceholders(icp.getPlayer(), hover.substring(0, hover.length() - 1)); + temp += convertToJsonColors(lastCode + placeholder, ",\"clickEvent\":{\"action\":\"" + action + "\",\"value\":\"" + text + "\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[" + convertToJsonColors(hover) + "]}}") + ","; + lastCode = getLastCode(lastCode + placeholder); + remaining = remaining.substring(indexEnd); + } + else { + temp += convertToJsonColors(lastCode + remaining); + break; + } + } + while(true); + return temp; + }*/ + + /**private static String convertLinks(String s) { + String remaining = s; + String temp = ""; + int indexLink = -1; + int indexLinkEnd = -1; + String link = ""; + String lastCode = "�f"; + do { + Pattern pattern = Pattern.compile("([a-zA-Z0-9�\\-:/]+\\.[a-zA-Z/0-9�\\-:_#]+(\\.[a-zA-Z/0-9.�\\-:#\\?\\+=_]+)?)"); + Matcher matcher = pattern.matcher(remaining); + if(matcher.find()) { + indexLink = matcher.start(); + indexLinkEnd = matcher.end(); + link = remaining.substring(indexLink, indexLinkEnd); + temp += convertToJsonColors(lastCode + remaining.substring(0, indexLink)) + ","; + lastCode = getLastCode(lastCode + remaining.substring(0, indexLink)); + String https = ""; + if(ChatColor.stripColor(link).contains("https://")) + https = "s"; + temp += convertToJsonColors(lastCode + link, ",\"underlined\":\"" + underlineURLs() + "\",\"clickEvent\":{\"action\":\"open_url\",\"value\":\"http" + https + "://" + ChatColor.stripColor(link.replace("http://", "").replace("https://", "")) + "\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[" + convertToJsonColors(lastCode + link) + "]}}") + ","; + lastCode = getLastCode(lastCode + link); + remaining = remaining.substring(indexLinkEnd); + } + else { + temp += convertToJsonColors(lastCode + remaining); + break; + } + } + while(true); + return temp; + }*/ + + public static String getLastCode(String s) { + String ts = ""; + char[] ch = s.toCharArray(); + for(int a = 0; a < s.length() - 1; a ++) { + if(String.valueOf(ch[a + 1]).matches("[lkomnLKOMN]") && ch[a] == '�') { + ts += String.valueOf(ch[a]) + ch[a + 1]; + a ++; + } + else if(String.valueOf(ch[a + 1]).matches("[0123456789abcdefrABCDEFR]") && ch[a] == '�') { + ts = String.valueOf(ch[a]) + ch[a + 1]; + a ++; + } + else if(ch[a + 1] == 'x' && ch[a] == '�') { + if(ch.length > a + 13) { + if(String.valueOf(ch[a + 3]).matches("[0123456789abcdefABCDEF]") && String.valueOf(ch[a + 5]).matches("[0123456789abcdefABCDEF]") && String.valueOf(ch[a + 7]).matches("[0123456789abcdefABCDEF]") && String.valueOf(ch[a + 9]).matches("[0123456789abcdefABCDEF]") && String.valueOf(ch[a + 11]).matches("[0123456789abcdefABCDEF]") && String.valueOf(ch[a + 13]).matches("[0123456789abcdefABCDEF]") && ch[a + 2] == '�' && ch[a + 4] == '�' && ch[a + 6] == '�' && ch[a + 8] == '�' && ch[a + 10] == '�' && ch[a + 12] == '�') { + ts = String.valueOf(ch[a]) + ch[a + 1] + ch[a + 2] + ch[a + 3] + ch[a + 4] + ch[a + 5] + ch[a + 6] + ch[a + 7] + ch[a + 8] + ch[a + 9] + ch[a + 10] + ch[a + 11] + ch[a + 12] + ch[a + 13]; + a += 13; + } + } + } + } + return ts; + } + + + private static String convertToJsonColors(String s) { + return convertToJsonColors(s, ""); + } + + private static String convertToJsonColors(String s, String extensions) { + String remaining = s; + String temp = ""; + int indexColor = -1; + int indexNextColor = -1; + String color = ""; + String modifier = ""; + boolean bold = false; + boolean obfuscated = false; + boolean italic = false; + boolean strikethrough = false; + boolean underlined = false; + String previousColor = ""; + int colorLength = LEGACY_COLOR_CODE_LENGTH; + do { + if(remaining.length() < LEGACY_COLOR_CODE_LENGTH) { + temp = "{\"text\":\"" + remaining + "\"},"; + break; + } + modifier = ""; + indexColor = remaining.indexOf(BUKKIT_COLOR_CODE_PREFIX); + previousColor = color; + + color = remaining.substring(1, indexColor + LEGACY_COLOR_CODE_LENGTH); + if(color.equals(BUKKIT_HEX_COLOR_CODE_PREFIX)) { + if(remaining.length() >= HEX_COLOR_CODE_LENGTH) { + color = HEX_COLOR_CODE_PREFIX + remaining.substring(LEGACY_COLOR_CODE_LENGTH, indexColor + HEX_COLOR_CODE_LENGTH).replace(BUKKIT_COLOR_CODE_PREFIX, ""); + colorLength = HEX_COLOR_CODE_LENGTH; + bold = false; + obfuscated = false; + italic = false; + strikethrough = false; + underlined = false; + } + } + else if(!color.matches("[0123456789abcdefABCDEF]")) { + switch(color) { + case "l": + case "L": { + bold = true; + break; + } + case "k": + case "K": { + obfuscated = true; + break; + } + case "o": + case "O": { + italic = true; + break; + } + case "m": + case "M": { + strikethrough = true; + break; + } + case "n": + case "N": { + underlined = true; + break; + } + case "r": + case "R": { + bold = false; + obfuscated = false; + italic = false; + strikethrough = false; + underlined = false; + color = "f"; + break; + } + } + if(!color.equals("f")) + color = previousColor; + if(color.length() == 0) + color = "f"; + } + else { + bold = false; + obfuscated = false; + italic = false; + strikethrough = false; + underlined = false; + } + if(bold) + modifier += ",\"bold\":\"true\""; + if(obfuscated) + modifier += ",\"obfuscated\":\"true\""; + if(italic) + modifier += ",\"italic\":\"true\""; + if(underlined) + modifier += ",\"underlined\":\"true\""; + if(strikethrough) + modifier += ",\"strikethrough\":\"true\""; + remaining = remaining.substring(colorLength); + colorLength = LEGACY_COLOR_CODE_LENGTH; + indexNextColor = remaining.indexOf(BUKKIT_COLOR_CODE_PREFIX); + if(indexNextColor == -1) { + indexNextColor = remaining.length(); + } + temp += "{\"text\":\"" + remaining.substring(0, indexNextColor) + "\",\"color\":\"" + hexidecimalToJsonColorRGB(color) + "\"" + modifier + extensions + "},"; + remaining = remaining.substring(indexNextColor); + } + while(remaining.length() > 1 && indexColor != -1); + if(temp.length() > 1) + temp = temp.substring(0, temp.length() - 1); + return temp; + } + + private static String hexidecimalToJsonColorRGB(String c) { + if(c.length() == 1) { + switch(c) { + case "0": return "black"; + case "1": return "dark_blue"; + case "2": return "dark_green"; + case "3": return "dark_aqua"; + case "4": return "dark_red"; + case "5": return "dark_purple"; + case "6": return "gold"; + case "7": return "gray"; + case "8": return "dark_gray"; + case "9": return "blue"; + case "a": + case "A": return "green"; + case "b": + case "B": return "aqua"; + case "c": + case "C": return "red"; + case "d": + case "D": return "light_purple"; + case "e": + case "E": return "yellow"; + case "f": + case "F": return "white"; + default: return "white"; + } + } + if(isValidHexColor(c)) { + return c; + } + return "white"; + } + + /**public static String convertPlainTextToJson(String s, boolean convertURL) { + if(convertURL) { + return "[" + Format.convertLinks(s) + "]"; + } + else { + return "[" + convertToJsonColors("�f" + s) + "]"; + } + } + + /**public static String formatModerationGUI(String json, Player player, String sender, String channelName, int hash) { + if(player.hasPermission("venturechat.gui")) { + json = json.substring(0, json.length() - 1); + json += "," + Format.convertToJsonColors(Format.FormatStringAll(plugin.getConfig().getString("guiicon")), ",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/vchatgui " + sender + " " + channelName + " " + hash +"\"},\"hoverEvent\":{\"action\":\"show_text\",\"value\":{\"text\":\"\",\"extra\":[" + Format.convertToJsonColors(Format.FormatStringAll(plugin.getConfig().getString("guitext"))) + "]}}") + "]"; + } + return json; + }*/ + + /**public static PacketContainer createPacketPlayOutChat(String json) { + WrappedChatComponent component = WrappedChatComponent.fromJson(json); + PacketContainer container = new PacketContainer(PacketType.Play.Server.CHAT); + container.getModifier().writeDefaults(); + container.getChatComponents().write(0, component); + return container; + } + + public static PacketContainer createPacketPlayOutChat(WrappedChatComponent component) { + PacketContainer container = new PacketContainer(PacketType.Play.Server.CHAT); + container.getModifier().writeDefaults(); + container.getChatComponents().write(0, component); + return container; + } + + public static void sendPacketPlayOutChat(Player player, PacketContainer packet) { + try { + ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet); + } + catch(Exception e) { + e.printStackTrace(); + } + } + + public static String toPlainText(Object o, Class c) { + List finalList = new ArrayList<>(); + StringBuilder stringbuilder = new StringBuilder(); + try { + splitComponents(finalList, o, c); + for(Object component : finalList) { + if(VersionHandler.is1_7_10()) { + stringbuilder.append((String) component.getClass().getMethod("e").invoke(component)); + } + else { + stringbuilder.append((String) component.getClass().getMethod("getText").invoke(component)); + } + } + } + catch(Exception e) { + e.printStackTrace(); + } + if(plugin.getConfig().getString("loglevel", "info").equals("debug")) { + System.out.println("my string"); + System.out.println("my string"); + System.out.println("my string"); + System.out.println("my string"); + System.out.println("my string"); + System.out.println(stringbuilder.toString()); + } + return stringbuilder.toString(); + } + + private static void splitComponents(List finalList, Object o, Class c) throws Exception { + if(plugin.getConfig().getString("loglevel", "info").equals("debug")) { + for(Method m : c.getMethods()) { + System.out.println(m.getName()); + } + } + if(VersionHandler.is1_7() || VersionHandler.is1_8() || VersionHandler.is1_9() || VersionHandler.is1_10() || VersionHandler.is1_11() || VersionHandler.is1_12() || VersionHandler.is1_13() || (VersionHandler.is1_14() && !VersionHandler.is1_14_4())) { + ArrayList list = (ArrayList) c.getMethod("a").invoke(o, new Object[0]); + for(Object component : list) { + ArrayList innerList = (ArrayList) c.getMethod("a").invoke(component, new Object[0]); + if(innerList.size() > 0) { + splitComponents(finalList, component, c); + } + else { + finalList.add(component); + } + } + } + else { + ArrayList list = (ArrayList) c.getMethod("getSiblings").invoke(o, new Object[0]); + for(Object component : list) { + ArrayList innerList = (ArrayList) c.getMethod("getSiblings").invoke(component, new Object[0]); + if(innerList.size() > 0) { + splitComponents(finalList, component, c); + } + else { + finalList.add(component); + } + } + } + }*/ + + protected static Pattern chatHexColorPattern = Pattern.compile("(?i)&([X])"); + protected static Pattern chatColorPattern = Pattern.compile("(?i)&([0-9A-F])"); + protected static Pattern chatMagicPattern = Pattern.compile("(?i)&([K])"); + protected static Pattern chatBoldPattern = Pattern.compile("(?i)&([L])"); + protected static Pattern chatStrikethroughPattern = Pattern.compile("(?i)&([M])"); + protected static Pattern chatUnderlinePattern = Pattern.compile("(?i)&([N])"); + protected static Pattern chatItalicPattern = Pattern.compile("(?i)&([O])"); + protected static Pattern chatResetPattern = Pattern.compile("(?i)&([R])"); + + public static String FormatStringColor(String string) { + String allFormated = string; + allFormated = chatColorPattern.matcher(allFormated).replaceAll("\u00A7$1"); + allFormated = chatHexColorPattern.matcher(allFormated).replaceAll("\u00A7$1"); + allFormated = allFormated.replaceAll("%", "\\%"); + + allFormated = convertHexColorCodeStringToBukkitColorCodeString(allFormated); + return allFormated; + } + + public static String FormatString(String string) { + String allFormated = string; + allFormated = chatMagicPattern.matcher(allFormated).replaceAll("\u00A7$1"); + allFormated = chatBoldPattern.matcher(allFormated).replaceAll("\u00A7$1"); + allFormated = chatStrikethroughPattern.matcher(allFormated).replaceAll("\u00A7$1"); + allFormated = chatUnderlinePattern.matcher(allFormated).replaceAll("\u00A7$1"); + allFormated = chatItalicPattern.matcher(allFormated).replaceAll("\u00A7$1"); + allFormated = chatResetPattern.matcher(allFormated).replaceAll("\u00A7$1"); + allFormated = allFormated.replaceAll("%", "\\%"); + return allFormated; + } + + public static String FormatStringAll(String string) { + String allFormated = Format.FormatString(string); + allFormated = Format.FormatStringColor(allFormated); + return allFormated; + } + + public static String FormatPlayerName(String playerPrefix, String playerDisplayName, String playerSuffix) { + playerPrefix = chatColorPattern.matcher(playerPrefix).replaceAll("\u00A7$1"); + playerPrefix = chatMagicPattern.matcher(playerPrefix).replaceAll("\u00A7$1"); + playerPrefix = chatBoldPattern.matcher(playerPrefix).replaceAll("\u00A7$1"); + playerPrefix = chatStrikethroughPattern.matcher(playerPrefix).replaceAll("\u00A7$1"); + playerPrefix = chatUnderlinePattern.matcher(playerPrefix).replaceAll("\u00A7$1"); + playerPrefix = chatItalicPattern.matcher(playerPrefix).replaceAll("\u00A7$1"); + playerPrefix = chatResetPattern.matcher(playerPrefix).replaceAll("\u00A7$1"); + + playerSuffix = chatColorPattern.matcher(playerSuffix).replaceAll("\u00A7$1"); + playerSuffix = chatMagicPattern.matcher(playerSuffix).replaceAll("\u00A7$1"); + playerSuffix = chatBoldPattern.matcher(playerSuffix).replaceAll("\u00A7$1"); + playerSuffix = chatStrikethroughPattern.matcher(playerSuffix).replaceAll("\u00A7$1"); + playerSuffix = chatUnderlinePattern.matcher(playerSuffix).replaceAll("\u00A7$1"); + playerSuffix = chatItalicPattern.matcher(playerSuffix).replaceAll("\u00A7$1"); + playerSuffix = chatResetPattern.matcher(playerSuffix).replaceAll("\u00A7$1"); + return playerPrefix + playerDisplayName.trim() + playerSuffix; + } + + /**public static String FilterChat(String msg) { + int t = 0; + List filters = plugin.getConfig().getStringList("filters"); + for(String s : filters) { + t = 0; + String[] pparse = new String[2]; + pparse[0] = " "; + pparse[1] = " "; + StringTokenizer st = new StringTokenizer(s, ","); + while(st.hasMoreTokens()) { + if(t < 2) { + pparse[t++] = st.nextToken(); + } + } + msg = msg.replaceAll("(?i)" + pparse[0], pparse[1]); + } + return msg; + }*/ + + public static boolean isValidColor(String color) { + Boolean bFound = false; + for(ChatColor bkColors : ChatColor.values()) { + if(color.equalsIgnoreCase(bkColors.name())) { + bFound = true; + } + } + return bFound; + } + + public static boolean isValidHexColor(String color) { + Pattern pattern = Pattern.compile("(^#[0-9a-fA-F]{6}\\b)"); + Matcher matcher = pattern.matcher(color); + return matcher.find(); + } + + public static String convertHexColorCodeToBukkitColorCode(String color) { + StringBuilder bukkitColorCode = new StringBuilder(BUKKIT_COLOR_CODE_PREFIX + BUKKIT_HEX_COLOR_CODE_PREFIX); + for(int a = 1; a < color.length(); a++) { + bukkitColorCode.append(BUKKIT_COLOR_CODE_PREFIX + color.charAt(a)); + } + return bukkitColorCode.toString(); + } + + public static String convertHexColorCodeStringToBukkitColorCodeString(String string) { + Pattern pattern = Pattern.compile("(#[0-9a-fA-F]{6})"); + Matcher matcher = pattern.matcher(string); + while(matcher.find()) { + int indexStart = matcher.start(); + int indexEnd = matcher.end(); + String hexColor = string.substring(indexStart, indexEnd); + String bukkitColor = convertHexColorCodeToBukkitColorCode(hexColor); + string = string.replaceAll(hexColor, bukkitColor); + matcher.reset(string); + } + return string; + } + + public static String escapeAllRegex(String input) { + return input.replace("[", "\\[").replace("]", "\\]").replace("{", "\\{").replace("}", "\\}").replace("(", "\\(").replace(")", "\\)").replace("|", "\\|").replace("+", "\\+").replace("*", "\\*"); + } + + /**public static boolean underlineURLs() { + return plugin.getConfig().getBoolean("underlineurls", true); + }*/ + public static final char colorChar = '\u00a7'; + //code taken from bukkit, so it can work on bungee too + public static String color(String textToTranslate){ + if (textToTranslate == null) return null; + if (!textToTranslate.contains("&")) return textToTranslate; + char[] b = textToTranslate.toCharArray(); + for (int i = 0; i < b.length - 1; i++) { + if ((b[i] == '&') && ("0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[(i + 1)]) > -1)){ + b[i] = colorChar; + b[(i + 1)] = Character.toLowerCase(b[(i + 1)]); + } + } + return new String(b); + } +} \ No newline at end of file diff --git a/src/com/github/joelgodofwar/sps/util/UpdateChecker.java b/src/com/github/joelgodofwar/sps/util/UpdateChecker.java new file mode 100644 index 0000000..dbb1756 --- /dev/null +++ b/src/com/github/joelgodofwar/sps/util/UpdateChecker.java @@ -0,0 +1,127 @@ +package com.github.joelgodofwar.sps.util; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; + +import org.apache.commons.lang.math.NumberUtils; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +public class UpdateChecker { + private static int project; + private URL checkURL; + private String newVersion; + private String async_newVersion; + private String newMinVers; + private String oldVersion; + private String oldMinVers; + @SuppressWarnings("unused") + private JavaPlugin plugin; + String[] strVersionNew; // [0]=1.14 [1]=1.0.0.? + String[] strVersionCurrent; // [0]=1.14 [1]=1.0.0.? + + + public UpdateChecker(JavaPlugin plugin, int projectID, String verURL) { + this.plugin = plugin; + project = projectID; + async_newVersion = plugin.getDescription().getVersion(); + try { + checkURL = new URL(verURL.replace("{vers}", async_newVersion.substring(0, 4))); + }catch(MalformedURLException e) { + Bukkit.getLogger().warning(Ansi.RED + "Could not connect to update server."); + //Bukkit.getPluginManager().disablePlugin(plugin); + } + } + public UpdateChecker(String plugin, int projectID, String verURL) { + async_newVersion = plugin; + try { + checkURL = new URL(verURL.replace("{vers}", async_newVersion.substring(0, 4))); + }catch(MalformedURLException e) { + Bukkit.getLogger().warning(Ansi.RED + "Could not connect to update server."); + //Bukkit.getPluginManager().disablePlugin(plugin); + } + } + public static String getResourceUrl() {return "https://spigotmc.org/resources/" + project;} + public boolean checkForUpdates() throws Exception { + boolean isOutdated = false; + URLConnection con = checkURL.openConnection(); + newVersion = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine(); + strVersionNew = newVersion.split("_"); // Split into minimum MC version and version + + newMinVers = strVersionNew[0]; + newVersion = strVersionNew[1]; + //System.out.println("newVersion=" + newVersion); + Version newVers = new Version(newVersion); + + strVersionCurrent = async_newVersion.split("_"); + + oldMinVers = strVersionCurrent[0]; + oldVersion = strVersionCurrent[1]; + //System.out.println("oldVersion=" + oldVersion); + Version oldVers = new Version(oldVersion); + + if(oldVers.isDev()){ /** If currently on Dev version, ignore build -1 from Patch */ + if(newVers.Major() > oldVers.Major()){isOutdated = true;} + if(newVers.Major() == oldVers.Major()){/** same do nothing */} + if(newVers.Minor() > oldVers.Minor()){isOutdated = true;} + else if(newVers.Minor() == oldVers.Minor()){/** same do nothing */} + if(newVers.Patch() > (oldVers.Patch() - 1)){isOutdated = true;} + else if(newVers.Patch() == (oldVers.Patch() - 1)){/** same do nothing */} + /**if(newVers.Build() > oldVers.Build()){isOutdated = true;} + else if(newVers.Build() == oldVers.Build()){/** same do nothing }*/ + }else { + if(newVers.Major() > oldVers.Major()){isOutdated = true;} + if(newVers.Major() == oldVers.Major()){/** same do nothing */} + if(newVers.Minor() > oldVers.Minor()){isOutdated = true;} + else if(newVers.Minor() == oldVers.Minor()){/** same do nothing */} + if(newVers.Patch() > oldVers.Patch()){isOutdated = true;} + else if(newVers.Patch() == oldVers.Patch()){/** same do nothing */} + if(newVers.Build() > oldVers.Build()){isOutdated = true;} + else if(newVers.Build() == oldVers.Build()){/** same do nothing */} + } + return isOutdated; //plugin.getDescription().getVersion().equals(newVersion); TODO: + } + public String newVersion(){ + return newMinVers + "_" + newVersion; + } + public String oldVersion(){ + return oldMinVers + "_" + oldVersion; + } + + public class Version{ + private int Major; // 1 + private int Minor; // 16 + private int Patch; // 1 + private int Build; // ? + private boolean isDev = false; + private String[] string2 = {"0","0","0","0"}; + public Version(String string){ + //System.out.println("string=" + string); + string2 = string.split("\\."); + //for (String a : string2) + //System.out.println(a); + //System.out.println("string2=" + string2.toString()); + //System.out.println("string2.length=" + string2.length); + this.Major = NumberUtils.toInt(string2[0]); + this.Minor = NumberUtils.toInt(string2[1]); + this.Patch = NumberUtils.toInt(string2[2]); + if(string2.length >= 4){ + if(string2[3].toUpperCase().contains("D")){ + isDev = true; + string2[3] = string2[3].toUpperCase().replace("D", ""); + } + this.Build = NumberUtils.toInt(string2[3]); + }else{ + this.Build = 0; + } + } + public int Major(){return Major;} + public int Minor(){return Minor;} + public int Patch(){return Patch;} + public int Build(){return Build;} + public boolean isDev(){return isDev;} + } +} \ No newline at end of file diff --git a/src/com/github/joelgodofwar/sps/util/Utils.java b/src/com/github/joelgodofwar/sps/util/Utils.java new file mode 100644 index 0000000..94cbc79 --- /dev/null +++ b/src/com/github/joelgodofwar/sps/util/Utils.java @@ -0,0 +1,15 @@ +package com.github.joelgodofwar.sps.util; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class Utils { + + public static void sendJson(CommandSender player, String string){ + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw \"" + player.getName() + "\" " + string); + } + public static void sendJson(Player player, String string){ + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw \"" + player.getName() + "\" " + string); + } +} diff --git a/src/com/github/joelgodofwar/sps/util/VersionChecker.java b/src/com/github/joelgodofwar/sps/util/VersionChecker.java new file mode 100644 index 0000000..8729da6 --- /dev/null +++ b/src/com/github/joelgodofwar/sps/util/VersionChecker.java @@ -0,0 +1,220 @@ +package com.github.joelgodofwar.sps.util; + +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.List; +//import java.util.Scanner; +//import java.io.IOException; +//import java.io.InputStream; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.DocumentBuilder; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +@SuppressWarnings("unused") +public class VersionChecker { + private String pluginName; + private JavaPlugin plugin; + private int projectID; + private String currentVersion; + private String githubURL; // = "https://github.com/JoelGodOfwar/NoEndermanGrief/raw/master/versions/1.14/versions.xml"; + String versionType; + private List releaseList = new ArrayList<>(); + private List developerList = new ArrayList<>(); + private String recommendedVersion = "uptodate"; + + public VersionChecker(JavaPlugin plugin, int projectID, String githubURL) { + this.plugin = plugin; + this.projectID = projectID; + this.currentVersion = plugin.getDescription().getVersion(); + this.githubURL = githubURL; + } + + public VersionChecker(String plugin, int projectID, String githubURL) { + this.currentVersion = plugin; + this.projectID = projectID; + this.githubURL = githubURL; + } + + public String getReleaseUrl() {return "https://spigotmc.org/resources/" + projectID;} + + public boolean checkForUpdates() throws Exception { + URL url = new URL(githubURL); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + URLConnection connection = url.openConnection(); + connection.setUseCaches(false); + connection.setRequestProperty("Cache-Control", "no-cache, no-store, must-revalidate"); + Document doc = db.parse(connection.getInputStream()); + doc.getDocumentElement().normalize(); + NodeList releaseNodes = doc.getElementsByTagName("release"); + for (int i = 0; i < releaseNodes.getLength(); i++) { + Node node = releaseNodes.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element element = (Element) node; + releaseList.add(element.getElementsByTagName("version").item(0).getTextContent().replace("", "").replace("", "")); + releaseList.add(element.getElementsByTagName("notes").item(0).getTextContent().replace("", "").replace("", "")); + releaseList.add(element.getElementsByTagName("link").item(0).getTextContent().replace("", "").replace("", "")); + } + } + NodeList developerNodes = doc.getElementsByTagName("developer"); + for (int i = 0; i < developerNodes.getLength(); i++) { + Node node = developerNodes.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element element = (Element) node; + developerList.add(element.getElementsByTagName("version").item(0).getTextContent().replace("", "").replace("", "")); + developerList.add(element.getElementsByTagName("notes").item(0).getTextContent().replace("", "").replace("", "")); + developerList.add(element.getElementsByTagName("link").item(0).getTextContent().replace("", "").replace("", "")); + } + } + + if (connection != null) { + connection.getInputStream().close(); + } + String releaseVersion = releaseList.get(0); + String developerVersion = developerList.get(0); + //Bukkit.getLogger().warning(Ansi.RED + "currentVersion=" + currentVersion); + //Bukkit.getLogger().warning(Ansi.RED + "releaseVersion=" + releaseVersion); + //Bukkit.getLogger().warning(Ansi.RED + "developerVersion=" + developerVersion); + if (currentVersion.compareTo(releaseVersion) < 0) { + recommendedVersion = "release"; + return true; + } else if (currentVersion.equals(releaseVersion)) { + recommendedVersion = "uptodate"; + return false; + } else if (currentVersion.contains(".D")) { + String[] splitCurrentVersion = currentVersion.split("\\.D"); + String currentReleaseVersion = splitCurrentVersion[0]; + String[] splitDeveloperVersion = developerVersion.split("\\.D"); + String developerReleaseVersion = splitDeveloperVersion[0]; + if (currentReleaseVersion.equals(releaseVersion) && developerReleaseVersion.compareTo(currentReleaseVersion) <= 0) { + recommendedVersion = "release"; + return true; + } else if (developerReleaseVersion.compareTo(releaseVersion) < 0 && developerReleaseVersion.equals(currentReleaseVersion)) { + recommendedVersion = "You are Up To Date"; + return false; + } else if (developerVersion.compareTo(currentVersion) > 0) { + recommendedVersion = "developer"; + return true; + } + } + + return false; + } + public List getReleaseList() { + return releaseList; + } + public List getDeveloperList() { + return developerList; + } + public String getRecommendedVersion() { + return recommendedVersion; + } + public String oldVersion() { + return currentVersion; + } + public String newVersion() { + if(recommendedVersion.equalsIgnoreCase("release")) { + return releaseList.get(0); + }else if(recommendedVersion.equalsIgnoreCase("developer")) { + return developerList.get(0); + }else { + return "UpToDate"; + } + } + public String newVersionNotes() { + if (recommendedVersion.equalsIgnoreCase("release")) { + return releaseList.get(1); + } else if (recommendedVersion.equalsIgnoreCase("developer")) { + return developerList.get(1); + } else { + return "UpToDate"; + } + } + public String getDownloadLink() { + if (recommendedVersion.equalsIgnoreCase("release")) { + return releaseList.get(2);//"https://www.spigotmc.org/resources/no-enderman-grief2.71236/history"; + } else if (recommendedVersion.equalsIgnoreCase("developer")) { + return developerList.get(2);//"https://discord.com/channels/654087250665144321/654444482372173875"; + } else { + return "UpToDate"; + } + } + + /**public boolean checkForUpdates2() { + if(currentVersion.contains(".D")){ + versionType = "developer"; + }else{ + versionType = "release"; + } + String[] versionArray = getLatestVersion(versionType); + + if (versionArray == null) { + Bukkit.getLogger().warning(Ansi.RED + "Could not connect to update server."); + return false; + } + + String latestVersion = versionArray[0]; + String latestNotes = versionArray[1]; + + if (latestVersion.equals(currentVersion)) { + return false; + } else { + System.out.println("There is a new version of " + pluginName + " available!"); + System.out.println("Your version: " + currentVersion); + System.out.println("Latest version: " + latestVersion); + System.out.println("Update notes: " + latestNotes); + System.out.println("Please update to the newest version."); + System.out.println("Download: https://www.spigotmc.org/resources/" + pluginName + ".75749/history"); + System.out.println("Donate: "); + return true; + } + }//*/ + + /**private String[] getLatestVersion(String versionType) { + try { + URL url = new URL(githubURL); + InputStream stream = url.openStream(); + Scanner scanner = new Scanner(stream); + scanner.useDelimiter("\\Z"); + String xmlContent = scanner.next(); + scanner.close(); + stream.close(); + + String versionTag = "<" + versionType + ">"; + String notesTag = "<" + versionType + "-notes>"; + String endTag = ""; + + int versionStartIndex = xmlContent.indexOf(versionTag); + int notesStartIndex = xmlContent.indexOf(notesTag); + int versionEndIndex = xmlContent.indexOf(endTag); + + if (versionStartIndex == -1 || notesStartIndex == -1 || versionEndIndex == -1) { + return null; + } + + String versionNumber = xmlContent.substring(versionStartIndex + versionTag.length(), versionEndIndex); + String notes = xmlContent.substring(notesStartIndex + notesTag.length(), xmlContent.indexOf(endTag + "-notes>")); + String[] versionArray = new String[2]; + versionArray[0] = versionNumber; + versionArray[1] = notes; + return versionArray; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + }//*/ + + /**public static void main(String[] args) { + //String pluginName = "MyPlugin"; + String currentVersion = "1.14_1.0.4"; + String githubURL = "https://github.com/JoelGodOfwar/NoEndermanGrief/raw/master/versions/1.14/versions.xml"; + VersionChecker checker = new VersionChecker(currentVersion, 71236, githubURL); + checker.checkForUpdates(); + }//*/ +} diff --git a/src/jdk/internal/joptsimple/internal/Strings.java b/src/jdk/internal/joptsimple/internal/Strings.java new file mode 100644 index 0000000..7928623 --- /dev/null +++ b/src/jdk/internal/joptsimple/internal/Strings.java @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * This file is available under and governed by the GNU General Public + * License version 2 only, as published by the Free Software Foundation. + * However, the following notice accompanied the original version of this + * file: + * + * The MIT License + * + * Copyright (c) 2004-2015 Paul R. Holser, Jr. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package jdk.internal.joptsimple.internal; + +import static java.lang.System.getProperty; +import static java.util.Arrays.asList; + +import java.util.Iterator; + +/** + * @author Paul Holser + */ +public final class Strings { + public static final String EMPTY = ""; + public static final String LINE_SEPARATOR = getProperty( "line.separator" ); + + private Strings() { + throw new UnsupportedOperationException(); + } + + /** + * Gives a string consisting of the given character repeated the given number of times. + * + * @param ch the character to repeat + * @param count how many times to repeat the character + * @return the resultant string + */ + public static String repeat( char ch, int count ) { + StringBuilder buffer = new StringBuilder(); + + for ( int i = 0; i < count; ++i ) + buffer.append( ch ); + + return buffer.toString(); + } + + /** + * Tells whether the given string is either {@code} or consists solely of whitespace characters. + * + * @param target string to check + * @return {@code true} if the target string is null or empty + */ + public static boolean isNullOrEmpty( String target ) { + return target == null || target.isEmpty(); + } + + + /** + * Gives a string consisting of a given string prepended and appended with surrounding characters. + * + * @param target a string + * @param begin character to prepend + * @param end character to append + * @return the surrounded string + */ + public static String surround( String target, char begin, char end ) { + return begin + target + end; + } + + /** + * Gives a string consisting of the elements of a given array of strings, each separated by a given separator + * string. + * + * @param pieces the strings to join + * @param separator the separator + * @return the joined string + */ + public static String join( String[] pieces, String separator ) { + return join( asList( pieces ), separator ); + } + + /** + * Gives a string consisting of the string representations of the elements of a given array of objects, + * each separated by a given separator string. + * + * @param pieces the elements whose string representations are to be joined + * @param separator the separator + * @return the joined string + */ + public static String join( Iterable pieces, String separator ) { + StringBuilder buffer = new StringBuilder(); + + for ( Iterator iter = pieces.iterator(); iter.hasNext(); ) { + buffer.append( iter.next() ); + + if ( iter.hasNext() ) + buffer.append( separator ); + } + + return buffer.toString(); + } +} \ No newline at end of file