public void Receive(GXPOP3Session sessionInfo, GXMailMessage gxmessage)
        {
            if (client == null)
            {
                LogError("Login Error", "Must login", MailConstants.MAIL_CantLogin);
                return;
            }

            if (lastReadMessage == count)
            {
                LogDebug("No messages to receive", "No messages to receive", MailConstants.MAIL_NoMessages);
                return;
            }
            try {
                if (count > lastReadMessage)
                {
                    Message m = null;
                    try
                    {
                        m = client.GetMessage(++lastReadMessage);
                    }
                    catch (Exception e)
                    {
                        LogError("Receive message error", e.Message, MailConstants.MAIL_ServerRepliedErr, e);
                    }

                    if (m != null)
                    {
                        MailMessage msg;
                        try
                        {
                            msg = m.ToMailMessage();
                        }
                        catch (ArgumentException ae)
                        {
                            GXLogging.Error(log, "Receive message error " + ae.Message + " subject:" + m.Headers.Subject, ae);
                            PropertyInfo subjectProp = m.Headers.GetType().GetProperty("Subject");
                            string       subject     = m.Headers.Subject;
                            if (HasCROrLF(subject))
                            {
                                subjectProp.SetValue(m.Headers, subject.Replace('\r', ' ').Replace('\n', ' '));
                                GXLogging.Warn(log, "Replaced CR and LF in subject " + m.Headers.Subject);
                            }
                            msg = m.ToMailMessage();
                        }
                        using (msg)
                        {
                            gxmessage.From = new GXMailRecipient(msg.From.DisplayName, msg.From.Address);
                            SetRecipient(gxmessage.To, msg.To);
                            SetRecipient(gxmessage.CC, msg.CC);
                            gxmessage.Subject = msg.Subject;
                            if (msg.IsBodyHtml)
                            {
                                gxmessage.HTMLText = msg.Body;
                                MessagePart plainText = m.FindFirstPlainTextVersion();
                                if (plainText != null)
                                {
                                    gxmessage.Text += plainText.GetBodyAsText();
                                }
                            }
                            else
                            {
                                gxmessage.Text = msg.Body;
                            }
                            if (msg.ReplyToList != null && msg.ReplyToList.Count > 0)
                            {
                                SetRecipient(gxmessage.ReplyTo, msg.ReplyToList);
                            }

                            gxmessage.DateSent = m.Headers.DateSent;
                            if (gxmessage.DateSent.Kind == DateTimeKind.Utc && GeneXus.Application.GxContext.Current != null)
                            {
                                gxmessage.DateSent = DateTimeUtil.FromTimeZone(m.Headers.DateSent, "Etc/UTC", GeneXus.Application.GxContext.Current);
                            }
                            gxmessage.DateReceived = GeneXus.Mail.Internals.Pop3.MailMessage.GetMessageDate(m.Headers.Date);
                            AddHeader(gxmessage, "DispositionNotificationTo", m.Headers.DispositionNotificationTo.ToString());
                            ProcessMailAttachments(gxmessage, m.FindAllAttachments());
                        }
                    }
                }
            }catch (Exception e)
            {
                LogError("Receive message error", e.Message, MailConstants.MAIL_ServerRepliedErr, e);
            }
        }
Esempio n. 2
0
        public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            DateTime utcAbsoluteExpiration = DateTimeUtil.ConvertToUniversalTime(absoluteExpiration);

            this._cacheInternal.DoInsert(true, key, value, dependencies, utcAbsoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null, true);
        }
Esempio n. 3
0
        // 典藏移交清单。内置统计方案
        // return:
        //      -1  出错
        //      0   成功
        //      1   用户中断
        int TransferList(out string strError)
        {
            strError = "";

            var items = new List <TransferItem>();

            EnableControls(false);

            stop.OnStop += new StopEventHandler(this.DoStop);
            stop.Initial("正在执行脚本 ...");
            stop.BeginLoop();
            try
            {
                // 搜集信息
                int nRet = DoLoop((string strLogFileName,
                                   string strXml,
                                   bool bInCacheFile,
                                   long lHint,
                                   long lIndex,
                                   long lAttachmentTotalLength,
                                   object param,
                                   out string strError1) =>
                {
                    strError1 = "";

                    XmlDocument dom = new XmlDocument();
                    dom.LoadXml(strXml);

                    // 搜集全部相关日志记录
                    string operation = DomUtil.GetElementText(dom.DocumentElement, "operation");
                    if (operation != "setEntity")
                    {
                        return(0);
                    }

                    string action = DomUtil.GetElementText(dom.DocumentElement, "action");
                    if (action != "transfer")
                    {
                        return(0);
                    }

                    var item        = new TransferItem();
                    item.BatchNo    = DomUtil.GetElementText(dom.DocumentElement, "batchNo");
                    item.Operator   = DomUtil.GetElementText(dom.DocumentElement, "operator");
                    string operTime = DomUtil.GetElementText(dom.DocumentElement, "operTime");
                    item.OperTime   = DateTimeUtil.FromRfc1123DateTimeString(operTime).ToLocalTime();

                    XmlDocument old_itemdom = new XmlDocument();
                    old_itemdom.LoadXml(DomUtil.GetElementText(dom.DocumentElement, "oldRecord"));

                    item.SourceLocation = DomUtil.GetElementText(old_itemdom.DocumentElement, "location");

                    string new_xml          = DomUtil.GetElementText(dom.DocumentElement, "record", out XmlNode node);
                    XmlDocument new_itemdom = new XmlDocument();
                    new_itemdom.LoadXml(new_xml);

                    item.TargetLocation = DomUtil.GetElementText(new_itemdom.DocumentElement, "location");
                    item.Barcode        = DomUtil.GetElementText(new_itemdom.DocumentElement, "barcode");
                    item.RecPath        = ((XmlElement)node).GetAttribute("recPath");
                    item.NewXml         = new_xml;
                    item.Style          = DomUtil.GetElementText(dom.DocumentElement, "style");
                    items.Add(item);
                    return(0);
                },
                                  out strError);
                if (nRet == -1 || nRet == 1)
                {
                    return(nRet);
                }
            }
            finally
            {
                stop.EndLoop();
                stop.OnStop -= new StopEventHandler(this.DoStop);
                stop.Initial("");
                stop.HideProgress();

                EnableControls(true);
            }

            // 让用户选择需要统计的范围。根据批次号、目标位置来进行选择
            var list = items.GroupBy(
                x => new { x.BatchNo, x.TargetLocation },
                (key, item_list) => new TransferGroup
            {
                BatchNo        = key.BatchNo,
                TargetLocation = key.TargetLocation,
                Items          = new List <TransferItem>(item_list)
            }).ToList();

            List <TransferGroup> groups = null;
            bool output_one_sheet       = true;

            using (var dlg = new SelectOutputRangeDialog())
            {
                dlg.Font   = this.Font;
                dlg.Groups = list;


                dlg.UiState = Program.MainForm.AppInfo.GetString(
                    "OperLogStatisForm",
                    "SelectOutputRangeDialog_uiState",
                    "");
                Program.MainForm.AppInfo.LinkFormState(dlg, "SelectOutputRangeDialog_formstate");
                dlg.ShowDialog(this);

                Program.MainForm.AppInfo.SetString(
                    "OperLogStatisForm",
                    "SelectOutputRangeDialog_uiState",
                    dlg.UiState);

                if (dlg.DialogResult == DialogResult.Cancel)
                {
                    return(1);
                }
                groups           = dlg.SelectedGroups;
                output_one_sheet = dlg.OutputOneSheet;
            }

            this.ShowMessage("正在创建 Excel 报表 ...");

            string fileName = "";

            // 创建 Excel 报表
            // 询问文件名
            using (SaveFileDialog dlg = new SaveFileDialog
            {
                Title = "请指定要输出的 Excel 文件名",
                CreatePrompt = false,
                OverwritePrompt = true,
                // dlg.FileName = this.ExportExcelFilename;
                // dlg.InitialDirectory = Environment.CurrentDirectory;
                Filter = "Excel 文件 (*.xlsx)|*.xlsx|All files (*.*)|*.*",
                RestoreDirectory = true
            })
            {
                if (dlg.ShowDialog() != DialogResult.OK)
                {
                    return(0);
                }

                fileName = dlg.FileName;

                XLWorkbook doc = null;
                try
                {
                    doc = new XLWorkbook(XLEventTracking.Disabled);
                    File.Delete(dlg.FileName);
                }
                catch (Exception ex)
                {
                    strError = ExceptionUtil.GetAutoText(ex);
                    return(-1);
                }

                if (output_one_sheet)
                {
                    CreateSheet(doc,
                                "典藏移交清单",
                                groups);
                }
                else
                {
                    int count = groups.Count;
                    int i     = 0;
                    foreach (var group in groups)
                    {
                        CreateSheet(doc,
                                    $"{++i} {count} {group.BatchNo}-{group.TargetLocation}",
                                    // Cut($"({++i} of {count})", 31),
                                    new List <TransferGroup> {
                            group
                        });
                    }
                }

                doc.SaveAs(dlg.FileName);
            }

            this.ClearMessage();

            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch
            {
            }
            return(0);
        }
Esempio n. 4
0
        protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            var releases = new List <ReleaseInfo>();

            var cats = MapTorznabCapsToTrackers(query);

            if (cats.Count == 0)
            {
                cats = GetAllTrackerCategories();
            }
            var catStr    = string.Join(";", cats);
            var searchUrl = SearchUrl + "?" + catStr;

            if (query.IsImdbQuery)
            {
                searchUrl += ";q=" + query.ImdbID;
            }
            else
            {
                searchUrl += ";q=" + WebUtilityHelpers.UrlEncode(query.GetQueryString(), Encoding);
            }

            var results = await RequestWithCookiesAndRetryAsync(searchUrl);

            // Check for being logged out
            if (results.IsRedirect)
            {
                if (results.RedirectingTo.Contains("login.php"))
                {
                    throw new Exception("The user is not logged in. It is possible that the cookie has expired or you made a mistake when copying it. Please check the settings.");
                }
                else
                {
                    throw new Exception($"Got a redirect to {results.RedirectingTo}, please adjust your the alternative link");
                }
            }

            try
            {
                var rows = JsonConvert.DeserializeObject <dynamic>(results.ContentString);

                foreach (var row in rows)
                {
                    var title = (string)row.name;
                    if ((!query.IsImdbQuery || !TorznabCaps.MovieSearchImdbAvailable) && !query.MatchQueryStringAND(title))
                    {
                        continue;
                    }
                    var torrentId          = (long)row.t;
                    var comments           = new Uri(SiteLink + "details.php?id=" + torrentId);
                    var seeders            = (int)row.seeders;
                    var imdbId             = (string)row["imdb-id"];
                    var downloadMultiplier = (double?)row["download-multiplier"] ?? 1;
                    var link        = new Uri(SiteLink + "download.php/" + torrentId + "/" + torrentId + ".torrent");
                    var publishDate = DateTimeUtil.UnixTimestampToDateTime((long)row.ctime).ToLocalTime();
                    var imdb        = ParseUtil.GetImdbID(imdbId);

                    var release = new ReleaseInfo
                    {
                        Title                = title,
                        Comments             = comments,
                        Guid                 = comments,
                        Link                 = link,
                        PublishDate          = publishDate,
                        Category             = MapTrackerCatToNewznab(row.c.ToString()),
                        Size                 = (long)row.size,
                        Files                = (long)row.files,
                        Grabs                = (long)row.completed,
                        Seeders              = seeders,
                        Peers                = seeders + (int)row.leechers,
                        Imdb                 = imdb,
                        DownloadVolumeFactor = downloadMultiplier,
                        UploadVolumeFactor   = 1,
                        MinimumRatio         = 1,
                        MinimumSeedTime      = 172800 // 48 hours
                    };

                    releases.Add(release);
                }
            }
            catch (Exception ex)
            {
                OnParseError(results.ContentString, ex);
            }
            return(releases);
        }
Esempio n. 5
0
 public DataAddress[] GetHistoricalSnapshots(string pathName, DateTime timeStart, DateTime timeEnd)
 {
     // Return the historical root nodes
     return(treeSystem.GetPathHistorical(pathName, DateTimeUtil.GetMillis(timeStart), DateTimeUtil.GetMillis(timeEnd)));
 }
