Advertisement
LaPanthere

[C#] MyBB Class v2

Mar 26th, 2014
1,239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 34.20 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.IO;
  7. using System.Net;
  8. using System.Threading;
  9.  
  10. namespace MyBBBot_v2
  11. {
  12.     public class MessageReceivedEventArgs : EventArgs
  13.     {
  14.         public string Message;
  15.         public ActionRequired ActionRequired;
  16.     }
  17.     public enum ActionRequired : int
  18.     {
  19.         MyBBCaptcha = 0,
  20.         GoogleCaptcha = 1,
  21.         SecurityQuestion = 2,
  22.     }
  23.     public class MyBB
  24.     {
  25.         /// <summary>
  26.         /// The board URL
  27.         /// </summary>
  28.         public string URL { get; set; }
  29.  
  30.         /// <summary>
  31.         /// The post key for the user.
  32.         /// </summary>
  33.         public string my_post_key { get; set; }
  34.  
  35.         /// <summary>
  36.         /// The user's UID
  37.         /// </summary>
  38.         public string UID { get; set; }
  39.  
  40.         /// <summary>
  41.         /// The board URL without the trailing slash.
  42.         /// </summary>
  43.         /// <param name="boardUrl"></param>
  44.         public MyBB(string boardUrl)
  45.         {
  46.             this.URL = boardUrl;
  47.         }
  48.  
  49.         private bool callbackComplete = false;
  50.         private string callbackData = "";
  51.  
  52.         public event MessageReceivedEventHandler MessageReceived;
  53.  
  54.         public delegate void MessageReceivedEventHandler(object sender, MessageReceivedEventArgs e);
  55.  
  56.         /// <summary>
  57.         /// Logs a MyBB User in and stores their cookie
  58.         /// </summary>
  59.         /// <param name="user">Username</param>
  60.         /// <param name="pass">Password</param>
  61.         /// <returns>Returns true if the user has been successfully logged in.</returns>
  62.         public bool Login(string user, string pass)
  63.         {
  64.             string data = Connections.postRequest(URL + "/member.php", string.Format("action=do_login&url=&username={0}&password={1}", user, pass), "");
  65.             if (!data.Contains("invalid") && !data.Contains("verification"))
  66.             {
  67.                 Regex mypostkey = new Regex(@"(?<=my_post_key = "").*?(?="")");
  68.                 my_post_key = mypostkey.Match(data).Value;
  69.  
  70.                 Regex userID = new Regex("<a href=\".*\\?action=profile&amp;uid=(.*?)\">");
  71.                 UID = userID.Match(data).Groups[1].Value;
  72.                 return true;
  73.             }
  74.             return false;
  75.         }
  76.  
  77.         /// <summary>
  78.         /// Gets the Cloudflare clearance cookie, bypassing Cloudflare's Under-Attack Mode
  79.         /// </summary>
  80.         /// <returns></returns>
  81.         public bool GetCloudflareCookie()
  82.         {
  83.             string cloudflare = Connections.getRequest(URL, "");
  84.  
  85.             Regex answer = new Regex(@".value\s+=\s([\d\+\*\-]+)");
  86.             Regex vc = new Regex(@"""([a-fA-F\d]{32})""");
  87.  
  88.             Match matchAnswer = answer.Match(cloudflare);
  89.             Match matchVC = vc.Match(cloudflare);
  90.  
  91.             string vcstr = matchVC.Groups[1].Value;
  92.             Uri url = new Uri(URL);
  93.             string answerstr = matchAnswer.Groups[1].Value + "+" + url.Host.Length;
  94.  
  95.             MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
  96.             sc.Language = "VBScript";
  97.             int result = (int)sc.Eval(answerstr);
  98.  
  99.             string url2 = string.Format("http://{0}/cdn-cgi/l/chk_jschl?jschl_vc={1}&jschl_answer={2}", url.Host, vcstr, result.ToString());
  100.  
  101.             string good = Connections.getRequest(url2, "");
  102.  
  103.             if (good.Contains("Hello There, Guest!") || good.Contains("MyBB"))
  104.                 return true;
  105.             else
  106.                 return false;
  107.         }
  108.  
  109.         /// <summary>
  110.         /// Reports a specific post ID
  111.         /// </summary>
  112.         /// <param name="postId">The post ID to report</param>
  113.         /// <param name="reason">The reason to display</param>
  114.         /// <returns>Returns true if successful.</returns>
  115.         public bool ReportPost(string postId, string reason)
  116.         {
  117.             string data = Connections.postRequest(URL + "/report.php", string.Format("my_post_key={0}&action=do_report&pid={1}&reason={2}", my_post_key, postId, reason), URL + "/index.php");
  118.             if (data.ToLower().Contains("thank you"))
  119.             {
  120.                 return true;
  121.             }
  122.             return false;
  123.         }
  124.  
  125.         /// <summary>
  126.         /// Gives reputation to the specified user id.
  127.         /// </summary>
  128.         /// <param name="userID">The <see cref="UID"/> of the user.</param>
  129.         /// <param name="amount">The amount of reputation, 0 for neutural.</param>
  130.         /// <param name="repComment">The comment to display on the reputation.</param>
  131.         /// <returns>Returns true if successful.</returns>
  132.         public bool GiveReputation(string userID, int amount, string repComment)
  133.         {
  134.             string data = Connections.postRequest(URL + "/reputation.php", string.Format("my_post_key={0}&action=do_add&uid={1}&pid=0&rid=&reputation={2}&comments={3}", my_post_key, userID, amount, repComment), URL + "/index.php");
  135.             if (data.ToLower().Contains("addded"))
  136.             {
  137.                 return true;
  138.             }
  139.             return false;
  140.         }
  141.  
  142.         /// <summary>
  143.         /// Performs a shout in the MyBBShoutbox
  144.         /// </summary>
  145.         /// <param name="text">The text to send.</param>
  146.         /// <returns>Returns true if successful.</returns>
  147.         public bool ShoutMyShoutbox(string text)
  148.         {
  149.             string data = Connections.postRequest(URL + "/xmlhttp.php?action=add_shout", "shout_data=" + text, URL + "/index.php");
  150.             if (data.ToLower().Contains("success!!"))
  151.             {
  152.                 return true;
  153.             }
  154.             return false;
  155.         }
  156.  
  157.         /// <summary>
  158.         /// Creates a post on the specified thread ID
  159.         /// </summary>
  160.         /// <param name="threadID">The thread ID to post on.</param>
  161.         /// <param name="subject">The subject of the post.</param>
  162.         /// <param name="message">The message of the post.</param>
  163.         /// <returns>Returns true if successful.</returns>
  164.         public bool CreatePost(string threadID, string subject, string message)
  165.         {
  166.             string postHash = "";
  167.             string lastPostID = "";
  168.             string fromPage = "";
  169.  
  170.             string threadPage = Connections.getRequest(string.Format("{0}/showthread.php?tid={1}", URL, threadID), URL + "/index.php");
  171.  
  172.             Regex postHashR = new Regex(@"(?<=name=""posthash"" value="").*?(?="")");
  173.             Regex lastPostIDR = new Regex(@"(?<=id=""lastpid"" value="").*?(?="")");
  174.             Regex fromPageR = new Regex(@"(?<=name=""from_page"" value="").*?(?="")");
  175.  
  176.             postHash = postHashR.Match(threadPage).Value;
  177.             lastPostID = lastPostIDR.Match(threadPage).Value;
  178.             fromPage = fromPageR.Match(threadPage).Value;
  179.  
  180.             if (postHash != "" && lastPostID != "" && fromPage != "")
  181.             {
  182.                 string data = Connections.postRequest(URL + "/newreply.php?ajax=1", string.Format("my_post_key={0}&subject={1}&action=do_newreply&posthash={2}&quoted_ids=&lastpid={3}&from_page={4}&tid={5}&method=quickreply&postoptions%5Bsignature%5D=1&message={6}&previewpost=Preview%20Post", my_post_key, subject, postHashR, lastPostID, fromPage, threadID, message), URL + "/index.php");
  183.                 if (!data.Contains("The massage is too short.") && !data.Contains("The subject is too short."))
  184.                 {
  185.                     return true;
  186.                 }
  187.                 return false;
  188.             }
  189.             return false;
  190.         }
  191.  
  192.         /// <summary>
  193.         /// Creates a thread in the specified forum ID
  194.         /// </summary>
  195.         /// <param name="forumID">The forum ID to post the thread in.</param>
  196.         /// <param name="subject">The subject of the thread.</param>
  197.         /// <param name="newMessage">The message of the thread.</param>
  198.         /// <returns>Returns true if successful.</returns>
  199.         public bool CreateThread(string forumID, string subject, string newMessage)
  200.         {
  201.             string postHash = "";
  202.             Regex postHashR = new Regex(@"(?<=name=""posthash"" value="").*?(?="")");
  203.  
  204.             string threadCreate = Connections.getRequest(URL + "/newthread.php?fid=" + forumID, URL + "/index.php");
  205.  
  206.             postHash = postHashR.Match(threadCreate).Value;
  207.            
  208.             Dictionary<string, object> Params = new Dictionary<string, object>();
  209.  
  210.             Params.Add("my_post_key", my_post_key);
  211.             Params.Add("threadprefix", "0");
  212.             Params.Add("subject", subject);
  213.             Params.Add("icon", "-1");
  214.             Params.Add("message_new", newMessage);
  215.             Params.Add("message", newMessage);
  216.             Params.Add("postoptions[signature]", "1");
  217.             Params.Add("postoptions[subscriptionmethod", "");
  218.             Params.Add("numpolloptions", "2");
  219.             Params.Add("attachment", new FormUpload.FileParameter(null, ""));
  220.             Params.Add("submit", "Post Thread");
  221.             Params.Add("action", "do_newthread");
  222.             Params.Add("posthash", postHash);
  223.             Params.Add("attachmentaid", "");
  224.             Params.Add("attachmentact", "");
  225.             Params.Add("quoted_ids", "");
  226.             Params.Add("tid", "");
  227.  
  228.             HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(URL + "/newthread.php?fid=" + forumID + "&processed=1", Connections.randUserAgent(), Params);
  229.  
  230.             StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
  231.             string fullResponse = responseReader.ReadToEnd();
  232.             webResponse.Close();
  233.  
  234.             return true;
  235.         }
  236.         public bool Register(string username, string password, string email, bool securityQuestions)
  237.         {
  238.             string failPage = Connections.postRequest(URL + "/member.php", "regcheck1=&regcheck2=true&username=&password=&password2=&email=&email2=&referrername=&imagestring=&imagehash=&allownotices=1&receivepms=1&pmnotice=1&subscriptionmethod=0&timezoneoffset=10&dstcorrection=2&language=&step=registration&action=do_register&regsubmit=Submit+Registration%21", URL + "/member.php");
  239.            
  240.             Connections.cookieContainer.Add(new Cookie("coppadob", Connections.Rnd.Next(1, 25).ToString() + "-" + Connections.Rnd.Next(1, 12).ToString() + "-" + Connections.Rnd.Next(1940, 2000).ToString(), "/", new Uri(URL).Host));
  241.             Regex mybbImageHash = new Regex(@"imagehash=.*?(?="")");
  242.             Regex googleImageHash = new Regex(@"http://api.recaptcha.net/challenge\?.*?(?="")");
  243.             Regex googleImageHash2 = new Regex(@"htt(p|ps)://www.google.com/recaptcha/api/challenge\?k=.*?(?="")");
  244.            
  245.             Regex regSecID = new Regex("regsecureq_id.*?=\"(.*?)\"");
  246.             Regex regSecQuestion = new Regex("regsecureq\".*?>(.*?)</span>");
  247.  
  248.             Match matchMyBB = mybbImageHash.Match(failPage);
  249.             Match matchGoogle = googleImageHash.Match(failPage);
  250.             Match matchGoogle2 = googleImageHash2.Match(failPage);
  251.  
  252.             Match matchRegSecQuestion = regSecQuestion.Match(failPage);
  253.             Match matchRegSecId = regSecID.Match(failPage);
  254.  
  255.             string regSecurityQuestion = "";
  256.             string regSecurityQuestionID = "";
  257.  
  258.             if (securityQuestions)
  259.             {
  260.                 regSecurityQuestion = matchRegSecQuestion.Groups[1].Value;
  261.                 regSecurityQuestionID = matchRegSecId.Groups[1].Value;
  262.             }
  263.             if (matchMyBB.Value != "" && matchMyBB.Success)
  264.             {
  265.                 string imageLink = GetImageMyBB(matchMyBB.Value);
  266.  
  267.  
  268.                 MessageReceivedEventArgs e = new MessageReceivedEventArgs();
  269.                 e.ActionRequired = ActionRequired.MyBBCaptcha;
  270.                 e.Message = imageLink;
  271.                 MessageReceived(this, e);
  272.                 while (!callbackComplete)
  273.                 {
  274.                     Thread.Sleep(500);
  275.                 }
  276.                 string captcha = callbackData; // CHANGE IN REQUEST
  277.  
  278.                 callbackComplete = false;
  279.                 callbackData = "";
  280.  
  281.                 if (securityQuestions)
  282.                 {
  283.                     MessageReceivedEventArgs e2 = new MessageReceivedEventArgs();
  284.                     e2.ActionRequired = ActionRequired.SecurityQuestion;
  285.                     e2.Message = regSecurityQuestion;
  286.  
  287.                     MessageReceived(this, e2);
  288.                     while (!callbackComplete)
  289.                     {
  290.                         Thread.Sleep(500);
  291.                     }
  292.                 }
  293.                 string realPage = "";
  294.                 string shit = matchMyBB.Value.Replace("imagehash=", "");
  295.                 if (!securityQuestions)
  296.                 {
  297.                     realPage = Connections.postRequest(URL + "/member.php", string.Format("regcheck1=&regcheck2=true&username={0}&password={1}&password2={2}&email={3}&email2={4}&referrername=&imagestring={5}&imagehash={6}&allownotices=1&receivepms=1&pmnotice=1&subscriptionmethod=0&timezoneoffset=10&dstcorrection=2&language=&step=registration&action=do_register&regsubmit=Submit+Registration%21", username, password, password, email, email, captcha, matchMyBB.Value.Replace("imagehash=", "")), URL + "/member.php");
  298.                 }
  299.                 else
  300.                 {
  301.                     realPage = Connections.postRequest(URL + "/member.php", string.Format("regcheck1=&regcheck2=true&username={0}&password={1}&password2={2}&email={3}&email2={4}&referrername=&imagestring={5}&imagehash={6}&regsecureans={7}&regsecureq_id={8}&allownotices=1&receivepms=1&pmnotice=1&subscriptionmethod=0&timezoneoffset=10&dstcorrection=2&language=&step=registration&action=do_register&regsubmit=Submit+Registration%21", username, password, password, email, email, captcha, matchMyBB.Value.Replace("imagehash=", ""), callbackData, regSecurityQuestionID), URL + "/member.php");
  302.                 }
  303.                 callbackComplete = false;
  304.                 callbackData = "";
  305.  
  306.                 if (realPage.Contains("Thank you for registering") || realPage.Contains("You last visited:") || realPage.Contains(username))
  307.                 {
  308.                     return true;
  309.                 }
  310.                 return false;
  311.             }
  312.             else if (matchGoogle.Value != "" && matchGoogle.Success || matchGoogle2.Value != "" && matchGoogle2.Success)
  313.             {
  314.                 string imageLink = "";
  315.                 string imageChallenge = "";
  316.                 if (matchGoogle.Value != "")
  317.                 {
  318.                     string[] data = GetImageGoogle(matchGoogle2.Value).Split('|');
  319.                     imageLink = data[0];
  320.                     imageChallenge = data[1];
  321.                 }
  322.                 else
  323.                 {
  324.                     string[] data = GetImageGoogle(matchGoogle2.Value).Split('|');
  325.                     imageLink = data[0];
  326.                     imageChallenge = data[1];
  327.                 }
  328.                 MessageReceivedEventArgs e = new MessageReceivedEventArgs();
  329.                 e.ActionRequired = ActionRequired.GoogleCaptcha;
  330.                 e.Message = imageLink;
  331.                 MessageReceived(this, e);
  332.                 while (!callbackComplete)
  333.                 {
  334.                     Thread.Sleep(500);
  335.                 }
  336.                 string captcha = callbackData;
  337.  
  338.                 callbackComplete = false;
  339.                 callbackData = "";
  340.  
  341.                 if (securityQuestions)
  342.                 {
  343.                     MessageReceivedEventArgs e2 = new MessageReceivedEventArgs();
  344.                     e2.ActionRequired = ActionRequired.SecurityQuestion;
  345.                     e2.Message = regSecurityQuestion;
  346.  
  347.                     MessageReceived(this, e2);
  348.                     while (!callbackComplete)
  349.                     {
  350.                         Thread.Sleep(500);
  351.                     }
  352.                 }
  353.                 string realPage = "";
  354.                 if (!securityQuestions)
  355.                 {
  356.                     realPage = Connections.postRequest(URL + "/member.php", "regcheck1=&regcheck2=true&username=" + username + "&password=" + password + "&password2=" + password + "&email=" + email + "&email2=" + email + "&referrername=&recaptcha_challenge_field=" + imageChallenge + "&recaptcha_response_field=" + captcha + "&allownotices=1&receivepms=1&pmnotice=1&subscriptionmethod=2&timezoneoffset=-5&dstcorrection=2&language=&step=registration&action=do_register&regsubmit=Submit+Registration%21", URL + "/member.php");
  357.                 }
  358.                 else
  359.                 {
  360.                     realPage = Connections.postRequest(URL + "/member.php", "regcheck1=&regcheck2=true&username=" + username + "&password=" + password + "&password2=" + password + "&email=" + email + "&email2=" + email + "&referrername=&recaptcha_challenge_field=" + imageChallenge + "&recaptcha_response_field=" + captcha + "&regsecureans=" + callbackData + "&regsecureq_id=" + regSecurityQuestionID + "&allownotices=1&receivepms=1&pmnotice=1&subscriptionmethod=2&timezoneoffset=-5&dstcorrection=2&language=&step=registration&action=do_register&regsubmit=Submit+Registration%21", URL + "/member.php");
  361.                 }
  362.                    
  363.                 callbackComplete = false;
  364.                 callbackData = "";
  365.  
  366.                 if (realPage.Contains("Thank you for registering") || realPage.Contains("You last visited:"))
  367.                 {
  368.                     return true;
  369.                 }
  370.                 return false;
  371.             }
  372.             return false;
  373.         }
  374.         private string GetImageMyBB(string data)
  375.         {
  376.             return URL + "/captcha.php?action=regimage&" + data;
  377.         }
  378.         private string GetImageGoogle(string data)
  379.         {
  380.             Regex challRegex = new Regex("(?<=challenge : ').*?(?=')");
  381.  
  382.             Match challMatch = challRegex.Match(Connections.getRequest(data, ""));
  383.  
  384.             if (challMatch.Success)
  385.             {
  386.                 string imageLink = "http://www.google.com/recaptcha/api/image?c=" + challMatch.Value + "|" + challMatch.Value;
  387.                 return imageLink;
  388.             }
  389.             return "";
  390.         }
  391.         public void CallBackAction(ActionRequired act, string answer)
  392.         {
  393.             callbackData = answer;
  394.             callbackComplete = true;
  395.         }
  396.  
  397.         /// <summary>
  398.         /// Verifies the board account associated with the specified mailcatch.com email
  399.         /// </summary>
  400.         /// <param name="emailaddress">The mailcatch.com email address associated with the board account, @mailcatch.com</param>
  401.         /// <returns></returns>
  402.         public bool VerifyEmail(string emailaddress)
  403.         {
  404.             Regex mainPageRegex = new Regex("href=\"(\\?box=.*?&show.*?)\"");
  405.  
  406.             string mainPage = Connections.getRequest("http://mailcatch.com/en/temporary-inbox?box=" + emailaddress.Remove(emailaddress.IndexOf("@")), "");
  407.  
  408.             Match matchMainPage = mainPageRegex.Match(mainPage);
  409.  
  410.             if (matchMainPage.Success)
  411.             {
  412.                 string link = "http://mailcatch.com/en/temporary-inbox" + matchMainPage.Groups[1].Value;
  413.  
  414.                 //Regex activateUrlRegex = new Regex(string.Format("href=\"({0}/member.php\\?action=activate&uid=.*?)\"", URL));
  415.                 Regex activateUrlRegex = new Regex(string.Format("({0}/member.php\\?action=activate&uid=.*)", URL));
  416.                 string emailPage = Connections.getRequest(link, "");
  417.  
  418.                 emailPage = emailPage.Replace("&amp;", "&");
  419.  
  420.                 Match matchActivate = activateUrlRegex.Match(emailPage);
  421.  
  422.                 if (matchActivate.Success)
  423.                 {
  424.                     string activatePage = Connections.getRequest(matchActivate.Groups[1].Value, "");
  425.                     if (!activatePage.ToLower().Contains("account is already activated") || !activatePage.ToLower().Contains("hello there, guest"))
  426.                         return true;
  427.                     else
  428.                         return false;
  429.                 }
  430.             }
  431.             return false;
  432.         }
  433.     }
  434.     class Connections
  435.     {
  436.         public static Random Rnd = new Random();
  437.         public static CookieContainer cookieContainer { get; set; }
  438.         public static byte[] ReceivedData { get; set; }
  439.         public static string randUserAgent()
  440.         {
  441.             string[] MyStringArr = {
  442.         //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17",
  443.         "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15",
  444.         //"Mozilla/5.0 (Windows; U; Windows NT 6.1; x64; fr; rv:1.9.2.13) Gecko/20101203 Firebird/3.6.13",
  445.         //"Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1",
  446.         //"Mozilla/5.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1",
  447.         //"Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2",
  448.         //"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.2 (KHTML, like Gecko) ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/532.2",
  449.         //"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.28) Gecko/20120410 Firefox/3.6.28 Lunascape/6.7.1.25446",
  450.         //"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.8.1.9) Gecko/20071110 Sylera/3.0.20 SeaMonkey/1.1.6"
  451.     };
  452.             return MyStringArr[Rnd.Next(MyStringArr.Length)];
  453.         }
  454.  
  455.         public MatchCollection RegexMatch(string Text, string Regexstring, RegexOptions Regexoption = RegexOptions.None)
  456.         {
  457.             System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(Regexstring, Regexoption);
  458.             MatchCollection matches = r.Matches(Text.Trim());
  459.             return matches;
  460.         }
  461.  
  462.         public static string postRequest(string url, string data, string referer)
  463.         {
  464.             string postData = data;
  465.             UTF8Encoding encoding = new UTF8Encoding();
  466.             byte[] byteData = encoding.GetBytes(postData);
  467.             HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create(url);
  468.             postReq.Method = "POST";
  469.             postReq.KeepAlive = true;
  470.             postReq.Timeout = 8000;
  471.             if (cookieContainer != null)
  472.             {
  473.                 postReq.CookieContainer = cookieContainer;
  474.             }
  475.             else
  476.             {
  477.                 cookieContainer = new CookieContainer();
  478.                 postReq.CookieContainer = cookieContainer;
  479.             }
  480.             postReq.ContentType = "application/x-www-form-urlencoded";
  481.             postReq.Referer = referer;
  482.             postReq.UserAgent = randUserAgent();
  483.             postReq.ContentLength = byteData.Length;
  484.  
  485.             Stream postreqstream = postReq.GetRequestStream();
  486.             postreqstream.Write(byteData, 0, byteData.Length);
  487.             postreqstream.Close();
  488.  
  489.             HttpWebResponse postresponse = default(HttpWebResponse);
  490.             try
  491.             {
  492.                 postresponse = (HttpWebResponse)postReq.GetResponse();
  493.             }
  494.             catch (WebException ex)
  495.             {
  496.                 postresponse = (HttpWebResponse)ex.Response;
  497.             }
  498.  
  499.             foreach (Cookie cook in postresponse.Cookies)
  500.             {
  501.                 postReq.CookieContainer.Add(cook);
  502.             }
  503.             cookieContainer = postReq.CookieContainer;
  504.  
  505.             StreamReader postreqreader = new StreamReader(postresponse.GetResponseStream());
  506.             string thepage = postreqreader.ReadToEnd();
  507.             return thepage;
  508.  
  509.         }
  510.  
  511.         public static string getRequest(string url, string referer)
  512.         {
  513.  
  514.             HttpWebRequest postGet = (HttpWebRequest)WebRequest.Create(url);
  515.             postGet.Timeout = 8000;
  516.             postGet.Method = "GET";
  517.             postGet.KeepAlive = true;
  518.  
  519.             if (cookieContainer != null)
  520.             {
  521.                 postGet.CookieContainer = cookieContainer;
  522.             }
  523.             else
  524.             {
  525.                 cookieContainer = new CookieContainer();
  526.                 postGet.CookieContainer = cookieContainer;
  527.             }
  528.  
  529.             postGet.ContentType = "application/x-www-form-urlencoded";
  530.             postGet.Referer = referer;
  531.             postGet.UserAgent = randUserAgent();
  532.  
  533.             HttpWebResponse postGetresponse = null;
  534.  
  535.             try
  536.             {
  537.                 postGetresponse = (HttpWebResponse)postGet.GetResponse();
  538.             }
  539.             catch (WebException ex)
  540.             {
  541.                 postGetresponse = (HttpWebResponse)ex.Response;
  542.             }
  543.  
  544.             StreamReader postGetreader = new StreamReader(postGetresponse.GetResponseStream());
  545.  
  546.             foreach (Cookie cook in postGetresponse.Cookies)
  547.             {
  548.                 postGet.CookieContainer.Add(cook);
  549.             }
  550.  
  551.             cookieContainer = postGet.CookieContainer;
  552.  
  553.             string thepage = postGetreader.ReadToEnd();
  554.             return thepage;
  555.         }
  556.         public static string postRequestMultipart(string url, string data, string referer, string boundary)
  557.         {
  558.             string postData = data;
  559.             UTF8Encoding encoding = new UTF8Encoding();
  560.             byte[] byteData = encoding.GetBytes(postData);
  561.             HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create(url);
  562.             postReq.Method = "POST";
  563.             postReq.KeepAlive = true;
  564.             postReq.Timeout = 12000;
  565.  
  566.             if (cookieContainer != null)
  567.             {
  568.                 postReq.CookieContainer = cookieContainer;
  569.             }
  570.             else
  571.             {
  572.                 cookieContainer = new CookieContainer();
  573.                 postReq.CookieContainer = cookieContainer;
  574.             }
  575.  
  576.             postReq.ContentType = "multipart/formdata; boundary=" + boundary;
  577.             postReq.Referer = referer;
  578.             postReq.UserAgent = randUserAgent();
  579.             Stream postreqstream = postReq.GetRequestStream();
  580.             using (StreamWriter streamWriter = new StreamWriter(postreqstream))
  581.             {
  582.                 foreach (string str in data.Split(new string[] { "\r\n" }, StringSplitOptions.None))
  583.                 {
  584.                     streamWriter.WriteLine(str);
  585.                 }
  586.             }
  587.             postreqstream.Close();
  588.  
  589.             HttpWebResponse postresponse = default(HttpWebResponse);
  590.             postresponse = (HttpWebResponse)postReq.GetResponse();
  591.  
  592.             foreach (Cookie cook in postresponse.Cookies)
  593.             {
  594.                 postReq.CookieContainer.Add(cook);
  595.             }
  596.             cookieContainer = postReq.CookieContainer;
  597.  
  598.  
  599.             StreamReader postreqreader = new StreamReader(postresponse.GetResponseStream());
  600.             string thepage = postreqreader.ReadToEnd();
  601.             return thepage;
  602.         }
  603.         public static string GetImage(string url)
  604.         {
  605.             HttpWebRequest postGet = (HttpWebRequest)WebRequest.Create(url);
  606.             postGet.Timeout = 8000;
  607.             postGet.Method = "GET";
  608.             postGet.KeepAlive = true;
  609.  
  610.             if (cookieContainer != null)
  611.             {
  612.                 postGet.CookieContainer = cookieContainer;
  613.             }
  614.             else
  615.             {
  616.                 cookieContainer = new CookieContainer();
  617.                 postGet.CookieContainer = cookieContainer;
  618.             }
  619.  
  620.             postGet.ContentType = "application/x-www-form-urlencoded";
  621.             postGet.UserAgent = randUserAgent();
  622.  
  623.             HttpWebResponse postGetresponse = null;
  624.  
  625.             try
  626.             {
  627.                 postGetresponse = (HttpWebResponse)postGet.GetResponse();
  628.             }
  629.             catch (WebException ex)
  630.             {
  631.                 postGetresponse = (HttpWebResponse)ex.Response;
  632.             }
  633.  
  634.             string file = "captcha_" + Environment.TickCount.ToString() + ".png";
  635.             Byte[] lnByte = null;
  636.  
  637.             using (BinaryReader reader = new BinaryReader(postGetresponse.GetResponseStream()))
  638.             {
  639.                 lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10);
  640.                 using (FileStream lxFS = new FileStream(file, FileMode.Create))
  641.                 {
  642.                     lxFS.Write(lnByte, 0, lnByte.Length);
  643.                 }
  644.             }
  645.  
  646.             /*HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create(url);
  647.  
  648.             lxRequest.CookieContainer = cookieContainer;
  649.             lxRequest.Method = "GET";
  650.             lxRequest.KeepAlive = true;
  651.  
  652.             // returned values are returned as a stream, then read into a string
  653.            
  654.             using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse())
  655.             {
  656.                 using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream()))
  657.                 {
  658.                     lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10);
  659.                     using (FileStream lxFS = new FileStream(file, FileMode.Create))
  660.                     {
  661.                         lxFS.Write(lnByte, 0, lnByte.Length);
  662.                     }
  663.                 }
  664.             }*/
  665.             return file;
  666.         }
  667.     }
  668.     // Implements multipart/form-data POST in C# http://www.ietf.org/rfc/rfc2388.txt
  669.     // http://www.briangrinstead.com/blog/multipart-form-post-in-c
  670.     public static class FormUpload
  671.     {
  672.         private static readonly Encoding encoding = Encoding.UTF8;
  673.         public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
  674.         {
  675.             string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
  676.             string contentType = "multipart/form-data; boundary=" + formDataBoundary;
  677.  
  678.             byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
  679.  
  680.             return PostForm(postUrl, userAgent, contentType, formData);
  681.         }
  682.         private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
  683.         {
  684.             HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
  685.  
  686.             if (request == null)
  687.             {
  688.                 throw new NullReferenceException("request is not a http request");
  689.             }
  690.  
  691.             // Set up the request properties.
  692.             request.Method = "POST";
  693.             request.ContentType = contentType;
  694.             request.UserAgent = userAgent;
  695.             request.CookieContainer = Connections.cookieContainer;
  696.             request.ContentLength = formData.Length;
  697.  
  698.             // You could add authentication here as well if needed:
  699.             // request.PreAuthenticate = true;
  700.             // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
  701.             // request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));
  702.  
  703.             // Send the form data to the request.
  704.             using (Stream requestStream = request.GetRequestStream())
  705.             {
  706.                 requestStream.Write(formData, 0, formData.Length);
  707.                 requestStream.Close();
  708.             }
  709.  
  710.             return request.GetResponse() as HttpWebResponse;
  711.         }
  712.  
  713.         private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
  714.         {
  715.             Stream formDataStream = new System.IO.MemoryStream();
  716.             bool needsCLRF = false;
  717.  
  718.             foreach (var param in postParameters)
  719.             {
  720.                 // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
  721.                 // Skip it on the first parameter, add it to subsequent parameters.
  722.                 if (needsCLRF)
  723.                     formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
  724.  
  725.                 needsCLRF = true;
  726.  
  727.                 if (param.Value is FileParameter)
  728.                 {
  729.                     FileParameter fileToUpload = (FileParameter)param.Value;
  730.  
  731.                     // Add just the first part of this param, since we will write the file data directly to the Stream
  732.                     string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
  733.                         boundary,
  734.                         param.Key,
  735.                         fileToUpload.FileName ?? param.Key,
  736.                         fileToUpload.ContentType ?? "application/octet-stream");
  737.  
  738.                     formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
  739.  
  740.                     // Write the file data directly to the Stream, rather than serializing it to a string.
  741.                     //formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
  742.                 }
  743.                 else
  744.                 {
  745.                     string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
  746.                         boundary,
  747.                         param.Key,
  748.                         param.Value);
  749.                     formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
  750.                 }
  751.             }
  752.  
  753.             // Add the end of the request.  Start with a newline
  754.             string footer = "\r\n--" + boundary + "--\r\n";
  755.             formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
  756.  
  757.             // Dump the Stream into a byte[]
  758.             formDataStream.Position = 0;
  759.             byte[] formData = new byte[formDataStream.Length];
  760.             formDataStream.Read(formData, 0, formData.Length);
  761.             formDataStream.Close();
  762.  
  763.             return formData;
  764.         }
  765.  
  766.         public class FileParameter
  767.         {
  768.             public byte[] File { get; set; }
  769.             public string FileName { get; set; }
  770.             public string ContentType { get; set; }
  771.             public FileParameter(byte[] file) : this(file, null) { }
  772.             public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
  773.             public FileParameter(byte[] file, string filename, string contenttype)
  774.             {
  775.                 File = file;
  776.                 FileName = filename;
  777.                 ContentType = contenttype;
  778.             }
  779.         }
  780.     }
  781. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement