Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //extern alias bouncy; //потому что HMACSHA256 есть и в bouncy castle, а мне нужен только один
- using System;
- using System.IO;
- using System.Collections.Generic;
- using System.Data.Objects;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using SeasideResearch.LibCurlNet;
- using System.Security.Cryptography;
- using System.Web;
- namespace TaskRunner
- {
- public static class InstagramPrivateAPI
- {
- // Потому что string - immutable, мы не можем в OnWriteData её поменять
- // А так - можем
- private class ReferenceString
- {
- public string val = "";
- }
- private static string proxyPass = "";
- static InstagramPrivateAPI()
- {
- using (var mydb = new RobogramEntities())
- {
- proxyPass = mydb.Settings.Single(t => t.Name == "proxy-n-vpn.com").Value;
- }
- Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL);
- }
- public static Random rand = new Random(DateTime.Now.Millisecond);
- public static CURLcode OnSSLContext(SSLContext ctx, Object extraData)
- {
- // To do anything useful with the SSLContext object, you'll need
- // to call the OpenSSL native methods on your own. So for this
- // demo, we just return what cURL is expecting.
- return CURLcode.CURLE_OK;
- }
- public static Int32 OnWriteData(Byte[] buf, Int32 size, Int32 nmemb,
- Object extraData)
- {
- //Console.Write(System.Text.Encoding.UTF8.GetString(buf));
- ((ReferenceString)extraData).val += System.Text.Encoding.UTF8.GetString(buf);
- return size * nmemb;
- }
- public static Int32 OnReadData(Byte[] buf, Int32 size, Int32 nmemb,
- Object extraData)
- {
- FileStream fs = (FileStream)extraData;
- return fs.Read(buf, 0, size * nmemb);
- }
- public static string SendRequest(string url, bool post, string post_data, string user_agent, bool cookies, string userid)
- {
- Easy.ReadFunction rf;
- FileStream fs;
- ReferenceString instagram_response = new ReferenceString();
- int d = 0;
- bool success = true;
- //Наша задача - попробовать сначала выполнить действие без авторизации, а если не получилось -
- //то его же, но уже после авторизации
- do
- {
- Easy easy = new Easy();
- Easy.WriteFunction wf = new Easy.WriteFunction(OnWriteData);
- easy.SetOpt(CURLoption.CURLOPT_URL, "https://i.instagram.com/api/v1/" + url);
- easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf);
- easy.SetOpt(CURLoption.CURLOPT_WRITEDATA, instagram_response);
- easy.SetOpt(CURLoption.CURLOPT_USERAGENT, user_agent);
- easy.SetOpt(CURLoption.CURLOPT_FOLLOWLOCATION, true);
- Easy.SSLContextFunction sf = new Easy.SSLContextFunction(OnSSLContext);
- easy.SetOpt(CURLoption.CURLOPT_SSL_CTX_FUNCTION, sf);
- easy.SetOpt(CURLoption.CURLOPT_CAINFO, "ca-bundle.crt");
- easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, false);
- var prms = GetProxyName(userid).Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
- easy.SetOpt(CURLoption.CURLOPT_PROXY, prms[0]);
- easy.SetOpt(CURLoption.CURLOPT_PROXYPORT, prms[1]);
- easy.SetOpt(CURLoption.CURLOPT_PROXYTYPE, CURLproxyType.CURLPROXY_HTTP);
- easy.SetOpt(CURLoption.CURLOPT_PROXYUSERPWD, prms[2] + ':' + prms[3]);
- if (post)
- {
- easy.SetOpt(CURLoption.CURLOPT_POST, true);
- easy.SetOpt(CURLoption.CURLOPT_POSTFIELDS, post_data);
- }
- if (cookies)
- {
- easy.SetOpt(CURLoption.CURLOPT_COOKIEFILE, string.Format("cookies{0}.txt", userid));
- }
- else
- {
- easy.SetOpt(CURLoption.CURLOPT_COOKIEJAR, string.Format("cookies{0}.txt", userid));
- }
- SeasideResearch.LibCurlNet.CURLcode response = easy.Perform();
- easy.GetInfo(CURLINFO.CURLINFO_HTTP_CONNECTCODE, ref d);
- easy.Cleanup();
- easy = null;
- // Curl.GlobalCleanup(); обойдемся без этого
- } while (!success);
- return instagram_response.val;
- }
- private static string GetProxyName(string userid)
- {
- string proxyName;
- using (var mydb = new RobogramEntities())
- {
- var id = Convert.ToInt32(userid);
- ObjectParameter proxyParameter = new ObjectParameter("proxyName", typeof(String));
- mydb.TuneProxy(id, proxyParameter);
- proxyName = proxyParameter.Value as string;
- }
- //proxyName = "http://95.172.40.0";
- return proxyName;
- }
- public static string GenerateGuid()
- {
- var rand = new System.Random();
- return string.Format("{0}{1}-{2}-{3}-{4}-{5}{6}{7}",
- rand.Next(0, 65535).ToString("x4"),
- rand.Next(0, 65535).ToString("x4"),
- rand.Next(0, 65535).ToString("x4"),
- rand.Next(16384, 20479).ToString("x4"),
- rand.Next(32768, 49151).ToString("x4"),
- rand.Next(0, 65535).ToString("x4"),
- rand.Next(0, 65535).ToString("x4"),
- rand.Next(0, 65535).ToString("x4"));
- }
- public static string GenerateUserAgent()
- {
- var resolutions = new string[] {"1920x1080" };
- var versions = new string[] { "SM-N9005" };
- var dpis = new string[] { "480"};
- var ver = versions[new System.Random().Next(0, versions.Count() - 1)];
- var dpi = dpis[new System.Random().Next(0, dpis.Count() - 1)];
- var res = resolutions[new System.Random().Next(0, resolutions.Count() - 1)];
- var vers = "";
- using (var mydb = new RobogramEntities())
- {
- vers = mydb.Settings.Single(t => t.Name == "InstagramVersion").Value.Trim();
- }
- return "Instagram " + vers + " Android (" +
- new System.Random().Next(10, 11).ToString() + "/" +
- new System.Random().Next(1, 3).ToString() + "." +
- new System.Random().Next(3, 5).ToString() + "." + new System.Random().Next(0, 5).ToString() +
- "; " + dpi + "; " + res + "; samsung; " + ver + "; " + ver + "; smdkc210; en_US)";
- }
- public static string GenerateSignature(string data)
- {
- var secret = "";
- using (var mydb = new RobogramEntities())
- {
- secret = mydb.Settings.Single(t => t.Name == "InstagramSecret").Value.Trim();
- }
- //secret = "d39d6469891a5bd8f5fa51e9d5028fd6814bd2a06c5b21e58f61d95ee34ee9ad";
- var secretBytes = Encoding.UTF8.GetBytes(secret);
- var dataBytes = Encoding.UTF8.GetBytes(data);
- string signature = "";
- using (var hmac = new /*bouncy.*/System.Security.Cryptography.HMACSHA256(secretBytes))
- {
- var hash = hmac.ComputeHash(dataBytes);
- for (int i = 0; i < hash.Length; i++)
- {
- signature += hash[i].ToString("x2");
- }
- // signature = Convert.ToBase64String(hash);
- }
- return signature;
- }
- public static string datetimeToUnixEpoch(DateTime datetime)
- {
- DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
- return ((int)(datetime - sTime).TotalSeconds).ToString();
- }
- public static string GetPostData(string filename)
- {
- if (!System.IO.File.Exists(filename))
- {
- Console.WriteLine(string.Format("The image {0} doesn't exist ", filename));
- return null;
- }
- else
- {
- string post_data = "device_timestamp=" + datetimeToUnixEpoch(DateTime.Now) +
- "&" + "photo=";
- foreach (var byt in System.IO.File.ReadAllBytes(filename))
- {
- post_data += byt.ToString("x2");
- }
- return post_data;
- }
- }
- public class InstaResponse
- {
- public string status;
- public string media_id;
- }
- public static bool login(string userid, string username, string password)
- {
- // Define the GuID
- string guid = GenerateGuid();
- // Define the user agent
- string agent = GenerateUserAgent();
- // Set the devide ID
- string device_id = "android-" + guid;
- /* LOG IN */
- // You must be logged in to the account that you wish to post a photo too
- // Set all of the parameters in the string, and then sign it with their API key using SHA-256
- string data = "{\"device_id\":\"" + device_id + "\",\"guid\":\"" + guid + "\",\"username\":\"" +
- username + "\",\"password\":\"" + password + "\",\"Content-Type\":\"application/" +
- "x-www-form-urlencoded; charset=UTF-8\"}";
- var sig = GenerateSignature(data);
- InstaResponse obj = null;
- data = "signed_body=" + sig + "." + System.Web.HttpUtility.UrlEncode(data) + "&ig_sig_key_version=7";
- string login = SendRequest("accounts/login/", true, data, agent, false, userid);
- if (login.StartsWith("Sorry, an error occurred while processing this request."))
- {
- return false;
- }
- else
- {
- if (string.IsNullOrEmpty(login))
- {
- return false;
- }
- else
- {
- // Decode the array that is returned
- try
- {
- obj = Newtonsoft.Json.JsonConvert.DeserializeObject<InstaResponse>(login);
- var status = obj.status;
- if (status == "ok") return true;
- }
- catch
- {
- }
- }
- }
- return false;
- }
- //Отдельная функция для постинга лайков
- public static InstaSharp.Models.Responses.LikesResponse likesPost(InstaSharp.Endpoints.Likes likes, string mediaId)
- {
- InstaSharp.Models.Responses.LikesResponse response =
- new InstaSharp.Models.Responses.LikesResponse
- {
- Meta = new InstaSharp.Models.Meta(),
- Data = ""
- };
- string data;
- string sig;
- var agent = GenerateUserAgent();
- string post;
- data = "{\"media_id\":\"" + mediaId + "\"}";
- //data = "{\"user_id\":\"186865763\"}";
- sig = GenerateSignature(data);
- data = "signed_body=" + sig + "." + System.Web.HttpUtility.UrlEncode(data) + "&ig_sig_key_version=7";
- //post = SendRequest("media/upload/", true, data, agent, true);
- post = SendRequest(string.Format("media/{0}/like/", mediaId), true, data, agent, true, likes.OAuthResponse.User.Id.ToString());
- string userid = likes.OAuthResponse.User.Id.ToString();
- //Если мы не смогли авторизоваться, ещё раз пытаться не будем
- if (post.Contains("login_required"))
- {
- using (var mydb = new RobogramEntities())
- {
- Users user = mydb.Users.Single(t => t.UserID == userid);
- bool loginresult = login(userid, user.Username, StringCipher.Decrypt(user.Userpass, user.UserpassSalt));
- if (!loginresult)
- {
- throw new Exception(strings.PasswordInvalid);
- }
- else {
- post = SendRequest(string.Format("media/{0}/like/", mediaId), true, data, agent, true, likes.OAuthResponse.User.Id.ToString());
- }
- }
- }
- // Decode the response
- var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<InstaResponse>(post);
- if (obj == null)
- {
- response.Meta.ErrorMessage = "The access_token provided is invalid.";
- response.Meta.Code = System.Net.HttpStatusCode.Forbidden;
- return response;
- }
- else
- {
- var status = obj.status;
- if (status == "ok")
- {
- response.Meta.ErrorMessage = null;
- response.Meta.Code = System.Net.HttpStatusCode.OK;
- return response;
- }
- }
- response.Meta.ErrorMessage = "The access_token provided is invalid.";
- response.Meta.Code = System.Net.HttpStatusCode.Forbidden;
- return response;
- }
- //Отдельная функция для подписок
- public static InstaSharp.Models.Responses.RelationshipResponse relationship(InstaSharp.Endpoints.Relationships relationship, int otherUserId,
- InstaSharp.Endpoints.Relationships.Action action)
- {
- InstaSharp.Models.Responses.RelationshipResponse response =
- new InstaSharp.Models.Responses.RelationshipResponse
- {
- Meta = new InstaSharp.Models.Meta(),
- Data = new InstaSharp.Models.Relationship()
- };
- string data;
- string sig;
- string post;
- data = "{\"user_id\":\"" + otherUserId + "\"}";
- sig = GenerateSignature(data);
- var agent = GenerateUserAgent();
- data = "signed_body=" + sig + "." + System.Web.HttpUtility.UrlEncode(data) + "&ig_sig_key_version=7";
- //post = SendRequest("media/upload/", true, data, agent, true);
- string endpoint = "";
- switch (action)
- {
- case InstaSharp.Endpoints.Relationships.Action.Follow:
- endpoint = "create";
- break;
- case InstaSharp.Endpoints.Relationships.Action.Unfollow:
- endpoint = "destroy";
- break;
- default:
- response.Meta.Code = System.Net.HttpStatusCode.OK;
- return response;
- }
- if (action == InstaSharp.Endpoints.Relationships.Action.Follow) endpoint = "create";
- post = SendRequest(string.Format("friendships/{0}/{1}/", endpoint, otherUserId), true, data, agent, true, relationship.OAuthResponse.User.Id.ToString());
- string userid = relationship.OAuthResponse.User.Id.ToString();
- //Если мы не смогли авторизоваться, ещё раз пытаться не будем
- if (post.Contains("login_required"))
- {
- using (var mydb = new RobogramEntities())
- {
- Users user = mydb.Users.Single(t => t.UserID == userid);
- bool loginresult = login(userid, user.Username, StringCipher.Decrypt(user.Userpass, user.UserpassSalt));
- if (!loginresult)
- {
- throw new Exception(strings.PasswordInvalid);
- }
- else
- {
- post = SendRequest(string.Format("friendships/{0}/{1}/", endpoint, otherUserId), true, data, agent, true, relationship.OAuthResponse.User.Id.ToString());
- }
- }
- }
- // Decode the response
- var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<InstaResponse>(post);
- if (obj == null)
- {
- response.Meta.ErrorMessage = "The access_token provided is invalid.";
- response.Meta.Code = System.Net.HttpStatusCode.Forbidden;
- return response;
- }
- else
- {
- var status = obj.status;
- //TODO: relationship
- if (status == "ok")
- {
- response.Meta.ErrorMessage = null;
- response.Meta.Code = System.Net.HttpStatusCode.OK;
- return response;
- }
- }
- response.Meta.ErrorMessage = "The access_token provided is invalid.";
- response.Meta.Code = System.Net.HttpStatusCode.Forbidden;
- return response;
- }
- public static bool run()
- {
- bool isLogin;
- using (var mydb = new RobogramEntities())
- {
- isLogin = login(
- mydb.Settings.Single(t => t.Name == "PrivateAPICode").Value,
- mydb.Settings.Single(t => t.Name == "PrivateAPILogin").Value,
- mydb.Settings.Single(t => t.Name == "PrivateAPIPass").Value);
- }
- return isLogin;
- //return login("1538319607", "dmitrelisov", "25del12");
- // Set the path to the file that you wish to post.
- // This must be jpeg format and it must be a perfect square
- //string filename = "pictures/test.jpg";
- //// Set the caption for the photo
- //string caption = "Test caption";
- //// Post the picture
- //// data = GetPostData(filename);
- //string[] post = null;
- //// Remove and line breaks from the caption
- //caption = caption.Replace("\r", "").Replace("\n", "");
- //var media_id = obj.media_id;
- //device_id = "android-" + guid;
- //data = "{\"device_id\":\"" + device_id + "\",\"guid\":\"" + guid +
- // "\",\"media_id\":\"" + media_id + "\",\"caption\":\"" +
- // caption.Trim() + "\",\"device_timestamp\":\"" +
- // datetimeToUnixEpoch(DateTime.Now) +
- // "\",\"source_type\":\"5\",\"filter_type\":\"0\",\"extra\":\"{}\"" +
- // ",\"Content-Type\":\"application/x-www-form-urlencoded; charset=UTF-8\"}";
- // sig = GenerateSignature(data);
- // var new_data = "signed_body=" + sig + "." +
- // System.Web.HttpUtility.UrlEncode(data) + "&ig_sig_key_version=6";
- // string[] conf = null;
- // try
- // {
- // // Now, configure the photo
- // conf = SendRequest("media/configure/", true, new_data, agent, true);
- // }
- // catch
- // {
- // Console.WriteLine("Empty response received from the server while " +
- // "trying to configure the image");
- // }
- // if (conf[1].StartsWith("login_required"))
- // {
- // Console.WriteLine("You are not logged in. There's a chance " +
- // "that the account is banned");
- // }
- // else
- // {
- // obj = Newtonsoft.Json.JsonConvert.DeserializeObject<InstaResponse>(post[0]);
- // status = obj.status;
- // if (status != "fail")
- // {
- // Console.WriteLine("Success");
- // }
- // else
- // {
- // Console.WriteLine("Fail");
- // }
- // }
- // }
- // else
- // {
- // Console.WriteLine("Status isn't okay");
- // }
- }
- }
- }
Add Comment
Please, Sign In to add comment