Esempio n. 1
0
 private async Task <byte[]> GetImageBytes(IBooruPost modelBase,
                                           ImageSizeType type,
                                           CancellationToken cancellationToken)
 {
     return(type == ImageSizeType.Full
         ? await _httpClient.GetByteArrayAsync(modelBase.FullImageUrl, cancellationToken).ConfigureAwait(false)
         : await _httpClient.GetByteArrayAsync(modelBase.PreviewImageUrl, cancellationToken).ConfigureAwait(false));
 }
Esempio n. 2
0
        /// <summary>
        /// Return full path to image in cache directory depends on imagesizetype
        /// </summary>
        private string GetImagePath(IBooruPost booruImage, ImageSizeType type)
        {
            var workDir = Path.Combine(Directory.GetCurrentDirectory(), _cachePath);

            return(type == ImageSizeType.Preview
                ? Path.Combine(
                       workDir, booruImage.Hash + "_preview")
                : Path.Combine(
                       workDir, booruImage.Hash + "_full"));
        }
Esempio n. 3
0
        public async Task <BitmapImage> FetchImageAsync(
            IBooruPost booruPost,
            ImageSizeType imageSizeType,
            bool caching = true,
            CancellationToken cancellationToken = default)
        {
            caching = _configuration.ImageCaching;
            cancellationToken.ThrowIfCancellationRequested();
            BitmapImage resultImage;

            if (caching)
            {
                if (_imageCachingService.IsHasCache(booruPost, imageSizeType))
                {
                    resultImage = await _imageCachingService.GetImageAsync(
                        booruPost, imageSizeType, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    var imageBytes = await GetImageBytes(
                        booruPost, imageSizeType, cancellationToken).ConfigureAwait(false);

                    await _imageCachingService.CacheImageAsync(booruPost, imageSizeType, imageBytes,
                                                               imageSizeType, cancellationToken).ConfigureAwait(false);

                    resultImage =
                        await _bitmapImageCreatorService.CreateImageAsync(imageBytes).ConfigureAwait(false);
                }
            }
            else
            {
                resultImage =
                    await _bitmapImageCreatorService.CreateImageAsync(await GetImageBytes(
                                                                          booruPost, imageSizeType, cancellationToken).ConfigureAwait(false))
                    .ConfigureAwait(false);
            }


            return(resultImage);
            //    return await _bitmapImageCreatorService.CreateImageAsync(
            //        await GetImageBytes(booruImage, imageSizeType));

            //if (_imageCachingService.IsHasCache(booruImage, imageSizeType))
            //    return await _imageCachingService.GetImageAsync(booruImage, imageSizeType, token);

            //var imageBytes = await GetImageBytes(booruImage, imageSizeType);
            //await _imageCachingService.CacheImageAsync(booruImage, imageSizeType, imageBytes,
            //    imageSizeType, token);
            //return await _bitmapImageCreatorService.CreateImageAsync(imageBytes);
        }
Esempio n. 4
0
        public async Task <BitmapImage> GetImageAsync(
            IBooruPost booruImage,
            ImageSizeType imageType,
            CancellationToken cancellationToken = default)
        {
            byte[] buff;
            using (var file = new FileStream(GetImagePath(booruImage, imageType),
                                             FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
            {
                buff = new byte[file.Length];
                await file.ReadAsync(buff, 0, (int)file.Length, cancellationToken).ConfigureAwait(false);
            }

            return(await _imageCreatorService.CreateImageAsync(buff).ConfigureAwait(false));
        }
Esempio n. 5
0
 public async Task CacheImageAsync(IBooruPost booruImage,
                                   ImageSizeType imageType,
                                   byte[] bytes,
                                   ImageSizeType sizeType,
                                   CancellationToken cancellationToken = default)
 {
     try
     {
         using (FileStream stream = File.Open(GetImagePath(booruImage, imageType), FileMode.OpenOrCreate))
         {
             await stream.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false);
         }
     }
     catch (IOException e)
     {
     }
 }
Esempio n. 6
0
        private async Task AddBooruImage(IBooruPost post,
                                         Action <BooruImage> addImageCallback,
                                         CancellationToken cancellationToken)
        {
            var image =
                await _imageFetcherService.FetchImageAsync(
                    post,
                    ImageSizeType.Preview,
                    caching : false,
                    cancellationToken : cancellationToken).ConfigureAwait(false);

            var booruImage = new BooruImage
            {
                Hash  = post.Hash,
                Image = image
            };

            addImageCallback.Invoke(booruImage);

            BooruPreviewImages.Add(booruImage);
        }
Esempio n. 7
0
 public bool IsHasCache(IBooruPost booruImage,
                        ImageSizeType imageType)
 {
     return(File.Exists(GetImagePath(
                            booruImage, imageType)));
 }
Esempio n. 8
0
        public static void Run()
        {
            lock (Bots)
            {
                foreach (TwitterBot bot in Bots)
                {
                    LogHeader($@"Posting to Twitter from {bot.Name}");

                    IBooruPost randomPost = null;
                    IMedia     media      = null;

                    int tries = 0;

                    while (media == null && tries < 10)
                    {
                        ++tries;
                        Debug.WriteLine($@"Attempting to prepare media attempt {tries}");

                        if (randomPost != null) // if we're here, we probably failed once and we don't want to retry
                        {
                            bot.DeletePost(randomPost.PostId);
                        }

                        randomPost = bot.GetRandomPost();
                        Log(randomPost?.PostUrl ?? @"No posts available");

                        if (randomPost == null)
                        {
                            break;
                        }

                        HttpResponseMessage httpResponse;

                        try
                        {
                            lock (DownloadLock)
                            {
                                Debug.WriteLine($@"Downloading {randomPost.FileUrl}");
                                httpResponse = HttpClient.GetAsync(randomPost.FileUrl).Result;
                                Thread.Sleep(TwitterBot.REQUEST_INTERVAL);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log(@"Error during request!", ConsoleColor.Black, ConsoleColor.Red);
                            DumpException(ex);
                            bot.DeletePost(randomPost.PostId);
                            media = null;
                            continue;
                        }

                        try
                        {
                            Debug.WriteLine($@"Uploading to Twitter");
                            using (Stream hrs = httpResponse.Content.ReadAsStreamAsync().Result)
                                media = bot.Client.UploadMedia(hrs);
                        }
                        catch (Exception ex)
                        {
                            Log(@"Error during stream handle!", ConsoleColor.Black, ConsoleColor.Red);
                            DumpException(ex);
                            bot.DeletePost(randomPost.PostId);
                            media = null;
                            continue;
                        }

                        httpResponse?.Dispose(); // f**k it

                        int seconds = 0;

                        while (!(media?.IsReadyToBeUsed ?? false))//false
                        {
                            Thread.Sleep(1000);
                            if (++seconds >= 5)
                            {
                                bot.DeletePost(randomPost.PostId);
                                media = null;
                                break;
                            }
                        }

                        if (media?.Data == null)
                        {
                            media = null;
                        }

                        Log($@"{bot.Name.PadRight(20)} - Tries: {tries} - Media Null? {media == null}", ConsoleColor.Black, ConsoleColor.Blue);
                    }

                    if (media != null)
                    {
                        try
                        {
                            bot.Client.PostTweet(randomPost.PostUrl, media);
                            bot.DeletePost(randomPost.PostId);
                        }
                        catch (Exception ex)
                        {
                            Log(ex, ConsoleColor.Red);
                            DumpException(ex);
                        }
                    }

                    Log($@"Validating cache for {bot.Name}");

                    if (!bot.EnsureCacheReady())
                    {
                        Log($@"Refreshing cache for {bot.Name}, this may take a little bit...");
                        new Thread(bot.RefreshCache)
                        {
                            IsBackground = true
                        }.Start();
                    }
                }
            }
        }
Esempio n. 9
0
 public BooruImage GetPreviewBooruImage(IBooruPost post)
 {
     return(BooruPreviewImages.FirstOrDefault(i => i.Hash == post.Hash));
 }