Exemple #1
0
        private void BookDownloaderOnDownloadCompleted(object sender, DownloadItemDataModel downloadItemDataModel)
        {
            _eventAggregator.Publish(new BookDownloaded(downloadItemDataModel));


            var catalogBookItemModel = new CatalogBookItemModel();

            catalogBookItemModel.Id          = downloadItemDataModel.CatalogItemId;
            catalogBookItemModel.Title       = downloadItemDataModel.Name;
            catalogBookItemModel.Author      = downloadItemDataModel.Author;
            catalogBookItemModel.Description = downloadItemDataModel.Description;
            if (!string.IsNullOrWhiteSpace(downloadItemDataModel.AcquisitionUrl))
            {
                catalogBookItemModel.AcquisitionLink = new BookAcquisitionLinkModel
                {
                    Url    = downloadItemDataModel.AcquisitionUrl,
                    Type   = downloadItemDataModel.AcquisitionType,
                    Prices = BookAcquisitionLinkModel.ParsePrices(downloadItemDataModel.AcquisitionPrices)
                };
            }
            if (downloadItemDataModel.IsTrial)
            {
                catalogBookItemModel.TrialLink = new BookDownloadLinkModel
                {
                    Url  = downloadItemDataModel.Path,
                    Type = downloadItemDataModel.Type
                };
            }

            _notificationsService.ShowToast(UIStrings.BookDownloader_Success, downloadItemDataModel.Name, _navigationService.UriFor <ReadPageViewModel>()
                                            .WithParam(vm => vm.BookId, downloadItemDataModel.BookID.ToString())
                                            .WithParam(vm => vm.CatalogId, downloadItemDataModel.DataSourceID)
                                            .WithParam(vm => vm.CatalogBookItemKey, TransientStorage.Put(catalogBookItemModel))
                                            .WithParam(vm => vm.TokenOffset, 0).BuildUri());
        }
Exemple #2
0
        public bool DownloadBook(CatalogBookItemModel catalogBookItemModel, int catalogId, bool fullBook = true)
        {
            var link = fullBook
                           ? GetDownloadLink(catalogBookItemModel.Links.ToArray())
                           : GetDownloadLink(catalogBookItemModel.TrialLink);

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

            if (!_bookDownloader.IsStarted)
            {
                _bookDownloader.Start();
            }

            var downloadModel = new BookDownloadModel
            {
                Path = link.Url,
                Type = GetBookType(link.Type),

                IsZip             = CheckIsZip(link.Type),
                Name              = catalogBookItemModel.Title,
                Author            = catalogBookItemModel.Author,
                Description       = catalogBookItemModel.Description,
                AcquisitionUrl    = catalogBookItemModel.AcquisitionLink != null ? catalogBookItemModel.AcquisitionLink.Url : null,
                AcquisitionType   = catalogBookItemModel.AcquisitionLink != null ? catalogBookItemModel.AcquisitionLink.Type : null,
                AcquisitionPrices = catalogBookItemModel.AcquisitionLink != null?catalogBookItemModel.AcquisitionLink.ToString() : null,
                                        DataSourceID  = catalogId,
                                        IsTrial       = !fullBook,
                                        CatalogItemId = catalogBookItemModel.Id
            };

            int oldQueueCount = _container.Count;

            _bookDownloadsRepository.Add(downloadModel);

            var downloadViewModel = new DownloadItemDataModel(downloadModel);

            _container.Enqueue(downloadViewModel);

            if (_container.Count == oldQueueCount)
            {
                int index = _container.GetDataModelIndex(downloadViewModel);
                if (index > -1)
                {
                    var viewModel = _container.Items[index];
                    if (viewModel.Status == DownloadStatus.Error)
                    {
                        viewModel.Status = DownloadStatus.Pending;
                        _bookDownloadsRepository.Remove(downloadModel.DownloadID);
                    }
                }
            }
            return(true);
        }
 public void NavigateToItem(CatalogBookItemModel model)
 {
     _navigationService
     .UriFor <BookInfoPageViewModel>()
     .WithParam(vm => vm.Title, model.Title.ToUpper())
     .WithParam(vm => vm.Description, model.Description)
     .WithParam(vm => vm.ImageUrl, model.ImageUrl)
     .WithParam(vm => vm.CatalogId, GetCatalogId(model.GetHashCode()))
     .WithParam(vm => vm.CatalogBookItemKey, TransientStorage.Put(model))
     .Navigate();
 }
