public static SerieInfo GetSerie(string name)
        {
            string    url  = name;
            string    key  = MakeKey(name);
            SerieInfo info = null;

            //string content = null;
            bool getNewContent = false;

            if (System.IO.File.Exists(_directory + key + ".xml"))
            {
                DateTime updateDate = GetNextUpdateForKey(key);
                if (updateDate < DateTime.Now)
                {
                    getNewContent = true;
                }
            }
            else
            {
                getNewContent = true;
            }

            if (getNewContent)
            {
                if (_NeedSleep)
                {
                    // Sleep X miliseconds
                    System.Threading.Thread.Sleep(250);
                }
                _NeedSleep = true;
                info       = GetNewInfo(name);
                // Do we have a valid result?
                if (info != null)
                {
                    if (info is EmptySerieInfo)
                    {
                        System.IO.File.WriteAllText(_directory + key + ".bad", info.ServiceAddress);
                        info = null;
                    }
                    else
                    {
                        FlowLib.Utils.FileOperations <SerieInfo> .SaveObject(_directory + key + ".xml", info);
                    }
                }
            }
            else
            {
                _NeedSleep = false;
                info       = FlowLib.Utils.FileOperations <SerieInfo> .LoadObject(_directory + key + ".xml");
            }

            if (info != null && info.NextEpisode != null && info.NextEpisode.Date > DateTime.MinValue)
            {
                System.IO.File.WriteAllText(_directory + key + ".update", info.NextEpisode.Date.ToString("yyyy-MM-dd"));
            }

            return(info);
        }
