using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Windows.Forms;

namespace VKontakte
{
	public class VKClient
	{
		public struct VideoInfoCachEntity
		{
			public VideoInfo Video;

			public int GroupID;
		}

		private const string HOST = "http://vkontakte.ru/";

		private const string LOCATION_HEADER = "Location";

		private const string CONTENT_TYPE_URLENCODED = "application/x-www-form-urlencoded";

		private const string CONTENT_TYPE_MULTIPART = "multipart/form-data; boundary=";

		private const string PARSE_CAPTCHA_SID = "\"captcha_sid\":\"";

		private const string CAPTCHA_DATA = "&captcha_sid={0}&captcha_key={1}";

		private const string BLANK = "blank.php";

		private static Encoding enc_ru = Encoding.GetEncoding(1251);

		public static IWebProxy Proxy { get; set; }

		public Dictionary<int, WallMessagesPostInfo> CachWallMessagesPostInfo { get; private set; }

		public Dictionary<int, TopicsCreationInfo> CachTopicsCreationInfo { get; private set; }

		public Dictionary<TopicInfo, TopicAnswersPostInfo> CachTopicAnswersPostInfo { get; private set; }

		public Dictionary<AlbumInfo, PhotoUploadInfo> CachPhotoUploadInfo { get; private set; }

		public Dictionary<int, AudioUploadInfo> CachAudioUploadInfo { get; private set; }

		public Dictionary<VideoInfoCachEntity, VideoAddInfo> CachVideoAddInfo { get; private set; }

		public Dictionary<VideoInfo, VideoCommentsPostInfo> CachVideoCommentsPostInfo { get; private set; }

		public VKAccount Account { get; private set; }

		public static VKAccount Authorize(string email, string pass)
		{
			if (email == null)
			{
				throw new NullReferenceException("Параметр email не имеет значения.");
			}
			if (pass == null)
			{
				throw new NullReferenceException("Параметр pass не имеет значения.");
			}
			string aut_Cookies = null;
			string text = null;
			string text2 = null;
			string key = null;
			do
			{
				string text3 = $"login.php?op=a_login_attempt&email={HttpUtility.UrlEncode(email)}&pass={HttpUtility.UrlEncode(pass)}";
				if (key != null)
				{
					text3 += $"&captcha_sid={text2}&captcha_key={key}";
				}
				VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/" + text3, Proxy);
				text2 = null;
				key = null;
				HttpWebResponse response = vKRequest.GetResponse();
				StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
				string text4 = streamReader.ReadLine();
				streamReader.Close();
				if (text4.StartsWith("good"))
				{
					List<string> list = new List<string>();
					string[] values = response.Headers.GetValues("Set-Cookie");
					string[] array = values;
					foreach (string text5 in array)
					{
						int num = text5.IndexOf('=');
						int num2 = text5.IndexOf(';');
						if (num != -1 && num2 != -1 && num < num2)
						{
							list.Add(text5.Substring(0, num2));
						}
						if (text == null)
						{
							text = Utility.GetTextBeetween(text5, "remixmid=", ";");
						}
					}
					aut_Cookies = string.Join("; ", list.ToArray());
					continue;
				}
				if (text4.StartsWith("failed"))
				{
					throw new AuthorizationFailedException();
				}
				if (text4.Contains("\"captcha_sid\":\""))
				{
					text2 = Utility.GetTextBeetween(text4, "\"captcha_sid\":\"", "\"");
					switch (CaptchaDialog.Show($"Авторизация({email})", text2, Proxy, ref key))
					{
					case DialogResult.Cancel:
						throw new CaptchaCanceledException();
					case DialogResult.Ignore:
						throw new CaptchaIgnoredException();
					}
				}
			}
			while (key != null);
			VKAccount result = default(VKAccount);
			result.EMail = email;
			result.Pass = pass;
			result.Aut_Cookies = aut_Cookies;
			result.ID = int.Parse(text);
			return result;
		}

		public static string GetPersonName(VKAccount account, int person_id)
		{
			if (person_id <= 0)
			{
				throw new ArgumentException("ID пользователя неверный");
			}
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/search.php?id=" + person_id, account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text = null;
			while (!streamReader.EndOfStream)
			{
				string text2 = streamReader.ReadLine();
				if (text2.Contains("<div style=\"overflow: hidden;\"><a href=\""))
				{
					int startIndex = text2.IndexOf("<div style=\"overflow: hidden;\"><a href=\"") + "<div style=\"overflow: hidden;\"><a href=\"".Length;
					startIndex = text2.IndexOf('>', startIndex) + 1;
					text = text2.Substring(startIndex, text2.IndexOf('<', startIndex) - startIndex);
					break;
				}
				if (text2.Contains("<div style=\"overflow: hidden;\">"))
				{
					text = Utility.GetTextBeetween(text2, "<div style=\"overflow: hidden;\">", "<");
					break;
				}
			}
			streamReader.Close();
			if (text == null)
			{
				throw new BlankErrorException(string.Format("Пользователь не найден", person_id));
			}
			return HttpUtility.HtmlDecode(text);
		}

		public static int[] GetPersonGroups(VKAccount account, int person_id)
		{
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/groups.php?id=" + person_id, account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			List<int> list = new List<int>();
			while (!streamReader.EndOfStream)
			{
				string textBeetween = Utility.GetTextBeetween(streamReader.ReadLine(), "<div style=\"width: 300px; overflow: hidden;\"><a id=\"groupName", "\"");
				if (textBeetween != null)
				{
					list.Add(-int.Parse(textBeetween));
				}
			}
			streamReader.Close();
			return list.ToArray();
		}

