Exemple #1
0
        public async Task Slap(CommandContext ctx, DiscordMember m)
        {
            var c      = new HttpClient();
            var weeurl = await Bot._weeb.GetRandomAsync("slap", new[] { "" });

            Stream img = new MemoryStream(await c.GetByteArrayAsync(Other.resizeLink(weeurl.Url)));
            var    em  = new DiscordEmbedBuilder();

            em.WithDescription($"{ctx.Member.Mention} slaps {m.Mention} ÒwÓ");
            em.WithImageUrl($"attachment://image.{MimeGuesser.GuessExtension(img)}");
            em.WithFooter("by nekos.life");

            DiscordMessageBuilder builder = new();

            builder.WithFile($"image.{MimeGuesser.GuessExtension(img)}", img);
            builder.WithEmbed(em.Build());
            await ctx.RespondAsync(builder);
        }
Exemple #2
0
        public async Task GumiPic(CommandContext ctx)
        {
            var    myresponse  = JsonConvert.DeserializeObject <ImgRet>(await new WebClient().DownloadStringTaskAsync($"https://api.meek.moe/gumi"));
            Stream dataStream2 = new MemoryStream(await new WebClient().DownloadDataTaskAsync(Other.resizeLink(myresponse.url)));
            var    emim        = new DiscordEmbedBuilder
            {
                Description = $"[Full Source Image Link]({myresponse.url.ToString()})",
                ImageUrl    = $"attachment://image.{MimeGuesser.GuessExtension(dataStream2)}"
            };

            if (myresponse.creator.Length != 0)
            {
                emim.AddField("Creator", myresponse.creator);
            }
            emim.WithAuthor(name: "via api.meek.moe", url: "https://api.meek.moe/");
            emim.WithFooter("Requested by " + ctx.Message.Author.Username, ctx.Message.Author.AvatarUrl);
            await ctx.RespondWithFileAsync(fileName : $"image.{MimeGuesser.GuessExtension(dataStream2)}", fileData : dataStream2, embed : emim.Build());
        }
Exemple #3
0
        public static async Task <Derpy> GetDerpy(string url)
        {
            var          hc  = new HttpClient();
            var          dl  = JsonConvert.DeserializeObject <Derpy>(await hc.GetStringAsync(url));
            MemoryStream str = new(await hc.GetByteArrayAsync(Other.resizeLink(dl.url)))
            {
                Position = 0
            };

            dl.Data     = str;
            dl.Filetype = MimeGuesser.GuessExtension(str);
            var em = new DiscordEmbedBuilder();

            em.WithImageUrl($"attachment://image.{dl.Filetype}");
            em.WithFooter("by derpyenterprises.org");
            dl.Embed = em.Build();
            return(dl);
        }
Exemple #4
0
        public async Task DivaPic(CommandContext ctx)
        {
            var c   = new HttpClient();
            var res = JsonConvert.DeserializeObject <Entities.MeekMoe>(await c.GetStringAsync($"https://api.meek.moe/diva"));
            var img = new MemoryStream(await c.GetByteArrayAsync(Other.resizeLink(res.url)))
            {
                Position = 0
            };
            var emim = new DiscordEmbedBuilder
            {
                Description = $"[Full Source Image Link]({res.url})",
                ImageUrl    = $"attachment://image.{MimeGuesser.GuessExtension(img)}"
            };

            emim.WithAuthor(name: "via api.meek.moe", url: "https://api.meek.moe/");
            emim.WithFooter("Requested by " + ctx.Message.Author.Username, ctx.Message.Author.AvatarUrl);
            Console.WriteLine(MimeGuesser.GuessExtension(img));
            await ctx.RespondWithFileAsync(fileName : $"image.{MimeGuesser.GuessExtension(img)}", fileData : img, embed : emim.Build());
        }