Exemple #2
0
        public int CompareTo(object obj)
        {
            SerieInfo otherInfo = obj as SerieInfo;

            if (otherInfo != null)
            {
                return(string.Compare(Name, otherInfo.Name));
            }
            throw new NotImplementedException();
        }
        public static string GetCacheInfoFromKey(string key)
        {
            if (System.IO.File.Exists(_directory + key + ".xml"))
            {
                SerieInfo info = FlowLib.Utils.FileOperations <SerieInfo> .LoadObject(_directory + key + ".xml");

                //SerieInfo info = Parse(content);
                if (info == null)
                {
                    System.IO.File.Delete(_directory + key + ".xml");
                }
                else
                {
                    return(string.Format("{0} [{1}] - Will be updated after: {2:yyyy-MM-dd}", info.Name, key, GetNextUpdateForKey(key)));
                }
            }

            return(string.Format("No cache found with Key: {0}.", key));
        }
        private static SerieInfo GetNewInfo(string name)
        {
            SerieInfo info = null;

            if (TvRage.IsValid)
            {
                info = TvRage.GetNewInfo(name);
            }

            // If we have no result. Test with some other TV service.
            if (info == null)
            {
                if (TheTvDb.IsValid)
                {
                    info = TheTvDb.GetNewInfo(name);
                }
            }
            return(info);
        }
        public static bool TryHandleMsg(DcBot connection, string id, string command, int msgtype)
        {
            if (string.IsNullOrEmpty(command))
            {
                return(false);
            }

            bool isCommand = false;

            switch (command[0])
            {
            case '+':
            case '-':
            case '!':
            case '.':
                isCommand = true;
                break;
            }

            if (!isCommand)
            {
                return(false);
            }

            StringBuilder sb = null;

            command = command.Substring(1);
            string param = null;
            int    pos;

            if ((pos = command.IndexOf(' ')) != -1)
            {
                param   = command.Substring(pos).Trim();
                command = command.Substring(0, pos).ToLower();
            }
            else
            {
                command = command.ToLower();
            }

            User usr = null;

            switch (command)
            {
            case "next":
                if (string.IsNullOrEmpty(param))
                {
                    connection.SendMessage(msgtype, id, "Command works like this: +next <Serie Name>. For example +next smallville");
                }
                else
                {
                    SerieInfo info = Service.GetSerie(param);
                    if (info != null)
                    {
                        if (info.NextEpisode != null)
                        {
                            connection.SendMessage(msgtype, id, string.Format("{0} - {1}", info.Name, info.NextEpisode));
                        }
                        else if (info.LatestEpisode != null)
                        {
                            connection.SendMessage(msgtype, id, string.Format("{0} - Last episode: {1}", info.Name, info.LatestEpisode));
                        }
                        else
                        {
                            connection.SendMessage(msgtype, id, string.Format("{0} - Status: {1}", info.Name, info.Status));
                        }
                    }
                    else
                    {
                        connection.SendMessage(Actions.PrivateMessage, id, "no info found.");
                    }
                }
                break;

            case "last":
                if (string.IsNullOrEmpty(param))
                {
                    connection.SendMessage(Actions.PrivateMessage, id, "Command works like this: +last <Serie Name>. For example +last smallville");
                }
                else
                {
                    SerieInfo info = Service.GetSerie(param);
                    if (info != null)
                    {
                        if (info.LatestEpisode != null)
                        {
                            connection.SendMessage(msgtype, id, string.Format("{0} - {1}", info.Name, info.LatestEpisode));
                        }
                        else
                        {
                            connection.SendMessage(msgtype, id, string.Format("{0} - Last: {1}", info.Name, info.Status));
                        }
                    }
                    else
                    {
                        connection.SendMessage(Actions.PrivateMessage, id, "no info found.");
                    }
                }
                break;

            case "new":
            case "list":
            case "debug":
            case "countdown":
            case "cd":
                usr = connection.GetUser(id);
                if (usr != null)
                {
                    long share;
                    if (!Program.USE_ACTIVE_MODE && usr.Tag.Mode != FlowLib.Enums.ConnectionTypes.Direct)
                    {
                        connection.SendMessage(Actions.PrivateMessage, id, "You need to be active to use this command.");
                    }
                    else if (!long.TryParse(usr.UserInfo.Share, out share) || share <= 0)
                    {
                        connection.SendMessage(Actions.PrivateMessage, id, "You need to share stuff to use this command.");
                    }
                    else
                    {
                        connection.SendMessage(Actions.PrivateMessage, id, "Please note that this command may take several minutes to complete. (Writing the command more then once will reset your position in queue and place you last)");
                        connection.GetFileList(usr, command);
                    }
                }
                break;

            case "ignore":
                if (param == null)
                {
                    sb = new StringBuilder();
                    sb.AppendLine("When, what and how to ignore.");

                    sb.AppendLine("When can ignore be used?");
                    sb.AppendLine("Ignore can be used with the following commands:");
                    sb.AppendLine("\t+new");
                    sb.AppendLine();

                    sb.AppendLine("What is ignore?");
                    sb.AppendLine("You can tell me to not display information about series.");
                    sb.AppendLine("If used in combination with +new command,");
                    sb.AppendLine("I will for example not display how many episodes you are behind for those series you have choosed me to ignore.");
                    sb.AppendLine();

                    sb.AppendLine("How do i ignore a serie?");
                    sb.AppendLine("You can tell me to ignore a serie by adding a file to your share for every serie you want me to ignore.");
                    sb.AppendLine("This file should have the following format:");
                    sb.AppendLine("\t<Serie name>.ignore");
                    sb.AppendLine("If you for example want to ignore 'Lost' you should add a file with this name:");
                    sb.AppendLine("\tLost.ignore");
                    sb.AppendLine();
                    sb.AppendLine("Type: +ignore <Serie name> to get the filename to use.");

                    connection.SendMessage(Actions.PrivateMessage, id, sb.ToString());
                }
                else
                {
                    // convert serie name to ignore filename
                    connection.SendMessage(Actions.PrivateMessage, id, string.Format("{0} will give you this filename: {1}.ignore", param, Ignore.CreateName(param)));
                }
                break;

            case "cache":
                sb = new StringBuilder();
                if (param == null)
                {
                    string[] files = System.IO.Directory.GetFiles(Service.Directory);
                    int      lines = 0;
                    foreach (string f in files)
                    {
                        System.IO.FileInfo fi = new System.IO.FileInfo(f);
                        if (!fi.Name.EndsWith(".update"))
                        {
                            sb.AppendLine(Service.GetCacheInfoFromKey(fi.Name));
                        }
                        // Make sure we are not exceeding max number of lines in hub.
                        if (Program.MAX_NUMBER_OF_LINES_IN_MESSAGE <= lines)
                        {
                            connection.SendMessage(Actions.PrivateMessage, id, sb.ToString());
                            sb    = new StringBuilder();
                            lines = 0;
                        }
                    }
                    // Have we any lines to send?
                    if (lines > 0)
                    {
                        connection.SendMessage(Actions.PrivateMessage, id, sb.ToString());
                    }
                }
                else
                {
                    connection.SendMessage(Actions.PrivateMessage, id, "This is a list command. You can't send params with it :)");
                }
                break;

            default:
                return(false);
            }
            return(true);
        }
