using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using TD.SandDock;
using VKontakte;

namespace Gsome
{
	public class AttackControl : DockControl
	{
		private delegate void Proc();

		private delegate void LogWriteCallBack(string msg, Color color, params object[] p);

		private struct ExcudedVKClient
		{
			public VKClient Base;

			public DateTime ExcludeTime;

			public ExcudedVKClient(VKClient client)
			{
				Base = client;
				ExcludeTime = DateTime.Now;
			}
		}

		private const int InactiveThreadTimeInterval = 1000;

		private IContainer components;

		private TreeView trConfigs;

		private SplitContainer spltcon;

		private TableLayoutPanel tlpCommands;

		private Button btnGsom;

		private Button btnStop;

		private TreeNode trndWallLuch;

		private TreeNode trndWallGraffiti;

		private TreeNode trndWallAudio;

		private TreeNode trndWallVideo;

		private TreeNode trndWall;

		private TreeNode trndTopicsExist;

		private TreeNode trndTopicsNew;

		private TreeNode trndTopics;

		private TreeNode trndAlbumsExist;

		private TreeNode trndAlbumsNew;

		private TreeNode trndAlbums;

		private TreeNode trndAudioLuch;

		private TreeNode trndAudio;

		private TreeNode trndVideoExist;

		private TreeNode trndVideoNew;

		private TreeNode trndVideo;

		private RichTextBox txtLog;

		private CheckBox chkLogAutoScroll;

		private List<VKClient> Clients;

		private AlbumInfo[] Albums;

		private TopicInfo[] Topics;

		private VideoInfo[] Videos;

		private static Random rnd = new Random();

		private static Gsom ggen = new Gsom(Configurations.General.Library, Encoding.Default);

		private string aimName;

		private volatile int aimId;

		private volatile int wallmsgCount;

		private volatile int topicsCount;

		private volatile int topicsAnswersCount;

		private volatile int albumsCount;

		private volatile int photosCount;

		private volatile int audiosCount;

		private volatile int videosCount;

		private volatile int videosCommentsCount;

		private Thread thrPrep;

		private LogWriteCallBack dLogWrite;

		private volatile int ExcludePauseInterval;

		private volatile bool stopAllThreads;

		private Thread[] threads;

		public int WallMessagesCount => wallmsgCount;

		public int TopicsCount => topicsCount;

		public int TopicsAnswersCount => topicsAnswersCount;

		public int AlbumsCount => albumsCount;

		public int PhotosCount => photosCount;

		public int AudiosCount => audiosCount;

		public int VideosCount => videosCount;

		public int VideosCommentsCount => videosCommentsCount;

		public bool IsPrepearing { get; private set; }

		public int PrepearingProgress { get; private set; }

		public bool IsActive { get; private set; }

		public string AimName => aimName;

		public int AimId => aimId;

