public Book AddBook(Book newBook, bool doRefresh = true) { _bookRepository.Upsert(newBook); var editions = newBook.Editions.Value; editions.ForEach(x => x.BookId = newBook.Id); _editionService.InsertMany(editions.Where(x => x.Id == 0).ToList()); _editionService.SetMonitored(editions.FirstOrDefault(x => x.Monitored) ?? editions.First()); _eventAggregator.PublishEvent(new BookAddedEvent(GetBook(newBook.Id), doRefresh)); return(newBook); }
public Book AddBook(Book newBook, bool doRefresh = true) { if (newBook.AuthorMetadataId == 0) { throw new InvalidOperationException("Cannot insert book with AuthorMetadataId = 0"); } _bookRepository.Upsert(newBook); var editions = newBook.Editions.Value; editions.ForEach(x => x.BookId = newBook.Id); _editionService.InsertMany(editions.Where(x => x.Id == 0).ToList()); _editionService.SetMonitored(editions.FirstOrDefault(x => x.Monitored) ?? editions.First()); _eventAggregator.PublishEvent(new BookAddedEvent(GetBook(newBook.Id), doRefresh)); return(newBook); }
public List <ImportResult> Import(List <ImportDecision <LocalBook> > decisions, bool replaceExisting, DownloadClientItem downloadClientItem = null, ImportMode importMode = ImportMode.Auto) { var importResults = new List <ImportResult>(); var allImportedTrackFiles = new List <BookFile>(); var allOldTrackFiles = new List <BookFile>(); var addedAuthors = new List <Author>(); var bookDecisions = decisions.Where(e => e.Item.Book != null && e.Approved) .GroupBy(e => e.Item.Book.ForeignBookId).ToList(); var iDecision = 1; foreach (var albumDecision in bookDecisions) { _logger.ProgressInfo($"Importing book {iDecision++}/{bookDecisions.Count} {albumDecision.First().Item.Book}"); var decisionList = albumDecision.ToList(); var author = EnsureAuthorAdded(decisionList, addedAuthors); if (author == null) { // failed to add the author, carry on with next book continue; } var book = EnsureBookAdded(decisionList); if (book == null) { // failed to add the book, carry on with next one continue; } if (replaceExisting) { RemoveExistingTrackFiles(author, book); } // set the correct release to be monitored before importing the new files var newRelease = albumDecision.First().Item.Edition; _logger.Debug("Updating release to {0}", newRelease); book.Editions = _editionService.SetMonitored(newRelease); // Publish book edited event. // Deliberatly don't put in the old book since we don't want to trigger an ArtistScan. _eventAggregator.PublishEvent(new BookEditedEvent(book, book)); } var qualifiedImports = decisions.Where(c => c.Approved) .GroupBy(c => c.Item.Author.Id, (i, s) => s .OrderByDescending(c => c.Item.Quality, new QualityModelComparer(s.First().Item.Author.QualityProfile)) .ThenByDescending(c => c.Item.Size)) .SelectMany(c => c) .ToList(); _logger.ProgressInfo($"Importing {qualifiedImports.Count} files"); _logger.Debug($"Importing {qualifiedImports.Count} files. replaceExisting: {replaceExisting}"); var filesToAdd = new List <BookFile>(qualifiedImports.Count); var trackImportedEvents = new List <TrackImportedEvent>(qualifiedImports.Count); foreach (var importDecision in qualifiedImports.OrderByDescending(e => e.Item.Size)) { var localTrack = importDecision.Item; var oldFiles = new List <BookFile>(); try { //check if already imported if (importResults.Select(r => r.ImportDecision.Item.Book.Id).Contains(localTrack.Book.Id)) { if (!(localTrack.FileTrackInfo.TrackNumbers != null && localTrack.FileTrackInfo.TrackNumbers.Any())) { importResults.Add(new ImportResult(importDecision, "Book has already been imported")); continue; } else { var matchingImportResults = importResults.Where(r => r.ImportDecision.Item.Book.Id == localTrack.Book.Id); if (matchingImportResults.Select(r => r.ImportDecision.Item.FileTrackInfo.TrackNumbers).Contains(localTrack.FileTrackInfo.TrackNumbers)) { importResults.Add(new ImportResult(importDecision, "Audiobook track has already been imported")); continue; } } } localTrack.Book.Author = localTrack.Author; var bookFile = new BookFile { Path = localTrack.Path.CleanFilePath(), Size = localTrack.Size, Modified = localTrack.Modified, DateAdded = DateTime.UtcNow, ReleaseGroup = localTrack.ReleaseGroup, Quality = localTrack.Quality, MediaInfo = localTrack.FileTrackInfo.MediaInfo, EditionId = localTrack.Edition.Id, Author = localTrack.Author, Edition = localTrack.Edition }; bool copyOnly; switch (importMode) { default: case ImportMode.Auto: copyOnly = downloadClientItem != null && !downloadClientItem.CanMoveFiles; break; case ImportMode.Move: copyOnly = false; break; case ImportMode.Copy: copyOnly = true; break; } if (!localTrack.ExistingFile) { bookFile.SceneName = GetSceneReleaseName(downloadClientItem); var moveResult = _bookFileUpgrader.UpgradeBookFile(bookFile, localTrack, copyOnly); oldFiles = moveResult.OldFiles; } else { // Delete existing files from the DB mapped to this path var previousFile = _mediaFileService.GetFileWithPath(bookFile.Path); if (previousFile != null) { _mediaFileService.Delete(previousFile, DeleteMediaFileReason.ManualOverride); } var rootFolder = _rootFolderService.GetBestRootFolder(localTrack.Path); if (rootFolder.IsCalibreLibrary) { bookFile.CalibreId = bookFile.Path.ParseCalibreId(); } _audioTagService.WriteTags(bookFile, false); } filesToAdd.Add(bookFile); importResults.Add(new ImportResult(importDecision)); if (!localTrack.ExistingFile) { _extraService.ImportTrack(localTrack, bookFile, copyOnly); } allImportedTrackFiles.Add(bookFile); allOldTrackFiles.AddRange(oldFiles); // create all the import events here, but we can't publish until the trackfiles have been // inserted and ids created trackImportedEvents.Add(new TrackImportedEvent(localTrack, bookFile, oldFiles, !localTrack.ExistingFile, downloadClientItem)); } catch (RootFolderNotFoundException e) { _logger.Warn(e, "Couldn't import book " + localTrack); _eventAggregator.PublishEvent(new TrackImportFailedEvent(e, localTrack, !localTrack.ExistingFile, downloadClientItem)); importResults.Add(new ImportResult(importDecision, "Failed to import book, Root folder missing.")); } catch (DestinationAlreadyExistsException e) { _logger.Warn(e, "Couldn't import book " + localTrack); importResults.Add(new ImportResult(importDecision, "Failed to import book, Destination already exists.")); } catch (UnauthorizedAccessException e) { _logger.Warn(e, "Couldn't import book " + localTrack); _eventAggregator.PublishEvent(new TrackImportFailedEvent(e, localTrack, !localTrack.ExistingFile, downloadClientItem)); importResults.Add(new ImportResult(importDecision, "Failed to import book, Permissions error")); } catch (Exception) { throw; } } var watch = new System.Diagnostics.Stopwatch(); watch.Start(); _mediaFileService.AddMany(filesToAdd); _logger.Debug($"Inserted new trackfiles in {watch.ElapsedMilliseconds}ms"); // now that trackfiles have been inserted and ids generated, publish the import events foreach (var trackImportedEvent in trackImportedEvents) { _eventAggregator.PublishEvent(trackImportedEvent); } var albumImports = importResults.Where(e => e.ImportDecision.Item.Book != null) .GroupBy(e => e.ImportDecision.Item.Book.Id).ToList(); foreach (var albumImport in albumImports) { var book = albumImport.First().ImportDecision.Item.Book; var author = albumImport.First().ImportDecision.Item.Author; if (albumImport.Where(e => e.Errors.Count == 0).ToList().Count > 0 && author != null && book != null) { _eventAggregator.PublishEvent(new BookImportedEvent( author, book, allImportedTrackFiles.Where(s => s.EditionId == book.Id).ToList(), allOldTrackFiles.Where(s => s.EditionId == book.Id).ToList(), replaceExisting, downloadClientItem)); } } //Adding all the rejected decisions importResults.AddRange(decisions.Where(c => !c.Approved) .Select(d => new ImportResult(d, d.Rejections.Select(r => r.Reason).ToArray()))); // Refresh any artists we added if (addedAuthors.Any()) { _commandQueueManager.Push(new BulkRefreshAuthorCommand(addedAuthors.Select(x => x.Id).ToList(), true)); } return(importResults); }