Esempio n. 6
0
        // 将IssueInfo数组中处在指定时间范围以外的行移除
        public static void RemoveOutofTimeRangeOrderInfos(ref List <IssueInfo> issue_infos,
                                                          TimeFilter filter)
        {
            // 不过滤
            if (filter.Style == "none")
            {
                return;
            }
            string   strLastArrivedPublishTime = "";
            DateTime start = filter.StartTime;
            DateTime end   = filter.EndTime;

            // 寻找实到1册以上的最后一期
            for (int i = 0; i < issue_infos.Count; i++)
            {
                IssueInfo info = issue_infos[i];

                int nArrivedCount = 0;

                try
                {
                    nArrivedCount = Convert.ToInt32(info.ArrivedCount);
                }
                catch
                {
                }

                if (nArrivedCount > 0)
                {
                    string strTemp = DateTimeUtil.ForcePublishTime8(info.PublishTime);

                    if (string.Compare(strTemp, strLastArrivedPublishTime) > 0)
                    {
                        strLastArrivedPublishTime = strTemp;
                    }
                }
            }

            // 校正end,使得它表示最后一个实际到达的期的出版日期
            if (String.IsNullOrEmpty(strLastArrivedPublishTime) == false)
            {
                DateTime last = DateTimeUtil.Long8ToDateTime(strLastArrivedPublishTime);
                if (last > end)
                {
                    end = last;
                }
            }

            for (int i = 0; i < issue_infos.Count; i++)
            {
                IssueInfo info = issue_infos[i];

                string strPublishTime = DateTimeUtil.ForcePublishTime8(info.PublishTime);

                DateTime publish_time = DateTimeUtil.Long8ToDateTime(strPublishTime);

                if (publish_time < start || (publish_time > end && end != new DateTime(0)))
                {
                    issue_infos.RemoveAt(i);
                    i--;
                }
            }
        }
Esempio n. 7
0
        // 预测下一期的出版时间
        // exception:
        //      可能因strPublishTime为不可能的日期而抛出异常
        // parameters:
        //      strPublishTime  当前这一期出版时间
        //      nIssueCount 一年内出多少期
        static string NextPublishTime(string strPublishTime,
                                      int nIssueCount)
        {
            DateTime now = DateTimeUtil.Long8ToDateTime(strPublishTime);

            // 一年一期
            if (nIssueCount == 1)
            {
                return(DateTimeUtil.DateTimeToString8(DateTimeUtil.NextYear(now)));
            }

            // 一年两期
            if (nIssueCount == 2)
            {
                // 6个月以后的同日
                for (int i = 0; i < 6; i++)
                {
                    now = DateTimeUtil.NextMonth(now);
                }

                return(DateTimeUtil.DateTimeToString8(now));
            }

            // 一年三期
            if (nIssueCount == 3)
            {
                // 4个月以后的同日
                for (int i = 0; i < 4; i++)
                {
                    now = DateTimeUtil.NextMonth(now);
                }

                return(DateTimeUtil.DateTimeToString8(now));
            }

            // 一年4期
            if (nIssueCount == 4)
            {
                // 3个月以后的同日
                for (int i = 0; i < 3; i++)
                {
                    now = DateTimeUtil.NextMonth(now);
                }

                return(DateTimeUtil.DateTimeToString8(now));
            }

            // 一年5期 和一年6期处理办法一样
            // 一年6期
            if (nIssueCount == 5 || nIssueCount == 6)
            {
                //
                // 2个月以后的同日
                for (int i = 0; i < 2; i++)
                {
                    now = DateTimeUtil.NextMonth(now);
                }

                return(DateTimeUtil.DateTimeToString8(now));
            }

            // 一年7/8/9/10/11期 和一年12期处理办法一样
            // 一年12期
            if (nIssueCount >= 7 && nIssueCount <= 12)
            {
                // 1个月以后的同日
                now = DateTimeUtil.NextMonth(now);

                return(DateTimeUtil.DateTimeToString8(now));
            }

            // 一年24期
            if (nIssueCount == 24)
            {
                // 15天以后
                now += new TimeSpan(15, 0, 0, 0);
                return(DateTimeUtil.DateTimeToString8(now));
            }

            // 一年36期
            if (nIssueCount == 36)
            {
                // 10天以后
                now += new TimeSpan(10, 0, 0, 0);
                return(DateTimeUtil.DateTimeToString8(now));
            }

            // 一年48期
            if (nIssueCount == 48)
            {
                // 7天以后
                now += new TimeSpan(7, 0, 0, 0);
                return(DateTimeUtil.DateTimeToString8(now));
            }

            return("????????");  // 无法处理的情形
        }
Esempio n. 8
0
        /// <summary>
        /// Execute our search query
        /// </summary>
        /// <param name="query">Query</param>
        /// <returns>Releases</returns>
        protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            var releases        = new List <ReleaseInfo>();
            var torrentRowList  = new List <CQ>();
            var exactSearchTerm = query.GetQueryString();
            var searchUrl       = SearchUrl;

            // Check login before performing a query
            await CheckLogin();

            // Check cache first so we don't query the server (if search term used or not in dev mode)
            if (!DevMode && !string.IsNullOrEmpty(exactSearchTerm))
            {
                lock (cache)
                {
                    // Remove old cache items
                    CleanCache();

                    // Search in cache
                    var cachedResult = cache.FirstOrDefault(i => i.Query == exactSearchTerm);
                    if (cachedResult != null)
                    {
                        return(cachedResult.Results.Select(s => (ReleaseInfo)s.Clone()).ToArray());
                    }
                }
            }

            var SearchTerms = new List <string> {
                exactSearchTerm
            };

            // duplicate search without diacritics
            var baseSearchTerm = StringUtil.RemoveDiacritics(exactSearchTerm);

            if (baseSearchTerm != exactSearchTerm)
            {
                SearchTerms.Add(baseSearchTerm);
            }

            foreach (var searchTerm in SearchTerms)
            {
                // Build our query
                var request = BuildQuery(searchTerm, query, searchUrl);

                // Getting results & Store content
                var response = await RequestStringWithCookiesAndRetry(request, ConfigData.CookieHeader.Value);

                _fDom = response.Content;

                try
                {
                    var firstPageRows = FindTorrentRows();

                    // Add them to torrents list
                    torrentRowList.AddRange(firstPageRows.Select(fRow => fRow.Cq()));

                    // If pagination available
                    int nbResults;
                    int pageLinkCount;
                    nbResults     = 1;
                    pageLinkCount = 1;

                    // Check if we have a minimum of one result
                    if (firstPageRows.Length > 1)
                    {
                        // Retrieve total count on our alone page
                        nbResults = firstPageRows.Count();
                    }
                    else
                    {
                        // Check if no result
                        if (torrentRowList.Count == 0)
                        {
                            // No results found
                            Output("\nNo result found for your query, please try another search term or change the theme you're currently using on the site as this is an unsupported solution...\n", "info");

                            // No result found for this query
                            break;
                        }
                    }

                    Output("\nFound " + nbResults + " result(s) (+/- " + firstPageRows.Length + ") in " + pageLinkCount + " page(s) for this query !");
                    Output("\nThere are " + (firstPageRows.Length - 2) + " results on the first page !");

                    // Loop on results

                    foreach (var tRow in torrentRowList.Skip(1).Take(torrentRowList.Count - 2))
                    {
                        Output("Torrent #" + (releases.Count + 1));

                        // ID
                        var idOrig = tRow.Find("td:eq(1) > a:eq(0)").Attr("href").Split('=')[1];
                        var id     = idOrig.Substring(0, idOrig.Length - 4);
                        Output("ID: " + id);

                        // Release Name
                        var name = tRow.Find("td:eq(1) > a:eq(0)").Text();

                        // Category
                        string categoryID = tRow.Find("td:eq(0) > a:eq(0)").Attr("href").Split('?').Last();
                        var    newznab    = MapTrackerCatToNewznab(categoryID);
                        Output("Category: " + MapTrackerCatToNewznab(categoryID).First().ToString() + " (" + categoryID + ")");

                        // Seeders
                        int seeders = ParseUtil.CoerceInt(Regex.Match(tRow.Find("td:eq(9)").Text(), @"\d+").Value);
                        Output("Seeders: " + seeders);

                        // Leechers
                        int leechers = ParseUtil.CoerceInt(Regex.Match(tRow.Find("td:eq(10)").Text(), @"\d+").Value);
                        Output("Leechers: " + leechers);

                        // Files
                        int files = 1;
                        files = ParseUtil.CoerceInt(Regex.Match(tRow.Find("td:eq(4)").Text(), @"\d+").Value);
                        Output("Files: " + files);

                        // Completed
                        int completed = ParseUtil.CoerceInt(Regex.Match(tRow.Find("td:eq(8)").Text(), @"\d+").Value);
                        Output("Completed: " + completed);

                        // Size
                        var humanSize = tRow.Find("td:eq(7)").Text().ToLowerInvariant();
                        var size      = ReleaseInfo.GetBytes(humanSize);
                        Output("Size: " + humanSize + " (" + size + " bytes)");

                        // Publish DateToString
                        var dateTimeOrig = tRow.Find("td:eq(6)").Text();
                        var datestr      = Regex.Replace(dateTimeOrig, @"<[^>]+>|&nbsp;", "").Trim();
                        datestr = Regex.Replace(datestr, "Today", DateTime.Now.ToString("MMM dd yyyy"), RegexOptions.IgnoreCase);
                        datestr = Regex.Replace(datestr, "Yesterday", DateTime.Now.Date.AddDays(-1).ToString("MMM dd yyyy"), RegexOptions.IgnoreCase);
                        DateTime date = DateTimeUtil.FromUnknown(datestr, "DK");
                        Output("Released on: " + date);

                        // Torrent Details URL
                        var detailsLink = new Uri(TorrentDescriptionUrl.Replace("{id}", id.ToString()));
                        Output("Details: " + detailsLink.AbsoluteUri);

                        // Torrent Comments URL
                        var commentsLink = new Uri(TorrentCommentUrl.Replace("{id}", id.ToString()));
                        Output("Comments Link: " + commentsLink.AbsoluteUri);

                        // Torrent Download URL
                        var passkey      = tRow.Find("td:eq(2) > a:eq(0)").Attr("href");
                        var key          = Regex.Match(passkey, "(?<=torrent_pass\\=)([a-zA-z0-9]*)");
                        Uri downloadLink = new Uri(TorrentDownloadUrl.Replace("{id}", id.ToString()).Replace("{passkey}", key.ToString()));
                        Output("Download Link: " + downloadLink.AbsoluteUri);

                        // Building release infos
                        var release = new ReleaseInfo
                        {
                            Category        = MapTrackerCatToNewznab(categoryID.ToString()),
                            Title           = name,
                            Seeders         = seeders,
                            Peers           = seeders + leechers,
                            MinimumRatio    = 1,
                            MinimumSeedTime = 172800,
                            PublishDate     = date,
                            Size            = size,
                            Files           = files,
                            Grabs           = completed,
                            Guid            = detailsLink,
                            Comments        = commentsLink,
                            Link            = downloadLink
                        };

                        // IMDB
                        var imdbLink = tRow.Find("a[href*=\"http://imdb.com/title/\"]").First().Attr("href");
                        release.Imdb = ParseUtil.GetLongFromString(imdbLink);

                        if (tRow.Find("img[title=\"Free Torrent\"]").Length >= 1)
                        {
                            release.DownloadVolumeFactor = 0;
                        }
                        else if (tRow.Find("img[title=\"Halfleech\"]").Length >= 1)
                        {
                            release.DownloadVolumeFactor = 0.5;
                        }
                        else if (tRow.Find("img[title=\"90% Freeleech\"]").Length >= 1)
                        {
                            release.DownloadVolumeFactor = 0.1;
                        }
                        else
                        {
                            release.DownloadVolumeFactor = 1;
                        }

                        release.UploadVolumeFactor = 1;

                        releases.Add(release);
                    }
                }
                catch (Exception ex)
                {
                    OnParseError("Error, unable to parse result \n" + ex.StackTrace, ex);
                }
            }
            // Return found releases
            return(releases);
        }