Exemple #5
0
        public static async Task <WeebSh> GetWeebSh(CommandContext ctx, string query, string[] tags = null, NsfwSearch nsfw = NsfwSearch.False)
        {
            var weeurl = await Bot._weeb.GetRandomAsync(query, tags, nsfw : nsfw);

            var          hc  = new HttpClient();
            MemoryStream img = new MemoryStream(await hc.GetByteArrayAsync(weeurl.Url));

            img.Position = 0;
            var em = new DiscordEmbedBuilder();

            //em.WithDescription($"{ctx.Member.Mention} hugs {m.Mention} uwu");
            em.WithImageUrl($"attachment://image.{MimeGuesser.GuessExtension(img)}");
            em.WithFooter("by weeb.sh");
            //await ctx.RespondWithFileAsync(embed: em.Build(), fileData: img, fileName: $"image.{MimeGuesser.GuessExtension(img)}");
            return(new WeebSh {
                ImgData = img,
                Extension = MimeGuesser.GuessExtension(img),
                Embed = em
            });
        }
        private static bool PhotoValidate(string filePath)
        {
            var fileType = MimeGuesser.GuessFileType(filePath);

            if (fileType.MimeType.Equals("image/jpeg"))
            {
                return(true);
            }
            else
            {
                try
                {
                    File.Delete(filePath);
                    return(false);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
        }
        private void backgroundWorkerPopulate_DoWork(object sender, DoWorkEventArgs e)
        {
            addLVI        addListViewItemDelegate = AddListViewItem;
            setDetailText setDetailTextDelegate   = SetDetailText;

            /* Full path */
            var fullPath      = new ListViewItem("Location");
            var fullPathValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.ParentDirectoryPath
            };

            fullPath.SubItems.Add(fullPathValue);
            fullPath.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { fullPath });

            /* Windows extension */
            var windowsExtension      = new ListViewItem("Indicated Extension");
            var windowsExtensionValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.Extension.Name
            };

            windowsExtension.SubItems.Add(windowsExtensionValue);
            windowsExtension.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { windowsExtension });

            /* Detected extension */
            var detectedExtension      = new ListViewItem("Detected Extension");
            var detectedExtensionValue = new ListViewItem.ListViewSubItem
            {
                Text = MimeGuesser.GuessExtension(fileItem.AbsolutePath)
            };

            detectedExtension.SubItems.Add(detectedExtensionValue);
            detectedExtension.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { detectedExtension });

            /* MIME Type */
            var mimeType      = new ListViewItem("Detected MIME Type");
            var mimeTypeValue = new ListViewItem.ListViewSubItem
            {
                Text = MimeGuesser.GuessMimeType(fileItem.AbsolutePath)
            };

            mimeType.SubItems.Add(mimeTypeValue);
            mimeType.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { mimeType });

            /* MIME Details */
            var    builder = new StringBuilder();
            string details = detailMagic.Read(fileItem.AbsolutePath);

            details = details.Replace("- data", string.Empty);

            foreach (var component in details.Split(','))
            {
                if (!component.Equals("- data"))
                {
                    builder.AppendLine(component.Trim());
                }
            }

            BeginInvoke(setDetailTextDelegate, new object[] { builder.ToString() });

            /* Size */
            var size      = new ListViewItem("Size");
            var sizeValue = new ListViewItem.ListViewSubItem
            {
                Text = Utils.GetDynamicFileSize(fileItem.AbsolutePath)
            };

            size.SubItems.Add(sizeValue);
            size.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { size });

            /* Creation date + time */
            var creationDateTime      = new ListViewItem("Creation Date");
            var creationDateTimeValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.CreationTimeAsText
            };

            creationDateTime.SubItems.Add(creationDateTimeValue);
            creationDateTime.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { creationDateTime });

            /* Access date + time */
            var accessDateTime      = new ListViewItem("Last Access Date");
            var accessDateTimeValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.LastAccessTimeAsText
            };

            accessDateTime.SubItems.Add(accessDateTimeValue);
            accessDateTime.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { accessDateTime });

            /* Modify date + time */
            var modifiedDateTime      = new ListViewItem("Last Modification Date");
            var modifiedDateTimeValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.LastWriteTimeAsText
            };

            modifiedDateTime.SubItems.Add(modifiedDateTimeValue);
            modifiedDateTime.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { modifiedDateTime });

            /* Attributes */
            var attributes      = new ListViewItem("Windows Attributes");
            var attributesValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.AttributesAsText
            };

            attributes.SubItems.Add(attributesValue);
            attributes.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { attributes });

            /* Owner */
            var owner      = new ListViewItem("Owner");
            var ownerValue = new ListViewItem.ListViewSubItem
            {
                Text = fileItem.Owner
            };

            owner.SubItems.Add(ownerValue);
            owner.SubItems.Add("No");
            BeginInvoke(addListViewItemDelegate, new object[] { owner });
        }