		public static void EnterGroup(VKAccount account, int group_id)
		{
			if (group_id >= 0)
			{
				throw new ArgumentException("ID группы неверный!");
			}
			group_id = Math.Abs(group_id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/groups.php?act=ajax&n=1&gid=" + group_id, account.Aut_Cookies, Proxy);
			vKRequest.GetResponse().Close();
		}

		public static string GetGroupName(VKAccount account, int group_id)
		{
			if (group_id >= 0)
			{
				throw new ArgumentException("ID группы неверный!");
			}
			group_id = Math.Abs(group_id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/club" + group_id, account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			string text = response.Headers["Location"];
			if (text != null && text.Contains("events.php"))
			{
				response.Close();
				vKRequest = VKRequest.Create("http://vkontakte.ru/events.php?act=s&gid=" + group_id, account.Aut_Cookies, Proxy);
				response = vKRequest.GetResponse();
			}
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text2 = null;
			while (!streamReader.EndOfStream && text2 == null)
			{
				text2 = Utility.GetTextBeetween(streamReader.ReadLine(), "<td><div class=\"dataWrap\"><b>", "<");
			}
			streamReader.Close();
			if (text2 == null)
			{
				throw new BlankErrorException("Неопределенная ошибка получения имени группы.");
			}
			return HttpUtility.HtmlDecode(text2);
		}

		public static WallMessagesPostInfo GetWallMessagesPostInfo(VKAccount account, int id)
		{
			bool flag = id < 0;
			id = Math.Abs(id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/" + string.Format("wall.php?{0}id={1}", flag ? "g" : string.Empty, id), account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			string text = response.Headers["Location"];
			if (text == "index.php")
			{
				response.Close();
				throw new BlankErrorException("Вы не можете просматривать стену.");
			}
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text2 = null;
			while (!streamReader.EndOfStream && text2 == null)
			{
				text2 = Utility.GetTextBeetween(streamReader.ReadLine(), "</span><a href=\"wall.php?act=write&", "\"");
			}
			streamReader.Close();
			if (text2 == null)
			{
				throw new BlankErrorException("Вы не можете просматривать стену.");
			}
			vKRequest = VKRequest.Create("http://vkontakte.ru/wall.php?act=write&" + text2, account.Aut_Cookies, Proxy);
			response = vKRequest.GetResponse();
			streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text3 = null;
			string text4 = null;
			string text5 = null;
			text2 = null;
			while (!streamReader.EndOfStream)
			{
				string src = streamReader.ReadLine();
				if (text3 == null)
				{
					text3 = Utility.GetTextBeetween(src, "<script>function", "</script>");
					continue;
				}
				if (text4 == null)
				{
					text4 = Utility.GetTextBeetween(src, "wall_hash: ", " ");
					continue;
				}
				if (text2 == null)
				{
					text2 = Utility.GetTextBeetween(src, "<input type=\"hidden\" id=\"to_id\" name=\"to_id\" value=\"", "\"");
					continue;
				}
				if (text5 != null)
				{
					break;
				}
				text5 = Utility.GetTextBeetween(src, "<input type=\"hidden\" id=\"wall_hash\" name=\"wall_hash\" value=\"", "\"");
			}
			streamReader.Close();
			int startIndex = text3.IndexOf(text4);
			startIndex = text3.IndexOf('=', startIndex) + 1;
			startIndex = text3.IndexOf("=\"", startIndex) + 2;
			char c = text3.Substring(startIndex, 1)[0];
			for (int i = 0; i < 4; i++)
			{
				startIndex = text3.IndexOf('+', startIndex) + 1;
			}
			int num = int.Parse(text3.Substring(startIndex, text3.IndexOf('-', startIndex) - startIndex));
			string text6 = string.Empty;
			for (int j = 0; j < text5.Length; j++)
			{
				int k;
				for (k = c + num - text5[j]; k < 48; k += 75)
				{
				}
				while (k > 122)
				{
					k -= 75;
				}
				text6 += char.ConvertFromUtf32(k);
				c = text5[j];
			}
			WallMessagesPostInfo result = default(WallMessagesPostInfo);
			result.Account = account;
			result.Hash = text6;
			result.ToID = text2;
			return result;
		}

		public static void PostWallMessage(WallMessagesPostInfo post_info, string message)
		{
			if (message == null)
			{
				throw new NullReferenceException("Параметру message не присвоено значение");
			}
			string text = null;
			string key = null;
			do
			{
				VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/wall.php", post_info.Account.Aut_Cookies, post: true, "application/x-www-form-urlencoded", Proxy);
				StreamWriter streamWriter = new StreamWriter(vKRequest.GetRequestStream(), Encoding.ASCII);
				streamWriter.Write("act=sent&to_id={0}&wall_hash={1}&message={2}", post_info.ToID, post_info.Hash, HttpUtility.UrlEncode(message));
				if (key != null)
				{
					streamWriter.Write("&captcha_sid={0}&captcha_key={1}", text, key);
				}
				streamWriter.Close();
				text = null;
				key = null;
				HttpWebResponse response = vKRequest.GetResponse();
				StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
				string text2 = streamReader.ReadLine();
				streamReader.Close();
				if (text2 == null)
				{
					throw new BlankErrorException("Неопределенная ошибка отправки сообщения.");
				}
				if (text2.Contains("blank.php"))
				{
					throw BlankErrorException.Create(text2, Proxy);
				}
				if (text2.Contains("\"captcha_sid\":\""))
				{
					text = Utility.GetTextBeetween(text2, "\"captcha_sid\":\"", "\"");
					switch (CaptchaDialog.Show($"Стена({post_info.Account.Name})", text, Proxy, ref key))
					{
					case DialogResult.Cancel:
						throw new CaptchaCanceledException();
					case DialogResult.Ignore:
						throw new CaptchaIgnoredException();
					}
				}
			}
			while (key != null);
		}

		public static void PostWallGraffiti(VKAccount account, int id, byte[] img_data)
		{
			if (img_data == null)
			{
				throw new NullReferenceException("Параметру img_data не присвоено значение");
			}
			bool flag = id < 0;
			id = Math.Abs(id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/" + $"graffiti.php?to_id={((!flag) ? id : 0)}&group_id={(flag ? id : 0)}", account.Aut_Cookies, post: true, "multipart/form-data; boundary=--OLEG-ANDREEV-PAVEL-DUROV-GRAFFITI-POST", Proxy);
			byte[] array = new byte[1024];
			Encoding.ASCII.GetBytes(Convert.ToBase64String(img_data), 0, 1024, array, 0);
			MD5 mD = MD5.Create();
			string text = string.Empty;
			byte[] array2 = mD.ComputeHash(array);
			byte[] array3 = array2;
			foreach (byte b in array3)
			{
				text += b.ToString("x2");
			}
			array = null;
			MimeWriter mimeWriter = new MimeWriter(vKRequest.GetRequestStream(), "--OLEG-ANDREEV-PAVEL-DUROV-GRAFFITI-POST");
			mimeWriter.WritePart("Signature", text);
			mimeWriter.WritePart("Filedata", "graffiti.png", "image/png", img_data);
			mimeWriter.WritePart("Upload", "Submit Query");
			mimeWriter.Finish();
			HttpWebResponse response = vKRequest.GetResponse();
			response.Close();
			string text2 = response.Headers["Location"];
			vKRequest = VKRequest.Create("http://vkontakte.ru/" + text2, account.Aut_Cookies, Proxy);
			response = vKRequest.GetResponse();
			response.Close();
			text2 = response.Headers["Location"];
			vKRequest = VKRequest.Create("http://vkontakte.ru/" + text2, account.Aut_Cookies, Proxy);
			response = vKRequest.GetResponse();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text3 = null;
			string text4 = null;
			string text5 = null;
			while (!streamReader.EndOfStream)
			{
				string src = streamReader.ReadLine();
				if (text5 == null)
				{
					text5 = Utility.GetTextBeetween(src, "<input type=\"hidden\" id=\"to_id\" name=\"to_id\" value=\"", "\"");
				}
				if (text3 == null)
				{
					text3 = Utility.GetTextBeetween(src, "<input type=\"hidden\" id=\"grid\" name=\"grid\" value=\"", "\"");
				}
				if (text4 != null)
				{
					break;
				}
				text4 = Utility.GetTextBeetween(src, "<input type=\"hidden\" id=\"wall_hash\" name=\"wall_hash\" value=\"", "\"");
			}
			streamReader.Close();
			string text6 = null;
			string key = null;
			do
			{
				string text7 = string.Format("?act=sent&grid={0}&to_id={1}&wall_hash={2}&message={0}", text3, text5, text4);
				if (key != null)
				{
					text7 += $"&captcha_sid={text6}&captcha_key={key}";
				}
				vKRequest = VKRequest.Create("http://vkontakte.ru/wall.php" + text7, account.Aut_Cookies, Proxy);
				text6 = null;
				key = null;
				response = vKRequest.GetResponse();
				streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
				string text8 = streamReader.ReadLine();
				streamReader.Close();
				if (text8.Contains("blank.php"))
				{
					throw BlankErrorException.Create(text8, Proxy);
				}
				if (text8.Contains("\"captcha_sid\":\""))
				{
					text6 = Utility.GetTextBeetween(text8, "\"captcha_sid\":\"", "\"");
					switch (CaptchaDialog.Show($"Граффити({account.Name})", text6, Proxy, ref key))
					{
					case DialogResult.Cancel:
						throw new CaptchaCanceledException();
					case DialogResult.Ignore:
						throw new CaptchaIgnoredException();
					}
				}
			}
			while (key != null);
		}

		public static TopicsCreationInfo GetTopicsCreationInfo(VKAccount account, int group_id)
		{
			if (group_id >= 0)
			{
				throw new ArgumentException("ID группы неверный!");
			}
			group_id = Math.Abs(group_id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/board.php?act=newtopic&id=" + group_id, account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text = null;
			while (!streamReader.EndOfStream && text == null)
			{
				text = Utility.GetTextBeetween(streamReader.ReadLine(), "<input type=\"hidden\" id=\"hash\" name=\"hash\" value=\"", "\"");
			}
			streamReader.Close();
			if (text == null)
			{
				throw new BlankErrorException("К сожалению, у Вас недостаточно прав для совершения этого действия.");
			}
			TopicsCreationInfo result = default(TopicsCreationInfo);
			result.Account = account;
			result.GroupID = group_id;
			result.Hash = text;
			return result;
		}

		public static TopicInfo CreateTopic(TopicsCreationInfo cr_info, string title, string post)
		{
			if (title == null)
			{
				throw new NullReferenceException("Параметру title не присвоено значение");
			}
			if (post == null)
			{
				throw new NullReferenceException("Параметру post не присвоено значение");
			}
			if (title.Length == 0)
			{
				throw new ArgumentException("Значение не может быть пустым", "title");
			}
			if (post.Length == 0)
			{
				throw new ArgumentException("Значение не может быть пустым", "post");
			}
			string s = null;
			string text = null;
			string key = null;
			do
			{
				VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/board.php", cr_info.Account.Aut_Cookies, post: true, "application/x-www-form-urlencoded", Proxy);
				StreamWriter streamWriter = new StreamWriter(vKRequest.GetRequestStream(), Encoding.ASCII);
				streamWriter.Write("act=a_new_topic&gid={0}&hash={1}&title={2}&post={3}", cr_info.GroupID, cr_info.Hash, HttpUtility.UrlEncode(title), HttpUtility.UrlEncode(post));
				if (key != null)
				{
					streamWriter.Write("&captcha_sid={0}&captcha_key={1}", text, HttpUtility.UrlEncode(key));
				}
				streamWriter.Close();
				text = null;
				key = null;
				HttpWebResponse response = vKRequest.GetResponse();
				StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
				string text2 = streamReader.ReadLine();
				streamReader.Close();
				if (text2.Contains("blank.php"))
				{
					throw BlankErrorException.Create(text2, Proxy);
				}
				if (text2.Contains("\"captcha_sid\":\""))
				{
					text = Utility.GetTextBeetween(text2, "\"captcha_sid\":\"", "\"");
					switch (CaptchaDialog.Show($"Обсуждения({cr_info.Account.Name})", text, Proxy, ref key))
					{
					case DialogResult.Cancel:
						throw new CaptchaCanceledException();
					case DialogResult.Ignore:
						throw new CaptchaIgnoredException();
					}
				}
				else
				{
					if (text2 == "Access denied")
					{
						throw new BlankErrorException(text2, -2);
					}
					if (text2.Contains("rtopic"))
					{
						s = Utility.GetTextBeetween(text2, "rtopic-" + cr_info.GroupID + "_", null);
					}
				}
			}
			while (key != null);
			int result = 0;
			if (!int.TryParse(s, out result))
			{
				throw new BlankErrorException("Неопределенная ошибка создания обсуждения.");
			}
			TopicInfo result2 = default(TopicInfo);
			result2.ID = result;
			result2.OwnerID = -cr_info.GroupID;
			result2.Title = title;
			result2.CreationDate = DateTime.Now.Date;
			return result2;
		}

		public static TopicInfo[] GetGroupTopics(VKAccount account, int group_id, int page, ref int tcount)
		{
			group_id = Math.Abs(group_id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/" + $"board.php?act=a_get_topics_page&gid={group_id}&order=2&page={page}", account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			List<TopicInfo> list = new List<TopicInfo>();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			while (!streamReader.EndOfStream)
			{
				string text = streamReader.ReadLine();
				if (text.StartsWith("<table"))
				{
					text = streamReader.ReadLine();
					int num = int.Parse(Utility.GetTextBeetween(text, "<h3 class=\"topicTitle\"><a href=\"topic-" + group_id + "_", "\""));
					string title = HttpUtility.HtmlDecode(Utility.GetTextBeetween(text, num + "\">", "</a>"));
					streamReader.ReadLine();
					streamReader.ReadLine();
					DateTime creationDate = ParseDate(HttpUtility.HtmlDecode(Utility.GetTextBeetween(streamReader.ReadLine(), "<span style=\"color: #888\">Создана ", "</span>")));
					while (!(text = streamReader.ReadLine()).Contains("Автор: <a href=\""))
					{
					}
					string text2 = Utility.GetTextBeetween(text, "Автор: <a href=\"id", "\"");
					if (text2 == null)
					{
						text2 = "0";
					}
					list.Add(new TopicInfo
					{
						ID = num,
						OwnerID = -group_id,
						Title = title,
						CreationDate = creationDate,
						AuthorID = int.Parse(text2)
					});
				}
				else
				{
					string textBeetween = Utility.GetTextBeetween(text, "<div id='new_summary' style='display: none'>В группе ", " ");
					if (textBeetween != null)
					{
						int.TryParse(textBeetween, out tcount);
					}
				}
			}
			streamReader.Close();
			return list.ToArray();
		}

		public static TopicAnswersPostInfo GetTopicAnswersPostInfo(VKAccount account, TopicInfo topic)
		{
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/" + $"topic{topic.OwnerID}_{topic.ID}", account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text = null;
			while (!streamReader.EndOfStream && text == null)
			{
				text = Utility.GetTextBeetween(streamReader.ReadLine(), "<input type=\"hidden\" id=\"hash\" name=\"hash\" value=\"", "\"");
			}
			streamReader.Close();
			TopicAnswersPostInfo result = default(TopicAnswersPostInfo);
			result.Account = account;
			result.GroupID = topic.OwnerID;
			result.TopicID = topic.ID;
			result.Hash = text;
			return result;
		}

		public static bool PostTopicAnswer(TopicAnswersPostInfo post_info, string comment)
		{
			if (comment == null)
			{
				throw new NullReferenceException("Параметру comment не присвоено значение");
			}
			if (comment.Length == 0)
			{
				throw new ArgumentException("Комментарий не может быть нулевой длины.", "comment");
			}
			string text = null;
			string text2 = null;
			string key = null;
			do
			{
				VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/board.php", post_info.Account.Aut_Cookies, post: true, "application/x-www-form-urlencoded", Proxy);
				StreamWriter streamWriter = new StreamWriter(vKRequest.GetRequestStream(), Encoding.ASCII);
				streamWriter.Write("act=a_post_answer&gid={0}&tid={1}&hash={2}&post={3}", post_info.GroupID, post_info.TopicID, post_info.Hash, HttpUtility.UrlEncode(comment));
				if (key != null)
				{
					streamWriter.Write("&captcha_sid={0}&captcha_key={1}", text2, key);
				}
				streamWriter.Close();
				HttpWebResponse response = vKRequest.GetResponse();
				StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
				text = streamReader.ReadLine();
				streamReader.Close();
				if (text == null)
				{
					throw new BlankErrorException("Неопределенная ошибка отправки ответа.");
				}
				if (text.Contains("\"captcha_sid\":\""))
				{
					text2 = Utility.GetTextBeetween(text, "\"captcha_sid\":\"", "\"");
					switch (CaptchaDialog.Show($"Обс. ответы({post_info.Account.Name})", text2, Proxy, ref key))
					{
					case DialogResult.Cancel:
						throw new CaptchaCanceledException();
					case DialogResult.Ignore:
						throw new CaptchaIgnoredException();
					}
				}
				else
				{
					if (text.Contains("blank.php"))
					{
						throw BlankErrorException.Create(text, Proxy);
					}
					if (text.Contains("flood_control"))
					{
						throw new BlankErrorException("Вы отправляете сообщения слишком быстро(flood_control).", 0);
					}
				}
				if (key != null)
				{
					Thread.Sleep(3000);
				}
			}
			while (key != null);
			return !text.Contains("r/topic");
		}

		public static int GetAlbumsCount(VKAccount account, int id)
		{
			bool flag = id < 0;
			id = Math.Abs(id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/" + string.Format("photos.php?{0}id={1}", flag ? "g" : string.Empty, id), account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			string text = response.Headers["Location"];
			if (text == "club" + id)
			{
				response.Close();
				throw new BlankErrorException("Просмотр альбомов группы не досупен.");
			}
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text2 = null;
			while (!streamReader.EndOfStream && text2 == null)
			{
				text2 = Utility.GetTextBeetween(streamReader.ReadLine(), "<div class=\"summary\">", " ");
			}
			streamReader.Close();
			if (text2 == null)
			{
				throw new BlankErrorException(string.Format("Просмотр альбомов {0} не досупен.", flag ? "группы" : "пользователя"));
			}
			return int.Parse(text2);
		}

		public static AlbumInfo[] Get50Albums(VKAccount account, int id, int offset)
		{
			bool flag = id < 0;
			id = Math.Abs(id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/" + string.Format("photos.php?act=getpages&{0}id={1}&offset={2}", flag ? "g" : string.Empty, id, offset), account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			int num = 0;
			string text = streamReader.ReadLine();
			if (text.Contains("<a href=\"#\""))
			{
				for (int num2 = 0; num2 > -1; num2 = text.IndexOf("<a href=\"#\"", num2 + 1))
				{
					num++;
				}
			}
			else
			{
				num = 2;
			}
			num--;
			List<AlbumInfo> list = new List<AlbumInfo>();
			int num3 = 0;
			while (!streamReader.EndOfStream)
			{
				text = streamReader.ReadLine();
				if (text.Contains("<div class=\"aname\"><a href=\"album"))
				{
					string textBeetween = Utility.GetTextBeetween(text, id + "_", "\">");
					string textBeetween2 = Utility.GetTextBeetween(text, textBeetween + "\">", "</a>");
					string textBeetween3 = Utility.GetTextBeetween(streamReader.ReadLine(), "<div class=\"ainfo\">", " ");
					string textBeetween4 = Utility.GetTextBeetween(streamReader.ReadLine(), "<div class=\"adesc\">", "</div>");
					string textBeetween5 = Utility.GetTextBeetween(streamReader.ReadLine(), ">Создан ", "</div>");
					list.Add(new AlbumInfo
					{
						Name = HttpUtility.HtmlDecode(textBeetween2),
						Description = HttpUtility.HtmlDecode(textBeetween4).Replace("<br>", "\r\n"),
						ID = int.Parse(textBeetween),
						CreationDate = ParseDate(textBeetween5),
						OwnerID = id * ((!flag) ? 1 : (-1)),
						PhotosCount = int.Parse(textBeetween3)
					});
					num3++;
				}
			}
			streamReader.Close();
			return list.ToArray();
		}

		public static AlbumCreationInfo GetAlbumCreationInfo(VKAccount account, int group_id)
		{
			if (group_id > 0)
			{
				throw new ArgumentException("ID группы неверный!");
			}
			group_id = Math.Abs(group_id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/photos.php?act=new&gid=" + group_id, account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			string text = response.Headers["Location"];
			if (text != null && text.Contains("club" + group_id))
			{
				response.Close();
				throw new BlankErrorException("Создание альбомов недоступно в этой группе.", -2);
			}
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text2 = null;
			while (!streamReader.EndOfStream && text2 == null)
			{
				text2 = Utility.GetTextBeetween(streamReader.ReadLine(), "<input type=\"hidden\" id=\"hash\" name=\"hash\" value=\"", "\"");
			}
			streamReader.Close();
			if (text2 == null)
			{
				throw new BlankErrorException("Ошибка чтения хэш-кода");
			}
			AlbumCreationInfo result = default(AlbumCreationInfo);
			result.Account = account;
			result.GroupID = group_id;
			result.Hash = text2;
			return result;
		}

		public static AlbumInfo CreateAlbum(AlbumCreationInfo cr_info, string name, string description)
		{
			if (name == null)
			{
				throw new NullReferenceException("Параметру name не присвоено значение");
			}
			if (description == null)
			{
				throw new NullReferenceException("Параметру description не присвоено значение");
			}
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/photos.php", cr_info.Account.Aut_Cookies, post: true, "application/x-www-form-urlencoded", Proxy);
			StreamWriter streamWriter = new StreamWriter(vKRequest.GetRequestStream(), Encoding.ASCII);
			if (cr_info.GroupID > 0)
			{
				streamWriter.Write("act=create&hash={0}&gid={1}&name={2}&desc={3}&access_level=0", cr_info.Hash, cr_info.GroupID, HttpUtility.UrlEncode(name, enc_ru), HttpUtility.UrlEncode(description, enc_ru));
			}
			else
			{
				streamWriter.Write("act=create&hash={0}&name={1}&desc={2}&visible=1", cr_info.Hash, HttpUtility.UrlEncode(name, enc_ru), HttpUtility.UrlEncode(description, enc_ru));
			}
			streamWriter.Close();
			HttpWebResponse response = vKRequest.GetResponse();
			response.Close();
			string text = response.Headers["Location"];
			int num = 0;
			int num2 = 0;
			if (text != null && text.Contains("id="))
			{
				num = int.Parse(Utility.GetTextBeetween(text, "id=", "&"));
				num2 = int.Parse(Utility.GetTextBeetween(text, "oid=", null));
			}
			if (num == 0 || num2 == 0)
			{
				throw new BlankErrorException("Неопределенная ошибка создания альбома");
			}
			AlbumInfo result = default(AlbumInfo);
			result.ID = num;
			result.OwnerID = num2;
			result.Name = name;
			result.Description = description;
			return result;
		}

		public static PhotoUploadInfo GetPhotoUploadInfo(VKAccount acount, AlbumInfo album)
		{
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/" + $"photos.php?act=add&id={album.ID}&oid={album.OwnerID}", acount.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text = null;
			string text2 = null;
			string text3 = null;
			string text4 = null;
			while (!streamReader.EndOfStream)
			{
				string src = streamReader.ReadLine();
				if (text == null)
				{
					text = Utility.GetTextBeetween(src, "<form id=\"upload\" name=\"upload\" action=\"", "\"");
					continue;
				}
				if (text2 == null)
				{
					text2 = Utility.GetTextBeetween(src, "<input type=\"hidden\" id=\"gid\" name=\"gid\" value=\"", "\"");
					continue;
				}
				if (text3 == null)
				{
					text3 = Utility.GetTextBeetween(src, "<input type=\"hidden\" id=\"hash\" name=\"hash\" value=\"", "\"");
					continue;
				}
				if (text4 != null)
				{
					break;
				}
				text4 = Utility.GetTextBeetween(src, "<input type=\"hidden\" id=\"rhash\" name=\"rhash\" value=\"", "\"");
			}
			streamReader.Close();
			PhotoUploadInfo result = default(PhotoUploadInfo);
			result.Account = acount;
			result.AlbumID = album.ID;
			result.GroupID = int.Parse(text2);
			result.Hash = text3;
			result.RHash = text4;
			result.UploadURL = text;
			return result;
		}

		public static FileSaveInfo UploadPhotos(PhotoUploadInfo up_info, List<byte[]> imgs_data)
		{
			if (imgs_data == null)
			{
				throw new NullReferenceException("Параметру imgs_data не присвоено значение");
			}
			if (imgs_data.Count > 6)
			{
				throw new ArgumentException("Количество выгружаемых фото не должно превышать 6");
			}
			string text = "---------------------------" + DateTime.Now.Ticks;
			VKRequest vKRequest = VKRequest.Create(up_info.UploadURL + string.Format("?act=do_add&id={0}&aid={0}&gid={1}&mid={2}&hash={3}&rhash={4}", up_info.AlbumID, up_info.GroupID, up_info.Account.ID, up_info.Hash, up_info.RHash), up_info.Account.Aut_Cookies, post: true, "multipart/form-data; boundary=" + text, Proxy);
			MimeWriter mimeWriter = new MimeWriter(vKRequest.GetRequestStream(), text);
			for (int i = 1; i <= imgs_data.Count; i++)
			{
				mimeWriter.WritePart("file" + i, "image" + i + ".jpg", "image/jpeg", imgs_data[i - 1]);
			}
			mimeWriter.Finish();
			HttpWebResponse response = vKRequest.GetResponse();
			response.Close();
			string text2 = response.Headers["Location"];
			FileSaveInfo result = default(FileSaveInfo);
			result.Account = up_info.Account;
			result.ConfirmUrl = text2.Replace("act=done_add", "act=a_done_add");
			return result;
		}

		public static void SavePhoto(FileSaveInfo sv_info)
		{
			SaveFile(sv_info, $"Фото({sv_info.Account.Name})");
		}

		public static AudioUploadInfo GetAudioUploadInfo(VKAccount account, int group_id)
		{
			if (group_id > 0)
			{
				throw new ArgumentException("ID группы неверный!");
			}
			group_id = Math.Abs(group_id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/audio.php?act=new&gid=" + group_id, account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text = null;
			string text2 = null;
			string text3 = null;
			string text4 = null;
			while (!streamReader.EndOfStream)
			{
				string src = streamReader.ReadLine();
				if (text == null)
				{
					text = Utility.GetTextBeetween(src, "<form action=\"", "\"");
					continue;
				}
				if (text2 == null)
				{
					text2 = Utility.GetTextBeetween(src, "<input type=\"hidden\" id=\"aid\" name=\"aid\" value=\"", "\"");
					continue;
				}
				if (text3 == null)
				{
					text3 = Utility.GetTextBeetween(src, "<input type=\"hidden\" id=\"hash\" name=\"hash\" value=\"", "\"");
					continue;
				}
				if (text4 != null)
				{
					break;
				}
				text4 = Utility.GetTextBeetween(src, "<input type=\"hidden\" id=\"rhash\" name=\"rhash\" value=\"", "\"");
			}
			streamReader.Close();
			AudioUploadInfo result = default(AudioUploadInfo);
			result.Account = account;
			result.UploadURL = text;
			result.AID = int.Parse(text2);
			result.Hash = text3;
			result.RHash = text4;
			result.GroupID = group_id;
			return result;
		}

		public static FileSaveInfo UploadAudio(AudioUploadInfo up_info, byte[] aud_data)
		{
			if (aud_data == null)
			{
				throw new NullReferenceException("Параметру aud_data не присвоено значение");
			}
			string text = "---------------------------" + DateTime.Now.Ticks;
			VKRequest vKRequest = VKRequest.Create($"{up_info.UploadURL}?act=add_audio&aid={up_info.AID}&gid={up_info.GroupID}&mid={up_info.Account.ID}&hash={up_info.Hash}&rhash={up_info.RHash}", up_info.Account.Aut_Cookies, post: true, "multipart/form-data; boundary=" + text, Proxy);
			MimeWriter mimeWriter = new MimeWriter(vKRequest.GetRequestStream(), text);
			mimeWriter.WritePart("file", "audio.mp3", "audio/mpeg", aud_data);
			mimeWriter.Finish();
			HttpWebResponse response = vKRequest.GetResponse();
			response.Close();
			string text2 = response.Headers["Location"];
			if (text2 == null)
			{
				throw new BlankErrorException("Security Breach2");
			}
			FileSaveInfo result = default(FileSaveInfo);
			result.Account = up_info.Account;
			result.ConfirmUrl = text2;
			return result;
		}

		public static void SaveAudio(FileSaveInfo sv_info, string performer, string title)
		{
			if (performer != null || title != null)
			{
				string text = "audio=";
				int num = sv_info.ConfirmUrl.IndexOf(text) + text.Length + 17;
				int num2 = sv_info.ConfirmUrl.IndexOf('&', num);
				sv_info.ConfirmUrl = sv_info.ConfirmUrl.Remove(num, num2 - num);
				string text2 = "";
				if (performer != null)
				{
					text2 += HttpUtility.UrlEncode(performer);
				}
				if (title != null)
				{
					text2 = text2 + "%01" + HttpUtility.UrlEncode(title);
				}
				sv_info.ConfirmUrl = sv_info.ConfirmUrl.Insert(num, text2);
			}
			SaveFile(sv_info, $"Аудио({sv_info.Account.Name})");
		}

		public static VideoAddInfo UploadVideo(VKAccount account, int upload_group_id, int add_group_id, byte[] vid_data, string name, string description)
		{
			if (upload_group_id > 0)
			{
				throw new ArgumentException("ID группы для выгрузки неверный!");
			}
			if (add_group_id > 0)
			{
				throw new ArgumentException("ID группы для добавления неверный!");
			}
			upload_group_id = Math.Abs(upload_group_id);
			add_group_id = Math.Abs(add_group_id);
			if (vid_data == null)
			{
				throw new NullReferenceException("Параметру vid_data не присвоено значение");
			}
			if (name == null)
			{
				throw new NullReferenceException("Параметру name не присвоено значение");
			}
			if (description == null)
			{
				throw new NullReferenceException("Параметру description не присвоено значение");
			}
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/video.php", account.Aut_Cookies, post: true, "application/x-www-form-urlencoded", Proxy);
			StreamWriter streamWriter = new StreamWriter(vKRequest.GetRequestStream(), Encoding.ASCII);
			streamWriter.Write("act=upload&gid={0}&name={1}&desc={2}", upload_group_id, HttpUtility.UrlEncode(name, enc_ru), HttpUtility.UrlEncode(description, enc_ru));
			streamWriter.Close();
			HttpWebResponse response = vKRequest.GetResponse();
			string text = response.Headers["Location"];
			if (text != null && text.Contains("club" + upload_group_id))
			{
				response.Close();
				throw new BlankErrorException("Добавление видео в эту группу недоступно.");
			}
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text2 = null;
			string text3 = null;
			string data = null;
			while (!streamReader.EndOfStream)
			{
				string src = streamReader.ReadLine();
				if (text2 == null)
				{
					text2 = Utility.GetTextBeetween(src, "'upload_url': '", "'");
					continue;
				}
				if (text3 == null)
				{
					text3 = Utility.GetTextBeetween(src, "&export_info=", "&signature");
				}
				if (text3 == null)
				{
					continue;
				}
				data = Utility.GetTextBeetween(src, "&signature=", "'");
				break;
			}
			streamReader.Close();
			string text4 = "---------------------------" + DateTime.Now.Ticks;
			vKRequest = VKRequest.Create(text2, post: true, "multipart/form-data; boundary=" + text4, Proxy);
			MimeWriter mimeWriter = new MimeWriter(vKRequest.GetRequestStream(), text4);
			mimeWriter.WritePart("video_file", "video_file.wmv", "video/x-ms-wmv", vid_data);
			mimeWriter.WritePart("export_info", text3);
			mimeWriter.WritePart("signature", data);
			mimeWriter.Finish();
			response = vKRequest.GetResponse();
			response.Close();
			text = response.Headers["Location"];
			if (text == null || text == "http://vkontakte.ru/")
			{
				throw new BlankErrorException("Неопределенная ошибка загрузки");
			}
			string text5 = null;
			string text6 = null;
			text5 = Utility.GetTextBeetween(text, "id=", "&");
			text6 = Utility.GetTextBeetween(text, "oid=", "&");
			vKRequest = VKRequest.Create(text + "&add=1&gid=" + add_group_id, account.Aut_Cookies, Proxy);
			response = vKRequest.GetResponse();
			streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text7 = null;
			while (!streamReader.EndOfStream && text7 == null)
			{
				text7 = Utility.GetTextBeetween(streamReader.ReadLine(), "hash:'", "'");
			}
			streamReader.Close();
			if (text7 == null)
			{
				throw new BlankErrorException("Ошибка чтения хэш-кода");
			}
			VideoAddInfo result = default(VideoAddInfo);
			result.Account = account;
			result.Hash = text7;
			result.GroupID = add_group_id;
			result.Video = new VideoInfo
			{
				ID = int.Parse(text5),
				OwnerID = int.Parse(text6),
				Name = name,
				Description = description
			};
			return result;
		}

		public static VideoAddInfo GetVideoAddInfo(VKAccount account, int group_id, VideoInfo video)
		{
			if (group_id > 0)
			{
				throw new ArgumentException("ID группы неверный!");
			}
			group_id = Math.Abs(group_id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/" + $"video{video.OwnerID}_{video.ID}?add=1&gid={group_id}", account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text = null;
			while (!streamReader.EndOfStream && text == null)
			{
				text = Utility.GetTextBeetween(streamReader.ReadLine(), "hash:'", "'");
			}
			streamReader.Close();
			if (text == null)
			{
				throw new BlankErrorException("Ошибка чтения хэш-кода");
			}
			VideoAddInfo result = default(VideoAddInfo);
			result.Account = account;
			result.Hash = text;
			result.GroupID = group_id;
			result.Video = video;
			return result;
		}

		public static void AddVideo(VideoAddInfo va_info, bool use_ajax)
		{
			string confirmUrl = string.Format("http://vkontakte.ru/video.php?act={0}add&vid={1}&oid={2}&gid={3}&hash={4}", use_ajax ? "a_" : string.Empty, va_info.Video.ID, va_info.Video.OwnerID, va_info.GroupID, va_info.Hash);
			FileSaveInfo sv_info = default(FileSaveInfo);
			sv_info.Account = va_info.Account;
			sv_info.ConfirmUrl = confirmUrl;
			SaveFile(sv_info, $"Видео({va_info.Account.Name})");
		}

		public static VideoInfo[] Get100Videos(VKAccount account, int id, int offset, out int total_count)
		{
			bool flag = id < 0;
			id = Math.Abs(id);
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/" + string.Format("video.php?{0}id={1}&st={2}", flag ? "g" : string.Empty, id, offset), account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			List<VideoInfo> list = new List<VideoInfo>();
			string text = null;
			while (!streamReader.EndOfStream)
			{
				string text2 = streamReader.ReadLine();
				if (text == null)
				{
					text = Utility.GetTextBeetween(text2, "<div class=\"summary\"><b>", " ");
				}
				if (text2.Contains("<div style=\"padding-top:5px\" id=\"videoInfo"))
				{
					string textBeetween = Utility.GetTextBeetween(text2, "<div style=\"padding-top:5px\" id=\"videoInfo", "\">");
					string textBeetween2 = Utility.GetTextBeetween(streamReader.ReadLine(), textBeetween + "\">", "</a>");
					string textBeetween3 = Utility.GetTextBeetween(streamReader.ReadLine(), "<div class=\"adesc\">", "</div>");
					string textBeetween4 = Utility.GetTextBeetween(streamReader.ReadLine(), "Загружено ", "</div>");
					list.Add(new VideoInfo
					{
						Name = HttpUtility.HtmlDecode(textBeetween2),
						Description = HttpUtility.HtmlDecode(textBeetween3).Replace("<br>", "\r\n"),
						ID = int.Parse(textBeetween),
						OwnerID = id * ((!flag) ? 1 : (-1)),
						LoadDate = ParseDate(textBeetween4)
					});
				}
			}
			streamReader.Close();
			if (text != null && text.ToLower() != "нет")
			{
				total_count = int.Parse(text);
			}
			else
			{
				total_count = 0;
			}
			return list.ToArray();
		}

		public static VideoCommentsPostInfo GetVideoCommentsPostInfo(VKAccount account, VideoInfo video)
		{
			VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/" + $"video{video.OwnerID}_{video.ID}", account.Aut_Cookies, Proxy);
			HttpWebResponse response = vKRequest.GetResponse();
			StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
			string text = null;
			while (!streamReader.EndOfStream && text == null)
			{
				text = Utility.GetTextBeetween(streamReader.ReadLine(), "<input type=\"hidden\" id=\"hash\" name=\"hash\" value=\"", "\"");
			}
			streamReader.Close();
			VideoCommentsPostInfo result = default(VideoCommentsPostInfo);
			result.Account = account;
			result.Video = video;
			result.Hash = text;
			return result;
		}

		public static bool PostVideoComment(VideoCommentsPostInfo post_info, string comment)
		{
			if (comment == null)
			{
				throw new NullReferenceException("Параметру comment не присвоено значение");
			}
			if (comment.Length == 0)
			{
				throw new ArgumentException("Комментарий не может быть нулевой длины.", "comment");
			}
			string text = null;
			string key = null;
			do
			{
				VKRequest vKRequest = VKRequest.Create("http://vkontakte.ru/video.php", post_info.Account.Aut_Cookies, post: true, "application/x-www-form-urlencoded", Proxy);
				StreamWriter streamWriter = new StreamWriter(vKRequest.GetRequestStream(), Encoding.ASCII);
				streamWriter.Write("act=getcomms&oid={0}&mid={1}&n=3&hash={2}&add_bookmark=on&seed={3}", post_info.Video.OwnerID, post_info.Video.ID, post_info.Hash, HttpUtility.UrlEncode(comment));
				if (key != null)
				{
					streamWriter.Write("&captcha_sid={0}&captcha_key={1}", text, key);
				}
				streamWriter.Close();
				HttpWebResponse response = vKRequest.GetResponse();
				StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
				string text2 = streamReader.ReadLine();
				streamReader.Close();
				if (text2 != null)
				{
					if (text2.Contains("\"captcha_sid\":\""))
					{
						text = Utility.GetTextBeetween(text2, "\"captcha_sid\":\"", "\"");
						switch (CaptchaDialog.Show($"Вид. комментарии({post_info.Account.Name})", text, Proxy, ref key))
						{
						case DialogResult.Cancel:
							throw new CaptchaCanceledException();
						case DialogResult.Ignore:
							throw new CaptchaIgnoredException();
						}
						Thread.Sleep(4000);
					}
					else
					{
						if (text2.Contains("blank.php"))
						{
							throw BlankErrorException.Create(text2, Proxy);
						}
						if (text2.ToLower().Contains("слишком быстро"))
						{
							throw new BlankErrorException(text2, 0);
						}
					}
					continue;
				}
				return false;
			}
			while (key != null);
			return true;
		}

		private static void SaveFile(FileSaveInfo sv_info, string captcha_title)
		{
			string text = null;
			string key = null;
			do
			{
				VKRequest vKRequest = VKRequest.Create(sv_info.ConfirmUrl + ((key != null) ? $"&captcha_sid={text}&captcha_key={key}" : string.Empty), sv_info.Account.Aut_Cookies, Proxy);
				text = null;
				key = null;
				HttpWebResponse response = vKRequest.GetResponse();
				StreamReader streamReader = new StreamReader(response.GetResponseStream(), enc_ru);
				string text2 = streamReader.ReadLine();
				streamReader.Close();
				if (text2 == null)
				{
					continue;
				}
				if (text2.Contains("blank.php"))
				{
					throw BlankErrorException.Create(text2, Proxy);
				}
				if (text2.Contains("\"captcha_sid\":\""))
				{
					text = Utility.GetTextBeetween(text2, "\"captcha_sid\":\"", "\"");
					switch (CaptchaDialog.Show(captcha_title, text, Proxy, ref key))
					{
					case DialogResult.Cancel:
						throw new CaptchaCanceledException();
					case DialogResult.Ignore:
						throw new CaptchaIgnoredException();
					}
				}
			}
			while (key != null);
		}

		private static DateTime ParseDate(string s)
		{
			s = s.Trim();
			if (s.Length == 0)
			{
				return DateTime.MinValue;
			}
			Match match = Regex.Match(s, "(\\p{Nd}{1,2} [а-я]{3} \\p{Nd}{4}) в (\\p{Nd}{1,2}:\\p{Nd}{1,2})");
			if (match.Success)
			{
				return DateTime.Parse(match.Groups[1].Value + " " + match.Groups[2].Value);
			}
			if (s.StartsWith("сегодня"))
			{
				return DateTime.Today;
			}
			if (s.StartsWith("вчера"))
			{
				return DateTime.Today.AddDays(-1.0);
			}
			return DateTime.Parse(s);
		}

		private VKClient()
		{
			CachWallMessagesPostInfo = new Dictionary<int, WallMessagesPostInfo>();
			CachTopicsCreationInfo = new Dictionary<int, TopicsCreationInfo>();
			CachTopicAnswersPostInfo = new Dictionary<TopicInfo, TopicAnswersPostInfo>();
			CachPhotoUploadInfo = new Dictionary<AlbumInfo, PhotoUploadInfo>();
			CachAudioUploadInfo = new Dictionary<int, AudioUploadInfo>();
			CachVideoAddInfo = new Dictionary<VideoInfoCachEntity, VideoAddInfo>();
			CachVideoCommentsPostInfo = new Dictionary<VideoInfo, VideoCommentsPostInfo>();
		}

		public static VKClient Create(string email, string pass)
		{
			VKAccount account = Authorize(email, pass);
			account.Name = GetPersonName(account, account.ID);
			VKClient vKClient = new VKClient();
			vKClient.Account = account;
			return vKClient;
		}

		public void PostWallMessage(int id, string message)
		{
			WallMessagesPostInfo wallMessagesPostInfo;
			if (CachWallMessagesPostInfo.ContainsKey(id))
			{
				wallMessagesPostInfo = CachWallMessagesPostInfo[id];
			}
			else
			{
				wallMessagesPostInfo = GetWallMessagesPostInfo(Account, id);
				CachWallMessagesPostInfo.Add(id, wallMessagesPostInfo);
			}
			PostWallMessage(wallMessagesPostInfo, message);
		}

		public void PostWallGraffiti(int id, byte[] img_data)
		{
			PostWallGraffiti(Account, id, img_data);
		}

		public TopicInfo CreateTopic(int group_id, string title, string post)
		{
			TopicsCreationInfo topicsCreationInfo;
			if (CachTopicsCreationInfo.ContainsKey(group_id))
			{
				topicsCreationInfo = CachTopicsCreationInfo[group_id];
			}
			else
			{
				topicsCreationInfo = GetTopicsCreationInfo(Account, group_id);
				CachTopicsCreationInfo.Add(group_id, topicsCreationInfo);
			}
			return CreateTopic(topicsCreationInfo, title, post);
		}

		public bool PostTopicAnswer(TopicInfo topic, string comment)
		{
			bool flag = CachTopicAnswersPostInfo.ContainsKey(topic);
			TopicAnswersPostInfo topicAnswersPostInfo;
			if (flag)
			{
				topicAnswersPostInfo = CachTopicAnswersPostInfo[topic];
			}
			else
			{
				topicAnswersPostInfo = GetTopicAnswersPostInfo(Account, topic);
				CachTopicAnswersPostInfo.Add(topic, topicAnswersPostInfo);
			}
			if (!PostTopicAnswer(topicAnswersPostInfo, comment))
			{
				return true;
			}
			if (flag)
			{
				CachTopicAnswersPostInfo.Remove(topic);
			}
			return false;
		}

		public AlbumInfo CreateAlbum(int group_id, string name, string description)
		{
			AlbumCreationInfo albumCreationInfo = GetAlbumCreationInfo(Account, group_id);
			Thread.Sleep(5000);
			return CreateAlbum(albumCreationInfo, name, description);
		}

		public FileSaveInfo UploadPhotos(AlbumInfo album, List<byte[]> img_data, bool save)
		{
			PhotoUploadInfo photoUploadInfo;
			if (CachPhotoUploadInfo.ContainsKey(album))
			{
				photoUploadInfo = CachPhotoUploadInfo[album];
			}
			else
			{
				photoUploadInfo = GetPhotoUploadInfo(Account, album);
				CachPhotoUploadInfo.Add(album, photoUploadInfo);
			}
			FileSaveInfo fileSaveInfo = UploadPhotos(photoUploadInfo, img_data);
			if (save)
			{
				SavePhoto(fileSaveInfo);
			}
			return fileSaveInfo;
		}

		public FileSaveInfo UploadAudio(int group_id, byte[] aud_data, bool save, string performer, string title)
		{
			AudioUploadInfo audioUploadInfo;
			if (CachAudioUploadInfo.ContainsKey(group_id))
			{
				audioUploadInfo = CachAudioUploadInfo[group_id];
			}
			else
			{
				audioUploadInfo = GetAudioUploadInfo(Account, group_id);
				CachAudioUploadInfo.Add(group_id, audioUploadInfo);
			}
			FileSaveInfo fileSaveInfo = UploadAudio(audioUploadInfo, aud_data);
			if (save)
			{
				SaveAudio(fileSaveInfo, performer, title);
			}
			return fileSaveInfo;
		}

		public FileSaveInfo UploadAudio(int group_id, byte[] aud_data, bool save)
		{
			return UploadAudio(group_id, aud_data, save, null, null);
		}

		public VideoAddInfo UploadVideo(int upload_group_id, int add_group_id, byte[] vid_data, string name, string description)
		{
			return UploadVideo(Account, upload_group_id, add_group_id, vid_data, name, description);
		}

		public void AddVideo(int group_id, VideoInfo video, bool use_ajax)
		{
			VideoInfoCachEntity videoInfoCachEntity = default(VideoInfoCachEntity);
			videoInfoCachEntity.GroupID = group_id;
			videoInfoCachEntity.Video = video;
			VideoInfoCachEntity key = videoInfoCachEntity;
			VideoAddInfo videoAddInfo;
			if (CachVideoAddInfo.ContainsKey(key))
			{
				videoAddInfo = CachVideoAddInfo[key];
			}
			else
			{
				videoAddInfo = GetVideoAddInfo(Account, group_id, video);
				CachVideoAddInfo.Add(key, videoAddInfo);
			}
			AddVideo(videoAddInfo, use_ajax);
		}

		public bool PostVideoComment(VideoInfo video, string comment)
		{
			VideoCommentsPostInfo videoCommentsPostInfo;
			if (CachVideoCommentsPostInfo.ContainsKey(video))
			{
				videoCommentsPostInfo = CachVideoCommentsPostInfo[video];
			}
			else
			{
				videoCommentsPostInfo = GetVideoCommentsPostInfo(Account, video);
				CachVideoCommentsPostInfo.Add(video, videoCommentsPostInfo);
			}
			return PostVideoComment(videoCommentsPostInfo, comment);
		}

		public string GetPersonName(int person_id)
		{
			return GetPersonName(Account, person_id);
		}

		public string GetGroupName(int group_id)
		{
			return GetGroupName(Account, group_id);
		}

		public void EnterGroup(int group_id)
		{
			EnterGroup(Account, group_id);
		}

		public int[] GetPersonGroups(int person_id)
		{
			return GetPersonGroups(Account, person_id);
		}

		public int GetAlbumsCount(int id)
		{
			return GetAlbumsCount(Account, id);
		}

		public AlbumInfo[] Get50Albums(int id, int offset)
		{
			return Get50Albums(Account, id, offset);
		}

		public TopicInfo[] GetGroupTopics(int group_id, int page, ref int count)
		{
			return GetGroupTopics(Account, group_id, page, ref count);
		}

		public VideoInfo[] Get100Videos(int id, int offset, out int total_count)
		{
			return Get100Videos(Account, id, offset, out total_count);
		}

		public VideoInfo[] Get100Videos(int id, int offset)
		{
			int total_count = 0;
			return Get100Videos(Account, id, offset, out total_count);
		}

		public void ClearCach()
		{
			lock (CachAudioUploadInfo)
			{
				CachAudioUploadInfo.Clear();
			}
			lock (CachPhotoUploadInfo)
			{
				CachPhotoUploadInfo.Clear();
			}
			lock (CachTopicAnswersPostInfo)
			{
				CachTopicAnswersPostInfo.Clear();
			}
			lock (CachTopicAnswersPostInfo)
			{
				CachTopicsCreationInfo.Clear();
			}
			lock (CachVideoAddInfo)
			{
				CachVideoAddInfo.Clear();
			}
			lock (CachWallMessagesPostInfo)
			{
				CachWallMessagesPostInfo.Clear();
			}
			lock (CachVideoCommentsPostInfo)
			{
				CachVideoCommentsPostInfo.Clear();
			}
		}
	}
}
