private PageReference CreatePageFromJson(PageObject pageObject, PageReference parent, IContentRepository contentRepo)
        {
            BasePage newPage;
            switch (pageObject.Type)
            {
                case 0:
                    ArticlePage aPage = contentRepo.GetDefault<ArticlePage>(parent);
                    aPage.MainBody = pageObject.MainBodyText;
                    newPage = aPage;
                    break;
                case 1:
                    newPage = contentRepo.GetDefault<FolderPage>(parent);
                    break;
                case 2:
                    ListPage lPage = contentRepo.GetDefault<ListPage>(parent);
                    lPage.MainBody = pageObject.MainBodyText;
                    newPage = lPage;
                    break;
                case 3:
                    newPage = contentRepo.GetDefault<PersonPage>(parent);
                    break;
                case 4:
                    newPage = contentRepo.GetDefault<PortalPage>(parent);
                    break;
                default:
                    newPage = contentRepo.GetDefault<ArticlePage>(parent);
                    break;
            }

            newPage.PageName = pageObject.PageName;
            newPage.IntroText = pageObject.IntroText;
            contentRepo.Save(newPage, SaveAction.Publish);
            return newPage.PageLink;
        }
示例#2
0
        public Page AddPage(int width = 210, int height = 297)
        {
            var contents = new ContentsObject(GetNextObjectNumber());
            var page = new PageObject(GetNextObjectNumber(), new Size(width, height));

            page.AddContents(contents);
            _pages.AddPage(page);
            _pageObjects.Add(page);

            return new Page(page);
        }
示例#3
0
        public void ExampleUsageTest()
        {
            _pageObject = _testConfig.StartTestAt<Homepage>();

            _pageObject.Page<Homepage>().MiddleWrapper.Click();
            _pageObject.Page<Homepage>().FillInForm("abc");

            _pageObject.Page<Homepage>().Blog.Click();
            _pageObject.VerifyRedirectionTo<Blog>();

            foreach (var post in _pageObject.Page<Blog>().Posts)
            {
                Console.WriteLine(post.Text);
            }
        }
 /// <summary>
 /// Clones the context for another <see cref="ControlObject"/> which resides within the same <see cref="BrowserSession"/>, on the same
 /// <see cref="BrowserWindow"/> and on the given <paramref name="pageObject"/>.
 /// </summary>
 /// <param name="pageObject">The <see cref="PageObject"/> on which the <see cref="ControlObject"/> resides.</param>
 /// <param name="scope">The scope of the other <see cref="ControlObject"/>.</param>
 public ControlObjectContext CloneForControl([NotNull] PageObject pageObject, [NotNull] ElementScope scope)
 {
     return(pageObject.Context.CloneForControl(pageObject, scope));
 }
 /// <summary>
 /// Private constructor, may be obtained only via a <see cref="PageObjectContext"/> or <see cref="ControlObjectContext"/>.
 /// </summary>
 internal ControlSelectionContext([NotNull] PageObject pageObject, [NotNull] ElementScope scope)
     : base(pageObject, scope)
 {
 }
        private async Task <PageObject> LoadPageObjectAsync(MangaObject MangaObject, ChapterObject ChapterObject, PageObject PageObject, CancellationToken ct, IProgress <Int32> progress)
        {
            try
            {
                await TaskConcurrencySemaphore.WaitAsync(ct);

                ct.ThrowIfCancellationRequested();

                ISiteExtension SiteExtension = CORE.SiteExtensions.First(_SiteExtension => PageObject.Url.Contains(_SiteExtension.ExtensionDescriptionAttribute.URLFormat));
                using (WebDownloader WebDownloader = new WebDownloader(SiteExtension.Cookies))
                {
                    WebDownloader.Referer = SiteExtension.ExtensionDescriptionAttribute.RefererHeader;
                    DownloadProgressChangedEventHandler ProgressEventHandler = (s, e) =>
                    {
                        if (!Equals(progress, null))
                        {
                            progress.Report((Int32)Math.Round((Double)e.ProgressPercentage * 0.9));
                        }
                        ct.ThrowIfCancellationRequested();
                    };
                    WebDownloader.DownloadProgressChanged += ProgressEventHandler;

                    String PageWebContent = await WebDownloader.DownloadStringTaskAsync(PageObject.Url).Retry(DOWNLOAD_TIMEOUT);

                    PageObject = SiteExtension.ParsePageObject(PageWebContent);

                    WebDownloader.DownloadProgressChanged -= ProgressEventHandler;
                }
                if (!Equals(progress, null))
                {
                    progress.Report(100);
                }
                return(PageObject);
            }
            finally { TaskConcurrencySemaphore.Release(); }
        }
