Beispiel #1
0
        private async void btnCreate_Click(object sender, EventArgs e)
        {
            var frmCreateXr = new frmCreateXR();
            var metadata    = await Task.Run(() => UIFunctions.GetAndValidateMetadata(txtMobi.Text, false, _logger));

            if (metadata != null)
            {
                // TODO DONT ACCESS THESE CONTROLS DIRECTLY
                frmCreateXr.txtAuthor.Text = metadata.Author;
                frmCreateXr.txtTitle.Text  = metadata.Title;
                frmCreateXr.txtAsin.Text   = metadata.Asin;
            }
            frmCreateXr.ShowDialog();
        }
Beispiel #2
0
        private void txtMobi_TextChanged(object sender, EventArgs e)
        {
            if (txtMobi.Text == "" || !File.Exists(txtMobi.Text))
            {
                return;
            }
            txtGoodreads.Text = "";
            prgBar.Value      = 0;

            var metadata = UIFunctions.GetAndValidateMetadata(txtMobi.Text, false, _logger);

            if (metadata == null)
            {
                txtMobi.Text = "";
                return;
            }
            metadata.CheckDrm();
            pbCover.Image = (Image)metadata.CoverImage?.Clone();

            lblTitle.Visible  = true;
            lblAuthor.Visible = true;
            lblAsin.Visible   = true;
            txtTitle.Visible  = true;
            txtAuthor.Visible = true;
            txtAsin.Visible   = true;

            txtAuthor.Text = metadata.Author;
            txtTitle.Text  = metadata.Title;
            txtAsin.Text   = metadata.Asin;
            _tooltip.SetToolTip(txtAsin, _amazonClient.Url(_settings.amazonTLD, txtAsin.Text));

            checkFiles(metadata.Author, metadata.Title, metadata.Asin, Path.GetFileNameWithoutExtension(txtMobi.Text));
            btnBuild.Enabled    = metadata.RawMlSupported;
            btnOneClick.Enabled = metadata.RawMlSupported;

            try
            {
                // Directory.Delete(randomFile, true);
            }
            catch (Exception ex)
            {
                _logger.Log($"An error occurred while trying to delete temporary files: {ex.Message}\r\n{ex.StackTrace}\r\n"
                            + "Try deleting these files manually.");
            }
        }
Beispiel #3
0
        private async Task btnSearchGoodreads_Run()
        {
            if (!File.Exists(txtMobi.Text))
            {
                MessageBox.Show("Specified book was not found.", "Book Not Found");
                return;
            }
            if (!Directory.Exists(_settings.outDir))
            {
                MessageBox.Show("Specified output directory does not exist. Please review the settings page.",
                                "Output Directory Not found");
                return;
            }

            //this.TopMost = true;
            using var metadata = await Task.Run(() => UIFunctions.GetAndValidateMetadata(txtMobi.Text, false, _logger));

            if (metadata == null)
            {
                return;
            }

            try
            {
                var books = new BookInfo[0];
                if (_settings.searchByAsin)
                {
                    books = (await _dataSource.SearchBookByAsinAsync(metadata.Asin)).ToArray();
                }

                if (books.Length <= 0)
                {
                    books = (await _dataSource.SearchBookAsync(metadata.Author, metadata.Title)).ToArray();
                    if (books.Length <= 0)
                    {
                        _logger.Log($"Unable to find this book on {_dataSource.Name}!\nEnsure the book's title ({metadata.Title}) is accurate!");
                        return;
                    }
                }

                string bookUrl;
                if (books.Length == 1)
                {
                    bookUrl = books[0].DataUrl;
                }
                else
                {
                    books = books.OrderByDescending(book => book.Reviews)
                            .ThenByDescending(book => book.Editions)
                            .ToArray();

                    // Pre-load cover images
                    foreach (var book in books.Where(book => !string.IsNullOrEmpty(book.ImageUrl)))
                    {
                        try
                        {
                            book.CoverImage = await _httpClient.GetImageAsync(book.ImageUrl, cancellationToken : _cancelTokens.Token);
                        }
                        catch (Exception ex)
                        {
                            _logger.Log($"Failed to download cover image: {ex.Message}");
                        }
                    }

                    _logger.Log($"Warning: Multiple results returned from {_dataSource.Name}...");
                    var frmG = new frmGR(books);
                    frmG.ShowDialog();
                    bookUrl = books[frmG.cbResults.SelectedIndex].DataUrl;
                }

                if (!string.IsNullOrEmpty(bookUrl))
                {
                    txtGoodreads.Text = bookUrl;
                    txtGoodreads.Refresh();
                    _logger.Log(
                        $"Book found on {_dataSource.Name}!\r\n{metadata.Title} by {metadata.Author}\r\n{_dataSource.Name} URL: {bookUrl}\r\n"
                        + "You may want to visit the URL to ensure it is correct.");
                }
            }
            catch (Exception ex)
            {
                _logger.Log($"An error occurred while searching: {ex.Message}\r\n{ex.StackTrace}");
            }
        }