Exemple #6
0
        public static void FuncListShare(DcBot connection, Share share, string usrId, FunctionTypes funcType)
        {
            int           lines        = 0;
            bool          anyInfo      = false;
            DateTime      todaysDate   = DateTime.Now.Date;
            List <string> servicesUsed = new List <string>();
            SortedList <SerieInfo, EpisodeInfo> list;
            Dictionary <string, KeyValuePair <string, int> > listIgnore;
            ClientInfo clientInfo = null;

            var user = connection.GetUser(usrId);

            if (user != null && user.Tag != null)
            {
                clientInfo = ClientParser.Parse(user.Tag.Version);
            }

            StringBuilder sb = new StringBuilder("Your current serie information:\r\n");

            lines++;

            GetSeriesFromShare(share, out list, out listIgnore);

            int ignoreCount = listIgnore.Count();

            sb.AppendFormat("I have found {0} different series in your share.\r\n", list.Count);
            lines++;
            sb.AppendFormat("You want me to ignore {0} of them.", ignoreCount);
            if (ignoreCount == 0)
            {
                sb.Append(" To learn more. Please write +ignore.");
            }
            sb.AppendLine();
            lines++;

            #region Get info about series
            LogMsg("Display Series");

            foreach (var seriePair in list)
            {
                SerieInfo info = seriePair.Key;
                if (info != null && !listIgnore.ContainsKey(Ignore.CreateName(info.Name)))
                {
                    EpisodeInfo epLast = info.LatestEpisode;
                    EpisodeInfo epNext = info.NextEpisode;

                    if (epLast != null)
                    {
                        int currentSeason  = epLast.Version / 100;
                        int currentEpisode = epLast.Version % 100;

                        int         usrSeasonVersion  = seriePair.Value.Version / 100;
                        int         usrEpisodeVersion = seriePair.Value.Version % 100;
                        EpisodeInfo usrEpisode        = seriePair.Value;

                        bool       addedInfo  = false;
                        MagnetLink magnetLink = null;

                        switch (funcType)
                        {
                        case FunctionTypes.ListAllEpisodes:
                        case FunctionTypes.ListNewEpisodes:
                            if (currentSeason > usrSeasonVersion)
                            {
                                if (currentSeason == (usrSeasonVersion + 1))
                                {
                                    sb.AppendFormat("\t{0}: A new season have started.", info.Name);
                                    addedInfo = true;
                                }
                                else
                                {
                                    sb.AppendFormat("\t{0}: You are behind more then one season.", info.Name);
                                    addedInfo = true;
                                }
                            }
                            else if (currentSeason == usrSeasonVersion)
                            {
                                if (currentEpisode > usrEpisodeVersion)
                                {
                                    int difEpisode = currentEpisode - usrEpisodeVersion;
                                    if (difEpisode == 1)
                                    {
                                        sb.AppendFormat("\t{0}: You are behind {1} episode.", info.Name, difEpisode);
                                        addedInfo  = true;
                                        magnetLink = MagnetLink.CreateMagnetLink(clientInfo, info.Name,
                                                                                 currentSeason,
                                                                                 usrEpisodeVersion + 1);
                                    }
                                    else
                                    {
                                        sb.AppendFormat("\t{0}: You are behind {1} episodes.", info.Name, difEpisode);
                                        magnetLink = MagnetLink.CreateMagnetLink(clientInfo, info.Name,
                                                                                 currentSeason,
                                                                                 usrEpisodeVersion + 1);
                                        addedInfo = true;
                                    }
                                }
                                else if (funcType == FunctionTypes.ListAllEpisodes)
                                {
                                    sb.AppendFormat("\t{0}: You have the latest episode.", info.Name);
                                    addedInfo = true;
                                }
                            }

                            if (addedInfo)
                            {
                                anyInfo = true;

                                bool showUserLastEpisodeInfo =
                                    magnetLink == null || (clientInfo != null && clientInfo.Type != ClientType.Jucy);
                                if (showUserLastEpisodeInfo)
                                {
                                    // If we dont have a magnet. Tell user what version he/she/it has :)
                                    sb.AppendFormat("\t\t(Your last episode is: S{0:00}E{1:00})",
                                                    usrSeasonVersion,
                                                    usrEpisodeVersion);
                                }

                                // Do we have a magnet link to show?
                                if (magnetLink != null)
                                {
                                    sb.AppendFormat("\t\t{0}", magnetLink.Link);
                                }
                                sb.Append("\r\n");

                                servicesUsed.Add(info.ServiceAddress);
                                lines++;
                            }
                            break;

                        case FunctionTypes.ListDebugInfoOnEpisodes:
                            anyInfo = true;
                            sb.AppendFormat("\t{0}\t\t(Episode: S{1:00}E{2:00})\r\n\t\t{3}\r\n", info.Name, usrSeasonVersion,
                                            usrEpisodeVersion, usrEpisode.RawFileName);
                            break;

                        case FunctionTypes.ListCountDownEpisodes:
                            if (epNext != null)
                            {
                                var difference = epNext.Date.Subtract(todaysDate);
                                if (difference.TotalDays >= 0)
                                {
                                    sb.AppendFormat("\t{0}\t\tDays left: {1} ({2:yyyy-MM-dd})\r\n", info.Name,
                                                    difference.TotalDays, epNext.Date);
                                    anyInfo = true;
                                }
                            }
                            break;
                        }
                    }
                }

                // Make sure we are not exceeding max number of lines in hub.
                if (Program.MAX_NUMBER_OF_LINES_IN_MESSAGE <= lines)
                {
                    connection.SendMessage(Actions.PrivateMessage, usrId, sb.ToString());
                    sb    = new StringBuilder();
                    lines = 0;
                }
            }
            LogMsg("/Display Series");

            switch (funcType)
            {
            case FunctionTypes.ListNewEpisodes:
                if (!anyInfo)
                {
                    sb.AppendLine("You seem to have latest episode of every serie you are sharing!");
                }
                break;
            }

            sb.AppendLine();
            sb.AppendLine();

            sb.Append("This result was given to you by: http://code.google.com/p/seriebot/ ");
            string[] servicesUsedDistinct = servicesUsed.Distinct().ToArray();
            int      serviceCount         = servicesUsedDistinct.Length;
            if (serviceCount > 0)
            {
                sb.Append("with the help by: ");
                sb.AppendLine(string.Join(", ", servicesUsedDistinct));
            }
            else
            {
                sb.AppendLine();
            }

            //sb.AppendLine("This service is powered by: www.tvrage.com");

            // message will here be converted to right format and then be sent.
            connection.SendMessage(Actions.PrivateMessage, usrId, sb.ToString());
            #endregion
        }