Exemple #8
0
        public static string SaveFile(IFormFile file, FileConfig config, FileType fileType, long?length = null)
        {
            if (file.Length <= 0)
            {
                throw new Exception("there is no content in uploaded file.");
            }

            var date         = DateTime.Now;
            var relativePath = $"{fileType}/{date.Year}/{date.Month}/{date.Day}/";
            var folderPath   = Path.Combine(config.PhysicalAddress, relativePath);

            var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);

            Directory.CreateDirectory(folderPath);
            var filepath = Path.Combine(folderPath, fileName);

            var          stream       = file.OpenReadStream();
            MemoryStream memoryStream = new MemoryStream();

            stream.CopyTo(memoryStream);
            var fileByte = memoryStream.ToArray();
            var newBytes = fileByte;

            if (length.HasValue)
            {
                newBytes = ImageResizer.ResizeImage(fileByte, (int)length.Value);
            }

            System.IO.File.WriteAllBytes(filepath, newBytes);


            //Check Mime Type
            var allowedExtensions = new List <string>
            {
                "image/png",
                "image/tiff",
                "image/jpeg",
                "image/bmp",
                "image/gif",
            };

            if (fileType == FileType.file)
            {
                allowedExtensions.Add("application/msword");
                allowedExtensions.Add("audio/mpeg");
                allowedExtensions.Add("audio/x-wav");
                allowedExtensions.Add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                allowedExtensions.Add("application/vnd.ms-excel");
                allowedExtensions.Add("application/octet-stream");
                allowedExtensions.Add("multipart/x-zip");
                allowedExtensions.Add("application/x-rar");
                allowedExtensions.Add("application/zip");
                allowedExtensions.Add("application/x-rar-compressed");
                allowedExtensions.Add("application/x-zip-compressed");
                allowedExtensions.Add("application/pdf");
                allowedExtensions.Add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            }

            var mimeType = MimeGuesser.GuessMimeType(filepath);

            if (allowedExtensions.Contains(mimeType))
            {
                return(Path.Combine(relativePath, fileName));
            }


            try
            {
                File.Delete(filepath);
            }
            catch (IOException)
            {
            }

            throw new Exception("فایل مورد نظر غیر مجاز می‌باشد");
        }
        public async static Task MainAsync(string[] args)
        {
            //Welcome user
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Digital Ocean Spaces Manager");
            Console.ResetColor();

            #region Keys
            Console.Write("Enter DO Access Key: ");
            ConsoleKeyInfo key;
            KeyManager     keyManager = new KeyManager();
            do
            {
                key = Console.ReadKey(true);

                if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                {
                    keyManager.AccessKey.AppendChar(key.KeyChar);
                    Console.Write("*");
                }
                else
                {
                    if (key.Key == ConsoleKey.Backspace && keyManager.AccessKey.Length > 0)
                    {
                        keyManager.AccessKey.RemoveAt(keyManager.AccessKey.Length - 1);
                        Console.Write("\b \b");
                    }
                }
            } while (key.Key != ConsoleKey.Enter);
            Console.Write("\n");
            Console.Write("Enter DO Secrey Key: ");
            keyManager.SecretKey.Clear();
            do
            {
                key = Console.ReadKey(true);

                if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                {
                    keyManager.SecretKey.AppendChar(key.KeyChar);
                    Console.Write("*");
                }
                else
                {
                    if (key.Key == ConsoleKey.Backspace && keyManager.SecretKey.Length > 0)
                    {
                        keyManager.SecretKey.RemoveAt(keyManager.SecretKey.Length - 1);
                        Console.Write("\b \b");
                    }
                }
            } while (key.Key != ConsoleKey.Enter);
            Console.Write("\n");
            #endregion

            string filePath, uploadName, spaceName, contentType = string.Empty;
            Console.Write("Enter Space name to use: ");
            spaceName = "sms";
            //spaceName = Console.ReadLine();

            // Can now setup manager
            DigitalOceanUploadManager digitalOceanUploadManager = new DigitalOceanUploadManager(keyManager, spaceName);

            Console.WriteLine("Do you wish to upload or download a file? (U - upload, D - download): ");
            var upDown = Console.ReadLine();

            if (upDown == "U")
            {
                bool fileExists = false;
                do
                {
                    Console.Write("Enter file location: ");
                    filePath = Console.ReadLine();
                    if (File.Exists(filePath))
                    {
                        contentType = MimeGuesser.GuessFileType(filePath).MimeType;
                        fileExists  = true;
                    }
                    else
                    {
                        fileExists = false;
                        Console.WriteLine("File does not exist.  Please enter again.");
                    }
                } while (!fileExists);
                Console.Write("Enter name to use when uploaded: ");
                uploadName = Console.ReadLine();
                Console.Write("Wipe away previous attempts? (Y/n): ");
                var wipeAway = Console.ReadLine();
                if (wipeAway == "Y")
                {
                    await digitalOceanUploadManager.CleanUpPreviousAttempts();
                }

                digitalOceanUploadManager.UploadStatusEvent    += DigitalOceanUploadManager_UploadStatusEvent;
                digitalOceanUploadManager.UploadExceptionEvent += DigitalOceanUploadManager_UploadExceptionEvent;
                var uploadId = await digitalOceanUploadManager.UploadFile(filePath, uploadName);

                Console.WriteLine("File upload complete");
                digitalOceanUploadManager.UploadStatusEvent    -= DigitalOceanUploadManager_UploadStatusEvent;
                digitalOceanUploadManager.UploadExceptionEvent -= DigitalOceanUploadManager_UploadExceptionEvent;
            }
            else if (upDown == "D")
            {
                Console.Write("Enter name used to upload file: ");
                var uploadFileName = Console.ReadLine();
                Console.Write("Enter location to save file: ");
                var downloadLocation = Console.ReadLine();
                var file             = await digitalOceanUploadManager.DownloadFile(uploadFileName);

                using (var fs = File.Create(downloadLocation))
                {
                    fs.Write(file, 0, file.Length);
                }
                Console.WriteLine($"File downloaded to {downloadLocation} ({file.Length})");
            }
            else if (upDown == "L") // List Files
            {
                var files = await digitalOceanUploadManager.ListFiles();

                foreach (var file in files)
                {
                    Console.WriteLine($"{file}");
                }
            }
            else if (upDown == "DA") // Download All
            {
                var files = await digitalOceanUploadManager.ListFiles();

                Console.Write("Enter location to save file: ");
                var downloadLocation = Console.ReadLine();
                var i = 0;
                foreach (var uploadFileName in files)
                {
                    i++;
                    if (uploadFileName.EndsWith('/'))
                    {
                        var dir = Path.GetDirectoryName(uploadFileName);
                        Directory.CreateDirectory(Path.Combine(downloadLocation, dir));
                        continue;
                    }
                    var file = await digitalOceanUploadManager.DownloadFile(uploadFileName);

                    var fullFilePath = Path.Combine(downloadLocation, uploadFileName);
                    using (var fs = File.Create(fullFilePath))
                    {
                        fs.Write(file, 0, file.Length);
                    }
                    Console.WriteLine($"{i} File downloaded to {fullFilePath} ({file.Length})");
                }
            }
            else
            {
                Console.WriteLine("No idea what you want.  Try again");
            }

            digitalOceanUploadManager?.Dispose();
            digitalOceanUploadManager = null;

            keyManager?.Dispose();
            keyManager = null;

            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
Exemple #10
0
 private string GetMimeType(string filePath)
 {
     return(MimeGuesser.GuessMimeType(filePath));
 }
Exemple #11
0
        public static string GetContentType(string filePath)
        {
            var absolutePath = Path.Combine(Directory.GetCurrentDirectory(), filePath);

            return(MimeGuesser.GuessMimeType(absolutePath));
        }
Exemple #12
0
        public async Task Cat(CommandContext ctx)
        {
            var ImgURL = await Web.GetNekos_Life("https://nekos.life/api/v2/img/neko");

            Stream img = new MemoryStream(await new WebClient().DownloadDataTaskAsync(Other.resizeLink(ImgURL.Url)));
            var    em  = new DiscordEmbedBuilder();

            em.WithImageUrl($"attachment://image.{MimeGuesser.GuessExtension(img)}");
            em.WithFooter("by nekos.life");
            await ctx.RespondWithFileAsync(embed : em.Build(), fileData : img, fileName : $"image.{MimeGuesser.GuessExtension(img)}");
        }
Exemple #13
0
        public bool IsImage(byte[] content)
        {
            var mimeType = MimeGuesser.GuessMimeType(content);

            return(mimeType.StartsWith("image"));
        }
 public BasicProperties(string FiletoScan, ref XMLParser raport)
 {
     try
     {
         var peHeader = new PeNet.PeFile(FiletoScan);
         raport.AddBasicProperties(peHeader.MD5, peHeader.SHA1, AuthentihashCheckSum(FiletoScan), peHeader.ImpHash, MimeGuesser.GuessFileType(FiletoScan).MimeType, peHeader.FileSize.ToString());
     }
     catch (Exception)
     {
         raport.AddBasicProperties(MD5CheckSum(FiletoScan), SHA1CheckSum(FiletoScan), AuthentihashCheckSum(FiletoScan), "", MimeGuesser.GuessFileType(FiletoScan).MimeType, "");
     }
 }
Exemple #15
0
 public string GetMimeType(byte[] content)
 {
     return(MimeGuesser.GuessMimeType(content));
 }
Exemple #16
0
        public static string SaveFile(IFormFile file, FileConfig config, DomainModels.SSOT.FileType type, string relativePath)
        {
            if (file.Length <= 0)
            {
                throw new Exception("there is no content in uploaded file.");
            }

            var date = DateTime.Now;
            //var relativePath = $"{type}/{date.Year}/{date.Month}/{date.Day}";
            var folderPath = Path.Combine(relativePath, "UploadFiles");

            var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);

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

            var filepath = Path.Combine(folderPath, fileName);

            using (var fileStream = new FileStream(filepath, FileMode.Create))
            {
                file.CopyTo(fileStream);
            }

            //Check Mime Type
            var allowedExtensions = new List <string>
            {
                "image/png",
                "image/tiff",
                "image/jpeg",
                "image/bmp",
                "image/gif",
            };

            if (type == DomainModels.SSOT.FileType.file)
            {
                allowedExtensions.Add("application/msword");
                allowedExtensions.Add("application/zip");
                allowedExtensions.Add("application/x-rar-compressed");
                allowedExtensions.Add("application/pdf");
                allowedExtensions.Add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            }

            var mimeType = MimeGuesser.GuessMimeType(filepath);

            if (allowedExtensions.Contains(mimeType))
            {
                return(fileName);
            }


            try
            {
                File.Delete(filepath);
            }
            catch (IOException)
            {
            }

            throw new Exception("فایل مورد نظر غیر مجاز می‌باشد");
        }