Beispiel #4
0
        private async Task btnKindleExtras_Run()
        {
            //Check current settings
            if (!File.Exists(txtMobi.Text))
            {
                MessageBox.Show("Specified book was not found.", "Book Not Found");
                return;
            }
            if (rdoGoodreads.Checked)
            {
                if (txtGoodreads.Text == "")
                {
                    MessageBox.Show($"No {_dataSource.Name} link was specified.", $"Missing {_dataSource.Name} Link");
                    return;
                }
                if (!txtGoodreads.Text.ToLower().Contains(_settings.dataSource.ToLower()))
                {
                    MessageBox.Show($"Invalid {_dataSource.Name} link was specified.\r\n"
                                    + $"If you do not want to use {_dataSource.Name}, you can change the data source in Settings."
                                    , $"Invalid {_dataSource.Name} Link");
                    return;
                }
            }
            if (_settings.realName.Trim().Length == 0 || _settings.penName.Trim().Length == 0)
            {
                MessageBox.Show(
                    "Both Real and Pen names are required for End Action\r\n" +
                    "file creation. This information allows you to rate this\r\n" +
                    "book on Amazon. Please review the settings page.",
                    "Amazon Customer Details Not found");
                return;
            }

            var metadata = await Task.Run(() => UIFunctions.GetAndValidateMetadata(txtMobi.Text, _settings.saverawml, _logger));

            if (metadata == null)
            {
                return;
            }

            SetDatasourceLabels(); // Reset the dataSource for the new build process
            _logger.Log($"Book's {_dataSource.Name} URL: {txtGoodreads.Text}");
            try
            {
                var bookInfo = new BookInfo(metadata, txtGoodreads.Text, txtMobi.Text);

                var outputDir = OutputDirectory(bookInfo.Author, bookInfo.Title, bookInfo.Asin, Path.GetFileNameWithoutExtension(txtMobi.Text), true);

                _logger.Log("Attempting to build Author Profile...");

                ApPath = $@"{outputDir}\AuthorProfile.profile.{bookInfo.Asin}.asc";

                // TODO: Load existing ap to use for end actions / start actions
                if (!Settings.Default.overwrite && File.Exists(ApPath))
                {
                    _logger.Log("AuthorProfile file already exists... Skipping!\r\n" +
                                "Please review the settings page if you want to overwite any existing files.");
                    return;
                }

                var response = await _authorProfileGenerator.GenerateAsync(new AuthorProfileGenerator.Request
                {
                    Book     = bookInfo,
                    Settings = new AuthorProfileGenerator.Settings
                    {
                        AmazonTld     = _settings.amazonTLD,
                        SaveBio       = _settings.saveBio,
                        UseNewVersion = _settings.useNewVersion,
                        EditBiography = _settings.editBiography
                    }
                }, _cancelTokens.Token);

                if (response == null)
                {
                    return;
                }

                var authorProfileOutput = JsonConvert.SerializeObject(AuthorProfileGenerator.CreateAp(response, bookInfo.Asin));

                try
                {
                    File.WriteAllText(ApPath, authorProfileOutput);
                    _logger.Log($"Author Profile file created successfully!\r\nSaved to {ApPath}");
                }
                catch (Exception ex)
                {
                    _logger.Log($"An error occurred while writing the Author Profile file: {ex.Message}\r\n{ex.StackTrace}");
                    return;
                }

                SaPath = $@"{outputDir}\StartActions.data.{bookInfo.Asin}.asc";
                _logger.Log("Attempting to build Start Actions and End Actions...");

                string AsinPrompt(string title, string author)
                {
                    var frmAsin = _diContainer.GetInstance <frmASIN>();

                    frmAsin.Text           = "Series Information";
                    frmAsin.lblTitle.Text  = title;
                    frmAsin.lblAuthor.Text = author;
                    frmAsin.tbAsin.Text    = "";
                    frmAsin.ShowDialog();
                    return(frmAsin.tbAsin.Text);
                }

                var ea = new EndActions(response, bookInfo, metadata.RawMlSize, _dataSource, new EndActions.Settings
                {
                    AmazonTld         = _settings.amazonTLD,
                    Android           = _settings.android,
                    OutDir            = _settings.outDir,
                    OutputToSidecar   = _settings.outputToSidecar,
                    PenName           = _settings.penName,
                    RealName          = _settings.realName,
                    UseNewVersion     = _settings.useNewVersion,
                    UseSubDirectories = _settings.useSubDirectories,
                    PromptAsin        = _settings.promptASIN
                }, AsinPrompt, _logger, _httpClient, _amazonClient, _amazonInfoParser);
                if (!await ea.Generate())
                {
                    return;
                }

                if (_settings.useNewVersion)
                {
                    await ea.GenerateNewFormatData(_progress, _cancelTokens.Token);

                    // TODO: Do the templates differently
                    Extras.Artifacts.EndActions eaBase;
                    try
                    {
                        var template = File.ReadAllText($@"{Environment.CurrentDirectory}\dist\BaseEndActions.json", Encoding.UTF8);
                        eaBase = JsonConvert.DeserializeObject <Extras.Artifacts.EndActions>(template);
                    }
                    catch (FileNotFoundException)
                    {
                        _logger.Log(@"Unable to find dist\BaseEndActions.json, make sure it has been extracted!");
                        return;
                    }
                    catch (Exception e)
                    {
                        _logger.Log($@"An error occurred while loading dist\BaseEndActions.json (make sure any new versions have been extracted!)\r\n{e.Message}\r\n{e.StackTrace}");
                        return;
                    }

                    await ea.GenerateEndActionsFromBase(eaBase);

                    StartActions sa;
                    try
                    {
                        var template = File.ReadAllText($@"{Environment.CurrentDirectory}\dist\BaseStartActions.json", Encoding.UTF8);
                        sa = JsonConvert.DeserializeObject <StartActions>(template);
                    }
                    catch (FileNotFoundException)
                    {
                        _logger.Log(@"Unable to find dist\BaseStartActions.json, make sure it has been extracted!");
                        return;
                    }
                    catch (Exception e)
                    {
                        _logger.Log($@"An error occurred while loading dist\BaseStartActions.json (make sure any new versions have been extracted!)\r\n{e.Message}\r\n{e.StackTrace}");
                        return;
                    }

                    // TODO: Separate out SA logic
                    string saContent = null;
                    if (_settings.downloadSA)
                    {
                        _logger.Log("Attempting to download Start Actions...");
                        try
                        {
                            saContent = await _amazonClient.DownloadStartActions(metadata.Asin);

                            _logger.Log("Successfully downloaded pre-made Start Actions!");
                        }
                        catch
                        {
                            _logger.Log("No pre-made Start Actions available, building...");
                        }
                    }
                    if (string.IsNullOrEmpty(saContent))
                    {
                        saContent = ea.GenerateStartActionsFromBase(sa);
                    }

                    _logger.Log("Writing StartActions to file...");
                    File.WriteAllText(ea.SaPath, saContent);
                    _logger.Log($"StartActions file created successfully!\r\nSaved to {SaPath}");

                    cmsPreview.Items[3].Enabled = true;
                    EaPath = $@"{outputDir}\EndActions.data.{bookInfo.Asin}.asc";
                }
                else
                {
                    ea.GenerateOld();
                }

                cmsPreview.Items[1].Enabled = true;

                checkFiles(bookInfo.Author, bookInfo.Title, bookInfo.Asin, Path.GetFileNameWithoutExtension(txtMobi.Text));
                if (_settings.playSound)
                {
                    var player = new System.Media.SoundPlayer($@"{Environment.CurrentDirectory}\done.wav");
                    player.Play();
                }
            }
            catch (Exception ex)
            {
                _logger.Log("An error occurred while creating the new Author Profile, Start Actions, and/or End Actions files:\r\n" + ex.Message + "\r\n" + ex.StackTrace);
            }
            finally
            {
                metadata.Dispose();
            }
        }