Esempio n. 9
0
        /*
         *  General sytax as defined in RFC822 for Date header is:
         *  [day ","] date time
         *  where
         *  day = Mon/Tue/Wed/Thu/Fri/Sat/Sun
         *  date = 1*2DIGITS month 2DIGITS
         *  month = Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec
         *  time = hour zone
         *  hour = 2DIGIT:2DIGIT[:2DIGIT] (hh:mm:ss) 00:00:00 - 23:59:59
         *  zone = (( "+" / "-" ) 4DIGIT) UT/GMT/EST/EDT/CST/CDT/MST/MDT/PST/PDT/1ALPHA
         */
        internal static DateTime GetMessageDate(string stringDate)
        {
            DateTime messageTime;

            try
            {
                bool     oldDateSpec = (stringDate.IndexOf("/") != -1);
                bool     hasStrDay   = (stringDate.IndexOf(",") > 0);           //StrDay is not empty
                string   dateStr     = RemoveQuotes(stringDate.Replace("/", " ").Replace(",", "").Trim());
                string[] dateParts   = dateStr.Split(" ".ToCharArray());

                int i = hasStrDay?0:-1;
                if (!IsNumber(dateParts[i + 1]))
                {
                    i = i + 1;
                }

                if (oldDateSpec)
                {
                    string[] tmpDateParts = new string[dateParts.Length];
                    for (int j = 0; j < dateParts.Length; j++)
                    {
                        if (j == (i + 1))
                        {
                            tmpDateParts[j] = dateParts[i + 2];
                        }
                        else if (j == (i + 2))
                        {
                            tmpDateParts[j] = dateParts[i + 1];
                        }
                        else
                        {
                            tmpDateParts[j] = dateParts[j];
                        }
                    }
                    dateParts = tmpDateParts;
                }

                //parse date
                int day   = int.Parse(dateParts[i + 1]);
                int month = oldDateSpec?int.Parse(dateParts[i + 2]):GetMonthIndex(dateParts[i + 2]);
                int year  = int.Parse(dateParts[i + 3]);

                //parse time
                string[] tmpTime = dateParts[i + 4].Split(":".ToCharArray());
                int      hr = int.Parse(tmpTime[0]);
                int      mm = 0, ss = 0;

                if (tmpTime.Length > 1)
                {
                    mm = int.Parse(tmpTime[1]);
                }

                if (tmpTime.Length > 2)
                {
                    ss = int.Parse(tmpTime[2]);
                }

                string timeZoneOffset = string.Empty;
                if (dateParts.Length > i + 5)
                {
                    timeZoneOffset = dateParts[i + 5];
                }

                messageTime = DateTimeUtil.DateTimeWithTimeZoneToUTC(year, month, day, hr, mm, ss, timeZoneOffset);
                if (GeneXus.Application.GxContext.Current != null)
                {
                    messageTime = DateTimeUtil.FromTimeZone(messageTime, "Etc/UTC", GeneXus.Application.GxContext.Current);
                }
                else
                {
                    messageTime = messageTime.ToLocalTime();
                }
            }
            catch
            {
                messageTime = DateTime.Now;
            }
            return(messageTime);
        }