Exemple #17
0
        public JsonResult UploadImageLinks()
        {
            //TODO better response ?
            var responseForEachFile  = new List <ResponseModel <string> >();
            var monitorId            = int.Parse(Request.Form.GetValues("monitorId")[0]);
            var uploadImageLinksData = Request.Form.GetValues("uploadImageLink")[0];
            var uploadImageLinks     = uploadImageLinksData.Split(new string[] { "uploadImageLink=" }, StringSplitOptions.RemoveEmptyEntries);

            var monitor = service.GetMonitorVm(monitorId);

            //use webclient to download files from links
            var wc = new WebClient();

            foreach (var link in uploadImageLinks)
            {
                var monitorUploadPath = Settings.ImagesServerUploadPath + "Monitor\\";
                var response          = new ResponseModel <string>();
                //check if url is valid
                if (Uri.IsWellFormedUriString(link, UriKind.RelativeOrAbsolute))
                {
                    //download
                    var currentFile = wc.DownloadData(link);
                    //validation null or empty
                    if (currentFile != null && currentFile.Length > 0)
                    {
                        //guess type
                        MimeGuesser.MagicFilePath = HttpRuntime.BinDirectory + "\\magic.mgc";
                        var fileType = MimeGuesser.GuessMimeType(currentFile);
                        //validation is image ?
                        if (fileType == "image/jpeg" || fileType == "image/png")
                        {
                            //validation size
                            if (currentFile.Length < (7 * 1024 * 1024))
                            {
                                response.IsSuccess = true;
                                //createfile name
                                var fileName = Guid.NewGuid().ToString() + ".jpg";

                                //for local development it's better to use relative paths,
                                //so we are going to use ..\images\monitor instead of C:\ala\...\...\...\bala\images\monitor
                                //If the path contains C:\******* it means it's rooted, and we use the raw value from the settings.
                                //if it contaisn only "..\images\" it will not be rooted and we need to map the IIS directory to rooted path directory
                                string uploadDir = "";
                                if (Path.IsPathRooted(monitorUploadPath))
                                {
                                    uploadDir = Path.Combine(monitorUploadPath, monitor.BrandName, monitor.Model);
                                }
                                else
                                {
                                    uploadDir = Path.Combine(HttpContext.Server.MapPath("~"), monitorUploadPath, monitor.BrandName, monitor.Model);
                                }

                                Directory.CreateDirectory(uploadDir);
                                var imageUrlPath = $@"/{monitor.BrandName}/{monitor.Model}/{fileName}";
                                var uploadPath   = Path.Combine(uploadDir, fileName);

                                //save to hdd
                                using (Image image = Image.FromStream(new MemoryStream(currentFile)))
                                {
                                    image.Save(uploadPath, ImageFormat.Jpeg);
                                }
                                //save to db
                                service.SaveImageToDb(monitorId, imageUrlPath);
                            }
                            else
                            {
                                response.Errors.Add("Image cannot be larger than 7mb");
                            }
                        }
                        else
                        {
                            response.Errors.Add("You can only upload image files(jpeg/png)");
                        }
                    }
                    else
                    {
                        response.Errors.Add("File is null or empty");
                    }
                }
                else
                {
                    response.Errors.Add("Bad Url");
                }
                responseForEachFile.Add(response);
            }
            return(new JsonResult()
            {
                Data = responseForEachFile
            });
        }
        public async static Task MainAsync(string[] args)
        {
            //Welcome user
            Console.BackgroundColor = ConsoleColor.Blue;
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Digital Ocean Spaces Manager");
            Console.ResetColor();

            #region Keys
            Console.Write("Enter DO Access Key: ");
            ConsoleKeyInfo key;
            KeyManager.ACCESS_KEY.Clear();
            do
            {
                key = Console.ReadKey(true);

                if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                {
                    KeyManager.ACCESS_KEY.AppendChar(key.KeyChar);
                    Console.Write("*");
                }
                else
                {
                    if (key.Key == ConsoleKey.Backspace && KeyManager.ACCESS_KEY.Length > 0)
                    {
                        KeyManager.ACCESS_KEY.RemoveAt(KeyManager.ACCESS_KEY.Length - 1);
                        Console.Write("\b \b");
                    }
                }
            } while (key.Key != ConsoleKey.Enter);
            Console.Write("\n");
            Console.Write("Enter DO Secrey Key: ");
            KeyManager.SECRET_KEY.Clear();
            do
            {
                key = Console.ReadKey(true);

                if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                {
                    KeyManager.SECRET_KEY.AppendChar(key.KeyChar);
                    Console.Write("*");
                }
                else
                {
                    if (key.Key == ConsoleKey.Backspace && KeyManager.ACCESS_KEY.Length > 0)
                    {
                        KeyManager.ACCESS_KEY.RemoveAt(KeyManager.ACCESS_KEY.Length - 1);
                        Console.Write("\b \b");
                    }
                }
            } while (key.Key != ConsoleKey.Enter);
            Console.Write("\n");
            #endregion

            var client = new AmazonS3Client(KeyManager.SecureStringToString(KeyManager.ACCESS_KEY), KeyManager.SecureStringToString(KeyManager.SECRET_KEY), new AmazonS3Config()
            {
                ServiceURL = "https://nyc3.digitaloceanspaces.com"
            });
            client.ExceptionEvent += Client_ExceptionEvent;

            string filePath, uploadName, spaceName, contentType = string.Empty;
            Console.Write("Enter Space name to use: ");
            spaceName = Console.ReadLine();
            bool fileExists = false;
            do
            {
                Console.Write("Enter file location: ");
                filePath = Console.ReadLine();
                if (File.Exists(filePath))
                {
                    contentType = MimeGuesser.GuessFileType(filePath).MimeType;
                    fileExists  = true;
                }
                else
                {
                    fileExists = false;
                    Console.WriteLine("File does not exist.  Please enter again.");
                }
            } while (!fileExists);
            Console.Write("Enter name to use when uploaded: ");
            uploadName = Console.ReadLine();
            Console.Write("Wipe away previous attempts? (Y/n): ");
            var wipeAway = Console.ReadLine();
            if (wipeAway == "Y")
            {
                var currentMultiParts = await client.ListMultipartUploadsAsync(spaceName);

                foreach (var multiPart in currentMultiParts.MultipartUploads)
                {
                    try
                    {
                        await client.AbortMultipartUploadAsync(currentMultiParts.BucketName, multiPart.Key, multiPart.UploadId);
                    }
                    catch (Exception) { }
                }

                Console.WriteLine("Wiped away previous upload attempts");
            }

            var fileInfo = new FileInfo(filePath);

            var multiPartStart = await client.InitiateMultipartUploadAsync(new Amazon.S3.Model.InitiateMultipartUploadRequest()
            {
                BucketName  = spaceName,
                ContentType = contentType,
                Key         = uploadName
            });

            try
            {
                var i = 0L;
                var n = 1;
                Dictionary <string, int> parts = new Dictionary <string, int>();
                while (i < fileInfo.Length)
                {
                    Console.WriteLine($"Starting upload for Part #{n}");
                    long partSize = 6000000;
                    var  lastPart = (i + partSize) >= fileInfo.Length;
                    if (lastPart)
                    {
                        partSize = fileInfo.Length - i;
                    }
                    bool complete = false;
                    int  retry    = 0;
                    Amazon.S3.Model.UploadPartResponse partResp = null;
                    do
                    {
                        retry++;
                        try
                        {
                            partResp = await client.UploadPartAsync(new Amazon.S3.Model.UploadPartRequest()
                            {
                                BucketName   = spaceName,
                                FilePath     = filePath,
                                FilePosition = i,
                                IsLastPart   = lastPart,
                                PartSize     = partSize,
                                PartNumber   = n,
                                UploadId     = multiPartStart.UploadId,
                                Key          = uploadName
                            });

                            complete = true;
                        }
                        catch (Exception)
                        {
                            Console.WriteLine($"Failed to upload part {n} on try #{retry}...");
                        }
                    } while (!complete && retry <= 3);

                    if (!complete || partResp == null)
                    {
                        throw new Exception($"Unable to upload part {n}... Failing");
                    }

                    parts.Add(partResp.ETag, n);
                    i += partSize;
                    n++;
                    Console.WriteLine($"Uploading {(((float)i/(float)fileInfo.Length) * 100).ToString("N2")} ({i}/{fileInfo.Length})");
                }

                Console.WriteLine("Done uploading!  Completing upload");
                var completePart = await client.CompleteMultipartUploadAsync(new Amazon.S3.Model.CompleteMultipartUploadRequest()
                {
                    UploadId   = multiPartStart.UploadId,
                    BucketName = spaceName,
                    Key        = uploadName,
                    PartETags  = parts.Select(p => new Amazon.S3.Model.PartETag(p.Value, p.Key)).ToList()
                });

                Console.WriteLine("Successfully uploaded!");
            }
            catch (Exception ex)
            {
                var abortPart = await client.AbortMultipartUploadAsync(spaceName, uploadName, multiPartStart.UploadId);

                Console.WriteLine("Error while uploading! " + ex.Message);
                await Task.Delay(10000);
            }
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
Exemple #19
0
        /// <summary>
        /// Uploads the file.
        /// </summary>
        /// <returns>The upload id.</returns>
        /// <param name="filePath">File path.</param>
        /// <param name="uploadName">Upload name.</param>
        /// <param name="maxPartRetry">Max part retry.</param>
        public async Task <string> UploadFile(string filePath, string uploadName, int maxPartRetry = 3, long maxPartSize = 6000000L)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException(nameof(filePath));
            }
            if (string.IsNullOrWhiteSpace(uploadName))
            {
                throw new ArgumentNullException(nameof(uploadName));
            }
            if (maxPartRetry < 1)
            {
                throw new ArgumentException("Max Part Retry needs to be greater than or equal to 1", nameof(maxPartRetry));
            }
            if (maxPartSize < 1)
            {
                throw new ArgumentException("Max Part Size needs to be greater than 0", nameof(maxPartSize));
            }

            var fileInfo    = new FileInfo(filePath);
            var contentType = MimeGuesser.GuessFileType(filePath).MimeType;

            Amazon.S3.Model.InitiateMultipartUploadResponse multiPartStart;

            using (var client = CreateNewClient())
            {
                multiPartStart = await client.InitiateMultipartUploadAsync(new Amazon.S3.Model.InitiateMultipartUploadRequest()
                {
                    BucketName  = _spaceName,
                    ContentType = contentType,
                    Key         = uploadName
                });

                var estimatedParts = (int)(fileInfo.Length / maxPartSize);
                if (estimatedParts == 0)
                {
                    estimatedParts = 1;
                }

                UploadStatusEvent?.Invoke(this, new UploadStatus(0, estimatedParts, 0, fileInfo.Length));

                try
                {
                    var i = 0L;
                    var n = 1;
                    Dictionary <string, int> parts = new Dictionary <string, int>();
                    while (i < fileInfo.Length)
                    {
                        long partSize = maxPartSize;
                        var  lastPart = (i + partSize) >= fileInfo.Length;
                        if (lastPart)
                        {
                            partSize = fileInfo.Length - i;
                        }
                        bool complete = false;
                        int  retry    = 0;
                        Amazon.S3.Model.UploadPartResponse partResp = null;
                        do
                        {
                            retry++;
                            try
                            {
                                partResp = await client.UploadPartAsync(new Amazon.S3.Model.UploadPartRequest()
                                {
                                    BucketName   = _spaceName,
                                    FilePath     = filePath,
                                    FilePosition = i,
                                    IsLastPart   = lastPart,
                                    PartSize     = partSize,
                                    PartNumber   = n,
                                    UploadId     = multiPartStart.UploadId,
                                    Key          = uploadName
                                });

                                complete = true;
                            }
                            catch (Exception ex)
                            {
                                UploadExceptionEvent?.Invoke(this, new UploadException($"Failed to upload part {n} on try #{retry}", ex));
                            }
                        } while (!complete && retry <= maxPartRetry);

                        if (!complete || partResp == null)
                        {
                            throw new Exception($"Unable to upload part {n}");
                        }

                        parts.Add(partResp.ETag, n);
                        i += partSize;
                        UploadStatusEvent?.Invoke(this, new UploadStatus(n, estimatedParts, i, fileInfo.Length));
                        n++;
                    }

                    // upload complete
                    var completePart = await client.CompleteMultipartUploadAsync(new Amazon.S3.Model.CompleteMultipartUploadRequest()
                    {
                        UploadId   = multiPartStart.UploadId,
                        BucketName = _spaceName,
                        Key        = uploadName,
                        PartETags  = parts.Select(p => new Amazon.S3.Model.PartETag(p.Value, p.Key)).ToList()
                    });
                }
                catch (Exception ex)
                {
                    var abortPart = await client.AbortMultipartUploadAsync(_spaceName, uploadName, multiPartStart.UploadId);

                    UploadExceptionEvent?.Invoke(this, new UploadException("Something went wrong upload file and it was aborted", ex));
                }
            }

            return(multiPartStart?.UploadId);
        }
Exemple #20
0
        public async Task Poke(CommandContext ctx, DiscordMember m)
        {
            var c      = new HttpClient();
            var weeurl = await Bot._weeb.GetRandomAsync("poke", new[] { "" });

            Stream img = new MemoryStream(await c.GetByteArrayAsync(Other.resizeLink(weeurl.Url)));
            var    em  = new DiscordEmbedBuilder();

            em.WithDescription($"{ctx.Member.Mention} pokes {m.Mention} ÓwÒ");
            em.WithImageUrl($"attachment://image.{MimeGuesser.GuessExtension(img)}");
            em.WithFooter("by nekos.life");
            await ctx.RespondWithFileAsync(embed : em.Build(), fileData : img, fileName : $"image.{MimeGuesser.GuessExtension(img)}");
        }