/// <summary>
        /// Обновить мангу.
        /// </summary>
        /// <param name="mangas">Обновляемая манга.</param>
        /// <param name="orderBy">Сортировка.</param>
        public async Task Update(List <int> mangas, Func <IQueryable <IManga>, IOrderedQueryable <IManga> > orderBy)
        {
            OnLibraryChanged(new LibraryViewModelArgs(null, null, MangaOperation.None, LibraryOperation.UpdateStarted));
            Log.Info(Strings.Library_Status_Update);
            try
            {
                mangaIndex = 0;
                List <int> materialized;
                using (var context = Repository.GetEntityContext("Prepare selected manga for update"))
                {
                    var entities = context.Get <IManga>().Where(m => m.NeedUpdate);

                    // Хибер не умеет в Contains от null, даже если для шарпа он не вычисляется.
                    if (mangas != null)
                    {
                        entities = entities.Where(m => mangas.Contains(m.Id));
                    }

                    // Если явно не указаны ID, которые стоит скачать - пытаемся качать в порядке сортировки.
                    if (orderBy != null && mangas == null)
                    {
                        entities = orderBy(entities);
                    }

                    materialized = await entities.Select(e => e.Id).ToListAsync().ConfigureAwait(false);

                    // Если указаны Id, пытаемся качать в их внутреннем порядке.
                    if (mangas != null)
                    {
                        materialized = materialized.OrderBy(m => mangas.IndexOf(m)).ToList();
                    }

                    mangasCount = materialized.Count;
                }

                void OnMangaAddedWhenLibraryUpdating(object sender, LibraryViewModelArgs args)
                {
                    if (args.MangaOperation == MangaOperation.Added)
                    {
                        materialized.Add(args.Manga.Id);
                        mangasCount = materialized.Count;
                        Log.Info($"Манга {args.Manga.Name} добавлена при обновлении и будет загружена автоматически");
                    }
                }

                LibraryChanged += OnMangaAddedWhenLibraryUpdating;
                for (var i = 0; i < materialized.Count; i++)
                {
                    await DownloadManager.CheckPause().ConfigureAwait(false);

                    using (var context = Repository.GetEntityContext($"Download updates for manga with id {materialized[i]}"))
                    {
                        var current = await context.Get <IManga>().SingleAsync(m => m.Id == materialized[i]).ConfigureAwait(false);

                        Log.Info(Strings.Library_Status_MangaUpdate + current.Name);
                        OnLibraryChanged(new LibraryViewModelArgs(null, current, MangaOperation.UpdateStarted, LibraryOperation.UpdateMangaChanged));
                        current.PropertyChanged += CurrentOnDownloadChanged;
                        UpdateDownloadPercent(current);
                        await current.Download().ConfigureAwait(false);

                        current.PropertyChanged -= CurrentOnDownloadChanged;
                        if (current.NeedCompress ?? current.Setting.CompressManga)
                        {
                            current.Compress();
                        }
                        mangaIndex++;
                        if (current.IsDownloaded)
                        {
                            OnLibraryChanged(new LibraryViewModelArgs(null, current, MangaOperation.UpdateCompleted, LibraryOperation.UpdateMangaChanged));
                        }
                    }
                }

                LibraryChanged -= OnMangaAddedWhenLibraryUpdating;
            }
            catch (AggregateException ae)
            {
                foreach (var ex in ae.Flatten().InnerExceptions)
                {
                    Log.Exception(ex);
                }
            }
            catch (System.Exception ex)
            {
                Log.Exception(ex);
            }
            finally
            {
                OnLibraryChanged(new LibraryViewModelArgs(null, null, MangaOperation.None, LibraryOperation.UpdateCompleted));
                Log.Info(Strings.Library_Status_UpdateComplete);
                ConfigStorage.Instance.AppConfig.LastUpdate = DateTime.Now;
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Обновить мангу.
        /// </summary>
        /// <param name="mangas">Обновляемая манга.</param>
        /// <param name="orderBy">Сортировка.</param>
        public async Task Update(List <int> mangas, Func <IQueryable <IManga>, IOrderedQueryable <IManga> > orderBy)
        {
            OnLibraryChanged(new LibraryViewModelArgs(null, null, MangaOperation.None, LibraryOperation.UpdateStarted));
            Log.Info(Strings.Library_Status_Update);
            try
            {
                mangaIndex = 0;
                List <int> materialized;
                if (mangas != null)
                {
                    materialized = mangas;
                }
                else
                {
                    using (var context = Repository.GetEntityContext("Prepare selected manga for update"))
                    {
                        var entities = context.Get <IManga>().Where(m => m.NeedUpdate);

                        // Пытаемся качать в порядке сортировки.
                        if (orderBy != null)
                        {
                            entities = orderBy(entities);
                        }

                        materialized = await entities.Select(e => e.Id).ToListAsync().ConfigureAwait(false);
                    }
                }

                mangasCount = materialized.Count;

                void OnMangaAddedWhenLibraryUpdating(object sender, LibraryViewModelArgs args)
                {
                    if (args.MangaOperation == MangaOperation.Added)
                    {
                        materialized.Add(args.Manga.Id);
                        mangasCount = materialized.Count;
                        Log.Info($"Манга {args.Manga.Name} добавлена при обновлении и будет загружена автоматически");
                    }
                }

                LibraryChanged += OnMangaAddedWhenLibraryUpdating;
                for (var i = 0; i < materialized.Count; i++)
                {
                    var mangaId = materialized[i];
                    await DownloadManager.CheckPause().ConfigureAwait(false);

                    using (var context = Repository.GetEntityContext($"Download updates for manga with id {mangaId}"))
                    {
                        var current = await context.Get <IManga>().SingleOrDefaultAsync(m => m.Id == mangaId).ConfigureAwait(false);

                        if (current == null || !current.NeedUpdate)
                        {
                            Log.Add(current == null ?
                                    $"Manga with id {mangaId} not found" :
                                    $"Manga with id {mangaId} has disabled updates");
                            continue;
                        }

                        Log.Info(Strings.Library_Status_MangaUpdate + current.Name);
                        OnLibraryChanged(new LibraryViewModelArgs(null, current, MangaOperation.UpdateStarted, LibraryOperation.UpdateMangaChanged));
                        current.PropertyChanged += CurrentOnDownloadChanged;
                        UpdateDownloadPercent(current);
                        await current.Download().ConfigureAwait(false);

                        current.PropertyChanged -= CurrentOnDownloadChanged;
                        if (current.NeedCompress ?? current.Setting.CompressManga)
                        {
                            current.Compress();
                        }
                        mangaIndex++;
                        if (current.IsDownloaded)
                        {
                            OnLibraryChanged(new LibraryViewModelArgs(null, current, MangaOperation.UpdateCompleted, LibraryOperation.UpdateMangaChanged));
                        }
                    }
                }

                LibraryChanged -= OnMangaAddedWhenLibraryUpdating;
            }
            catch (AggregateException ae)
            {
                foreach (var ex in ae.Flatten().InnerExceptions)
                {
                    Log.Exception(ex);
                }
            }
            catch (System.Exception ex)
            {
                Log.Exception(ex);
            }
            finally
            {
                OnLibraryChanged(new LibraryViewModelArgs(null, null, MangaOperation.None, LibraryOperation.UpdateCompleted));
                Log.Info(Strings.Library_Status_UpdateComplete);
                ConfigStorage.Instance.AppConfig.LastUpdate = DateTime.Now;
            }
        }