Esempio n. 10
0
        // GET: WeChat
        public ActionResult Index()
        {
            logger.Info(this.GetType().FullName + " - Index....");
            WeChatChargeModel model = new WeChatChargeModel();

            //get weichat account openid from redirect URL parameters
            if (!string.IsNullOrEmpty(Request["openid"]))
            {
                model.OpenId             = Request["openid"].ToString();
                Session["wechat_openid"] = model.OpenId;
            }
            else
            {
                if (Session["wechat_openid"] != null)
                {
                    logger.Info("already has wechat openid stored.");
                    model.OpenId = Session["wechat_openid"] != null ? Session["wechat_openid"].ToString() : "";
                }
                else
                {
                    string code = Request["code"];
                    if (!string.IsNullOrEmpty(code))
                    {
                        logger.Info("new request from wechat public account, code is " + code);
                        AccessToken weChatAccessToken = AuthHelper.GetAccessToken(PersistentValueManager.config, code);
                        if (weChatAccessToken != null)
                        {
                            logger.Info("get wechat account openid by code " + code);
                            model.OpenId             = weChatAccessToken.OpenId;
                            Session["wechat_openid"] = model.OpenId;
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(model.OpenId))
            {
                logger.Info("Wechat OpenId:" + model.OpenId);
            }
            else
            {
                logger.Error("Wechat OpenId is empty, cannot processing any more.");
            }
            model.nancestr = Guid.NewGuid().ToString().Replace("-", "");
            if (model.nancestr.Length > 32)
            {
                model.nancestr = model.nancestr.Substring(0, 32);
            }
            model.appid     = PersistentValueManager.config.APPID;
            model.timestamp = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now).ToString();
            SortedDictionary <string, string> param = new SortedDictionary <string, string>();
            JSAPITicket ticket = PersistentValueManager.GetWeChatJsApiTicket();

            if (ticket != null)
            {
                param.Add("jsapi_ticket", ticket.Ticket);
                logger.Info("jsapi_ticket:" + ticket.Ticket);
            }
            //param.Add("appId", model.appid);
            param.Add("timestamp", model.timestamp);
            param.Add("noncestr", model.nancestr);
            param.Add("url", Request.Url.AbsoluteUri.ToString());
            logger.Info(Request.Url.AbsoluteUri.ToString());
            //param.Add("jsApiList", "[chooseWXPay]");
            string sign = UrlSignUtil.SHA1_Hash(param);

            model.signature = sign;
            logger.Info("Done Index....");
            return(View(model));
        }
Esempio n. 11
0
        public JsonResult PreCharge(WeChatChargeModel model)
        {
            logger.Info("WeChatController.PreCharge......................................................");
            ApiMessage  message = new ApiMessage();
            ChargeOrder order   = null;

            if (ModelState.IsValid)
            {
                try
                {
                    if (string.IsNullOrEmpty(model.OpenId))
                    {
                        message.Status  = "ERROR";
                        message.Message = "请从公众号菜单打开此页面";
                        return(Json(message, JsonRequestBehavior.AllowGet));
                    }
                    //ChargeBridge cb = new ChargeBridge();
                    order = new ChargeOrder()
                    {
                        ChargeType       = 0,
                        AgencyId         = 0,
                        Id               = 0,
                        Province         = model.Province,
                        City             = model.City,
                        MobileSP         = model.SPName,
                        MobileNumber     = model.Mobile,
                        OutOrderId       = "",
                        ResourceId       = 0,
                        ResourceTaocanId = model.ResourceTaocanId,
                        RouteId          = 0,
                        CreatedTime      = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now),
                        Payed            = false,
                        OpenId           = model.OpenId,
                        OpenAccountType  = 1
                    };
                    //
                    OrderManagement    orderMgt    = new OrderManagement();
                    ResourceManagement resourceMgr = new ResourceManagement(0);

                    string msg = string.Empty;
                    if (orderMgt.IsThisMonthCharged(order.MobileNumber, order.ResourceTaocanId, out msg))
                    {
                        message.Status  = "ERROR";
                        message.Message = msg;
                        return(Json(message, JsonRequestBehavior.AllowGet));
                    }

                    order = orderMgt.GenerateOrder(order);
                    int total = 0;
                    List <BResourceTaocan> taocans = resourceMgr.FindResourceTaocans(order.ResourceTaocanId, 0, 0, out total);
                    if (taocans == null || taocans.Count == 0)
                    {
                        message.Message = "当前套餐不可用";
                        message.Status  = "ERROR";
                        return(Json(message, JsonRequestBehavior.AllowGet));
                    }
                    logger.Info(string.Format("Order is generated, Id - {0}, mobile - {1}", order.Id, order.MobileNumber));
                    BResourceTaocan taocan = taocans[0];
                    message.Status  = "OK";
                    message.Message = "预充值订单已经生成";
                    message.Item    = null;
                    //
                    string ip = Request.ServerVariables["REMOTE_ADDR"];
                    if (ip != null && ip.IndexOf("::") > -1)
                    {
                        ip = "127.0.0.1";
                    }
                    string prepayId = WeChatPaymentWrapper.GetPrepayId(PersistentValueManager.config, Session["wechat_openid"] != null ? Session["wechat_openid"].ToString() : "", order.PaymentId.ToString(), "TEST WECHATPAY", ip, (int)taocan.Taocan.Sale_price * 100, TradeType.JSAPI);
                    logger.Info(string.Format("Prepay Id - {0}", prepayId));
                    WeChatOrder weOrder = new WeChatOrder();
                    weOrder.Order = new ChargeOrder {
                        Id = order.Id, Payed = order.Payed, PaymentId = order.PaymentId, MobileNumber = order.MobileNumber, MobileSP = order.MobileSP, Province = order.Province
                    };
                    weOrder.PrepayId = prepayId;
                    weOrder.PaySign  = "";
                    message.Item     = weOrder;

                    AccessToken token  = PersistentValueManager.GetWeChatAccessToken();
                    JSAPITicket ticket = PersistentValueManager.GetWeChatJsApiTicket();
                    SortedDictionary <string, string> parameters = new SortedDictionary <string, string>();
                    parameters.Add("appId", PersistentValueManager.config.APPID);
                    parameters.Add("timeStamp", model.timestamp);
                    parameters.Add("nonceStr", model.nancestr);
                    parameters.Add("package", "prepay_id=" + prepayId);
                    parameters.Add("signType", "MD5");

                    logger.Info(string.Format("timeStamp:{0}", model.timestamp));
                    logger.Info(string.Format("nonceStr:{0}", model.nancestr));
                    logger.Info(string.Format("package:{0}", "prepay_id=" + prepayId));

                    string querystr = null;
                    foreach (KeyValuePair <string, string> para in parameters)
                    {
                        if (querystr == null)
                        {
                            querystr = para.Key + "=" + para.Value;
                        }
                        else
                        {
                            querystr += "&" + para.Key + "=" + para.Value;
                        }
                    }
                    querystr += "&key=" + PersistentValueManager.config.ShopSecret;
                    logger.Info(querystr);
                    string sign = UrlSignUtil.GetMD5(querystr);
                    model.paySign   = sign.ToUpper();
                    model.prepay_id = prepayId;
                    logger.Info(string.Format("paySign:{0}", sign.ToUpper()));
                    message.Item = model;
                }
                catch (KMBitException kex)
                {
                    logger.Error(kex);
                    message.Message = kex.Message;
                    message.Status  = "ERROR";
                }
                catch (Exception ex)
                {
                    message.Message = "未知错误,请联系我们";
                    message.Status  = "ERROR";
                    logger.Fatal(ex);
                }
                finally
                {
                }
            }

            logger.Info("Done.");
            return(Json(message, JsonRequestBehavior.AllowGet));
        }
Esempio n. 12
0
 void executePrivate( )
 {
     /* GeneXus formulas */
     /* Output device settings */
     AV10tNowDate         = DateTimeUtil.ServerNow(context, pr_default);
     AV11tJWTTokenContent = "";
     AV15tAllCookieName.FromJSonString(new zutil_getallcookiename(context).executeUdp( ), null);
     AV18I = 1;
     while (AV18I <= AV15tAllCookieName.Count)
     {
         if ((StringUtil.StrCmp(StringUtil.Trim(((String)AV15tAllCookieName.Item(AV18I))), "GX_CLIENT_ID") != 0) && (StringUtil.StrCmp(StringUtil.Trim(((String)AV15tAllCookieName.Item(AV18I))), "GX_SESSION_ID") != 0) && (StringUtil.StrCmp(StringUtil.Trim(((String)AV15tAllCookieName.Item(AV18I))), "GxTZOffset") != 0))
         {
             AV9tSetFlag = context.SetCookie(((String)AV15tAllCookieName.Item(AV18I)), "", "/", DateTimeUtil.TAdd(AV10tNowDate, 86400 * (-5)), "", 0);
         }
         AV18I = (short)(AV18I + 1);
     }
     AV14websession.Clear();
     this.cleanup();
 }
Esempio n. 13
0
        private async Task <IEnumerable <ReleaseInfo> > GetReleases(string resultUrl, bool latestOnly, string titleContains = null)
        {
            var releases = new List <ReleaseInfo>();
            var parser   = new HtmlParser();

            var response = await RequestStringWithCookiesAndRetry(resultUrl);

            await FollowIfRedirect(response);

            try
            {
                var match = Regex.Match(response.Content, "(var hs_showid = )([0-9]*)(;)", RegexOptions.IgnoreCase);
                if (match.Success == false)
                {
                    return(releases);
                }

                var showId = int.Parse(match.Groups[2].Value);

                var apiUrls = new [] {
                    ApiEndpoint + "?method=getshows&type=batch&showid=" + showId, // https://horriblesubs.info/api.php?method=getshows&type=batch&showid=1194
                    ApiEndpoint + "?method=getshows&type=show&showid=" + showId   // https://horriblesubs.info/api.php?method=getshows&type=show&showid=869
                };

                var rows = new List <IElement>();
                foreach (var apiUrl in apiUrls)
                {
                    var nextId = 0;
                    while (true)
                    {
                        var showApiResponse = await RequestStringWithCookiesAndRetry(apiUrl + "&nextid=" + nextId);

                        var showApiDom        = parser.ParseDocument(showApiResponse.Content);
                        var releaseRowResults = showApiDom.QuerySelectorAll("div.rls-info-container");
                        rows.AddRange(releaseRowResults);
                        nextId++;

                        if (releaseRowResults.Length == 0 || latestOnly)
                        {
                            break;
                        }
                    }
                }

                foreach (var row in rows)
                {
                    var dateStr     = row.QuerySelector(".rls-date").TextContent.Trim();
                    var publishDate = DateTimeUtil.FromUnknown(dateStr);

                    var qTitle = row.QuerySelector("a");
                    var title  = qTitle.TextContent;
                    title = title.Replace("SD720p1080p", "");
                    title = title.Replace(dateStr, "");

                    if (!string.IsNullOrWhiteSpace(titleContains) && !title.Contains(titleContains))
                    {
                        continue;
                    }

                    // Ensure fansub group name is present in the title
                    // This is needed for things like configuring tag restrictions in Sonarr
                    if (!title.Contains("[HorribleSubs]"))
                    {
                        title = "[HorribleSubs] " + title;
                    }

                    var episode  = qTitle.QuerySelector("strong")?.TextContent;
                    var comments = new Uri(resultUrl + (episode != null ? "#" + episode : ""));

                    var p480 = row.QuerySelector(".link-480p");
                    if (p480 != null) // size = 400 MB
                    {
                        AddRelease(releases, p480, $"{title} [480p]", 419430400, comments, publishDate);
                    }

                    var p720 = row.QuerySelector(".link-720p");
                    if (p720 != null) // size 700 MB
                    {
                        AddRelease(releases, p720, $"{title} [720p]", 734003200, comments, publishDate);
                    }

                    var p1080 = row.QuerySelector(".link-1080p");
                    if (p1080 != null) // size 1.4 GB
                    {
                        AddRelease(releases, p1080, $"{title} [1080p]", 1503238553, comments, publishDate);
                    }
                }
            }
            catch (Exception ex)
            {
                OnParseError(response.Content, ex);
            }
            return(releases);
        }
Esempio n. 14
0
 /// <summary>
 /// 转换为日期字符串
 /// </summary>
 /// <param name="dt">日期</param>
 /// <returns></returns>
 public static String ToDateString(this DateTime dt)
 {
     return(DateTimeUtil.ToDateString(dt));
 }
Esempio n. 15
0
        // 启动一般监控任务
        public static void StartMonitorTask()
        {
            if (_monitorTask != null)
            {
                return;
            }

            CancellationToken token = _cancel.Token;

            // bool download_complete = false;

            token.Register(() =>
            {
                _eventMonitor.Set();
            });

            _monitorTask = Task.Factory.StartNew(async() =>
            {
                WpfClientInfo.WriteInfoLog("书柜监控专用线程开始");
                try
                {
                    while (token.IsCancellationRequested == false)
                    {
                        // await Task.Delay(TimeSpan.FromSeconds(10));
                        _eventMonitor.WaitOne(_monitorIdleLength);

                        token.ThrowIfCancellationRequested();

                        // ***
                        // 关闭天线射频
                        if (_tagAdded)
                        {
                            _ = Task.Run(async() =>
                            {
                                try
                                {
                                    await SelectAntennaAsync();
                                }
                                catch (Exception ex)
                                {
                                    WpfClientInfo.WriteErrorLog($"关闭天线射频 SelectAntennaAsync() 时出现异常: {ExceptionUtil.GetDebugText(ex)}");
                                }
                            });
                            _tagAdded = false;
                        }

                        if (DateTime.Now - _lastDetectTime > _detectPeriod)
                        {
                            DetectLibraryNetwork();

                            _lastDetectTime = DateTime.Now;
                        }

                        // 提醒关门
                        WarningCloseDoor();

                        // 下载或同步读者信息
                        string startDate = LoadStartDate();
                        if (/*download_complete == false || */
                            string.IsNullOrEmpty(startDate))
                        {
                            // 如果 Config 中没有记载断点位置,说明以前从来没有首次同步过。需要进行一次首次同步
                            if (string.IsNullOrEmpty(startDate))
                            {
                                // SaveStartDate("");

                                var repl_result = await PatronReplication.DownloadAllPatronRecordAsync(token);
                                if (repl_result.Value == -1)
                                {
                                    // TODO: 判断通讯出错的错误码。如果是通讯出错,则稍后需要重试下载
                                }
                                else
                                {
                                    SaveStartDate(repl_result.StartDate);
                                }

                                // 立刻允许接着做一次零星同步
                                ActivateMonitor();
                            }
                            // download_complete = true;
                        }
                        else
                        {
                            // 进行零星同步
                            if (DateTime.Now - _lastReplicateTime > _replicatePeriod)
                            {
                                // string startDate = LoadStartDate();

                                // testing
                                // startDate = "20200507:0-";

                                if (string.IsNullOrEmpty(startDate) == false)
                                {
                                    string endDate = DateTimeUtil.DateTimeToString8(DateTime.Now);

                                    // parameters:
                                    //      strLastDate   处理中断或者结束时返回最后处理过的日期
                                    //      last_index  处理或中断返回时最后处理过的位置。以后继续处理的时候可以从这个偏移开始
                                    // return:
                                    //      -1  出错
                                    //      0   中断
                                    //      1   完成
                                    ReplicationResult repl_result = await PatronReplication.DoReplication(
                                        startDate,
                                        endDate,
                                        LogType.OperLog,
                                        token);
                                    if (repl_result.Value == -1)
                                    {
                                        WpfClientInfo.WriteErrorLog($"同步出错: {repl_result.ErrorInfo}");
                                    }
                                    else if (repl_result.Value == 1)
                                    {
                                        string lastDate = repl_result.LastDate + ":" + repl_result.LastIndex + "-";    // 注意 - 符号不能少。少了意思就会变成每次只获取一条日志记录了
                                        SaveStartDate(lastDate);
                                    }

                                    _lastReplicateTime = DateTime.Now;
                                }
                            }
                        }
                    }
                    _monitorTask = null;
                }
                catch (OperationCanceledException)
                {
                }
                catch (Exception ex)
                {
                    WpfClientInfo.WriteErrorLog($"书柜监控专用线程出现异常: {ExceptionUtil.GetDebugText(ex)}");
                    App.SetError("shelf_monitor", $"书柜监控专用线程出现异常: {ex.Message}");
                }
                finally
                {
                    WpfClientInfo.WriteInfoLog("书柜监控专用线程结束");
                }
            },
                                                 token,
                                                 TaskCreationOptions.LongRunning,
                                                 TaskScheduler.Default);
        }
Esempio n. 16
0
        protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            var releases = new List <ReleaseInfo>();

            var qc = new NameValueCollection();

            if (query.IsImdbQuery)
            {
                qc.Add("q", query.ImdbID);
            }
            else if (!string.IsNullOrWhiteSpace(query.GetQueryString()))
            {
                qc.Add("q", query.GetQueryString());
            }

            foreach (var cat in MapTorznabCapsToTrackers(query))
            {
                qc.Add(cat, string.Empty);
            }

            var searchUrl = SearchUrl + "?" + qc.GetQueryString();
            var response  = await RequestWithCookiesAndRetryAsync(searchUrl, referer : SearchUrl);

            var results = response.ContentString;

            if (results == null || !results.Contains("/lout.php"))
            {
                throw new Exception("The user is not logged in. It is possible that the cookie has expired or you made a mistake when copying it. Please check the settings.");
            }

            if (string.IsNullOrWhiteSpace(query.ImdbID) && string.IsNullOrWhiteSpace(query.SearchTerm) && results.Contains("No Torrents Found!"))
            {
                throw new Exception("Got No Torrents Found! Make sure your IPTorrents profile config contain proper default category settings.");
            }

            try
            {
                var parser = new HtmlParser();
                var doc    = parser.ParseDocument(results);

                var rows = doc.QuerySelectorAll("table[id='torrents'] > tbody > tr");
                foreach (var row in rows)
                {
                    var qTitleLink = row.QuerySelector("a.hv");
                    if (qTitleLink == null) // no results
                    {
                        continue;
                    }

                    // drop invalid char that seems to have cropped up in some titles. #6582
                    var title   = qTitleLink.TextContent.Trim().Replace("\u000f", "");
                    var details = new Uri(SiteLink + qTitleLink.GetAttribute("href").TrimStart('/'));

                    var qLink = row.QuerySelector("a[href^=\"/download.php/\"]");
                    var link  = new Uri(SiteLink + qLink.GetAttribute("href").TrimStart('/'));

                    var descrSplit  = row.QuerySelector("div.sub").TextContent.Split('|');
                    var dateSplit   = descrSplit.Last().Split(new [] { " by " }, StringSplitOptions.None);
                    var publishDate = DateTimeUtil.FromTimeAgo(dateSplit.First());
                    var description = descrSplit.Length > 1 ? "Tags: " + descrSplit.First().Trim() : "";
                    description += dateSplit.Length > 1 ? " Uploaded by: " + dateSplit.Last().Trim() : "";

                    var catIcon = row.QuerySelector("td:nth-of-type(1) a");
                    if (catIcon == null)
                    {
                        // Torrents - Category column == Text or Code
                        // release.Category = MapTrackerCatDescToNewznab(row.Cq().Find("td:eq(0)").Text()); // Works for "Text" but only contains the parent category
                        throw new Exception("Please, change the 'Torrents - Category column' option to 'Icons' in the website Settings. Wait a minute (cache) and then try again.");
                    }
                    // Torrents - Category column == Icons
                    var cat = MapTrackerCatToNewznab(catIcon.GetAttribute("href").Substring(1));

                    var size = ReleaseInfo.GetBytes(row.Children[5].TextContent);

                    var colIndex = 6;
                    int?files    = null;
                    if (row.Children.Length == 10) // files column is enabled in the site settings
                    {
                        files = ParseUtil.CoerceInt(row.Children[colIndex].TextContent.Replace("Go to files", ""));
                        colIndex++;
                    }
                    var grabs          = ParseUtil.CoerceInt(row.Children[colIndex++].TextContent);
                    var seeders        = ParseUtil.CoerceInt(row.Children[colIndex++].TextContent);
                    var leechers       = ParseUtil.CoerceInt(row.Children[colIndex].TextContent);
                    var dlVolumeFactor = row.QuerySelector("span.free") != null ? 0 : 1;

                    var release = new ReleaseInfo
                    {
                        Title                = title,
                        Details              = details,
                        Guid                 = details,
                        Link                 = link,
                        PublishDate          = publishDate,
                        Category             = cat,
                        Description          = description,
                        Size                 = size,
                        Files                = files,
                        Grabs                = grabs,
                        Seeders              = seeders,
                        Peers                = seeders + leechers,
                        DownloadVolumeFactor = dlVolumeFactor,
                        UploadVolumeFactor   = 1,
                        MinimumRatio         = 1,
                        MinimumSeedTime      = 1209600 // 336 hours
                    };

                    releases.Add(release);
                }
            }
            catch (Exception ex)
            {
                OnParseError(results, ex);
            }

            return(releases);
        }