Exemple #7
0
        public static void FuncCountDownShare(DcBot connection, Share share, string usrId)
        {
            int           lines        = 0;
            bool          anyInfo      = false;
            DateTime      todaysDate   = DateTime.Now.Date;
            List <string> servicesUsed = new List <string>();
            SortedList <SerieInfo, EpisodeInfo> list;
            Dictionary <string, KeyValuePair <string, int> > listIgnore;

            StringBuilder sb = new StringBuilder("Countdown of your Series:\r\n");

            lines++;

            GetSeriesFromShare(share, out list, out listIgnore);

            // Get series and make sure we order it on total days left and serie name..
            SortedList <string, SerieInfo> listOrderedByDate = new SortedList <string, SerieInfo>();

            foreach (var seriePair in list)
            {
                SerieInfo info = seriePair.Key;
                if (info != null && !listIgnore.ContainsKey(Ignore.CreateName(info.Name)))
                {
                    EpisodeInfo epNext = info.NextEpisode;
                    if (epNext != null)
                    {
                        var    difference = epNext.Date.Subtract(todaysDate);
                        double totalDays  = difference.TotalDays;
                        if (totalDays >= 0)
                        {
                            string key = string.Format("{0:000}-{1}", totalDays, info.Name);
                            listOrderedByDate.Add(key, info);

                            servicesUsed.Add(info.ServiceAddress);

                            anyInfo = true;
                        }
                    }
                }
            }

            List <string> outputList        = new List <string>();
            DateTime      lastDate          = DateTime.MinValue;
            DateTime      today             = DateTime.Today;
            DateTime      tomorrow          = DateTime.Today.AddDays(1);
            int           nOfDaysLeftInWeek = 0;

            switch (today.DayOfWeek)
            {
            case DayOfWeek.Monday:
                nOfDaysLeftInWeek = 6;
                break;

            case DayOfWeek.Tuesday:
                nOfDaysLeftInWeek = 5;
                break;

            case DayOfWeek.Wednesday:
                nOfDaysLeftInWeek = 4;
                break;

            case DayOfWeek.Thursday:
                nOfDaysLeftInWeek = 3;
                break;

            case DayOfWeek.Friday:
                nOfDaysLeftInWeek = 2;
                break;

            case DayOfWeek.Saturday:
                nOfDaysLeftInWeek = 1;
                break;

            case DayOfWeek.Sunday:
            default:
                nOfDaysLeftInWeek = 0;
                break;
            }

            bool nextWeekHasHit       = false;
            bool moreThenAMonthHasHit = false;

            foreach (var orderedPair in listOrderedByDate)
            {
                bool showDateAfterName = false;
                bool stuffAdded        = false;

                if (DateTime.Compare(lastDate, orderedPair.Value.NextEpisode.Date.Date) < 0)
                {
                    lastDate = orderedPair.Value.NextEpisode.Date.Date;

                    if (DateTime.Equals(today, lastDate.Date))
                    {
                        sb.Append("\tToday");
                        sb.AppendFormat(" ({0:yyyy-MM-dd}):", lastDate);
                        stuffAdded = true;
                    }
                    else if (DateTime.Equals(tomorrow, lastDate.Date))
                    {
                        sb.Append("\tTomorrow");
                        sb.AppendFormat(" ({0:yyyy-MM-dd}):", lastDate);
                        stuffAdded = true;
                    }
                    else
                    {
                        // How many days have to pass until this date?
                        var timeLeft = lastDate.Subtract(today);
                        // Does this date occure this week?
                        if (timeLeft.TotalDays <= nOfDaysLeftInWeek)
                        {
                            switch (lastDate.DayOfWeek)
                            {
                            case DayOfWeek.Monday:
                                sb.Append("\tMonday");
                                break;

                            case DayOfWeek.Tuesday:
                                sb.Append("\tTuesday");
                                break;

                            case DayOfWeek.Wednesday:
                                sb.Append("\tWednesday");
                                break;

                            case DayOfWeek.Thursday:
                                sb.Append("\tThursday");
                                break;

                            case DayOfWeek.Friday:
                                sb.Append("\tFriday");
                                break;

                            case DayOfWeek.Saturday:
                                sb.Append("\tSaturday");
                                break;

                            case DayOfWeek.Sunday:
                                sb.Append("\tSunday");
                                break;
                            }
                            sb.AppendFormat(" ({0:yyyy-MM-dd}):", lastDate);
                            stuffAdded = true;
                        }
                        else if (timeLeft.TotalDays <= 7 + nOfDaysLeftInWeek)  // Does this date occure next week?
                        {
                            if (!nextWeekHasHit)
                            {
                                sb.Append("\tNext week");
                                var dateBeginingOfNextWeek = today.AddDays(1 + nOfDaysLeftInWeek);
                                var dateEndingOfNextWeek   = today.AddDays(7 + nOfDaysLeftInWeek);
                                sb.AppendFormat(" ({0:yyyy-MM-dd} -> {1:yyyy-MM-dd}):", dateBeginingOfNextWeek,
                                                dateEndingOfNextWeek);

                                nextWeekHasHit = true;
                                stuffAdded     = true;
                            }
                            showDateAfterName = true;
                        }
                        else
                        {
                            if (!moreThenAMonthHasHit)
                            {
                                sb.Append("\tMore than 2 weeks:");
                                moreThenAMonthHasHit = true;
                                stuffAdded           = true;
                            }
                            showDateAfterName = true;
                        }
                    }

                    if (stuffAdded)
                    {
                        sb.AppendLine();
                        lines++;
                    }
                }

                sb.Append("\t\t");
                sb.Append(orderedPair.Value.Name);

                if (showDateAfterName)
                {
                    sb.AppendFormat(" ({0:yyyy-MM-dd})", lastDate);
                }

                // Make sure we are not exceeding max number of lines in hub.
                if (Program.MAX_NUMBER_OF_LINES_IN_MESSAGE <= lines)
                {
                    connection.SendMessage(Actions.PrivateMessage, usrId, sb.ToString());
                    sb    = new StringBuilder();
                    lines = 0;
                }

                sb.AppendLine();
                lines++;
            }

            LogMsg("/Display Series");

            sb.AppendLine();
            sb.AppendLine();

            sb.Append("This result was given to you by: http://code.google.com/p/seriebot/ ");
            string[] servicesUsedDistinct = servicesUsed.Distinct().ToArray();
            int      serviceCount         = servicesUsedDistinct.Length;

            if (serviceCount > 0)
            {
                sb.Append("with the help by: ");
                sb.AppendLine(string.Join(", ", servicesUsedDistinct));
            }
            else
            {
                sb.AppendLine();
            }

            //sb.AppendLine("This service is powered by: www.tvrage.com");

            // message will here be converted to right format and then be sent.
            connection.SendMessage(Actions.PrivateMessage, usrId, sb.ToString());
        }
