Guest User

RedditData.java

a guest
Dec 22nd, 2012
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.47 KB | None | 0 0
  1. package reddit;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.DataOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.net.HttpURLConnection;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. import java.net.URLEncoder;
  11. import java.util.ArrayList;
  12. import java.util.HashMap;
  13. import java.util.List;
  14. import java.util.regex.Matcher;
  15. import java.util.regex.Pattern;
  16.  
  17. import com.google.gson.stream.JsonReader;
  18. import com.google.gson.stream.JsonToken;
  19.  
  20. public class RedditData {
  21.  
  22.     public static final long MIN_REQUEST_DELAY = 5050l;
  23.     public static final String USER_HEADER = /*"currency converter by /u/Tjstretchalot"*/ "jew boy sandler stalker by /u/Tjstretchalot";
  24.  
  25.     private long lastRequest;
  26.     @SuppressWarnings("unused")
  27.     private int total_request_count;
  28.     private String myModHash;
  29.     private String myCookie;
  30.     private static final String myFirstTime = "reddit_first=%7B%22firsttime%22%3A%20%22first%22%7D";
  31.     @SuppressWarnings("unused")
  32.     private String user;
  33.  
  34.     public RedditData() {
  35.         lastRequest = 0;
  36.         total_request_count = 0;
  37.     }
  38.    
  39.     private static HttpURLConnection createConnection(String urlLoc, int contentlength) throws IOException {
  40.         URL url = new URL(urlLoc);
  41.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  42.  
  43.         conn.setDoOutput( contentlength != 0 );
  44.         conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  45.         conn.setRequestProperty("User-Header", USER_HEADER);
  46.         conn.setRequestProperty("Content-Length", Integer.toString(contentlength));
  47.         conn.setUseCaches (false);
  48.         return conn;
  49.     }
  50.    
  51.     /**
  52.      * Preferably the connection returned by createconnection
  53.      * @param conn
  54.      * @param addModhash
  55.      * @return
  56.      * @throws IOException
  57.      * @throws RedditException
  58.      */
  59.     private void authorizeConnection( HttpURLConnection conn ) throws IOException, RedditException {
  60.         if(myModHash == null || myCookie == null) {
  61.             throw new RedditException("Attempted authorized method before logging in");
  62.         }
  63.         //System.out.println("[Authorize Connection] Authorizing with the cookie " + myCookie);
  64.         conn.setRequestProperty("Cookie", myCookie);
  65.     }
  66.    
  67.     private void writeOutput( HttpURLConnection conn, String output ) throws IOException {
  68.         DataOutputStream out = new DataOutputStream(conn.getOutputStream());
  69.         out.writeBytes(output);
  70.         out.close();
  71.     }
  72.  
  73.     public void login( String username, String password ) throws IOException, RedditException {
  74.         user = username;
  75.         doRequestCheck();
  76.  
  77.         String urlLoc = "http://www.reddit.com/api/login/" + username;
  78.         String urlParameters = "rem=true&user=" + username + "&passwd=" + password + "&api_type=json";
  79.        
  80.         HttpURLConnection conn = createConnection( urlLoc, urlParameters.getBytes().length );
  81.         writeOutput(conn, urlParameters);
  82.  
  83.         JsonReader jr = new JsonReader( new InputStreamReader( conn.getInputStream() ) );
  84.  
  85.         String modhash = null;
  86.         String cookie = null;
  87.         jr.beginObject();
  88.         String nm;
  89.         while( jr.hasNext() ) {
  90.             nm = jr.nextName();
  91.            
  92.             if(nm.equals("json")) {
  93.                 jr.beginObject();
  94.                
  95.                 while(jr.hasNext()) {
  96.                     nm = jr.nextName();
  97.                    
  98.                     if(nm.equals("data")) {
  99.                         jr.beginObject();
  100.                        
  101.                         while(jr.hasNext()) {
  102.                             nm = jr.nextName();
  103.                            
  104.                             if(nm.equals("modhash")) {
  105.                                 modhash = jr.nextString();
  106.                                 System.out.println("Found modhash: " + modhash);
  107.                             }else if(nm.equals("cookie")) {
  108.                                 cookie = jr.nextString();
  109.                                 System.out.println("Found cookie: " + cookie);
  110.                             }else {
  111.                                 System.out.println("Found something else: " + nm);
  112.                                 jr.skipValue();
  113.                             }
  114.                         }
  115.                        
  116.                         jr.endObject();
  117.                     }else {
  118.                         jr.skipValue();
  119.                     }
  120.                 }
  121.                
  122.                 jr.endObject();
  123.             }else {
  124.                 jr.skipValue();
  125.             }
  126.         }
  127.         jr.endObject();
  128.         jr.close();
  129.        
  130. //      BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
  131. //     
  132. //      System.out.println(in.readLine());
  133.        
  134. //      in.close();
  135.        
  136.         System.out.println("Cookie given by json is '" + cookie + "' set-cookie field is '" + conn.getHeaderField("Set-Cookie"));
  137.         cookie = conn.getHeaderField("Set-Cookie");
  138.         cookie = cookie.substring(0, cookie.indexOf(";"));
  139.         conn.disconnect();
  140.         if(modhash == null) {
  141.             throw new RedditException( "Modhash not found" );
  142.         }
  143.        
  144.         myModHash = modhash;
  145.         myCookie = cookie;
  146.        
  147.        
  148.     }
  149.  
  150.     public List<String> getTopPostURLS( ) throws IOException, RedditException {
  151.         doRequestCheck();
  152.         List<String> result = new ArrayList<>();
  153.  
  154.         String urlLoc = "http://www.reddit.com/r/all.json";
  155.         HttpURLConnection conn = createConnection( urlLoc, 0 );
  156.         authorizeConnection(conn);
  157.         conn.setRequestProperty("Cookie", conn.getRequestProperty("Cookie") + "; " + myFirstTime);
  158.         JsonReader jr = new JsonReader( new InputStreamReader( conn.getInputStream() ) );
  159.  
  160.         String nm;
  161.        
  162.        
  163.         jr.beginObject();
  164. //      System.out.println("BEGIN OBJECT");
  165. //      printRecursive(jr, jr.nextName(), 2);
  166. //      System.out.println("END OBJECT");
  167. //      jr.endObject();
  168. //      if(1 == 3 / 3)
  169. //          return result;
  170.         while(jr.hasNext()) {
  171.             nm = jr.nextName();
  172.             if(!nm.equals("data") || jr.peek() != JsonToken.BEGIN_OBJECT)
  173.             {
  174.                 jr.skipValue();
  175.                 continue;
  176.             }
  177.  
  178.             jr.beginObject();
  179.  
  180.             while(jr.hasNext()) {
  181.                 nm = jr.nextName();
  182.                 if(nm.equals("children")) {
  183.                     jr.beginArray();
  184.                     while( jr.hasNext() ) {
  185.                         jr.beginObject();
  186.                         while(jr.hasNext()) {
  187.                             nm = jr.nextName();
  188.                             if(nm.equals("data")) {
  189.                                 jr.beginObject();
  190.                                 while(jr.hasNext()) {
  191.                                     nm = jr.nextName();
  192.                                     if(nm.equals("permalink")) {
  193.                                         result.add(jr.nextString());
  194.                                     }else {
  195.                                         jr.skipValue();
  196.                                     }
  197.                                 }
  198.                                 jr.endObject();
  199.  
  200.                             }else {
  201.                                 jr.skipValue();
  202.                             }
  203.                         }
  204.                         jr.endObject();
  205.                     }
  206.                     jr.endArray();
  207.                 }else if(nm.equals("modhash")) {
  208.                     myModHash = jr.nextString();
  209.                     System.out.println("Modhash updated; now it is " + myModHash);
  210.                 }else {
  211.                     jr.skipValue();
  212.                 }
  213.             }
  214.             jr.endObject();
  215.         }
  216.         jr.endObject();
  217.         jr.close();
  218.         conn.disconnect();
  219.         return result;
  220.     }
  221.  
  222.    
  223.  
  224.     private void printRecursive(JsonReader jr, String nm, int spacing) throws IOException {
  225.         String spcString = "";
  226.         for(int i = 0; i < spacing; i++) {
  227.             spcString += " ";
  228.         }
  229.         while(jr.hasNext()) {
  230.             if(jr.peek() == JsonToken.END_ARRAY)
  231.             {
  232.                 jr.endArray();
  233.                 return;
  234.             }else if(jr.peek() == JsonToken.END_OBJECT) {
  235.                 jr.endObject();
  236.                 return;
  237.             }else if(jr.peek() == JsonToken.BEGIN_ARRAY) {
  238.                 jr.beginArray();
  239.                 System.out.println(spcString + "ARRAY " + nm);
  240.                 printRecursive(jr, nm, spacing + 2);
  241.                 jr.endArray();
  242.             }else if(jr.peek() == JsonToken.BEGIN_OBJECT) {
  243.                 jr.beginObject();
  244.                 System.out.println(spcString + "OBJECT " + nm);
  245.                 printRecursive(jr, nm, spacing + 2);
  246.                 jr.endObject();
  247.             }else if(jr.peek() == JsonToken.NAME)
  248.                 nm = jr.nextName();
  249.             else {
  250.                 System.out.print(spcString + nm + "=");
  251.                 switch(jr.peek()) {
  252.                 case STRING:
  253.                     System.out.println(jr.nextString().replace("\n", spcString + "\n"));
  254.                     break;
  255.                 case NUMBER:
  256.                     System.out.println(jr.nextDouble());
  257.                     break;
  258.                 case NULL:
  259.                     System.out.println("null");
  260.                     jr.skipValue();
  261.                     break;
  262.                 case BOOLEAN:
  263.                     System.out.println(jr.nextBoolean());
  264.                     break;
  265.                 default:
  266.                     System.out.println("Unknown");
  267.                 }
  268.             }
  269.         }
  270.     }
  271.  
  272.     public List<Comment> loadAllComments( String commentlink, List<String> skip_ids, String... regex ) throws IOException, RedditException {
  273.         doRequestCheck();
  274.         HashMap<String, Object> page_data;
  275.         List<Comment> result = new ArrayList<>();
  276.  
  277.         List<Matcher> matchers = new ArrayList<>();
  278.         for(String r : regex) {
  279.             Pattern p = Pattern.compile(r);
  280.             matchers.add(p.matcher(""));
  281.         }
  282.  
  283.         String urlLoc = "http://www.reddit.com" + commentlink + ".json"; // http://reddit.com/r/gaming/comments/1405fo/the_humble_thq_bundle/.json for example
  284.         HttpURLConnection conn = createConnection( urlLoc, 0 );
  285.         authorizeConnection(conn);
  286.  
  287.         String nm;
  288.        
  289.         JsonReader jr = new JsonReader( new InputStreamReader( conn.getInputStream() ) );
  290.  
  291.         jr.beginArray();
  292.        
  293.         page_data = loadPageData(jr);
  294.         jr.beginObject();
  295.         while(jr.hasNext()) {
  296.             nm = jr.nextName();
  297.             if(nm.equals("data")) {
  298.                 jr.beginObject();
  299.                 while(jr.hasNext()) {
  300.                     nm = jr.nextName();
  301.  
  302.                     if(nm.equals("children")) {
  303.                         jr.beginArray();
  304.  
  305.                         while(jr.hasNext()) {
  306.                             jr.beginObject();
  307.  
  308.                             while(jr.hasNext()) {
  309.                                 nm = jr.nextName();
  310.  
  311.                                 if(nm.equals("data")) {
  312.                                     jr.beginObject();
  313.  
  314.                                     parseCommentIntoList( result, skip_ids, jr, matchers, (String) page_data.get("permalink") );
  315.  
  316.                                     jr.endObject();
  317.                                 }else {
  318.                                     jr.skipValue();
  319.                                 }
  320.                             }
  321.  
  322.                             jr.endObject();
  323.                         }
  324.  
  325.                         jr.endArray();
  326.                     }else if(nm.equals("modhash")) {
  327.                         myModHash = jr.nextString();
  328.                         System.out.println("Modhash updated; now it is " + myModHash);
  329.                     }else {
  330.                         jr.skipValue();
  331.                     }
  332.                 }
  333.                 jr.endObject();
  334.             }else {
  335.                 jr.skipValue();
  336.             }
  337.         }
  338.         jr.endObject();
  339.         jr.endArray();
  340.         jr.close();
  341.         conn.disconnect();
  342.         return result;
  343.     }
  344.  
  345.     private HashMap<String, Object> loadPageData(JsonReader jr) throws IOException {
  346.         HashMap<String, Object> page_data = new HashMap<>();
  347.         jr.beginObject();
  348.         String nm;
  349.         while(jr.hasNext()) {
  350.             nm = jr.nextName();
  351.            
  352.             if(nm.equals("data")) {
  353.                 jr.beginObject();
  354.                
  355.                 while(jr.hasNext()) {
  356.                     nm = jr.nextName();
  357.                    
  358.                     if(nm.equals("children")) {
  359.                         jr.beginArray();
  360.                         while(jr.hasNext()) {
  361.                             nm = jr.nextName();
  362.                            
  363.                             JsonToken type = jr.peek();
  364.                             switch(type) {
  365.                             case STRING:
  366.                                 page_data.put(nm, jr.nextString());
  367.                                 break;
  368.                             case NUMBER:
  369.                                 page_data.put(nm,  jr.nextDouble());
  370.                                 break;
  371.                             case NULL:
  372.                                 page_data.put(nm, null);
  373.                                 break;
  374.                             case BOOLEAN:
  375.                                 page_data.put(nm, jr.nextBoolean());
  376.                                 break;
  377.                             default:
  378.                                 jr.skipValue();
  379.                                 break;
  380.                             }
  381.                         }
  382.                         jr.endArray();
  383.                     }else {
  384.                         jr.skipValue();
  385.                     }
  386.                 }
  387.                
  388.                 jr.endObject();
  389.             }else {
  390.                 jr.skipValue();
  391.             }
  392.         }
  393.        
  394.         jr.endObject();
  395.         return page_data;
  396.     }
  397.  
  398.     private void parseCommentIntoList(List<Comment> result, List<String> skip_ids, JsonReader jr, List<Matcher> matchers, String oppermalink) throws IOException {
  399.         Comment base = new Comment();
  400.         base.oppermalink = oppermalink;
  401.         int ups = 0;
  402.         int downs = 0;
  403.         while(jr.hasNext()) {
  404.             String nm = jr.nextName();
  405.  
  406.            
  407.             if(nm.equals("author")) {
  408.                 base.author = jr.nextString();
  409.                 //System.out.println("Found author name: " + base.author);
  410.             }else if(nm.equals("link_title"))  {
  411.                 base.title = jr.nextString();
  412.             }else if(nm.equals("name")) {
  413.                 base.permalink = jr.nextString();
  414.                 //System.out.println("Found id: " + base.permalink);
  415.             }else if(nm.equals("body")) {
  416.                 base.data = jr.nextString();
  417.                 //System.out.println("Found body: " + base.data);
  418.             }else if(nm.equals("link_id")) {
  419.                 base.opid = jr.nextString();
  420.             }else if(nm.equals("id")) {
  421.                 base.linkid = jr.nextString();
  422.             }else if(nm.equals("ups")) {
  423.                 ups = jr.nextInt();
  424.             }else if(nm.equals("downs")) {
  425.                 downs = jr.nextInt();
  426.             }else if(nm.equals("subreddit")) {
  427.                 base.subreddit = jr.nextString();
  428.             }else if(nm.equals("replies")) {
  429.                 //System.out.println("Found replies on comment; is the comment complete? " + base.isCompleteComment() );
  430.                 if(jr.peek() != JsonToken.BEGIN_OBJECT) {
  431.                     //System.out.println("Found odd value: " + jr.nextString());
  432.                     jr.skipValue();
  433.                     continue;
  434.                 }
  435.                 jr.beginObject();
  436.                 while( jr.hasNext() ) {
  437.                     nm = jr.nextName();
  438.                    
  439.                     if(nm.equals("children")) {
  440.                         jr.beginArray();
  441.                        
  442.                         while(jr.hasNext()) {
  443.                             jr.beginObject();
  444.                            
  445.                             while(jr.hasNext()) {
  446.                                 nm = jr.nextName();
  447.                                
  448.                                 if(nm.equals("data")) {
  449.                                     jr.beginObject();
  450.                                     //System.out.println("NEW COMMENT");
  451.                                     parseCommentIntoList(result, skip_ids, jr, matchers, oppermalink);
  452.                                     //System.out.println("END");
  453.                                     jr.endObject();
  454.                                 }else {
  455.                                     jr.skipValue();
  456.                                 }
  457.                             }
  458.                            
  459.                             jr.endObject();
  460.                         }
  461.                        
  462.                         jr.endArray();
  463.                     }else {
  464.                         jr.skipValue();
  465.                     }
  466.                 }
  467.                 jr.endObject();
  468.             }else {
  469.                 jr.skipValue();
  470.             }
  471.         }
  472.        
  473.         if(!base.isCompleteComment() || skip_ids.contains(base.permalink) || base.author.equals("ConvertsCurrencyBot")) {
  474.             return;
  475.         }
  476.         base.points = ups - downs;
  477.         for(Matcher m : matchers) {
  478.             m.reset(base.data);
  479.            
  480.             if(m.find()) {
  481.                 result.add(base);
  482.                 return;
  483.             }
  484.         }
  485.     }
  486.    
  487.     public void postComment(String txt, String parentID) throws IOException, RedditException {
  488.         doRequestCheck();
  489.         String urlLoc = "http://www.reddit.com/api/comment";
  490.         String urlParameters = "parent=" + parentID + "&text=" + txt + "&uh=" + myModHash + "&api_type=json";
  491.         //System.out.println(urlParameters + ", byte length is " + urlParameters.getBytes().length);
  492.         HttpURLConnection conn = createConnection(urlLoc, urlParameters.getBytes().length);
  493.         authorizeConnection(conn);
  494.         writeOutput(conn, urlParameters);
  495.         BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
  496.        
  497.         String str;
  498.         while((str = in.readLine()) != null) {
  499.             System.out.println(str);
  500.         }
  501.        
  502.         in.close();
  503.        
  504.         conn.disconnect();
  505.         increaseDelay( 1000 * 60 * 10 ); // 15 minutes in between comments
  506.     }
  507.  
  508.     private void doRequestCheck() throws TooManyRedditRequests {
  509.         if( !canMakeNewRequest() )
  510.             throw new TooManyRedditRequests( "You have made too many requests recently" );
  511.         lastRequest = System.currentTimeMillis();
  512.         total_request_count++;
  513.     }
  514.  
  515.     public boolean canMakeNewRequest() {
  516.         return System.currentTimeMillis() - lastRequest > MIN_REQUEST_DELAY;
  517.     }
  518.  
  519.     public void increaseDelay(int i) {
  520.         lastRequest += i;
  521.     }
  522.  
  523.     public List<Comment> loadUserComments(String userN, List<String> skip_ids, List<Matcher> matchers) throws TooManyRedditRequests, IOException {
  524.         doRequestCheck();
  525.        
  526.         List<Comment> res = new ArrayList<>();
  527.        
  528.         String URL = "http://reddit.com/user/" + userN + ".json";
  529.         HttpURLConnection conn = createConnection(URL, 0);
  530.        
  531.         JsonReader in = new JsonReader(new InputStreamReader(conn.getInputStream()));
  532.         in.setLenient(false);
  533.         String nm;
  534.         in.beginObject();
  535.         while(in.hasNext()) {
  536.             nm = in.nextName();
  537.             System.out.println(nm);
  538.             if(nm.equals("data")) {
  539.                 in.beginObject();
  540.                 while(in.hasNext()) {
  541.                     nm = in.nextName();
  542.                    
  543.                     if(nm.equals("children")) {
  544.                         in.beginArray();
  545.                        
  546.                         while(in.hasNext()) {
  547.                             in.beginObject();
  548.                            
  549.                             while(in.hasNext()) {
  550.                                 nm = in.nextName();
  551.                                
  552.                                 if(nm.equals("data")) {
  553.                                     in.beginObject();
  554.                                     parseCommentIntoList(res, skip_ids, in, matchers, "NOT_FOUND");
  555.                                     in.endObject();
  556.                                 }else {
  557.                                     in.skipValue();
  558.                                 }
  559.                             }
  560.                            
  561.                             in.endObject();
  562.                         }
  563.                        
  564.                         in.endArray();
  565.                     }else {
  566.                         in.skipValue();
  567.                     }
  568.                 }
  569.                
  570.                 in.endObject();
  571.             }else if(nm.equals("error")) {
  572.                 System.err.println("Found an error! Printing the rest recursively.");
  573.                 printRecursive(in, nm, 2);
  574.             }else {
  575.                 in.skipValue();
  576.             }
  577.         }
  578.         in.endObject();
  579.         in.close();
  580.         return res;
  581.     }
  582.  
  583.     public void findPermaLink(Comment c) throws IOException, RedditException {
  584.         if(c == null)
  585.             return;
  586.         doRequestCheck();
  587.        
  588.         HttpURLConnection conn = createConnection("http://www.reddit.com/by_id/" + c.opid + ".json", 0);
  589.         authorizeConnection(conn);
  590.         //java.io.FileReader f = new java.io.FileReader(new java.io.File("byid.txt"));
  591.        
  592.         JsonReader in = new JsonReader(new InputStreamReader(conn.getInputStream()));
  593.         //JsonReader in = new JsonReader(f);
  594.         HashMap<String, Object> data = new HashMap<>();
  595.         String nm;
  596.         in.beginObject();
  597.         while(in.hasNext()) {
  598.             nm = in.nextName();
  599.             if(nm.equals("data")) {
  600.                 //System.out.println("1");
  601.                 in.beginObject();
  602.                 while(in.hasNext()) {
  603.                     nm = in.nextName();
  604.                    
  605.                     if(nm.equals("children")) {
  606.                         //System.out.println("2");
  607.                         in.beginArray();
  608.                         in.beginObject();
  609.                        
  610.                         while(in.hasNext()) {
  611.                             nm = in.nextName();
  612.                            
  613.                             if(nm.equals("data")) {
  614.                                 //System.out.println("3");
  615.                                 in.beginObject();
  616.                                 while(in.hasNext()) {
  617.                                     nm = in.nextName();
  618.                                    
  619.                                     JsonToken type = in.peek();
  620.                                     switch(type) {
  621.                                     case STRING:
  622.                                         data.put(nm, in.nextString());
  623.                                         break;
  624.                                     case NUMBER:
  625.                                         data.put(nm,  in.nextDouble());
  626.                                         break;
  627.                                     case NULL:
  628.                                         data.put(nm, null);
  629.                                         in.skipValue();
  630.                                         break;
  631.                                     case BOOLEAN:
  632.                                         data.put(nm, in.nextBoolean());
  633.                                         break;
  634.                                     default:
  635. //                                      System.out.println("Skipping a " + type);
  636.                                         in.skipValue();
  637. //                                      System.out.println("Still have stuff: " + in.hasNext());
  638.                                         break;
  639.                                     }
  640.                                 }
  641.                                 in.endObject();
  642.                             }else
  643.                                 in.skipValue();
  644.                         }
  645.                        
  646.                         in.endObject();
  647.                         in.endArray();
  648.                     }else {
  649.                         in.skipValue();
  650.                     }
  651.                 }
  652.                 in.endObject();
  653.             }else {
  654.                 in.skipValue();
  655.             }
  656.            
  657.         }
  658.         in.endObject();
  659.         in.close();
  660.        
  661.         c.oppermalink = (String) data.get("url");
  662.         //System.out.println(data);
  663.        
  664.     }
  665. }
Add Comment
Please, Sign In to add comment