Advertisement
Guest User

Untitled

a guest
May 29th, 2015
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.22 KB | None | 0 0
  1. import java.util.Date;
  2. import java.text.DateFormat;
  3. import java.text.SimpleDateFormat;
  4. import java.text.ParseException;
  5.  
  6. import java.io.*;
  7.  
  8. /*
  9.  * - add image.
  10.  * - add link.
  11.  */
  12. class Post implements Comparable<Post>
  13. {
  14.     public final Integer THREAD_ID;
  15.     public final Integer POST_ID;
  16.     public final Date DATE;
  17.     public final String USER_NAME;
  18.     public final String USER_ID;
  19.     public final String TEXT;
  20.  
  21.     private static DateFormat dateFt =
  22.         new SimpleDateFormat("d/MMM/yyyy HH:mm:ss");
  23.  
  24.     public Post(int t_id,int p_id,Date d,String uname,String u_id,String txt)
  25.     {
  26.         THREAD_ID = t_id;
  27.         POST_ID = p_id;
  28.         DATE = d;
  29.         USER_NAME = uname;
  30.         USER_ID = u_id;
  31.         TEXT = txt;
  32.     }
  33.  
  34.     // ------------------
  35.  
  36.     boolean isThread() {
  37.         return THREAD_ID.equals(POST_ID);
  38.     }
  39.  
  40.     public static Post fromCSV(String line)
  41.     {
  42.         String[] f = line.split(",",6);
  43.         Date date;
  44.         try {
  45.             date = dateFt.parse(f[2]);
  46.         }
  47.         catch (ParseException e) {
  48.             date = null;
  49.             System.err.println(e.getMessage());
  50.         }
  51.         return new Post(
  52.                 Integer.valueOf(f[0]),
  53.                 Integer.valueOf(f[1]),
  54.                 date,
  55.                 f[3],
  56.                 f[4],
  57.                 f[5]
  58.                 );
  59.     }
  60.  
  61.     public String toCSV()
  62.     {
  63.         return THREAD_ID+","+POST_ID+","+dateFt.format(DATE)+","
  64.             +USER_NAME+","+USER_ID+"," +TEXT+"\n";
  65.     }
  66.  
  67.     /* Date, and then post number. */
  68.     public int compareTo(Post o)
  69.     {
  70.         int dcomp = (o.DATE).compareTo(DATE);
  71.         if (dcomp != 0)
  72.             return dcomp;
  73.         return (o.POST_ID).compareTo(POST_ID);
  74.     }
  75.  
  76.     public boolean equals(Object o)
  77.     {
  78.         if (o instanceof Post) {
  79.             return (this.compareTo(((Post)o)) == 0);
  80.             //return POST_ID.equals(((Post)o).POST_ID);
  81.         } else
  82.             return false;
  83.     }
  84.  
  85.     public String toString()
  86.     {
  87.         return THREAD_ID + "/" + POST_ID + ", " + dateFt.format(DATE) +
  88.             ", " + USER_NAME + " " + USER_ID + ": " + "\n" + TEXT;
  89.     }
  90. }
  91.  
  92.  
  93. import java.net.URL;
  94. import java.net.URLConnection;
  95.  
  96. import java.util.SortedSet;
  97. import java.util.Date;
  98. import java.util.TimeZone;
  99. import java.util.List;
  100. import java.util.ArrayList;
  101. import java.io.*;
  102. import java.nio.file.Path;
  103.  
  104. import java.text.DateFormat;
  105. import java.text.SimpleDateFormat;
  106. import java.text.ParseException;
  107.  
  108. //import org.w3c.dom.Document;
  109.  
  110. import org.jsoup.Jsoup;
  111. import org.jsoup.nodes.Document;
  112. import org.jsoup.nodes.Element;
  113. import org.jsoup.select.Elements;
  114.  
  115.  
  116. class Board
  117. {
  118.     String BOARD_ID;
  119.     String BOARD_URL;
  120.     long VISIT_WAIT = 800;  // milli
  121.  
  122.     private Post previousNew; // sort of 'sliding window'
  123.     private Post actualNew;
  124.     private Post lastRead;
  125.     private String saveFile = null;
  126.     private int NUM_PAGES;
  127.  
  128.     private SortedSet<Post> boardPosts = new java.util.TreeSet<>();
  129.  
  130.     Board(String _url,String _id)
  131.     {
  132.         this(_url);
  133.         BOARD_ID = _id;
  134.  
  135.         saveFile = _id + ".csv";
  136.         Path path = java.nio.file.Paths.get(saveFile);
  137.         if (java.nio.file.Files.exists(path))
  138.         {
  139.             BufferedReader in = null;
  140.             try {
  141.                 in = java.nio.file.Files.newBufferedReader(path);
  142.                 String line;
  143.                 while ((line = in.readLine()) != null) {
  144.                     Post post = Post.fromCSV(line);
  145.                     addPost(post);
  146.                 }
  147.             } catch (IOException e) {
  148.                 System.err.println(e.getMessage());
  149.             } finally {
  150.                 try {
  151.                     if (in != null)
  152.                         in.close();
  153.                 }
  154.                 catch (IOException e) {
  155.                     System.err.println("Error closing file");
  156.                 }
  157.             }
  158.         }
  159.     }
  160.  
  161.     Board(String _url)
  162.     {
  163.         // TODO: throw exception here
  164.         BOARD_URL = _url;
  165.         numPages = numberOfPages();
  166.     }
  167.  
  168.     // ---------------
  169.  
  170.     /* Visit board page. Get new posts. */
  171.     boolean update() throws IOException
  172.     {
  173.         //System.out.println("Updating " + BOARD_URL + "...");
  174.         boolean changed = false;
  175.  
  176.         Writer out = null;
  177.         try {
  178.             Document doc = Jsoup.connect(BOARD_URL).get();
  179.             Elements threads =
  180.                 doc.getElementsByAttributeValueMatching("id",
  181.                         "^thread\\d+[a-z]+$");
  182.  
  183.             if (saveFile != null)
  184.                 out = new FileWriter(saveFile,true);
  185.            
  186.             for (Element elem : threads)
  187.             {
  188.                 List<Post> posts = visit(Integer.valueOf(
  189.                             elem
  190.                             .id()
  191.                             .replaceAll("[a-z]+",""))
  192.                         );
  193.                 try { Thread.sleep(VISIT_WAIT); }
  194.                 catch (InterruptedException e) { }
  195.  
  196.                 for (Post p : posts)
  197.                 {
  198.                     addPost(p);
  199.  
  200.                     String pStr = p + "\n";
  201.                     if (!BOARD_ID.isEmpty())
  202.                         pStr = BOARD_ID + "/" + pStr;
  203.                     if (p.isThread())
  204.                         pStr = "-> " + pStr;
  205.                     System.out.println(pStr);
  206.  
  207.                     if (out != null)
  208.                         out.write(p.toCSV());
  209.  
  210.                     changed = true;
  211.                 }
  212.             }
  213.  
  214.         }
  215.         catch (IOException e) {
  216.             System.err.println("Error in " + BOARD_URL);
  217.             throw e;
  218.         }
  219.         finally {
  220.             if (out != null)
  221.                 out.close();
  222.         }
  223.         return changed;
  224.     }
  225.  
  226.     /* Visit thread page. Get new posts. */
  227.     private List<Post> visit(int threadId) throws IOException
  228.     {
  229.         String url = BOARD_URL + "/res/" + threadId + ".html";
  230.         //System.out.println("Visiting " + url);
  231.         List<Post> posts;
  232.         try {
  233.             Document doc = Jsoup.connect(url).get();
  234.  
  235.             Elements threadPosts =
  236.                 doc.getElementsByAttributeValueMatching("id",
  237.                         "^(thread\\d+[a-z]+)|(reply\\d+)$");
  238.  
  239.             posts = new ArrayList<Post>();
  240.  
  241.             // iterate backwards
  242.             for (int i=threadPosts.size()-1; i >= 0; i--)
  243.             {
  244.                 Element elem = threadPosts.get(i);
  245.                 Post p = parsePost(elem,threadId);
  246.                 if (exists(p))
  247.                     return posts;
  248.                 posts.add(p);
  249.             }
  250.         }
  251.         catch (IOException e) {
  252.             System.err.println("Error in " + e);
  253.             throw e;
  254.         }
  255.         return posts;
  256.     }
  257.  
  258.     /* Extract from DOM node. */
  259.     private Post parsePost(Element elem,int threadId)
  260.     {
  261.         String numberText = elem
  262.             .getElementsByAttributeValueMatching("name","\\d+").first()
  263.             .attr("name");
  264.             //.getElementsByTag("a").first()
  265.         int postId = Integer.valueOf(numberText);
  266.         //System.out.println(postId);
  267.  
  268.         String postText = elem
  269.             .getElementsByTag("blockquote")
  270.             .first()
  271.             .child(0)
  272.             .text();  // not ownText because of links
  273.  
  274.         String userId = elem.ownText();;
  275.         if (userId.matches("^ID: [a-f0-9]{6}"))
  276.             userId = userId.replaceAll("^ID: ","");
  277.         else
  278.             userId = "";
  279.  
  280.         String date = elem
  281.             .getElementsByTag("label")
  282.             .first()
  283.             .ownText()
  284.             .replaceAll("^[A-Z][a-z]{2} ","");
  285.         Date postDate;
  286.         try {
  287.             DateFormat df = new SimpleDateFormat("d/MMM/yyyy HH:mm:ss");
  288.             df.setTimeZone(TimeZone.getTimeZone("Europe/Lisbon"));
  289.             postDate = df.parse(date);
  290.         }
  291.         catch (ParseException e) {
  292.             System.err.println(e.getMessage());
  293.             postDate = null;
  294.         }
  295.  
  296.         String userName = elem
  297.             .getElementsByClass("postername")
  298.             .first()
  299.             .text(); // not ownText because of links
  300.  
  301.         return new Post(
  302.                 threadId,
  303.                 postId,
  304.                 postDate,
  305.                 userName,
  306.                 userId,
  307.                 postText
  308.                 );
  309.     }
  310.  
  311.     private int numberOfPages()
  312.     {
  313.         int lastPage = 0;
  314.         try {
  315.             Document doc = Jsoup.connect(BOARD_URL).get();
  316.             lastPage = Integer.valueOf(
  317.                     doc
  318.                     .select("td a")
  319.                     .select("[href~=^/[a-z]+/\\d+.html$]")
  320.                     .select(":matchesOwn(\\d+)")
  321.                     .last()
  322.                     .ownText());
  323.         } catch (IOException e ) {
  324.             e.getMessage();
  325.         }
  326.         return lastPage + 1;
  327.     }
  328.  
  329.     private void addPost(Post post)
  330.     {
  331.         boardPosts.add(post);
  332.     }
  333.  
  334.     private boolean exists(Post post)
  335.     {
  336.         return boardPosts.contains(post);
  337.     }
  338.  
  339.     public void print()
  340.     {
  341.         for (Post p : boardPosts)
  342.             System.out.println(p);
  343.     }
  344.  
  345.     public void print(int n)
  346.     {
  347.         for (Post p : latest(n))
  348.             System.out.println(p);
  349.     }
  350.  
  351.     public List<Post> latest(int n)
  352.     {
  353.         List<Post> l = new ArrayList<>();
  354.         int i = 0;
  355.         for (Post p : boardPosts) {
  356.             l.add(p);
  357.             if (i++ == n)
  358.                 break;
  359.         }
  360.         return l;
  361.     }
  362.  
  363.     public boolean equals(Object o)
  364.     {
  365.         if (o instanceof Board) {
  366.             return BOARD_URL.equals(((Board)o).BOARD_URL);
  367.         } else
  368.             return false;
  369.     }
  370.  
  371.     public void statistics()
  372.     {
  373.         System.out.println("No. posts: " + boardPosts.size());
  374.     }
  375.  
  376.     public static void main(String[] args)
  377.     {
  378.         Board board = new Board("http://ptchan.net/b");
  379.         try {
  380.             board.update();
  381.             board.print(5);
  382.         }
  383.         catch (IOException e) {
  384.             System.err.println(e.getMessage());
  385.         }
  386.     }
  387. }
  388.  
  389.  
  390. import java.util.Set;
  391. import java.util.List;
  392. import java.util.ArrayList;
  393. import java.util.Queue;
  394. import java.util.PriorityQueue;
  395. import java.io.IOException;
  396.  
  397.  
  398. public class Imageboard
  399. {
  400.     private Set<Board> boards = new java.util.HashSet<>();
  401.     private long BOARD_WAIT = 800;
  402.  
  403.     public static void main(String[] args)
  404.     {
  405.         Imageboard img = new Imageboard();
  406.         img.register("http://ptchan.net/a",     "a"     );
  407.         img.register("http://ptchan.net/b",     "b"     );
  408.         img.register("http://ptchan.net/con",   "con"   );
  409.         img.register("http://ptchan.net/c",     "c"     );
  410.         img.register("http://ptchan.net/cu",    "cu"    );
  411.         img.register("http://ptchan.net/des",   "des"   );
  412.         img.register("http://ptchan.net/dis",   "dis"   );
  413.         img.register("http://ptchan.net/fit",   "fit"   );
  414.         img.register("http://ptchan.net/o",     "o"     );
  415.         img.register("http://ptchan.net/t",     "t"     );
  416.         img.register("http://ptchan.net/u",     "u"     );
  417.         img.register("http://ptchan.net/xxx",   "xxx"   );
  418.         img.register("http://ptchan.net/int",   "int"   );
  419.         img.register("http://ptchan.net/pt",    "pt"    );
  420.         img.register("http://ptchan.net/meta",  "meta"  );
  421.  
  422.         while (true)
  423.         {
  424.             img.update();
  425.         }
  426.     }
  427.  
  428.     public void update()
  429.     {
  430.         for (Board b : boards) {
  431.             try {
  432.                 boolean changed = b.update();
  433.  
  434.             } catch (IOException e) {
  435.                 System.out.println(e.getMessage());
  436.             }
  437.             try { Thread.sleep(BOARD_WAIT); }
  438.             catch (InterruptedException e) { }
  439.         }
  440.     }
  441.  
  442.     public void register(String url,String name)
  443.     {
  444.         boards.add(new Board(url,name));
  445.     }
  446.  
  447.     public List<Post> latest(int n)
  448.     {
  449.         Queue<Post> queue = new PriorityQueue<>();
  450.         for (Board b : boards)
  451.             queue.addAll(b.latest(n));
  452.         List<Post> list = new ArrayList<>();
  453.         while (n-- > 0)
  454.             list.add(queue.poll());
  455.         return list;
  456.     }
  457. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement