NotificationManager.java 17 KB

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