Advertisement
Mouamle

TgChannelParser

May 3rd, 2019
462
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. import org.jsoup.Jsoup;
  2. import org.jsoup.nodes.Document;
  3. import org.jsoup.nodes.Element;
  4.  
  5. import java.io.IOException;
  6. import java.net.URL;
  7. import java.time.Duration;
  8. import java.util.Optional;
  9.  
  10. /**
  11.  * A class that gets the image from a telegram channel post
  12.  *
  13.  * @author t.me/Chase_22
  14.  * @author t.me/MouamleH
  15.  * @version 0.0.1
  16.  */
  17. public class TgChannelParser {
  18.  
  19.     private static int READ_TIMEOUT = (int) Duration.ofSeconds(5).toMillis();
  20.     private Document html;
  21.  
  22.     /**
  23.      * @param url the post url
  24.      * @throws IOException throws an exception if the url was not found
  25.      *                     or the timeout was reached
  26.      */
  27.     public TgChannelParser(String url) throws IOException {
  28.         html = Jsoup.parse(new URL(url + "?embed=1"), READ_TIMEOUT);
  29.     }
  30.  
  31.     /**
  32.      * @return an Optional containing the image url if the post contains an image
  33.      */
  34.     public Optional<String> getImageUrl() {
  35.         Element element = html.selectFirst(".tgme_widget_message_photo_wrap");
  36.  
  37.         if (element == null) {
  38.             element = html.selectFirst(".link_preview_image");
  39.         }
  40.  
  41.         if (element != null) {
  42.             String style = element.attr("style");
  43.             String imageUrl = style.substring(style.indexOf("'") + 1, style.lastIndexOf("'"));
  44.             return Optional.of(imageUrl);
  45.         }
  46.  
  47.         return Optional.empty();
  48.     }
  49.  
  50.     /**
  51.      * @return true if the post is present, false otherwise
  52.      */
  53.     public boolean isPresent() {
  54.         return !html.toString().contains("Post not found");
  55.     }
  56.  
  57.     /**
  58.      * @return true if the post contains an image, false otherwise
  59.      */
  60.     public boolean containsImage() {
  61.         return getImageUrl().isPresent();
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement