Beispiel #1
0
        public void AddDocumentToPackage(int documentId, int packageId)
        {
            using (var dc = new DocuContext())
            {
                //var testDocument = new Document
                //{
                //    Title = "Test Document",
                //    Description = "A document as a test",
                //    FilePath = "www.google.com",
                //    UploadDate = DateTime.Today
                //};
                //dc.Documents.Add(testDocument);
                //dc.SaveChanges();

                //documentId = testDocument.DocumentId;
                //packageId = 1;

                var added = new PackageDocument
                {
                    DocumentId = documentId,
                    PackageId  = packageId
                };
                dc.PackageDocuments.Add(added);
                dc.SaveChanges();
            }
        }
        void EnsureFeedLoaded()
        {
            if (_packageDocument == null)
            {
                var feed     = LoadFeed(_feedUri.ToString());
                var packages = new List <PackageItem>(feed.ToPackageDocument().Packages);

                SyndicationLink nextLink;
                while ((nextLink = feed.Links.SingleOrDefault(x => x.RelationshipType.EqualsNoCase("next"))) != null)
                {
                    feed = LoadFeed(nextLink.GetAbsoluteUri().ToString());
                    packages.AddRange(feed.ToPackageDocument().Packages);
                }
                _packageDocument = new PackageDocument()
                {
                    Packages = packages.AsReadOnly()
                };
            }
        }
        //EPUBファイルがドロップされたらテキストボックスに表示し、読み込む
        private void OnDrop(object sender, DragEventArgs e)
        {
            string[] files = e.Data.GetData(DataFormats.FileDrop) as string[];
            if (files != null)
            {
                var textBox  = sender as TextBox;
                var fileName = files[0];

                //拡張子がepubでなければエラーメッセージを出して終了する
                if (Path.GetExtension(fileName).ToLower().Equals(".epub") != true)
                {
                    MessageBox.Show("EPUBファイルではありません");
                    return;
                }

                //Epubファイルなので読み込みを行う
                epubFile     = fileName;                                  //対象ファイルとして設定する
                textBox.Text = files[0];                                  //TextBoxに表示する

                tempDir = Unpacker.UnpackEpubToTemp(epubFile);            //Epubをテンポラリフォルダに解凍する
                tempDirsToDelete.Add(tempDir);                            //削除対象に追加

                var pacDoc    = ContainerXML.GetPackageDocument(tempDir); //パッケージ文書を取得する
                var textItems = PackageDocument.GetTextItems(pacDoc);     //Epub内のテキストファイルを取得する
                textItems = textItems.OrderBy(i => i).ToList();           //ソートする

                //ファイルをリストボックスに追加する
                fileLists.Items.Clear();                //現在のアイテムを削除する
                foreach (var item in textItems)
                {
                    fileLists.Items.Add(item.Remove(0, tempDir.Length + 1));   //相対パス部分だけを表示する
                }

                ePubGenBtn.IsEnabled = true;    //Epub生成ボタンを動作可能にする
            }
        }
 protected void when_parsing_package_document()
 {
     PackageDoc = Feed.ToPackageDocument();
 }