Exemple #8
0
        protected static void GetSeriesFromShare(Share share, out SortedList <SerieInfo, EpisodeInfo> list, out Dictionary <string, KeyValuePair <string, int> > listIgnore)
        {
            list = new SortedList <SerieInfo, EpisodeInfo>();
            #region Get latest version of all series
            LogMsg("Copy and split share");
            IEnumerable <KeyValuePair <string, ContentInfo> > tmp = share;

            int count = tmp.Count();

            int length = count / 2;
            var t1     = tmp.Take(length);
            var t2     = tmp.Skip(count - (length + 1));

            LogMsg("/Copy and split share");


            LogMsg("Find Ignore and Series");

            var t1Func = Test(t1);
            var t2Func = Test(t2);

            // Sleep while threads are working..
            while (t1Func.Progress == 0 || t2Func.Progress == 0)
            {
                Thread.Sleep(100);
            }

            System.Collections.Specialized.StringDictionary sd = new System.Collections.Specialized.StringDictionary();

            listIgnore = t1Func.IgnoreList.Union(t2Func.IgnoreList).ToDictionary(f => f.Key, System.Collections.Generic.EqualityComparer <string> .Default);

            var listWithDuplicates = t1Func.DuplicatesList.Where(
                f => !t2Func.DuplicatesList.ContainsKey(f.Key) ||
                f.Value.Version >= t2Func.DuplicatesList[f.Key].Version).Union(t2Func.DuplicatesList.Where(
                                                                                   f2 => !t1Func.DuplicatesList.ContainsKey(f2.Key) ||
                                                                                   f2.Value.Version > t1Func.DuplicatesList[f2.Key].Version))
                                     .ToDictionary(f3 => f3.Key, System.Collections.Generic.EqualityComparer <string> .Default);

            LogMsg("/Find Ignore and Series");
            #endregion

            #region Get info from series and remove duplicates (happens because of different folder names)
            //SortedList<SerieInfo, EpisodeInfo> list = new SortedList<SerieInfo, EpisodeInfo>();

            LogMsg("Get Series");
            foreach (var seriePair in listWithDuplicates)
            {
                SerieInfo info = Service.GetSerie(seriePair.Key);
                if (info != null)
                {
                    bool addValue = true;
                    if (list.ContainsKey(info))
                    {
                        if (list[info].Version >= seriePair.Value.Value.Version)
                        {
                            addValue = false;
                        }
                        else
                        {
                            list.Remove(info);
                        }
                    }

                    if (addValue)
                    {
                        list.Add(info, seriePair.Value.Value);
                    }
                }
            }
            LogMsg("/Get Series");
            #endregion
        }