Esempio n. 17
0
        public ApiMessage ExportOrders()
        {
            this.IniRequest();
            ApiMessage message          = new ApiMessage();
            int        orderId          = 0;
            int        agencyId         = 0;
            int        resourceId       = 0;
            int        resourceTaocanId = 0;
            int        status           = 0;
            string     mobileNumber     = null;
            DateTime   sDate            = DateTime.MinValue;
            DateTime   eDate            = DateTime.MinValue;

            if (request["OrderId"] != null)
            {
                int.TryParse(request["OrderId"].ToString(), out orderId);
            }
            if (request["AgencyId"] != null)
            {
                int.TryParse(request["AgencyId"].ToString(), out agencyId);
            }
            if (request["Status"] != null)
            {
                int.TryParse(request["Status"], out status);
            }
            if (request["ResourceId"] != null)
            {
                int.TryParse(request["ResourceId"].ToString(), out resourceId);
            }
            if (request["ResourceTaocanId"] != null)
            {
                int.TryParse(request["ResourceTaocanId"].ToString(), out resourceTaocanId);
            }
            mobileNumber = request["MobileNumber"];
            if (!string.IsNullOrEmpty(request["StartTime"]))
            {
                DateTime.TryParse(request["StartTime"], out sDate);
            }
            if (!string.IsNullOrEmpty(request["EndTime"]))
            {
                DateTime.TryParse(request["EndTime"], out eDate);
            }
            int             total    = 0;
            long            sintDate = sDate != DateTime.MinValue ? DateTimeUtil.ConvertDateTimeToInt(sDate) : 0;
            long            eintDate = eDate != DateTime.MinValue ? DateTimeUtil.ConvertDateTimeToInt(eDate) : 0;
            OrderManagement orderMgr = new OrderManagement(User.Identity.Name);
            List <BOrder>   orders   = orderMgr.FindOrders(orderId,
                                                           agencyId,
                                                           resourceId,
                                                           resourceTaocanId,
                                                           0,
                                                           null, mobileNumber,
                                                           new int[] { status },
                                                           sintDate,
                                                           eintDate,
                                                           out total,
                                                           0,
                                                           0, false);

            message.Status = "OK";

            string       path     = request.PhysicalApplicationPath;
            string       fileName = orderMgr.CurrentLoginUser.User.Id + "_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".csv";
            string       fullPath = System.IO.Path.Combine(path + "\\Temp", fileName);
            FileStream   fs       = null;
            StreamWriter sw       = null;

            try
            {
                fs = new FileStream(fullPath, FileMode.Create);
                sw = new StreamWriter(fs, Encoding.UTF8);
                sw.WriteLine("编号,资源,代理商,手机号,省份,城市,平台成本价,平台售价,代理商代理价,代理商售价,时间,状态");
                foreach (BOrder order in orders)
                {
                    StringBuilder builder = new StringBuilder();
                    builder.Append(order.Id.ToString() + ",");
                    builder.Append(order.ReseouceName + ",");
                    builder.Append((order.AgentName != null ? order.AgentName.ToString() : "") + ",");
                    builder.Append(order.MobilePhone + ",");
                    builder.Append((order.MobileProvince != null ? order.MobileProvince : "") + ",");
                    builder.Append((order.MobileCity != null ? order.MobileCity : "") + ",");
                    builder.Append(order.PlatformCostPrice.ToString("0.00") + ",");
                    builder.Append(order.PlatformSalePrice.ToString("0.00") + ",");
                    builder.Append(order.PurchasePrice.ToString("0.00") + ",");
                    builder.Append(order.SalePrice.ToString("0.00") + ",");
                    builder.Append(DateTimeUtil.ConvertToDateTime(order.CreatedTime).ToString("yyyy-MM-dd HH:mm") + ",");
                    builder.Append(order.StatusText != null ? order.StatusText : "");
                    sw.WriteLine(builder.ToString());
                }
            }
            catch (Exception ex)
            {
                logger.Fatal(ex);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
            message.Item = "http://" + request.Url.Authority + "/Temp/" + fileName;
            return(message);
        }
 public override DateTime Dbms2NetDateTime(DateTime dt, Boolean precision)
 {
     return((precision) ? DateTimeUtil.ResetMicroseconds(dt) : DateTimeUtil.ResetMillisecondsTicks(dt));
 }
Esempio n. 19
0
        //
        /// <summary>
        /// 将IssueInfo数组中处在指定时间范围以外的行移除
        /// </summary>
        /// <param name="issue_infos">要处理的集合</param>
        /// <param name="filter">时间过滤器</param>
        /// <param name="strDebugInfo">返回调试信息</param>
        public static void RemoveOutofTimeRangeOrderInfos(ref List <IssueInfo> issue_infos,
                                                          TimeFilter filter,
                                                          out string strDebugInfo)
        {
            strDebugInfo = "";

            if (filter.Style == "none")
            {
                strDebugInfo = "不进行时间过滤";
                return;
            }

            DateTime start = filter.StartTime;
            DateTime end   = filter.EndTime;

#if NO
            // 寻找实到1册以上的最后一期。这是一个技巧,因为如果某期虽然超过催缺的范围,但它实际上到了,表明比这期时间还要早的期应该也到了。这样就要考虑实际的情况,而不是拘泥操作者设定的时间
            if (filter.VerifyArrivedIssue == true)
            {
                string strLastArrivedPublishTime = "";
                // 寻找实到1册以上的最后一期
                for (int i = 0; i < issue_infos.Count; i++)
                {
                    IssueInfo info = issue_infos[i];

                    int nArrivedCount = 0;

                    try
                    {
                        nArrivedCount = Convert.ToInt32(info.ArrivedCount);
                    }
                    catch
                    {
                    }

                    if (nArrivedCount > 0)
                    {
                        string strTemp = DateTimeUtil.ForcePublishTime8(info.PublishTime);

                        if (string.Compare(strTemp, strLastArrivedPublishTime) > 0)
                        {
                            strLastArrivedPublishTime = strTemp;
                        }
                    }
                }

                // 校正end,使得它表示最后一个实际到达的期的出版日期
                if (String.IsNullOrEmpty(strLastArrivedPublishTime) == false)
                {
                    DateTime last = DateTimeUtil.Long8ToDateTime(strLastArrivedPublishTime);
                    if (last > end)
                    {
                        strDebugInfo += "filter的末尾时间从 " + end.ToShortDateString() + " 修正到实际已到的最后一期 " + last.ToShortDateString() + "\r\n";
                        end           = last;
                    }
                }
            }
#endif

            for (int i = 0; i < issue_infos.Count; i++)
            {
                IssueInfo info = issue_infos[i];

                DateTime publish_time   = new DateTime(0);
                string   strPublishTime = info.PublishTime;
                if (string.IsNullOrEmpty(strPublishTime) == false)
                {
                    strPublishTime = DateTimeUtil.ForcePublishTime8(strPublishTime);
                    publish_time   = DateTimeUtil.Long8ToDateTime(strPublishTime);
                }

                DateTime order_time   = new DateTime(0);
                string   strOrderTime = info.OrderTime;
                if (string.IsNullOrEmpty(strOrderTime) == false)
                {
                    order_time  = DateTimeUtil.FromRfc1123DateTimeString(info.OrderTime).ToLocalTime();
                    order_time += filter.OrderTimeDelta;
                }

                if (filter.Style == "publishtime")
                {
                    if (string.IsNullOrEmpty(strPublishTime) == true)
                    {
                        // 如果坚持要用出版时间,则不处理
                        strDebugInfo += IssueHost.GetIssueString(info) + " 因出版日期为空,被排除\r\n";
                        goto DO_REMOVE;
                    }
                    // 用出版时间来判断
                    if (IssueHost.IsInRange(start, end, publish_time) == false)
                    {
                        strDebugInfo += IssueHost.GetIssueString(info) + " 因出版日期 " + publish_time.ToShortDateString() + " 不在 " + IssueHost.GetRangeString(start, end) + " 范围内,被排除\r\n";
                        goto DO_REMOVE;
                    }
                    goto CONTINUE;
                }

                if (filter.Style == "ordertime")
                {
                    if (string.IsNullOrEmpty(strOrderTime) == true)
                    {
                        // 如果坚持要用订购时间,则不处理
                        strDebugInfo += IssueHost.GetIssueString(info) + " 因订购日期为空,被排除\r\n";
                        goto DO_REMOVE;
                    }
                    // 用订购时间来判断
                    if (IssueHost.IsInRange(start, end, order_time) == false)
                    {
                        strDebugInfo += IssueHost.GetIssueString(info) + " 因订购日期推测的出版日期 " + order_time.ToShortDateString() + " 不在 " + IssueHost.GetRangeString(start, end) + " 范围内,被排除\r\n";
                        goto DO_REMOVE;
                    }
                    goto CONTINUE;
                }

                if (filter.Style == "both")
                {
                    if (string.IsNullOrEmpty(strPublishTime) == false)
                    {
                        // 用出版时间来判断
                        if (IssueHost.IsInRange(start, end, publish_time) == false)
                        {
                            strDebugInfo += IssueHost.GetIssueString(info) + " 因出版日期 " + publish_time.ToShortDateString() + " 不在 " + IssueHost.GetRangeString(start, end) + " 范围内,被排除\r\n";
                            goto DO_REMOVE;
                        }
                        goto CONTINUE;
                    }

                    if (string.IsNullOrEmpty(strOrderTime) == false)
                    {
                        // 用订购时间来判断
                        if (IssueHost.IsInRange(start, end, order_time) == false)
                        {
                            strDebugInfo += IssueHost.GetIssueString(info) + " 因订购日期推测的出版日期 " + order_time.ToShortDateString() + " 不在 " + IssueHost.GetRangeString(start, end) + " 范围内,被排除\r\n";
                            goto DO_REMOVE;
                        }
                        goto CONTINUE;
                    }

                    // 两个时间都为空
                    goto DO_REMOVE;
                }

CONTINUE:
                strDebugInfo += IssueHost.GetIssueString(info) + " 被保留\r\n";
                continue;
DO_REMOVE:
                issue_infos.RemoveAt(i);
                i--;
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Execute our search query
        /// </summary>
        /// <param name="query">Query</param>
        /// <returns>Releases</returns>
        protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            var releases   = new List <ReleaseInfo>();
            var searchTerm = query.SanitizedSearchTerm + " " + query.GetEpisodeSearchString();

            searchTerm = searchTerm.Trim();
            searchTerm = searchTerm.ToLower();
            searchTerm = searchTerm.Replace(" ", ".");

            if (EnhancedAnime && query.HasSpecifiedCategories && (query.Categories.Contains(TorznabCatType.TVAnime.ID) || query.Categories.Contains(100032) || query.Categories.Contains(100101) || query.Categories.Contains(100110)))
            {
                var regex = new Regex(" ([0-9]+)");
                searchTerm = regex.Replace(searchTerm, " E$1");
            }

            logger.Info("\nXthor - Search requested for \"" + searchTerm + "\"");

            // Multiple page support
            var nextPage = 1; var followingPages = true;

            do
            {
                // Build our query
                var request = BuildQuery(searchTerm, query, ApiEndpoint, nextPage);

                // Getting results
                logger.Info("\nXthor - Querying API page " + nextPage);
                var results = await QueryTrackerAsync(request);

                // Torrents Result Count
                var torrentsCount = 0;

                try
                {
                    // Deserialize our Json Response
                    var xthorResponse = JsonConvert.DeserializeObject <XthorResponse>(results);

                    // Check Tracker's State
                    CheckApiState(xthorResponse.Error);

                    // If contains torrents
                    if (xthorResponse.Torrents != null)
                    {
                        // Store torrents rows count result
                        torrentsCount = xthorResponse.Torrents.Count();
                        logger.Info("\nXthor - Found " + torrentsCount + " torrents on current page.");

                        // Adding each torrent row to releases
                        // Exclude hidden torrents (category 106, example => search 'yoda' in the API) #10407
                        releases.AddRange(xthorResponse.Torrents
                                          .Where(torrent => torrent.Category != 106).Select(torrent =>
                        {
                            //issue #3847 replace multi keyword
                            if (!string.IsNullOrEmpty(ReplaceMulti))
                            {
                                var regex    = new Regex("(?i)([\\.\\- ])MULTI([\\.\\- ])");
                                torrent.Name = regex.Replace(torrent.Name, "$1" + ReplaceMulti + "$2");
                            }

                            // issue #8759 replace vostfr and subfrench with English
                            if (ConfigData.Vostfr.Value)
                            {
                                torrent.Name = torrent.Name.Replace("VOSTFR", "ENGLISH").Replace("SUBFRENCH", "ENGLISH");
                            }

                            var publishDate = DateTimeUtil.UnixTimestampToDateTime(torrent.Added);
                            //TODO replace with download link?
                            var guid    = new Uri(TorrentDetailsUrl.Replace("{id}", torrent.Id.ToString()));
                            var details = new Uri(TorrentDetailsUrl.Replace("{id}", torrent.Id.ToString()));
                            var link    = new Uri(torrent.Download_link);
                            var release = new ReleaseInfo
                            {
                                // Mapping data
                                Category             = MapTrackerCatToNewznab(torrent.Category.ToString()),
                                Title                = torrent.Name,
                                Seeders              = torrent.Seeders,
                                Peers                = torrent.Seeders + torrent.Leechers,
                                MinimumRatio         = 1,
                                MinimumSeedTime      = 345600,
                                PublishDate          = publishDate,
                                Size                 = torrent.Size,
                                Grabs                = torrent.Times_completed,
                                Files                = torrent.Numfiles,
                                UploadVolumeFactor   = 1,
                                DownloadVolumeFactor = (torrent.Freeleech == 1 ? 0 : 1),
                                Guid                 = guid,
                                Details              = details,
                                Link                 = link,
                                TMDb                 = torrent.Tmdb_id
                            };

                            return(release);
                        }));
                        nextPage++;
                    }
                    else
                    {
                        logger.Info("\nXthor - No results found on page  " + (nextPage - 1) + ", stopping follow of next page.");
                        //  No results or no more results available
                        followingPages = false;
                    }
                }
                catch (Exception ex)
                {
                    OnParseError("Unable to parse result \n" + ex.StackTrace, ex);
                }

                // Stop ?
                if (nextPage > MaxPageLoads | torrentsCount < 32 | string.IsNullOrWhiteSpace(searchTerm))
                {
                    logger.Info("\nXthor - Stopping follow of next page " + nextPage + " due to page limit or max available results reached or indexer test.");
                    followingPages = false;
                }
            } while (followingPages);

            // Check if there is duplicate and return unique rows - Xthor API can be very buggy !
            var uniqReleases = releases.GroupBy(x => x.Guid).Select(x => x.First()).ToList();

            // Return found releases
            return(uniqReleases);
        }
Esempio n. 21
0
        // 将猜测的期节点合并到this.Issues数组中
        int MergeGuessIssues(List <OneIssue> guess_issues,
                             out string strError)
        {
            strError = "";

            try
            {
                List <int> not_matchs = new List <int>();
                int        nLastIndex = 0;
                TimeSpan   last_delta = new TimeSpan(0);
                for (int i = 0; i < guess_issues.Count; i++)
                {
                    OneIssue guess_issue = guess_issues[i];

                    string strYear  = guess_issue.PublishTime.Substring(0, 4);
                    string strIssue = guess_issue.Issue;

                    // 在this.Issues中根据年、期号查找一个节点
                    // return:
                    //      -1  not found
                    //      >=0 found
                    int index = FindIssue(strYear,
                                          strIssue,
                                          nLastIndex);
                    if (index == -1)
                    {
                        not_matchs.Add(i);  // 没有匹配上的下标

                        // 将一个期节点插入this.Issues数组的适当位置
                        // 可能会抛出异常
                        AddIssueByIssueNo(guess_issue);
                        guess_issue.IsGuess = true;
                    }
                    else
                    {
                        OneIssue found = this.Issues[index];
                        string   strRealPublishTime  = found.PublishTime;
                        string   strGuessPublishTime = guess_issue.PublishTime;

                        strRealPublishTime  = CannonicalizePublishTimeString(strRealPublishTime);
                        strGuessPublishTime = CannonicalizePublishTimeString(strGuessPublishTime);


                        // 看看差多少天,然后对前面没有匹配的节点的出版时间进行相应的平移
                        DateTime real  = DateTimeUtil.Long8ToDateTime(strRealPublishTime);
                        DateTime guess = DateTimeUtil.Long8ToDateTime(strGuessPublishTime);
                        TimeSpan delta = real - guess;

                        last_delta = delta;

                        // 移动出版时间
                        // 可能会抛出异常
                        MovePublishTime(guess_issues,
                                        not_matchs,
                                        delta);
                        not_matchs.Clear();
                    }
                }

                // 最后一段没有匹配上的
                if (not_matchs.Count > 0 &&
                    last_delta != new TimeSpan(0))
                {
                    // 移动出版时间
                    // 可能会抛出异常
                    MovePublishTime(guess_issues,
                                    not_matchs,
                                    last_delta);
                    not_matchs.Clear();
                }

                return(0);
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                return(-1);
            }
        }
Esempio n. 22
0
        public WorldListEntry([NotNull] XElement el)
        {
            if (el == null)
            {
                throw new ArgumentNullException("el");
            }
            XAttribute temp;

            if ((temp = el.Attribute("name")) == null)
            {
                throw new FormatException("WorldListEntity: Cannot parse XML: Unnamed worlds are not allowed.");
            }
            if (!World.IsValidName(temp.Value))
            {
                throw new FormatException("WorldListEntity: Cannot parse XML: Invalid world name skipped \"" +
                                          temp.Value + "\".");
            }
            name = temp.Value;

            if ((temp = el.Attribute("hidden")) != null && !String.IsNullOrEmpty(temp.Value))
            {
                bool hidden;
                if (Boolean.TryParse(temp.Value, out hidden))
                {
                    Hidden = hidden;
                }
                else
                {
                    throw new FormatException(
                              "WorldListEntity: Cannot parse XML: Invalid value for \"hidden\" attribute.");
                }
            }
            else
            {
                Hidden = false;
            }

            if ((temp = el.Attribute("backup")) != null)
            {
                TimeSpan realBackupTimer;
                if (DateTimeUtil.TryParseTimeSpan(temp.Value, out realBackupTimer))
                {
                    Backup = BackupNameFromValue(realBackupTimer);
                }
                else
                {
                    Logger.Log(LogType.Error,
                               "WorldListEntity: Cannot parse backup settings for world \"{0}\". Assuming default.",
                               name);
                    Backup = BackupEnumNames[0];
                }
            }
            else
            {
                Backup = BackupEnumNames[0];
            }

            XElement tempEl;

            if ((tempEl = el.Element(WorldManager.AccessSecurityXmlTagName)) != null ||
                (tempEl = el.Element("accessSecurity")) != null)
            {
                accessSecurity = new SecurityController(tempEl, false);
            }
            if ((tempEl = el.Element(WorldManager.BuildSecurityXmlTagName)) != null ||
                (tempEl = el.Element("buildSecurity")) != null)
            {
                buildSecurity = new SecurityController(tempEl, false);
            }

            XElement blockEl = el.Element(BlockDB.XmlRootName);

            if (blockEl == null)
            {
                BlockDBEnabled = YesNoAuto.Auto;
            }
            else
            {
                if ((temp = blockEl.Attribute("enabled")) != null)
                {
                    YesNoAuto enabledStateTemp;
                    if (EnumUtil.TryParse(temp.Value, out enabledStateTemp, true))
                    {
                        BlockDBEnabled = enabledStateTemp;
                    }
                    else
                    {
                        Logger.Log(LogType.Warning,
                                   "WorldListEntity: Could not parse BlockDB \"enabled\" attribute of world \"{0}\", assuming \"Auto\".",
                                   name);
                        BlockDBEnabled = YesNoAuto.Auto;
                    }
                }

                if ((temp = blockEl.Attribute("preload")) != null)
                {
                    bool isPreloaded;
                    if (Boolean.TryParse(temp.Value, out isPreloaded))
                    {
                        blockDBIsPreloaded = isPreloaded;
                    }
                    else
                    {
                        Logger.Log(LogType.Warning,
                                   "WorldListEntity: Could not parse BlockDB \"preload\" attribute of world \"{0}\", assuming NOT preloaded.",
                                   name);
                    }
                }
                if ((temp = blockEl.Attribute("limit")) != null)
                {
                    int limit;
                    if (Int32.TryParse(temp.Value, out limit))
                    {
                        blockDBLimit = limit;
                    }
                    else
                    {
                        Logger.Log(LogType.Warning,
                                   "WorldListEntity: Could not parse BlockDB \"limit\" attribute of world \"{0}\", assuming NO limit.",
                                   name);
                    }
                }
                if ((temp = blockEl.Attribute("timeLimit")) != null)
                {
                    int timeLimitSeconds;
                    if (Int32.TryParse(temp.Value, out timeLimitSeconds))
                    {
                        blockDBTimeLimit = TimeSpan.FromSeconds(timeLimitSeconds);
                    }
                    else
                    {
                        Logger.Log(LogType.Warning,
                                   "WorldListEntity: Could not parse BlockDB \"timeLimit\" attribute of world \"{0}\", assuming NO time limit.",
                                   name);
                    }
                }
            }

            if ((tempEl = el.Element("LoadedBy")) != null)
            {
                LoadedBy = tempEl.Value;
            }
            if ((tempEl = el.Element("MapChangedBy")) != null)
            {
                MapChangedBy = tempEl.Value;
            }

            if ((tempEl = el.Element("LoadedOn")) != null)
            {
                if (!DateTimeUtil.TryParseDateTime(tempEl.Value, ref LoadedOn))
                {
                    LoadedOn = DateTime.MinValue;
                }
            }
            if ((tempEl = el.Element("MapChangedOn")) != null)
            {
                if (!DateTimeUtil.TryParseDateTime(tempEl.Value, ref MapChangedOn))
                {
                    MapChangedOn = DateTime.MinValue;
                }
            }
            environmentEl = el.Element(WorldManager.EnvironmentXmlTagName);

            rankMains = el.Elements(WorldManager.RankMainXmlTagName).ToArray();
        }
Esempio n. 23
0
        protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            var releases     = new List <ReleaseInfo>();
            var searchString = GetSearchTerm(query);

            var searchUrl       = APIUrl;
            var queryCollection = new NameValueCollection
            {
                { "action", "browse" },
                //{"group_results", "0"}, # results won't include all information
                { "order_by", "time" },
                { "order_way", "desc" }
            };

            if (!string.IsNullOrWhiteSpace(query.ImdbID))
            {
                if (imdbInTags)
                {
                    queryCollection.Add("taglist", query.ImdbID);
                }
                else
                {
                    queryCollection.Add("cataloguenumber", query.ImdbID);
                }
            }
            else if (!string.IsNullOrWhiteSpace(searchString))
            {
                queryCollection.Add("searchstr", searchString);
            }

            if (query.Artist != null)
            {
                queryCollection.Add("artistname", query.Artist);
            }

            if (query.Label != null)
            {
                queryCollection.Add("recordlabel", query.Label);
            }

            if (query.Year != null)
            {
                queryCollection.Add("year", query.Year.ToString());
            }

            if (query.Album != null)
            {
                queryCollection.Add("groupname", query.Album);
            }

            foreach (var cat in MapTorznabCapsToTrackers(query))
            {
                queryCollection.Add("filter_cat[" + cat + "]", "1");
            }

            // remove . as not used in titles
            searchUrl += "?" + queryCollection.GetQueryString().Replace(".", " ");

            var apiKey  = configData.ApiKey;
            var headers = apiKey != null ? new Dictionary <string, string> {
                ["Authorization"] = String.Format(AuthorizationFormat, apiKey.Value)
            } : null;

            var response = await RequestWithCookiesAndRetryAsync(searchUrl, headers : headers);

            // we get a redirect in html pages and an error message in json response (api)
            if (response.IsRedirect && !useApiKey)
            {
                // re-login only if API key is not in use.
                await ApplyConfiguration(null);

                response = await RequestWithCookiesAndRetryAsync(searchUrl);
            }
            else if (response.ContentString != null && response.ContentString.Contains("failure") && useApiKey)
            {
                // reason for failure should be explained.
                var jsonError   = JObject.Parse(response.ContentString);
                var errorReason = (string)jsonError["error"];
                throw new Exception(errorReason);
            }


            try
            {
                var json = JObject.Parse(response.ContentString);
                foreach (JObject r in json["response"]["results"])
                {
                    var groupTime   = DateTimeUtil.UnixTimestampToDateTime(long.Parse((string)r["groupTime"]));
                    var groupName   = WebUtility.HtmlDecode((string)r["groupName"]);
                    var artist      = WebUtility.HtmlDecode((string)r["artist"]);
                    var cover       = (string)r["cover"];
                    var tags        = r["tags"].ToList();
                    var groupYear   = (string)r["groupYear"];
                    var releaseType = (string)r["releaseType"];
                    var title       = new StringBuilder();
                    if (!string.IsNullOrEmpty(artist))
                    {
                        title.Append(artist + " - ");
                    }
                    title.Append(groupName);
                    if (!string.IsNullOrEmpty(groupYear) && groupYear != "0")
                    {
                        title.Append(" [" + groupYear + "]");
                    }
                    if (!string.IsNullOrEmpty(releaseType) && releaseType != "Unknown")
                    {
                        title.Append(" [" + releaseType + "]");
                    }
                    var description = tags?.Any() == true && !string.IsNullOrEmpty(tags[0].ToString())
                        ? "Tags: " + string.Join(", ", tags) + "\n"
                        : null;
                    Uri poster = null;
                    if (!string.IsNullOrEmpty(cover))
                    {
                        poster = (cover.StartsWith("http")) ? new Uri(cover) : new Uri(PosterUrl + cover);
                    }
                    var release = new ReleaseInfo
                    {
                        PublishDate = groupTime,
                        Title       = title.ToString(),
                        Description = description,
                        Poster      = poster
                    };


                    if (imdbInTags)
                    {
                        release.Imdb = tags
                                       .Select(tag => ParseUtil.GetImdbID((string)tag))
                                       .Where(tag => tag != null).FirstIfSingleOrDefault();
                    }

                    if (r["torrents"] is JArray)
                    {
                        foreach (JObject torrent in r["torrents"])
                        {
                            var release2 = (ReleaseInfo)release.Clone();
                            FillReleaseInfoFromJson(release2, torrent);
                            if (ReleaseInfoPostParse(release2, torrent, r))
                            {
                                releases.Add(release2);
                            }
                        }
                    }
                    else
                    {
                        FillReleaseInfoFromJson(release, r);
                        if (ReleaseInfoPostParse(release, r, r))
                        {
                            releases.Add(release);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                OnParseError(response.ContentString, ex);
            }

            return(releases);
        }
Esempio n. 24
0
 public override void ToJSON(bool includeState)
 {
     AddObjectProperty("SecUserId", gxTv_SdtSecUser_Secuserid, false);
     AddObjectProperty("SecUserName", gxTv_SdtSecUser_Secusername, false);
     AddObjectProperty("SecUserPassword", gxTv_SdtSecUser_Secuserpassword, false);
     AddObjectProperty("SecUserCrtUser", gxTv_SdtSecUser_Secusercrtuser, false);
     AddObjectProperty("SecUserCrtUser_N", gxTv_SdtSecUser_Secusercrtuser_N, false);
     AddObjectProperty("SecUserUpdUser", gxTv_SdtSecUser_Secuserupduser, false);
     AddObjectProperty("SecUserUpdUser_N", gxTv_SdtSecUser_Secuserupduser_N, false);
     datetime_STZ = gxTv_SdtSecUser_Secusercrtdate;
     sDateCnv     = "";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Year(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("0000", 1, 4 - StringUtil.Len(sNumToPad)) + sNumToPad;
     sDateCnv     = sDateCnv + "-";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Month(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
     sDateCnv     = sDateCnv + "-";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Day(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
     sDateCnv     = sDateCnv + "T";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Hour(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
     sDateCnv     = sDateCnv + ":";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Minute(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
     sDateCnv     = sDateCnv + ":";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Second(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
     AddObjectProperty("SecUserCrtDate", sDateCnv, false);
     AddObjectProperty("SecUserCrtDate_N", gxTv_SdtSecUser_Secusercrtdate_N, false);
     datetime_STZ = gxTv_SdtSecUser_Secuserupddate;
     sDateCnv     = "";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Year(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("0000", 1, 4 - StringUtil.Len(sNumToPad)) + sNumToPad;
     sDateCnv     = sDateCnv + "-";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Month(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
     sDateCnv     = sDateCnv + "-";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Day(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
     sDateCnv     = sDateCnv + "T";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Hour(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
     sDateCnv     = sDateCnv + ":";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Minute(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
     sDateCnv     = sDateCnv + ":";
     sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Second(datetime_STZ)), 10, 0));
     sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
     AddObjectProperty("SecUserUpdDate", sDateCnv, false);
     AddObjectProperty("SecUserUpdDate_N", gxTv_SdtSecUser_Secuserupddate_N, false);
     AddObjectProperty("SecUserWorkload", gxTv_SdtSecUser_Secuserworkload, false);
     AddObjectProperty("SecUserWorkload_N", gxTv_SdtSecUser_Secuserworkload_N, false);
     if (includeState)
     {
         AddObjectProperty("Mode", gxTv_SdtSecUser_Mode, false);
         AddObjectProperty("Initialized", gxTv_SdtSecUser_Initialized, false);
         AddObjectProperty("SecUserId_Z", gxTv_SdtSecUser_Secuserid_Z, false);
         AddObjectProperty("SecUserName_Z", gxTv_SdtSecUser_Secusername_Z, false);
         AddObjectProperty("SecUserPassword_Z", gxTv_SdtSecUser_Secuserpassword_Z, false);
         AddObjectProperty("SecUserCrtUser_Z", gxTv_SdtSecUser_Secusercrtuser_Z, false);
         AddObjectProperty("SecUserUpdUser_Z", gxTv_SdtSecUser_Secuserupduser_Z, false);
         datetime_STZ = gxTv_SdtSecUser_Secusercrtdate_Z;
         sDateCnv     = "";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Year(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("0000", 1, 4 - StringUtil.Len(sNumToPad)) + sNumToPad;
         sDateCnv     = sDateCnv + "-";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Month(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
         sDateCnv     = sDateCnv + "-";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Day(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
         sDateCnv     = sDateCnv + "T";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Hour(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
         sDateCnv     = sDateCnv + ":";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Minute(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
         sDateCnv     = sDateCnv + ":";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Second(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
         AddObjectProperty("SecUserCrtDate_Z", sDateCnv, false);
         datetime_STZ = gxTv_SdtSecUser_Secuserupddate_Z;
         sDateCnv     = "";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Year(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("0000", 1, 4 - StringUtil.Len(sNumToPad)) + sNumToPad;
         sDateCnv     = sDateCnv + "-";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Month(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
         sDateCnv     = sDateCnv + "-";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Day(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
         sDateCnv     = sDateCnv + "T";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Hour(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
         sDateCnv     = sDateCnv + ":";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Minute(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
         sDateCnv     = sDateCnv + ":";
         sNumToPad    = StringUtil.Trim(StringUtil.Str((decimal)(DateTimeUtil.Second(datetime_STZ)), 10, 0));
         sDateCnv     = sDateCnv + StringUtil.Substring("00", 1, 2 - StringUtil.Len(sNumToPad)) + sNumToPad;
         AddObjectProperty("SecUserUpdDate_Z", sDateCnv, false);
         AddObjectProperty("SecUserWorkload_Z", gxTv_SdtSecUser_Secuserworkload_Z, false);
         AddObjectProperty("SecUserCrtUser_N", gxTv_SdtSecUser_Secusercrtuser_N, false);
         AddObjectProperty("SecUserUpdUser_N", gxTv_SdtSecUser_Secuserupduser_N, false);
         AddObjectProperty("SecUserCrtDate_N", gxTv_SdtSecUser_Secusercrtdate_N, false);
         AddObjectProperty("SecUserUpdDate_N", gxTv_SdtSecUser_Secuserupddate_N, false);
         AddObjectProperty("SecUserWorkload_N", gxTv_SdtSecUser_Secuserworkload_N, false);
     }
     return;
 }
Esempio n. 25
0
        protected override async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            List <ReleaseInfo> releases = new List <ReleaseInfo>();

            var searchString    = query.GetQueryString();
            var searchUrl       = SearchUrl;
            var queryCollection = new NameValueCollection();

            queryCollection.Add("incldead", "1");
            queryCollection.Add("showspam", "1");

            if (!string.IsNullOrWhiteSpace(searchString))
            {
                queryCollection.Add("search", searchString);
            }

            var    cats = MapTorznabCapsToTrackers(query);
            string cat  = "0";

            if (cats.Count == 1)
            {
                cat = cats[0];
            }
            queryCollection.Add("cat", cat);

            searchUrl += "?" + queryCollection.GetQueryString();

            var results = await RequestStringWithCookiesAndRetry(searchUrl);

            // Occasionally the cookies become invalid, login again if that happens
            if (results.IsRedirect)
            {
                await ApplyConfiguration(null);

                results = await RequestStringWithCookiesAndRetry(searchUrl);
            }

            try
            {
                CQ  dom  = results.Content;
                var rows = dom["table[cellpadding=2] > tbody > tr:has(td.row3)"];
                foreach (var row in rows)
                {
                    var release = new ReleaseInfo();
                    release.MinimumRatio    = 1;
                    release.MinimumSeedTime = 48 * 60 * 60;

                    var qRow          = row.Cq();
                    var qCatLink      = qRow.Find("a[href^=browse.php?cat=]").First();
                    var qDetailsLink  = qRow.Find("a[href^=details.php?id=]").First();
                    var qSeeders      = qRow.Find("td:eq(9)");
                    var qLeechers     = qRow.Find("td:eq(10)");
                    var qDownloadLink = qRow.Find("a[href^=download.php]").First();
                    var qTimeAgo      = qRow.Find("td:eq(5)");
                    var qSize         = qRow.Find("td:eq(7)");

                    var catStr = qCatLink.Attr("href").Split('=')[1].Split('&')[0];
                    release.Category = MapTrackerCatToNewznab(catStr);

                    release.Link     = new Uri(SiteLink + qDownloadLink.Attr("href"));
                    release.Title    = qDetailsLink.Attr("title").Trim();
                    release.Comments = new Uri(SiteLink + qDetailsLink.Attr("href"));
                    release.Guid     = release.Link;

                    var sizeStr = qSize.Text();
                    release.Size = ReleaseInfo.GetBytes(sizeStr);

                    release.Seeders = ParseUtil.CoerceInt(qSeeders.Text());
                    release.Peers   = ParseUtil.CoerceInt(qLeechers.Text()) + release.Seeders;

                    var dateStr = qTimeAgo.Text();
                    release.PublishDate = DateTimeUtil.FromTimeAgo(dateStr);

                    var files = qRow.Find("td:nth-child(4)").Text();
                    release.Files = ParseUtil.CoerceInt(files);

                    var grabs = qRow.Find("td:nth-child(9)").Text();
                    release.Grabs = ParseUtil.CoerceInt(grabs);

                    var ka       = qRow.Next();
                    var DLFactor = ka.Find("table > tbody > tr:nth-child(3) > td:nth-child(2)").Text().Replace("X", "");
                    var ULFactor = ka.Find("table > tbody > tr:nth-child(3) > td:nth-child(1)").Text().Replace("X", "");
                    release.DownloadVolumeFactor = ParseUtil.CoerceDouble(DLFactor);
                    release.UploadVolumeFactor   = ParseUtil.CoerceDouble(ULFactor);

                    releases.Add(release);
                }
            }
            catch (Exception ex)
            {
                OnParseError(results.Content, ex);
            }

            return(releases);
        }
Esempio n. 26
0
        public APIChargeResult Charge(int agentId, int routeId, string mobile, string spname, string province, string city, string callBackUrl, string client_order_id)
        {
            if (string.IsNullOrEmpty(mobile))
            {
                throw new KMBitException("手机号码不能为空");
            }
            if (string.IsNullOrEmpty(spname))
            {
                throw new KMBitException("手机号归属运行商不能为空");
            }
            if (string.IsNullOrEmpty(province))
            {
                throw new KMBitException("手机号归属省份不能为空");
            }
            //if (string.IsNullOrEmpty(city))
            //{
            //    throw new KMBitException("手机号归属城市不能为空");
            //}
            ChargeResult result = null;
            ChargeBridge cb     = new ChargeBridge();
            ChargeOrder  order  = new ChargeOrder()
            {
                ClientOrderId    = client_order_id,
                Payed            = false,
                OperateUserId    = 0,
                AgencyId         = agentId,
                Id               = 0,
                Province         = province,
                City             = city != null? city:"",
                MobileNumber     = mobile,
                MobileSP         = spname,
                OutOrderId       = "",
                ResourceId       = 0,
                ResourceTaocanId = 0,
                RouteId          = routeId,
                CreatedTime      = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now),
                CallbackUrl      = callBackUrl
            };
            chargebitEntities db       = null;
            OrderManagement   orderMgt = new OrderManagement();

            try
            {
                db = new chargebitEntities();
                Users agent = (from u in db.Users where u.Id == agentId select u).FirstOrDefault <Users>();
                if (agent == null)
                {
                    throw new KMBitException(string.Format("编号为{0}的代理商不存在", agentId));
                }
                if (!agent.Enabled)
                {
                    throw new KMBitException(string.Format("代理商{0}已经被关闭禁用", agent.Name));
                }
                //verify mobile sp
                Agent_route route = (from r in db.Agent_route where r.Id == routeId && r.User_id == agentId select r).FirstOrDefault <Agent_route>();
                if (route == null)
                {
                    throw new KMBitException(string.Format("代理商 {1} 编号为{0}的路由不存在", routeId, agent.Name));
                }
                if (!route.Enabled)
                {
                    throw new KMBitException(string.Format("代理商 {1} 编号为{0}的路由已经被关闭", routeId, agent.Name));
                }
                Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == route.Resource_taocan_id select t).FirstOrDefault <Resource_taocan>();
                int             spId   = (from sp in db.Sp where sp.Name.Contains(spname.Trim()) select sp.Id).FirstOrDefault <int>();
                if (spId == 0)
                {
                    throw new KMBitException("手机运营商的值必须是-中国移动,中国联通或者中国电信");
                }
                int provinceId = (from area in db.Area where area.Name.Contains(province) select area.Id).FirstOrDefault <int>();
                if (provinceId == 0)
                {
                    throw new KMBitException("手机号码归属省份值不正确,例如 河南,海南,江苏,请以此种格式传入");
                }
                if (taocan.NumberProvinceId > 0 && provinceId > 0)
                {
                    if (provinceId != taocan.NumberProvinceId)
                    {
                        throw new KMBitException(string.Format("当前路由不能充{0}-{1}的手机号码", spname, province));
                    }
                }
                order = orderMgt.GenerateOrder(order);
                //result = cb.Charge(order);
                if (order.Id > 0)
                {
                    result         = new ChargeResult();
                    result.Status  = ChargeStatus.SUCCEED;
                    result.Message = "充值信息已提交到充值系统";
                }
            }
            catch (KMBitException kex)
            {
                throw kex;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                result         = new ChargeResult();
                result.Status  = ChargeStatus.FAILED;
                result.Message = "未知错误,请联系平台管理员";
            }

            APIChargeResult apiResult = new APIChargeResult();

            //apiResult.Message = result.Message;
            apiResult.OrderId = order.Id;
            switch (result.Status)
            {
            case ChargeStatus.SUCCEED:
                apiResult.Status  = ChargeStatus.SUCCEED.ToString();
                apiResult.Message = result.Message;
                break;

            case ChargeStatus.FAILED:
                apiResult.Status = ChargeStatus.FAILED.ToString();
                break;

            case ChargeStatus.ONPROGRESS:
                apiResult.Status = ChargeStatus.SUCCEED.ToString();
                break;

            case ChargeStatus.PENDIND:
                apiResult.Status = ChargeStatus.SUCCEED.ToString();
                break;
            }

            return(apiResult);
        }
Esempio n. 27
0
        public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
        {
            DateTime utcAbsoluteExpiration = DateTimeUtil.ConvertToUniversalTime(absoluteExpiration);

            this._cacheInternal.DoInsert(true, key, value, dependencies, utcAbsoluteExpiration, slidingExpiration, priority, onRemoveCallback, true);
        }
Esempio n. 28
0
        /// <summary>
        /// Verifies if an OCSP response is genuine
        /// If it doesn't verify against the issuer certificate and response's certificates, it may verify
        /// using a trusted anchor or cert.
        /// </summary>
        /// <param name="ocspResp">the OCSP response</param>
        /// <param name="issuerCert">the issuer certificate</param>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        /// <exception cref="System.IO.IOException"/>
        public virtual void IsValidResponse(BasicOcspResp ocspResp, X509Certificate issuerCert)
        {
            //OCSP response might be signed by the issuer certificate or
            //the Authorized OCSP responder certificate containing the id-kp-OCSPSigning extended key usage extension
            X509Certificate responderCert = null;

            //first check if the issuer certificate signed the response
            //since it is expected to be the most common case
            if (IsSignatureValid(ocspResp, issuerCert))
            {
                responderCert = issuerCert;
            }
            //if the issuer certificate didn't sign the ocsp response, look for authorized ocsp responses
            // from properties or from certificate chain received with response
            if (responderCert == null)
            {
                if (ocspResp.GetCerts() != null)
                {
                    //look for existence of Authorized OCSP responder inside the cert chain in ocsp response
                    IEnumerable <X509Certificate> certs = SignUtils.GetCertsFromOcspResponse(ocspResp);
                    foreach (X509Certificate cert in certs)
                    {
                        IList keyPurposes = null;
                        try {
                            keyPurposes = cert.GetExtendedKeyUsage();
                            if ((keyPurposes != null) && keyPurposes.Contains(id_kp_OCSPSigning) && IsSignatureValid(ocspResp, cert))
                            {
                                responderCert = cert;
                                break;
                            }
                        }
                        catch (CertificateParsingException) {
                        }
                    }
                    // Certificate signing the ocsp response is not found in ocsp response's certificate chain received
                    // and is not signed by the issuer certificate.
                    if (responderCert == null)
                    {
                        throw new VerificationException(issuerCert, "OCSP response could not be verified");
                    }
                }
                else
                {
                    //certificate chain is not present in response received
                    //try to verify using rootStore
                    if (rootStore != null)
                    {
                        try {
                            foreach (X509Certificate anchor in SignUtils.GetCertificates(rootStore))
                            {
                                if (IsSignatureValid(ocspResp, anchor))
                                {
                                    responderCert = anchor;
                                    break;
                                }
                            }
                        }
                        catch (Exception) {
                            responderCert = (X509Certificate)null;
                        }
                    }
                    // OCSP Response does not contain certificate chain, and response is not signed by any
                    // of the rootStore or the issuer certificate.
                    if (responderCert == null)
                    {
                        throw new VerificationException(issuerCert, "OCSP response could not be verified");
                    }
                }
            }
            //check "This certificate MUST be issued directly by the CA that issued the certificate in question".
            responderCert.Verify(issuerCert.GetPublicKey());
            // validating ocsp signers certificate
            // Check if responders certificate has id-pkix-ocsp-nocheck extension,
            // in which case we do not validate (perform revocation check on) ocsp certs for lifetime of certificate
            if (responderCert.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNocheck.Id) == null)
            {
                X509Crl crl;
                try {
                    crl = CertificateUtil.GetCRL(responderCert);
                }
                catch (Exception) {
                    crl = (X509Crl)null;
                }
                if (crl != null && crl is X509Crl)
                {
                    CRLVerifier crlVerifier = new CRLVerifier(null, null);
                    crlVerifier.SetRootStore(rootStore);
                    crlVerifier.SetOnlineCheckingAllowed(onlineCheckingAllowed);
                    crlVerifier.Verify((X509Crl)crl, responderCert, issuerCert, DateTimeUtil.GetCurrentUtcTime());
                    return;
                }
            }
            //check if lifetime of certificate is ok
            responderCert.CheckValidity();
        }
Esempio n. 29
0
        public async Task <IEnumerable <ReleaseInfo> > PerformQuery(TorznabQuery query)
        {
            var releases = new List <ReleaseInfo>();

            var queryString = query.GetQueryString();
            var url         = TorrentsUrl;

            WebClientStringResult results = null;


            var pairs = new Dictionary <string, string> {
                { "portlet", "true" }
            };

            if (!string.IsNullOrWhiteSpace(queryString))
            {
                pairs.Add("search", queryString);
                results = await PostDataWithCookiesAndRetry(SearchUrl, pairs, null, TorrentsUrl);
            }
            else
            {
                results = await PostDataWithCookiesAndRetry(TorrentsUrl, pairs, null, TorrentsUrl);
            }

            try
            {
                CQ  dom  = results.Content;
                var rows = dom["#torrent-table tr"];

                if (!string.IsNullOrWhiteSpace(queryString))
                {
                    rows = dom["table tr"];
                }

                foreach (var row in rows.Skip(1))
                {
                    var release  = new ReleaseInfo();
                    var qRow     = row.Cq();
                    var titleRow = qRow.Find("td:eq(2)").First();
                    titleRow.Children().Remove();
                    release.Title = titleRow.Text().Trim();
                    if (string.IsNullOrWhiteSpace(release.Title))
                    {
                        continue;
                    }
                    release.Description = release.Title;

                    var qLink = row.Cq().Find("td:eq(4) a:eq(0)");
                    release.Link = new Uri(SiteLink + qLink.Attr("href"));
                    release.Guid = release.Link;
                    var qLinkComm = row.Cq().Find("td:eq(4) a:eq(1)");
                    release.Comments = new Uri(SiteLink + qLinkComm.Attr("href"));

                    var dateString = qRow.Find(".datetime").Attr("data-timestamp");
                    release.PublishDate = DateTimeUtil.UnixTimestampToDateTime(ParseUtil.CoerceDouble(dateString));
                    var infoString = row.Cq().Find("td:eq(3)").Text();

                    release.Size = ParseUtil.CoerceLong(Regex.Match(infoString, "\\((\\d+)\\)").Value.Replace("(", "").Replace(")", ""));

                    var infosplit = infoString.Replace("/", string.Empty).Split(":".ToCharArray());
                    release.Seeders = ParseUtil.CoerceInt(infosplit[1]);
                    release.Peers   = release.Seeders + ParseUtil.CoerceInt(infosplit[2]);

                    // var tags = row.Cq().Find(".label-tag").Text(); These don't see to parse - bad tags?

                    releases.Add(release);
                }
            }
            catch (Exception ex)
            {
                OnParseError(results.Content, ex);
            }

            /* else
             * {
             *   var rssUrl = SiteLink + "rss/recent?passkey=" + configData.RSSKey.Value;
             *
             *   results = await RequestStringWithCookiesAndRetry(rssUrl);
             *   try
             *   {
             *       var doc = XDocument.Parse(results.Content);
             *       foreach (var result in doc.Descendants("item"))
             *       {
             *           var xTitle = result.Element("title").Value;
             *           var xLink = result.Element("link").Value;
             *           var xGUID = result.Element("guid").Value;
             *           var xDesc = result.Element("description").Value;
             *           var xDate = result.Element("pubDate").Value;
             *           var release = new ReleaseInfo();
             *           release.Guid  =release.Link =  new Uri(xLink);
             *           release.MinimumRatio = 1;
             *           release.Seeders = 1; // We are not supplied with peer info so just mark it as one.
             *           foreach (var element in xDesc.Split(";".ToCharArray()))
             *           {
             *               var split = element.IndexOf(':');
             *               if (split > -1)
             *               {
             *                   var key = element.Substring(0, split).Trim();
             *                   var value = element.Substring(split+1).Trim();
             *
             *                   switch (key)
             *                   {
             *                       case "Filename":
             *                           release.Title = release.Description = value;
             *                           break;
             *                   }
             *               }
             *           }
             *
             *           //"Thu, 24 Sep 2015 18:07:07 +0000"
             *           release.PublishDate = DateTime.ParseExact(xDate, "ddd, dd MMM yyyy HH:mm:ss +0000", CultureInfo.InvariantCulture);
             *
             *           if (!string.IsNullOrWhiteSpace(release.Title))
             *           {
             *               releases.Add(release);
             *           }
             *       }
             *   }
             *   catch (Exception ex)
             *   {
             *       OnParseError(results.Content, ex);
             *   }*/


            foreach (var release in releases)
            {
                if (release.Title.Contains("1080p") || release.Title.Contains("720p"))
                {
                    release.Category = TorznabCatType.TVHD.ID;
                }
                else
                {
                    release.Category = TorznabCatType.TVSD.ID;
                }
            }

            return(releases);
        }
Esempio n. 30
0
        private PhotoChanges Update(Photo photo)
        {
            PhotoChanges changes = photo.Changes;

            // Update photo.
            if (changes.DescriptionChanged || changes.DefaultVersionIdChanged || changes.TimeChanged || changes.UriChanged || changes.RatingChanged || changes.MD5SumChanged)
            {
                Database.Execute(
                    new HyenaSqliteCommand(
                        "UPDATE photos " +
                        "SET description = ?, " +
                        "    default_version_id = ?, " +
                        "    time = ?, " +
                        "    base_uri = ?, " +
                        "    filename = ?, " +
                        "    rating = ? " +
                        "WHERE id = ? ",
                        photo.Description,
                        photo.DefaultVersionId,
                        DateTimeUtil.FromDateTime(photo.Time),
                        photo.VersionUri(Photo.OriginalVersionId).GetBaseUri().ToString(),
                        photo.VersionUri(Photo.OriginalVersionId).GetFilename(),
                        String.Format("{0}", photo.Rating),
                        photo.Id
                        )
                    );
            }

            // Update tags.
            if (changes.TagsRemoved != null)
            {
                foreach (Tag tag in changes.TagsRemoved)
                {
                    Database.Execute(new HyenaSqliteCommand(
                                         "DELETE FROM photo_tags WHERE photo_id = ? AND tag_id = ?",
                                         photo.Id,
                                         tag.Id));
                }
            }

            if (changes.TagsAdded != null)
            {
                foreach (Tag tag in changes.TagsAdded)
                {
                    Database.Execute(new HyenaSqliteCommand(
                                         "INSERT OR IGNORE INTO photo_tags (photo_id, tag_id) " +
                                         "VALUES (?, ?)",
                                         photo.Id,
                                         tag.Id));
                }
            }

            // Update versions.
            if (changes.VersionsRemoved != null)
            {
                foreach (uint version_id in changes.VersionsRemoved)
                {
                    Database.Execute(new HyenaSqliteCommand(
                                         "DELETE FROM photo_versions WHERE photo_id = ? AND version_id = ?",
                                         photo.Id,
                                         version_id));
                }
            }

            if (changes.VersionsAdded != null)
            {
                foreach (uint version_id in changes.VersionsAdded)
                {
                    PhotoVersion version = photo.GetVersion(version_id);
                    InsertVersion(photo, version);
                }
            }
            if (changes.VersionsModified != null)
            {
                foreach (uint version_id in changes.VersionsModified)
                {
                    PhotoVersion version = photo.GetVersion(version_id);
                    Database.Execute(new HyenaSqliteCommand(
                                         "UPDATE photo_versions SET name = ?, " +
                                         "base_uri = ?, filename = ?, protected = ?, import_md5 = ? " +
                                         "WHERE photo_id = ? AND version_id = ?",
                                         version.Name,
                                         version.BaseUri.ToString(),
                                         version.Filename,
                                         version.IsProtected,
                                         (version.ImportMD5 != String.Empty ? version.ImportMD5 : null),
                                         photo.Id,
                                         version_id));
                }
            }
            photo.Changes = null;
            return(changes);
        }