Beispiel #5
0
 protected void when_parsing_package_document()
 {
     PackageDoc = Feed.ToPackageDocument();
 }
        //テンプレートからEpubファイルを作成する
        public bool GenerateEpubDocument()
        {
            //ファイルの上書きを確認する
            var epubFileName = GetEpubFileName();

            if (File.Exists(epubFileName))
            {
                var overwrite = MessageBox.Show("ファイルを上書きしますか?", "Nov2Epub", MessageBoxButton.OKCancel);
                if (overwrite == MessageBoxResult.OK)
                {
                    File.Delete(epubFileName);
                }
                else //上書きしないならそのまま終了
                {
                    return(false);
                }
            }
            //テンプレートファイルをテンポラリディレクトリにコピーする
            var templateDir = GetTemplateDirectory();                                                            //テンプレートディレクトリ
            var tempDir     = Path.GetTempPath();                                                                //テンポラリディレクトリ
            var epubDirName = Path.Combine(tempDir, Path.GetFileNameWithoutExtension(Path.GetRandomFileName())); //ランダム

            CopyDirectory(templateDir, epubDirName);                                                             //コピーする

            //パッケージドキュメントを更新する
            var packFile = ContainerXML.GetPackageDocument(epubDirName);

            PackageDocument.WriteMetaData(packFile, metaData);

            //表紙ファイルを更新する
            var coverImageDst = Path.Combine(epubDirName, @"OEBPS\Images\Cover.JPG");

            File.Copy(coverImageFileName, coverImageDst, true);

            //扉ページを更新する
            var titlePageDst = Path.Combine(epubDirName, @"OEBPS\Text\Title.xhtml");

            InfoPage.UpdateTitlePage(titlePageDst, metaData);

            //テキストを更新する
            var textTemplateFile = Path.Combine(epubDirName, @"OEBPS\Text\Text.xhtml");
            var headerAnchors    = TextConverter.ConvertText(novelFileName, textTemplateFile, opt);

            //本文の縦書き/横書きをCSSに設定する
            var textCssTemplateFile = Path.Combine(epubDirName, @"OEBPS\Styles\Text.css");

            TextStyleSheet.SetOrientationStyle(textCssTemplateFile, metaData.isVertical);

            //目次の縦書き/横書きをCSSに設定する
            var navCssTemplateFile = Path.Combine(epubDirName, @"OEBPS\Styles\Nav.css");

            TextStyleSheet.SetOrientationStyle(navCssTemplateFile, metaData.isVertical);


            //ナビゲーションドキュメントを作成する
            var navFileName = Path.Combine(epubDirName, @"OEBPS\Text\nav.xhtml");

            NavigationDocument.WriteNavigationDocument(navFileName, headerAnchors);

            //奥付ページを更新する
            var ColophonPage = Path.Combine(epubDirName, @"OEBPS\Text\Colophon.xhtml");

            InfoPage.UpdateTitlePage(ColophonPage, metaData);

            //不要ファイルを削除する
            var thumbsFile = Path.Combine(epubDirName, @"OEBPS\Images\Thumbs.db");

            if (File.Exists(thumbsFile) == true)
            {
                File.Delete(thumbsFile);
            }

            //EPubファイルを作成する
            Archiver.ArchiveEpubWithPostProcess(epubDirName, epubFileName);

            //テンポラリディレクトリを削除する
            Directory.Delete(epubDirName, true);

            //Identifierを更新する
            IdentifierDictionary.SaveIdentifierDictionary();

            return(true);
        }
