/clsStatMonger.cs

https://github.com/joshgoodwin/TubeGuardian · C# · 2441 lines · 2093 code · 209 blank · 139 comment · 315 complexity · 63a32ae9f00946f368d52ed21ced7ab7 MD5 · raw file

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Google.GData.YouTube;
  6. using Google.GData.Extensions;
  7. using Google.YouTube;
  8. using System.Threading;
  9. using System.IO;
  10. using System.Xml;
  11. using System.Runtime.InteropServices;
  12. using System.Timers;
  13. using System.Net;
  14. using System.Net.Sockets;
  15. using System.Web;
  16. using mshtml;
  17. using System.Text.RegularExpressions;
  18. namespace TubeGuardian
  19. {
  20. // Hack-a-licious http 1.1 request using tcp sockets
  21. public class GetSocket
  22. {
  23. private static Socket ConnectSocket(string server, int port)
  24. {
  25. Socket s = null;
  26. IPHostEntry hostEntry = null;
  27. // Get host related information.
  28. hostEntry = Dns.GetHostEntry(server);
  29. // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
  30. // an exception that occurs when the host IP Address is not compatible with the address family
  31. // (typical in the IPv6 case).
  32. foreach (IPAddress address in hostEntry.AddressList)
  33. {
  34. IPEndPoint ipe = new IPEndPoint(address, port);
  35. Socket tempSocket =
  36. new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  37. tempSocket.Connect(ipe);
  38. if (tempSocket.Connected)
  39. {
  40. s = tempSocket;
  41. break;
  42. }
  43. else
  44. {
  45. continue;
  46. }
  47. }
  48. return s;
  49. }
  50. // This method requests the home page content for the specified server.
  51. public static string SocketSendReceive(string server, int port, string headers, string data)
  52. {
  53. Byte[] bytesData = Encoding.ASCII.GetBytes(data);
  54. headers = headers + "\nContent-Length: " + bytesData.Length;
  55. string request = headers + "\n\n" + data;
  56. Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
  57. Byte[] bytesReceived = new Byte[256];
  58. // Create a socket connection with the specified server and port.
  59. Socket s = ConnectSocket(server, port);
  60. if (s == null)
  61. return ("Connection failed");
  62. // Send request to the server.
  63. s.Send(bytesSent, bytesSent.Length, 0);
  64. // Receive the server home page content.
  65. int bytes = 0;
  66. string page = "";
  67. bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
  68. page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
  69. return page;
  70. }
  71. }
  72. /* Bot-ish class that contantly maintains an updated dictionary of clsDataPoint objects */
  73. public class clsStatMonger
  74. {
  75. // private data members
  76. private List<clsCredentials> _accounts = new List<clsCredentials>();
  77. private List<clsVideoFeedReader> _feed_readers = new List<clsVideoFeedReader>();
  78. private List<clsVideoEntry> _initial_dataset = new List<clsVideoEntry>();
  79. private List<clsVideoEntry> _current_dataset = new List<clsVideoEntry>();
  80. private Dictionary<string, List<clsDataPoint>> _historical_data = new Dictionary<string, List<clsDataPoint>>();
  81. private System.Timers.Timer _update_timer;
  82. private clsFileLogger _file_logger = null;
  83. private string _dev_key = string.Empty;
  84. private string _app_name = string.Empty;
  85. private clsSettings _settings;
  86. // constructor
  87. public clsStatMonger(string DeveloperKey, string ApplicationName, List<clsCredentials> Credentials, clsSettings settings)
  88. {
  89. _file_logger = new clsFileLogger("CollectorData.log");
  90. _settings = settings;
  91. _settings.OnAccountAdded += new clsSettings.AccountAddedHandler(_settings_OnAccountAdded);
  92. _settings.OnAccountRemoved += new clsSettings.AccountRemovedHandler(_settings_OnAccountRemoved);
  93. _dev_key = DeveloperKey;
  94. _app_name = ApplicationName;
  95. this.Enabled = false;
  96. _update_timer = new System.Timers.Timer();
  97. _update_timer.Enabled = false;
  98. _update_timer.Interval = _settings.Collect_Interval * 1000 * 60;
  99. _update_timer.Elapsed += new ElapsedEventHandler(_update_timer_Elapsed);
  100. _accounts = Credentials;
  101. foreach (clsCredentials c in _accounts)
  102. {
  103. clsVideoFeedReader new_feed = new clsVideoFeedReader(DeveloperKey, ApplicationName, c.Username);
  104. if (c.Password != string.Empty && c.Password != "-")
  105. new_feed.SetCredentials(c.Username, c.Password);
  106. new_feed.OnEntryFetched += new clsVideoFeedReader.EntryFetchedHandler(new_feed_OnEntryFetched);
  107. new_feed.OnStatusChange += new clsVideoFeedReader.StatusChangeHandler(new_feed_OnStatusChange);
  108. _feed_readers.Add(new_feed);
  109. }
  110. }
  111. public clsStatMonger(string DataFile)
  112. {
  113. LoadDataFile(DataFile);
  114. }
  115. void _settings_OnAccountRemoved(object sender, clsCredentials Account)
  116. {
  117. RemoveAccount(Account);
  118. }
  119. void _settings_OnAccountAdded(object sender, clsCredentials Account)
  120. {
  121. AddAccount(Account);
  122. }
  123. // public methods
  124. public void Enable()
  125. {
  126. if (this.Enabled)
  127. return;
  128. this.Enabled = true;
  129. _update_videos();
  130. _update_timer.Interval = _settings.Collect_Interval;
  131. _update_timer.Enabled = true;
  132. }
  133. public void Disable()
  134. {
  135. this.Enabled = false;
  136. _update_timer.Enabled = false;
  137. }
  138. public void Update()
  139. {
  140. _update_videos();
  141. }
  142. public void AddAccount(clsCredentials Account)
  143. {
  144. foreach (clsVideoFeedReader r in _feed_readers)
  145. if (r.Username == Account.Username)
  146. return;
  147. clsVideoFeedReader new_feed = new clsVideoFeedReader(_dev_key, _app_name, Account.Username);
  148. if (Account.Password != "-")
  149. new_feed.SetCredentials(Account.Username, Account.Password);
  150. new_feed.OnEntryFetched += new clsVideoFeedReader.EntryFetchedHandler(new_feed_OnEntryFetched);
  151. new_feed.OnStatusChange += new clsVideoFeedReader.StatusChangeHandler(new_feed_OnStatusChange);
  152. new_feed.OnException += new clsVideoFeedReader.ExceptionHandler(new_feed_OnException);
  153. _feed_readers.Add(new_feed);
  154. }
  155. public void RemoveAccount(clsCredentials Account)
  156. {
  157. int i = 0;
  158. while (i < _feed_readers.Count)
  159. {
  160. if (_feed_readers[i].Username == Account.Username)
  161. {
  162. _feed_readers[i].Dispose();
  163. _feed_readers.RemoveAt(i);
  164. }
  165. else
  166. i++;
  167. }
  168. }
  169. public void AddDataset(List<clsVideoEntry> InitialDataset, Dictionary<string, List<clsDataPoint>> HistoricalData)
  170. {
  171. List<clsDataPoint> new_datapoints = new List<clsDataPoint>();
  172. int i = 0;
  173. while (i<InitialDataset.Count)
  174. {
  175. clsVideoEntry new_entry = InitialDataset[i];
  176. i++;
  177. if (new_entry == null)
  178. continue;
  179. clsVideoEntry old_entry = _GetEntryByIdFromList(_initial_dataset, new_entry.VideoID);
  180. if (old_entry == null)
  181. {
  182. _initial_dataset.Add(new_entry);
  183. try { _historical_data.Add(new_entry.VideoID, new List<clsDataPoint>()); }
  184. catch { }
  185. continue;
  186. }
  187. List<clsDataPoint> new_dps = _compare_entities(new_entry, old_entry);
  188. if (new_entry.Time < old_entry.Time)
  189. old_entry = new_entry;
  190. foreach (clsDataPoint dp in new_dps)
  191. _historical_data[new_entry.VideoID].Add(new clsDataPoint(dp));
  192. }
  193. foreach (KeyValuePair<string, List<clsDataPoint>> kvp in HistoricalDataPoints)
  194. {
  195. if (!_historical_data.ContainsKey(kvp.Key))
  196. {
  197. _historical_data.Add(kvp.Key, new List<clsDataPoint>(kvp.Value));
  198. continue;
  199. }
  200. _historical_data[kvp.Key].AddRange(new List<clsDataPoint>(kvp.Value));
  201. }
  202. _sort_historical_data();
  203. }
  204. public void LoadDataFile(string LogFileContents)
  205. {
  206. List<clsVideoEntry> init = new List<clsVideoEntry>();
  207. Dictionary<string, List<clsDataPoint>> hist = new Dictionary<string, List<clsDataPoint>>();
  208. string log = LogFileContents;
  209. Regex r = new Regex("init : .+?{(.+?)}.+?{(.+?)}.+?{(.+?)}.+?{(.+?)}.+?{(.+?)}.+?{(.+?)}.+?{(.+?)}.+?{(.+?)}.+?{(.+?)}");
  210. MatchCollection matches = r.Matches(log);
  211. foreach (Match m in matches)
  212. {
  213. Google.GData.YouTube.YouTubeEntry entry = new Google.GData.YouTube.YouTubeEntry();
  214. entry.VideoId = m.Groups[3].Value;
  215. Google.GData.Extensions.FeedLink feedlink = new Google.GData.Extensions.FeedLink();
  216. feedlink.CountHint = int.Parse(m.Groups[8].Value);
  217. entry.Comments = new Google.GData.Extensions.Comments();
  218. entry.Comments.FeedLink = feedlink;
  219. entry.Statistics = new Google.GData.YouTube.Statistics();
  220. entry.Statistics.ViewCount = m.Groups[7].Value;
  221. entry.Statistics.FavoriteCount = m.Groups[9].Value;
  222. entry.Rating = new Google.GData.Extensions.Rating();
  223. entry.Rating.NumRaters = int.Parse(m.Groups[5].Value);
  224. entry.Rating.Average = double.Parse(m.Groups[6].Value);
  225. entry.Title = new Google.GData.Client.AtomTextConstruct(Google.GData.Client.AtomTextConstructElementType.Title, m.Groups[4].Value);
  226. clsVideoEntry new_e = new clsVideoEntry(entry);
  227. new_e.Time = DateTime.Parse(m.Groups[1].Value + " " + m.Groups[2].Value);
  228. clsVideoEntry old_entry = _GetEntryByIdFromList(init, new_e.VideoID);
  229. if ( old_entry == null)
  230. init.Add(new_e);
  231. else
  232. {
  233. List<clsDataPoint> new_dps = _compare_entities(new_e, old_entry);
  234. if (new_e.Time < old_entry.Time)
  235. old_entry = new_e;
  236. foreach (clsDataPoint dp in new_dps)
  237. {
  238. if (!hist.ContainsKey(new_e.VideoID))
  239. hist.Add(new_e.VideoID, new List<clsDataPoint>());
  240. hist[new_e.VideoID].Add(dp);
  241. }
  242. }
  243. }
  244. r = new Regex("upd : d{(.*)},t{(.*)},vId{(.*),(.*)},old{(.*)},new{(.*)}");
  245. matches = r.Matches(log);
  246. foreach (Match m in matches)
  247. {
  248. string v = m.Groups[3].Value;
  249. string f = m.Groups[4].Value;
  250. double Iv = double.Parse(m.Groups[5].Value);
  251. double Nv = double.Parse(m.Groups[6].Value);
  252. if (!hist.ContainsKey(v))
  253. hist.Add(v, new List<clsDataPoint>());
  254. clsDataPointField field = new clsDataPointField();
  255. switch (f)
  256. {
  257. case "VIEWS":
  258. field.Field = clsDataPointField.VideoDataFields.VIEWS;
  259. break;
  260. case "RATERS":
  261. field.Field = clsDataPointField.VideoDataFields.RATERS;
  262. break;
  263. case "AVERAGE_RATING":
  264. field.Field = clsDataPointField.VideoDataFields.AVERAGE_RATING;
  265. break;
  266. case "COMMENT_COUNT":
  267. field.Field = clsDataPointField.VideoDataFields.COMMENT_COUNT;
  268. break;
  269. case "FAVORITED_COUNT":
  270. field.Field = clsDataPointField.VideoDataFields.FAVORITED_COUNT;
  271. break;
  272. }
  273. clsDataPoint new_dp = new clsDataPoint(Iv, Nv, field, v);
  274. new_dp.Time = DateTime.Parse(m.Groups[1].Value + " " + m.Groups[2].Value);
  275. hist[v].Add(new_dp);
  276. }
  277. _initial_dataset = init;
  278. _historical_data = hist;
  279. _sort_historical_data();
  280. }
  281. private void _sort_historical_data()
  282. {
  283. int i = 0;
  284. while (i < _historical_data.Count)
  285. {
  286. List<clsDataPoint> current_dps = _historical_data.ElementAt(i).Value;
  287. i++;
  288. current_dps.Sort(delegate(clsDataPoint d1, clsDataPoint d2)
  289. { return d1.Time.CompareTo(d2.Time); }
  290. );
  291. //current_dps = _remove_duplicates(current_dps);
  292. }
  293. }
  294. private static List<clsDataPoint> _remove_duplicates(List<clsDataPoint> input)
  295. {
  296. List<clsDataPoint> unique = new List<clsDataPoint>();
  297. foreach (clsDataPoint dp in input)
  298. if (unique.FindIndex(delegate(clsDataPoint d) { return ((dp.VideoID.Equals(d.VideoID)) && (dp.Time.Ticks.Equals(d.Time.Ticks)) && (dp.Field.Field.Equals(d.Field.Field)) && (dp.New.Equals(d.New)) && (dp.Old.Equals(d.Old))); }) == -1)
  299. unique.Add(dp);
  300. return unique;
  301. }
  302. private static List<clsDataPoint> _compare_entities(clsVideoEntry e_adding, clsVideoEntry e_init)
  303. {
  304. clsDataPoint new_dp = null;
  305. List<clsDataPoint> ret = new List<clsDataPoint>();
  306. if (e_adding.Time < e_init.Time)
  307. {
  308. if (e_adding.ViewsCount != e_adding.ViewsCount)
  309. {
  310. new_dp = new clsDataPoint((double)e_adding.ViewsCount, (double)e_init.ViewsCount, new clsDataPointField(clsDataPointField.VideoDataFields.VIEWS), e_init.VideoID);
  311. new_dp.Time = e_init.Time;
  312. ret.Add(new_dp);
  313. }
  314. if (e_adding.ViewsCount != e_adding.ViewsCount)
  315. {
  316. new_dp = new clsDataPoint((double)e_adding.Raters, (double)e_init.Raters, new clsDataPointField(clsDataPointField.VideoDataFields.RATERS), e_init.VideoID);
  317. new_dp.Time = e_init.Time;
  318. ret.Add(new_dp);
  319. }
  320. if (e_adding.ViewsCount != e_adding.ViewsCount)
  321. {
  322. new_dp = new clsDataPoint((double)e_adding.FavoritedCount, (double)e_init.FavoritedCount, new clsDataPointField(clsDataPointField.VideoDataFields.FAVORITED_COUNT), e_init.VideoID);
  323. new_dp.Time = e_init.Time;
  324. ret.Add(new_dp);
  325. }
  326. if (e_adding.ViewsCount != e_adding.ViewsCount)
  327. {
  328. new_dp = new clsDataPoint((double)e_adding.CommentCount, (double)e_init.CommentCount, new clsDataPointField(clsDataPointField.VideoDataFields.COMMENT_COUNT), e_init.VideoID);
  329. new_dp.Time = e_init.Time;
  330. ret.Add(new_dp);
  331. }
  332. if (e_adding.ViewsCount != e_adding.ViewsCount)
  333. {
  334. new_dp = new clsDataPoint((double)e_adding.AverageRating, (double)e_init.AverageRating, new clsDataPointField(clsDataPointField.VideoDataFields.AVERAGE_RATING), e_init.VideoID);
  335. new_dp.Time = e_init.Time;
  336. ret.Add(new_dp);
  337. }
  338. e_init = e_adding;
  339. }
  340. else
  341. {
  342. if (e_init.ViewsCount != e_init.ViewsCount)
  343. {
  344. new_dp = new clsDataPoint((double)e_init.ViewsCount, (double)e_adding.ViewsCount, new clsDataPointField(clsDataPointField.VideoDataFields.VIEWS), e_adding.VideoID);
  345. new_dp.Time = e_adding.Time;
  346. ret.Add(new_dp);
  347. }
  348. if (e_init.ViewsCount != e_init.ViewsCount)
  349. {
  350. new_dp = new clsDataPoint((double)e_init.Raters, (double)e_adding.Raters, new clsDataPointField(clsDataPointField.VideoDataFields.RATERS), e_adding.VideoID);
  351. new_dp.Time = e_adding.Time;
  352. ret.Add(new_dp);
  353. }
  354. if (e_init.ViewsCount != e_init.ViewsCount)
  355. {
  356. new_dp = new clsDataPoint((double)e_init.FavoritedCount, (double)e_adding.FavoritedCount, new clsDataPointField(clsDataPointField.VideoDataFields.FAVORITED_COUNT), e_adding.VideoID);
  357. new_dp.Time = e_adding.Time;
  358. ret.Add(new_dp);
  359. }
  360. if (e_init.ViewsCount != e_init.ViewsCount)
  361. {
  362. new_dp = new clsDataPoint((double)e_init.CommentCount, (double)e_adding.CommentCount, new clsDataPointField(clsDataPointField.VideoDataFields.COMMENT_COUNT), e_adding.VideoID);
  363. new_dp.Time = e_adding.Time;
  364. ret.Add(new_dp);
  365. }
  366. if (e_init.ViewsCount != e_init.ViewsCount)
  367. {
  368. new_dp = new clsDataPoint((double)e_init.AverageRating, (double)e_adding.AverageRating, new clsDataPointField(clsDataPointField.VideoDataFields.AVERAGE_RATING), e_adding.VideoID);
  369. new_dp.Time = e_adding.Time;
  370. ret.Add(new_dp);
  371. }
  372. }
  373. return ret;
  374. }
  375. private YouTubeEntry _new_youtube_entry(string title, double views, double raters, double favs, double avgR, double comments)
  376. {
  377. YouTubeEntry e = new YouTubeEntry();
  378. e.Rating = new Rating();
  379. e.Comments.FeedLink = new FeedLink();
  380. e.Statistics = new Statistics();
  381. e.Title = new Google.GData.Client.AtomTextConstruct();
  382. e.Statistics.FavoriteCount = favs.ToString();
  383. e.Statistics.ViewCount = views.ToString();
  384. e.Rating.Average = avgR;
  385. e.Rating.NumRaters = (int)raters;
  386. e.Comments.FeedLink.CountHint = (int)comments;
  387. e.Title.Text = title;
  388. return e;
  389. }
  390. // public events
  391. public delegate void EntryAddedEventHandler(object Sender, clsVideoEntry Entry);
  392. public event EntryAddedEventHandler OnEntryAdded;
  393. private void _entry_added(clsVideoEntry Entry)
  394. {
  395. if (_file_logger != null)
  396. _file_logger.appendFile(Entry.ToString());
  397. if (OnEntryAdded != null)
  398. OnEntryAdded(this, Entry);
  399. }
  400. public delegate void EntryUpdatedEventHandler(object Sender, clsDataPoint DataPoint, clsVideoEntry Entry);
  401. public event EntryUpdatedEventHandler OnEntryUpdated;
  402. private void _entry_updated(clsDataPoint DataPoint, clsVideoEntry Entry)
  403. {
  404. if (_file_logger != null)
  405. _file_logger.appendFile(DataPoint.ToString());
  406. if (OnEntryUpdated != null)
  407. OnEntryUpdated(this, DataPoint, Entry);
  408. }
  409. public delegate void FeedReaderUpdatedEventHandler(object Sender, clsVideoFeedReader.enumFeedReaderState status);
  410. public event FeedReaderUpdatedEventHandler OnFeedReaderUpdated;
  411. private void _feed_reader_updated(object sender, clsVideoFeedReader.enumFeedReaderState status)
  412. {
  413. if (OnFeedReaderUpdated != null)
  414. OnFeedReaderUpdated(sender, status);
  415. }
  416. public delegate void FeedReaderExceptionEventHandler(object Sender, string exception);
  417. public event FeedReaderExceptionEventHandler OnFeedReaderException;
  418. private void _feed_reader_exception(object sender, string exception)
  419. {
  420. if (OnFeedReaderException != null)
  421. OnFeedReaderException(sender, exception);
  422. }
  423. // private methods
  424. private void _update_timer_Elapsed(object sender, ElapsedEventArgs e)
  425. {
  426. if (this.Enabled == false)
  427. return;
  428. _update_timer.Enabled = false;
  429. _update_timer.Interval = _settings.Collect_Interval * 1000 * 60;
  430. _update_timer.Enabled = true;
  431. _update_videos();
  432. }
  433. private void new_feed_OnStatusChange(object Sender, clsVideoFeedReader.enumFeedReaderState NewState)
  434. {
  435. _feed_reader_updated(Sender, NewState);
  436. }
  437. private void new_feed_OnEntryFetched(object Sender, clsVideoEntry Entry)
  438. {
  439. clsVideoEntry initial_entry;
  440. if ((initial_entry = _GetEntryByIdFromList(_initial_dataset, Entry.VideoID)) == null)
  441. {
  442. _initial_dataset.Add(Entry);
  443. _current_dataset.Add(Entry);
  444. _entry_added(Entry);
  445. }
  446. else
  447. {
  448. clsVideoEntry CurrentEntry = _GetEntryByIdFromList(_current_dataset, Entry.VideoID);
  449. if (CurrentEntry == null)
  450. {
  451. _current_dataset.Add(Entry);
  452. _compare_entries(initial_entry, Entry);
  453. }
  454. else
  455. {
  456. _current_dataset.Remove(CurrentEntry);
  457. _current_dataset.Add(Entry);
  458. _compare_entries(CurrentEntry, Entry);
  459. }
  460. }
  461. }
  462. private void new_feed_OnException(object Sender, Exception e)
  463. {
  464. _feed_reader_exception(Sender, e.Message);
  465. }
  466. private void _compare_entries(clsVideoEntry OldEntry, clsVideoEntry NewEntry)
  467. {
  468. if (OldEntry.VideoID != NewEntry.VideoID)
  469. return;
  470. _compare_stat(OldEntry.AverageRating, NewEntry.AverageRating, clsDataPointField.VideoDataFields.AVERAGE_RATING, NewEntry);
  471. _compare_stat(OldEntry.CommentCount, NewEntry.CommentCount, clsDataPointField.VideoDataFields.COMMENT_COUNT, NewEntry);
  472. _compare_stat(OldEntry.FavoritedCount, NewEntry.FavoritedCount, clsDataPointField.VideoDataFields.FAVORITED_COUNT, NewEntry);
  473. _compare_stat(OldEntry.Raters, NewEntry.Raters, clsDataPointField.VideoDataFields.RATERS, NewEntry);
  474. _compare_stat(OldEntry.ViewsCount, NewEntry.ViewsCount, clsDataPointField.VideoDataFields.VIEWS, NewEntry);
  475. }
  476. private void _compare_stat(double Old, double New, clsDataPointField.VideoDataFields Field, clsVideoEntry Entry)
  477. {
  478. if (Old == New)
  479. return;
  480. else
  481. {
  482. clsDataPoint new_datapoint = new clsDataPoint(Old, New, new clsDataPointField(Field), Entry.VideoID);
  483. if (_historical_data.ContainsKey(Entry.VideoID))
  484. _historical_data[Entry.VideoID].Add(new_datapoint);
  485. else
  486. {
  487. List<clsDataPoint> new_dp_list = new List<clsDataPoint>();
  488. new_dp_list.Add(new_datapoint);
  489. _historical_data.Add(Entry.VideoID, new_dp_list);
  490. }
  491. _entry_updated(new_datapoint, Entry);
  492. }
  493. }
  494. private clsVideoEntry _GetEntryByIdFromList(List<clsVideoEntry> Entries, string VideoID)
  495. {
  496. int index = Entries.FindIndex(delegate(clsVideoEntry e) { return e.VideoID.Equals(VideoID); });
  497. return (index == -1) ? null : Entries[index];
  498. }
  499. private void _update_videos()
  500. {
  501. foreach (clsVideoFeedReader r in _feed_readers)
  502. if (!r.IsBusy)
  503. r.GetVideosModifiedSince(r.Updated);
  504. }
  505. // public properties
  506. public bool Enabled { get; private set; }
  507. public List<clsVideoEntry> CurrentDataSet
  508. {
  509. get { return new List<clsVideoEntry>(_current_dataset); }
  510. }
  511. public List<clsVideoEntry> InitialDataSet
  512. {
  513. get { return _initial_dataset; }
  514. }
  515. public Dictionary<string, List<clsDataPoint>> HistoricalDataPoints
  516. {
  517. get { return _historical_data; }
  518. }
  519. public clsFileLogger FileLogger
  520. {
  521. get { return _file_logger; }
  522. set { _file_logger = value; }
  523. }
  524. public List<clsVideoEntry> GetVideosByUsername(string username)
  525. {
  526. List<clsVideoEntry> ret = new List<clsVideoEntry>();
  527. foreach (clsVideoEntry e in _current_dataset)
  528. if (e.Account.Username == username)
  529. ret.Add(e);
  530. return ret;
  531. }
  532. public List<clsVideoFeedReader> FeedReaders { get { return _feed_readers; } }
  533. }
  534. /* Type-ish class to hold youtube usernames, and passwords */
  535. public class clsCredentials
  536. {
  537. public clsCredentials(string Username, string Password) { this.Username = Username; this.Password = Password; }
  538. public clsCredentials() { }
  539. public string Username
  540. {
  541. get;
  542. set;
  543. }
  544. public string Password
  545. {
  546. get;
  547. set;
  548. }
  549. }
  550. /* Type-ish class to hold data points (old/new value + data field) */
  551. public class clsDataPoint
  552. {
  553. public clsDataPoint()
  554. {
  555. this.Old = this.New = 0;
  556. this.Field = new clsDataPointField();
  557. this.Time = DateTime.Now;
  558. }
  559. public clsDataPoint(double OldValue, double NewValue, clsDataPointField DataField, string VideoID)
  560. {
  561. this.Old = OldValue;
  562. this.New = NewValue;
  563. this.Field = DataField;
  564. this.Time = DateTime.Now;
  565. this.VideoID = VideoID;
  566. }
  567. public clsDataPoint(clsDataPoint dp)
  568. {
  569. this.Old = dp.Old;
  570. this.New = dp.New;
  571. this.Field = dp.Field;
  572. this.Time = dp.Time;
  573. this.VideoID = dp.VideoID;
  574. }
  575. public override string ToString()
  576. {
  577. string[] values = {"upd : d{" + Time.ToShortDateString() + "}", "t{" + Time.ToShortTimeString() + "}", "vId{" + VideoID, Field.Field.ToString() + "}", "old{" + Old.ToString() + "}", "new{" + New.ToString() + "}" };
  578. return string.Join(",", values);
  579. }
  580. public clsDataPointField Field { get; set; }
  581. public double Old { get; set; }
  582. public double New { get; set; }
  583. public double Delta { get { return New - Old; } }
  584. public DateTime Time { get; set; }
  585. public string VideoID { get; set; }
  586. }
  587. /* Type-ish class to hold data field values and convert to string equivalents */
  588. public class clsDataPointField
  589. {
  590. public enum VideoDataFields
  591. {
  592. UNKNOWN = -1,
  593. VIEWS,
  594. RATERS,
  595. AVERAGE_RATING,
  596. COMMENT_COUNT,
  597. FAVORITED_COUNT
  598. }
  599. public clsDataPointField() { this.Field = VideoDataFields.UNKNOWN; }
  600. public clsDataPointField(VideoDataFields f) { this.Field = f; }
  601. public VideoDataFields Field { get; set; }
  602. public override string ToString()
  603. {
  604. switch (this.Field)
  605. {
  606. case VideoDataFields.AVERAGE_RATING:
  607. return "Average Rating";
  608. case VideoDataFields.COMMENT_COUNT:
  609. return "Comment Count";
  610. case VideoDataFields.FAVORITED_COUNT:
  611. return "Favorited Count";
  612. case VideoDataFields.RATERS:
  613. return "Raters";
  614. case VideoDataFields.UNKNOWN:
  615. return "Unknown";
  616. case VideoDataFields.VIEWS:
  617. return "Views";
  618. default:
  619. return "Error";
  620. }
  621. }
  622. }
  623. /* Wrapper class to access the information needed from YouTubeEntry objects */
  624. public class clsVideoEntry
  625. {
  626. private YouTubeEntry _yt_entry = null;
  627. // constructor
  628. public clsVideoEntry(YouTubeEntry e)
  629. {
  630. _yt_entry = e;
  631. }
  632. public override string ToString()
  633. {
  634. string[] values = { "init : t{" + Time.ToShortDateString() + "}", "d{" + Time.ToShortTimeString() + "}","vIf{" + VideoID + "}","ti{" + Title + "}", "r#{" + Raters.ToString() +"}", "ar{" + AverageRating.ToString() + "}", "v#{" + ViewsCount.ToString() + "}", "c#{" + CommentCount.ToString() + "}", "f#{" + FavoritedCount.ToString() + "}" };
  635. return string.Join(",", values);
  636. }
  637. public override bool Equals(object obj)
  638. {
  639. clsVideoEntry e = (clsVideoEntry)obj;
  640. return this.VideoID.Equals(e.VideoID);
  641. }
  642. public override int GetHashCode()
  643. {
  644. return this.Account.Username.GetHashCode();
  645. }
  646. // public properties
  647. public bool IsNull
  648. {
  649. get { return (_yt_entry == null); }
  650. }
  651. public int Raters
  652. {
  653. get { try { return _yt_entry.Rating.NumRaters; } catch { return 0; } }
  654. }
  655. public double AverageRating
  656. {
  657. get { try { return _yt_entry.Rating.Average; } catch { return 0; } }
  658. }
  659. public int ViewsCount
  660. {
  661. get { try { return int.Parse(_yt_entry.Statistics.ViewCount); } catch { return 0; } }
  662. }
  663. public int CommentCount
  664. {
  665. get { try { return _yt_entry.Comments.FeedLink.CountHint; } catch { return 0; } }
  666. }
  667. public int FavoritedCount
  668. {
  669. get { try { return int.Parse(_yt_entry.Statistics.FavoriteCount); } catch { return 0; } }
  670. }
  671. public string VideoID
  672. {
  673. get { try { return _yt_entry.VideoId; } catch { return string.Empty; } }
  674. }
  675. public string Title
  676. {
  677. get { try { return _yt_entry.Title.Text; } catch { return string.Empty; } }
  678. }
  679. public YouTubeEntry YouTubeEntry
  680. {
  681. get { return _yt_entry; }
  682. }
  683. public DateTime Time { get; set; }
  684. public clsCredentials Account { get; set; }
  685. }
  686. /* Utility class for reading video feeds asynchronously for a single account */
  687. public class clsVideoFeedReader
  688. {
  689. private class QueryArgs
  690. {
  691. public YouTubeService Service { get; set; }
  692. public YouTubeQuery Query { get; set; }
  693. }
  694. private class QueryReturn
  695. {
  696. public YouTubeFeed Feed { get; set; }
  697. public Exception Exception { get; set; }
  698. public YouTubeQuery NextQuery { get; set; }
  699. }
  700. public enum enumFeedReaderState
  701. {
  702. ERROR = -1,
  703. IDLE,
  704. GETTING_FIRST_CHUNK,
  705. GOT_FIRST_CHUNK,
  706. GETTING_ANOTHER_CHUNK,
  707. GOT_ANOTHER_CHUUNK
  708. }
  709. private enumFeedReaderState _state = enumFeedReaderState.IDLE;
  710. private YouTubeService _yt_service = null;
  711. private string _username = string.Empty;
  712. private string _password = string.Empty;
  713. private string _dev_key = string.Empty;
  714. private string _app_name = string.Empty;
  715. private int _retrieved = 0;
  716. private int _max_retry_query = 3;
  717. private int _current_retry_query = 1;
  718. private System.ComponentModel.BackgroundWorker _query_thread = new System.ComponentModel.BackgroundWorker();
  719. private DateTime _last_updated = DateTime.MinValue;
  720. public clsVideoFeedReader(string DevelopersKey, string ApplicationName, string Username)
  721. {
  722. _dev_key = DevelopersKey;
  723. _app_name = ApplicationName;
  724. _username = Username;
  725. _yt_service = new YouTubeService(ApplicationName, string.Empty, DevelopersKey);
  726. _query_thread.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_query_thread_RunWorkerCompleted);
  727. _query_thread.DoWork += new System.ComponentModel.DoWorkEventHandler(_query_thread_DoWork);
  728. }
  729. public clsVideoFeedReader(string DevelopersKey, string ApplicationName, string Username, string Password)
  730. : this(DevelopersKey, ApplicationName, Username)
  731. {
  732. if (_password != "-")
  733. {
  734. _password = Password;
  735. SetCredentials(Username, Password);
  736. }
  737. }
  738. // public methods
  739. public void SetCredentials(string Username, string Password)
  740. {
  741. _username = Username;
  742. _password = Password;
  743. _yt_service.setUserCredentials(Username, Password);
  744. }
  745. public void GetVideos()
  746. {
  747. YouTubeQuery query = new YouTubeQuery(YouTubeQuery.CreateUserUri(_username));
  748. query.NumberToRetrieve = 50;
  749. _retrieved = 0;
  750. _current_retry_query = 1;
  751. _status_changed(enumFeedReaderState.GETTING_FIRST_CHUNK);
  752. _last_updated = DateTime.Now;
  753. _do_query(query);
  754. }
  755. public void GetVideosModifiedSince(DateTime When)
  756. {
  757. YouTubeQuery query = new YouTubeQuery(YouTubeQuery.CreateUserUri(_username));
  758. query.NumberToRetrieve = 50;
  759. query.ModifiedSince = When;
  760. _retrieved = 0;
  761. _current_retry_query = 1;
  762. _status_changed(enumFeedReaderState.GETTING_FIRST_CHUNK);
  763. _last_updated = DateTime.Now;
  764. _do_query(query);
  765. }
  766. public void Dispose()
  767. {
  768. _query_thread.Dispose();
  769. OnEntryFetched = null;
  770. OnException = null;
  771. OnProgress = null;
  772. OnQueryRetry = null;
  773. OnStatusChange = null;
  774. }
  775. // private methods
  776. private void _do_query(YouTubeQuery q)
  777. {
  778. if (_query_thread.IsBusy)
  779. return;
  780. QueryArgs qa = new QueryArgs();
  781. qa.Query = q;
  782. qa.Service = _yt_service;
  783. _query_thread.RunWorkerAsync(qa);
  784. }
  785. private void _query_thread_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
  786. {
  787. QueryArgs qa = e.Argument as QueryArgs;
  788. QueryReturn qr = new QueryReturn();
  789. qr.Exception = null;
  790. qr.Feed = null;
  791. try
  792. {
  793. YouTubeFeed feed = qa.Service.Query(qa.Query);
  794. qr.Feed = feed;
  795. }
  796. catch (Exception exception)
  797. {
  798. qr.Exception = exception;
  799. qr.NextQuery = qa.Query;
  800. }
  801. e.Result = qr;
  802. }
  803. private void _query_thread_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
  804. {
  805. QueryReturn qr = e.Result as QueryReturn;
  806. YouTubeFeed feed = qr.Feed;
  807. if (feed != null)
  808. {
  809. _retrieved += feed.Entries.Count;
  810. foreach (YouTubeEntry entry in feed.Entries)
  811. _entry_fetched(entry);
  812. if (_state == enumFeedReaderState.GETTING_FIRST_CHUNK || _state == enumFeedReaderState.GETTING_ANOTHER_CHUNK)
  813. _status_changed(_state + 1);
  814. if (feed.NextChunk != null)
  815. {
  816. _progress(_retrieved, feed.TotalResults);
  817. _status_changed(enumFeedReaderState.GETTING_ANOTHER_CHUNK);
  818. _do_query(new YouTubeQuery(feed.NextChunk));
  819. }
  820. else
  821. {
  822. _progress(1, 1);
  823. _status_changed(enumFeedReaderState.IDLE);
  824. }
  825. }
  826. else
  827. {
  828. _exception(qr.Exception);
  829. if (_current_retry_query < _max_retry_query)
  830. {
  831. _current_retry_query++;
  832. if (qr.NextQuery != null)
  833. {
  834. _status_changed(_state);
  835. _do_query(new YouTubeQuery(qr.NextQuery.Uri.AbsoluteUri));
  836. }
  837. else
  838. {
  839. _progress(1, 1);
  840. _status_changed(enumFeedReaderState.ERROR);
  841. }
  842. }
  843. else
  844. {
  845. _progress(1, 1);
  846. _status_changed(enumFeedReaderState.ERROR);
  847. }
  848. }
  849. }
  850. // public events
  851. public delegate void StatusChangeHandler(object Sender, enumFeedReaderState NewState);
  852. public event StatusChangeHandler OnStatusChange;
  853. private void _status_changed(enumFeedReaderState state)
  854. {
  855. _state = state;
  856. if (OnStatusChange != null)
  857. OnStatusChange(this, state);
  858. }
  859. public delegate void EntryFetchedHandler(object Sender, clsVideoEntry Entry);
  860. public event EntryFetchedHandler OnEntryFetched;
  861. private void _entry_fetched(YouTubeEntry Entry)
  862. {
  863. if (OnEntryFetched != null)
  864. {
  865. clsVideoEntry nEntry = new clsVideoEntry(Entry);
  866. nEntry.Time = DateTime.Now;
  867. nEntry.Account = new clsCredentials(_username, _password);
  868. OnEntryFetched(this, nEntry);
  869. }
  870. }
  871. public delegate void ProgressHandler(object Sender, int Current, int Total);
  872. public event ProgressHandler OnProgress;
  873. private void _progress(int Current, int Total)
  874. {
  875. if (OnProgress != null)
  876. OnProgress(this, Current, Total);
  877. }
  878. public delegate void QueryRetryHandler(object Sender, Exception e);
  879. public event QueryRetryHandler OnQueryRetry;
  880. private void _query_retry(Exception e)
  881. {
  882. if (OnQueryRetry != null)
  883. OnQueryRetry(this, e);
  884. }
  885. public delegate void ExceptionHandler(object Sender, Exception e);
  886. public event ExceptionHandler OnException;
  887. private void _exception(Exception e)
  888. {
  889. if (OnException != null)
  890. OnException(this, e);
  891. }
  892. // public properties
  893. public string StateString
  894. {
  895. get
  896. {
  897. switch (_state)
  898. {
  899. case enumFeedReaderState.ERROR:
  900. return "Error";
  901. case enumFeedReaderState.GETTING_ANOTHER_CHUNK:
  902. return "Getting another chunk";
  903. case enumFeedReaderState.GETTING_FIRST_CHUNK:
  904. return "Getting first chunk";
  905. case enumFeedReaderState.GOT_ANOTHER_CHUUNK:
  906. return "Got another chunk";
  907. case enumFeedReaderState.GOT_FIRST_CHUNK:
  908. return "Got first chunk";
  909. case enumFeedReaderState.IDLE:
  910. return "Idle";
  911. default:
  912. return "Error";
  913. }
  914. }
  915. }
  916. public enumFeedReaderState State
  917. {
  918. get { return _state; }
  919. }
  920. public int MaxRetries
  921. {
  922. get { return _max_retry_query; }
  923. set { _max_retry_query = value; }
  924. }
  925. public bool IsBusy
  926. {
  927. get { return _query_thread.IsBusy; }
  928. }
  929. public DateTime Updated
  930. {
  931. get { return _last_updated; }
  932. }
  933. public string Username
  934. {
  935. get { return _username; }
  936. }
  937. }
  938. /* Math class for crunching all of the numbers in any given data set */
  939. public class clsStatMasher
  940. {
  941. private List<clsVideoEntry> _initial_dataset = null;
  942. private Dictionary<string, List<clsDataPoint>> _historical_data = null;
  943. public clsStatMasher() {}
  944. public clsStatMasher(List<clsVideoEntry> InitialDataSet, Dictionary<string, List<clsDataPoint>> HistoricalData)
  945. {
  946. _initial_dataset = InitialDataSet;
  947. _historical_data = HistoricalData;
  948. }
  949. // public methods
  950. public List<clsDataPoint> GetDataPointsByID(string VideoID)
  951. {
  952. if (_historical_data.ContainsKey(VideoID))
  953. return _historical_data[VideoID];
  954. else
  955. return null;
  956. }
  957. public clsVideoEntry GetInitialDataByID(string VideoID)
  958. {
  959. if (_initial_dataset == null)
  960. return null;
  961. int index = _initial_dataset.FindIndex(delegate(clsVideoEntry e) { return e.VideoID.Equals(VideoID); });
  962. if (index >= 0)
  963. return _initial_dataset[index];
  964. else
  965. return null;
  966. }
  967. public double AverageNewRatingByID(string VideoID)
  968. {
  969. clsVideoEntry InitialData = GetInitialDataByID(VideoID);
  970. List<clsDataPoint> HistoricalData = GetDataPointsByID(VideoID);
  971. if (InitialData == null || HistoricalData == null || HistoricalData.Count == 0)
  972. return 0;
  973. double[] A = { InitialData.AverageRating, -1 };
  974. double[] N = { InitialData.Raters, -1 };
  975. int counted = 0;
  976. for (int i = HistoricalData.Count - 1; i >= 0; i--)
  977. {
  978. if (A[1] != -1 && N[1] != -1)
  979. break;
  980. if (HistoricalData[i].Field.Field == clsDataPointField.VideoDataFields.RATERS)
  981. {
  982. if (N[1] == -1)
  983. N[1] = HistoricalData[i].New;
  984. counted += (int)HistoricalData[i].Delta;
  985. }
  986. if (HistoricalData[i].Field.Field == clsDataPointField.VideoDataFields.AVERAGE_RATING && A[1] == -1)
  987. A[1] = HistoricalData[i].New;
  988. }
  989. if (counted == 0)
  990. return 0;
  991. if (A[1] == -1)
  992. return 0;
  993. return _calc_average_new_rating(A[0], A[1], N[0], N[1]);
  994. }
  995. public KeyValuePair<int,double> AverageNewRatingByID(string VideoID, int numMostRecentVotes)
  996. {
  997. clsVideoEntry InitialData = GetInitialDataByID(VideoID);
  998. List<clsDataPoint> HistoricalData = GetDataPointsByID(VideoID);
  999. if (InitialData == null || HistoricalData == null || HistoricalData.Count == 0)
  1000. return new KeyValuePair<int,double>(0,0);
  1001. double[] A = { 0, -1 };
  1002. double[] N = { 0, -1 };
  1003. int counted = 0;
  1004. for (int i = HistoricalData.Count - 1; i >= 0; i--)
  1005. {
  1006. if ((counted >= numMostRecentVotes) && A[1] != -1 && N[1] != 1)
  1007. break;
  1008. if (HistoricalData[i].Field.Field == clsDataPointField.VideoDataFields.RATERS)
  1009. {
  1010. if( N[1] == -1)
  1011. N[1] = HistoricalData[i].New;
  1012. N[0] = HistoricalData[i].Old;
  1013. counted += (int)HistoricalData[i].Delta;
  1014. }
  1015. if (HistoricalData[i].Field.Field == clsDataPointField.VideoDataFields.AVERAGE_RATING)
  1016. {
  1017. if (A[1] == -1)
  1018. A[1] = HistoricalData[i].New;
  1019. A[0] = HistoricalData[i].Old;
  1020. }
  1021. }
  1022. if (counted == 0)
  1023. return new KeyValuePair<int, double>(0, 0);
  1024. if (A[1] == -1)
  1025. return new KeyValuePair<int, double>(0, 0);
  1026. return new KeyValuePair<int,double>(counted, _calc_average_new_rating(A[0], A[1], N[0], N[1]));
  1027. }
  1028. public void CleanUp()
  1029. {
  1030. _initial_dataset = null;
  1031. _historical_data = null;
  1032. }
  1033. public double GetMovedStatByField(string VideoID, clsDataPointField.VideoDataFields field)
  1034. {
  1035. clsVideoEntry InitialData = GetInitialDataByID(VideoID);
  1036. List<clsDataPoint> HistoricalData = GetDataPointsByID(VideoID);
  1037. if (InitialData == null || HistoricalData == null || HistoricalData.Count == 0)
  1038. return 0;
  1039. double ret = 0;
  1040. int num = 0;
  1041. foreach (clsDataPoint d in HistoricalData)
  1042. {
  1043. if (d.Field.Field == field)
  1044. {
  1045. if (d.Field.Field == clsDataPointField.VideoDataFields.AVERAGE_RATING)
  1046. num++;
  1047. else
  1048. ret += d.Delta;
  1049. }
  1050. }
  1051. if (field == clsDataPointField.VideoDataFields.AVERAGE_RATING)
  1052. return num;
  1053. else
  1054. return ret;
  1055. }
  1056. // private methods
  1057. private double _calc_average_new_rating(double old_average, double new_average, double old_raters, double new_raters)
  1058. {
  1059. System.Diagnostics.Debug.Print((((new_average * new_raters) - (old_average * old_raters)) / (new_raters - old_raters)).ToString());
  1060. return ((new_average * new_raters) - (old_average * old_raters)) / (new_raters - old_raters);
  1061. }
  1062. // public properties
  1063. public List<clsVideoEntry> InitialDataSet
  1064. {
  1065. get { return _initial_dataset; }
  1066. set { _initial_dataset = value; }
  1067. }
  1068. public Dictionary<string, List<clsDataPoint>> HistoricalDataPoints
  1069. {
  1070. get { return _historical_data; }
  1071. set { _historical_data = value; }
  1072. }
  1073. }
  1074. /* Utility class to check video settings */
  1075. public class clsSettingsManager
  1076. {
  1077. [DllImport("urlmon.dll")]
  1078. [PreserveSig]
  1079. [return: MarshalAs(UnmanagedType.Error)]
  1080. static extern int CoInternetSetFeatureEnabled(
  1081. int FeatureEntry,
  1082. [MarshalAs(UnmanagedType.U4)] int dwFlags,
  1083. bool fEnable);
  1084. private const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
  1085. private const int SET_FEATURE_ON_PROCESS = 0x00000002;
  1086. // private enums
  1087. public enum InternalState
  1088. {
  1089. unknown = -1,
  1090. idle,
  1091. login_step_1,
  1092. login_step_2,
  1093. login_step_3,
  1094. login_check,
  1095. get_settings,
  1096. save_settings
  1097. }
  1098. public enum FailureCodes
  1099. {
  1100. FAILURE_LOGGING_IN,
  1101. FAILURE_CHANGING_SETTINGS
  1102. }
  1103. private class Action
  1104. {
  1105. public string VideoID { get; set; }
  1106. public bool Enable { get; set; }
  1107. public Action(string ID, bool act)
  1108. {
  1109. this.VideoID = ID;
  1110. this.Enable = act;
  1111. }
  1112. }
  1113. // private member variable
  1114. private InternalState _state = InternalState.idle;
  1115. private HttpWebRequest _last_request = null;
  1116. private CookieContainer _cookie_jar = null;
  1117. private Cookie _login_info = null;
  1118. private int _request_timeout = 20 * 1000; // 20 seconds default
  1119. private System.ComponentModel.BackgroundWorker _response_fetcher = new System.ComponentModel.BackgroundWorker();
  1120. private System.ComponentModel.BackgroundWorker _post_response_fetcher = new System.ComponentModel.BackgroundWorker();
  1121. private bool _enable = false;
  1122. private string _video_id = string.Empty;
  1123. private System.Timers.Timer _activity_timer = new System.Timers.Timer();
  1124. private List<Action> _action_list = new List<Action>();
  1125. private Action _current_action;
  1126. private int _current_action_fail_count = 0;
  1127. public void Dispose()
  1128. {
  1129. _cookie_jar = null;
  1130. OnException = null;
  1131. OnFailure = null;
  1132. OnStatusChange = null;
  1133. OnSuccess = null;
  1134. _activity_timer.Enabled = false;
  1135. _response_fetcher.Dispose();
  1136. _post_response_fetcher.Dispose();
  1137. _activity_timer.Dispose();
  1138. _action_list.Clear();
  1139. }
  1140. // public events
  1141. public delegate void ExceptionEventHandler(object sender, Exception e);
  1142. public event ExceptionEventHandler OnException;
  1143. private void _raise_exception(Exception e)
  1144. {
  1145. if (OnException != null)
  1146. OnException(this, e);
  1147. }
  1148. public delegate void StatusEventHandler(object sender, InternalState s);
  1149. public event StatusEventHandler OnStatusChange;
  1150. private void _raise_status_change(InternalState s)
  1151. {
  1152. _state = s;
  1153. if (OnStatusChange != null)
  1154. OnStatusChange(this, s);
  1155. if (s == InternalState.idle)
  1156. if (_action_list.Count > 0)
  1157. _do_next_action();
  1158. else
  1159. _activity_timer.Enabled = true;
  1160. }
  1161. public delegate void FailureEventHandler(object sender, FailureCodes f);
  1162. public event FailureEventHandler OnFailure;
  1163. private void _raise_failure(FailureCodes f)
  1164. {
  1165. _current_action_fail_count++;
  1166. if (_current_action_fail_count < 3)
  1167. _action_list.Add(_current_action);
  1168. else
  1169. _current_action_fail_count = 0;
  1170. if (OnFailure != null)
  1171. OnFailure(this, f);
  1172. }
  1173. public delegate void SuccessEventHandler(object sender, FailureCodes f);
  1174. public event SuccessEventHandler OnSuccess;
  1175. private void _raise_success(FailureCodes f)
  1176. {
  1177. _current_action_fail_count = 0;
  1178. if (OnSuccess != null)
  1179. OnSuccess(this, f);
  1180. }
  1181. // contructors
  1182. public clsSettingsManager() : this(string.Empty, string.Empty) { }
  1183. public clsSettingsManager(string Username, string Password)
  1184. {
  1185. int feature = FEATURE_DISABLE_NAVIGATION_SOUNDS;
  1186. CoInternetSetFeatureEnabled(feature, SET_FEATURE_ON_PROCESS, true);
  1187. this.Username = Username;
  1188. this.Password = Password;
  1189. _activity_timer.Interval = 8000;
  1190. _activity_timer.Elapsed += new ElapsedEventHandler(_activity_timer_Elapsed);
  1191. _response_fetcher.DoWork += new System.ComponentModel.DoWorkEventHandler(_worker_thread_get_response);
  1192. _response_fetcher.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_worker_thread_got_response);
  1193. _response_fetcher.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(_worker_thread_getting_response);
  1194. _post_response_fetcher.DoWork += new System.ComponentModel.DoWorkEventHandler(_post_response_fetcher_DoWork);
  1195. _post_response_fetcher.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_post_response_fetcher_RunWorkerCompleted);
  1196. _post_response_fetcher.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(_post_response_fetcher_ProgressChanged);
  1197. _activity_timer.Enabled = true;
  1198. }
  1199. void _activity_timer_Elapsed(object sender, ElapsedEventArgs e)
  1200. {
  1201. _do_next_action();
  1202. }
  1203. private void _do_next_action()
  1204. {
  1205. if (this.Username == string.Empty || this.Username == null || this.Password == string.Empty || this.Password == null)
  1206. return;
  1207. if (_state != InternalState.idle)
  1208. return;
  1209. if (_action_list.Count == 0)
  1210. return;
  1211. _state = InternalState.unknown;
  1212. _activity_timer.Enabled = false;
  1213. Action a = _action_list[0];
  1214. _action_list.Remove(a);
  1215. _current_action = a;
  1216. if (a.VideoID == null)
  1217. {
  1218. _get_cookies();
  1219. return;
  1220. }
  1221. else if (_cookie_jar == null)
  1222. {
  1223. _get_cookies();
  1224. _current_action = new Action(null, false);
  1225. _action_list.Add(a);
  1226. return;
  1227. }
  1228. _enable = a.Enable;
  1229. _raise_status_change(InternalState.get_settings);
  1230. _video_id = a.VideoID;
  1231. _do_get_request("http://www.youtube.com/my_videos_edit?video_id=" + a.VideoID, _cookie_jar);
  1232. }
  1233. // public methods
  1234. public void DisableVideo(string VideoID)
  1235. {
  1236. _remove_action(VideoID);
  1237. _action_list.Add(new Action(VideoID, false));
  1238. }
  1239. public void EnableVideo(string VideoID)
  1240. {
  1241. _remove_action(VideoID);
  1242. _action_list.Add(new Action(VideoID, true));
  1243. }
  1244. public void StopActing()
  1245. {
  1246. _action_list.Clear();
  1247. _state = InternalState.idle;
  1248. }
  1249. // private methods
  1250. private void _remove_action(string VideoID)
  1251. {
  1252. int i = 0;
  1253. while (i < _action_list.Count)
  1254. {
  1255. if (_action_list[i].VideoID == VideoID)
  1256. _action_list.Remove(_action_list[i]);
  1257. else
  1258. i++;
  1259. }
  1260. }
  1261. private void _check_login_info()
  1262. {
  1263. if (_login_info == null || _cookie_jar.Count <= 0)
  1264. return;
  1265. _do_get_request("http://www.youtube.com/my_videos", _cookie_jar);
  1266. //return response.StatusCode == HttpStatusCode.OK;
  1267. }
  1268. private void _get_cookies()
  1269. {
  1270. if (_response_fetcher.IsBusy || _post_response_fetcher.IsBusy)
  1271. {
  1272. _raise_exception(new Exception("Thread is busy!"));
  1273. _raise_failure(FailureCodes.FAILURE_LOGGING_IN);
  1274. _raise_status_change(InternalState.idle);
  1275. return;
  1276. }
  1277. CookieContainer cookie_jar = new CookieContainer();
  1278. string url = "https://www.google.com/accounts/ServiceLogin?uilel=3&service=youtube&passive=true&continue=http%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26nomobiletemp%3D1%26hl%3Den_US%26next%3D%252Findex&hl=en_US&ltmpl=sso";
  1279. _raise_status_change(InternalState.login_step_1);
  1280. _do_get_request(url, cookie_jar);
  1281. }
  1282. private void _do_get_request(string url, CookieContainer cookieJar)
  1283. {
  1284. HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(url);
  1285. _request.Timeout = _request_timeout;
  1286. _request.CookieContainer = cookieJar;
  1287. _request.AllowAutoRedirect = true;
  1288. _request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.13) Gecko/2009073022 Firefox/3.0.13 (.NET CLR 3.5.30729)";
  1289. _request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
  1290. _request.KeepAlive = false;
  1291. _request.Method = "GET";
  1292. _last_request = _request;
  1293. _response_fetcher.RunWorkerAsync(_request);
  1294. }
  1295. private class post_arguments
  1296. {
  1297. public HttpWebRequest Request { get; set; }
  1298. public byte[] post_data { get; set; }
  1299. public post_arguments(HttpWebRequest r, byte[] d) { this.Request = r; this.post_data = d; }
  1300. }
  1301. private void _do_post_request(string url, string post_data, CookieContainer CookieJar)
  1302. {
  1303. ASCIIEncoding encoding = new ASCIIEncoding();
  1304. byte[] data = Encoding.UTF8.GetBytes(post_data);
  1305. HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(url);
  1306. _request.ContentLength = data.Length;
  1307. _request.CookieContainer = CookieJar;
  1308. _request.Timeout = _request_timeout;
  1309. _request.AllowAutoRedirect = true;
  1310. _request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.13) Gecko/2009073022 Firefox/3.0.13 (.NET CLR 3.5.30729)";
  1311. _request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
  1312. _request.Headers.Add(HttpRequestHeader.KeepAlive, "300");
  1313. _request.KeepAlive = false;
  1314. _request.ProtocolVersion = HttpVersion.Version10;
  1315. _request.ContentType = "application/x-www-form-urlencoded";
  1316. _request.Referer = _last_request.RequestUri.ToString();
  1317. _request.Method = "POST";
  1318. _last_request = _request;
  1319. _post_response_fetcher_DoWork(this, new System.ComponentModel.DoWorkEventArgs(new post_arguments(_request, data)));
  1320. }
  1321. private string _get_login_form(string html)
  1322. {
  1323. IHTMLDocument3 domDocument = _getDocumentFromHTML(html) as IHTMLDocument3;
  1324. IHTMLFormElement _form = (IHTMLFormElement)domDocument.getElementById("gaia_loginform");
  1325. if (_form == null)
  1326. return null;
  1327. string post_data = string.Empty;
  1328. IHTMLInputElement _continue = _getElementByName(domDocument, "continue") as IHTMLInputElement;
  1329. IHTMLInputElement _service = _getElementByName(domDocument, "service") as IHTMLInputElement;
  1330. IHTMLInputElement _GALX = _getElementByName(domDocument, "GALX") as IHTMLInputElement;
  1331. IHTMLInputElement _rmShown = _getElementByName(domDocument, "rmShown") as IHTMLInputElement;
  1332. IHTMLInputElement _asts = _getElementByName(domDocument, "asts") as IHTMLInputElement;
  1333. IHTMLInputElement _ltmpl = _getElementByName(domDocument, "ltmpl") as IHTMLInputElement;
  1334. IHTMLInputElement _uilel = _getElementByName(domDocument, "uilel") as IHTMLInputElement;
  1335. IHTMLInputElement _hl = _getElementByName(domDocument, "hl") as IHTMLInputElement;
  1336. IHTMLInputElement _ltmpl2 = _getElementByName(domDocument, "ltmpl") as IHTMLInputElement;
  1337. post_data = "Email=" + Username + "&Passwd=" + Password + "&PersistentCookie=yes&signIn=Sign+in";
  1338. post_data += "&" + _continue.name + "=" + _continue.value;
  1339. post_data += "&" + _service.name + "=" + _service.value;
  1340. post_data += "&" + _GALX.name + "=" + _GALX.value;
  1341. post_data += "&" + _rmShown.name + "=" + _rmShown.value;
  1342. post_data += "&" + _asts.name + "=" + _asts.value;
  1343. post_data += "&" + _ltmpl.name + "=" + _ltmpl.value;
  1344. post_data += "&" + _uilel.name + "=" + _uilel.value;
  1345. post_data += "&" + _hl.name + "=" + _hl.value;
  1346. post_data += "&" + _ltmpl2.name + "=" + _ltmpl2.value;
  1347. return post_data;
  1348. }
  1349. private string _get_settings_form(string html, bool Enabled)
  1350. {
  1351. //'XSRF_TOKEN': 'cH-siYb9w2jglfqsArlTaZCRj2l8MTI2NDMxMzU0Nw=='
  1352. string session = string.Empty;
  1353. int start = 0; int end = 0;
  1354. start = html.IndexOf("'XSRF_TOKEN': '");
  1355. if (start > -1)
  1356. {
  1357. start += "'XSRF_TOKEN': '".Length;
  1358. end = html.IndexOf("',", start + 1);
  1359. if (end > -1)
  1360. session = html.Substring(start, end - start);
  1361. }
  1362. //return "ns=1&next=&video_id=whqvyRfwwiw&action_videosave=1&ignore_broadcast_settings=0&field_myvideo_title=123abc&field_myvideo_descr=fuck+yea&field_myvideo_keywords=nada&field_myvideo_categories=22&field_current_still_id=2&field_still_id=2&field_privacy=private&private_share_entity=&allow_comments=No&allow_comment_ratings=No&allow_responses=Kinda&allow_ratings=No&allow_embedding=Yes&allow_syndication=Yes&field_date_mon=0&field_date_day=0&field_date_yr=0&location=&altitude=&session_token=" + session.Replace("=", "%3D");
  1363. string field_myvideo_descr, field_myvideo_keywords;
  1364. field_myvideo_descr = _getTextAreaElement(html, "field_myvideo_descr");
  1365. field_myvideo_keywords = _getTextAreaElement(html, "field_myvideo_keywords");
  1366. string ns, next, video_id, action_videosave, ignore_broadcast_settings, field_myvideo_title, field_current_still_id,
  1367. field_still_id, location, altitude;
  1368. ns = _getInputElement(html, "ns");
  1369. next = _getInputElement(html, "next");
  1370. video_id = _getInputElement(html, "video_id");
  1371. action_videosave = _getInputElement(html, "action_videosave");
  1372. ignore_broadcast_settings = _getInputElement(html, "ignore_broadcast_settings");
  1373. field_myvideo_title = _getInputElement(html, "field_myvideo_title");
  1374. field_current_still_id = _getInputElement(html, "field_current_still_id");
  1375. field_still_id = _getInputElement(html, "field_still_id");
  1376. location = _getInputElement(html, "location");
  1377. altitude = _getInputElement(html, "altitude");
  1378. string field_myvideo_categories, month, day, year;
  1379. field_myvideo_categories = _getSelectedElement(html, "field_myvideo_categories");
  1380. month = _getSelectedElement(html, "field_date_mon");
  1381. day = _getSelectedElement(html, "field_date_day");
  1382. year = _getSelectedElement(html, "field_date_yr");
  1383. if (month == null)
  1384. month = "0";
  1385. if (day == null)
  1386. day = "0";
  1387. if (year == null)
  1388. year = "0";
  1389. string privacy_selected, comments_selected, comment_ratings_selected, responses_selected,
  1390. embedding_selected, syndication_selected;
  1391. privacy_selected = _getSelectedRadioElement(html, "field_privacy");
  1392. comments_selected = _getSelectedRadioElement(html, "allow_comments");
  1393. comment_ratings_selected = _getSelectedRadioElement(html, "allow_comment_ratings");
  1394. responses_selected = _getSelectedRadioElement(html, "allow_responses");
  1395. embedding_selected = _getSelectedRadioElement(html, "allow_embedding");
  1396. syndication_selected = _getSelectedRadioElement(html, "allow_syndication");
  1397. string post_data = string.Empty;
  1398. post_data = "ns=" + ns + "&next=&video_id=" + System.Web.HttpUtility.UrlEncode(video_id) + "&action_videosave=1&ignore_broadcast_settings=" + System.Web.HttpUtility.UrlEncode(ignore_broadcast_settings) + "&field_myvideo_title=" + System.Web.HttpUtility.UrlEncode(field_myvideo_title) + "&field_myvideo_descr=" + System.Web.HttpUtility.UrlEncode(field_myvideo_descr.Replace("&amp;", "&")) + "&field_myvideo_keywords=" + System.Web.HttpUtility.UrlEncode(field_myvideo_keywords) + "&field_myvideo_categories=" + System.Web.HttpUtility.UrlEncode(field_myvideo_categories);
  1399. post_data += "&field_current_still_id=" + System.Web.HttpUtility.UrlEncode(field_current_still_id) + "&field_still_id=" + System.Web.HttpUtility.UrlEncode(field_still_id) + "&field_privacy=" + System.Web.HttpUtility.UrlEncode(privacy_selected) + "&private_video_token=&private-url=&allow_comments=" + System.Web.HttpUtility.UrlEncode(comments_selected) + "&allow_comment_ratings=" + System.Web.HttpUtility.UrlEncode(comment_ratings_selected) + "&allow_responses=" + System.Web.HttpUtility.UrlEncode(responses_selected) + "&allow_ratings=" + System.Web.HttpUtility.UrlEncode(Enabled ? "Yes" : "No");
  1400. post_data += "&allow_embedding=" + System.Web.HttpUtility.UrlEncode(embedding_selected) + "&allow_syndication=" + System.Web.HttpUtility.UrlEncode(syndication_selected) + "&field_date_mon=" + System.Web.HttpUtility.UrlEncode(month) + "&field_date_day=" + System.Web.HttpUtility.UrlEncode(day) + "&field_date_yr=" + System.Web.HttpUtility.UrlEncode(year) + "&location=" + System.Web.HttpUtility.UrlEncode(location) + "&altitude=" + System.Web.HttpUtility.UrlEncode(altitude) + "&session_token=" + session.Replace("=", "%3D");
  1401. System.Console.Write(post_data);
  1402. return post_data;
  1403. /*
  1404. IHTMLDocument3 domDocument = _getDocumentFromHTML(html) as IHTMLDocument3;
  1405. IHTMLFormElement _form = (IHTMLFormElement)domDocument.getElementById("video-details-form");
  1406. if (_form == null)
  1407. return null;
  1408. // text inputs
  1409. IHTMLTextAreaElement field_myvideo_descr = _getElementByName(domDocument, "field_myvideo_descr") as IHTMLTextAreaElement;
  1410. IHTMLTextAreaElement field_myvideo_keywords = _getElementByName(domDocument, "field_myvideo_keywords") as IHTMLTextAreaElement;
  1411. if (field_myvideo_descr == null || field_myvideo_keywords == null)
  1412. return null;
  1413. IHTMLInputElement ns = _getElementByName(domDocument, "ns") as IHTMLInputElement;
  1414. IHTMLInputElement next = _getElementByName(domDocument, "next") as IHTMLInputElement;
  1415. IHTMLInputElement video_id = _getElementByName(domDocument, "video_id") as IHTMLInputElement;
  1416. IHTMLInputElement action_videosave = _getElementByName(domDocument, "action_videosave") as IHTMLInputElement;
  1417. IHTMLInputElement ignore_broadcast_settings = _getElementByName(domDocument, "ignore_broadcast_settings") as IHTMLInputElement;
  1418. IHTMLInputElement field_myvideo_title = _getElementByName(domDocument, "field_myvideo_title") as IHTMLInputElement;
  1419. IHTMLInputElement field_current_still_id = _getElementByName(domDocument, "field_current_still_id") as IHTMLInputElement;
  1420. IHTMLInputElement field_still_id = _getElementByName(domDocument, "field_still_id") as IHTMLInputElement;
  1421. IHTMLInputElement location = _getElementByName(domDocument, "location") as IHTMLInputElement;
  1422. IHTMLInputElement altitude = _getElementByName(domDocument, "altitude") as IHTMLInputElement;
  1423. if (ns == null || next == null || video_id == null || action_videosave == null
  1424. || ignore_broadcast_settings == null || field_myvideo_keywords == null
  1425. || field_current_still_id == null || field_still_id == null
  1426. || location == null || altitude == null)
  1427. return null;
  1428. // selects
  1429. IHTMLSelectElement field_myvideo_categories = _getElementByName(domDocument, "field_myvideo_categories") as IHTMLSelectElement;
  1430. IHTMLSelectElement categories = _getElementByName(domDocument, "field_myvideo_categories") as IHTMLSelectElement;
  1431. IHTMLSelectElement month = _getElementByName(domDocument, "field_date_mon") as IHTMLSelectElement;
  1432. IHTMLSelectElement day = _getElementByName(domDocument, "field_date_day") as IHTMLSelectElement;
  1433. IHTMLSelectElement year = _getElementByName(domDocument, "field_date_yr") as IHTMLSelectElement;
  1434. if (field_myvideo_categories == null || categories == null || month == null || day == null || year == null)
  1435. return null;
  1436. // radio options
  1437. IHTMLElementCollection options = domDocument.getElementsByName("field_privacy");
  1438. IHTMLInputElement privicy_selected = _get_selected_option(options);
  1439. options = domDocument.getElementsByName("allow_comments");
  1440. IHTMLInputElement comments_selected = _get_selected_option(options);
  1441. options = domDocument.getElementsByName("allow_comment_ratings");
  1442. IHTMLInputElement comment_ratings_selected = _get_selected_option(options);
  1443. options = domDocument.getElementsByName("allow_responses");
  1444. IHTMLInputElement responses_selected = _get_selected_option(options);
  1445. options = domDocument.getElementsByName("allow_embedding");
  1446. IHTMLInputElement embedding_selected = _get_selected_option(options);
  1447. options = domDocument.getElementsByName("allow_syndication");
  1448. IHTMLInputElement syndication_selected = _get_selected_option(options);
  1449. if (privicy_selected == null || comments_selected == null || comment_ratings_selected == null ||
  1450. responses_selected == null || embedding_selected == null || syndication_selected == null)
  1451. return null;
  1452. // fucking WORKS!!! return "ns=1&next=&video_id=whqvyRfwwiw&action_videosave=1&ignore_broadcast_settings=0&field_myvideo_title=123abc&field_myvideo_descr=fuck+yea&field_myvideo_keywords=nada&field_myvideo_categories=22&field_current_still_id=2&field_still_id=2&field_privacy=private&private_share_entity=00DDB08E54250E2A&allow_comments=No&allow_comment_ratings=No&allow_responses=Kinda&allow_ratings=No&allow_embedding=Yes&allow_syndication=Yes&field_date_mon=0&field_date_day=0&field_date_yr=0&location=&altitude=&session_token=" + session.Replace("=", "%3D");
  1453. try
  1454. {
  1455. post_data = "ns=1&next=&video_id=" + System.Web.HttpUtility.UrlEncode(video_id.value) + "&action_videosave=1&ignore_broadcast_settings=" + System.Web.HttpUtility.UrlEncode(ignore_broadcast_settings.value) + "&field_myvideo_title=" + System.Web.HttpUtility.UrlEncode(field_myvideo_title.value) + "&field_myvideo_descr=" + System.Web.HttpUtility.UrlDecode(field_myvideo_descr.value) + "&field_myvideo_keywords=" + System.Web.HttpUtility.UrlDecode(field_myvideo_keywords.value) + "&field_myvideo_categories=" + System.Web.HttpUtility.UrlEncode(field_myvideo_categories.value);
  1456. post_data += "&field_current_still_id=" + System.Web.HttpUtility.UrlEncode(field_current_still_id.value) + "&field_still_id=" + System.Web.HttpUtility.UrlEncode(field_still_id.value) + "&field_privacy=" + System.Web.HttpUtility.UrlEncode(privicy_selected.value) + "&allow_comments=" + System.Web.HttpUtility.UrlEncode(comments_selected.value) + "&allow_comment_ratings=" + System.Web.HttpUtility.UrlEncode(comment_ratings_selected.value) + "&allow_responses=" + System.Web.HttpUtility.UrlEncode(responses_selected.value) + "&allow_ratings=" + System.Web.HttpUtility.UrlEncode(Enabled ? "Yes" : "No");
  1457. post_data += "&allow_embedding=" + System.Web.HttpUtility.UrlEncode(embedding_selected.value) + "&allow_syndication=" + System.Web.HttpUtility.UrlEncode(syndication_selected.value) + "&field_date_mon=" + System.Web.HttpUtility.UrlEncode(month.value) + "&field_date_day=" + System.Web.HttpUtility.UrlEncode(day.value) + "&field_date_yr=" + System.Web.HttpUtility.UrlEncode(year.value) + "&location=" + System.Web.HttpUtility.UrlEncode(location.value) + "&altitude=" + System.Web.HttpUtility.UrlEncode(altitude.value) + "&session_token=" + session.Replace("=", "%3D");
  1458. return post_data;
  1459. }
  1460. catch (Exception ex)
  1461. {
  1462. _raise_exception(ex);
  1463. return null;
  1464. }
  1465. */
  1466. }
  1467. private string _getTextAreaElement(string html, string name)
  1468. {
  1469. Regex r = new Regex("<textarea.*?name=\"" + name + "\".*?>(.*?)</textarea>", RegexOptions.Singleline);
  1470. Match m = r.Match(html);
  1471. if (!m.Success)
  1472. return null;
  1473. else
  1474. return m.Groups[1].Value;
  1475. }
  1476. private string _getInputElement(string html, string name)
  1477. {
  1478. Regex r = new Regex("<input.*?type=(\"hidden\"|\"text\").*?name=\"" + name + "\".*?value=\"(.*?)\"" );
  1479. Match m = r.Match(html);
  1480. if (!m.Success)
  1481. return null;
  1482. else
  1483. return m.Groups[2].Value;
  1484. }
  1485. private string _getSelectedElement(string html, string name)
  1486. {
  1487. Regex _regX_select = new Regex("<select name=\"" + name + "\".+?>(.+)</select>", RegexOptions.Singleline);
  1488. Match m = _regX_select.Match(html);
  1489. if (!m.Success)
  1490. return null;
  1491. string options = m.Groups[1].Value;
  1492. Regex _regX_selected = new Regex("<option value=\"(.+?)\" selected>");
  1493. m = _regX_selected.Match(options);
  1494. if (!m.Success)
  1495. return null;
  1496. else
  1497. return m.Groups[1].Value;
  1498. }
  1499. private string _getSelectedRadioElement(string html, string name)
  1500. {
  1501. Regex _regX_Radio = new Regex("<input type=\"radio\".+?name=\"" + name + "\".+?value=\"(.+?)\".+?checked");
  1502. Match m = _regX_Radio.Match(html);
  1503. if (!m.Success)
  1504. return null;
  1505. else
  1506. return m.Groups[1].Value;
  1507. }
  1508. private IHTMLInputElement _get_selected_option(IHTMLElementCollection options)
  1509. {
  1510. foreach (IHTMLInputElement o in options)
  1511. if (o.@checked == true)
  1512. return o;
  1513. return null;
  1514. }
  1515. private string _get_redirect_url(string html)
  1516. {
  1517. string search_right = "'";
  1518. string search_left = "url='";
  1519. int redir_start = html.IndexOf(search_left);
  1520. if (redir_start < 0)
  1521. {
  1522. redir_start = html.IndexOf("url=&#39;");
  1523. if (redir_start > 0)
  1524. {
  1525. search_right = "&#39;";
  1526. search_left = "url=&#39;";
  1527. }
  1528. }
  1529. if (redir_start >= 0)
  1530. {
  1531. redir_start += search_left.Length;
  1532. int redir_end = html.IndexOf(search_right, redir_start);
  1533. if (redir_end != -1)
  1534. {
  1535. return html.Substring(redir_start, redir_end - redir_start);
  1536. }
  1537. }
  1538. return null;
  1539. }
  1540. private IHTMLElement _getElementByName(IHTMLDocument3 doc, string name)
  1541. {
  1542. IHTMLElementCollection elements = doc.getElementsByName(name);
  1543. foreach (IHTMLElement element in elements)
  1544. return element;
  1545. return null;
  1546. }
  1547. private HTMLDocumentClass _getDocumentFromHTML(string html)
  1548. {
  1549. //html = html.Replace("<SCRIPT", "<SC");
  1550. object[] oPageText = { html };
  1551. HTMLDocumentClass myDoc = new HTMLDocumentClass();
  1552. IHTMLDocument2 oMyDoc = (IHTMLDocument2)myDoc;
  1553. oMyDoc.write(oPageText);
  1554. oMyDoc.close();
  1555. return oMyDoc as HTMLDocumentClass;
  1556. }
  1557. // private threading methods
  1558. void _post_response_fetcher_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
  1559. {
  1560. throw new NotImplementedException();
  1561. }
  1562. void _post_response_fetcher_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
  1563. {
  1564. throw new NotImplementedException();
  1565. }
  1566. void _post_response_fetcher_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
  1567. {
  1568. post_arguments args = e.Argument as post_arguments;
  1569. HttpWebRequest _request = args.Request;
  1570. byte[] data = args.post_data;
  1571. switch (_state)
  1572. {
  1573. case InternalState.save_settings:
  1574. int tries = 0;
  1575. Stream post_stream = null;
  1576. try
  1577. {
  1578. _request.Expect = string.Empty;
  1579. post_stream = _request.GetRequestStream();
  1580. }
  1581. catch (Exception ex)
  1582. {
  1583. _raise_exception(ex);
  1584. _raise_failure(FailureCodes.FAILURE_CHANGING_SETTINGS);
  1585. _raise_status_change(InternalState.idle);
  1586. return;
  1587. }
  1588. if (post_stream == null)
  1589. return;
  1590. try
  1591. {
  1592. post_stream.Write(data, 0, data.Length);
  1593. }
  1594. catch (Exception ex)
  1595. {
  1596. _raise_exception(ex);
  1597. _raise_failure(FailureCodes.FAILURE_CHANGING_SETTINGS);
  1598. _raise_status_change(InternalState.idle);
  1599. post_stream.Close();
  1600. post_stream.Dispose();
  1601. return;
  1602. }
  1603. finally
  1604. {
  1605. post_stream.Close();
  1606. post_stream.Dispose();
  1607. }
  1608. try
  1609. {
  1610. HttpWebResponse _response = (HttpWebResponse)_request.GetResponse();
  1611. StreamReader stream = new StreamReader(_response.GetResponseStream(), System.Text.Encoding.ASCII);
  1612. string html = string.Empty;
  1613. try
  1614. {
  1615. html = stream.ReadToEnd();
  1616. }
  1617. catch (Exception ex)
  1618. {
  1619. _raise_exception(ex);
  1620. _raise_failure(FailureCodes.FAILURE_CHANGING_SETTINGS);
  1621. _raise_status_change(InternalState.idle);
  1622. stream.Close();
  1623. stream.Dispose();
  1624. _response.Close();
  1625. return;
  1626. }
  1627. finally
  1628. {
  1629. stream.Close();
  1630. stream.Dispose();
  1631. _response.Close();
  1632. }
  1633. _raise_success(FailureCodes.FAILURE_CHANGING_SETTINGS);
  1634. _raise_status_change(InternalState.idle);
  1635. }
  1636. catch (Exception ex)
  1637. {
  1638. _raise_exception(ex);
  1639. _raise_failure(FailureCodes.FAILURE_CHANGING_SETTINGS);
  1640. _raise_status_change(InternalState.idle);
  1641. post_stream.Close();
  1642. post_stream.Dispose();
  1643. return;
  1644. }
  1645. break;
  1646. case InternalState.login_step_2:
  1647. try
  1648. {
  1649. post_stream = _request.GetRequestStream();
  1650. }
  1651. catch (Exception ex)
  1652. {
  1653. _raise_exception(ex);
  1654. _raise_failure(FailureCodes.FAILURE_LOGGING_IN);
  1655. _raise_status_change(InternalState.idle);
  1656. return;
  1657. }
  1658. try
  1659. {
  1660. post_stream.Write(data, 0, data.Length);
  1661. }
  1662. catch (Exception ex)
  1663. {
  1664. _raise_exception(ex);
  1665. _raise_failure(FailureCodes.FAILURE_LOGGING_IN);
  1666. _raise_status_change(InternalState.idle);
  1667. post_stream.Close();
  1668. post_stream.Dispose();
  1669. return;
  1670. }
  1671. finally
  1672. {
  1673. post_stream.Close();
  1674. post_stream.Dispose();
  1675. }
  1676. try
  1677. {
  1678. HttpWebResponse _res = (HttpWebResponse)_request.GetResponse();
  1679. StreamReader str = new StreamReader(_res.GetResponseStream(), System.Text.Encoding.ASCII);
  1680. string htm = string.Empty;
  1681. try
  1682. {
  1683. htm = str.ReadToEnd();
  1684. }
  1685. catch (Exception ex)
  1686. {
  1687. _raise_exception(ex);
  1688. _raise_failure(FailureCodes.FAILURE_LOGGING_IN);
  1689. _raise_status_change(InternalState.idle);
  1690. str.Close();
  1691. str.Dispose();
  1692. _res.Close();
  1693. return;
  1694. }
  1695. finally
  1696. {
  1697. str.Close();
  1698. str.Dispose();
  1699. _res.Close();
  1700. }
  1701. foreach (Cookie c in _last_request.CookieContainer.GetCookies(new Uri("http://www.youtube.com")))
  1702. {
  1703. if (c.Name == "LOGIN_INFO")
  1704. {
  1705. _cookie_jar = _last_request.CookieContainer;
  1706. _login_info = c;
  1707. _raise_success(FailureCodes.FAILURE_LOGGING_IN);
  1708. _raise_status_change(InternalState.idle);
  1709. return;
  1710. }
  1711. }
  1712. string url = _get_redirect_url(htm);
  1713. if (url == null || url == string.Empty)
  1714. {
  1715. _raise_status_change(InternalState.idle);
  1716. _raise_failure(FailureCodes.FAILURE_LOGGING_IN);
  1717. _raise_exception(new Exception("_post_response_fetcher_DoWork: failed to get redirect url from step 2."));
  1718. return;
  1719. }
  1720. _raise_status_change(InternalState.login_step_3);
  1721. _do_get_request(url, _request.CookieContainer);
  1722. }
  1723. catch ( Exception ex )
  1724. {
  1725. _raise_exception(ex);
  1726. _raise_failure(FailureCodes.FAILURE_LOGGING_IN);
  1727. _raise_status_change(InternalState.idle);
  1728. post_stream.Close();
  1729. post_stream.Dispose();
  1730. return;
  1731. }
  1732. break;
  1733. default:
  1734. _raise_exception(new Exception("_post_response_fetcher_DoWork: failed to select state."));
  1735. _raise_failure(FailureCodes.FAILURE_LOGGING_IN);
  1736. _raise_status_change(InternalState.idle);
  1737. break;
  1738. }
  1739. }
  1740. void _worker_thread_getting_response(object sender, System.ComponentModel.ProgressChangedEventArgs e)
  1741. {
  1742. throw new NotImplementedException();
  1743. }
  1744. void _worker_thread_got_response(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
  1745. {
  1746. HttpWebResponse response = e.Result as HttpWebResponse;
  1747. switch (_state)
  1748. {
  1749. case InternalState.get_settings:
  1750. StreamReader stream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII);
  1751. string html = null;
  1752. try
  1753. {
  1754. html = stream.ReadToEnd();
  1755. }
  1756. catch (Exception ex)
  1757. {
  1758. _raise_exception(ex);
  1759. _raise_failure(FailureCodes.FAILURE_CHANGING_SETTINGS);
  1760. stream.Close();
  1761. stream.Dispose();
  1762. response.Close();
  1763. _raise_status_change(InternalState.idle);
  1764. return;
  1765. }
  1766. finally
  1767. {
  1768. stream.Close();
  1769. stream.Dispose();
  1770. response.Close();
  1771. }
  1772. if (html == string.Empty || html == null)
  1773. {
  1774. _raise_exception(new Exception("_worker_thread_got_response: failed to get html in get_settings step 1"));
  1775. _raise_failure(FailureCodes.FAILURE_CHANGING_SETTINGS);
  1776. _raise_status_change(InternalState.idle);
  1777. return;
  1778. }
  1779. string post_data = _get_settings_form(html, _enable);
  1780. string url = "http://www.youtube.com/my_videos_edit";
  1781. if (post_data == string.Empty || post_data == null)
  1782. {
  1783. _raise_exception(new Exception("_worker_thread_got_response: failed to get post_data in get_settings step 1"));
  1784. _raise_failure(FailureCodes.FAILURE_CHANGING_SETTINGS);
  1785. _raise_status_change(InternalState.idle);
  1786. return;
  1787. }
  1788. _raise_status_change(InternalState.save_settings);
  1789. System.Console.Write(_login_info.ToString());
  1790. //string host = "www.youtube.com";
  1791. //string headers = "POST /my_videos_edit HTTP/1.1\nHost: www.youtube.com\nUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\nCookie: "+_cookie_jar.GetCookieHeader(new Uri("http://www.youtube.com")) + "\nContent-Type: application/x-www-form-urlencoded";
  1792. //string result = GetSocket.SocketSendReceive(host, 80, headers, post_data);
  1793. //_raise_success(FailureCodes.FAILURE_CHANGING_SETTINGS);
  1794. //_raise_status_change(InternalState.idle);
  1795. _do_post_request(url, post_data, _last_request.CookieContainer);
  1796. break;
  1797. case InternalState.login_step_1:
  1798. try
  1799. {
  1800. stream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII);
  1801. html = null;
  1802. html = stream.ReadToEnd();
  1803. }
  1804. catch (Exception ex)
  1805. {
  1806. _raise_exception(ex);
  1807. _raise_failure(FailureCodes.FAILURE_LOGGING_IN);
  1808. _raise_status_change(InternalState.idle);
  1809. response.Close();
  1810. return;
  1811. }
  1812. finally
  1813. {
  1814. response.Close();
  1815. }
  1816. if (html == string.Empty || html == null)
  1817. {
  1818. _raise_exception(new Exception("_worker_thread_got_response: failed to get html in step 1"));
  1819. _raise_failure(FailureCodes.FAILURE_LOGGING_IN);
  1820. _raise_status_change(InternalState.idle);
  1821. return;
  1822. }
  1823. post_data = _get_login_form(html);
  1824. url = "https://www.google.com/accounts/ServiceLoginAuth?service=youtube";
  1825. _raise_status_change(InternalState.login_step_2);
  1826. _do_post_request(url, post_data, _last_request.CookieContainer);
  1827. break;
  1828. case InternalState.login_step_3:
  1829. foreach (Cookie c in _last_request.CookieContainer.GetCookies(_last_request.RequestUri))
  1830. {
  1831. if (c.Name == "LOGIN_INFO")
  1832. {
  1833. _cookie_jar = _last_request.CookieContainer;
  1834. _login_info = c;
  1835. _raise_success(FailureCodes.FAILURE_LOGGING_IN);
  1836. _raise_status_change(InternalState.idle);
  1837. response.Close();
  1838. return;
  1839. }
  1840. }
  1841. _raise_exception(new Exception("Failed to get login cookies"));
  1842. _raise_failure(FailureCodes.FAILURE_LOGGING_IN);
  1843. _raise_status_change(InternalState.idle);
  1844. response.Close();
  1845. break;
  1846. default:
  1847. _raise_exception(new Exception("worker_thread_got_response: failed to determine thread state."));
  1848. _raise_failure(FailureCodes.FAILURE_LOGGING_IN);
  1849. _raise_status_change(InternalState.idle);
  1850. break;
  1851. }
  1852. response.Close();
  1853. }
  1854. void _worker_thread_get_response(object sender, System.ComponentModel.DoWorkEventArgs e)
  1855. {
  1856. HttpWebRequest r = (HttpWebRequest)e.Argument;
  1857. e.Result = r.GetResponse();
  1858. }
  1859. // public properties
  1860. public string Username { get; set; }
  1861. public string Password { get; set; }
  1862. public InternalState State { get { return _state; } }
  1863. public int ActivityListCount { get { return _action_list.Count; } }
  1864. public string VideoID { get { return _video_id; } }
  1865. }
  1866. /* Utility class to handle multiple clsSettingsManager objects */
  1867. public class clsED
  1868. {
  1869. private List<clsSettingsManager> _settings_managers = new List<clsSettingsManager>();
  1870. private clsFileLogger _logger = null;
  1871. private clsSettings _settings;
  1872. private bool _in_action = false;
  1873. public clsED()
  1874. {
  1875. }
  1876. public clsED(clsSettings Settings)
  1877. {
  1878. _settings = Settings;
  1879. _settings.OnAccountAdded += new clsSettings.AccountAddedHandler(_settings_OnAccountAdded);
  1880. _settings.OnAccountRemoved += new clsSettings.AccountRemovedHandler(_settings_OnAccountRemoved);
  1881. if (_settings.ED_Log_File != null && _settings.ED_Log_File != string.Empty)
  1882. _logger = new clsFileLogger(_settings.ED_Log_File);
  1883. foreach (clsCredentials Account in _settings.Accounts)
  1884. {
  1885. if (Account.Password == "-")
  1886. continue;
  1887. clsSettingsManager sm = new clsSettingsManager(Account.Username, Account.Password);
  1888. sm.OnException += new clsSettingsManager.ExceptionEventHandler(sm_OnException);
  1889. sm.OnFailure += new clsSettingsManager.FailureEventHandler(sm_OnFailure);
  1890. sm.OnStatusChange += new clsSettingsManager.StatusEventHandler(sm_OnStatusChange);
  1891. sm.OnSuccess += new clsSettingsManager.SuccessEventHandler(sm_OnSuccess);
  1892. _settings_managers.Add(sm);
  1893. }
  1894. }
  1895. void _settings_OnAccountRemoved(object sender, clsCredentials Account)
  1896. {
  1897. RemoveAccount(Account);
  1898. }
  1899. void _settings_OnAccountAdded(object sender, clsCredentials Account)
  1900. {
  1901. AddAccount(Account);
  1902. }
  1903. void sm_OnSuccess(object sender, clsSettingsManager.FailureCodes f)
  1904. {
  1905. clsSettingsManager thisSM = (clsSettingsManager)sender;
  1906. if (_logger != null)
  1907. _logger.appendFile(DateTime.Now.ToString() + "-" + thisSM.Username + " Success @ " + f.ToString());
  1908. }
  1909. void sm_OnStatusChange(object sender, clsSettingsManager.InternalState s)
  1910. {
  1911. _in_action = false;
  1912. if (s == clsSettingsManager.InternalState.idle)
  1913. {
  1914. foreach (clsSettingsManager sm in _settings_managers)
  1915. {
  1916. _in_action = (sm.State != clsSettingsManager.InternalState.idle);
  1917. break;
  1918. }
  1919. }
  1920. clsSettingsManager thisSM = (clsSettingsManager)sender;
  1921. System.Diagnostics.Debug.WriteLine(thisSM.Username + " Status changed to " + s.ToString());
  1922. }
  1923. void sm_OnFailure(object sender, clsSettingsManager.FailureCodes f)
  1924. {
  1925. clsSettingsManager thisSM = (clsSettingsManager)sender;
  1926. if (_logger != null)
  1927. _logger.appendFile(DateTime.Now.ToString() + "-" + thisSM.Username + " Failed @ " + f.ToString());
  1928. }
  1929. void sm_OnException(object sender, Exception e)
  1930. {
  1931. clsSettingsManager thisSM = (clsSettingsManager)sender;
  1932. if (_logger != null)
  1933. _logger.appendFile(DateTime.Now.ToString() + "-" + thisSM.Username + " Exception: " + e.Message);
  1934. }
  1935. private void AddAccount(clsCredentials Account)
  1936. {
  1937. foreach (clsSettingsManager sm in _settings_managers)
  1938. if (sm.Username == Account.Username)
  1939. return;
  1940. if (Account.Password == "-")
  1941. return;
  1942. clsSettingsManager newSM = new clsSettingsManager(Account.Username, Account.Password);
  1943. newSM.OnSuccess += new clsSettingsManager.SuccessEventHandler(sm_OnSuccess);
  1944. newSM.OnFailure += new clsSettingsManager.FailureEventHandler(sm_OnFailure);
  1945. newSM.OnException += new clsSettingsManager.ExceptionEventHandler(sm_OnException);
  1946. newSM.OnStatusChange += new clsSettingsManager.StatusEventHandler(sm_OnStatusChange);
  1947. _settings_managers.Add(newSM);
  1948. }
  1949. private void RemoveAccount(clsCredentials Account)
  1950. {
  1951. int i = 0;
  1952. while (i < _settings_managers.Count)
  1953. {
  1954. if (_settings_managers[i].Username == Account.Username)
  1955. {
  1956. _settings_managers[i].Dispose();
  1957. _settings_managers.RemoveAt(i);
  1958. }
  1959. else
  1960. i++;
  1961. }
  1962. }
  1963. public void ChangeAccountRatings(clsCredentials Account, string VideoID, bool Enable)
  1964. {
  1965. foreach (clsSettingsManager sm in _settings_managers)
  1966. {
  1967. if (sm.Username == Account.Username)
  1968. {
  1969. if (Enable)
  1970. sm.EnableVideo(VideoID);
  1971. else
  1972. sm.DisableVideo(VideoID);
  1973. _raise_started_action();
  1974. return;
  1975. }
  1976. }
  1977. }
  1978. public void ChangeAccountRatings(clsCredentials Account, List<clsVideoEntry> Videos, bool Enable)
  1979. {
  1980. foreach (clsSettingsManager sm in _settings_managers)
  1981. {
  1982. if (sm.Username == Account.Username)
  1983. {
  1984. if (Enable)
  1985. {
  1986. foreach (clsVideoEntry e in Videos)
  1987. sm.EnableVideo(e.VideoID);
  1988. }
  1989. else
  1990. {
  1991. foreach (clsVideoEntry e in Videos)
  1992. sm.DisableVideo(e.VideoID);
  1993. }
  1994. _raise_started_action();
  1995. return;
  1996. }
  1997. }
  1998. }
  1999. public delegate void StartedActionEventHandler(object Sender);
  2000. public event StartedActionEventHandler OnStartedAction;
  2001. private void _raise_started_action()
  2002. {
  2003. if (_in_action == true)
  2004. return;
  2005. if (OnStartedAction != null)
  2006. OnStartedAction(this);
  2007. }
  2008. public List<clsSettingsManager> SettingsManagers { get { return _settings_managers; } }
  2009. public clsFileLogger Logger { set { _logger = value; } }
  2010. }
  2011. /* Utility class that write to file */
  2012. public class clsFileLogger
  2013. {
  2014. private string _file_name = string.Empty;
  2015. public delegate void ErrorEventHandler(object sender, IOException e);
  2016. public event ErrorEventHandler OnError;
  2017. protected virtual void Error(IOException e)
  2018. {
  2019. if (OnError != null)
  2020. OnError(this, e);
  2021. }
  2022. public clsFileLogger(string filename)
  2023. {
  2024. _file_name = filename;
  2025. }
  2026. public void Initialize()
  2027. {
  2028. try
  2029. {
  2030. FileStream file = new FileStream(_file_name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  2031. file.Close();
  2032. }
  2033. catch (IOException e)
  2034. { Error(e); }
  2035. }
  2036. public string readFile()
  2037. {
  2038. FileStream file = new FileStream(_file_name, FileMode.OpenOrCreate, FileAccess.Read);
  2039. StreamReader sr = new StreamReader(file);
  2040. string ret = sr.ReadToEnd();
  2041. sr.Close();
  2042. file.Close();
  2043. return ret;
  2044. }
  2045. public void appendFile(string data)
  2046. {
  2047. StreamWriter sw = File.AppendText(_file_name);
  2048. sw.WriteLine(data);
  2049. sw.Flush();
  2050. sw.Close();
  2051. }
  2052. }
  2053. /*Class to maintain settings */
  2054. public class clsSettings
  2055. {
  2056. private const string DEFAULT_FILENAME = "TubeGuardian.log";
  2057. private const string DEFAULT_SETTINGS_FILENAME = "TubeGuardian.settings";
  2058. private string _settings_file_name;
  2059. private int _collect_interval;
  2060. private string _collect_log_file;
  2061. private int _analyzer_relevant_entries;
  2062. private double _analyzer_vote_threshold;
  2063. private bool _analyzer_disable_affected;
  2064. private bool _analyzer_disable_all;
  2065. private int _analyzer_disable_duration;
  2066. private string _ed_log_file;
  2067. // Gatherer settings
  2068. public int Collect_Interval { get { return _collect_interval; } set { _collect_interval = value; _event_settings_changed(); } }
  2069. public string Collect_Log_File { get { return _collect_log_file; } set { _collect_log_file = value; _event_settings_changed(); } }
  2070. // Account settings
  2071. public List<clsCredentials> Accounts { get; private set; }
  2072. // Analyzer settings
  2073. public int Analyzer_Relevant_Entries { get { return _analyzer_relevant_entries; } set { _analyzer_relevant_entries = value; _event_settings_changed(); } }
  2074. public double Analyzer_Vote_Threshold { get { return _analyzer_vote_threshold; } set { _analyzer_vote_threshold = value; _event_settings_changed(); } }
  2075. public bool Analyzer_Disable_Affected { get { return _analyzer_disable_affected; } set { _analyzer_disable_affected = value; _event_settings_changed(); } }
  2076. public bool Analyzer_Disable_All { get { return _analyzer_disable_all; } set { _analyzer_disable_all = value; _event_settings_changed(); } }
  2077. public int Analyzer_Disable_Duration { get { return _analyzer_disable_duration; } set { _analyzer_disable_duration = value; _event_settings_changed(); } }
  2078. // ED settinds
  2079. public string ED_Log_File { get { return _ed_log_file; } set { _ed_log_file = value; _event_settings_changed(); } }
  2080. public clsSettings(string filename)
  2081. {
  2082. _settings_file_name = filename;
  2083. LoadSettings();
  2084. }
  2085. public clsSettings() : this(DEFAULT_SETTINGS_FILENAME) { }
  2086. public void LoadSettings()
  2087. {
  2088. this.Collect_Interval = 10;
  2089. this.Collect_Log_File = DEFAULT_FILENAME;
  2090. this.Analyzer_Vote_Threshold = 2.5;
  2091. this.Analyzer_Relevant_Entries = 10;
  2092. this.Analyzer_Disable_Duration = 300;
  2093. this.Analyzer_Disable_All = false;
  2094. this.Analyzer_Disable_Affected = true;
  2095. this.Accounts = new List<clsCredentials>();
  2096. this.ED_Log_File = DEFAULT_FILENAME;
  2097. /*
  2098. FileStream file = new FileStream(_settings_file_name, FileMode.OpenOrCreate, FileAccess.Read);
  2099. StreamReader sr = new StreamReader(file);
  2100. string data = sr.ReadToEnd();
  2101. sr.Close();
  2102. file.Close();
  2103. */
  2104. Properties.Settings.Default.Reload();
  2105. string data = Properties.Settings.Default.AppSettings;
  2106. if (data == string.Empty)
  2107. return;
  2108. else
  2109. {
  2110. string accounts = _get_section(data, "ACCOUNTS {", "}");
  2111. if (accounts != null)
  2112. {
  2113. string[] individuals = accounts.Split(',');
  2114. foreach (string acct in individuals)
  2115. {
  2116. string[] UP = acct.Split(':');
  2117. AddAccount(new clsCredentials(UP[0], UP[1]));
  2118. }
  2119. }
  2120. try { this.Collect_Interval = int.Parse(_get_section(data, "C_I{", "}")); }
  2121. catch { }
  2122. try { this.Collect_Log_File = _get_section(data, "C_L{", "}"); }
  2123. catch { }
  2124. try { this.Analyzer_Vote_Threshold = double.Parse(_get_section(data, "A_V{", "}")); }
  2125. catch { }
  2126. try { this.Analyzer_Relevant_Entries = int.Parse(_get_section(data, "A_R{", "}")); }
  2127. catch { }
  2128. try { this.Analyzer_Disable_All = bool.Parse(_get_section(data, "A_D1{", "}")); }
  2129. catch { }
  2130. try { this.Analyzer_Disable_Affected = bool.Parse(_get_section(data, "A_D2{", "}")); }
  2131. catch { }
  2132. try { this.ED_Log_File = _get_section(data, "ED_L{", "}"); }
  2133. catch { }
  2134. }
  2135. }
  2136. public void SaveSettings()
  2137. {
  2138. string data = null;
  2139. data = "ACCOUNTS {";
  2140. foreach (clsCredentials account in Accounts)
  2141. data += account.Username + ":" + account.Password + ",";
  2142. data = data.Substring(0, data.Length - 1);
  2143. data += "}";
  2144. data += "C_I{" + this.Collect_Interval.ToString() + "}\n";
  2145. data += "C_L{" + this.Collect_Log_File + "}\n";
  2146. data += "A_V{" + this.Analyzer_Vote_Threshold.ToString() + "}\n";
  2147. data += "A_R{" + this.Analyzer_Relevant_Entries.ToString() + "}\n";
  2148. data += "A_D1{" + this.Analyzer_Disable_All.ToString() + "}\n";
  2149. data += "A_D2{" + this.Analyzer_Disable_Affected.ToString() + "}\n";
  2150. data += "A_D3{" + this.Analyzer_Disable_Duration.ToString() + "}\n";
  2151. data += "ED_L{" + this.ED_Log_File + "}\n";
  2152. Properties.Settings.Default.AppSettings = data;
  2153. Properties.Settings.Default.Save();
  2154. //File.WriteAllText(_settings_file_name, data);
  2155. }
  2156. public void AddAccount(clsCredentials Account)
  2157. {
  2158. if (Account == null)
  2159. return;
  2160. RemoveAccount(Account);
  2161. this.Accounts.Add(Account);
  2162. _event_account_added(Account);
  2163. }
  2164. public void RemoveAccount(clsCredentials Account)
  2165. {
  2166. if (Account == null)
  2167. return;
  2168. int i = 0;
  2169. while (i < Accounts.Count)
  2170. {
  2171. if (Accounts[i].Username == Account.Username)
  2172. {
  2173. _event_account_removed(Accounts[i]);
  2174. Accounts.RemoveAt(i);
  2175. }
  2176. else i++;
  2177. }
  2178. }
  2179. private string _get_section(string data, string left, string right)
  2180. {
  2181. int i_left = -1;
  2182. int i_right = -1;
  2183. i_left = data.IndexOf(left);
  2184. if (i_left == -1)
  2185. return null;
  2186. i_left += left.Length;
  2187. i_right = data.IndexOf(right, i_left);
  2188. if (i_right == -1)
  2189. return null;
  2190. return data.Substring(i_left, i_right - i_left);
  2191. }
  2192. // public methods
  2193. public clsCredentials GetAccountByUsername( string username )
  2194. {
  2195. foreach (clsCredentials acct in Accounts)
  2196. if (acct.Username == username)
  2197. return acct;
  2198. return null;
  2199. }
  2200. // events!
  2201. public delegate void AccountAddedHandler(object sender, clsCredentials Account);
  2202. public event AccountAddedHandler OnAccountAdded;
  2203. private void _event_account_added(clsCredentials Account)
  2204. {
  2205. if (OnAccountAdded != null)
  2206. OnAccountAdded(this, Account);
  2207. }
  2208. public delegate void AccountRemovedHandler(object sender, clsCredentials Account);
  2209. public event AccountRemovedHandler OnAccountRemoved;
  2210. private void _event_account_removed(clsCredentials Account)
  2211. {
  2212. if (OnAccountRemoved != null)
  2213. OnAccountRemoved(this, Account);
  2214. }
  2215. public delegate void SettingsChangedHandler(object sender);
  2216. public event SettingsChangedHandler OnSettingsChanged;
  2217. private void _event_settings_changed()
  2218. {
  2219. if (OnSettingsChanged != null)
  2220. OnSettingsChanged(this);
  2221. }
  2222. }
  2223. }