Beispiel #5
0
        private async Task btnBuild_Run()
        {
            //Check current settings
            if (!File.Exists(txtMobi.Text))
            {
                MessageBox.Show(@"Specified book was not found.", @"Book Not Found");
                return;
            }
            if (rdoGoodreads.Checked && txtGoodreads.Text == "")
            {
                MessageBox.Show($"No {_dataSource.Name} link was specified.", $"Missing {_dataSource.Name} Link");
                return;
            }
            if (!Directory.Exists(_settings.outDir))
            {
                MessageBox.Show(@"Specified output directory does not exist.\r\nPlease review the settings page.", @"Output Directory Not found");
                return;
            }
            if (_settings.realName.Trim().Length == 0 || _settings.penName.Trim().Length == 0)
            {
                MessageBox.Show(
                    @"Both Real and Pen names are required for End Action\r\n" +
                    @"file creation. This information allows you to rate this\r\n" +
                    "book on Amazon. Please review the settings page.",
                    "Amazon Customer Details Not found");
                return;
            }

            prgBar.Value = 0;

            // todo this is crap
            var metadata = await Task.Run(() => UIFunctions.GetAndValidateMetadata(txtMobi.Text, _settings.saverawml, _logger));

            if (metadata == null)
            {
                return;
            }

            // Added author name to log output
            _logger.Log($"Book's {_dataSource.Name} URL: {txtGoodreads.Text}");
            if (_cancelTokens.IsCancellationRequested)
            {
                return;
            }
            _logger.Log("Attempting to build X-Ray...");

            //If AZW3 file use AZW3 offset, if checked. Checked by default.
            var AZW3 = Path.GetExtension(txtMobi.Text) == ".azw3" && _settings.overrideOffset;

            _logger.Log($"Offset: {(AZW3 ? $"{_settings.offsetAZW3} (AZW3)" : _settings.offset.ToString())}");

            //Create X-Ray and attempt to create the base file (essentially the same as the site)
            XRay.XRay xray;
            SetDatasourceLabels(); // Reset the dataSource for the new build process
            try
            {
                Task <XRay.XRay> xrayTask;
                if (rdoGoodreads.Checked)
                {
                    xrayTask = _xrayService.CreateXRayAsync(txtGoodreads.Text, metadata.DbName, metadata.UniqueId, metadata.Asin,
                                                            AZW3 ? _settings.offsetAZW3 : _settings.offset, _dataSource, _progress, _cancelTokens.Token);
                }
                else
                {
                    // TODO Set datasource properly
                    var fileDataSource = _diContainer.GetInstance <SecondaryDataSourceFactory>().Get(SecondaryDataSourceFactory.Enum.File);
                    xrayTask = _xrayService.CreateXRayAsync(txtXMLFile.Text, metadata.DbName, metadata.UniqueId, metadata.Asin,
                                                            AZW3 ? _settings.offsetAZW3 : _settings.offset, fileDataSource, _progress, _cancelTokens.Token);
                }

                xray = await Task.Run(() => xrayTask).ConfigureAwait(false);

                _xrayService.ExportAndDisplayTerms(xray, xray.AliasPath);

                if (_settings.enableEdit && DialogResult.Yes ==
                    MessageBox.Show(
                        "Terms have been exported to an alias file or already exist in that file. Would you like to open the file in notepad for editing?\r\n"
                        + "See the MobileRead forum thread (link in Settings) for more information on building aliases.",
                        "Aliases",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2))
                {
                    Functions.RunNotepad(xray.AliasPath);
                }
                if (!File.Exists(xray.AliasPath))
                {
                    _logger.Log("Aliases file not found.");
                }
                else
                {
                    _aliasesRepository.LoadAliasesForXRay(xray);
                    _logger.Log($"Character aliases read from {xray.AliasPath}.");
                }

                _logger.Log("Initial X-Ray built, adding locations and chapters...");
                //Expand the X-Ray file from the unpacked mobi
                if (await Task.Run(() => xray.ExpandFromRawMl(metadata.GetRawMlStream(), SafeShow, _progress, _cancelTokens.Token, _settings.ignoresofthyphen, !_settings.useNewVersion)).ConfigureAwait(false) > 0)
                {
                    _logger.Log("Build canceled or error occurred while processing locations and chapters.");
                    return;
                }
            }
            catch (OperationCanceledException)
            {
                _logger.Log("Build canceled.");
                return;
            }
            catch (Exception ex)
            {
                _logger.Log($"An error occurred while building the X-Ray:\r\n{ex.Message}\r\n{ex.StackTrace}");
                return;
            }

            _logger.Log("Saving X-Ray to file...");
            string outFolder;

            try
            {
                if (_settings.android)
                {
                    outFolder = $@"{_settings.outDir}\Android\{metadata.Asin}";
                    Directory.CreateDirectory(outFolder);
                }
                else
                {
                    outFolder = OutputDirectory(metadata.Author, metadata.Title, metadata.Asin, Path.GetFileNameWithoutExtension(txtMobi.Text), true);
                }
            }
            catch (Exception ex)
            {
                _logger.Log($"Failed to create output directory: {ex.Message}\r\n{ex.StackTrace}\r\nFiles will be placed in the default output directory.");
                outFolder = _settings.outDir;
            }
            var newPath = $"{outFolder}\\{xray.XRayName(_settings.android)}";

            try
            {
                var xrayExporter = _xrayExporterFactory.Get(_settings.useNewVersion ? XRayExporterFactory.Enum.Sqlite : XRayExporterFactory.Enum.Json);
                xrayExporter.Export(xray, newPath, _progress, _cancelTokens.Token);
            }
            catch (OperationCanceledException)
            {
                _logger.Log("Building canceled.");
                return;
            }
            catch (Exception ex)
            {
                // TODO: Add option to retry maybe?
                _logger.Log($"An error occurred while creating the X-Ray file. Is it opened in another program?\r\n{ex.Message}");
                return;
            }

            if (_settings.useNewVersion)
            {
                XrPath = $@"{outFolder}\XRAY.entities.{metadata.Asin}";

                //Save the new XRAY.ASIN.previewData file
                try
                {
                    var pdPath = $@"{outFolder}\XRAY.{metadata.Asin}.previewData";
                    _previewDataExporter.Export(xray, pdPath);
                    _logger.Log($"X-Ray previewData file created successfully!\r\nSaved to {pdPath}");
                }
                catch (Exception ex)
                {
                    _logger.Log($"An error occurred saving the previewData file: {ex.Message}\r\n{ex.StackTrace}");
                }
            }

            _logger.Log($"X-Ray file created successfully!\r\nSaved to {newPath}");

            checkFiles(metadata.Author, metadata.Title, metadata.Asin, Path.GetFileNameWithoutExtension(txtMobi.Text));

            if (_settings.playSound)
            {
                var player = new System.Media.SoundPlayer(Environment.CurrentDirectory + @"\done.wav");
                player.Play();
            }

            metadata.Dispose();
        }