Exemplo n.º 1
0
 public RootDialog(IBargainBotDialogFactory dialogFactory, IRepository <User> userRepo, AmazonClient amazonClient)
 {
     _dialogFactory = dialogFactory;
     _userRepo      = userRepo;
     _amazonClient  = amazonClient;
     _cookie        = null;
 }
Exemplo n.º 2
0
        public void ItemSearch()
        {
            var client = new AmazonClient(CountryType.Japan);
            var r      = client.ItemSearch(SearchIndexType.Books);

            Console.WriteLine(r);
        }
Exemplo n.º 3
0
        public Task <Term[]> DownloadTermsAsync(string asin, string regionTld, CancellationToken cancellationToken)
        {
            return(HandleDownloadExceptionsAsync(async() =>
            {
                if (!AmazonClient.IsAsin(asin))
                {
                    return null;
                }

                var requestContent = new StringContent(JsonUtil.Serialize(new DownloadRequest
                {
                    Asin = asin,
                    Type = DownloadRequest.TypeEnum.Terms,
                    RegionTld = regionTld
                }), Encoding.UTF8, "application/json");
                var request = new HttpRequestMessage(HttpMethod.Post, $"{BaseUrl}{DownloadEndpoint}")
                {
                    Content = requestContent
                };
                // Increase timeout for terms requests
                request.SetTimeout(TimeSpan.FromSeconds(30));
                var response = await _httpClient.SendAsync(request, cancellationToken);
                var responseStream = await response.Content.ReadAsStreamAsync();
                var responseString = await new StreamReader(responseStream, Encoding.UTF8).ReadToEndAsync();
                return XmlUtil.Deserialize <Term[]>(responseString);
            }));
        }
Exemplo n.º 4
0
        private async Task CheckAndFixIncorrectAsinOrThrowAsync(IMetadata metadata, string bookPath, CancellationToken cancellationToken)
        {
            if (AmazonClient.IsAsin(metadata.Asin))
            {
                return;
            }

            // todo add check for fixasin flag
            if (!metadata.CanModify)
            {
                throw new Exception($"Invalid Amazon ASIN detected: {metadata.Asin}!\r\nKindle may not display an X-Ray for this book.\r\nYou must either use Calibre's Quality Check plugin (Fix ASIN for Kindle Fire) or a MOBI editor (exth 113 and optionally 504) to change this.");
            }

            _logger.Log($"Invalid Amazon ASIN detected: {metadata.Asin}!\nKindle may not display an X-Ray for this book.\r\nAttempting to fix it automatically...");
            _logger.Log($"Searching Amazon for {metadata.Title} by {metadata.Author}...");
            // todo config tld
            var amazonSearchResult = await _amazonClient.SearchBook(metadata.Title, metadata.Author, "com", cancellationToken);

            if (amazonSearchResult != null)
            {
                metadata.SetAsin(amazonSearchResult.Asin);
#if NETCOREAPP3_1
                await using var fs = new FileStream(bookPath, FileMode.Create);
#else
                using var fs = new FileStream(bookPath, FileMode.Create);
#endif
                metadata.Save(fs);
                _logger.Log($"Successfully updated the ASIN to {metadata.Asin}! Be sure to copy this new version of the book to your Kindle device.");
            }
            else
            {
                _logger.Log("Unable to automatically find a matching ASIN for this book on Amazon :(");
            }
        }
        private ISearchResult FindAmazonOffer(Book book)
        {
            var appSettings  = AppSettings;
            var amazonClient = new AmazonClient(appSettings);
            var amazonSite   = new AmazonSite(amazonClient);

            return(amazonSite.FindBookByISBN(book.ISBN13));
        }
Exemplo n.º 6
0
        private bool CheckAsin()
        {
            if (AmazonClient.IsAsin(tbAsin.Text))
            {
                return(true);
            }

            MessageBox.Show("This does not appear to be a valid ASIN.\r\nAre you sure it is correct?", "Invalid ASIN", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
            return(false);
        }
Exemplo n.º 7
0
 public static void IncorrectAsinPromptOrThrow(string asin)
 {
     if (!AmazonClient.IsAsin(asin) &&
         DialogResult.No == MessageBox.Show($"Incorrect ASIN detected: {asin}!\n" +
                                            "Kindle may not display an X-Ray for this book.\n" +
                                            "Do you wish to continue?", "Incorrect ASIN", MessageBoxButtons.YesNo))
     {
         throw new Exception($"Incorrect ASIN detected: {asin}!\r\n" +
                             "Kindle may not display an X-Ray for this book.\r\n" +
                             "You must either use Calibre's Quality Check plugin (Fix ASIN for Kindle Fire) " +
                             "or a MOBI editor (exth 113 and optionally 504) to change this.");
     }
 }
Exemplo n.º 8
0
        private async void btnDownloadTerms_Click(object sender, EventArgs e)
        {
            if (!AmazonClient.IsAsin(txtAsin.Text))
            {
                MessageBox.Show($"'{txtAsin.Text} is not a valid ASIN.\r\nRoentgen requires one!");
                return;
            }

            ToggleInterface(false);
            await DownloadTermsAsync(txtAsin.Text);

            ToggleInterface(true);
        }
Exemplo n.º 9
0
        static Crash()
        {
            string         AWSError;
            AWSCredentials AWSCredentialsForOutput = new StoredProfileAWSCredentials(Settings.Default.AWSS3ProfileName, Settings.Default.AWSCredentialsFilepath);
            AmazonS3Config S3ConfigForOutput       = new AmazonS3Config
            {
                ServiceURL = Settings.Default.AWSS3URL
            };

            AmazonClient = new AmazonClient(AWSCredentialsForOutput, null, S3ConfigForOutput, out AWSError);

            if (!AmazonClient.IsS3Valid)
            {
                System.Diagnostics.Debug.WriteLine("Failed to initailize S3");
            }
        }
Exemplo n.º 10
0
        private string GetFilePath(String FileName)
        {
            string Path = null;

            if (Settings.Default.DownloadFromS3)
            {
                int ReportIDSegment = (Id / 10000) * 10000;

                string reportPath = string.Format("{0}/{1}/{2}/{2}{3}", Settings.Default.AWSS3KeyPrefix, ReportIDSegment, Id, FileName);

                Path = AmazonClient.GetS3SignedUrl("crashreporter", reportPath, 60);
            }
            else
            {
                Path = Properties.Settings.Default.CrashReporterFiles + Id + FileName;
            }

            return(Path);
        }
Exemplo n.º 11
0
        private async Task <T> DownloadArtifactAsync <T>(string asin, string regionTld, DownloadRequest.TypeEnum type, CancellationToken cancellationToken) where T : class
        {
            if (!AmazonClient.IsAsin(asin))
            {
                return(null);
            }

            var request = new StringContent(JsonUtil.Serialize(new DownloadRequest
            {
                Asin      = asin,
                Type      = type,
                RegionTld = regionTld
            }), Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync($"{BaseUrl}{DownloadEndpoint}", request, cancellationToken);

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

            var responseString = await new StreamReader(responseStream, Encoding.UTF8).ReadToEndAsync();

            return(JsonUtil.Deserialize <T>(responseString, false));
        }
Exemplo n.º 12
0
 /// <summary>
 /// Initializes a new instance of the login form with a specified OAuth client.
 /// </summary>
 /// <param name="client">Instance of the OAuth client.</param>
 /// <param name="autoLogout">Disables saving and restoring authorization cookies in WebBrowser. Default: false.</param>
 /// <param name="loadUserInfo">Indicates the need to make a request for recive the user profile or not. Default: false.</param>
 /// <param name="responseType">Allows to set the type of response that is expected from the server. Default: <see cref="ResponseType.Token"/>.</param>
 public AmazonLogin(AmazonClient client, bool autoLogout = false, bool loadUserInfo = false, string responseType = "token") : base(client, autoLogout, loadUserInfo, responseType)
 {
     this.Width  = 785;
     this.Height = 575;
     this.Icon   = Properties.Resources.amazon;
 }
 public PictureTransformWorker(AmazonClient amazonClient)
 {
     _amazonClient = amazonClient;
 }
Exemplo n.º 14
0
 public HomeController(AmazonClient amazonClient)
 {
     _amazonClient = amazonClient;
 }
Exemplo n.º 15
0
        public void GetRanking()
        {
            var c = new AmazonClient(CountryType.Japan);

            c.GetRanking(SearchIndexType.Books);
        }
Exemplo n.º 16
0
        public string ItemSearch(CountryType countryType, SearchIndexType indexType, int itemPage = 1)
        {
            var cachePath = @"C:\amazon\cache";

            if (!Directory.Exists(cachePath))
            {
                Directory.CreateDirectory(cachePath);
            }

            var filepath = Path.Combine(cachePath, string.Format("{0}-{1}-{2}.cache", countryType, indexType, itemPage));

            lock (filepath)
            {
                try
                {
                    if (File.Exists(filepath))
                    {
                        var file = new FileInfo(filepath);
                        if (file.LastWriteTime.CompareTo(DateTime.Now.AddMinutes(-30)) > 0)
                        {
                            return(File.ReadAllText(filepath));
                        }
                        //File.Delete(filepath);
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }
            }


            var client = new AmazonClient(countryType);

            var accessFilePath = Path.Combine(cachePath, @"last_access.txt");

            if (!File.Exists(accessFilePath))
            {
                File.WriteAllText(accessFilePath, DateTime.Now.ToString());
            }
            var lastAccessInfo = new FileInfo(accessFilePath);

            if (lastAccessInfo.LastWriteTime.CompareTo(DateTime.Now.AddSeconds(-1)) > 0)
            {
                Thread.Sleep(1000);
            }
            File.SetLastWriteTime(accessFilePath, DateTime.Now);
            var response = client.ItemSearch(indexType, itemPage: itemPage);

            lock (filepath)
            {
                try
                {
                    File.WriteAllText(filepath, response);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                    throw;
                }
            }

            return(response);
        }
Exemplo n.º 17
0
 public DealJob(AmazonClient amazonClient, IRepository <Deal> dealRepo, IRepository <User> userRepo)
 {
     _dealRepo     = dealRepo;
     _userRepo     = userRepo;
     _amazonClient = amazonClient;
 }
Exemplo n.º 18
0
        public void GetItemDetail()
        {
            var c = new AmazonClient(CountryType.Japan);

            c.GetItemDetail("B007X1U8ZQ");
        }
Exemplo n.º 19
0
        public void ItemLookup()
        {
            var client = new AmazonClient(CountryType.US);

            Console.WriteLine(client.ItemLookup("0545010225", ResponseGroupType.Small));
        }
Exemplo n.º 20
0
        public void CartCreate()
        {
            var client = new AmazonClient(CountryType.US);

            Console.WriteLine(client.CartCreate());
        }
        /// <summary>
        /// Start the service, and stop the service if there were any errors found.
        /// </summary>
        /// <param name="Arguments">Command line arguments (unused).</param>
        protected override void OnStart(string[] Arguments)
        {
            // Create a log file for any start-up messages
            Log = new LogWriter("CrashReportProcess", LogFolder);

            Config.LoadConfig();

            Slack = new SlackWriter
            {
                WebhookUrl = Config.Default.SlackWebhookUrl,
                Channel    = Config.Default.SlackChannel,
                Username   = Config.Default.SlackUsername,
                IconEmoji  = Config.Default.SlackEmoji
            };

            Symbolicator = new Symbolicator();

            StatusReporter = new StatusReporting();

            ReportIndex = new ReportIndex
            {
                IsEnabled = !string.IsNullOrWhiteSpace(Config.Default.ProcessedReportsIndexPath),
                Filepath  = Config.Default.ProcessedReportsIndexPath,
                Retention = TimeSpan.FromDays(Config.Default.ReportsIndexRetentionDays)
            };

            ReportIndex.ReadFromFile();

            WriteEvent("Initializing AWS");
            string          AWSError;
            AWSCredentials  AWSCredentialsForDataRouter = new StoredProfileAWSCredentials(Config.Default.AWSProfileInputName, Config.Default.AWSCredentialsFilepath);
            AmazonSQSConfig SqsConfigForDataRouter      = new AmazonSQSConfig
            {
                ServiceURL = Config.Default.AWSSQSServiceInputURL
            };
            AmazonS3Config S3ConfigForDataRouter = new AmazonS3Config
            {
                ServiceURL = Config.Default.AWSS3ServiceInputURL
            };

            DataRouterAWS = new AmazonClient(AWSCredentialsForDataRouter, SqsConfigForDataRouter, S3ConfigForDataRouter, out AWSError);
            if (!DataRouterAWS.IsSQSValid || !DataRouterAWS.IsS3Valid)
            {
                WriteFailure("AWS failed to initialize profile for DataRouter access. Error:" + AWSError);
                StatusReporter.Alert("AWSFailInput", "AWS failed to initialize profile for DataRouter access", 0);
            }
            AWSCredentials AWSCredentialsForOutput = new StoredProfileAWSCredentials(Config.Default.AWSProfileOutputName, Config.Default.AWSCredentialsFilepath);
            AmazonS3Config S3ConfigForOutput       = new AmazonS3Config
            {
                ServiceURL = Config.Default.AWSS3ServiceOutputURL
            };

            OutputAWS = new AmazonClient(AWSCredentialsForOutput, null, S3ConfigForOutput, out AWSError);
            if (!OutputAWS.IsS3Valid)
            {
                WriteFailure("AWS failed to initialize profile for output S3 bucket access. Error:" + AWSError);
                StatusReporter.Alert("AWSFailOutput", "AWS failed to initialize profile for output S3 bucket access", 0);
            }

            // Add directory watchers
            WriteEvent("Creating ReportWatcher");
            Watcher = new ReportWatcher();

            WriteEvent("Creating ReportProcessors");
            for (int ProcessorIndex = 0; ProcessorIndex < Config.Default.ProcessorThreadCount; ProcessorIndex++)
            {
                var Processor = new ReportProcessor(Watcher, ProcessorIndex);
                Processors.Add(Processor);
            }

            // Init events by enumerating event names
            WriteEvent("Initializing Event Counters");
            FieldInfo[] EventNameFields = typeof(StatusReportingEventNames).GetFields(BindingFlags.Static | BindingFlags.Public);
            StatusReporter.InitCounters(EventNameFields.Select(EventNameField => (string)EventNameField.GetValue(null)));

            WriteEvent("Initializing Performance Mean Counters");
            FieldInfo[] MeanNameFields = typeof(StatusReportingPerfMeanNames).GetFields(BindingFlags.Static | BindingFlags.Public);
            StatusReporter.InitMeanCounters(MeanNameFields.Select(MeanNameField => (string)MeanNameField.GetValue(null)));

            WriteEvent("Initializing Folder Monitors");
            Dictionary <string, string> FoldersToMonitor = new Dictionary <string, string>();

            FoldersToMonitor.Add(Config.Default.ProcessedReports, "Processed Reports");
            FoldersToMonitor.Add(Config.Default.ProcessedVideos, "Processed Videos");
            FoldersToMonitor.Add(Config.Default.DepotRoot, "P4 Workspace");
            FoldersToMonitor.Add(Config.Default.InternalLandingZone, "CRR Landing Zone");
            FoldersToMonitor.Add(Config.Default.DataRouterLandingZone, "Data Router Landing Zone");
            FoldersToMonitor.Add(Config.Default.PS4LandingZone, "PS4 Landing Zone");
            FoldersToMonitor.Add(Assembly.GetExecutingAssembly().Location, "CRP Binaries and Logs");
            FoldersToMonitor.Add(Config.Default.MDDPDBCachePath, "MDD PDB Cache");
            StatusReporter.InitFolderMonitors(FoldersToMonitor);

            WriteEvent("Starting StatusReporter");
            StatusReporter.Start();

            // Start the threads now
            Watcher.Start();
            foreach (var Processor in Processors)
            {
                Processor.Start();
            }

            DateTime StartupTime = DateTime.UtcNow;

            WriteEvent("Successfully started at " + StartupTime);
        }
 public CreateOrderWorkflow(Venue venue, TCreateOrderService orderCreator, AmazonClient client)
 {
     _orderCreator = orderCreator;
     _client       = client;
     _venue        = venue;
 }