示例#7
0
 public static void WaitForScreenToLoad(this PageObject page, IWebElement element)
 {
     page.Wait.Until(ExpectedConditions.ElementToBeClickable(element));
 }
示例#8
0
		private static void SampleInitDB()
		{
			PageObject page = new PageObject();

			page.Title = "Tralala";
			List<DataLibrary.Menu> subMenu = new List<Menu>();

			#region Menu
			page.Menu = new List<Menu>();
			Menu parent = new Menu(2, "About Us", "About", subMenu, page, null);
			page.Menu.Add(parent);

			subMenu.Add(new Menu(8, "About", "Company News", page, parent));
			subMenu.Add(new Menu(9, "About", "Our Team Work", page, parent));
			subMenu.Add(new Menu(10, "About", "History", page, parent));
			subMenu.Add(new Menu(11, "About", "Testimonials", page, parent));
			subMenu.Add(new Menu(12, "About", "Privacy Policy", page, parent));
			subMenu.Add(new Menu(13, "About", "Contact", page, parent));

			parent = new Menu(1, "Index", "Home", page, null);
			page.Menu.Add(parent);



			subMenu = new List<Menu>();
			parent = new Menu(3, "Services", "Services", subMenu, page, null);
			page.Menu.Add(parent);

			subMenu.Add(new Menu(14, "Services", "Company News", page, parent));
			subMenu.Add(new Menu(15, "Services", "Our Team Work", page, parent));
			subMenu.Add(new Menu(16, "Services", "History", page, parent));
			subMenu.Add(new Menu(17, "Services", "Testimonials", page, parent));


			subMenu = new List<Menu>();
			parent = new Menu(4, "Clients", "Clients", subMenu, page, null);
			page.Menu.Add(parent);
			subMenu.Add(new Menu(18, "Clients", "Company News", page, parent));
			subMenu.Add(new Menu(19, "Clients", "Our Team Work", page, parent));


			subMenu = new List<Menu>();
			parent = new Menu(5, "Products", "Products", subMenu, page, null);
			page.Menu.Add(parent);
			subMenu.Add(new Menu(14, "Products", "History", page, parent));
			subMenu.Add(new Menu(15, "Products", "Testimonials", page, parent));
			subMenu.Add(new Menu(16, "Products", "Privacy Policy", page, parent));
			subMenu.Add(new Menu(17, "Products", "Contact", page, parent));


			page.Menu.Add(new Menu(6, "Our Resources", "Resources", page, null));
			page.Menu.Add(new Menu(7, "Partners", "Partners", page, null));
			#endregion

			#region News
			page.News = new List<News>();
			page.News.Add(new News("GDP Increase of 3% - What does it mean?", "Seemingly never-ending woes about oil, war, and inflation have had the world bracing for recessions and hard economic times in general. But the The Company has experienced an unexpectedly high annualized growth rate of 3.3% in Q2.", DateTime.Now, page));
			page.News.Add(new News("Who says we don't want Foreign Investment?", "They only push for foreign investment via government invitations. They are very quiet about the way they invite foreign investment to their country. They have to be – they are communist, and are supposed to be self-sufficient.” Gary Brown said.", DateTime.Now.AddDays(-4), page));
			page.News.Add(new News("The Company Names Three to its Board", "The Company today announced that it has appointed three business leaders to its board of directors. At the same time a board secretary has been also appointed. “We’re delighted that John, Ronald, and Mary have joined our board.", DateTime.Now.AddDays(-10), page));
			page.News.Add(new News("GDP Increase of 3% - What does it mean?", "They only push for foreign investment via government invitations. They are very quiet about the way they invite foreign investment to their country. They have to be – they are communist, and are supposed to be self-sufficient.", DateTime.Now.AddDays(-1), page));
			page.News.Add(new News("Who says we don't want Foreign Investment?", "Seemingly never-ending woes about oil, war, and inflation have had the world bracing for recessions and hard economic times in general. But the The Company has experienced an unexpectedly high annualized growth rate of 3.3% in Q2.", DateTime.Now.AddDays(-2), page));
			#endregion

			#region Dynamic Content
			page.Content = new List<DynamicContent>();
			page.Content.Add(new DynamicContent(DynamicTypes.Main, "Welcome", "Welcome Text",
				@"<b>Our Company is a globally </b>operating provider of 
                    business services. Our highly professional employees develop
                    integrated service solutions and ideas for lasting successful business.
                    The Company is always there to provide any help and valuable advice our customer may need. We treat our customers as possessing partners, so they decide how extensive our services should be.<br/><br/>The purpose of our Company is to provide our customers with the best services in the field, while ensuring good values and commitment that build long-term partner relationships. We are able to achieve this by providing a trained dedicated staff, complete business services and immediate ...", "", page));
			page.Content.Add(new DynamicContent(DynamicTypes.Main, "Learn More", "Learn More",
			   "Our strength in finance and accounting lies in staff special expertise in systems development and implementation, workflow, system support and accounting services and the close integration of these areas. The combination of technical and business expertise is the foundation for integrated process solutions that meet the most stringent requirements.", "", page));
			page.Content.Add(new DynamicContent(DynamicTypes.Rep, "Our Advantage", "simple principles of service", "No matter the size of your business, our Company understands that it should run at maximum efficience. Needless to say, that we have everything for that. Our team is able to develop any network solutions that will increase productivity and save you millions. We are a prosperous, successul Company and we give all our clients our personal guarantee.", "", page));
			page.Content.Add(new DynamicContent(DynamicTypes.Rep, "Featured Services", "Finance and Accounting s", "Our strength in finance and accounting lies in staff special expertise in systems development and implementation, workflow, system support and accounting services and the close integration of these areas. The combination of technical and business expertise is the foundation for integrated process solutions that meet the most stringent requirements.", "", page));
			// List<DynamicContent> type2 = page.Content.Where(p => p.Type == DynamicTypes.Rep).ToList();
			#endregion
			if (page.Id == 0)
			{
				page.Save();
			}
			else
			{
				page.Update();
			}
		}
示例#9
0
 private static void ExtractLinkPattern(PageObject pageObject, JToken pattern)
 {
     //pageObject.LinkPattern = pattern.Value<string>();
 }
示例#10
0
        private Func <Task <(Action on, Action off, object value)> > ParseLayoutView(Type type,
                                                                                     XNodeInfo xinfo, PageObject page, ParseInfo parseInfo)
        {
            Log.Information("PARSE ELEMENT {name} as ILayoutController", xinfo.Name);

            var createObject = CreateInstance(xinfo, type, out ParseInfo createInfo);

            var pinfo = parseInfo.Merge(createInfo);

            Func <Layout <View>, Task <(Action on, Action off)> > createElement = (layout) => DefaultTask2Action;

            foreach (var child in xinfo.Elements.Value)
            {
                var res       = ParseElement(child, page, pinfo);
                var locCreate = createElement;

                createElement = async(layout) =>
                {
                    var res1 = await locCreate.Invoke(layout);

                    var res2 = await res.Invoke( );

                    if (res2.value != null)
                    {
                        layout.Children.Add(res2.value as View);
                    }

                    return(JoinAction(res1.on, res2.on), JoinAction(res1.off, res2.off));
                };
            }

            var createProperty = ParseElementProperty(xinfo, page, type, pinfo);

            return(async( ) =>
            {
                var layout = createObject( ) as Layout <View>;

                var res1 = await createProperty(layout);

                var res2 = await createElement(layout);

                return (JoinAction(res1.on, res2.on), JoinAction(res1.off, res2.off), layout);
            });
        }
 public String CacheKey(MangaObject MangaObject, ChapterObject ChapterObject, PageObject PageObject)
 {
     return(String.Format("{0}/{1}/{2}", MangaObject.MangaArchiveName(CORE.MANGA_ARCHIVE_EXTENSION), ChapterObject.ChapterArchiveName(CORE.CHAPTER_ARCHIVE_EXTENSION), PageObject.PageNumber));
 }
示例#12
0
    private static void AddFileToStory(StoryObject story, string file)
    {
        int pathDepth = 2;

        string[] splitPath = file.Split('/');

        for (int i = 0; i < splitPath.Length; i++)
        {
            //Debug.Log (splitPath[i]);
            if (splitPath[i] == currentStoryName)
            {
                if (i + pathDepth + 2 >= splitPath.Length)
                {
                    Debug.LogWarningFormat("Can't add file to story {0}", file);
                    return;
                }
                string pageName = splitPath[i + pathDepth + 1];
                //Get the page from the story
                PageObject page = story.GetPage(pageName);
                //Debug.Log (pageName);
                //page = null;
                //If the page wasn't in the story yet, create a new object
                if (page == null)
                {
                    page = new PageObject()
                    {
                        name = pageName
                    };
                    story.pageObjects.Add(page);
                }

                //Get the audio from the page. The name is actually the foldername, not the file name of the audio
                string audioName = splitPath[i + pathDepth + 2];

                //If the audio doesn't exist, craete a new one
                AudioObject audioObj = page.GetAudio(audioName);
                if (audioObj == null)
                {
                    audioObj = new AudioObject()
                    {
                        name = audioName
                    };
                    page.audioObjects.Add(audioObj);
                }

                Object    fileObj = myLoadedAssetBundle.LoadAsset(file);
                AudioClip clip    = fileObj as AudioClip;
                if (clip != null)
                {
                    audioObj.clip = clip;
                    return;
                }

                TextAsset txt = fileObj as TextAsset;

                if (txt != null)
                {
                    //SceneRef[SceneRefCounter] = audioName;
                    //Debug.Log (SceneRef[SceneRefCounter]);
                    //SceneRefCounter ++;
                    //Debug.Log (txt.text);
                    audioObj.sentence = GetSentence(txt.text);
                    return;
                }

                Debug.LogErrorFormat("File of type {0} detected inside the AssetBundle. It only supports AudioClips and TextAssets!", fileObj.GetType());

                return;
            }
        }

        Debug.Log("Done");
    }
示例#13
0
        public static async Task <object> GetReturnValueAsync(this IInvocation invocation, PageObject pageObject, SelectorAttribute attribute)
        {
            var page = pageObject.Page;

            if (page == null)
            {
                return(null);
            }

            if (invocation.IsReturning <ElementHandle>())
            {
                return(await page.QuerySelectorAsync(attribute.Selector).ConfigureAwait(false));
            }

            if (invocation.IsReturning <ElementHandle[]>())
            {
                return(await page.QuerySelectorAllAsync(attribute.Selector).ConfigureAwait(false));
            }

            if (invocation.IsReturningElementObject())
            {
                var proxyType     = invocation.Method.ReturnType.GetGenericArguments()[0];
                var elementHandle = await page.QuerySelectorAsync(attribute.Selector).ConfigureAwait(false);

                return(ProxyFactory.ElementObject(proxyType, page, elementHandle));
            }

            if (invocation.IsReturningElementObjectArray())
            {
                var arrayType      = invocation.Method.ReturnType.GetGenericArguments()[0];
                var proxyType      = arrayType.GetElementType();
                var elementHandles = await page.QuerySelectorAllAsync(attribute.Selector).ConfigureAwait(false);

                return(ProxyFactory.ElementObjectArray(proxyType, page, elementHandles));
            }

            return(null);
        }
示例#14
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string action = context.Request["action"];

            if (string.IsNullOrEmpty(action))
            {
                return;
            }
            if (action.Equals("getdtu"))
            {
                GetDtu(context);
            }
            else if (action.Equals("getunit"))
            {
                GetUnit(context);
            }
            else if (action.Equals("save"))
            {
                SaveUnit(context);
            }
            else if (action.Equals("adddtu"))
            {
                AddDTU(context);
            }
            else if (action.Equals("deldtu"))
            {
                DelDTU(context);
            }
            else if (action.Equals("editdtu"))
            {
                EditDTU(context);
            }
            else if (action.Equals("gettxwarn"))
            {
                GetTXWarn(context);
            }
            else if (action.Equals("gettdwarn"))
            {
                GetTDWarn(context);
            }
            else if (action.Equals("getcardwarn"))
            {
                GetCardWarn(context);
            }
            else if (action.Equals("getworklog"))
            {
                //接收分页数据
                int    page = 1, rows = 15, total = 0;
                string tmp = context.Request["page"].ToString();
                if (!string.IsNullOrEmpty(tmp))
                {
                    page = int.Parse(tmp);
                }
                tmp = context.Request["rows"].ToString();
                if (!string.IsNullOrEmpty(tmp))
                {
                    rows = int.Parse(tmp);
                }
                //接收参数
                DateTime begintime = new DateTime();
                string   sj        = context.Request["begintime"] ?? "";
                if (sj.Length > 0)
                {
                    begintime = DateTime.Parse(sj);
                }
                DateTime endtime = new DateTime();
                string   ej      = context.Request["endtime"] ?? "";
                if (ej.Length > 0)
                {
                    endtime = DateTime.Parse(ej);
                }

                List <OprLog>       dtuList = dtubll.GetWorkLogList(begintime, endtime, page, rows, ref total);
                PageObject <OprLog> pageO   = new PageObject <OprLog>();
                pageO.total = total;
                pageO.rows  = dtuList;
                var str = jss.Serialize(pageO);
                context.Response.Write(str);
            }
        }
示例#15
0
        public async void StartWorkAsync()
        {
            IsWork = true;

            var screenShotCreator = new GwentWindowScreenShotCreator();
            var cv            = new OpenCvGwentStateChecker(screenShotCreator);
            var inputEmulator = new AutoitInputDeviceEmulator();   //脚本输入模拟

            var pageFactory = new PageObjectFactory();

            LogText = new StringBuilder();

            await Task.Run(() =>
            {
                LogText.Append($"{DateTime.Now.ToString("s")}:  Start Work");
                GameStatusChanged?.Invoke(LogText.ToString());
                while (IsWork)
                {
                    try
                    {
                        if (screenShotCreator.IsGameWindowFullVisible())
                        {
                            // 页面监测 是否长时间未变化
                            if (PageObject.IsPagesTooLongNotChanged())
                            {
                                if (GwentProcessStarter.CloseProcess())
                                {
                                    GwentProcessStarter.StartProcess();
                                }
                            }

                            if (cv.GetCurrentGlobalGameStates() !=
                                GlobalGameStates.GameModesTab)
                            {
                                pageFactory.CheckAndClearGlobalMessageBoxes();

                                pageFactory
                                .CheckAndClearOpponentSurrenderedMessageBox();

                                pageFactory
                                .CheckAndClearGameSessionExceptionMessageBoxes();

                                var gameSess = cv.GetCurrentGameSessionStates();
                                GameStatusChanged?.Invoke(gameSess.ToString());

                                if (gameSess != GameSessionStates.Unknown)
                                {
                                    if (gameSess == GameSessionStates.MatchResultsScreen ||
                                        gameSess == GameSessionStates.MatchRewardsScreen)
                                    {
                                        new MatchResultsRewardsScreenPage(cv, new DefaultWaitingService(), inputEmulator,
                                                                          new Game(new Deck(""), new User("")))
                                        .ClosePageStatistics();
                                    }
                                    else
                                    {
                                        new GameSessionPage(cv, new DefaultWaitingService(), inputEmulator,
                                                            new Game(new Deck(""), new User("")))
                                        .GiveUp()
                                        .ClosePageStatistics();
                                    }
                                }
                                pageFactory.StartGame()?.GotoGameModesPage();
                            }

                            var gameModes = new GameModesPage(cv, new DefaultWaitingService(), inputEmulator)
                                            .GotoSeasonalGameMode()
                                            .EndMulligan()
                                            .GiveUp()
                                            .ClosePageStatistics();
                        }
                        else
                        {
                            if (GwentProcessStarter.WindowExists() == false)
                            {
                                GwentProcessStarter.StartProcess();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        GameStatusChanged?.Invoke(e.Message);
                        if (!e.Message.Contains("This is not a page")) //Это не страница
                        {
                            logger.Error(e.Message + e.StackTrace);
                        }
                    }
                }
                LogText.Append($"{DateTime.Now.ToString("s")}:  Stop Work");
                GameStatusChanged?.Invoke(LogText.ToString());
            });
        }
示例#16
0
 public void SetUp()
 {
     _pageObject = new PageObject();
 }
        public async Task DownloadAsync(MangaObject MangaObject, ChapterObject ChapterObject, IProgress <Int32> ProgressReporter = null)
        {
            String CK = CacheKey(MangaObject, ChapterObject);

            if (ActiveDownloadsCache.Contains(CK))
            {
                return;
            }
            ActiveDownloadsCache.Set(CK, true, DateTimeOffset.MaxValue);

            try
            {
                await Task.Delay(TimeSpan.FromSeconds(1));

                // Load the ChapterObject via Async and LimitedTaskFactory
                IProgress <Int32> ChapterObjectProgressReporter = new Progress <Int32>(ProgressValue =>
                {
                    if (!Equals(ProgressReporter, null))
                    {
                        ProgressReporter.Report((Int32)Math.Round((Double)ProgressValue * 0.25));
                    }
                });
                ChapterObject = await ContentTaskFactory.StartNew(() => LoadChapterObjectAsync(
                                                                      MangaObject,
                                                                      ChapterObject,
                                                                      cts.Token,
                                                                      ChapterObjectProgressReporter)).Unwrap();

                if (!ChapterObject.Pages.Count.Equals(0))
                { // Check for pages
                  // Save the ChapterObject via Async to Save Path with Retry and Timeout of 30min
                    await StoreChapterObject(MangaObject, ChapterObject);

                    // Load the PageObjects from the ChapterObject
                    List <Task <PageObject> > PageObjectDownloadTasks = new List <Task <PageObject> >();

                    foreach (PageObject PageObject in ChapterObject.Pages)
                    {
                        PageObjectDownloadTasks.Add(ContentTaskFactory.StartNew(() => LoadPageObjectAsync(
                                                                                    MangaObject,
                                                                                    ChapterObject,
                                                                                    PageObject,
                                                                                    cts.Token,
                                                                                    null)).Unwrap());
                    }

                    foreach (Task <PageObject> PageObjectDownloadTask in PageObjectDownloadTasks)
                    {
                        PageObject PageObject = await PageObjectDownloadTask;
                        Int32      index      = ChapterObject.Pages.FindIndex(_PageObject => Equals(_PageObject.PageNumber, PageObject.PageNumber));
                        ChapterObject.Pages[index] = PageObject;
                    }
                    await StoreChapterObject(MangaObject, ChapterObject);

                    // Download Images
                    IEnumerable <Task> DownloadImageTasksQuery =
                        from PageObject in ChapterObject.Pages
                        select DownloadImageAsync(
                            PageObject.ImgUrl,
                            PageObject.Url,
                            CORE.SiteExtensions.First(_SiteExtension => PageObject.Url.Contains(_SiteExtension.ExtensionDescriptionAttribute.URLFormat)).Cookies,
                            SavePath(MangaObject, ChapterObject),
                            Path.GetFileName(new Uri(PageObject.ImgUrl).LocalPath));

                    List <Task> DownloadImageTasks = DownloadImageTasksQuery.ToList();
                    Int32       OriginalDownloadImageTasksCount = DownloadImageTasks.Count;

                    while (DownloadImageTasks.Count > 0)
                    {
                        Task completedTask = await Task.WhenAny(DownloadImageTasks);

                        DownloadImageTasks.Remove(completedTask);

                        Int32 DownloadImageTasksProgress = (Int32)Math.Round(((Double)(OriginalDownloadImageTasksCount - DownloadImageTasks.Count) / (Double)OriginalDownloadImageTasksCount) * 75);
                        if (!Equals(ProgressReporter, null))
                        {
                            ProgressReporter.Report(25 + DownloadImageTasksProgress);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (!Equals(CORE.Logger, null))
                {
                    CORE.Logger.Warn(String.Format("[ContentDownloadManager] An exception was thrown while processing {0}.", MangaObject.Name), ex);
                }
                throw ex;
            }
            finally
            {
                if (!Equals(ProgressReporter, null))
                {
                    ProgressReporter.Report(100);
                }
                ActiveDownloadsCache.Remove(CK);
            }
        }
示例#18
0
 private static void ExtractPagination(PageObject pageObject, JToken token)
 {
     pageObject.Pagination = token.Value <string>();
 }
 public void Download(MangaObject MangaObject, ChapterObject ChapterObject, PageObject PageObject, IProgress <Int32> ProgressReporter = null)
 {
     Task.Run(() => DownloadAsync(MangaObject, ChapterObject, PageObject, ProgressReporter));
 }
示例#20
0
        private async Task <BookmarkObject> LoadBookmarkObjectAsync(Boolean OpeningPreviousChapter = false, Boolean ResumeChapter = false)
        {
            BookmarkObject BookmarkObject = null;

            try
            {
                if (!Equals(LoadBookmarkObjectAsyncCTS, null))
                {
                    if (LoadBookmarkObjectAsyncCTS.Token.CanBeCanceled)
                    {
                        LoadBookmarkObjectAsyncCTS.Cancel();
                    }
                }
            }
            catch { }
            using (LoadBookmarkObjectAsyncCTS = new CancellationTokenSource())
            {
                try
                {
                    Stream BookmarkObjectStream = await App.CORE.ZipManager.ReadAsync(MangaArchiveFilePath, typeof(BookmarkObject).Name).Retry(TIMEOUT);

                    LoadBookmarkObjectAsyncCTS.Token.ThrowIfCancellationRequested();
                    using (BookmarkObjectStream)
                    { BookmarkObject = BookmarkObjectStream.Deserialize <BookmarkObject>(SerializeType: App.SerializeType); }

                    if (Equals(BookmarkObject, null))
                    {
                        BookmarkObject = new BookmarkObject();
                    }

                    if (!Equals(BookmarkObject.Volume, ChapterObject.Volume))
                    {
                        BookmarkObject.Volume = ChapterObject.Volume;
                    }
                    if (!Equals(BookmarkObject.Chapter, ChapterObject.Chapter))
                    {
                        BookmarkObject.Chapter = ChapterObject.Chapter;
                    }
                    if (!Equals(BookmarkObject.SubChapter, ChapterObject.SubChapter))
                    {
                        BookmarkObject.SubChapter = ChapterObject.SubChapter;
                    }

                    if (OpeningPreviousChapter)
                    {
                        PageObject LastPageObject = ChapterObject.Pages.Last();
                        if (BookmarkObject.Page < LastPageObject.PageNumber)
                        {
                            BookmarkObject.Page = LastPageObject.PageNumber;
                        }
                    }
                    else if (!ResumeChapter || BookmarkObject.Page <= 0)
                    {
                        BookmarkObject.Page = ChapterObject.Pages.First().PageNumber;
                    }

                    if (!Equals(ChapterObject, null))
                    {
                        BookmarkObject.LastPage = ChapterObject.Pages.Last().PageNumber;
                    }
                }
                catch (OperationCanceledException) { BookmarkObject = new BookmarkObject(); }
                catch (Exception ex) { throw ex; }
                finally { }
            }

            return(BookmarkObject);
        }
        public async Task DownloadAsync(MangaObject MangaObject, ChapterObject ChapterObject, PageObject PageObject, IProgress <Int32> ProgressReporter = null)
        {
            String CK = CacheKey(MangaObject, ChapterObject, PageObject);

            if (ActiveDownloadsCache.Contains(CK))
            {
                return;
            }
            ActiveDownloadsCache.Set(CK, true, DateTimeOffset.MaxValue);

            try
            {
                // Only load page from we if ImgUrl is empty.
                if (String.IsNullOrWhiteSpace(PageObject.ImgUrl))
                {
                    await Task.Delay(TimeSpan.FromSeconds(1));

                    // Load the PageObject via Async and LimitedTaskFactory
                    PageObject = await ContentTaskFactory.StartNew(() => LoadPageObjectAsync(
                                                                       MangaObject,
                                                                       ChapterObject,
                                                                       PageObject,
                                                                       cts.Token,
                                                                       ProgressReporter)).Unwrap();

                    ChapterObject = await StorePageObject(MangaObject, ChapterObject, PageObject);
                }

                ISiteExtension SiteExtension = CORE.SiteExtensions.First(_SiteExtension =>
                                                                         { return(PageObject.Url.Contains(_SiteExtension.ExtensionDescriptionAttribute.URLFormat)); });
                // Start the DownloadImage task, don't wait.
                DownloadImage(PageObject.ImgUrl, PageObject.Url, SiteExtension.Cookies, SavePath(MangaObject, ChapterObject), Path.GetFileName(new Uri(PageObject.ImgUrl).LocalPath));
            }
            catch (Exception ex)
            {
                if (!Equals(CORE.Logger, null))
                {
                    CORE.Logger.Warn(String.Format("[ContentDownloadManager] An exception was thrown while processing {0}.", MangaObject.Name), ex);
                }
                throw ex;
            }
            finally
            {
                if (!Equals(ProgressReporter, null))
                {
                    ProgressReporter.Report(100);
                }
                ActiveDownloadsCache.Remove(CK);
            }
        }
        private async Task <ChapterObject> StorePageObject(MangaObject MangaObject, ChapterObject ChapterObject, PageObject PageObject)
        {
            Int32 index = ChapterObject.Pages.FindIndex(_PageObject => Equals(_PageObject.PageNumber, PageObject.PageNumber));

            ChapterObject.Pages[index] = PageObject;
            // Save the ChapterObject via Async to Save Path with Retry and Timeout of 30min
            await CORE.ZipManager.WriteAsync(
                SavePath(MangaObject, ChapterObject),
                ChapterObject.GetType().Name,
                ChapterObject.Serialize(SerializeType: SerializeType)
                ).Retry(FILE_ACCESS_TIMEOUT, DEFAULT_DELAY, DELAY_INCREMENT);

            return(ChapterObject);
        }
示例#23
0
文件: Page.cs 项目: W0dan/PdfCraft
 internal Page(PageObject page)
 {
     _page = page;
 }