		protected override void Dispose(bool disposing)
		{
			if (disposing && components != null)
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		private void InitializeComponent()
		{
			trndWallLuch = new System.Windows.Forms.TreeNode("Пускать лучепонос");
			trndWallGraffiti = new System.Windows.Forms.TreeNode("Постить граффити");
			trndWallAudio = new System.Windows.Forms.TreeNode("Постить аудио");
			trndWallVideo = new System.Windows.Forms.TreeNode("Постить видео");
			trndWall = new System.Windows.Forms.TreeNode("Стена", new System.Windows.Forms.TreeNode[4] { trndWallLuch, trndWallGraffiti, trndWallAudio, trndWallVideo });
			trndTopicsExist = new System.Windows.Forms.TreeNode("Пячить существующие");
			trndTopicsNew = new System.Windows.Forms.TreeNode("Создавать новые");
			trndTopics = new System.Windows.Forms.TreeNode("Обсуждения", new System.Windows.Forms.TreeNode[2] { trndTopicsExist, trndTopicsNew });
			trndAlbumsExist = new System.Windows.Forms.TreeNode("Пячить существующие");
			trndAlbumsNew = new System.Windows.Forms.TreeNode("Создавать новые");
			trndAlbums = new System.Windows.Forms.TreeNode("Альбомы", new System.Windows.Forms.TreeNode[2] { trndAlbumsExist, trndAlbumsNew });
			trndAudioLuch = new System.Windows.Forms.TreeNode("Лучепонос в названии");
			trndAudio = new System.Windows.Forms.TreeNode("Аудио", new System.Windows.Forms.TreeNode[1] { trndAudioLuch });
			trndVideoExist = new System.Windows.Forms.TreeNode("Пячить существующие");
			trndVideoNew = new System.Windows.Forms.TreeNode("Добавлять новые");
			trndVideo = new System.Windows.Forms.TreeNode("Видео", new System.Windows.Forms.TreeNode[2] { trndVideoExist, trndVideoNew });
			trConfigs = new System.Windows.Forms.TreeView();
			spltcon = new System.Windows.Forms.SplitContainer();
			txtLog = new System.Windows.Forms.RichTextBox();
			tlpCommands = new System.Windows.Forms.TableLayoutPanel();
			btnGsom = new System.Windows.Forms.Button();
			btnStop = new System.Windows.Forms.Button();
			chkLogAutoScroll = new System.Windows.Forms.CheckBox();
			spltcon.Panel1.SuspendLayout();
			spltcon.Panel2.SuspendLayout();
			spltcon.SuspendLayout();
			tlpCommands.SuspendLayout();
			SuspendLayout();
			trConfigs.CheckBoxes = true;
			trConfigs.Dock = System.Windows.Forms.DockStyle.Fill;
			trConfigs.Location = new System.Drawing.Point(0, 0);
			trConfigs.Name = "trConfigs";
			trConfigs.Nodes.AddRange(new System.Windows.Forms.TreeNode[5] { trndWall, trndTopics, trndAlbums, trndAudio, trndVideo });
			trConfigs.Size = new System.Drawing.Size(155, 131);
			trConfigs.TabIndex = 0;
			tlpCommands.SetColumnSpan(spltcon, 3);
			spltcon.Dock = System.Windows.Forms.DockStyle.Fill;
			spltcon.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
			spltcon.Location = new System.Drawing.Point(3, 26);
			spltcon.Name = "spltcon";
			spltcon.Panel1.Controls.Add(trConfigs);
			spltcon.Panel2.Controls.Add(txtLog);
			spltcon.Panel2.Padding = new System.Windows.Forms.Padding(1);
			spltcon.Panel2.Paint += new System.Windows.Forms.PaintEventHandler(spltcon_Panel2_Paint);
			spltcon.Size = new System.Drawing.Size(546, 415);
			spltcon.SplitterDistance = 120;
			spltcon.TabIndex = 1;
			txtLog.BackColor = System.Drawing.SystemColors.Window;
			txtLog.BorderStyle = System.Windows.Forms.BorderStyle.None;
			txtLog.Dock = System.Windows.Forms.DockStyle.Fill;
			txtLog.Font = new System.Drawing.Font("Courier New", 9.75f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 204);
			txtLog.Location = new System.Drawing.Point(1, 1);
			txtLog.Name = "txtLog";
			txtLog.ReadOnly = true;
			txtLog.Size = new System.Drawing.Size(420, 413);
			txtLog.TabIndex = 1;
			txtLog.Text = "";
			txtLog.WordWrap = false;
			txtLog.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(txtLog_LinkClicked);
			tlpCommands.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
			tlpCommands.ColumnCount = 3;
			tlpCommands.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100f));
			tlpCommands.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
			tlpCommands.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
			tlpCommands.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20f));
			tlpCommands.Controls.Add(spltcon, 0, 1);
			tlpCommands.Controls.Add(btnGsom, 2, 2);
			tlpCommands.Controls.Add(btnStop, 1, 2);
			tlpCommands.Controls.Add(chkLogAutoScroll, 0, 0);
			tlpCommands.Dock = System.Windows.Forms.DockStyle.Fill;
			tlpCommands.Location = new System.Drawing.Point(0, 0);
			tlpCommands.Name = "tlpCommands";
			tlpCommands.RowCount = 3;
			tlpCommands.RowStyles.Add(new System.Windows.Forms.RowStyle());
			tlpCommands.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100f));
			tlpCommands.RowStyles.Add(new System.Windows.Forms.RowStyle());
			tlpCommands.Size = new System.Drawing.Size(552, 475);
			tlpCommands.TabIndex = 3;
			btnGsom.Enabled = false;
			btnGsom.Location = new System.Drawing.Point(464, 447);
			btnGsom.Name = "btnGsom";
			btnGsom.Size = new System.Drawing.Size(85, 25);
			btnGsom.TabIndex = 0;
			btnGsom.Text = "Gsom!";
			btnGsom.UseVisualStyleBackColor = true;
			btnGsom.Click += new System.EventHandler(btnGsom_Click);
			btnStop.Enabled = false;
			btnStop.Location = new System.Drawing.Point(373, 447);
			btnStop.Name = "btnStop";
			btnStop.Size = new System.Drawing.Size(85, 25);
			btnStop.TabIndex = 1;
			btnStop.Text = "Стоп";
			btnStop.UseVisualStyleBackColor = true;
			btnStop.Click += new System.EventHandler(btnStop_Click);
			chkLogAutoScroll.Anchor = System.Windows.Forms.AnchorStyles.Right;
			chkLogAutoScroll.AutoSize = true;
			chkLogAutoScroll.Checked = true;
			chkLogAutoScroll.CheckState = System.Windows.Forms.CheckState.Checked;
			tlpCommands.SetColumnSpan(chkLogAutoScroll, 3);
			chkLogAutoScroll.Location = new System.Drawing.Point(426, 3);
			chkLogAutoScroll.Name = "chkLogAutoScroll";
			chkLogAutoScroll.Size = new System.Drawing.Size(123, 17);
			chkLogAutoScroll.TabIndex = 2;
			chkLogAutoScroll.Text = "Автоскролинг лога";
			chkLogAutoScroll.UseVisualStyleBackColor = true;
			base.Controls.Add(tlpCommands);
			base.Name = "AttackControl";
			base.Size = new System.Drawing.Size(552, 475);
			spltcon.Panel1.ResumeLayout(false);
			spltcon.Panel2.ResumeLayout(false);
			spltcon.ResumeLayout(false);
			tlpCommands.ResumeLayout(false);
			tlpCommands.PerformLayout();
			ResumeLayout(false);
		}

		public static AttackControl Create(int aimId, List<VKClient> clients)
		{
			VKClient vKClient = clients[rnd.Next(0, clients.Count)];
			string text = ((aimId >= 0) ? VKClient.GetPersonName(vKClient.Account, aimId) : VKClient.GetGroupName(vKClient.Account, aimId));
			AttackControl attackControl = new AttackControl();
			attackControl.aimName = text;
			attackControl.aimId = aimId;
			attackControl.Clients = clients;
			if (aimId > 0)
			{
				attackControl.trConfigs.Nodes.Remove(attackControl.trndTopics);
				attackControl.trConfigs.Nodes.Remove(attackControl.trndAlbums);
				attackControl.trConfigs.Nodes.Remove(attackControl.trndAudio);
				attackControl.trConfigs.Nodes.Remove(attackControl.trndVideo);
			}
			string text2 = string.Empty;
			string text3 = text;
			foreach (char c in text3)
			{
				if (char.IsLetter(c) || char.IsDigit(c) || c == '-' || c == ',' || c == '.' || c == ' ')
				{
					text2 += c;
				}
			}
			text2 = text2.Trim();
			if (text2.Length > 30)
			{
				text2 = text2.Substring(0, 27) + "...";
			}
			attackControl.TabText = ((text2.Length > 0) ? text2 : text);
			attackControl.LogWriteInfo("Цель: {0} http://vkontakte.ru/{1}{2}", text, (aimId < 0) ? "club" : "id", Math.Abs(aimId));
			return attackControl;
		}

		private AttackControl()
		{
			InitializeComponent();
			dLogWrite = LogWrite;
			trndWall.Checked = Configurations.Wall.Enabled;
			trndWallLuch.Checked = Configurations.Wall.Lucheponos;
			trndWallGraffiti.Checked = Configurations.Wall.PostGraffiti;
			trndWallAudio.Checked = Configurations.Wall.PostAudio;
			trndWallVideo.Checked = Configurations.Wall.PostVideo;
			trndTopics.Checked = Configurations.Topics.Enabled;
			trndTopicsExist.Checked = Configurations.Topics.CreateNewTopics;
			trndTopicsNew.Checked = Configurations.Topics.CreateNewTopics;
			trndAlbums.Checked = Configurations.Albums.Enabled;
			trndAlbumsExist.Checked = Configurations.Albums.PhotosUploadToExist;
			trndAlbumsNew.Checked = Configurations.Albums.CreateNew;
			trndAudio.Checked = Configurations.Audio.Enabled;
			trndAudioLuch.Checked = Configurations.Audio.Rename;
			trndVideo.Checked = Configurations.Video.Enabled;
			trndVideoExist.Checked = Configurations.Video.CommentExist;
			trndVideoNew.Checked = Configurations.Video.AddNew;
		}

		public void Prepare()
		{
			thrPrep = new Thread(_Prepare)
			{
				IsBackground = true
			};
			thrPrep.Start();
		}

		private void _Prepare()
		{
			IsPrepearing = true;
			if (aimId < 0)
			{
				List<VKClient> list = new List<VKClient>();
				bool flag = true;
				int num = 1000 / Clients.Count;
				List<VKClient> list2 = new List<VKClient>(Clients);
				foreach (VKClient item4 in list2)
				{
					if (stopAllThreads)
					{
						return;
					}
					item4.EnterGroup(aimId);
					int[] personGroups = item4.GetPersonGroups(item4.Account.ID);
					if (Array.Exists(personGroups, (int id) => id == aimId))
					{
						LogWrite("{0} вступил в группу, http://vkontakte.ru/id{1}", item4.Account.Name, item4.Account.ID);
						list.Add(item4);
					}
					else
					{
						LogWriteError("{0} НЕ вступил в группу, http://vkontakte.ru/id{1}", item4.Account.Name, item4.Account.ID);
						if (flag && MessageBox.Show("Вступление в группу с первого аккаунта не прошло успешно.\r\nВозможно группа загрыта, продолжить вступление с остальных аккаунтов?", "Ошибка вступления в группу", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
						{
							LogWriteInfo("Вступление в группу прервано.");
							IsPrepearing = false;
							return;
						}
						Clients.Remove(item4);
					}
					flag = false;
					PrepearingProgress += num;
				}
				int count = list.Count;
				if (count == 0)
				{
					LogWriteError("Ни один аккаунт не вступил в группу, сканирование прервано.");
					IsPrepearing = false;
					return;
				}
				ExcludePauseInterval = 100 * Clients.Count;
				LogWriteInfo("Сканируем обсуждения");
				try
				{
					PrepearingProgress = 0;
					List<TopicInfo> list3 = new List<TopicInfo>();
					int count2 = -1;
					int num2 = -1;
					int grabMaxCount = Configurations.Topics.GrabMaxCount;
					int num3 = 1;
					int num4 = 0;
					while ((num3 <= num2 || num2 == -1) && (num3 - 1) * 50 < grabMaxCount)
					{
						if (stopAllThreads)
						{
							return;
						}
						TopicInfo[] groupTopics = list[num4].GetGroupTopics(aimId, num3, ref count2);
						if (num2 == -1)
						{
							LogWrite("В группе {0} oбсуждений", count2);
							num2 = ((count2 > grabMaxCount) ? ((int)Math.Ceiling((double)grabMaxCount / 50.0)) : ((int)Math.Ceiling((double)count2 / 50.0)));
							if (num2 == 0)
							{
								num2 = 1;
							}
							Thread.Sleep(500);
							num = 1000 / num2;
						}
						TopicInfo[] array = groupTopics;
						for (int i = 0; i < array.Length; i++)
						{
							TopicInfo item = array[i];
							if (Configurations.Topics.RecognizeByKey && ContainsKey(item.Title, item.AuthorID))
							{
								continue;
							}
							if (Configurations.Topics.NoAttackTodayCreated)
							{
								DateTime creationDate = item.CreationDate;
								if (creationDate.Date == DateTime.UtcNow.Date)
								{
									continue;
								}
							}
							list3.Add(item);
							if (Configurations.General.FullLog)
							{
								LogWrite("Обсуждение \"{0}\" создано {1:d} {1:t}, http://vkontakte.ru/topic{2}_{3}", item.Title, item.CreationDate, item.OwnerID, item.ID);
							}
						}
						PrepearingProgress += num;
						if (num3 < num2)
						{
							Thread.Sleep(1000 / count);
						}
						num3++;
						num4 = (num4 + 1) % count;
					}
					Topics = list3.ToArray();
				}
				catch (Exception ex)
				{
					LogWriteError(ex.Message);
				}
				LogWriteInfo("Сканируем альбомы");
				try
				{
					PrepearingProgress = 0;
					int grabMaxCount2 = Configurations.Albums.GrabMaxCount;
					int num5 = list[rnd.Next(0, count)].GetAlbumsCount(aimId);
					int num6 = ((num5 > grabMaxCount2) ? ((int)Math.Ceiling((double)grabMaxCount2 / 50.0)) : ((int)Math.Ceiling((double)num5 / 50.0)));
					if (num6 == 0)
					{
						num6 = 1;
					}
					num = 1000 / num6;
					LogWrite("В группе {0} альбомов", num5);
					Thread.Sleep(1000);
					List<AlbumInfo> list4 = new List<AlbumInfo>();
					int num7 = 0;
					int num8 = 0;
					while (num7 < num5 && num7 < grabMaxCount2)
					{
						if (stopAllThreads)
						{
							return;
						}
						AlbumInfo[] array2 = list[num8].Get50Albums(aimId, num7);
						AlbumInfo[] array3 = array2;
						for (int j = 0; j < array3.Length; j++)
						{
							AlbumInfo item2 = array3[j];
							if (item2.PhotosCount >= 501)
							{
								continue;
							}
							if (Configurations.Albums.RecognizeByKey)
							{
								string description = item2.Description;
								DateTime creationDate2 = item2.CreationDate;
								if (ContainsKey(description, creationDate2.GetHashCode()))
								{
									continue;
								}
							}
							if (Configurations.Albums.NoAttackTodayCreated)
							{
								DateTime creationDate3 = item2.CreationDate;
								if (creationDate3.Date == DateTime.UtcNow.Date)
								{
									continue;
								}
							}
							list4.Add(item2);
							if (Configurations.General.FullLog)
							{
								LogWrite("Альбом \"{0}\" содержит {1} фото, cоздан {2:d}, http://vkontakte.ru/album{3}_{4}", item2.Name, item2.PhotosCount, item2.CreationDate, aimId, item2.ID);
							}
						}
						PrepearingProgress += num;
						Thread.Sleep(1000 / count);
						num7 += 50;
						num8 = (num8 + 1) % count;
					}
					Albums = list4.ToArray();
				}
				catch (Exception ex2)
				{
					LogWriteError(ex2.Message);
				}
				LogWriteInfo("Сканируем видео");
				try
				{
					PrepearingProgress = 0;
					int grabMaxCount3 = Configurations.Video.GrabMaxCount;
					List<VideoInfo> list5 = new List<VideoInfo>();
					int total_count = 0;
					list[rnd.Next(0, count)].Get100Videos(aimId, 0, out total_count);
					LogWrite("В группе {0} видео", total_count);
					int num9 = ((total_count > grabMaxCount3) ? ((int)Math.Ceiling((double)grabMaxCount3 / 100.0)) : ((int)Math.Ceiling((double)total_count / 100.0)));
					if (num9 == 0)
					{
						num9 = 1;
					}
					num = 1000 / num9;
					int num10 = total_count - 100;
					if (num10 < 0)
					{
						num10 = 0;
					}
					int num11 = 0;
					do
					{
						if (stopAllThreads)
						{
							return;
						}
						VideoInfo[] array4 = list[num11].Get100Videos(aimId, num10);
						num11 = (num11 + 1) % count;
						for (int num12 = array4.Length - 1; num12 >= 0; num12--)
						{
							VideoInfo item3 = array4[num12];
							if (!Configurations.Video.NoAttackTodayCreated || !(item3.LoadDate == DateTime.UtcNow.Date))
							{
								if (Configurations.General.FullLog)
								{
									LogWrite("Видео \"{0}\" добавлено {1:d}, http://vkontakte.ru/video{2}_{3}", item3.Name, item3.LoadDate, item3.OwnerID, item3.ID);
								}
								list5.Add(item3);
							}
						}
						PrepearingProgress += num;
						Thread.Sleep(1000 / count);
						num10 -= 100;
					}
					while (num10 > 0 && total_count - num10 < grabMaxCount3);
					Videos = list5.ToArray();
				}
				catch (Exception ex3)
				{
					LogWriteError(ex3.Message);
				}
			}
			PrepearingProgress = 100;
			GC.Collect();
			LogWriteInfo("Информация о группе собрана, жми \"Gsom!\" для отаке.");
			Invoke((Proc)delegate
			{
				btnGsom.Enabled = true;
			});
			IsPrepearing = false;
		}

		private void LogWrite(string s, params object[] p)
		{
			LogWrite(s, Color.Black, p);
		}

		private void LogWriteInfo(string i, params object[] p)
		{
			LogWrite(i, Color.Green, p);
		}

		private void LogWriteError(string err, params object[] p)
		{
			LogWrite(err, Color.Red, p);
		}

		private void LogWrite(string msg, Color color, params object[] p)
		{
			if (txtLog.IsDisposed)
			{
				return;
			}
			if (txtLog.InvokeRequired)
			{
				Invoke(dLogWrite, msg, color, p);
				return;
			}
			txtLog.SelectionLength = 0;
			txtLog.SelectionStart = txtLog.TextLength;
			txtLog.SelectionColor = Color.Gray;
			txtLog.AppendText($"{DateTime.Now:t} ");
			txtLog.SelectionColor = color;
			txtLog.AppendText(string.Format(msg.Replace("\r\n", " ") + "\r\n", p));
			if (chkLogAutoScroll.Checked)
			{
				txtLog.ScrollToCaret();
			}
		}

		private void spltcon_Panel2_Paint(object sender, PaintEventArgs e)
		{
			Control control = sender as Control;
			if (TextBoxRenderer.IsSupported)
			{
				TextBoxRenderer.DrawTextBox(e.Graphics, control.ClientRectangle, TextBoxState.Normal);
			}
			else
			{
				e.Graphics.DrawRectangle(SystemPens.ActiveBorder, 0, 0, control.ClientRectangle.Width - 1, control.ClientRectangle.Height - 1);
			}
		}

		private void txtLog_LinkClicked(object sender, LinkClickedEventArgs e)
		{
			try
			{
				Process.Start(e.LinkText);
			}
			catch
			{
			}
		}

		private void btnGsom_Click(object sender, EventArgs e)
		{
			btnGsom.Enabled = false;
			Application.DoEvents();
			stopAllThreads = false;
			threads = new Thread[8]
			{
				new Thread(PostWallMessages)
				{
					IsBackground = true
				},
				new Thread(CreateNewTopics)
				{
					IsBackground = true
				},
				new Thread(PostTopicsAnswers)
				{
					IsBackground = true
				},
				new Thread(CreateAlbums)
				{
					IsBackground = true
				},
				new Thread(PhotosUpload)
				{
					IsBackground = true
				},
				new Thread(AudioUpload)
				{
					IsBackground = true
				},
				new Thread(VideosAdd)
				{
					IsBackground = true
				},
				new Thread(CommentVideos)
				{
					IsBackground = true
				}
			};
			LogWriteInfo("GSOM!");
			Thread[] array = threads;
			foreach (Thread thread in array)
			{
				thread.Start();
			}
			btnStop.Enabled = true;
			IsActive = true;
		}

		private void btnStop_Click(object sender, EventArgs e)
		{
			btnStop.Enabled = false;
			Application.DoEvents();
			stopAllThreads = true;
			while (thrPrep != null && thrPrep.IsAlive)
			{
				Application.DoEvents();
				Thread.Sleep(100);
			}
			if (threads != null)
			{
				Thread[] array = threads;
				foreach (Thread thread in array)
				{
					while (thread.IsAlive)
					{
						Application.DoEvents();
						Thread.Sleep(100);
					}
				}
			}
			threads = null;
			btnGsom.Enabled = true;
			IsActive = false;
		}

		private void PostWallMessages()
		{
			int num = Configurations.Wall.Audio.Length;
			int num2 = Configurations.Wall.Videos.Length;
			int num3 = Configurations.Wall.Graffities.Length;
			GsomFormats gsomFormats = GsomFormats.Default;
			if (Configurations.General.AddExtraLines)
			{
				gsomFormats |= GsomFormats.InsertExtraLines;
			}
			if (Configurations.General.AddAsciiImages)
			{
				gsomFormats |= GsomFormats.UseMultiLineMessages;
			}
			if (Configurations.General.RandomCase)
			{
				gsomFormats |= GsomFormats.RandomCase;
			}
			int num4 = Configurations.Wall.TimeDelay;
			int id = aimId;
			List<VKClient> list = new List<VKClient>(Clients);
			Queue<ExcudedVKClient> queue = new Queue<ExcudedVKClient>();
			List<int> list2 = new List<int>();
			bool flag = false;
			do
			{
				flag = false;
				VKClient vKClient = null;
				try
				{
					int num5 = 0;
					while (!stopAllThreads)
					{
						if (trndWall.Checked)
						{
							if (list.Count > 0)
							{
								vKClient = list[num5];
								num5 = (num5 + 1) % list.Count;
								list2.Clear();
								if (trndWallLuch.Checked)
								{
									list2.Add(1);
								}
								if (trndWallGraffiti.Checked && num3 > 0)
								{
									list2.Add(2);
								}
								if (trndWallAudio.Checked && num > 0)
								{
									list2.Add(3);
								}
								if (trndWallVideo.Checked && num2 > 0)
								{
									list2.Add(4);
								}
								if (list2.Count > 0)
								{
									int index = rnd.Next(0, list2.Count);
									try
									{
										switch (list2[index])
										{
										case 1:
											vKClient.PostWallMessage(id, ggen.Generate(Configurations.Wall.MessageLength, gsomFormats));
											break;
										case 2:
											vKClient.PostWallGraffiti(id, Files.GetFile(Configurations.Wall.Graffities[rnd.Next(0, num3)]));
											break;
										case 3:
											vKClient.PostWallMessage(id, Configurations.Wall.Audio[rnd.Next(0, num)]);
											break;
										case 4:
											vKClient.PostWallMessage(id, Configurations.Wall.Videos[rnd.Next(0, num2)]);
											break;
										}
										wallmsgCount++;
									}
									catch (CaptchaIgnoredException)
									{
									}
								}
								Thread.Sleep(num4 / list.Count);
							}
							else
							{
								Thread.Sleep(1000);
							}
							while (queue.Count > 0 && (DateTime.Now - queue.Peek().ExcludeTime).TotalSeconds >= (double)ExcludePauseInterval)
							{
								VKClient @base = queue.Dequeue().Base;
								list.Add(@base);
								LogWrite("Стена> Аккаунт {0} восстановлен.", @base.Account.Name);
							}
						}
						else
						{
							Thread.Sleep(1000);
						}
					}
				}
				catch (BlankErrorException ex2)
				{
					LogWriteError("Стена({0})> {1}", vKClient.Account.Name, ex2.Message);
					switch (ex2.Code)
					{
					case 0:
					{
						if (Configurations.General.AutoDelays)
						{
							num4 += 200;
							LogWrite("Стена> Времменая задержка повышена на 200мс и составляет {0}мс.", num4);
						}
						LogWrite("Стена> Попячивание временно приостановлено.");
						DateTime now = DateTime.Now;
						while ((DateTime.Now - now).TotalSeconds < 15.0)
						{
							if (stopAllThreads)
							{
								return;
							}
							Thread.Sleep(1000);
						}
						LogWrite("Стена> Попячивание возобновлено.");
						break;
					}
					case 3:
					case 9:
						list.Remove(vKClient);
						LogWrite("Стена> Аккаунт {0} исключен.", vKClient.Account.Name);
						break;
					default:
						list.Remove(vKClient);
						queue.Enqueue(new ExcudedVKClient(vKClient));
						LogWrite("Стена> Аккаунт {0} временно исключен.", vKClient.Account.Name);
						break;
					}
					flag = true;
				}
				catch (CaptchaCanceledException ex3)
				{
					LogWriteError("Стена({0})> Капча отменена.", vKClient.Account.Name, ex3.Message);
					list.Remove(vKClient);
					queue.Enqueue(new ExcudedVKClient(vKClient));
					LogWrite("Стена> Аккаунт {0} временно исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (AuthorizationFailedException)
				{
					LogWriteError("Стена({0})> Ошибка авторизации.", vKClient.Account.Name);
					list.Remove(vKClient);
					LogWrite("Стена> Аккаунт {0} исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (WebException ex5)
				{
					LogWriteError("Стена({0})> {1}", vKClient.Account.Name, ex5.Message);
					flag = true;
				}
				if (list.Count == 0 && queue.Count == 0)
				{
					LogWriteError("Стена> Все аккаунты исключены, попячивание остановлено.");
					return;
				}
				if (flag)
				{
					Thread.Sleep(num4);
				}
			}
			while (flag);
			if (trndWall.Checked)
			{
				LogWriteInfo("Стена> Попячивание остановлено.");
			}
		}

		private void CreateNewTopics()
		{
			int num = aimId;
			if (num > 0)
			{
				return;
			}
			GsomFormats gsomFormats = GsomFormats.Default;
			if (Configurations.General.AddExtraLines)
			{
				gsomFormats |= GsomFormats.InsertExtraLines;
			}
			if (Configurations.General.AddAsciiImages)
			{
				gsomFormats |= GsomFormats.UseMultiLineMessages;
			}
			if (Configurations.General.RandomCase)
			{
				gsomFormats |= GsomFormats.RandomCase;
			}
			int num2 = Configurations.Topics.CreationTimeDelay;
			List<VKClient> list = new List<VKClient>(Clients);
			Queue<ExcudedVKClient> queue = new Queue<ExcudedVKClient>();
			bool flag = false;
			do
			{
				flag = false;
				VKClient vKClient = null;
				try
				{
					int num3 = 0;
					while (!stopAllThreads)
					{
						if (trndTopics.Checked && trndTopicsNew.Checked)
						{
							if (list.Count > 0)
							{
								vKClient = list[num3];
								num3 = (num3 + 1) % list.Count;
								try
								{
									vKClient.CreateTopic(num, InsertKey(ggen.Generate(Configurations.Topics.TitleLength, gsomFormats ^ GsomFormats.InsertExtraLines ^ GsomFormats.UseMultiLineMessages), vKClient.Account.ID), ggen.Generate(Configurations.Topics.PostLength, gsomFormats));
									topicsCount++;
								}
								catch (CaptchaIgnoredException)
								{
								}
								Thread.Sleep(num2 / list.Count);
							}
							else
							{
								Thread.Sleep(1000);
							}
							while (queue.Count > 0 && (DateTime.Now - queue.Peek().ExcludeTime).TotalSeconds >= (double)ExcludePauseInterval)
							{
								VKClient @base = queue.Dequeue().Base;
								list.Add(@base);
								LogWrite("Обсуждения-создание> Аккаунт {0} восстановлен.", @base.Account.Name);
							}
						}
						else
						{
							Thread.Sleep(1000);
						}
					}
				}
				catch (BlankErrorException ex2)
				{
					LogWriteError("Обсуждения-создание({0})> {1}", vKClient.Account.Name, ex2.Message);
					switch (ex2.Code)
					{
					case 0:
					{
						if (Configurations.General.AutoDelays)
						{
							num2 += 200;
							LogWrite("Обсуждения-создание> Времменая задержка повышена на 200мс и составляет {0}мс.", num2);
						}
						LogWrite("Обсуждения-создание> Попячивание временно приостановлено.");
						DateTime now = DateTime.Now;
						while ((DateTime.Now - now).TotalSeconds < 15.0)
						{
							if (stopAllThreads)
							{
								return;
							}
							Thread.Sleep(1000);
						}
						LogWrite("Обсуждения-создание> Попячивание возобновлено.");
						break;
					}
					case -2:
					case 9:
						list.Remove(vKClient);
						LogWrite("Обсуждения-создание> Аккаунт {0} исключен.", vKClient.Account.Name);
						break;
					default:
						list.Remove(vKClient);
						queue.Enqueue(new ExcudedVKClient(vKClient));
						LogWrite("Обсуждения-создание> Аккаунт {0} временно исключен.", vKClient.Account.Name);
						break;
					}
					flag = true;
				}
				catch (CaptchaCanceledException ex3)
				{
					LogWriteError("Обсуждения-создание({0})> Капча отменена.", vKClient.Account.Name, ex3.Message);
					list.Remove(vKClient);
					queue.Enqueue(new ExcudedVKClient(vKClient));
					LogWrite("Обсуждения-создание> Аккаунт {0} временно исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (AuthorizationFailedException)
				{
					LogWriteError("Обсуждения-создание({0})> Ошибка авторизации.", vKClient.Account.Name);
					list.Remove(vKClient);
					LogWrite("Обсуждения-создание> Аккаунт {0} исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (WebException ex5)
				{
					LogWriteError("Обсуждения-создание({0})> {1}", vKClient.Account.Name, ex5.Message);
					flag = true;
				}
				if (list.Count == 0 && queue.Count == 0)
				{
					LogWriteError("Обсуждения-создание> Все аккаунты исключены, попячивание остановлено.");
					return;
				}
				if (flag)
				{
					Thread.Sleep(num2);
				}
			}
			while (flag);
			if (trndTopics.Checked && trndTopicsNew.Checked)
			{
				LogWriteInfo("Обсуждения-создание> Попячивание остановлено.");
			}
		}

		private void PostTopicsAnswers()
		{
			int num = aimId;
			if (num > 0 || Topics == null || Topics.Length == 0)
			{
				return;
			}
			GsomFormats gsomFormats = GsomFormats.Default;
			if (Configurations.General.AddExtraLines)
			{
				gsomFormats |= GsomFormats.InsertExtraLines;
			}
			if (Configurations.General.AddAsciiImages)
			{
				gsomFormats |= GsomFormats.UseMultiLineMessages;
			}
			if (Configurations.General.RandomCase)
			{
				gsomFormats |= GsomFormats.RandomCase;
			}
			int num2 = Configurations.Topics.AnswerTimeDelay;
			List<VKClient> list = new List<VKClient>(Clients);
			Queue<ExcudedVKClient> queue = new Queue<ExcudedVKClient>();
			int num3 = 0;
			if (Configurations.Topics.RandomAnswerStart)
			{
				num3 = rnd.Next(0, Topics.Length);
			}
			int num4 = -1;
			VKClient vKClient = null;
			bool flag = false;
			do
			{
				flag = false;
				try
				{
					while (!stopAllThreads)
					{
						if (trndTopics.Checked && trndTopicsExist.Checked)
						{
							if (list.Count > 0)
							{
								num4 = (num4 + 1) % list.Count;
								vKClient = list[num4];
								try
								{
									if (vKClient.PostTopicAnswer(Topics[num3], ggen.Generate(Configurations.Topics.AnswerLength, gsomFormats)))
									{
										topicsAnswersCount++;
									}
								}
								catch (CaptchaIgnoredException)
								{
								}
								if (topicsAnswersCount % 20 == 0)
								{
									num3 = (num3 + 1) % Topics.Length;
								}
								Thread.Sleep(num2 / list.Count);
							}
							else
							{
								Thread.Sleep(1000);
							}
							while (queue.Count > 0 && (DateTime.Now - queue.Peek().ExcludeTime).TotalSeconds >= (double)ExcludePauseInterval)
							{
								VKClient @base = queue.Dequeue().Base;
								list.Add(@base);
								LogWrite("Обсуждения-ответы> Аккаунт {0} восстановлен.", @base.Account.Name);
							}
						}
						else
						{
							Thread.Sleep(1000);
						}
					}
				}
				catch (BlankErrorException ex2)
				{
					LogWriteError("Обсуждения-ответы({0})> {1}", vKClient.Account.Name, ex2.Message);
					switch (ex2.Code)
					{
					case 0:
						if (Configurations.General.AutoDelays)
						{
							num2 += 200;
							LogWrite("Обсуждения-ответы> Времменая задержка повышена на 200мс и составляет {0}мс.", num2);
						}
						else
						{
							Thread.Sleep(1000);
						}
						break;
					case 9:
						list.Remove(vKClient);
						LogWrite("Обсуждения-ответы> Аккаунт {0} исключен.", vKClient.Account.Name);
						break;
					default:
						list.Remove(vKClient);
						queue.Enqueue(new ExcudedVKClient(vKClient));
						LogWrite("Обсуждения-ответы> Аккаунт {0} временно исключен.", vKClient.Account.Name);
						break;
					}
					flag = true;
				}
				catch (CaptchaCanceledException ex3)
				{
					LogWriteError("Обсуждения-ответы({0})> Капча отменена.", vKClient.Account.Name, ex3.Message);
					list.Remove(vKClient);
					queue.Enqueue(new ExcudedVKClient(vKClient));
					LogWrite("Обсуждения-ответы> Аккаунт {0} временно исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (AuthorizationFailedException)
				{
					LogWriteError("Обсуждения-ответы({0})> Ошибка авторизации.", vKClient.Account.Name);
					list.Remove(vKClient);
					LogWrite("Обсуждения-ответы> Аккаунт {0} исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (WebException ex5)
				{
					LogWriteError("Обсуждения-ответы({0})> {1}", vKClient.Account.Name, ex5.Message);
					flag = true;
				}
				if (list.Count == 0 && queue.Count == 0)
				{
					LogWriteError("Обсуждения-ответы> Все аккаунты исключены, попячивание остановлено.");
					return;
				}
				if (flag)
				{
					Thread.Sleep(num2);
				}
			}
			while (flag);
			if (trndTopics.Checked && trndTopicsExist.Checked)
			{
				LogWriteInfo("Обсуждения-ответы> Попячивание остановлено.");
			}
		}

		private void CreateAlbums()
		{
			int num = aimId;
			if (num > 0)
			{
				return;
			}
			int num2 = Configurations.Albums.Photos.Length;
			int timeDelay = Configurations.Wall.TimeDelay;
			List<VKClient> list = new List<VKClient>(Clients);
			Queue<ExcudedVKClient> queue = new Queue<ExcudedVKClient>();
			GsomFormats gsomFormats = GsomFormats.Default;
			if (Configurations.General.RandomCase)
			{
				gsomFormats |= GsomFormats.RandomCase;
			}
			if (Configurations.General.AddExtraLines)
			{
				gsomFormats |= GsomFormats.InsertExtraLines;
			}
			if (Configurations.General.AddAsciiImages)
			{
				gsomFormats |= GsomFormats.UseMultiLineMessages;
			}
			bool flag = false;
			do
			{
				flag = false;
				VKClient vKClient = null;
				try
				{
					int num3 = 0;
					while (!stopAllThreads)
					{
						if (trndAlbums.Checked && trndAlbumsNew.Checked)
						{
							if (list.Count > 0)
							{
								vKClient = list[num3];
								num3 = (num3 + 1) % list.Count;
								AlbumInfo album = vKClient.CreateAlbum(num, ggen.Phrases[rnd.Next(0, ggen.Phrases.Count)], InsertKey(ggen.Generate(Configurations.Albums.DescriptionLength, gsomFormats), DateTime.UtcNow.Date.GetHashCode()));
								try
								{
									if (num2 > 0)
									{
										List<byte[]> list2 = new List<byte[]>();
										list2.Add(Files.GetFile(Configurations.Albums.Photos[rnd.Next(0, num2)]));
										vKClient.UploadPhotos(album, list2, save: true);
									}
								}
								catch (CaptchaCanceledException)
								{
									LogWriteError("Альбомы-создание({0})> Капча отменена, фото не добавлено в новый альбом.", vKClient.Account.Name);
								}
								catch (CaptchaIgnoredException)
								{
									LogWriteError("Альбомы-создание({0})> Капча игнорирована, фото не добавлено в новый альбом.", vKClient.Account.Name);
								}
								albumsCount++;
								Thread.Sleep(timeDelay / list.Count);
							}
							else
							{
								Thread.Sleep(1000);
							}
							while (queue.Count > 0 && (DateTime.Now - queue.Peek().ExcludeTime).TotalSeconds >= (double)ExcludePauseInterval)
							{
								VKClient @base = queue.Dequeue().Base;
								list.Add(@base);
								LogWrite("Альбомы-создание> Аккаунт {0} восстановлен.", @base.Account.Name);
							}
						}
						else
						{
							Thread.Sleep(1000);
						}
					}
				}
				catch (BlankErrorException ex3)
				{
					LogWriteError("Альбомы-создание({0})> {1}", vKClient.Account.Name, ex3.Message);
					switch (ex3.Code)
					{
					case 0:
					{
						LogWrite("Альбомы-создание> Попячивание временно приостановлено.");
						DateTime now = DateTime.Now;
						while ((DateTime.Now - now).TotalSeconds < 1800.0)
						{
							if (stopAllThreads)
							{
								return;
							}
							Thread.Sleep(1000);
						}
						LogWrite("Альбомы-создание> Попячивание возобновлено.");
						break;
					}
					case -2:
					case 9:
					case 1602:
						list.Remove(vKClient);
						LogWrite("Альбомы-создание> Аккаунт {0} исключен.", vKClient.Account.Name);
						break;
					default:
						list.Remove(vKClient);
						queue.Enqueue(new ExcudedVKClient(vKClient));
						LogWrite("Альбомы-создание> Аккаунт {0} временно исключен.", vKClient.Account.Name);
						break;
					}
					flag = true;
				}
				catch (AuthorizationFailedException)
				{
					LogWriteError("Альбомы-создание({0})> Ошибка авторизации.", vKClient.Account.Name);
					list.Remove(vKClient);
					LogWrite("Альбомы-создание> Аккаунт {0} исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (WebException ex5)
				{
					LogWriteError("Альбомы-создание({0})> {1}", vKClient.Account.Name, ex5.Message);
					flag = true;
				}
				if (list.Count == 0 && queue.Count == 0)
				{
					LogWriteError("Альбомы-создание> Все аккаунты исключены, попячивание остановлено.");
					return;
				}
				if (flag)
				{
					Thread.Sleep(timeDelay);
				}
			}
			while (flag);
			if (trndAlbums.Checked && trndAlbumsNew.Checked)
			{
				LogWriteInfo("Альбомы-создание> Попячивание остановлено");
			}
		}

		private void PhotosUpload()
		{
			int num = aimId;
			if (num > 0 || Albums == null || Albums.Length == 0)
			{
				return;
			}
			int num2 = Configurations.Albums.Photos.Length;
			if (num2 == 0)
			{
				return;
			}
			int photosUploadTimeDelay = Configurations.Albums.PhotosUploadTimeDelay;
			List<VKClient> list = new List<VKClient>(Clients);
			AlbumInfo albumInfo = Albums[0];
			int num3 = 0;
			int num4 = 0;
			while (num3 < Albums.Length && !stopAllThreads)
			{
				if (trndAlbums.Checked && trndAlbumsExist.Checked)
				{
					VKClient vKClient = list[num4];
					albumInfo = Albums[num3];
					if (albumInfo.PhotosCount < 500)
					{
						try
						{
							List<byte[]> list2 = new List<byte[]>();
							while (list2.Count < 3)
							{
								list2.Add(Files.GetFile(Configurations.Albums.Photos[rnd.Next(0, num2)]));
							}
							FileSaveInfo sv_info = vKClient.UploadPhotos(albumInfo, list2, save: true);
							photosCount += 3;
							while (!stopAllThreads)
							{
								if (trndAlbums.Checked && trndAlbumsExist.Checked)
								{
									if (Configurations.Albums.PhotosAlwaysUpload)
									{
										vKClient.UploadPhotos(albumInfo, list2, save: true);
									}
									else
									{
										VKClient.SavePhoto(sv_info);
									}
									photosCount += 3;
									Thread.Sleep(photosUploadTimeDelay);
								}
								else
								{
									Thread.Sleep(1000);
								}
							}
						}
						catch (BlankErrorException ex)
						{
							if (ex.Code == 21)
							{
								albumInfo.PhotosCount = 501;
								LogWrite("Альбомы-загрузка> \"{0}\" заполнен.", albumInfo.Name);
								num3++;
							}
							else
							{
								LogWriteError("Альбомы-загрузка({0})> \"{1}\" - {2}.", vKClient.Account.Name, albumInfo.Name, ex.Message);
							}
						}
						catch (WebException ex2)
						{
							LogWriteError("Альбомы-загрузка({0})> \"{1}\" - {2}.", vKClient.Account.Name, albumInfo.Name, ex2.Message);
						}
						catch (CaptchaCanceledException)
						{
							LogWriteError("Альбомы-загрузка({0})> \"{1}\" - Игнорирована капча.", vKClient.Account.Name, albumInfo.Name);
						}
						catch (CaptchaIgnoredException)
						{
						}
					}
				}
				else
				{
					Thread.Sleep(1000);
				}
				num4 = (num4 + 1) % list.Count;
			}
			if (trndAlbums.Checked && trndAlbumsExist.Checked)
			{
				LogWriteInfo("Альбомы-загрузка> Попячивание остановлено");
			}
		}

		private void AudioUpload()
		{
			int num = aimId;
			if (num > 0)
			{
				return;
			}
			int num2 = Configurations.Audio.AudioFiles.Length;
			if (num2 == 0)
			{
				return;
			}
			GsomFormats gsomFormats = GsomFormats.Default;
			if (Configurations.General.RandomCase)
			{
				gsomFormats |= GsomFormats.RandomCase;
			}
			int num3 = Configurations.Audio.TimeDelay;
			List<VKClient> list = new List<VKClient>(Clients);
			Queue<ExcudedVKClient> queue = new Queue<ExcudedVKClient>();
			bool flag = false;
			do
			{
				flag = false;
				VKClient vKClient = null;
				try
				{
					int num4 = 0;
					while (!stopAllThreads)
					{
						if (trndAudio.Checked)
						{
							if (list.Count > 0)
							{
								vKClient = list[num4];
								num4 = (num4 + 1) % list.Count;
								try
								{
									if (trndAudioLuch.Checked)
									{
										vKClient.UploadAudio(num, Files.GetFile(Configurations.Audio.AudioFiles[rnd.Next(0, num2)]), save: true, ggen.Generate(Configurations.Audio.PerformerLength, gsomFormats), ggen.Generate(Configurations.Audio.TitleLength, gsomFormats));
									}
									else
									{
										vKClient.UploadAudio(num, Files.GetFile(Configurations.Audio.AudioFiles[rnd.Next(0, num2)]), save: true);
									}
									audiosCount++;
								}
								catch (CaptchaIgnoredException)
								{
								}
								Thread.Sleep(num3 / list.Count);
							}
							else
							{
								Thread.Sleep(1000);
							}
							while (queue.Count > 0 && (DateTime.Now - queue.Peek().ExcludeTime).TotalSeconds >= (double)ExcludePauseInterval)
							{
								VKClient @base = queue.Dequeue().Base;
								list.Add(@base);
								LogWrite("Аудио> Аккаунт {0} восстановлен.", @base.Account.Name);
							}
						}
						else
						{
							Thread.Sleep(1000);
						}
					}
				}
				catch (BlankErrorException ex2)
				{
					LogWriteError("Аудио({0})> {1}", vKClient.Account.Name, ex2.Message);
					switch (ex2.Code)
					{
					case 0:
					{
						if (Configurations.General.AutoDelays)
						{
							num3 += 200;
							LogWrite("Аудио> Времменая задержка повышена на 200мс и составляет {0}мс.", num3);
						}
						LogWrite("Аудио> Попячивание временно приостановлено.");
						DateTime now = DateTime.Now;
						while ((DateTime.Now - now).TotalSeconds < 15.0)
						{
							if (stopAllThreads)
							{
								return;
							}
							Thread.Sleep(1000);
						}
						LogWrite("Аудио> Попячивание возобновлено.");
						break;
					}
					case 9:
					case 1805:
					case 1807:
						list.Remove(vKClient);
						LogWrite("Аудио> Аккаунт {0} исключен.", vKClient.Account.Name);
						break;
					default:
						list.Remove(vKClient);
						queue.Enqueue(new ExcudedVKClient(vKClient));
						LogWrite("Аудио> Аккаунт {0} временно исключен.", vKClient.Account.Name);
						break;
					}
					flag = true;
				}
				catch (CaptchaCanceledException ex3)
				{
					LogWriteError("Аудио({0})> Капча отменена.", vKClient.Account.Name, ex3.Message);
					list.Remove(vKClient);
					queue.Enqueue(new ExcudedVKClient(vKClient));
					LogWrite("Аудио> Аккаунт {0} временно исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (AuthorizationFailedException)
				{
					LogWriteError("Аудио({0})> Ошибка авторизации.", vKClient.Account.Name);
					list.Remove(vKClient);
					LogWrite("Аудио> Аккаунт {0} исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (WebException ex5)
				{
					LogWriteError("Аудио({0})> {1}", vKClient.Account.Name, ex5.Message);
					flag = true;
				}
				if (list.Count == 0 && queue.Count == 0)
				{
					LogWriteError("Аудио> Все аккаунты исключены, попячивание остановлено.");
					return;
				}
				if (flag)
				{
					Thread.Sleep(num3);
				}
			}
			while (flag);
			if (trndAudio.Checked)
			{
				LogWriteInfo("Аудио> Попячивание остановлено.");
			}
		}

		private void VideosAdd()
		{
			int num = aimId;
			if (num > 0)
			{
				return;
			}
			int num2 = Configurations.Video.Videos.Length;
			if (num2 == 0)
			{
				return;
			}
			int num3 = Configurations.Video.AddTimeDelay;
			List<VKClient> list = new List<VKClient>(Clients);
			Queue<ExcudedVKClient> queue = new Queue<ExcudedVKClient>();
			int num4 = -1;
			VKClient vKClient = null;
			bool flag = false;
			do
			{
				flag = false;
				try
				{
					while (!stopAllThreads)
					{
						if (trndVideo.Checked && trndVideoNew.Checked)
						{
							if (list.Count > 0)
							{
								num4 = (num4 + 1) % list.Count;
								vKClient = list[num4];
								try
								{
									vKClient.AddVideo(num, Configurations.Video.Videos[rnd.Next(0, num2)], Configurations.Video.UseAjax);
									videosCount++;
								}
								catch (CaptchaIgnoredException)
								{
								}
								Thread.Sleep(num3 / list.Count);
							}
							else
							{
								Thread.Sleep(1000);
							}
							while (queue.Count > 0 && (DateTime.Now - queue.Peek().ExcludeTime).TotalSeconds >= (double)ExcludePauseInterval)
							{
								VKClient @base = queue.Dequeue().Base;
								list.Add(@base);
								LogWrite("Видео-добавление> Аккаунт {0} восстановлен.", @base.Account.Name);
							}
						}
						else
						{
							Thread.Sleep(1000);
						}
					}
				}
				catch (BlankErrorException ex2)
				{
					LogWriteError("Видео-добавление({0})> {1}", vKClient.Account.Name, ex2.Message);
					switch (ex2.Code)
					{
					case 0:
						if (Configurations.General.AutoDelays)
						{
							num3 += 200;
							LogWrite("Видео-добавление> Времменая задержка повышена на 200мс и составляет {0}мс.", num3);
						}
						break;
					case 9:
					case 1602:
						list.Remove(vKClient);
						LogWrite("Видео-добавление> Аккаунт {0} исключен.", vKClient.Account.Name);
						break;
					default:
						list.Remove(vKClient);
						queue.Enqueue(new ExcudedVKClient(vKClient));
						LogWrite("Видео-добавление> Аккаунт {0} временно исключен.", vKClient.Account.Name);
						break;
					}
					flag = true;
				}
				catch (CaptchaCanceledException ex3)
				{
					LogWriteError("Видео-добавление({0})> Капча отменена.", vKClient.Account.Name, ex3.Message);
					list.Remove(vKClient);
					queue.Enqueue(new ExcudedVKClient(vKClient));
					LogWrite("Видео-добавление> Аккаунт {0} временно исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (AuthorizationFailedException)
				{
					LogWriteError("Видео-добавление({0})> Ошибка авторизации.", vKClient.Account.Name);
					list.Remove(vKClient);
					LogWrite("Видео-добавление> Аккаунт {0} исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (WebException ex5)
				{
					LogWriteError("Видео-добавление({0})> {1}", vKClient.Account.Name, ex5.Message);
					flag = true;
				}
				if (list.Count == 0 && queue.Count == 0)
				{
					LogWriteError("Видео-добавление> Все аккаунты исключены, попячивание остановлено.");
					return;
				}
				if (flag)
				{
					Thread.Sleep(num3);
				}
			}
			while (flag);
			if (trndVideo.Checked && trndVideoNew.Checked)
			{
				LogWriteInfo("Видео-добавление> Попячивание остановлено.");
			}
		}

		private void CommentVideos()
		{
			int num = aimId;
			if (num > 0 || Videos == null || Videos.Length == 0)
			{
				return;
			}
			GsomFormats gsomFormats = GsomFormats.Default;
			if (Configurations.General.AddExtraLines)
			{
				gsomFormats |= GsomFormats.InsertExtraLines;
			}
			if (Configurations.General.AddAsciiImages)
			{
				gsomFormats |= GsomFormats.UseMultiLineMessages;
			}
			if (Configurations.General.RandomCase)
			{
				gsomFormats |= GsomFormats.RandomCase;
			}
			int num2 = Configurations.Video.CommentTimeDelay;
			List<VKClient> list = new List<VKClient>(Clients);
			Queue<ExcudedVKClient> queue = new Queue<ExcudedVKClient>();
			int num3 = 0;
			if (Configurations.Video.RandomCommentStart)
			{
				num3 = rnd.Next(0, Videos.Length);
			}
			int num4 = -1;
			VKClient vKClient = null;
			bool flag = false;
			do
			{
				flag = false;
				try
				{
					while (!stopAllThreads)
					{
						if (trndVideo.Checked && trndVideoExist.Checked)
						{
							if (list.Count > 0)
							{
								num4 = (num4 + 1) % list.Count;
								vKClient = list[num4];
								try
								{
									if (vKClient.PostVideoComment(Videos[num3], ggen.Generate(Configurations.Topics.AnswerLength, gsomFormats)))
									{
										videosCommentsCount++;
									}
								}
								catch (CaptchaIgnoredException)
								{
								}
								if (videosCommentsCount % 20 == 0)
								{
									num3 = (num3 + 1) % Videos.Length;
								}
								Thread.Sleep(num2 / list.Count);
							}
							else
							{
								Thread.Sleep(1000);
							}
							while (queue.Count > 0 && (DateTime.Now - queue.Peek().ExcludeTime).TotalSeconds >= (double)ExcludePauseInterval)
							{
								VKClient @base = queue.Dequeue().Base;
								list.Add(@base);
								LogWrite("Видео-комментарии> Аккаунт {0} восстановлен.", @base.Account.Name);
							}
						}
						else
						{
							Thread.Sleep(1000);
						}
					}
				}
				catch (BlankErrorException ex2)
				{
					LogWriteError("Видео-комментарии({0})> {1}", vKClient.Account.Name, ex2.Message);
					switch (ex2.Code)
					{
					case 0:
						if (Configurations.General.AutoDelays)
						{
							num2 += 200;
							LogWrite("Видео-комментарии> Времменая задержка повышена на 200мс и составляет {0}мс.", num2);
						}
						else
						{
							Thread.Sleep(1000);
						}
						break;
					case 9:
						list.Remove(vKClient);
						LogWrite("Видео-комментарии> Аккаунт {0} исключен.", vKClient.Account.Name);
						break;
					default:
						list.Remove(vKClient);
						queue.Enqueue(new ExcudedVKClient(vKClient));
						LogWrite("Видео-комментарии> Аккаунт {0} временно исключен.", vKClient.Account.Name);
						break;
					}
					flag = true;
				}
				catch (CaptchaCanceledException ex3)
				{
					LogWriteError("Видео-комментарии({0})> Капча отменена.", vKClient.Account.Name, ex3.Message);
					list.Remove(vKClient);
					queue.Enqueue(new ExcudedVKClient(vKClient));
					LogWrite("Видео-комментарии> Аккаунт {0} временно исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (AuthorizationFailedException)
				{
					LogWriteError("Видео-комментарии({0})> Ошибка авторизации.", vKClient.Account.Name);
					list.Remove(vKClient);
					LogWrite("Видео-комментарии> Аккаунт {0} исключен.", vKClient.Account.Name);
					flag = true;
				}
				catch (WebException ex5)
				{
					HttpWebResponse httpWebResponse = ex5.Response as HttpWebResponse;
					LogWriteError("Видео-комментарии({0})> {1}", vKClient.Account.Name, ex5.Message);
					if (ex5.Status == WebExceptionStatus.ProtocolError && httpWebResponse.StatusCode == HttpStatusCode.BadRequest && Configurations.General.AutoDelays)
					{
						num2 += 200;
						LogWrite("Видео-комментарии> Времменая задержка повышена на 200мс и составляет {0}мс.", num2);
					}
					else
					{
						Thread.Sleep(1000);
					}
					flag = true;
				}
				if (list.Count == 0 && queue.Count == 0)
				{
					LogWriteError("Видео-комментарии> Все аккаунты исключены, попячивание остановлено.");
					return;
				}
				if (flag)
				{
					Thread.Sleep(num2);
				}
			}
			while (flag);
			if (trndVideo.Checked && trndVideoExist.Checked)
			{
				LogWriteInfo("Видео-комментарии> Попячивание остановлено.");
			}
		}

		public static string InsertKey(string s, int key)
		{
			int num = rnd.Next(2, 9);
			string text = key.ToString();
			s = s.Replace("\r", "");
			int num2 = 0;
			int num3 = 0;
			while (num2 < text.Length)
			{
				int num4 = text[num2] - 48;
				if (s.Length < num3)
				{
					s = s.PadRight(num3);
				}
				s = s.Insert(num3, char.ConvertFromUtf32(num4 + 97));
				num2++;
				num3 += num;
			}
			s = s.Insert(0, char.ConvertFromUtf32(num + 97));
			s = s.Replace("\n", "\r\n");
			return s;
		}

		public static bool ContainsKey(string s, int key)
		{
			s = s.Replace("\r\n", "\n");
			if (s.Length == 0)
			{
				return false;
			}
			string text = key.ToString();
			int num = s[0] - 97;
			if (2 > num || num > 9)
			{
				return false;
			}
			int num2 = 0;
			int num3 = 1;
			while (num2 < text.Length)
			{
				if (s.Length <= num3)
				{
					return false;
				}
				int num4 = text[num2] - 48;
				int num5 = s[num3] - 97;
				if (num4 != num5)
				{
					return false;
				}
				num2++;
				num3 += num;
			}
			return true;
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			btnStop_Click(null, null);
			base.OnClosing(e);
			GC.Collect();
		}
	}
}