Exemple #4
0
        public override Uri MapUri(Uri uri)
        {
            var navigationService = IoC.Get <INavigationService>();
            var catalogRepository = IoC.Get <ICatalogRepository>();

            string tempUri = uri.ToString();

            // File association launch
            if (tempUri.Contains("/FileTypeAssociation"))
            {
                // Get the file ID (after "fileToken=").
                int    fileIDIndex = tempUri.IndexOf("fileToken=", StringComparison.InvariantCulture) + 10;
                string fileID      = tempUri.Substring(fileIDIndex);

                // Get the file name.
                string incomingFileName = SharedStorageAccessManager.GetSharedFileName(fileID);

                // Get the file extension.
// ReSharper disable PossibleNullReferenceException
                string incomingFileType = Path.GetExtension(incomingFileName).ToLower();
// ReSharper restore PossibleNullReferenceException


                var catalog = catalogRepository.GetAll().Single(c => c.Type == CatalogType.StorageFolder);

                var bookItemModel = new CatalogBookItemModel
                {
                    Title       = Path.GetFileNameWithoutExtension(incomingFileName),
                    Description = string.Empty,
                    Author      = string.Empty,
                    Links       = new List <BookDownloadLinkModel>
                    {
                        new BookDownloadLinkModel {
                            Type = incomingFileType, Url = fileID
                        }
                    },
                    Id = fileID
                };

                return(navigationService
                       .UriFor <BookInfoPageViewModel>()
                       .WithParam(vm => vm.Title, bookItemModel.Title.ToUpper())
                       .WithParam(vm => vm.Description, bookItemModel.Description)
                       .WithParam(vm => vm.CatalogId, catalog.Id)
                       .WithParam(vm => vm.CatalogBookItemKey, TransientStorage.Put(bookItemModel))
                       .BuildUri());
            }
            // Otherwise perform normal launch.
            return(uri);
        }
        public static CatalogFolderModel ToFolder(this CatalitFb2BooksDto booksDto, string authorizationString)
        {
            var folderModel = new CatalogFolderModel {
                Items = new List <CatalogItemModel>()
            };

            if (booksDto.Books == null || !booksDto.Books.Any())
            {
                return(folderModel);
            }

            foreach (var fb2BookDto in booksDto.Books)
            {
                var bookCatalogItem = new CatalogBookItemModel();

                //TODO: change buy url and download links
                //bookCatalogItem.AcquisitionLink = new BookAcquisitionLinkModel
                //    {
                //        Type = ".fb2",
                //        Prices = new List<BookPriceModel> {new BookPriceModel {CurrencyCode = "RUB", Price = fb2BookDto.Price}},
                //        Url = "http://www.someurl.com/"
                //    };
                bookCatalogItem.Links = new List <BookDownloadLinkModel>
                {
                    new BookDownloadLinkModel
                    {
                        Type = ".fb2.zip",
                        Url  = CreateDownloadUrl(fb2BookDto, authorizationString)
                    }
                };

                bookCatalogItem.Id = fb2BookDto.Id.ToString(CultureInfo.InvariantCulture);
                //bookCatalogItem.Id = string.Concat(fb2BookDto.Id.ToString(CultureInfo.InvariantCulture), "|",
                //                                   fb2BookDto.Description.Hidden.DocumentInfo.Id);

                // title
                bookCatalogItem.Title = fb2BookDto.Description.Hidden.TitleInfo.BookTitle;

                // author
                bookCatalogItem.Author = CreateAuthorFullName(fb2BookDto.Description.Hidden.TitleInfo.Author);

                // cover image
                bookCatalogItem.ImageUrl = new Uri(fb2BookDto.ImageCover);

                folderModel.Items.Add(bookCatalogItem);
            }

            return(folderModel);
        }
        private async Task CheckForDownloadItem(string url)
        {
            var link = await GetDownloadLink(url);

            if (link != null)
            {
                if (!string.IsNullOrEmpty(CatalogBookItemKey) && TransientStorage.Contains(CatalogBookItemKey))
                {
                    var catalogBookItem = TransientStorage.Get <CatalogBookItemModel>(CatalogBookItemKey);
                    catalogBookItem.Links = new List <BookDownloadLinkModel> {
                        link
                    };

                    _navigationService
                    .UriFor <BookInfoPageViewModel>()
                    .WithParam(vm => vm.Title, catalogBookItem.Title.ToUpper())
                    .WithParam(vm => vm.Description, catalogBookItem.Description)
                    .WithParam(vm => vm.ImageUrl, catalogBookItem.ImageUrl)
                    .WithParam(vm => vm.CatalogId, CatalogId)
                    .WithParam(vm => vm.StartDownload, true)
                    .WithParam(vm => vm.CatalogBookItemKey, TransientStorage.Put(catalogBookItem))
                    .Navigate();
                    _navigated = true;
                }
                else
                {
                    var catalogBookItemModel = new CatalogBookItemModel
                    {
                        Links = new List <BookDownloadLinkModel> {
                            link
                        },
                        Title = Title,
                        Id    = Guid.NewGuid().ToString()
                    };
                    _downloadController.DownloadBook(catalogBookItemModel, CatalogId);
                    _catalogItemId = catalogBookItemModel.Id;
                }
            }
        }
        protected override void OnInitialize()
        {
            base.OnInitialize();

            Book = _bookRepository.Get(BookId);
            if (Book == null)
            {
                _navigationService.GoBack();
                return;
            }

            if (ToLastReadPage)
            {
                TokenOffset = Book.CurrentTokenID;
            }

            if (TransientStorage.Contains(CatalogBookItemKey))
            {
                CatalogBookItemModel = TransientStorage.Get <CatalogBookItemModel>(CatalogBookItemKey);
            }

            UpdateIsFavouriteBook();
        }
        public async Task <string> BuyBook(CatalogBookItemModel book, string authorizationString)
        {
            if (string.IsNullOrEmpty(authorizationString))
            {
                throw new CatalogAuthorizationException(CatalogType.Litres, AUTHORIZATION_URL);
            }

            try
            {
                var art  = string.Empty;
                var uuid = string.Empty;

                if (book.Id.Contains("|"))
                {
                    var idParts = book.Id.Split('|');
                    art  = idParts[0];
                    uuid = idParts[1];
                }
                else
                {
                    art = book.Id;
                }

                var response = await _webClient.DoPostAsync(BUY_BOOK_URL, CreateAcquisitionParams(art, uuid, EncryptService.Decrypt(authorizationString)));

                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new ReadCatalogException("Unable to read catalog");
                }

                var responseStream = await response.Content.ReadAsStreamAsync();

                var xDoc = XDocument.Load(responseStream);
                if (xDoc.Root.Name == "catalit-purchase-ok")
                {
                    var format = string.Format("sid={0}&art={1}", EncryptService.Decrypt(authorizationString), art);
                    if (!string.IsNullOrEmpty(uuid))
                    {
                        format = string.Concat(format, string.Format("uuid={0}", uuid));
                    }

                    return(string.Concat(DOWNLOAD_BOOK_URL, format));
                }

                if (xDoc.Root.Name == "catalit-purchase-failed")
                {
                    if (xDoc.Root.Attribute("error").Value == "1")
                    {
                        throw new CatalogNotEnoughMoneyException(CatalogType.Litres, string.Concat(NOT_ENOUGH_MONEY_URL, string.Format("?sid={0}", EncryptService.Decrypt(authorizationString))));
                    }
                    if (xDoc.Root.Attribute("error").Value == "3")
                    {
                        //throw new CatalogBookAlreadyBoughtException(CatalogType.Litres, book.Id);
                        var format = string.Format("sid={0}&art={1}", EncryptService.Decrypt(authorizationString), art);
                        if (!string.IsNullOrEmpty(uuid))
                        {
                            format = string.Concat(format, string.Format("uuid={0}", uuid));
                        }

                        return(string.Concat(DOWNLOAD_BOOK_URL, format));
                    }
                }

                if (xDoc.Root.Name == "catalit-authorization-failed")
                {
                    throw new CatalogAuthorizationException(CatalogType.Litres, AUTHORIZATION_URL);
                }
            }
            catch (WebException)
            {
                throw new ReadCatalogException("Unable to read catalog");
            }

            throw new ReadCatalogException("Unable to read catalog");
        }
        public static CatalogFolderModel ToFolder(this CatalogContentDto catalogContentDto, string authorityUrl, CatalogType type, int catalogId)
        {
            var folderModel = new CatalogFolderModel();
            var folderItems = new List <CatalogItemModel>();

            if (catalogContentDto.Links != null)
            {
                // pagination, next page
                var nextPageLink = catalogContentDto.Links.SingleOrDefault(l => !string.IsNullOrEmpty(l.Rel) && l.Rel.Equals("next") &&
                                                                           !string.IsNullOrEmpty(l.Type) &&
                                                                           (l.Type.Contains(CATALOG_LINK_TYPE_PREFIX) || (l.Type.Contains(CATALOG_LINK_TYPE))));
                if (nextPageLink != null)
                {
                    folderModel.NextPageUrl = GetValidUrl(nextPageLink.Href, authorityUrl);
                }
            }

            if (catalogContentDto.Entries != null)
            {
                foreach (var entryDto in catalogContentDto.Entries)
                {
                    CatalogItemModel model = null;

                    // book or just folder
                    var links = entryDto.Links.Where(e =>
                    {
                        if (string.IsNullOrEmpty(e.Rel) || (!e.Rel.StartsWith(REL_ACQUISITION_PREFIX)))
                        {
                            if (string.IsNullOrEmpty(e.Type) ||
                                !(e.Type.StartsWith(APPLICATION_PREFIX) && FormatConstants.Any(fc => e.Type.Contains(fc)) && !ApparentlyIgnoredFormatConstants.Any(fc => e.Type.Contains(fc))))
                            {
                                return(false);
                            }
                            return(true);
                        }

                        return(!string.IsNullOrEmpty(e.Type));    // && FormatConstants.Any(formatConstant => e.Type.Contains(formatConstant));
                    });

                    if (links.Count() != 0)
                    {
                        // links with price
                        var priceLink = links.SingleOrDefault(l => REL_ACQUISITION_BUY_PREFIX.Equals(l.Rel) && !string.IsNullOrEmpty(l.Href) &&
                                                              l.Prices != null && l.Prices.Any(p => !p.Price.Equals("0.00")));

                        // download links for diff. formats
                        var downloadLinks = (from linkDto in links
                                             where !string.IsNullOrEmpty(linkDto.Type) && !string.IsNullOrEmpty(linkDto.Href) && !REL_ACQUISITION_BUY_PREFIX.Equals(linkDto.Rel)
                                             select new BookDownloadLinkModel
                        {
                            Type = linkDto.Type, Url = GetValidUrl(linkDto.Href, authorityUrl, true)
                        }).Where(dl => FormatConstants.Any(fc => dl.Type.Contains(fc))).ToList();

                        // if there are now supported formats in downloadLinks, but there were some acquisition links with another formats => skip this book.
                        if (!downloadLinks.Any() && priceLink == null)
                        {
                            var htmlBuyLink = links.SingleOrDefault(l => REL_ACQUISITION_BUY_PREFIX.Equals(l.Rel));
                            if (htmlBuyLink == null)
                            {
                                continue;
                            }
                            model = new CatalogItemModel {
                                HtmlUrl = GetValidUrl(htmlBuyLink.Href, authorityUrl)
                            };
                        }
                        else
                        {
                            // this is book
                            BookAcquisitionLinkModel acquisitionLink = null;
                            if (priceLink != null && priceLink.Prices.Any(p => !p.Price.Equals("0.00")))
                            {
                                acquisitionLink = new BookAcquisitionLinkModel
                                {
                                    Type   = !string.IsNullOrEmpty(priceLink.DcFormat) ? priceLink.DcFormat : priceLink.Type,
                                    Prices = priceLink.Prices != null?priceLink.Prices.Select(p => new BookPriceModel {
                                        CurrencyCode = p.CurrencyCode, Price = p.Price
                                    })
                                             .ToList() : null,
                                                 Url = GetValidUrl(priceLink.Href, authorityUrl)
                                };
                            }

                            var id = string.IsNullOrEmpty(entryDto.Id) ? string.Concat(catalogId, "-", entryDto.Title) : entryDto.Id;

                            model = new CatalogBookItemModel
                            {
                                AcquisitionLink = acquisitionLink,
                                Links           = downloadLinks,
                                Id        = id,
                                TrialLink = type == CatalogType.Litres ? CreateTrialLink(entryDto.Id) : null
                            };
                        }
                    }
                    // check for Litres bookshelf
                    else if (entryDto.Links.Any(l => LITRES_REL_BOOKSHELF_PREFIX.Equals(l.Rel)))
                    {
                        model = new LitresBookshelfCatalogItemModel();
                    }
                    // check for Litres topup
                    else if (entryDto.Links.Any(l => LITRES_REL_TOPUP_PREFIX.Equals(l.Rel)))
                    {
                        model = new LitresTopupCatalogItemModel
                        {
                            HtmlUrl = LITRES_PUT_MONEY_LINK_FORMAT,
                            Title   = LITRES_REL_TOPUP_TITLE
                        };
                    }
                    else
                    {
                        // this is default folder
                        if (model == null)
                        {
                            model = new CatalogItemModel();
                        }
                    }

                    // title
                    if (string.IsNullOrEmpty(model.Title))
                    {
                        if (entryDto.Title == null)
                        {
                            continue;
                        }
                        if (!string.IsNullOrEmpty(entryDto.Title.Text))
                        {
                            model.Title = entryDto.Title.Text;
                        }
                        else if (!string.IsNullOrEmpty(entryDto.Title.DivValue))
                        {
                            model.Title = entryDto.Title.DivValue;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    // description
                    model.Description = entryDto.Content != null && !string.IsNullOrEmpty(entryDto.Content.Value)
                                            ? entryDto.Content.Value
                                            : string.Empty;

                    // author
                    model.Author = entryDto.Author != null && !string.IsNullOrEmpty(entryDto.Author.Name)
                                        ? entryDto.Author.Name
                                        : string.Empty;

                    // opds catalog url
                    if (!(model is LitresTopupCatalogItemModel) && string.IsNullOrEmpty(model.HtmlUrl))
                    {
                        var catalogLink = entryDto.Links.FirstOrDefault(l => !string.IsNullOrEmpty(l.Type) && (l.Type.Contains(CATALOG_LINK_TYPE_PREFIX) || l.Type.Contains(CATALOG_LINK_TYPE) || l.Type.Contains(LITRES_CATALOG_LINK_TYPE_)));
                        if (catalogLink != null)
                        {
                            model.OpdsUrl = GetValidUrl(catalogLink.Href, authorityUrl);
                        }
                    }

                    // html url, to open in browser
                    var htmlLink = entryDto.Links.FirstOrDefault(l => HTML_TEXT_LINK_TYPE.Equals(l.Type) && !string.IsNullOrEmpty(l.Href));
                    if (htmlLink != null)
                    {
                        if (string.IsNullOrEmpty(model.HtmlUrl))
                        {
                            model.HtmlUrl = GetValidUrl(htmlLink.Href, authorityUrl);
                        }
                    }

                    //image
                    var imageLinks = entryDto.Links.Where(l => !string.IsNullOrEmpty(l.Type) && l.Type.Equals(IMAGE_LINK_TYPE));
                    if (imageLinks.Any())
                    {
                        if (imageLinks.Count() > 1)
                        {
                            var imageLink = imageLinks.SingleOrDefault(l => l.Rel.Equals(REL_IMAGE_PREFIX));
                            if (imageLink != null)
                            {
                                model.ImageUrl = new Uri(GetValidUrl(imageLink.Href, authorityUrl, true));
                            }
                        }
                        else
                        {
                            model.ImageUrl = new Uri(GetValidUrl(imageLinks.First().Href, authorityUrl, true));
                        }
                    }

                    // decoding of description & title
                    model.Description = HttpUtility.HtmlDecode(model.Description);
                    model.Title       = HttpUtility.HtmlDecode(model.Title);
                    model.Author      = HttpUtility.HtmlDecode(model.Author);

                    if (model.Description.Contains("<") && model.Description.Contains(">"))
                    {
                        model.Description = HtmlToText.Convert(model.Description);
                    }
                    model.Description = model.Description.Trim();
                    if (model.Author.Contains("<") && model.Author.Contains(">"))
                    {
                        model.Author = HtmlToText.Convert(model.Author);
                    }

                    folderItems.Add(model);
                }
            }

            folderModel.Items = folderItems;
            return(folderModel);
        }