PageRenderTime 46ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/wuffy-official/bot
Java | 208 lines | 165 code | 43 blank | 0 comment | 44 complexity | 140801115fbac3d7fbcef8862bffe92e MD5 | raw file
Possible License(s): Apache-2.0
  1. package net.wuffy.notification.types;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. import org.bson.Document;
  8. import com.google.api.services.youtube.model.Channel;
  9. import com.google.api.services.youtube.model.SearchResult;
  10. import com.mongodb.client.MongoCollection;
  11. import com.mongodb.client.model.UpdateOneModel;
  12. import com.mongodb.client.model.WriteModel;
  13. import net.wuffy.common.logger.Logger;
  14. import net.wuffy.common.util.GsonUtil;
  15. import net.wuffy.core.youtube.YoutubeAPI;
  16. import net.wuffy.core.youtube.YoutubeOptionalParameterBuilder;
  17. import net.wuffy.core.youtube.YoutubeOptionalParameters;
  18. import net.wuffy.core.youtube.YoutubePart;
  19. import net.wuffy.notification.WebhookQueue;
  20. import net.wuffy.notification.Wuffy;
  21. public class YoutubeAnnouncement extends Announcement {
  22. private static final String DEFAULT_EMBED_MESSAGE = "{\"username\":\"Youtube\",\"avatar_url\":\"%tm300x300\",\"embeds\":[{\"title\":\"%ti\",\"image\":{\"url\":\"%tm580x900\"},\"url\":\"%u\",\"color\":16711680,\"timestamp\":\"%pa\",\"footer\":{\"icon_url\":\"%tm300x300\",\"text\":\"%ct\"},\"author\":{\"name\":\"%ct\",\"url\":\"%u\",\"icon_url\":\"%tm300x300\"}}]}";
  23. private Map<String, List<Message>> queueNames = new HashMap<String, List<Message>>();
  24. private final YoutubeAPI youtubeAPI;
  25. public YoutubeAnnouncement(MongoCollection<Document> guildCollection, YoutubeAPI youtubeAPI) {
  26. super(guildCollection, 4000, "Youtube", "YOUTUBE");
  27. this.youtubeAPI = youtubeAPI;
  28. }
  29. @Override
  30. protected void update() {
  31. try {
  32. if(this.queueNames.isEmpty()) {
  33. this.running.set(false);
  34. return;
  35. }
  36. String id = this.queueNames.keySet().toArray()[0].toString();
  37. List<Message> messages = this.queueNames.remove(id);
  38. Channel channel = null;
  39. List<SearchResult> searches = null;
  40. try {
  41. channel = this.youtubeAPI.getChannelHandler().getById(id,
  42. YoutubePart.ID,
  43. YoutubePart.SNIPPET).getItems().get(0);
  44. searches = this.youtubeAPI.getSearchHandler().get(new YoutubeOptionalParameterBuilder()
  45. .add(YoutubeOptionalParameters.CHANNELID, id)
  46. .add(YoutubeOptionalParameters.ORDER, "date")
  47. .add(YoutubeOptionalParameters.TYPE, "video")
  48. .add(YoutubeOptionalParameters.MAXRESULTS, 5),
  49. YoutubePart.SNIPPET).getItems();
  50. } catch(Exception e) {
  51. Logger.fatal("Announcement youtube", "Error by requesting data. waiting 10 seconds and adding id to the end of the queue again!", e);
  52. this.queueNames.put(id, messages);
  53. Thread.sleep(10000); //Waiting 10 seconds while error
  54. }
  55. if(searches == null || searches.isEmpty())
  56. return;
  57. List<WriteModel<Document>> writeModels = new ArrayList<WriteModel<Document>>();
  58. for(Message message : messages) {
  59. String last = null;
  60. String lastLive = null;
  61. List<String> webhookMessages = null;
  62. for(SearchResult result : searches) {
  63. if(result.getSnippet().getLiveBroadcastContent().equals("live")) {
  64. if(message.lastUpdateLiveStream != null && message.lastUpdateLiveStream.equals(result.getId().getVideoId()))
  65. break;
  66. if(lastLive == null)
  67. lastLive = result.getId().getVideoId();
  68. } else {
  69. if(message.lastUpdate != null && message.lastUpdate.equals(result.getId().getVideoId()))
  70. break;
  71. if(last == null)
  72. last = result.getId().getVideoId();
  73. }
  74. if(webhookMessages == null)
  75. webhookMessages = new ArrayList<String>();
  76. webhookMessages.add((message.message == null || message.message.isEmpty() ? DEFAULT_EMBED_MESSAGE : message.message)
  77. .replace("%ct", result.getSnippet().getChannelTitle())
  78. .replace("%ti", result.getSnippet().getTitle())
  79. .replace("%pa", result.getSnippet().getPublishedAt().toStringRfc3339())
  80. .replace("%d", result.getSnippet().getDescription())
  81. .replace("%u", String.format("https://www.youtube.com/watch?v=%s", result.getId().getVideoId()))
  82. .replace("%td300x300", result.getSnippet().getThumbnails().getDefault().setWidth(300L).setHeight(300L).getUrl())
  83. .replace("%tm300x300", result.getSnippet().getThumbnails().getMedium().setWidth(300L).setHeight(300L).getUrl())
  84. .replace("%th300x300", result.getSnippet().getThumbnails().getHigh().setWidth(300L).setHeight(300L).getUrl())
  85. .replace("%td580x900", result.getSnippet().getThumbnails().getDefault().setWidth(580L).setHeight(900L).getUrl())
  86. .replace("%tm580x900", result.getSnippet().getThumbnails().getMedium().setWidth(580L).setHeight(900L).getUrl())
  87. .replace("%th580x900", result.getSnippet().getThumbnails().getHigh().setWidth(580L).setHeight(900L).getUrl())
  88. .replace("%tcd300x300", channel.getSnippet().getThumbnails().getDefault().setWidth(300L).setHeight(300L).getUrl())
  89. .replace("%tcm300x300", channel.getSnippet().getThumbnails().getMedium().setWidth(300L).setHeight(300L).getUrl())
  90. .replace("%tch300x300", channel.getSnippet().getThumbnails().getHigh().setWidth(300L).setHeight(300L).getUrl())
  91. .replace("%tcd580x900", channel.getSnippet().getThumbnails().getDefault().setWidth(580L).setHeight(900L).getUrl())
  92. .replace("%tcm580x900", channel.getSnippet().getThumbnails().getMedium().setWidth(580L).setHeight(900L).getUrl())
  93. .replace("%tch580x900", channel.getSnippet().getThumbnails().getHigh().setWidth(580L).setHeight(900L).getUrl()));
  94. if(message.lastUpdate == null)
  95. break;
  96. }
  97. if(last != null)
  98. writeModels.add(new UpdateOneModel<Document>(
  99. new Document("_guildId", message.guildId)
  100. .append("notification.YOUTUBE.channelId", message.channelId),
  101. new Document("$set", new Document("notification.YOUTUBE.$.lastUpdate", last))));
  102. if(lastLive != null)
  103. writeModels.add(new UpdateOneModel<Document>(
  104. new Document("_guildId", message.guildId)
  105. .append("notification.YOUTUBE.channelId", message.channelId),
  106. new Document("$set", new Document("notification.YOUTUBE.$.lastUpdateLiveStream", lastLive))));
  107. if(webhookMessages != null && !webhookMessages.isEmpty()) {
  108. if(webhookMessages.size() > 1)
  109. Collections.reverse(webhookMessages);
  110. for(String webhookMessage : webhookMessages)
  111. WebhookQueue.add(message.webhook, webhookMessage);
  112. }
  113. }
  114. if(!writeModels.isEmpty())
  115. Wuffy.getInstance().getExtensionGuild().getPrintBatchResult().onResult(Wuffy.getInstance().getGuildCollection().bulkWrite(writeModels), null);
  116. if(this.queueNames.isEmpty())
  117. this.running.set(false);
  118. } catch(Exception e) {
  119. Logger.fatal("Announcement youtube", "Failed to execute. waiting 10 seconds!", e);
  120. this.queueNames.clear();
  121. this.running.set(false);
  122. try {
  123. Thread.sleep(10000);
  124. } catch (InterruptedException e2) {
  125. e2.printStackTrace();
  126. }
  127. }
  128. }
  129. @Override
  130. public void _add(String guildId, List<Document> documents) {
  131. for(Document document : documents) {
  132. Message message = GsonUtil.GSON.fromJson(document.toJson(), Message.class);
  133. if(message != null && message.webhook != null && !message.webhook.isEmpty()) {
  134. message.guildId = guildId;
  135. if(message.channelId == null)
  136. continue;
  137. if(!this.queueNames.containsKey(message.channelId))
  138. this.queueNames.put(message.channelId, new ArrayList<Message>());
  139. this.queueNames.get(message.channelId).add(message);
  140. }
  141. }
  142. }
  143. @Override
  144. protected boolean isQueueEmpty() {
  145. return this.queueNames.isEmpty();
  146. }
  147. class Message {
  148. public String guildId;
  149. public String name;
  150. public String webhook;
  151. public String message;
  152. public String lastUpdate;
  153. public String lastUpdateLiveStream;
  154. public String channelId;
  155. public Message(String guildId, String name, String webhook, String message, String lastUpdate, String lastUpdateLiveStream, String channelId) {
  156. this.guildId = guildId;
  157. this.name = name;
  158. this.webhook = webhook;
  159. this.message = message;
  160. this.lastUpdate = lastUpdate;
  161. this.lastUpdateLiveStream = lastUpdateLiveStream;
  162. this.channelId = channelId;
  163. }
  164. }
  165. }