PageRenderTime 70ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/wuffy-notification/src/main/java/net/wuffy/notification/types/TwitchAnnouncement.java

https://bitbucket.org/wuffy-official/bot
Java | 172 lines | 133 code | 38 blank | 1 comment | 30 complexity | e7c1d9823a8e0bfa1410eddb76fc27a2 MD5 | raw file
Possible License(s): Apache-2.0
  1. package net.wuffy.notification.types;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.stream.Collectors;
  7. import org.bson.Document;
  8. import com.mongodb.client.MongoCollection;
  9. import com.mongodb.client.model.UpdateOneModel;
  10. import com.mongodb.client.model.WriteModel;
  11. import net.wuffy.common.logger.Logger;
  12. import net.wuffy.common.util.GsonUtil;
  13. import net.wuffy.core.twitch.TwitchAPI;
  14. import net.wuffy.core.twitch.response.TwitchResponse;
  15. import net.wuffy.core.twitch.response.TwitchResponseGame;
  16. import net.wuffy.core.twitch.response.TwitchResponseStream;
  17. import net.wuffy.core.twitch.response.TwitchResponseUser;
  18. import net.wuffy.notification.WebhookQueue;
  19. import net.wuffy.notification.Wuffy;
  20. public class TwitchAnnouncement extends Announcement {
  21. private static final String DEFAULT_EMBED_MESSAGE = "{\"username\":\"Twitch\",\"avatar_url\":\"https://wuffy.eu/pictures/example_avatar_300x300.png\",\"content\":\"@here **%n** ist jetzt live auf Twitch\",\"embeds\":[{\"title\":\"%t\",\"url\":\"%urll\",\"color\":6570405,\"timestamp\":\"%sa\",\"thumbnail\":{\"url\":\"%urlg300x300\"},\"image\":{\"url\":\"%urlt580x900\"},\"author\":{\"name\":\"%n\",\"url\":\"%urll\",\"icon_url\":\"%urlpi\"},\"footer\":{\"icon_url\":\"%urlpi\",\"text\":\"%n\"},\"fields\":[{\"name\":\"Game\",\"value\":\"%g\",\"inline\":true},{\"name\":\"Viewers\",\"value\":\"%vc\",\"inline\":true}]}]}";
  22. private Map<String, List<Message>> queueNames = new HashMap<String, List<Message>>();
  23. private final TwitchAPI twitchAPI;
  24. public TwitchAnnouncement(MongoCollection<Document> guildCollection, TwitchAPI twitchAPI) {
  25. super(guildCollection, 6000, "Twitch", "TWITCH");
  26. this.twitchAPI = twitchAPI;
  27. }
  28. @Override
  29. protected void update() {
  30. try {
  31. List<String> fetchNames = new ArrayList<String>();
  32. for(String name : this.queueNames.keySet())
  33. if(fetchNames.size() > 100)
  34. break;
  35. else
  36. fetchNames.add(name);
  37. Map<String, List<Message>> messages = new HashMap<String, List<Message>>();
  38. fetchNames.forEach(name -> messages.put(name, this.queueNames.remove(name)));
  39. if(fetchNames.isEmpty()) {
  40. this.running.set(false);
  41. return;
  42. }
  43. Map<String, TwitchResponseUser> users = null;
  44. TwitchResponse<TwitchResponseStream> streams = null;
  45. Map<String, TwitchResponseGame> games = null;
  46. try {
  47. users = this.twitchAPI.getUserHandler().getByName(fetchNames).data.stream().collect(Collectors.toMap(key -> key.id, value -> value));
  48. streams = this.twitchAPI.getStreamHandler().getById(users.keySet().stream().collect(Collectors.toList()));
  49. games = this.twitchAPI.getGameHandler().getById(streams.data.stream()
  50. .filter(data -> data != null && data.game_id != null && data.type != null && data.type.equals("live"))
  51. .map(data -> data.game_id)
  52. .distinct()
  53. .collect(Collectors.toList())).data.stream()
  54. .collect(Collectors.toMap(key -> key.id, value -> value));
  55. } catch(Exception e) {
  56. Logger.fatal("Announcement twitch", "Error by requesting data. waiting 10 seconds and adding all names to the end of the queue again!", e);
  57. this.queueNames.putAll(messages);
  58. Thread.sleep(10000); //Waiting 10 seconds while error
  59. return;
  60. }
  61. List<WriteModel<Document>> writeModels = new ArrayList<WriteModel<Document>>();
  62. for(TwitchResponseStream stream : streams.data) {
  63. if(stream == null || stream.type == null || !stream.type.equals("live"))
  64. continue;
  65. TwitchResponseUser user = users.get(stream.user_id);
  66. for(Message message : messages.get(user.display_name.toLowerCase())) {
  67. if(message.lastUpdate != null && message.lastUpdate.equals(stream.started_at))
  68. continue;
  69. //Update started_at to mongodb
  70. writeModels.add(new UpdateOneModel<Document>(
  71. new Document("_guildId", message.guildId)
  72. .append("notification.TWITCH.name", message.name),
  73. new Document("$set", new Document("notification.TWITCH.$.lastUpdate", stream.started_at))));
  74. WebhookQueue.add(message.webhook, (message.message == null || message.message.isEmpty() ? DEFAULT_EMBED_MESSAGE : message.message)
  75. .replace("%vc", Integer.toString(stream.viewer_count))
  76. .replace("%n", user.display_name)
  77. .replace("%urll", String.format("https://www.twitch.tv/%s", user.display_name))
  78. .replace("%t", stream.title)
  79. .replace("%urlt300x300", stream.thumbnail_url.replace("{width}", "300").replace("{height}", "300"))
  80. .replace("%urlt580x900", stream.thumbnail_url.replace("{width}", "320").replace("{height}", "180"))
  81. .replace("%urlpi", user.profile_image_url)
  82. .replace("%urloi", user.offline_image_url)
  83. .replace("%sa", stream.started_at)
  84. .replace("%g", games.get(stream.game_id).name)
  85. .replace("%urlg300x300", games.get(stream.game_id).box_art_url.replace("{width}", "300").replace("{height}", "300"))
  86. .replace("%urlg580x900", games.get(stream.game_id).box_art_url.replace("{width}", "320").replace("{height}", "180")));
  87. }
  88. }
  89. if(!writeModels.isEmpty())
  90. Wuffy.getInstance().getExtensionGuild().getPrintBatchResult().onResult(Wuffy.getInstance().getGuildCollection().bulkWrite(writeModels), null);
  91. if(this.queueNames.isEmpty())
  92. this.running.set(false);
  93. } catch(Exception e) {
  94. Logger.fatal("Announcement twitch", "Failed to execute. waiting 10 seconds!", e);
  95. this.queueNames.clear();
  96. this.running.set(false);
  97. try {
  98. Thread.sleep(10000);
  99. } catch (InterruptedException e2) {
  100. e2.printStackTrace();
  101. }
  102. }
  103. }
  104. @Override
  105. public void _add(String guildId, List<Document> documents) {
  106. for(Document document : documents) {
  107. Message message = GsonUtil.GSON.fromJson(document.toJson(), Message.class);
  108. if(message != null && message.webhook != null && !message.webhook.isEmpty()) {
  109. message.guildId = guildId;
  110. if(!this.queueNames.containsKey(message.name.toLowerCase()))
  111. this.queueNames.put(message.name.toLowerCase(), new ArrayList<Message>());
  112. this.queueNames.get(message.name.toLowerCase()).add(message);
  113. }
  114. }
  115. }
  116. @Override
  117. protected boolean isQueueEmpty() {
  118. return this.queueNames.isEmpty();
  119. }
  120. class Message {
  121. public String guildId;
  122. public String name;
  123. public String webhook;
  124. public String message;
  125. public String lastUpdate;
  126. public Message(String guildId, String name, String webhook, String message, String lastUpdate) {
  127. this.guildId = guildId;
  128. this.name = name;
  129. this.webhook = webhook;
  130. this.message = message;
  131. this.lastUpdate = lastUpdate;
  132. }
  133. }
  134. }