Beispiel #7
0
        private static async Task RunAddPackageAsync(PackageOperation packageOperation, CloudBlockBlob packageBlob, ILogger log, List <IndexAction <PackageDocument> > indexActions)
        {
            var packagesToIndex = new List <PackageDocument>();

            log.LogInformation("Downloading package {packageId}@{packageVersionNormalized} for indexing...",
                               packageOperation.Id, packageOperation.Version);

            using (var packageInputStream = await HttpClient.GetStreamAsync(packageOperation.PackageUrl))
                using (var packageInputSeekableStream = TemporaryFileStream.Create())
                {
                    await packageInputStream.CopyToAsync(packageInputSeekableStream);

                    packageInputSeekableStream.Position = 0;

                    log.LogInformation("Finished downloading package {packageId}@{packageVersionNormalized} for indexing...",
                                       packageOperation.Id, packageOperation.Version);

                    using (var nugetPackage = new PackageArchiveReader(packageInputSeekableStream))
                    {
                        log.LogInformation("Analyzing package {packageId}@{packageVersionNormalized}...",
                                           packageOperation.Id, packageOperation.Version);

                        // Get some metadata
                        var nuspecReader    = nugetPackage.NuspecReader;
                        var packageIdentity = nuspecReader.GetIdentity();
                        var packageSummary  = nuspecReader.GetDescription();
                        if (string.IsNullOrEmpty(packageSummary))
                        {
                            packageSummary = nuspecReader.GetSummary();
                        }

                        var packageToIndex = new PackageDocument(
                            packageIdentity.Id,
                            packageIdentity.Version.ToNormalizedString(),
                            packageIdentity.Version.OriginalVersion,
                            nuspecReader.GetTitle(),
                            packageSummary,
                            nuspecReader.GetAuthors(),
                            nuspecReader.GetTags(),
                            nuspecReader.GetIconUrl(),
                            nuspecReader.GetLicenseUrl(),
                            nuspecReader.GetProjectUrl(),
                            packageOperation.Published,
                            AuxiliaryNuGetData.GetDownloadCount(packageIdentity.Id),
                            packageOperation.IsListed,
                            packageIdentity.Version.IsPrerelease);

                        var targetFrameworks = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                        var typeNames        = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                        var frameworkSpecificGroups = nugetPackage.GetReferenceItems();
                        foreach (var frameworkSpecificGroup in frameworkSpecificGroups)
                        {
                            // Get some metadata
                            var targetFramework = frameworkSpecificGroup.TargetFramework.GetShortFolderName();
                            targetFrameworks.Add(targetFramework);

                            log.LogInformation(
                                "Collecting information for {packageId}@{packageVersionNormalized} and framework {targetFramework}...",
                                packageOperation.Id, packageOperation.Version, targetFramework);

                            // Collect assembly data
                            foreach (var item in frameworkSpecificGroup.Items)
                            {
                                var entry     = nugetPackage.GetEntry(item);
                                var entryName = item;

                                log.LogInformation(
                                    "Collecting assembly information from {entryName} for {packageId}@{packageVersionNormalized} and framework {targetFramework}...",
                                    entryName, packageOperation.Id, packageOperation.Version, targetFramework);

                                using (var assemblyStream = entry.Open())
                                    using (var assemblySeekableStream = TemporaryFileStream.Create())
                                    {
                                        await assemblyStream.CopyToAsync(assemblySeekableStream);

                                        assemblySeekableStream.Position = 0;

                                        using (var portableExecutableReader = new PEReader(assemblySeekableStream))
                                        {
                                            var metadataReader = portableExecutableReader.GetMetadataReader();
                                            foreach (var typeDefinition in metadataReader.TypeDefinitions.Select(metadataReader
                                                                                                                 .GetTypeDefinition))
                                            {
                                                if (!typeDefinition.Attributes.HasFlag(TypeAttributes.Public))
                                                {
                                                    continue;
                                                }

                                                var typeNamespace = metadataReader.GetString(typeDefinition.Namespace);
                                                var typeName      = metadataReader.GetString(typeDefinition.Name);

                                                if (typeName.StartsWith("<") || typeName.StartsWith("__Static") ||
                                                    typeName.Contains("c__DisplayClass"))
                                                {
                                                    continue;
                                                }

                                                log.LogDebug(
                                                    "{packageId}@{packageVersionNormalized}, framework {targetFramework}, entry {entryName}: adding {namespace}.{type}",
                                                    packageOperation.Id, packageOperation.Version, targetFramework, entryName, typeNamespace, typeName);

                                                typeNames.Add($"{typeNamespace}.{typeName}");
                                            }
                                        }
                                    }

                                log.LogInformation(
                                    "Finished collecting assembly information from {entryName} for {packageId}@{packageVersionNormalized} and framework {targetFramework}.",
                                    entryName, packageOperation.Id, packageOperation.Version, targetFramework);
                            }

                            log.LogInformation(
                                "Finished collecting information for {packageId}@{packageVersionNormalized} and framework {targetFramework}.",
                                packageOperation.Id, packageOperation.Version, targetFramework);
                        }

                        packageToIndex.TargetFrameworks = targetFrameworks.ToHashSet();
                        packageToIndex.TypeNames        = typeNames.ToHashSet();

                        log.LogInformation("Finished analyzing package {packageId}@{packageVersionNormalized}.",
                                           packageOperation.Id, packageOperation.Version);

                        // Build index
                        log.LogInformation(
                            "Creating index actions for package {packageId}@{packageVersionNormalized}...",
                            packageOperation.Id, packageOperation.Version);

                        // Add to index blob
                        packagesToIndex.Add(packageToIndex);

                        // Add to index
                        indexActions.Add(IndexAction.MergeOrUpload(packageToIndex));

                        log.LogInformation(
                            "Finished creating index actions for package {packageId}@{packageVersionNormalized}.",
                            packageOperation.Id, packageOperation.Version);

                        log.LogInformation("Finished analyzing package {packageId}@{packageVersionNormalized}.",
                                           packageOperation.Id, packageOperation.Version);
                    }
                }

            log.LogInformation("Storing index blob for package {packageId}@{packageVersionNormalized}...",
                               packageOperation.Id, packageOperation.Version);

            // Store index blob
            try
            {
                await packageBlob.DeleteIfExistsAsync();

                using (var jsonStream = await packageBlob.OpenWriteAsync())
                    using (var jsonWriter = new StreamWriter(jsonStream))
                    {
                        JsonSerializer.Serialize(jsonWriter, packagesToIndex);
                    }

                log.LogInformation("Finished storing index blob for package {packageId}@{packageVersionNormalized}.",
                                   packageOperation.Id, packageOperation.Version);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Error storing index blob for package {packageId}@{packageVersionNormalized}.",
                             packageOperation.Id, packageOperation.Version);
            }
        }