Guest User

Untitled

a guest
Jul 8th, 2016
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 21.69 KB | None | 0 0
  1. //extern alias bouncy; //потому что HMACSHA256 есть и в bouncy castle, а мне нужен только один
  2. using System;
  3. using System.IO;
  4. using System.Collections.Generic;
  5. using System.Data.Objects;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using SeasideResearch.LibCurlNet;
  10. using System.Security.Cryptography;
  11. using System.Web;
  12.  
  13. namespace TaskRunner
  14. {
  15.  
  16.     public static class InstagramPrivateAPI
  17.     {
  18.         // Потому что string - immutable, мы не можем в OnWriteData её поменять
  19.         // А так - можем
  20.         private class ReferenceString
  21.         {
  22.             public string val = "";
  23.         }
  24.         private static string proxyPass = "";
  25.  
  26.         static InstagramPrivateAPI()
  27.         {
  28.  
  29.             using (var mydb = new RobogramEntities())
  30.             {
  31.                 proxyPass = mydb.Settings.Single(t => t.Name == "proxy-n-vpn.com").Value;
  32.             }
  33.             Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL);
  34.         }
  35.  
  36.         public static Random rand = new Random(DateTime.Now.Millisecond);
  37.  
  38.         public static CURLcode OnSSLContext(SSLContext ctx, Object extraData)
  39.         {
  40.             // To do anything useful with the SSLContext object, you'll need
  41.             // to call the OpenSSL native methods on your own. So for this
  42.             // demo, we just return what cURL is expecting.
  43.             return CURLcode.CURLE_OK;
  44.         }
  45.  
  46.         public static Int32 OnWriteData(Byte[] buf, Int32 size, Int32 nmemb,
  47.              Object extraData)
  48.         {
  49.             //Console.Write(System.Text.Encoding.UTF8.GetString(buf));
  50.             ((ReferenceString)extraData).val += System.Text.Encoding.UTF8.GetString(buf);
  51.             return size * nmemb;
  52.         }
  53.  
  54.         public static Int32 OnReadData(Byte[] buf, Int32 size, Int32 nmemb,
  55.         Object extraData)
  56.         {
  57.             FileStream fs = (FileStream)extraData;
  58.             return fs.Read(buf, 0, size * nmemb);
  59.         }
  60.  
  61.         public static string SendRequest(string url, bool post, string post_data, string user_agent, bool cookies, string userid)
  62.         {
  63.  
  64.             Easy.ReadFunction rf;
  65.             FileStream fs;
  66.             ReferenceString instagram_response = new ReferenceString();
  67.             int d = 0;
  68.             bool success = true;
  69.             //Наша задача - попробовать сначала выполнить действие без авторизации, а если не получилось -
  70.             //то его же, но уже после авторизации
  71.             do
  72.             {
  73.                 Easy easy = new Easy();
  74.                 Easy.WriteFunction wf = new Easy.WriteFunction(OnWriteData);
  75.                 easy.SetOpt(CURLoption.CURLOPT_URL, "https://i.instagram.com/api/v1/" + url);
  76.                 easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf);
  77.                 easy.SetOpt(CURLoption.CURLOPT_WRITEDATA, instagram_response);
  78.                 easy.SetOpt(CURLoption.CURLOPT_USERAGENT, user_agent);
  79.                 easy.SetOpt(CURLoption.CURLOPT_FOLLOWLOCATION, true);
  80.  
  81.                 Easy.SSLContextFunction sf = new Easy.SSLContextFunction(OnSSLContext);
  82.                 easy.SetOpt(CURLoption.CURLOPT_SSL_CTX_FUNCTION, sf);
  83.                 easy.SetOpt(CURLoption.CURLOPT_CAINFO, "ca-bundle.crt");
  84.                 easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, false);
  85.  
  86.                 var prms = GetProxyName(userid).Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
  87.                 easy.SetOpt(CURLoption.CURLOPT_PROXY, prms[0]);
  88.                 easy.SetOpt(CURLoption.CURLOPT_PROXYPORT, prms[1]);
  89.                 easy.SetOpt(CURLoption.CURLOPT_PROXYTYPE, CURLproxyType.CURLPROXY_HTTP);
  90.                 easy.SetOpt(CURLoption.CURLOPT_PROXYUSERPWD, prms[2] + ':' + prms[3]);
  91.  
  92.                 if (post)
  93.                 {
  94.                     easy.SetOpt(CURLoption.CURLOPT_POST, true);
  95.                     easy.SetOpt(CURLoption.CURLOPT_POSTFIELDS, post_data);
  96.                 }
  97.  
  98.                 if (cookies)
  99.                 {
  100.                     easy.SetOpt(CURLoption.CURLOPT_COOKIEFILE, string.Format("cookies{0}.txt", userid));
  101.                 }
  102.                 else
  103.                 {
  104.                     easy.SetOpt(CURLoption.CURLOPT_COOKIEJAR, string.Format("cookies{0}.txt", userid));
  105.                 }
  106.  
  107.  
  108.                 SeasideResearch.LibCurlNet.CURLcode response = easy.Perform();
  109.                 easy.GetInfo(CURLINFO.CURLINFO_HTTP_CONNECTCODE, ref d);
  110.                 easy.Cleanup();
  111.                 easy = null;
  112.                 // Curl.GlobalCleanup(); обойдемся без этого
  113.             } while (!success);
  114.  
  115.             return instagram_response.val;
  116.         }
  117.  
  118.         private static string GetProxyName(string userid)
  119.         {
  120.             string proxyName;
  121.             using (var mydb = new RobogramEntities())
  122.             {
  123.                 var id = Convert.ToInt32(userid);
  124.                 ObjectParameter proxyParameter = new ObjectParameter("proxyName", typeof(String));
  125.  
  126.                 mydb.TuneProxy(id, proxyParameter);
  127.                 proxyName = proxyParameter.Value as string;
  128.             }
  129.             //proxyName = "http://95.172.40.0";
  130.             return proxyName;
  131.         }
  132.  
  133.         public static string GenerateGuid()
  134.         {
  135.             var rand = new System.Random();
  136.             return string.Format("{0}{1}-{2}-{3}-{4}-{5}{6}{7}",
  137.                    rand.Next(0, 65535).ToString("x4"),
  138.                    rand.Next(0, 65535).ToString("x4"),
  139.                   rand.Next(0, 65535).ToString("x4"),
  140.                    rand.Next(16384, 20479).ToString("x4"),
  141.                   rand.Next(32768, 49151).ToString("x4"),
  142.                    rand.Next(0, 65535).ToString("x4"),
  143.                    rand.Next(0, 65535).ToString("x4"),
  144.                    rand.Next(0, 65535).ToString("x4"));
  145.         }
  146.  
  147.         public static string GenerateUserAgent()
  148.         {
  149.             var resolutions = new string[] {"1920x1080" };
  150.             var versions = new string[] { "SM-N9005" };
  151.             var dpis = new string[] { "480"};
  152.  
  153.             var ver = versions[new System.Random().Next(0, versions.Count() - 1)];
  154.             var dpi = dpis[new System.Random().Next(0, dpis.Count() - 1)];
  155.             var res = resolutions[new System.Random().Next(0, resolutions.Count() - 1)];
  156.  
  157.             var vers = "";
  158.             using (var mydb = new RobogramEntities())
  159.             {
  160.                 vers = mydb.Settings.Single(t => t.Name == "InstagramVersion").Value.Trim();
  161.             }
  162.             return "Instagram " + vers + " Android (" +
  163.                 new System.Random().Next(10, 11).ToString() + "/" +
  164.                 new System.Random().Next(1, 3).ToString() + "." +
  165.                 new System.Random().Next(3, 5).ToString() + "." + new System.Random().Next(0, 5).ToString() +
  166.                 "; " + dpi + "; " + res + "; samsung; " + ver + "; " + ver + "; smdkc210; en_US)";
  167.         }
  168.  
  169.         public static string GenerateSignature(string data)
  170.         {
  171.             var secret = "";
  172.             using (var mydb = new RobogramEntities())
  173.             {
  174.                 secret = mydb.Settings.Single(t => t.Name == "InstagramSecret").Value.Trim();
  175.             }
  176.             //secret = "d39d6469891a5bd8f5fa51e9d5028fd6814bd2a06c5b21e58f61d95ee34ee9ad";
  177.  
  178.             var secretBytes = Encoding.UTF8.GetBytes(secret);
  179.             var dataBytes = Encoding.UTF8.GetBytes(data);
  180.             string signature = "";
  181.  
  182.             using (var hmac = new /*bouncy.*/System.Security.Cryptography.HMACSHA256(secretBytes))
  183.             {
  184.                 var hash = hmac.ComputeHash(dataBytes);
  185.                 for (int i = 0; i < hash.Length; i++)
  186.                 {
  187.                     signature += hash[i].ToString("x2");
  188.                 }
  189.                 //    signature = Convert.ToBase64String(hash);
  190.             }
  191.             return signature;
  192.         }
  193.         public static string datetimeToUnixEpoch(DateTime datetime)
  194.         {
  195.             DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  196.             return ((int)(datetime - sTime).TotalSeconds).ToString();
  197.         }
  198.  
  199.         public static string GetPostData(string filename)
  200.         {
  201.             if (!System.IO.File.Exists(filename))
  202.             {
  203.                 Console.WriteLine(string.Format("The image {0} doesn't exist ", filename));
  204.                 return null;
  205.             }
  206.             else
  207.             {
  208.                 string post_data = "device_timestamp=" + datetimeToUnixEpoch(DateTime.Now) +
  209.                     "&" + "photo=";
  210.                 foreach (var byt in System.IO.File.ReadAllBytes(filename))
  211.                 {
  212.                     post_data += byt.ToString("x2");
  213.                 }
  214.                 return post_data;
  215.             }
  216.         }
  217.  
  218.         public class InstaResponse
  219.         {
  220.             public string status;
  221.             public string media_id;
  222.         }
  223.  
  224.  
  225.         public static bool login(string userid, string username, string password)
  226.         {
  227.             // Define the GuID
  228.             string guid = GenerateGuid();
  229.  
  230.             // Define the user agent
  231.             string agent = GenerateUserAgent();
  232.  
  233.             // Set the devide ID
  234.             string device_id = "android-" + guid;
  235.  
  236.             /* LOG IN */
  237.             // You must be logged in to the account that you wish to post a photo too
  238.             // Set all of the parameters in the string, and then sign it with their API key using SHA-256
  239.             string data = "{\"device_id\":\"" + device_id + "\",\"guid\":\"" + guid + "\",\"username\":\"" +
  240.                          username + "\",\"password\":\"" + password + "\",\"Content-Type\":\"application/" +
  241.                          "x-www-form-urlencoded; charset=UTF-8\"}";
  242.             var sig = GenerateSignature(data);
  243.             InstaResponse obj = null;
  244.             data = "signed_body=" + sig + "." + System.Web.HttpUtility.UrlEncode(data) + "&ig_sig_key_version=7";
  245.             string login = SendRequest("accounts/login/", true, data, agent, false, userid);
  246.  
  247.  
  248.             if (login.StartsWith("Sorry, an error occurred while processing this request."))
  249.             {
  250.                 return false;
  251.             }
  252.             else
  253.             {
  254.                 if (string.IsNullOrEmpty(login))
  255.                 {
  256.                     return false;
  257.                 }
  258.                 else
  259.                 {
  260.                     //  Decode the array that is returned
  261.                     try
  262.                     {
  263.                         obj = Newtonsoft.Json.JsonConvert.DeserializeObject<InstaResponse>(login);
  264.                         var status = obj.status;
  265.                         if (status == "ok") return true;
  266.                     }
  267.                     catch
  268.                     {
  269.                     }
  270.                 }
  271.             }
  272.             return false;
  273.         }
  274.  
  275.         //Отдельная функция для постинга лайков
  276.         public static InstaSharp.Models.Responses.LikesResponse likesPost(InstaSharp.Endpoints.Likes likes, string mediaId)
  277.         {
  278.             InstaSharp.Models.Responses.LikesResponse response =
  279.                 new InstaSharp.Models.Responses.LikesResponse
  280.                 {
  281.                     Meta = new InstaSharp.Models.Meta(),
  282.                     Data = ""
  283.                 };
  284.             string data;
  285.             string sig;
  286.             var agent = GenerateUserAgent();
  287.             string post;
  288.             data = "{\"media_id\":\"" + mediaId + "\"}";
  289.             //data = "{\"user_id\":\"186865763\"}";
  290.             sig = GenerateSignature(data);
  291.             data = "signed_body=" + sig + "." + System.Web.HttpUtility.UrlEncode(data) + "&ig_sig_key_version=7";
  292.  
  293.             //post = SendRequest("media/upload/", true, data, agent, true);
  294.             post = SendRequest(string.Format("media/{0}/like/", mediaId), true, data, agent, true, likes.OAuthResponse.User.Id.ToString());
  295.             string userid = likes.OAuthResponse.User.Id.ToString();
  296.             //Если мы не смогли авторизоваться, ещё раз пытаться не будем
  297.             if (post.Contains("login_required"))
  298.             {
  299.                 using (var mydb = new RobogramEntities())
  300.                 {
  301.                     Users user = mydb.Users.Single(t => t.UserID == userid);
  302.                     bool loginresult = login(userid, user.Username, StringCipher.Decrypt(user.Userpass, user.UserpassSalt));
  303.                     if (!loginresult)
  304.                     {
  305.                         throw new Exception(strings.PasswordInvalid);
  306.                     }
  307.                     else {
  308.                          post = SendRequest(string.Format("media/{0}/like/", mediaId), true, data, agent, true, likes.OAuthResponse.User.Id.ToString());
  309.                     }
  310.                 }
  311.             }
  312.  
  313.             // Decode the response
  314.             var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<InstaResponse>(post);
  315.  
  316.             if (obj == null)
  317.             {
  318.                 response.Meta.ErrorMessage = "The access_token provided is invalid.";
  319.                 response.Meta.Code = System.Net.HttpStatusCode.Forbidden;
  320.                 return response;
  321.             }
  322.             else
  323.             {
  324.                 var status = obj.status;
  325.  
  326.                 if (status == "ok")
  327.                 {
  328.                     response.Meta.ErrorMessage = null;
  329.                     response.Meta.Code = System.Net.HttpStatusCode.OK;
  330.                     return response;
  331.                 }
  332.             }
  333.             response.Meta.ErrorMessage = "The access_token provided is invalid.";
  334.             response.Meta.Code = System.Net.HttpStatusCode.Forbidden;
  335.             return response;
  336.         }
  337.  
  338.         //Отдельная функция для подписок
  339.         public static InstaSharp.Models.Responses.RelationshipResponse relationship(InstaSharp.Endpoints.Relationships relationship, int otherUserId,
  340.                                                                                                  InstaSharp.Endpoints.Relationships.Action action)
  341.         {
  342.             InstaSharp.Models.Responses.RelationshipResponse response =
  343.                                                 new InstaSharp.Models.Responses.RelationshipResponse
  344.                                                 {
  345.                                                     Meta = new InstaSharp.Models.Meta(),
  346.                                                     Data = new InstaSharp.Models.Relationship()
  347.                                                 };
  348.             string data;
  349.             string sig;
  350.             string post;
  351.             data = "{\"user_id\":\"" +  otherUserId + "\"}";
  352.             sig = GenerateSignature(data);
  353.             var agent = GenerateUserAgent();
  354.             data = "signed_body=" + sig + "." + System.Web.HttpUtility.UrlEncode(data) + "&ig_sig_key_version=7";
  355.             //post = SendRequest("media/upload/", true, data, agent, true);
  356.             string endpoint = "";
  357.             switch (action)
  358.             {
  359.                 case InstaSharp.Endpoints.Relationships.Action.Follow:
  360.                     endpoint = "create";
  361.                     break;
  362.                 case InstaSharp.Endpoints.Relationships.Action.Unfollow:
  363.                     endpoint = "destroy";
  364.                     break;
  365.                 default:
  366.                     response.Meta.Code = System.Net.HttpStatusCode.OK;
  367.                     return response;
  368.             }
  369.             if (action == InstaSharp.Endpoints.Relationships.Action.Follow) endpoint = "create";
  370.             post = SendRequest(string.Format("friendships/{0}/{1}/", endpoint, otherUserId), true, data, agent, true, relationship.OAuthResponse.User.Id.ToString());
  371.  
  372.             string userid = relationship.OAuthResponse.User.Id.ToString();
  373.             //Если мы не смогли авторизоваться, ещё раз пытаться не будем
  374.             if (post.Contains("login_required"))
  375.             {
  376.                 using (var mydb = new RobogramEntities())
  377.                 {
  378.                     Users user = mydb.Users.Single(t => t.UserID == userid);
  379.                     bool loginresult = login(userid, user.Username, StringCipher.Decrypt(user.Userpass, user.UserpassSalt));
  380.                     if (!loginresult)
  381.                     {
  382.                         throw new Exception(strings.PasswordInvalid);
  383.                     }
  384.                     else
  385.                     {
  386.                         post = SendRequest(string.Format("friendships/{0}/{1}/", endpoint, otherUserId), true, data, agent, true, relationship.OAuthResponse.User.Id.ToString());
  387.                     }
  388.                 }
  389.             }
  390.  
  391.             // Decode the response
  392.             var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<InstaResponse>(post);
  393.  
  394.             if (obj == null)
  395.             {
  396.                 response.Meta.ErrorMessage = "The access_token provided is invalid.";
  397.                 response.Meta.Code = System.Net.HttpStatusCode.Forbidden;
  398.                 return response;
  399.             }
  400.             else
  401.             {
  402.                 var status = obj.status;
  403.                 //TODO: relationship
  404.                 if (status == "ok")
  405.                 {
  406.                     response.Meta.ErrorMessage = null;
  407.                     response.Meta.Code = System.Net.HttpStatusCode.OK;
  408.                     return response;
  409.                 }
  410.             }
  411.             response.Meta.ErrorMessage = "The access_token provided is invalid.";
  412.             response.Meta.Code = System.Net.HttpStatusCode.Forbidden;
  413.             return response;
  414.         }
  415.  
  416.  
  417.         public static bool run()
  418.         {
  419.             bool isLogin;
  420.             using (var mydb = new RobogramEntities())
  421.             {
  422.                 isLogin = login(
  423.                     mydb.Settings.Single(t => t.Name == "PrivateAPICode").Value,
  424.                     mydb.Settings.Single(t => t.Name == "PrivateAPILogin").Value,
  425.                     mydb.Settings.Single(t => t.Name == "PrivateAPIPass").Value);
  426.             }
  427.             return isLogin;
  428.  
  429.             //return login("1538319607", "dmitrelisov", "25del12");
  430.  
  431.             // Set the path to the file that you wish to post.
  432.             // This must be jpeg format and it must be a perfect square
  433.             //string filename = "pictures/test.jpg";
  434.  
  435.             //// Set the caption for the photo
  436.             //string caption = "Test caption";
  437.             //// Post the picture
  438.             //// data = GetPostData(filename);
  439.             //string[] post = null;
  440.  
  441.             //// Remove and line breaks from the caption
  442.             //caption = caption.Replace("\r", "").Replace("\n", "");
  443.  
  444.  
  445.  
  446.             //var media_id = obj.media_id;
  447.             //device_id = "android-" + guid;
  448.             //data = "{\"device_id\":\"" + device_id + "\",\"guid\":\"" + guid +
  449.             //    "\",\"media_id\":\"" + media_id + "\",\"caption\":\"" +
  450.             //    caption.Trim() + "\",\"device_timestamp\":\"" +
  451.             //    datetimeToUnixEpoch(DateTime.Now) +
  452.             //    "\",\"source_type\":\"5\",\"filter_type\":\"0\",\"extra\":\"{}\"" +
  453.             //    ",\"Content-Type\":\"application/x-www-form-urlencoded; charset=UTF-8\"}";
  454.             //                            sig = GenerateSignature(data);
  455.             //                            var new_data = "signed_body=" + sig + "." +
  456.             //                                System.Web.HttpUtility.UrlEncode(data) + "&ig_sig_key_version=6";
  457.  
  458.             //                            string[] conf = null;
  459.             //                            try
  460.             //                            {
  461.             //                                // Now, configure the photo
  462.             //                                conf = SendRequest("media/configure/", true, new_data, agent, true);
  463.             //                            }
  464.             //                            catch
  465.             //                            {
  466.             //                                Console.WriteLine("Empty response received from the server while " +
  467.             //                                    "trying to configure the image");
  468.  
  469.             //                            }
  470.  
  471.             //                            if (conf[1].StartsWith("login_required"))
  472.             //                            {
  473.             //                                Console.WriteLine("You are not logged in. There's a chance " +
  474.             //                                    "that the account is banned");
  475.             //                            }
  476.             //                            else
  477.             //                            {
  478.             //                                obj = Newtonsoft.Json.JsonConvert.DeserializeObject<InstaResponse>(post[0]);
  479.             //                                status = obj.status;
  480.  
  481.             //                                if (status != "fail")
  482.             //                                {
  483.             //                                    Console.WriteLine("Success");
  484.             //                                }
  485.             //                                else
  486.             //                                {
  487.             //                                    Console.WriteLine("Fail");
  488.             //                                }
  489.             //                            }
  490.             //                        }
  491.             //                        else
  492.             //                        {
  493.             //                            Console.WriteLine("Status isn't okay");
  494.             //                        }
  495.         }
  496.     }
  497. }
Add Comment
Please, Sign In to add comment