Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Google.GData.YouTube;
- using Google.GData.Extensions;
- using Google.YouTube;
- using System.Threading;
- using System.IO;
- using System.Xml;
- using System.Runtime.InteropServices;
- using System.Timers;
- using System.Net;
- using System.Net.Sockets;
- using System.Web;
- using mshtml;
- namespace TubeGuardian
- {
- /* Bot-ish class that contantly maintains an updated dictionary of clsDataPoint objects */
- public class clsStatMonger
- {
- // private data members
- private List<clsCredentials> _accounts = new List<clsCredentials>();
- private List<clsVideoFeedReader> _feed_readers = new List<clsVideoFeedReader>();
- private List<clsVideoEntry> _initial_dataset = new List<clsVideoEntry>();
- private List<clsVideoEntry> _current_dataset = new List<clsVideoEntry>();
- private Dictionary<string, List<clsDataPoint>> _historical_data = new Dictionary<string, List<clsDataPoint>>();
- private System.Timers.Timer _update_timer;
- private clsFileLogger _file_logger = null;
- private string _dev_key = string.Empty;
- private string _app_name = string.Empty;
- private clsSettings _settings;
- // constructor
- public clsStatMonger(string DeveloperKey, string ApplicationName, List<clsCredentials> Credentials, clsSettings settings)
- {
- _file_logger = new clsFileLogger("CollectorData.log");
- _settings = settings;
- _settings.OnAccountAdded += new clsSettings.AccountAddedHandler(_settings_OnAccountAdded);
- _settings.OnAccountRemoved += new clsSettings.AccountRemovedHandler(_settings_OnAccountRemoved);
- _dev_key = DeveloperKey;
- _app_name = ApplicationName;
- this.Enabled = false;
- _update_timer = new System.Timers.Timer();
- _update_timer.Enabled = false;
- _update_timer.Interval = _settings.Collect_Interval * 1000 * 60;
- _update_timer.Elapsed += new ElapsedEventHandler(_update_timer_Elapsed);
- _accounts = Credentials;
- foreach (clsCredentials c in _accounts)
- {
- clsVideoFeedReader new_feed = new clsVideoFeedReader(DeveloperKey, ApplicationName, c.Username);
- if (c.Password != string.Empty && c.Password != "-")
- new_feed.SetCredentials(c.Username, c.Password);
- new_feed.OnEntryFetched += new clsVideoFeedReader.EntryFetchedHandler(new_feed_OnEntryFetched);
- new_feed.OnStatusChange += new clsVideoFeedReader.StatusChangeHandler(new_feed_OnStatusChange);
- _feed_readers.Add(new_feed);
- }
- }
- void _settings_OnAccountRemoved(object sender, clsCredentials Account)
- {
- RemoveAccount(Account);
- }
- void _settings_OnAccountAdded(object sender, clsCredentials Account)
- {
- AddAccount(Account);
- }
- // public methods
- public void Enable()
- {
- if (this.Enabled)
- return;
- this.Enabled = true;
- _update_videos();
- _update_timer.Interval = _settings.Collect_Interval;
- _update_timer.Enabled = true;
- }
- public void Disable()
- {
- this.Enabled = false;
- _update_timer.Enabled = false;
- }
- public void Update()
- {
- _update_videos();
- }
- public void AddAccount(clsCredentials Account)
- {
- foreach (clsVideoFeedReader r in _feed_readers)
- if (r.Username == Account.Username)
- return;
- clsVideoFeedReader new_feed = new clsVideoFeedReader(_dev_key, _app_name, Account.Username);
- if (Account.Password != "-")
- new_feed.SetCredentials(Account.Username, Account.Password);
- new_feed.OnEntryFetched += new clsVideoFeedReader.EntryFetchedHandler(new_feed_OnEntryFetched);
- new_feed.OnStatusChange += new clsVideoFeedReader.StatusChangeHandler(new_feed_OnStatusChange);
- new_feed.OnException += new clsVideoFeedReader.ExceptionHandler(new_feed_OnException);
- _feed_readers.Add(new_feed);
- }
- public void RemoveAccount(clsCredentials Account)
- {
- int i = 0;
- while (i < _feed_readers.Count)
- {
- if (_feed_readers[i].Username == Account.Username)
- {
- _feed_readers[i].Dispose();
- _feed_readers.RemoveAt(i);
- }
- else
- i++;
- }
- }
- // public events
- public delegate void EntryAddedEventHandler(object Sender, clsVideoEntry Entry);
- public event EntryAddedEventHandler OnEntryAdded;
- private void _entry_added(clsVideoEntry Entry)
- {
- if (_file_logger != null)
- _file_logger.appendFile(Entry.ToString());
- if (OnEntryAdded != null)
- OnEntryAdded(this, Entry);
- }
- public delegate void EntryUpdatedEventHandler(object Sender, clsDataPoint DataPoint, clsVideoEntry Entry);
- public event EntryUpdatedEventHandler OnEntryUpdated;
- private void _entry_updated(clsDataPoint DataPoint, clsVideoEntry Entry)
- {
- if (_file_logger != null)
- _file_logger.appendFile(DataPoint.ToString());
- if (OnEntryUpdated != null)
- OnEntryUpdated(this, DataPoint, Entry);
- }
- public delegate void FeedReaderUpdatedEventHandler(object Sender, clsVideoFeedReader.enumFeedReaderState status);
- public event FeedReaderUpdatedEventHandler OnFeedReaderUpdated;
- private void _feed_reader_updated(object sender, clsVideoFeedReader.enumFeedReaderState status)
- {
- if (OnFeedReaderUpdated != null)
- OnFeedReaderUpdated(sender, status);
- }
- public delegate void FeedReaderExceptionEventHandler(object Sender, string exception);
- public event FeedReaderExceptionEventHandler OnFeedReaderException;
- private void _feed_reader_exception(object sender, string exception)
- {
- if (OnFeedReaderException != null)
- OnFeedReaderException(sender, exception);
- }
- // private methods
- private void _update_timer_Elapsed(object sender, ElapsedEventArgs e)
- {
- if (this.Enabled == false)
- return;
- _update_timer.Enabled = false;
- _update_timer.Interval = _settings.Collect_Interval * 1000 * 60;
- _update_timer.Enabled = true;
- _update_videos();
- }
- private void new_feed_OnStatusChange(object Sender, clsVideoFeedReader.enumFeedReaderState NewState)
- {
- _feed_reader_updated(Sender, NewState);
- }
- private void new_feed_OnEntryFetched(object Sender, clsVideoEntry Entry)
- {
- clsVideoEntry initial_entry;
- if ((initial_entry = _GetEntryByIdFromList(_initial_dataset, Entry.VideoID)) == null)
- {
- _initial_dataset.Add(Entry);
- _current_dataset.Add(Entry);
- _entry_added(Entry);
- }
- else
- {
- clsVideoEntry CurrentEntry = _GetEntryByIdFromList(_current_dataset, Entry.VideoID);
- if (CurrentEntry == null)
- {
- _current_dataset.Add(Entry);
- _compare_entries(initial_entry, Entry);
- }
- else
- {
- _current_dataset.Remove(CurrentEntry);
- _current_dataset.Add(Entry);
- _compare_entries(CurrentEntry, Entry);
- }
- }
- }
- private void new_feed_OnException(object Sender, Exception e)
- {
- _feed_reader_exception(Sender, e.Message);
- }
- private void _compare_entries(clsVideoEntry OldEntry, clsVideoEntry NewEntry)
- {
- if (OldEntry.VideoID != NewEntry.VideoID)
- return;
- _compare_stat(OldEntry.AverageRating, NewEntry.AverageRating, clsDataPointField.VideoDataFields.AVERAGE_RATING, NewEntry);
- _compare_stat(OldEntry.CommentCount, NewEntry.CommentCount, clsDataPointField.VideoDataFields.COMMENT_COUNT, NewEntry);
- _compare_stat(OldEntry.FavoritedCount, NewEntry.FavoritedCount, clsDataPointField.VideoDataFields.FAVORITED_COUNT, NewEntry);
- _compare_stat(OldEntry.Raters, NewEntry.Raters, clsDataPointField.VideoDataFields.RATERS, NewEntry);
- _compare_stat(OldEntry.ViewsCount, NewEntry.ViewsCount, clsDataPointField.VideoDataFields.VIEWS, NewEntry);
- }
- private void _compare_stat(double Old, double New, clsDataPointField.VideoDataFields Field, clsVideoEntry Entry)
- {
- if (Old == New)
- return;
- else
- {
- clsDataPoint new_datapoint = new clsDataPoint(Old, New, new clsDataPointField(Field), Entry.VideoID);
- if (_historical_data.ContainsKey(Entry.VideoID))
- _historical_data[Entry.VideoID].Add(new_datapoint);
- else
- {
- List<clsDataPoint> new_dp_list = new List<clsDataPoint>();
- new_dp_list.Add(new_datapoint);
- _historical_data.Add(Entry.VideoID, new_dp_list);
- }
- _entry_updated(new_datapoint, Entry);
- }
- }
- private clsVideoEntry _GetEntryByIdFromList(List<clsVideoEntry> Entries, string VideoID)
- {
- int index = Entries.FindIndex(delegate(clsVideoEntry e) { return e.VideoID.Equals(VideoID); });
- return (index == -1) ? null : Entries[index];
- }
- private void _update_videos()
- {
- foreach (clsVideoFeedReader r in _feed_readers)
- if (!r.IsBusy)
- r.GetVideosModifiedSince(r.Updated);
- }
- // public properties
- public bool Enabled { get; private set; }
- public List<clsVideoEntry> CurrentDataSet
- {
- get { return new List<clsVideoEntry>(_current_dataset); }
- }
- public List<clsVideoEntry> InitialDataSet
- {
- get { return _initial_dataset; }
- }
- public Dictionary<string, List<clsDataPoint>> HistoricalDataPoints
- {
- get { return _historical_data; }
- }
- public clsFileLogger FileLogger
- {
- get { return _file_logger; }
- set { _file_logger = value; }
- }
- public List<clsVideoEntry> GetVideosByUsername(string username)
- {
- List<clsVideoEntry> ret = new List<clsVideoEntry>();
- foreach (clsVideoEntry e in _current_dataset)
- if (e.Account.Username == username)
- ret.Add(e);
- return ret;
- }
- public List<clsVideoFeedReader> FeedReaders { get { return _feed_readers; } }
- }
- /* Type-ish class to hold youtube usernames, and passwords */
- public class clsCredentials
- {
- public clsCredentials(string Username, string Password) { this.Username = Username; this.Password = Password; }
- public clsCredentials() { }
- public string Username
- {
- get;
- set;
- }
- public string Password
- {
- get;
- set;
- }
- }
- /* Type-ish class to hold data points (old/new value + data field) */
- public class clsDataPoint
- {
- public clsDataPoint()
- {
- this.Old = this.New = 0;
- this.Field = new clsDataPointField();
- this.Time = DateTime.Now;
- }
- public clsDataPoint(double OldValue, double NewValue, clsDataPointField DataField, string VideoID)
- {
- this.Old = OldValue;
- this.New = NewValue;
- this.Field = DataField;
- this.Time = DateTime.Now;
- this.VideoID = VideoID;
- }
- public override string ToString()
- {
- string[] values = {"upd : d{" + Time.ToShortDateString() + "}", "t{" + Time.ToShortTimeString() + "}", "vId{" + VideoID, Field.Field.ToString() + "}", "old{" + Old.ToString() + "}", "new{" + New.ToString() + "}" };
- return string.Join(",", values);
- }
- public clsDataPointField Field { get; set; }
- public double Old { get; set; }
- public double New { get; set; }
- public double Delta { get { return New - Old; } }
- public DateTime Time { get; set; }
- public string VideoID { get; set; }
- }
- /* Type-ish class to hold data field values and convert to string equivalents */
- public class clsDataPointField
- {
- public enum VideoDataFields
- {
- UNKNOWN = -1,
- VIEWS,
- RATERS,
- AVERAGE_RATING,
- COMMENT_COUNT,
- FAVORITED_COUNT
- }
- public clsDataPointField() { this.Field = VideoDataFields.UNKNOWN; }
- public clsDataPointField(VideoDataFields f) { this.Field = f; }
- public VideoDataFields Field { get; set; }
- public override string ToString()
- {
- switch (this.Field)
- {
- case VideoDataFields.AVERAGE_RATING:
- return "Average Rating";
- case VideoDataFields.COMMENT_COUNT:
- return "Comment Count";
- case VideoDataFields.FAVORITED_COUNT:
- return "Favorited Count";
- case VideoDataFields.RATERS:
- return "Raters";
- case VideoDataFields.UNKNOWN:
- return "Unknown";
- case VideoDataFields.VIEWS:
- return "Views";
- default:
- return "Error";
- }
- }
- }
- /* Wrapper class to access the information needed from YouTubeEntry objects */
- public class clsVideoEntry
- {
- private YouTubeEntry _yt_entry = null;
- // constructor
- public clsVideoEntry(YouTubeEntry e)
- {
- _yt_entry = e;
- }
- public override string ToString()
- {
- 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() + "}" };
- return string.Join(",", values);
- }
- public override bool Equals(object obj)
- {
- clsVideoEntry e = (clsVideoEntry)obj;
- return this.VideoID.Equals(e.VideoID);
- }
- public override int GetHashCode()
- {
- return this.Account.Username.GetHashCode();
- }
- // public properties
- public bool IsNull
- {
- get { return (_yt_entry == null); }
- }
- public int Raters
- {
- get { try { return _yt_entry.Rating.NumRaters; } catch { return 0; } }
- }
- public double AverageRating
- {
- get { try { return _yt_entry.Rating.Average; } catch { return 0; } }
- }
- public int ViewsCount
- {
- get { try { return int.Parse(_yt_entry.Statistics.ViewCount); } catch { return 0; } }
- }
- public int CommentCount
- {
- get { try { return _yt_entry.Comments.FeedLink.CountHint; } catch { return 0; } }
- }
- public int FavoritedCount
- {
- get { try { return int.Parse(_yt_entry.Statistics.FavoriteCount); } catch { return 0; } }
- }
- public string VideoID
- {
- get { try { return _yt_entry.VideoId; } catch { return string.Empty; } }
- }
- public string Title
- {
- get { try { return _yt_entry.Title.Text; } catch { return string.Empty; } }
- }
- public YouTubeEntry YouTubeEntry
- {
- get { return _yt_entry; }
- }
- public DateTime Time { get; set; }
- public clsCredentials Account { get; set; }
- }
- /* Utility class for reading video feeds asynchronously for a single account */
- public class clsVideoFeedReader
- {
- private class QueryArgs
- {
- public YouTubeService Service { get; set; }
- public YouTubeQuery Query { get; set; }
- }
- private class QueryReturn
- {
- public YouTubeFeed Feed { get; set; }
- public Exception Exception { get; set; }
- public YouTubeQuery NextQuery { get; set; }
- }
- public enum enumFeedReaderState
- {
- ERROR = -1,
- IDLE,
- GETTING_FIRST_CHUNK,
- GOT_FIRST_CHUNK,
- GETTING_ANOTHER_CHUNK,
- GOT_ANOTHER_CHUUNK
- }
- private enumFeedReaderState _state = enumFeedReaderState.IDLE;
- private YouTubeService _yt_service = null;
- private string _username = string.Empty;
- private string _password = string.Empty;
- private string _dev_key = string.Empty;
- private string _app_name = string.Empty;
- private int _retrieved = 0;
- private int _max_retry_query = 3;
- private int _current_retry_query = 1;
- private System.ComponentModel.BackgroundWorker _query_thread = new System.ComponentModel.BackgroundWorker();
- private DateTime _last_updated = DateTime.MinValue;
- public clsVideoFeedReader(string DevelopersKey, string ApplicationName, string Username)
- {
- _dev_key = DevelopersKey;
- _app_name = ApplicationName;
- _username = Username;
- _yt_service = new YouTubeService(ApplicationName, string.Empty, DevelopersKey);
- _query_thread.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_query_thread_RunWorkerCompleted);
- _query_thread.DoWork += new System.ComponentModel.DoWorkEventHandler(_query_thread_DoWork);
- }
- public clsVideoFeedReader(string DevelopersKey, string ApplicationName, string Username, string Password)
- : this(DevelopersKey, ApplicationName, Username)
- {
- if (_password != "-")
- {
- _password = Password;
- SetCredentials(Username, Password);
- }
- }
- // public methods
- public void SetCredentials(string Username, string Password)
- {
- _username = Username;
- _password = Password;
- _yt_service.setUserCredentials(Username, Password);
- }
- public void GetVideos()
- {
- YouTubeQuery query = new YouTubeQuery(YouTubeQuery.CreateUserUri(_username));
- query.NumberToRetrieve = 50;
- _retrieved = 0;
- _current_retry_query = 1;
- _status_changed(enumFeedReaderState.GETTING_FIRST_CHUNK);
- _last_updated = DateTime.Now;
- _do_query(query);
- }
- public void GetVideosModifiedSince(DateTime When)
- {
- YouTubeQuery query = new YouTubeQuery(YouTubeQuery.CreateUserUri(_username));
- query.NumberToRetrieve = 50;
- query.ModifiedSince = When;
- _retrieved = 0;
- _current_retry_query = 1;
- _status_changed(enumFeedReaderState.GETTING_FIRST_CHUNK);
- _last_updated = DateTime.Now;
- _do_query(query);
- }
- public void Dispose()
- {
- _query_thread.Dispose();
- OnEntryFetched = null;
- OnException = null;
- OnProgress = null;
- OnQueryRetry = null;
- OnStatusChange = null;
- }
- // private methods
- private void _do_query(YouTubeQuery q)
- {
- if (_query_thread.IsBusy)
- return;
- QueryArgs qa = new QueryArgs();
- qa.Query = q;
- qa.Service = _yt_service;
- _query_thread.RunWorkerAsync(qa);
- }
- private void _query_thread_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
- {
- QueryArgs qa = e.Argument as QueryArgs;
- QueryReturn qr = new QueryReturn();
- qr.Exception = null;
- qr.Feed = null;
- try
- {
- YouTubeFeed feed = qa.Service.Query(qa.Query);
- qr.Feed = feed;
- }
- catch (Exception exception)
- {
- qr.Exception = exception;
- qr.NextQuery = qa.Query;
- }
- e.Result = qr;
- }
- private void _query_thread_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
- {
- QueryReturn qr = e.Result as QueryReturn;
- YouTubeFeed feed = qr.Feed;
- if (feed != null)
- {
- _retrieved += feed.Entries.Count;
- foreach (YouTubeEntry entry in feed.Entries)
- _entry_fetched(entry);
- if (_state == enumFeedReaderState.GETTING_FIRST_CHUNK || _state == enumFeedReaderState.GETTING_ANOTHER_CHUNK)
- _status_changed(_state + 1);
- if (feed.NextChunk != null)
- {
- _progress(_retrieved, feed.TotalResults);
- _status_changed(enumFeedReaderState.GETTING_ANOTHER_CHUNK);
- _do_query(new YouTubeQuery(feed.NextChunk));
- }
- else
- {
- _progress(1, 1);
- _status_changed(enumFeedReaderState.IDLE);
- }
- }
- else
- {
- _exception(qr.Exception);
- if (_current_retry_query < _max_retry_query)
- {
- _current_retry_query++;
- if (qr.NextQuery != null)
- {
- _status_changed(_state);
- _do_query(new YouTubeQuery(qr.NextQuery.Uri.AbsoluteUri));
- }
- else
- {
- _progress(1, 1);
- _status_changed(enumFeedReaderState.ERROR);
- }
- }
- else
- {
- _progress(1, 1);
- _status_changed(enumFeedReaderState.ERROR);
- }
- }
- }
- // public events
- public delegate void StatusChangeHandler(object Sender, enumFeedReaderState NewState);
- public event StatusChangeHandler OnStatusChange;
- private void _status_changed(enumFeedReaderState state)
- {
- _state = state;
- if (OnStatusChange != null)
- OnStatusChange(this, state);
- }
- public delegate void EntryFetchedHandler(object Sender, clsVideoEntry Entry);
- public event EntryFetchedHandler OnEntryFetched;
- private void _entry_fetched(YouTubeEntry Entry)
- {
- if (OnEntryFetched != null)
- {
- clsVideoEntry nEntry = new clsVideoEntry(Entry);
- nEntry.Time = DateTime.Now;
- nEntry.Account = new clsCredentials(_username, _password);
- OnEntryFetched(this, nEntry);
- }
- }
- public delegate void ProgressHandler(object Sender, int Current, int Total);
- public event ProgressHandler OnProgress;
- private void _progress(int Current, int Total)
- {
- if (OnProgress != null)
- OnProgress(this, Current, Total);
- }
- public delegate void QueryRetryHandler(object Sender, Exception e);
- public event QueryRetryHandler OnQueryRetry;
- private void _query_retry(Exception e)
- {
- if (OnQueryRetry != null)
- OnQueryRetry(this, e);
- }
- public delegate void ExceptionHandler(object Sender, Exception e);
- public event ExceptionHandler OnException;
- private void _exception(Exception e)
- {
- if (OnException != null)
- OnException(this, e);
- }
- // public properties
- public string StateString
- {
- get
- {
- switch (_state)
- {
- case enumFeedReaderState.ERROR:
- return "Error";
- case enumFeedReaderState.GETTING_ANOTHER_CHUNK:
- return "Getting another chunk";
- case enumFeedReaderState.GETTING_FIRST_CHUNK:
- return "Getting first chunk";
- case enumFeedReaderState.GOT_ANOTHER_CHUUNK:
- return "Got another chunk";
- case enumFeedReaderState.GOT_FIRST_CHUNK:
- return "Got first chunk";
- case enumFeedReaderState.IDLE:
- return "Idle";
- default:
- return "Error";
- }
- }
- }
- public enumFeedReaderState State
- {
- get { return _state; }
- }
- public int MaxRetries
- {
- get { return _max_retry_query; }
- set { _max_retry_query = value; }
- }
- public bool IsBusy
- {
- get { return _query_thread.IsBusy; }
- }
- public DateTime Updated
- {
- get { return _last_updated; }
- }
- public string Username
- {
- get { return _username; }
- }
- }
- /* Math class for crunching all of the numbers in any given data set */
- public class clsStatMasher
- {
- private List<clsVideoEntry> _initial_dataset = null;
- private Dictionary<string, List<clsDataPoint>> _historical_data = null;
- public clsStatMasher() {}
- public clsStatMasher(List<clsVideoEntry> InitialDataSet, Dictionary<string, List<clsDataPoint>> HistoricalData)
- {
- _initial_dataset = InitialDataSet;
- _historical_data = HistoricalData;
- }
- // public methods
- public List<clsDataPoint> GetDataPointsByID(string VideoID)
- {
- if (_historical_data.ContainsKey(VideoID))
- return _historical_data[VideoID];
- else
- return null;
- }
- public clsVideoEntry GetInitialDataByID(string VideoID)
- {
- if (_initial_dataset == null)
- return null;
- int index = _initial_dataset.FindIndex(delegate(clsVideoEntry e) { return e.VideoID.Equals(VideoID); });
- if (index >= 0)
- return _initial_dataset[index];
- else
- return null;
- }
- public double AverageNewRatingByID(string VideoID)
- {
- clsVideoEntry InitialData = GetInitialDataByID(VideoID);
- List<clsDataPoint> HistoricalData = GetDataPointsByID(VideoID);
- if (InitialData == null || HistoricalData == null || HistoricalData.Count == 0)
- return 0;
- double[] A = { InitialData.AverageRating, -1 };
- double[] N = { InitialData.Raters, -1 };
- int counted = 0;
- for (int i = HistoricalData.Count - 1; i >= 0; i--)
- {
- if (A[1] != -1 && N[1] != -1)
- break;
- if (HistoricalData[i].Field.Field == clsDataPointField.VideoDataFields.RATERS)
- {
- if (N[1] == -1)
- N[1] = HistoricalData[i].New;
- counted += (int)HistoricalData[i].Delta;
- }
- if (HistoricalData[i].Field.Field == clsDataPointField.VideoDataFields.AVERAGE_RATING && A[1] == -1)
- A[1] = HistoricalData[i].New;
- }
- if (counted == 0)
- return 0;
- if (A[1] == -1)
- return 0;
- return _calc_average_new_rating(A[0], A[1], N[0], N[1]);
- }
- public KeyValuePair<int,double> AverageNewRatingByID(string VideoID, int numMostRecentVotes)
- {
- clsVideoEntry InitialData = GetInitialDataByID(VideoID);
- List<clsDataPoint> HistoricalData = GetDataPointsByID(VideoID);
- if (InitialData == null || HistoricalData == null || HistoricalData.Count == 0)
- return new KeyValuePair<int,double>(0,0);
- double[] A = { 0, -1 };
- double[] N = { 0, -1 };
- int counted = 0;
- for (int i = HistoricalData.Count - 1; i >= 0; i--)
- {
- if ((counted >= numMostRecentVotes) && A[1] != -1 && N[1] != 1)
- break;
- if (HistoricalData[i].Field.Field == clsDataPointField.VideoDataFields.RATERS)
- {
- if( N[1] == -1)
- N[1] = HistoricalData[i].New;
- N[0] = HistoricalData[i].Old;
- counted += (int)HistoricalData[i].Delta;
- }
- if (HistoricalData[i].Field.Field == clsDataPointField.VideoDataFields.AVERAGE_RATING)
- {
- if (A[1] == -1)
- A[1] = HistoricalData[i].New;
- A[0] = HistoricalData[i].Old;
- }
- }
- if (counted == 0)
- return new KeyValuePair<int, double>(0, 0);
- if (A[1] == -1)
- return new KeyValuePair<int, double>(0, 0);
- return new KeyValuePair<int,double>(counted, _calc_average_new_rating(A[0], A[1], N[0], N[1]));
- }
- public void CleanUp()
- {
- _initial_dataset = null;
- _historical_data = null;
- }
- public double GetMovedStatByField(string VideoID, clsDataPointField.VideoDataFields field)
- {
- clsVideoEntry InitialData = GetInitialDataByID(VideoID);
- List<clsDataPoint> HistoricalData = GetDataPointsByID(VideoID);
- if (InitialData == null || HistoricalData == null || HistoricalData.Count == 0)
- return 0;
- double ret = 0;
- int num = 0;
- foreach (clsDataPoint d in HistoricalData)
- {
- if (d.Field.Field == field)
- {
- if (d.Field.Field == clsDataPointField.VideoDataFields.AVERAGE_RATING)
- num++;
- else
- ret += d.Delta;
- }
- }
- if (field == clsDataPointField.VideoDataFields.AVERAGE_RATING)
- return num;
- else
- return ret;
- }
- // private methods
- private double _calc_average_new_rating(double old_average, double new_average, double old_raters, double new_raters)
- {
- System.Diagnostics.Debug.Print((((new_average * new_raters) - (old_average * old_raters)) / (new_raters - old_raters)).ToString());
- return ((new_average * new_raters) - (old_average * old_raters)) / (new_raters - old_raters);
- }
- // public properties
- public List<clsVideoEntry> InitialDataSet
- {
- get { return _initial_dataset; }
- set { _initial_dataset = value; }
- }
- public Dictionary<string, List<clsDataPoint>> HistoricalDataPoints
- {
- get { return _historical_data; }
- set { _historical_data = value; }
- }
- }
- /* Utility class to check/edit video settings */
- // sorry, this it too dangerous to give out - EDITED
- /* Utility class to handle multiple clsSettingsManager objects */
- public class clsED
- {
- private List<clsSettingsManager> _settings_managers = new List<clsSettingsManager>();
- private clsFileLogger _logger = null;
- private clsSettings _settings;
- private bool _in_action = false;
- public clsED()
- {
- }
- public clsED(clsSettings Settings)
- {
- _settings = Settings;
- _settings.OnAccountAdded += new clsSettings.AccountAddedHandler(_settings_OnAccountAdded);
- _settings.OnAccountRemoved += new clsSettings.AccountRemovedHandler(_settings_OnAccountRemoved);
- if (_settings.ED_Log_File != null && _settings.ED_Log_File != string.Empty)
- _logger = new clsFileLogger(_settings.ED_Log_File);
- foreach (clsCredentials Account in _settings.Accounts)
- {
- if (Account.Password == "-")
- continue;
- clsSettingsManager sm = new clsSettingsManager(Account.Username, Account.Password);
- sm.OnException += new clsSettingsManager.ExceptionEventHandler(sm_OnException);
- sm.OnFailure += new clsSettingsManager.FailureEventHandler(sm_OnFailure);
- sm.OnStatusChange += new clsSettingsManager.StatusEventHandler(sm_OnStatusChange);
- sm.OnSuccess += new clsSettingsManager.SuccessEventHandler(sm_OnSuccess);
- _settings_managers.Add(sm);
- }
- }
- void _settings_OnAccountRemoved(object sender, clsCredentials Account)
- {
- RemoveAccount(Account);
- }
- void _settings_OnAccountAdded(object sender, clsCredentials Account)
- {
- AddAccount(Account);
- }
- void sm_OnSuccess(object sender, clsSettingsManager.FailureCodes f)
- {
- clsSettingsManager thisSM = (clsSettingsManager)sender;
- if (_logger != null)
- _logger.appendFile(DateTime.Now.ToString() + "-" + thisSM.Username + " Success @ " + f.ToString());
- }
- void sm_OnStatusChange(object sender, clsSettingsManager.InternalState s)
- {
- _in_action = false;
- if (s == clsSettingsManager.InternalState.idle)
- {
- foreach (clsSettingsManager sm in _settings_managers)
- {
- _in_action = (sm.State != clsSettingsManager.InternalState.idle);
- break;
- }
- }
- clsSettingsManager thisSM = (clsSettingsManager)sender;
- System.Diagnostics.Debug.WriteLine(thisSM.Username + " Status changed to " + s.ToString());
- }
- void sm_OnFailure(object sender, clsSettingsManager.FailureCodes f)
- {
- clsSettingsManager thisSM = (clsSettingsManager)sender;
- if (_logger != null)
- _logger.appendFile(DateTime.Now.ToString() + "-" + thisSM.Username + " Failed @ " + f.ToString());
- }
- void sm_OnException(object sender, Exception e)
- {
- clsSettingsManager thisSM = (clsSettingsManager)sender;
- if (_logger != null)
- _logger.appendFile(DateTime.Now.ToString() + "-" + thisSM.Username + " Exception: " + e.Message);
- }
- private void AddAccount(clsCredentials Account)
- {
- foreach (clsSettingsManager sm in _settings_managers)
- if (sm.Username == Account.Username)
- return;
- if (Account.Password == "-")
- return;
- clsSettingsManager newSM = new clsSettingsManager(Account.Username, Account.Password);
- newSM.OnSuccess += new clsSettingsManager.SuccessEventHandler(sm_OnSuccess);
- newSM.OnFailure += new clsSettingsManager.FailureEventHandler(sm_OnFailure);
- newSM.OnException += new clsSettingsManager.ExceptionEventHandler(sm_OnException);
- newSM.OnStatusChange += new clsSettingsManager.StatusEventHandler(sm_OnStatusChange);
- _settings_managers.Add(newSM);
- }
- private void RemoveAccount(clsCredentials Account)
- {
- int i = 0;
- while (i < _settings_managers.Count)
- {
- if (_settings_managers[i].Username == Account.Username)
- {
- _settings_managers[i].Dispose();
- _settings_managers.RemoveAt(i);
- }
- else
- i++;
- }
- }
- public void ChangeAccountRatings(clsCredentials Account, string VideoID, bool Enable)
- {
- foreach (clsSettingsManager sm in _settings_managers)
- {
- if (sm.Username == Account.Username)
- {
- if (Enable)
- sm.EnableVideo(VideoID);
- else
- sm.DisableVideo(VideoID);
- _raise_started_action();
- return;
- }
- }
- }
- public void ChangeAccountRatings(clsCredentials Account, List<clsVideoEntry> Videos, bool Enable)
- {
- foreach (clsSettingsManager sm in _settings_managers)
- {
- if (sm.Username == Account.Username)
- {
- if (Enable)
- {
- foreach (clsVideoEntry e in Videos)
- sm.EnableVideo(e.VideoID);
- }
- else
- {
- foreach (clsVideoEntry e in Videos)
- sm.DisableVideo(e.VideoID);
- }
- _raise_started_action();
- return;
- }
- }
- }
- public delegate void StartedActionEventHandler(object Sender);
- public event StartedActionEventHandler OnStartedAction;
- private void _raise_started_action()
- {
- if (_in_action == true)
- return;
- if (OnStartedAction != null)
- OnStartedAction(this);
- }
- public List<clsSettingsManager> SettingsManagers { get { return _settings_managers; } }
- public clsFileLogger Logger { set { _logger = value; } }
- }
- /* Utility class that write to file */
- public class clsFileLogger
- {
- private string _file_name = string.Empty;
- public delegate void ErrorEventHandler(object sender, IOException e);
- public event ErrorEventHandler OnError;
- protected virtual void Error(IOException e)
- {
- if (OnError != null)
- OnError(this, e);
- }
- public clsFileLogger(string filename)
- {
- _file_name = filename;
- }
- public void Initialize()
- {
- try
- {
- FileStream file = new FileStream(_file_name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
- file.Close();
- }
- catch (IOException e)
- { Error(e); }
- }
- public string readFile()
- {
- FileStream file = new FileStream(_file_name, FileMode.OpenOrCreate, FileAccess.Read);
- StreamReader sr = new StreamReader(file);
- string ret = sr.ReadToEnd();
- sr.Close();
- file.Close();
- return ret;
- }
- public void appendFile(string data)
- {
- StreamWriter sw = File.AppendText(_file_name);
- sw.WriteLine(data);
- sw.Flush();
- sw.Close();
- }
- }
- /*Class to maintain settings */
- public class clsSettings
- {
- private const string DEFAULT_FILENAME = "TubeGuardian.log";
- private const string DEFAULT_SETTINGS_FILENAME = "TubeGuardian.settings";
- private string _settings_file_name;
- private int _collect_interval;
- private string _collect_log_file;
- private int _analyzer_relevant_entries;
- private double _analyzer_vote_threshold;
- private bool _analyzer_disable_affected;
- private bool _analyzer_disable_all;
- private int _analyzer_disable_duration;
- private string _ed_log_file;
- // Gatherer settings
- public int Collect_Interval { get { return _collect_interval; } set { _collect_interval = value; _event_settings_changed(); } }
- public string Collect_Log_File { get { return _collect_log_file; } set { _collect_log_file = value; _event_settings_changed(); } }
- // Account settings
- public List<clsCredentials> Accounts { get; private set; }
- // Analyzer settings
- public int Analyzer_Relevant_Entries { get { return _analyzer_relevant_entries; } set { _analyzer_relevant_entries = value; _event_settings_changed(); } }
- public double Analyzer_Vote_Threshold { get { return _analyzer_vote_threshold; } set { _analyzer_vote_threshold = value; _event_settings_changed(); } }
- public bool Analyzer_Disable_Affected { get { return _analyzer_disable_affected; } set { _analyzer_disable_affected = value; _event_settings_changed(); } }
- public bool Analyzer_Disable_All { get { return _analyzer_disable_all; } set { _analyzer_disable_all = value; _event_settings_changed(); } }
- public int Analyzer_Disable_Duration { get { return _analyzer_disable_duration; } set { _analyzer_disable_duration = value; _event_settings_changed(); } }
- // ED settinds
- public string ED_Log_File { get { return _ed_log_file; } set { _ed_log_file = value; _event_settings_changed(); } }
- public clsSettings(string filename)
- {
- _settings_file_name = filename;
- LoadSettings();
- }
- public clsSettings() : this(DEFAULT_SETTINGS_FILENAME) { }
- public void LoadSettings()
- {
- this.Collect_Interval = 10;
- this.Collect_Log_File = DEFAULT_FILENAME;
- this.Analyzer_Vote_Threshold = 2.5;
- this.Analyzer_Relevant_Entries = 10;
- this.Analyzer_Disable_Duration = 300;
- this.Analyzer_Disable_All = false;
- this.Analyzer_Disable_Affected = true;
- this.Accounts = new List<clsCredentials>();
- this.ED_Log_File = DEFAULT_FILENAME;
- FileStream file = new FileStream(_settings_file_name, FileMode.OpenOrCreate, FileAccess.Read);
- StreamReader sr = new StreamReader(file);
- string data = sr.ReadToEnd();
- sr.Close();
- file.Close();
- if (data == string.Empty)
- return;
- else
- {
- string accounts = _get_section(data, "ACCOUNTS {", "}");
- if (accounts != null)
- {
- string[] individuals = accounts.Split(',');
- foreach (string acct in individuals)
- {
- string[] UP = acct.Split(':');
- AddAccount(new clsCredentials(UP[0], UP[1]));
- }
- }
- try { this.Collect_Interval = int.Parse(_get_section(data, "C_I{", "}")); }
- catch { }
- try { this.Collect_Log_File = _get_section(data, "C_L{", "}"); }
- catch { }
- try { this.Analyzer_Vote_Threshold = double.Parse(_get_section(data, "A_V{", "}")); }
- catch { }
- try { this.Analyzer_Relevant_Entries = int.Parse(_get_section(data, "A_R{", "}")); }
- catch { }
- try { this.Analyzer_Disable_All = bool.Parse(_get_section(data, "A_D1{", "}")); }
- catch { }
- try { this.Analyzer_Disable_Affected = bool.Parse(_get_section(data, "A_D2{", "}")); }
- catch { }
- try { this.ED_Log_File = _get_section(data, "ED_L{", "}"); }
- catch { }
- }
- }
- public void SaveSettings()
- {
- string data = null;
- data = "ACCOUNTS {";
- foreach (clsCredentials account in Accounts)
- data += account.Username + ":" + account.Password + ",";
- data = data.Substring(0, data.Length - 1);
- data += "}";
- data += "C_I{" + this.Collect_Interval.ToString() + "}\n";
- data += "C_L{" + this.Collect_Log_File + "}\n";
- data += "A_V{" + this.Analyzer_Vote_Threshold.ToString() + "}\n";
- data += "A_R{" + this.Analyzer_Relevant_Entries.ToString() + "}\n";
- data += "A_D1{" + this.Analyzer_Disable_All.ToString() + "}\n";
- data += "A_D2{" + this.Analyzer_Disable_Affected.ToString() + "}\n";
- data += "A_D3{" + this.Analyzer_Disable_Duration.ToString() + "}\n";
- data += "ED_L{" + this.ED_Log_File + "}\n";
- File.WriteAllText(_settings_file_name, data);
- }
- public void AddAccount(clsCredentials Account)
- {
- if (Account == null)
- return;
- RemoveAccount(Account);
- this.Accounts.Add(Account);
- _event_account_added(Account);
- }
- public void RemoveAccount(clsCredentials Account)
- {
- if (Account == null)
- return;
- int i = 0;
- while (i < Accounts.Count)
- {
- if (Accounts[i].Username == Account.Username)
- {
- _event_account_removed(Accounts[i]);
- Accounts.RemoveAt(i);
- }
- else i++;
- }
- }
- private string _get_section(string data, string left, string right)
- {
- int i_left = -1;
- int i_right = -1;
- i_left = data.IndexOf(left);
- if (i_left == -1)
- return null;
- i_left += left.Length;
- i_right = data.IndexOf(right, i_left);
- if (i_right == -1)
- return null;
- return data.Substring(i_left, i_right - i_left);
- }
- // public methods
- public clsCredentials GetAccountByUsername( string username )
- {
- foreach (clsCredentials acct in Accounts)
- if (acct.Username == username)
- return acct;
- return null;
- }
- // events!
- public delegate void AccountAddedHandler(object sender, clsCredentials Account);
- public event AccountAddedHandler OnAccountAdded;
- private void _event_account_added(clsCredentials Account)
- {
- if (OnAccountAdded != null)
- OnAccountAdded(this, Account);
- }
- public delegate void AccountRemovedHandler(object sender, clsCredentials Account);
- public event AccountRemovedHandler OnAccountRemoved;
- private void _event_account_removed(clsCredentials Account)
- {
- if (OnAccountRemoved != null)
- OnAccountRemoved(this, Account);
- }
- public delegate void SettingsChangedHandler(object sender);
- public event SettingsChangedHandler OnSettingsChanged;
- private void _event_settings_changed()
- {
- if (OnSettingsChanged != null)
- OnSettingsChanged(this);
- }
- }
- }
Add Comment
Please, Sign In to add comment