NotificationManager.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package com.gmail.nossr50.util.player;
  2. import com.gmail.nossr50.config.AdvancedConfig;
  3. import com.gmail.nossr50.config.Config;
  4. import com.gmail.nossr50.datatypes.LevelUpBroadcastPredicate;
  5. import com.gmail.nossr50.datatypes.PowerLevelUpBroadcastPredicate;
  6. import com.gmail.nossr50.datatypes.interactions.NotificationType;
  7. import com.gmail.nossr50.datatypes.notifications.SensitiveCommandType;
  8. import com.gmail.nossr50.datatypes.skills.CoreSkills;
  9. import com.gmail.nossr50.util.Misc;
  10. import com.neetgames.mcmmo.player.OnlineMMOPlayer;
  11. import com.gmail.nossr50.datatypes.skills.SubSkillType;
  12. import com.gmail.nossr50.events.skills.McMMOPlayerNotificationEvent;
  13. import com.gmail.nossr50.locale.LocaleLoader;
  14. import com.gmail.nossr50.mcMMO;
  15. import com.gmail.nossr50.util.Permissions;
  16. import com.gmail.nossr50.util.sounds.SoundManager;
  17. import com.gmail.nossr50.util.sounds.SoundType;
  18. import com.gmail.nossr50.util.text.McMMOMessageType;
  19. import com.gmail.nossr50.util.text.TextComponentFactory;
  20. import com.neetgames.mcmmo.skill.RootSkill;
  21. import net.kyori.adventure.audience.Audience;
  22. import net.kyori.adventure.audience.MessageType;
  23. import net.kyori.adventure.identity.Identity;
  24. import net.kyori.adventure.text.Component;
  25. import net.kyori.adventure.text.event.HoverEvent;
  26. import net.kyori.adventure.text.format.TextColor;
  27. import org.bukkit.Bukkit;
  28. import org.bukkit.ChatColor;
  29. import org.bukkit.Server;
  30. import org.bukkit.SoundCategory;
  31. import org.bukkit.command.CommandSender;
  32. import org.bukkit.entity.Player;
  33. import org.jetbrains.annotations.NotNull;
  34. import java.time.LocalDate;
  35. public class NotificationManager {
  36. public static final String HEX_BEIGE_COLOR = "#c2a66e";
  37. public static final String HEX_LIME_GREEN_COLOR = "#8ec26e";
  38. /**
  39. * Sends players notifications from mcMMO
  40. * Does so by sending out an event so other plugins can cancel it
  41. * @param player target player
  42. * @param notificationType notifications defined type
  43. * @param key the locale key for the notifications defined message
  44. */
  45. public static void sendPlayerInformation(@NotNull Player player, @NotNull NotificationType notificationType, @NotNull String key)
  46. {
  47. OnlineMMOPlayer mmoPlayer = mcMMO.getUserManager().queryPlayer(player);
  48. if(mmoPlayer == null || !mmoPlayer.hasSkillChatNotifications())
  49. return;
  50. McMMOMessageType destination = AdvancedConfig.getInstance().doesNotificationUseActionBar(notificationType) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM;
  51. Component message = TextComponentFactory.getNotificationTextComponentFromLocale(key);
  52. McMMOPlayerNotificationEvent customEvent = checkNotificationEvent(player, notificationType, destination, message);
  53. sendNotification(player, customEvent);
  54. }
  55. public static boolean doesPlayerUseNotifications(@NotNull Player player)
  56. {
  57. OnlineMMOPlayer mmoPlayer = mcMMO.getUserManager().queryPlayer(player);
  58. if(mmoPlayer == null)
  59. return false;
  60. else
  61. return mmoPlayer.hasSkillChatNotifications();
  62. }
  63. /**
  64. * Sends players notifications from mcMMO
  65. * This does this by sending out an event so other plugins can cancel it
  66. * This event in particular is provided with a source player, and players near the source player are sent the information
  67. *
  68. * @param targetPlayer the recipient player for this message
  69. * @param notificationType type of notification
  70. * @param key Locale Key for the string to use with this event
  71. * @param values values to be injected into the locale string
  72. */
  73. public static void sendNearbyPlayersInformation(@NotNull Player targetPlayer, @NotNull NotificationType notificationType, @NotNull String key, String... values) {
  74. sendPlayerInformation(targetPlayer, notificationType, key, values);
  75. }
  76. public static void sendPlayerInformationChatOnly(@NotNull Player player, @NotNull String key, String... values) {
  77. OnlineMMOPlayer mmoPlayer = mcMMO.getUserManager().queryPlayer(player);
  78. //Don't send chat notifications if they are disabled
  79. if(mmoPlayer != null && !mmoPlayer.hasSkillChatNotifications())
  80. return;
  81. String preColoredString = LocaleLoader.getString(key, (Object[]) values);
  82. player.sendMessage(preColoredString);
  83. }
  84. public static void sendPlayerInformationChatOnlyPrefixed(@NotNull Player player, @NotNull String key, String... values)
  85. {
  86. OnlineMMOPlayer mmoPlayer = mcMMO.getUserManager().queryPlayer(player);
  87. //Don't send chat notifications if they are disabled
  88. if(mmoPlayer != null && !mmoPlayer.hasSkillChatNotifications())
  89. return;
  90. String preColoredString = LocaleLoader.getString(key, (Object[]) values);
  91. String prefixFormattedMessage = LocaleLoader.getString("mcMMO.Template.Prefix", preColoredString);
  92. player.sendMessage(prefixFormattedMessage);
  93. }
  94. public static void sendPlayerInformation(@NotNull Player player, @NotNull NotificationType notificationType, @NotNull String key, String... values) {
  95. OnlineMMOPlayer mmoPlayer = mcMMO.getUserManager().queryPlayer(player);
  96. //Don't send chat notifications if they are disabled
  97. if(mmoPlayer != null && !mmoPlayer.hasSkillChatNotifications())
  98. return;
  99. McMMOMessageType destination = AdvancedConfig.getInstance().doesNotificationUseActionBar(notificationType) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM;
  100. Component message = TextComponentFactory.getNotificationMultipleValues(key, values);
  101. McMMOPlayerNotificationEvent customEvent = checkNotificationEvent(player, notificationType, destination, message);
  102. sendNotification(player, customEvent);
  103. }
  104. private static void sendNotification(@NotNull Player player, @NotNull McMMOPlayerNotificationEvent customEvent) {
  105. if (customEvent.isCancelled())
  106. return;
  107. final Audience audience = mcMMO.getAudiences().player(player);
  108. //If the message is being sent to the action bar we need to check if the copy if a copy is sent to the chat system
  109. if(customEvent.getChatMessageType() == McMMOMessageType.ACTION_BAR)
  110. {
  111. audience.sendActionBar(customEvent.getNotificationTextComponent());
  112. if(customEvent.isMessageAlsoBeingSentToChat())
  113. {
  114. //Send copy to chat system
  115. audience.sendMessage(Identity.nil(), customEvent.getNotificationTextComponent(), MessageType.SYSTEM);
  116. }
  117. } else {
  118. audience.sendMessage(Identity.nil(), customEvent.getNotificationTextComponent(), MessageType.SYSTEM);
  119. }
  120. }
  121. private static @NotNull McMMOPlayerNotificationEvent checkNotificationEvent(@NotNull Player player, @NotNull NotificationType notificationType, @NotNull McMMOMessageType destination, @NotNull Component message) {
  122. //Init event
  123. McMMOPlayerNotificationEvent customEvent = new McMMOPlayerNotificationEvent(player,
  124. notificationType, message, destination, AdvancedConfig.getInstance().doesNotificationSendCopyToChat(notificationType));
  125. //Call event
  126. Bukkit.getServer().getPluginManager().callEvent(customEvent);
  127. return customEvent;
  128. }
  129. /**
  130. * Handles sending level up notifications to a mmoPlayer
  131. * @param mmoPlayer target mmoPlayer
  132. * @param rootSkill skill that leveled up
  133. * @param newLevel new level of that skill
  134. */
  135. public static void sendPlayerLevelUpNotification(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull RootSkill rootSkill, int levelsGained, int newLevel)
  136. {
  137. if(!mmoPlayer.hasSkillChatNotifications())
  138. return;
  139. McMMOMessageType destination = AdvancedConfig.getInstance().doesNotificationUseActionBar(NotificationType.LEVEL_UP_MESSAGE) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM;
  140. Component levelUpTextComponent = TextComponentFactory.getNotificationLevelUpTextComponent(CoreSkills.getSkill(rootSkill), levelsGained, newLevel);
  141. McMMOPlayerNotificationEvent customEvent = checkNotificationEvent(Misc.adaptPlayer(mmoPlayer), NotificationType.LEVEL_UP_MESSAGE, destination, levelUpTextComponent);
  142. sendNotification(Misc.adaptPlayer(mmoPlayer), customEvent);
  143. }
  144. public static void broadcastTitle(@NotNull Server server, @NotNull String title, @NotNull String subtitle, int i1, int i2, int i3)
  145. {
  146. for(Player player : server.getOnlinePlayers())
  147. {
  148. player.sendTitle(title, subtitle, i1, i2, i3);
  149. }
  150. }
  151. public static void sendPlayerUnlockNotification(@NotNull OnlineMMOPlayer mmoPlayer, @NotNull SubSkillType subSkillType)
  152. {
  153. if(!mmoPlayer.hasSkillChatNotifications())
  154. return;
  155. //CHAT MESSAGE
  156. mcMMO.getAudiences().player(Misc.adaptPlayer(mmoPlayer)).sendMessage(Identity.nil(), TextComponentFactory.getSubSkillUnlockedNotificationComponents(mmoPlayer, subSkillType));
  157. //Unlock Sound Effect
  158. SoundManager.sendCategorizedSound(Misc.adaptPlayer(mmoPlayer), Misc.adaptPlayer(mmoPlayer).getLocation(), SoundType.SKILL_UNLOCKED, SoundCategory.MASTER);
  159. //ACTION BAR MESSAGE
  160. /*if(AdvancedConfig.getInstance().doesNotificationUseActionBar(NotificationType.SUBSKILL_UNLOCKED))
  161. Misc.adaptPlayer(mmoPlayer).spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(LocaleLoader.getString("JSON.SkillUnlockMessage",
  162. subSkillType.getLocaleName(),
  163. String.valueOf(RankUtils.getRank(Misc.adaptPlayer(mmoPlayer),
  164. subSkillType)))));*/
  165. }
  166. /**
  167. * Sends a message to all admins with the admin notification formatting from the locale
  168. * Admins are currently players with either Operator status or Admin Chat permission
  169. * @param msg message fetched from locale
  170. */
  171. private static void sendAdminNotification(@NotNull String msg) {
  172. //If its not enabled exit
  173. if(!Config.getInstance().adminNotifications())
  174. return;
  175. for(Player player : Bukkit.getServer().getOnlinePlayers())
  176. {
  177. if(player.isOp() || Permissions.adminChat(player))
  178. {
  179. player.sendMessage(LocaleLoader.getString("Notifications.Admin.Format.Others", msg));
  180. }
  181. }
  182. //Copy it out to Console too
  183. mcMMO.p.getLogger().info(LocaleLoader.getString("Notifications.Admin.Format.Others", msg));
  184. }
  185. /**
  186. * Sends a confirmation message to the CommandSender who just executed an admin command
  187. * @param commandSender target command sender
  188. * @param msg message fetched from locale
  189. */
  190. private static void sendAdminCommandConfirmation(@NotNull CommandSender commandSender, @NotNull String msg) {
  191. commandSender.sendMessage(LocaleLoader.getString("Notifications.Admin.Format.Self", msg));
  192. }
  193. /**
  194. * Convenience method to report info about a command sender using a sensitive command
  195. * @param commandSender the command user
  196. * @param sensitiveCommandType type of command issued
  197. */
  198. public static void processSensitiveCommandNotification(@NotNull CommandSender commandSender, @NotNull SensitiveCommandType sensitiveCommandType, String... args) {
  199. /*
  200. * Determine the 'identity' of the one who executed the command to pass as a parameters
  201. */
  202. String senderName = LocaleLoader.getString("Server.ConsoleName");
  203. if(commandSender instanceof Player)
  204. {
  205. senderName = ((Player) commandSender).getDisplayName() + ChatColor.RESET + "-" + ((Player) commandSender).getUniqueId();
  206. }
  207. //Send the notification
  208. switch(sensitiveCommandType)
  209. {
  210. case XPRATE_MODIFY:
  211. sendAdminNotification(LocaleLoader.getString("Notifications.Admin.XPRate.Start.Others", addItemToFirstPositionOfArray(senderName, args)));
  212. sendAdminCommandConfirmation(commandSender, LocaleLoader.getString("Notifications.Admin.XPRate.Start.Self", args));
  213. break;
  214. case XPRATE_END:
  215. sendAdminNotification(LocaleLoader.getString("Notifications.Admin.XPRate.End.Others", addItemToFirstPositionOfArray(senderName, args)));
  216. sendAdminCommandConfirmation(commandSender, LocaleLoader.getString("Notifications.Admin.XPRate.End.Self", args));
  217. break;
  218. }
  219. }
  220. /**
  221. * Takes an array and an object, makes a new array with object in the first position of the new array,
  222. * and the following elements in this new array being a copy of the existing array retaining their order
  223. * @param itemToAdd the string to put at the beginning of the new array
  224. * @param existingArray the existing array to be copied to the new array at position [0]+1 relative to their original index
  225. * @return the new array combining itemToAdd at the start and existing array elements following while retaining their order
  226. */
  227. public static @NotNull String[] addItemToFirstPositionOfArray(@NotNull String itemToAdd, @NotNull String... existingArray) {
  228. String[] newArray = new String[existingArray.length + 1];
  229. newArray[0] = itemToAdd;
  230. System.arraycopy(existingArray, 0, newArray, 1, existingArray.length);
  231. return newArray;
  232. }
  233. //TODO: Remove the code duplication, am lazy atm
  234. //TODO: Fix broadcasts being skipped for situations where a player skips over the milestone like with the addlevels command
  235. public static void processLevelUpBroadcasting(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType primarySkillType, int level) {
  236. if(level <= 0)
  237. return;
  238. //Check if broadcasting is enabled
  239. if(Config.getInstance().shouldLevelUpBroadcasts()) {
  240. //Permission check
  241. if(!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) {
  242. return;
  243. }
  244. int levelInterval = Config.getInstance().getLevelUpBroadcastInterval();
  245. int remainder = level % levelInterval;
  246. if(remainder == 0) {
  247. //Grab appropriate audience
  248. Audience audience = mcMMO.getAudiences().filter(getLevelUpBroadcastPredicate(mmoPlayer.getPlayer()));
  249. //TODO: Make prettier
  250. HoverEvent<Component> levelMilestoneHover = Component.text(mmoPlayer.getPlayer().getName())
  251. .append(Component.newline())
  252. .append(Component.text(LocalDate.now().toString()))
  253. .append(Component.newline())
  254. .append(Component.text(primarySkillType.getName()+" reached level "+level)).color(TextColor.fromHexString(HEX_BEIGE_COLOR))
  255. .asHoverEvent();
  256. String localeMessage = LocaleLoader.getString("Broadcasts.LevelUpMilestone", mmoPlayer.getPlayer().getDisplayName(), level, primarySkillType.getName());
  257. Component message = Component.text(localeMessage).hoverEvent(levelMilestoneHover);
  258. Bukkit.getScheduler().runTaskLater(mcMMO.p, () -> audience.sendMessage(Identity.nil(), message), 0);
  259. }
  260. }
  261. }
  262. //TODO: Remove the code duplication, am lazy atm
  263. //TODO: Fix broadcasts being skipped for situations where a player skips over the milestone like with the addlevels command
  264. public static void processPowerLevelUpBroadcasting(@NotNull McMMOPlayer mmoPlayer, int powerLevel) {
  265. if(powerLevel <= 0)
  266. return;
  267. //Check if broadcasting is enabled
  268. if(Config.getInstance().shouldPowerLevelUpBroadcasts()) {
  269. //Permission check
  270. if(!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) {
  271. return;
  272. }
  273. int levelInterval = Config.getInstance().getPowerLevelUpBroadcastInterval();
  274. int remainder = powerLevel % levelInterval;
  275. if(remainder == 0) {
  276. //Grab appropriate audience
  277. Audience audience = mcMMO.getAudiences().filter(getPowerLevelUpBroadcastPredicate(mmoPlayer.getPlayer()));
  278. //TODO: Make prettier
  279. HoverEvent<Component> levelMilestoneHover = Component.text(mmoPlayer.getPlayer().getName())
  280. .append(Component.newline())
  281. .append(Component.text(LocalDate.now().toString()))
  282. .append(Component.newline())
  283. .append(Component.text("Power level has reached "+powerLevel)).color(TextColor.fromHexString(HEX_BEIGE_COLOR))
  284. .asHoverEvent();
  285. String localeMessage = LocaleLoader.getString("Broadcasts.PowerLevelUpMilestone", mmoPlayer.getPlayer().getDisplayName(), powerLevel);
  286. Component message = Component.text(localeMessage).hoverEvent(levelMilestoneHover);
  287. Bukkit.getScheduler().runTaskLater(mcMMO.p, () -> audience.sendMessage(Identity.nil(), message), 0);
  288. }
  289. }
  290. }
  291. //TODO: Could cache
  292. public static @NotNull LevelUpBroadcastPredicate<CommandSender> getLevelUpBroadcastPredicate(@NotNull CommandSender levelUpPlayer) {
  293. return new LevelUpBroadcastPredicate<>(levelUpPlayer);
  294. }
  295. public static @NotNull PowerLevelUpBroadcastPredicate<CommandSender> getPowerLevelUpBroadcastPredicate(@NotNull CommandSender levelUpPlayer) {
  296. return new PowerLevelUpBroadcastPredicate<>(levelUpPlayer);
  297. }
  298. }