Advertisement
Guest User

Untitled

a guest
Apr 8th, 2018
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 16.25 KB | None | 0 0
  1. import Entity.AccountsEntity;
  2. import Entity.FollowListsEntity;
  3. import Entity.ProxyEntity;
  4. import org.apache.http.HttpHost;
  5. import org.apache.http.auth.AuthScope;
  6. import org.apache.http.auth.UsernamePasswordCredentials;
  7. import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
  8. import org.apache.log4j.Logger;
  9. import org.brunocvcunha.instagram4j.Instagram4j;
  10. import org.brunocvcunha.instagram4j.requests.*;
  11. import org.brunocvcunha.instagram4j.requests.payload.*;
  12. import org.hibernate.Session;
  13. import org.hibernate.SessionFactory;
  14. import org.hibernate.cfg.Configuration;
  15. import javax.persistence.Query;
  16. import java.io.*;
  17. import java.util.List;
  18. import java.net.URL;
  19. import java.net.URLConnection;
  20. import java.util.Random;
  21.  
  22. public class Main {
  23.  
  24.     private static final Logger log = Logger.getLogger(Main.class); //create logger
  25.  
  26.     public static void main(String[] args) throws InterruptedException {
  27.         doProcessing(); //debug
  28.         //while (true) doProcessing(); //production
  29.     }
  30.  
  31.     /**
  32.      * Main method
  33.      */
  34.     static private void doProcessing() throws InterruptedException {
  35.         if (isConnected()) { // if isset internet connection
  36.             log.info("isConnected");
  37.  
  38.             // create connection to database
  39.             SessionFactory sessions = new Configuration().configure().buildSessionFactory();
  40.             Session session = sessions.openSession();
  41.             session.beginTransaction();
  42.  
  43.             //select all columns from accounts table where status = 1
  44.             Query accountsQuery = session.createQuery("from AccountsEntity where status = :code ");
  45.             accountsQuery.setParameter("code", "1");
  46.             List<AccountsEntity> accountsList = (List<AccountsEntity>) accountsQuery.getResultList();
  47.  
  48.             if (!accountsList.isEmpty()) { // if accountsList not empty
  49.                 log.info("!accountsList.isEmpty");
  50.                 String accountId = accountsList.get(0).getAccountId(); //user account_id
  51.  
  52.                 //select all columns from proxy table where accountId = this.accountId
  53.                 Query proxyQuery = session.createQuery("from ProxyEntity where accountId = :code ");
  54.                 proxyQuery.setParameter("code", accountId);
  55.                 List<ProxyEntity> proxyList = (List<ProxyEntity>) proxyQuery.getResultList();
  56.                 String proxyUser = proxyList.get(0).getLogin();
  57.                 String proxyPass = proxyList.get(0).getPassword();
  58.                 String proxyHost = proxyList.get(0).getHost();
  59.                 String[] proxyHostPortSplit = proxyHost.split(":");
  60.  
  61.                 //select all from follow_list table where accountId = this.accountId
  62.                 Query followListQuery = session.createQuery("from FollowListsEntity where accountId = :accountId ");
  63.                 followListQuery.setParameter("accountId", accountId);
  64.                 List<FollowListsEntity> followListsEntityList = (List<FollowListsEntity>) followListQuery.getResultList();
  65.                 String[] list = followListsEntityList.get(0).getList().split("::");
  66.  
  67.                 if (!followListsEntityList.isEmpty()) { //if followList not empty
  68.                     log.info("!followListsEntityList.isEmpty");
  69.                     String username = accountsList.get(0).getLogin(); //user login
  70.                     String password = accountsList.get(0).getPassword(); //user password
  71.                     //MixedArray followList = Pherialize.unserialize(followListsEntityList.get(0).getList()).toArray();//accounts list to following
  72.                     int action = accountsList.get(0).getAction(); //action (1-following; 2-following&liking; 3-unfollowing)
  73.                     int startFollows = accountsList.get(0).getStartFollows(); //count for resume work on restart app
  74.  
  75.                     //get cookie file for login with it
  76.                     /*ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
  77.                             "/var/www/ciliogram.loc/vendor/mgp25/instagram-php/sessions/"+username+"/"+username+"-cookies.dat"));
  78.                             //"C:/Users/Admin/Desktop/yrozenketter-cookies.dat"));
  79.                     CookieStore cookieStore = (CookieStore) ois.readObject();
  80.                     ois.close();*/
  81.  
  82.                     log.info("Creating thread");
  83.                     //set status = 2 in accounts where accountId = this.accountId
  84.                     Query query = session.createQuery("update AccountsEntity set status = :status where accountId = :account");
  85.                     query.setParameter("status", "2");
  86.                     query.setParameter("account", accountId);
  87.                     query.executeUpdate();
  88.                     session.getTransaction().commit();
  89.  
  90.                     Thread myThready = new Thread(() -> { //create new thread
  91.                         try {
  92.                             switch (action) {
  93.                                 case 1: // if action is 1 (following)
  94.                                     doFollowing(username, password, list, startFollows, proxyHostPortSplit[0], Integer.parseInt(proxyHostPortSplit[1]), proxyUser, proxyPass);
  95.                                     break;
  96.                                 case 2: // if action is 2 (following&liking)
  97.                                     doFollowingAndLiking(username, password, list, startFollows, proxyHostPortSplit[0], Integer.parseInt(proxyHostPortSplit[1]), proxyUser, proxyPass);
  98.                                     break;
  99.                                 case 3: // if action = 3  (unfollowing)
  100.                                     doUnfollowing(username, password, Long.parseLong(accountId), proxyHostPortSplit[0], Integer.parseInt(proxyHostPortSplit[1]), proxyUser, proxyPass);
  101.                                     break;
  102.                                 default: //exception
  103.                                     System.exit(0); //debug
  104.                                     break;
  105.                             }
  106.                         } catch (IOException | InterruptedException e) {
  107.                             e.printStackTrace();
  108.                         }
  109.                         log.info("Start thread");
  110.                     });
  111.                     myThready.start(); // start created thread
  112.                 }
  113.             }
  114.         }
  115.         log.info("[Main Thread] Sleep 5 mins.");
  116.         Thread.sleep(300000); //sleep 5 mins
  117.     }
  118.  
  119.     /**
  120.      * Following method
  121.      */
  122.     static private void doFollowing(String username, String password, String[] list, int startFollows,
  123.                                     String server, int port, String proxyUser, String pass) throws IOException, InterruptedException {
  124.     }
  125.  
  126.     /**
  127.      * Following and liking method
  128.      */
  129.     static private void doFollowingAndLiking(String username, String password, String[] list, int startFollows,
  130.                                              String server, int port, String proxyUser, String pass) throws IOException, InterruptedException {
  131.         Instagram4j instagram = Instagram4j.builder().username(username).password(password).build();//create instagram object
  132.         instagram.setup(); //setup settings before login
  133.         //Login with proxy:
  134.         HttpHost proxy = new HttpHost(server, port, "http");
  135.         DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
  136.         instagram.getClient().setRoutePlanner(routePlanner);
  137.         instagram.getClient().getParams().setIntParameter("http.connection.timeout", 6000000);
  138.         instagram.getClient().getCredentialsProvider().setCredentials(new AuthScope(server, port), new UsernamePasswordCredentials(proxyUser, pass));
  139.         log.info("Using proxy: " + server + ":" + port + ", user: " + proxyUser + ", pass: " + pass);
  140.         InstagramLoginResult loginResult = instagram.login(); //login
  141.         if (instagram.isLoggedIn() && loginResult.getStatus().equals("ok")) { // if login = true
  142.             log.info("isLoggedIn");
  143.             int count = 0;
  144.             for (int i = startFollows; i < list.length-1; i++) {//starting loop from startFollows count
  145.                 log.info("Start iteration " + i);
  146.  
  147.                 SessionFactory sessions = new Configuration().configure().buildSessionFactory();
  148.                 Session session = sessions.openSession();
  149.                 session.beginTransaction();
  150.                 Query startFollowsQuery = session.createQuery("update AccountsEntity set startFollows = :startFollows where accountId = :account");
  151.                 startFollowsQuery.setParameter("startFollows", i);
  152.                 startFollowsQuery.setParameter("account", String.valueOf(instagram.getUserId()));
  153.                 startFollowsQuery.executeUpdate();
  154.                 session.getTransaction().commit();
  155.  
  156.                 //get friendship status (following, followed_by)
  157.                 InstagramFriendshipStatus status = instagram.sendRequest(new InstagramGetFriendshipRequest(Long.parseLong(list[i].trim())));
  158.                 if (!status.following && !status.followed_by && !status.outgoing_request && !status.incoming_request && !status.is_private && !status.blocking) {
  159.                     log.info("Following user " + list[i]);
  160.                     StatusResult followRequest = instagram.sendRequest(new InstagramFollowRequest(Long.parseLong(list[i].trim())));//follow account from list
  161.                     count++;
  162.                     if(followRequest.isSpam()){
  163.                         setAccountStatus(instagram, "Spam block.");
  164.                         int rnd = getRandomNumberInRange(1320000, 1980000);// create random delay from 52 to 77 seconds
  165.                         log.warn("Spam block. Sleep 22-33 minutes.");
  166.                         Thread.sleep(rnd); //sleep random delay
  167.                         --i;
  168.                         count = 0;
  169.                     } else if (followRequest.getStatus().equals("fail")){
  170.                         setAccountStatus(instagram, followRequest.getFeedback_title());
  171.                         int rnd = getRandomNumberInRange(1320000, 1980000);// create random delay from 52 to 77 seconds
  172.                         log.warn(followRequest.getFeedback_title() + ". Sleep 22-33 minutes.");
  173.                         Thread.sleep(rnd); //sleep random delay
  174.                         --i;
  175.                         count = 0;
  176.                     } else if (!status.is_private && !status.isBlocking()) {
  177.                         int rnd_int = getRandomNumberInRange(15000, 25000); // create random delay from 15 to 25 seconds
  178.                         log.info("Sleep " + rnd_int / 1000 + "sec.");
  179.                         Thread.sleep(rnd_int); //sleep random delay
  180.                         //get account from list feed
  181.                         InstagramFeedResult media = instagram.sendRequest(new InstagramUserFeedRequest(Long.parseLong(list[i].trim())));
  182.                         List<InstagramFeedItem> listMedia = media.getItems(); //get items from feed
  183.                         log.info("Liking random media");
  184.                         if (listMedia.size() >= 6) { //if account have more then 5 items in feed
  185.                             //like random item from 1 to 6
  186.                             instagram.sendRequest(new InstagramLikeRequest(listMedia.get(getRandomNumberInRange(0, 5)).getPk()));
  187.                         } else if (listMedia.size() >= 3) { //if account have more then 2 items in feed
  188.                             //like random item from 1 to 3
  189.                             instagram.sendRequest(new InstagramLikeRequest(listMedia.get(getRandomNumberInRange(0, 2)).getPk()));
  190.                         } else { //if account have less then 3 items in feed
  191.                             //like first item
  192.                             instagram.sendRequest(new InstagramLikeRequest(listMedia.get(0).getPk()));
  193.                         }
  194.                         count++;
  195.                         int rnd = getRandomNumberInRange(52000, 77000);// create random delay from 52 to 77 seconds
  196.                         log.info("Sleep " + rnd / 1000 + "sec.");
  197.                         Thread.sleep(rnd); //sleep random delay
  198.                         if (count >= 60) {
  199.                             count = 0;
  200.                             Thread.sleep(getRandomNumberInRange(1320000, 1980000));
  201.                             log.info("Count > 60, sleep 22-33 minutes.");
  202.                         }
  203.                     }
  204.                 } else { //if we followed account from list OR account from list followed us
  205.                     log.info("Skipping following user " + list[i]); //skip
  206.                 }
  207.             }
  208.         } else {
  209.             setAccountStatus(instagram, "Login failed.");
  210.         }
  211.     }
  212.  
  213.     /**
  214.      * Unfollowing method
  215.      */
  216.     static private void doUnfollowing(String username, String password, Long accId,
  217.                                       String server, int port, String proxyUser, String pass) throws IOException, InterruptedException {
  218.         Instagram4j instagram = Instagram4j.builder().username(username).password(password).build();//create instagram object
  219.         instagram.setup();//setup settings before login
  220.         //Login with proxy:
  221.         HttpHost proxy = new HttpHost(server, port, "http");
  222.         DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
  223.         instagram.getClient().setRoutePlanner(routePlanner);
  224.         instagram.getClient().getParams().setIntParameter("http.connection.timeout", 600000);
  225.         instagram.getClient().getCredentialsProvider().setCredentials(new AuthScope(server, port), new UsernamePasswordCredentials(proxyUser, pass));
  226.         instagram.login();//login into account
  227.         if (instagram.isLoggedIn()) {// if login = true
  228.             log.info("isLoggedIn");
  229.             //get user following list
  230.             InstagramGetUserFollowersResult userFollowing = instagram.sendRequest(new InstagramGetUserFollowingRequest(accId));
  231.             List<InstagramUserSummary> users = userFollowing.getUsers();
  232.             for (InstagramUserSummary user : users) {  //for this list...
  233.                 //get friendship status (following, followed_by)
  234.                 InstagramFriendshipStatus status = instagram.sendRequest(new InstagramGetFriendshipRequest(user.getPk()));
  235.                 if (status.following || status.followed_by) { //if we followed account from list OR account from list followed us
  236.                     log.info("Unfollowing user " + user.getPk());
  237.                     instagram.sendRequest(new InstagramUnfollowRequest(user.getPk())); //unfollow account from list
  238.                     int rnd = getRandomNumberInRange(52000, 77000);// create random delay from 52 to 77 seconds
  239.                     log.info("Sleep " + rnd / 1000 + "sec.");
  240.                     Thread.sleep(rnd);//sleep random delay
  241.                 } else {//if we don`t followed account from list OR account from list don`t followed us
  242.                     log.info("Skipping unfollowing user " + user.getPk()); //skip
  243.                 }
  244.             }
  245.         }
  246.     }
  247.  
  248.     /**
  249.      * Random int method
  250.      */
  251.     private static int getRandomNumberInRange(int min, int max) {
  252.         if (min >= max) {
  253.             throw new IllegalArgumentException("max must be greater than min");
  254.         }
  255.         Random r = new Random();
  256.         return r.nextInt((max - min) + 1) + min;
  257.     }
  258.  
  259.     /**
  260.      * @return bool Connected server to internet or not
  261.      */
  262.     private static boolean isConnected() {
  263.         try {
  264.             URL url = new URL("http://google.com");
  265.             URLConnection connection = url.openConnection();
  266.             connection.connect();
  267.             return true;
  268.         } catch (Exception e) {
  269.             return false;
  270.         }
  271.     }
  272.  
  273.     private static void setAccountStatus(Instagram4j instagram, String status) {
  274.         if(status == null && status == "") {
  275.             status = "NullStatus";
  276.         }
  277.         SessionFactory sessions = new Configuration().configure().buildSessionFactory();
  278.         Session session = sessions.openSession();
  279.         session.beginTransaction();
  280.         Query query = session.createQuery("update AccountsEntity set status = :status where accountId = :account");
  281.         query.setParameter("status", status);
  282.         query.setParameter("account", String.valueOf(instagram.getUserId()));
  283.         query.executeUpdate();
  284.         session.getTransaction().commit();
  285.     }
  286. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement