Пример #1
0
        static void Main(string[] args)
        {
            //RegExpLib.CreateRegExpAssembly();
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            HubSetting settings = new HubSetting();

            WriteLine("*** NofArguments:" + args.Length);
            string file = null;

            if (args.Length > 0)
            {
                file = args[0];
                WriteLine(string.Format("*** Arguments[0 = {0}]", file));
            }
            else
            {
                WriteLine("*** No arguments");
                file = "localhost.xml";
            }

            if (!string.IsNullOrEmpty(file) && !string.IsNullOrEmpty(file.Trim()))
            {
                Settings xml = new Settings();
                xml.Read(file);
                if (xml.Hubs.Count > 0)
                {
                    settings = xml.Hubs[0];

                    // Set custom settings
                    DEBUG           = xml.UseDebug;
                    USE_ACTIVE_MODE = xml.UserActiveConnectionMode;
                    CONVERT_EXTERNAL_IP_TO_INTERNAL_IP = xml.ConvertExternalIpToInternalIp;

                    int prt = xml.ActivePort;
                    if (prt >= System.Net.IPEndPoint.MinPort && prt <= System.Net.IPEndPoint.MaxPort)
                    {
                        PORT_ACTIVE = prt;
                    }
                    int prtTls = xml.TlsPort;
                    if (prtTls >= System.Net.IPEndPoint.MinPort && prtTls <= System.Net.IPEndPoint.MaxPort)
                    {
                        PORT_TLS = prtTls;
                    }

                    int tmp = xml.MaxNumberOfLinesInMessage;
                    if (tmp > 0)
                    {
                        MAX_NUMBER_OF_LINES_IN_MESSAGE = tmp;
                    }


                    WriteLine("*** Getting External IP");
                    //string strIp = FlowLib.Utils.WebOperations.GetPage("http://ip.flowertwig.org");
                    //System.Net.IPAddress ipAddress;
                    //if (System.Net.IPAddress.TryParse(strIp, out ipAddress))
                    //{
                    //    WriteLine("\tIP: " + strIp);
                    //    settings.Set("ExternalIP", strIp);
                    //}else
                    //{
                    //    WriteLine("\tUnable to get External IP");
                    //}

                    DcBot bot = new DcBot(settings);
                    bot.Connect();

                    Cleaner.Start();
                }
                else
                {
                    WriteLine("*** No hubs found in settings file.");
                    settings.Address         = "127.0.0.1";
                    settings.Port            = 411;
                    settings.DisplayName     = "Serie";
                    settings.Protocol        = "Nmdc";
                    settings.UserDescription = "https://code.google.com/p/seriebot/";

                    // Add default values so user know that it is possible to customize.
                    settings.Set(Settings.KEY_USE_DEBUG, DEBUG.ToString());
                    settings.Set(Settings.KEY_MAX_NUMBER_OF_LINES_IN_MESSAGE, MAX_NUMBER_OF_LINES_IN_MESSAGE.ToString());
                    settings.Set(Settings.KEY_USE_ACTIVE_CONNECTION_MODE, USE_ACTIVE_MODE.ToString());
                    settings.Set(Settings.KEY_PORT_TCP_AND_UDP, PORT_ACTIVE.ToString());
                    settings.Set(Settings.KEY_PORT_TLS, PORT_TLS.ToString());

                    xml = new Settings();
                    xml.Hubs.Add(settings);
                    xml.Write("localhost.xml");
                    WriteLine("*** Example setting file has been created.");
                    WriteLine("*** Press enter/return key to quit.");
                }
            }
            Console.Read();
            WriteLine("*** Application terminated by user.");
        }
Пример #2
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());
        }
Пример #3
0
        public static bool TryHandleDownload(DcBot connection, DownloadItem item, Source source)
        {
            if (item != null && source != null)
            {
                string fileType = item.ContentInfo.Get(ContentInfo.FILELIST);
                string func = item.ContentInfo.Get("FUNC");
                string path = item.ContentInfo.Get(ContentInfo.STORAGEPATH);
                string usrId = item.ContentInfo.Get("USR");

                byte[] data = null;

                BaseFilelist filelist = null;

                int i = 0;
                while (i < 10)
                {
                    try
                    {
                        data = File.ReadAllBytes(path);
                        break;
                    }
                    catch (Exception)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    finally
                    {
                        i++;
                    }

                }

                if (data == null)
                    return false;

                switch (fileType)
                {
                    case BaseFilelist.XMLBZ:
                        filelist = new FilelistXmlBz2(data, true);
                        break;
                    case BaseFilelist.XML:
                        filelist = new FilelistXmlBz2(data, false);
                        break;
                    case BaseFilelist.BZ:
                        filelist = new FilelistMyList(data, true);
                        break;
                    default:
                        connection.SendMessage(Actions.PrivateMessage, usrId, "Unrecognized filelist.");
                        return false;
                }

                LogMsg("CreateShare");
                filelist.CreateShare();
                LogMsg("/CreateShare");
                Share share = filelist.Share as Share;

                File.Delete(path);

                if (share != null)
                {
                    switch (func)
                    {
                        case "new":
                            FuncListShare(connection, share, usrId, FunctionTypes.ListNewEpisodes); break;
                        case "list":
                            FuncListShare(connection, share, usrId, FunctionTypes.ListAllEpisodes); break;
                        case "debug":
                            FuncListShare(connection, share, usrId, FunctionTypes.ListDebugInfoOnEpisodes); break;
                        case "countdown":
                        case "cd":
                            FuncCountDownShare(connection, share, usrId); break;
                    }
                }
            }

            return false;
        }
Пример #4
0
        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;
        }
Пример #5
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
        }
Пример #6
0
        static void Main(string[] args)
        {
            //RegExpLib.CreateRegExpAssembly();
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            HubSetting settings = new HubSetting();

            WriteLine("*** NofArguments:" + args.Length);
            string file = null;
            if (args.Length > 0)
            {
                file = args[0];
                WriteLine(string.Format("*** Arguments[0 = {0}]", file));
            }else{
                WriteLine("*** No arguments");
                file = "localhost.xml";
            }

            if (!string.IsNullOrEmpty(file) && !string.IsNullOrEmpty(file.Trim()))
            {
                Settings xml = new Settings();
                xml.Read(file);
                if (xml.Hubs.Count > 0)
                {
                    settings = xml.Hubs[0];

                    // Set custom settings
                    DEBUG = xml.UseDebug;
                    USE_ACTIVE_MODE = xml.UserActiveConnectionMode;
                    CONVERT_EXTERNAL_IP_TO_INTERNAL_IP = xml.ConvertExternalIpToInternalIp;

                    int prt = xml.ActivePort;
                    if (prt >= System.Net.IPEndPoint.MinPort && prt <= System.Net.IPEndPoint.MaxPort)
                    {
                        PORT_ACTIVE = prt;
                    }
                    int prtTls = xml.TlsPort;
                    if (prtTls >= System.Net.IPEndPoint.MinPort && prtTls <= System.Net.IPEndPoint.MaxPort)
                    {
                        PORT_TLS = prtTls;
                    }

                    int tmp = xml.MaxNumberOfLinesInMessage;
                    if (tmp > 0)
                    {
                        MAX_NUMBER_OF_LINES_IN_MESSAGE = tmp;
                    }

                    WriteLine("*** Getting External IP");
                    //string strIp = FlowLib.Utils.WebOperations.GetPage("http://ip.flowertwig.org");
                    //System.Net.IPAddress ipAddress;
                    //if (System.Net.IPAddress.TryParse(strIp, out ipAddress))
                    //{
                    //    WriteLine("\tIP: " + strIp);
                    //    settings.Set("ExternalIP", strIp);
                    //}else
                    //{
                    //    WriteLine("\tUnable to get External IP");
                    //}

                    DcBot bot = new DcBot(settings);
                    bot.Connect();

                    Cleaner.Start();
                }
                else
                {
                    WriteLine("*** No hubs found in settings file.");
                    settings.Address = "127.0.0.1";
                    settings.Port = 411;
                    settings.DisplayName = "Serie";
                    settings.Protocol = "Nmdc";
                    settings.UserDescription = "https://code.google.com/p/seriebot/";

                    // Add default values so user know that it is possible to customize.
                    settings.Set(Settings.KEY_USE_DEBUG, DEBUG.ToString());
                    settings.Set(Settings.KEY_MAX_NUMBER_OF_LINES_IN_MESSAGE, MAX_NUMBER_OF_LINES_IN_MESSAGE.ToString());
                    settings.Set(Settings.KEY_USE_ACTIVE_CONNECTION_MODE, USE_ACTIVE_MODE.ToString());
                    settings.Set(Settings.KEY_PORT_TCP_AND_UDP, PORT_ACTIVE.ToString());
                    settings.Set(Settings.KEY_PORT_TLS, PORT_TLS.ToString());

                    xml = new Settings();
                    xml.Hubs.Add(settings);
                    xml.Write("localhost.xml");
                    WriteLine("*** Example setting file has been created.");
                    WriteLine("*** Press enter/return key to quit.");
                }
            }
            Console.Read();
            WriteLine("*** Application terminated by user.");
        }
        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);
        }
Пример #8
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
        }
Пример #9
0
        public static bool TryHandleDownload(DcBot connection, DownloadItem item, Source source)
        {
            if (item != null && source != null)
            {
                string fileType = item.ContentInfo.Get(ContentInfo.FILELIST);
                string func     = item.ContentInfo.Get("FUNC");
                string path     = item.ContentInfo.Get(ContentInfo.STORAGEPATH);
                string usrId    = item.ContentInfo.Get("USR");

                byte[] data = null;

                BaseFilelist filelist = null;

                int i = 0;
                while (i < 10)
                {
                    try
                    {
                        data = File.ReadAllBytes(path);
                        break;
                    }
                    catch (Exception)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    finally
                    {
                        i++;
                    }
                }

                if (data == null)
                {
                    return(false);
                }

                switch (fileType)
                {
                case BaseFilelist.XMLBZ:
                    filelist = new FilelistXmlBz2(data, true);
                    break;

                case BaseFilelist.XML:
                    filelist = new FilelistXmlBz2(data, false);
                    break;

                case BaseFilelist.BZ:
                    filelist = new FilelistMyList(data, true);
                    break;

                default:
                    connection.SendMessage(Actions.PrivateMessage, usrId, "Unrecognized filelist.");
                    return(false);
                }

                LogMsg("CreateShare");
                filelist.CreateShare();
                LogMsg("/CreateShare");
                Share share = filelist.Share as Share;

                File.Delete(path);

                if (share != null)
                {
                    switch (func)
                    {
                    case "new":
                        FuncListShare(connection, share, usrId, FunctionTypes.ListNewEpisodes); break;

                    case "list":
                        FuncListShare(connection, share, usrId, FunctionTypes.ListAllEpisodes); break;

                    case "debug":
                        FuncListShare(connection, share, usrId, FunctionTypes.ListDebugInfoOnEpisodes); break;

                    case "countdown":
                    case "cd":
                        FuncCountDownShare(connection, share, usrId); break;
                    }
                }
            }

            return(false);
        }
Пример #10
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());
        }