public static void AddVideoOutput(this WebDocument document, string outputPath, Presentation pres)
        {
            List <VideoFrame> videoFrames = ShapeHelper.GetListOfShapes <VideoFrame>(pres);

            for (int i = 0; i < videoFrames.Count; i++)
            {
                IVideo video = videoFrames[i].EmbeddedVideo;
                string ext   = MimeTypesMap.GetExtension(videoFrames[i].EmbeddedVideo.ContentType);
                string path  = Path.Combine(outputPath, string.Format("video{0}.{1}", i, ext));

                var outputFile = document.Output.Add(path, video);
                document.Output.BindResource(outputFile, video);
            }
        }
Ejemplo n.º 2
0
        public static string GetMimeType(this string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName) || !Path.HasExtension(fileName))
            {
                return(null);
            }

            switch (Path.GetExtension(fileName).ToLower())
            {
            case ".ogg": return("video/ogg");
            }

            return(MimeTypesMap.GetMimeType(fileName));
        }
Ejemplo n.º 3
0
        public override async Task Create()
        {
            this.FileName = Path.GetFileName(this.FilePath);
            this.FileSize = new FileInfo(this.FilePath).Length;
            this.MimeType = MimeTypesMap.GetMimeType(this.FileName);

            await base.Create();

            // Create multipart form including setting form data and file content
            MultipartFormDataContent form = await this.CreateMultipartForm();

            // Upload to S3
            await this.PostS3Request(form);
        }
Ejemplo n.º 4
0
        public async Task <string> saveArtwork(TagLib.Tag tag, int id)
        {
            IPicture   picture = tag.Pictures[0];
            ByteVector vector  = picture.Data;

            Byte[] bytes     = vector.ToArray();
            string extension = MimeTypesMap.GetExtension(picture.MimeType);

            System.IO.Directory.CreateDirectory(System.IO.Path.Combine(App.LocalStoragePath, "AlbumArt"));
            var filename = System.IO.Path.Combine(App.LocalStoragePath, "AlbumArt", id.ToString() + "." + extension);

            System.IO.File.WriteAllBytes(filename, bytes);
            return(id.ToString() + "." + extension);
        }
Ejemplo n.º 5
0
        public ICloudFileMetadata UploadStream(Stream source, string targetPath, string contentType = "application/octet-stream", string bucketName = "")
        {
            EnsureBucketExist(bucketName);

            //bool fileNameExistInTargetFolder = Path.GetExtension(targetPath) != string.Empty;
            //if (!fileNameExistInTargetFolder)
            //{
            //	throw new ArgumentException($"'{nameof(targetPath)}' does not have a valid file extension");
            //}

            string destinationPath = Path.Combine(_options.Path
                                                  , _bucketName
                                                  , targetPath);

            //var progress = new Progress<IUploadProgress>(p => _logger.LogTrace($"destination gs://{{bucket}}/{{destinationFileName}}, bytes: {p.BytesSent}, status: {p.Status}", _bucketName, destinationFileName));

            source.Seek(0, SeekOrigin.Begin);

            try
            {
                if (!Directory.Exists(RootPath))
                {
                    throw new DirectoryNotFoundException($"{RootPath} does not exists.");
                }
                Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
                using (FileStream fileStream = File.Create(destinationPath))
                {
                    source.CopyTo(fileStream);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                throw;
            }

            var fileInfo = new FileInfo(destinationPath);
            var output   = new CloudFileMetadata
            {
                Bucket         = _bucketName
                , Size         = (ulong)fileInfo.Length
                , Name         = GetFileName(fileInfo.FullName)
                , LastModified = fileInfo.LastWriteTimeUtc
                , ContentType  = MimeTypesMap.GetMimeType(fileInfo.Name)
            };

            return(output);
        }
Ejemplo n.º 6
0
        public static string GetMimeType(string filename)
        {
            if (string.IsNullOrWhiteSpace(filename))
            {
                throw new Exception("empty filename");
            }

            string extension = filename.Split('.')[1];

            if (string.IsNullOrEmpty(extension))
            {
                throw new Exception("no extension found");
            }

            return(MimeTypesMap.GetMimeType(extension));
        }
Ejemplo n.º 7
0
        public static string GetFileName(Image image)
        {
            if (image.Id < 0)
            {
                throw new Exception("invalid Id");
            }

            if (string.IsNullOrEmpty(image.MimeType))
            {
                throw new Exception("invalid file mime type");
            }

            string extension = MimeTypesMap.GetExtension(image.MimeType);

            return(image.Id + "." + extension);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Convenience method that creates an attachment from a stream.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="fileName">The name of the attachment.</param>
        /// <param name="mimeType">Optional: MIME type of the attachment. If this parameter is null, the MIME type will be derived from the fileName extension.</param>
        /// <param name="contentId">Optional: the unique identifier for this attachment IF AND ONLY IF the attachment should be embedded in the body of the email. This is useful, for example, if you want to embbed an image to be displayed in the HTML content. For standard attachment, this value should be null.</param>
        /// <returns>The attachment</returns>
        public static Attachment FromBinary(byte[] content, string fileName, string mimeType = null, string contentId = null)
        {
            if (string.IsNullOrEmpty(mimeType))
            {
                mimeType = MimeTypesMap.GetMimeType(fileName);
            }

            return(new Attachment()
            {
                Content = Convert.ToBase64String(content),
                ContentId = contentId,
                Disposition = string.IsNullOrEmpty(contentId) ? "attachment" : "inline",
                FileName = fileName,
                Type = mimeType
            });
        }
Ejemplo n.º 9
0
        public async Task <FileAttachment> PostFileAsync(string filePath, string fileName, string url)
        {
            var client = new RestClient($"{BaseUrl}/{url}");

            client.Timeout = -1;
            var request = new RestRequest(Method.POST);

            request.AddHeader("Accept", "application/json, text/json");
            request.AddHeader("Content-Type", "multipart/form-data");
            request.AddHeader("Authorization", $"Basic {Utils.EncodeBase64(apiKey)}");
            request.AddFile("file", filePath);
            request.AddParameter("file_name", fileName);
            request.AddParameter("content_type", MimeTypesMap.GetMimeType(fileName));
            IRestResponse response = await client.ExecuteAsync(request);

            return(Serializer.FromJson <FileAttachment>(response.Content));
        }
Ejemplo n.º 10
0
        public void ReturnFileName_GivenValidImage()
        {
            // Arrange
            string JPEG  = "jpeg";
            Image  image = new Image()
            {
                Id       = 1,
                MimeType = MimeTypesMap.GetMimeType(JPEG)
            };
            string expected = image.Id + "." + JPEG;

            // Act
            string result = Common.GetFileName(image);

            // Assert
            Assert.Equal(expected, result);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Convenience method that creates an attachment from a local file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <param name="mimeType">Optional: MIME type of the attachment. If this parameter is null, the MIME type will be derived from the file extension.</param>
        /// <param name="contentId">Optional: the unique identifier for this attachment IF AND ONLY IF the attachment should be embedded in the body of the email. This is useful, for example, if you want to embbed an image to be displayed in the HTML content. For standard attachment, this value should be null.</param>
        /// <returns>The attachment.</returns>
        /// <exception cref="System.IO.FileNotFoundException">Unable to find the local file.</exception>
        public static Attachment FromLocalFile(string filePath, string mimeType = null, string contentId = null)
        {
            var fileInfo = new FileInfo(filePath);

            if (!fileInfo.Exists)
            {
                throw new FileNotFoundException("Unable to find the local file", filePath);
            }

            if (string.IsNullOrEmpty(mimeType))
            {
                mimeType = MimeTypesMap.GetMimeType(filePath);
            }

            var content = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

            return(new Attachment(content, fileInfo.Name, mimeType, contentId));
        }
Ejemplo n.º 12
0
        public static TagLib.Image.File Parse(Uri uri)
        {
            // Detect mime-type
            string mime = MimeTypesMap.GetMimeType(Path.GetFileName(uri.AbsolutePath));

            if (mime.StartsWith("application/x-extension-"))
            {
                // Works around broken metadata detection - https://bugzilla.gnome.org/show_bug.cgi?id=624781
                mime = $"taglib/{mime.Substring (24)}";
            }

            // Parse file
            var res = new TagLibFileAbstraction {
                Uri = uri
            };
            var sidecar_uri = GetSidecarUri(uri);
            var sidecar_res = new TagLibFileAbstraction {
                Uri = sidecar_uri
            };

            TagLibFile file = null;

            try {
                file = TagLib.File.Create(res, mime, ReadStyle.Average) as TagLibFile;
            } catch (Exception) {
                //Log.Debug ($"Loading of metadata failed for file: {uri}, trying extension fallback");

                try {
                    file = TagLib.File.Create(res, ReadStyle.Average) as TagLibFile;
                } catch (Exception e) {
                    //Log.Debug ($"Loading of metadata failed for file: {uri}");
                    // Log.DebugException (e);
                    return(null);
                }
            }

            // Load XMP sidecar
            if (System.IO.File.Exists(sidecar_uri.AbsolutePath))
            {
                file.ParseXmpSidecar(sidecar_res);
            }

            return(file);
        }
Ejemplo n.º 13
0
        public ICloudFileMetadata UploadFile(string sourcePath, string targetPath, string bucketName = "") //, bool addTimeStampToFileName)
        {
            string contentType = null;

            try
            {
                contentType = MimeTypesMap.GetMimeType(sourcePath);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "There is an error occured while trying to retrieve MimeType");
            }
            using (FileStream fileStream = File.OpenRead(sourcePath))
            {
                return(string.IsNullOrWhiteSpace(contentType)
                           ? UploadStream(fileStream, targetPath, bucketName: bucketName)
                           : UploadStream(fileStream, targetPath, contentType, bucketName));
            }
        }
Ejemplo n.º 14
0
        public object SaveDiagramToFile([FromQuery] string fileName)
        {
            byte[] diagram = Convert.FromBase64String(StaticData.DataDiagram);

            string filePath = Path.ChangeExtension(fileName + " отчет с диаграммой", ".docx");

            System.IO.File.Copy("TemplatesReportsWord/DiagramReportTemplate.docx", filePath);

            using (FileStream fstream = System.IO.File.Open(filePath, FileMode.Open))
            {
                List <IContentItem> fieldContents = new List <IContentItem>();
                TableContent        tableContent;
                List <FieldContent> rows = new List <FieldContent>();

                tableContent = TableContent.Create("systemMembers");
                foreach (var calculation in StaticData.DiagramCalculation.calculations)
                {
                    rows.Clear();
                    rows.Add(new FieldContent("nameSystem", calculation.nameSystem));
                    rows.Add(new FieldContent("parameterValue", calculation.value.ToString()));
                    tableContent.AddRow(rows.ToArray());
                }
                fieldContents.Add(tableContent);
                fieldContents.Add(new FieldContent("nameParameter", StaticData.DiagramCalculation.parameterName));

                fieldContents.Add(new ImageContent("diagram", diagram));
                using (var outputDocument = new TemplateProcessor(fstream).SetRemoveContentControls(true))
                {
                    outputDocument.FillContent(new Content(fieldContents.ToArray()));
                    outputDocument.SaveChanges();
                }
            }
            var memory = new MemoryStream();

            using (var stream = new FileStream(filePath, FileMode.Open))
            {
                stream.CopyTo(memory);
            }
            System.IO.File.Delete(filePath);

            memory.Position = 0;
            return(File(memory, MimeTypesMap.GetMimeType(filePath), filePath));
        }
Ejemplo n.º 15
0
        public List <ICloudFileMetadata> GetFileList(string prefix = null, string bucketName = "")
        {
            EnsureBucketExist(bucketName);
            var output = new List <ICloudFileMetadata>();

            try
            {
                var files = Directory.GetFiles(RootPath
                                               , Constants.WildCardStar
                                               , SearchOption.AllDirectories)
                            .ToList();
                if (!string.IsNullOrWhiteSpace(prefix))
                {
                    string modifiedPrefix = Path.Combine(RootPath
                                                         , prefix?.Replace(Path.AltDirectorySeparatorChar
                                                                           , Path.DirectorySeparatorChar));
                    files = files.Where(f => f.StartsWith(modifiedPrefix))
                            .ToList();
                }

                foreach (string file in files)
                {
                    var fileInfo = new FileInfo(file);
                    output.Add(new CloudFileMetadata
                    {
                        Bucket         = _bucketName
                        , Size         = (ulong)fileInfo.Length
                        , Name         = GetFileName(fileInfo.FullName)
                        , LastModified = fileInfo.LastWriteTimeUtc
                        , ContentType  = MimeTypesMap.GetMimeType(fileInfo.Name)
                        , SignedUrl    = fileInfo.FullName
                    });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e
                                 , e.Message);
                throw;
            }

            return(output);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Convenience method that creates an attachment from a stream.
        /// </summary>
        /// <param name="contentStream">The stream.</param>
        /// <param name="fileName">The name of the attachment.</param>
        /// <param name="mimeType">Optional: MIME type of the attachment. If this parameter is null, the MIME type will be derived from the fileName extension.</param>
        /// <param name="contentId">Optional: the unique identifier for this attachment IF AND ONLY IF the attachment should be embedded in the body of the email. This is useful, for example, if you want to embbed an image to be displayed in the HTML content. For standard attachment, this value should be null.</param>
        /// <returns>The attachment</returns>
        public AttachmentBase CreateAttachmentFromStream(Stream contentStream, string fileName, string mimeType = null, string contentId = null)
        {
            if (string.IsNullOrEmpty(mimeType))
            {
                mimeType = MimeTypesMap.GetMimeType(fileName);
            }

            if (string.IsNullOrEmpty(contentId))
            {
                return(new Attachment(contentStream, Path.GetFileName(fileName), mimeType));
            }
            else
            {
                var linkedResource = new LinkedResource(contentStream, mimeType);
                linkedResource.ContentId        = contentId;
                linkedResource.ContentType.Name = Path.GetFileName(fileName);
                linkedResource.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
                return(linkedResource);
            }
        }
Ejemplo n.º 17
0
        public FileAttachment(string url, object meta = null, string caption = null, string fileName        = null,
                              long?fileSize           = 0, string mimeType   = null, string defaultMimeType = null) : base(url, meta)
        {
            Caption = caption;

            if (string.IsNullOrEmpty(mimeType))
            {
                FileName = string.IsNullOrEmpty(fileName)
                    ? _getFilename(url, defaultMimeType: defaultMimeType)
                    : fileName;
                MimeType = MimeTypesMap.GetMimeType(FileName);
            }
            else
            {
                MimeType = mimeType;
                FileName = string.IsNullOrEmpty(fileName) ? _getFilename(url, mimeType) : fileName;
            }

            FileSize = fileSize;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Downloads the highest bitrate file specified in a Media IEnumerable to a file specified by the title.
        /// File Extension is determined by the MimeType and should be guaranteed to be compatible as a result
        /// </summary>
        /// <param name="source">IEnumerable of Media Definitions retrieved from BiliBili page</param>
        /// <param name="title">The title of the video</param>
        /// <returns>A task representing the return of the absolute path of the downloaded file</returns>
        private static async Task <string> DownloadBest(IEnumerable <Media> source, string title)
        {
            //Grab highest bitrate source
            Console.WriteLine("Finding best media...");
            Media bestMedia = source.OrderByDescending(a => a.Bandwidth).First();

            Console.WriteLine("Url: " + bestMedia.BaseUrl);
            Console.WriteLine("MimeType: " + bestMedia.MimeType);

            //Find a free place to put the file
            FileInfo targetFile = FindFreeFile(DownloadPath, $"{title}.{MimeTypesMap.GetExtension(bestMedia.MimeType)}");

            Console.WriteLine("Downloading media...");

            await SafeDownload(bestMedia.BaseUrl, targetFile);

            Console.WriteLine($"{bestMedia.MimeType} downloaded to: " + targetFile.FullName);

            return(targetFile.FullName);
        }
Ejemplo n.º 19
0
        private static void download_file3(string course, ChromeDriver driver, string path, IWebElement element)
        {
            string outline = element.GetAttribute("href");

            using (WebClient client = new WebClient())
            {
                client.Headers[HttpRequestHeader.Cookie] = cookieString(driver);
                var    data      = client.DownloadData(outline);
                var    extension = MimeTypesMap.GetExtension(client.ResponseHeaders["Content-Type"]);
                string fileName  = GetSafeFilename(element.Text);

                System.IO.Directory.CreateDirectory(path);
                string file_name = path + "\\" + System.IO.Path.GetFileNameWithoutExtension(fileName) + "." + extension;
                if (file_name.Length > 259)
                {
                    Console.WriteLine("Warning: Course:" + course + " file:" + fileName + ". Please download manually");
                    return;
                }
                File.WriteAllBytes(file_name, data);
            }
        }
        private async Task <FilesResource.CreateMediaUpload> Upload(string fileName, Google.Apis.Drive.v3.Data.File fileMetadata, Stream stream, bool isShared)
        {
            var mimeType = MimeTypesMap.GetMimeType($"{fileName}.json");

            var fileRequest = _driveService.Files.Create(fileMetadata, stream, mimeType);

            fileRequest.Fields = "*";
            var result = await fileRequest.UploadAsync();

            if (result.Status != UploadStatus.Completed)
            {
                throw new Exception("Error while uploading json file!");
            }

            if (isShared)
            {
                await SetPermissions(fileRequest.ResponseBody.Id);
            }

            return(fileRequest);
        }
        /// <summary>
        /// Convenience method that creates an attachment from a stream.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="fileName">The name of the attachment.</param>
        /// <param name="mimeType">Optional: MIME type of the attachment. If this parameter is null, the MIME type will be derived from the fileName extension.</param>
        /// <param name="contentId">Optional: the unique identifier for this attachment IF AND ONLY IF the attachment should be embedded in the body of the email. This is useful, for example, if you want to embbed an image to be displayed in the HTML content. For standard attachment, this value should be null.</param>
        /// <returns>The attachment.</returns>
        /// <exception cref="Exception">File exceeds the size limit.</exception>
        public static Attachment FromBinary(byte[] content, string fileName, string mimeType = null, string contentId = null)
        {
            if (content.Length > MAX_ATTACHMENT_SIZE)
            {
                throw new Exception("Attachment exceeds the size limit");
            }

            if (string.IsNullOrEmpty(mimeType))
            {
                mimeType = MimeTypesMap.GetMimeType(fileName);
            }

            return(new Attachment()
            {
                Content = Convert.ToBase64String(content),
                ContentId = contentId,
                Disposition = string.IsNullOrEmpty(contentId) ? "attachment" : "inline",
                FileName = fileName,
                Type = mimeType
            });
        }
Ejemplo n.º 22
0
        public async Task <FileResult> DownloadRequirementsFile(Guid requirementsId, Guid id)
        {
            try
            {
                var file = await _context.Files.FindAsync(id);

                var requirement = await _context.Requirements.FindAsync(requirementsId);

                var laboratoryWork = await _context.LaboratoryWorks.FindAsync(requirement.LaboratoryWorkId);

                var discipline = await _context.Disciplines.FindAsync(laboratoryWork.DisciplineId);

                FileStream fs       = new FileStream(file.PathToFile, FileMode.Open);
                string     fileName = $"{laboratoryWork.Name} - {discipline.ShortName}{Auxiliary.GetExtension(file.Name)}";
                return(File(fs, MimeTypesMap.GetMimeType(file.Name), fileName));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(null);
            }
        }
Ejemplo n.º 23
0
        private void ParseResources(XmlDocument xmlDocument,
                                    EnexParagraphExtension paragraphExtension, XmlNode note)
        {
            var resources = _media.Concat(_attachments);

            foreach (var fileName in resources)
            {
                var resource = xmlDocument.CreateElement("resource");
                var data     = xmlDocument.CreateElement("data");
                data.SetAttribute("encoding", "base64");
                data.InnerText = Convert.ToBase64String(File.ReadAllBytes(fileName));
                resource.AppendChild(data);
                var mime     = xmlDocument.CreateElement("mime");
                var mimeType = MimeTypesMap.GetMimeType(fileName);
                mime.InnerText = mimeType;
                resource.AppendChild(mime);
                var recognition     = xmlDocument.CreateElement("recognition");
                var recognitionDoc  = new XmlDocument();
                var recognitionDecl = recognitionDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                recognitionDoc.AppendChild(recognitionDecl);
                var recognitionDocType = recognitionDoc.CreateDocumentType("recoIndex", "SYSTEM",
                                                                           "http://xml.evernote.com/pub/recoIndex.dtd", null);
                recognitionDoc.AppendChild(recognitionDocType);
                var recoIndex = recognitionDoc.CreateElement("recoIndex");
                recoIndex.SetAttribute("objType", mimeType);
                var hash = paragraphExtension.FindHash(fileName);
                recoIndex.SetAttribute("objID", hash);
                recognitionDoc.AppendChild(recoIndex);
                var recognitionCdata = xmlDocument.CreateCDataSection(recognitionDoc.OuterXml);
                recognition.AppendChild(recognitionCdata);
                resource.AppendChild(recognition);
                var resourceAttributes = xmlDocument.CreateElement("resource-attributes");
                var resourceFileName   = xmlDocument.CreateElement("file-name");
                resourceFileName.InnerText = Path.GetFileName(fileName);
                resourceAttributes.AppendChild(resourceFileName);
                resource.AppendChild(resourceAttributes);
                note.AppendChild(resource);
            }
        }
Ejemplo n.º 24
0
        private static string _getFilename(string url, string mimeType = null, string defaultMimeType = null)
        {
            var fileName = Path.GetFileName(new Uri(url).LocalPath);

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = "noname";
            }
            if (!fileName.Contains("."))
            {
                if (mimeType != null)
                {
                    return($"{fileName}.{MimeTypesMap.GetExtension(mimeType)}");
                }
                if (defaultMimeType != null)
                {
                    return($"{fileName}.{MimeTypesMap.GetExtension(defaultMimeType)}");
                }
            }

            return(fileName);
        }
        private void FileValidation(string propertyName, IFormFile file, CustomContext context, int maxFileLengthInMb, IEnumerable <string> allowedExtensions)
        {
            const int bytesInMegaByte  = 1000000;
            var       maxLengthInBytes = maxFileLengthInMb * bytesInMegaByte;

            if (file.Length == 0)
            {
                context.AddFailure(propertyName, "File cannot be empty");
                return;
            }

            if (!allowedExtensions.Any(extension => extension.Equals(MimeTypesMap.GetExtension(file.ContentType), StringComparison.OrdinalIgnoreCase)))
            {
                context.AddFailure(propertyName, "Not supported file type");
                return;
            }

            if (file.Length > maxLengthInBytes)
            {
                context.AddFailure(propertyName, "Too big file");
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Add file from stream as <see cref="StreamContent"/>.
        /// </summary>
        /// <param name="multipartForm"></param>
        /// <param name="name">Name to use for the http form parameter.</param>
        /// <param name="stream"></param>
        /// <param name="fileName"></param>
        /// <param name="mimeType"></param>
        public static void AddFile(this MultipartFormDataContent multipartForm, string name, Stream stream, string fileName, string?mimeType = null)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (mimeType == null)
            {
                var fileExt = Path.GetExtension(fileName);
                if (string.IsNullOrEmpty(fileExt))
                {
                    throw new ArgumentException($"'{nameof(mimeType)}' needs to be specified or '{nameof(fileName)}' must contains extension.");
                }
                mimeType = MimeTypesMap.GetMimeType(fileName);
            }

            var fileStreamContent = new StreamContent(stream);

            fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue(mimeType);

            multipartForm.Add(fileStreamContent, name, fileName);
        }
        public static void AddImagesOutput(this WebDocument document, string outputPath, Presentation pres)
        {
            for (int index = 0; index < pres.Images.Count; index++)
            {
                IPPImage image = pres.Images[index];
                string   path;
                string   ext;

                if (image.ContentType == "image/x-emf" || image.ContentType == "image/x-wmf") // Output will convert metafiles to png
                {
                    ext = "png";
                }
                else
                {
                    ext = MimeTypesMap.GetExtension(image.ContentType);
                }

                path = Path.Combine(outputPath, string.Format("image{0}.{1}", index, ext));

                var outputFile = document.Output.Add(path, image);
                document.Output.BindResource(outputFile, image);
            }
        }
Ejemplo n.º 28
0
        public void AddPlaylistItem(string filepath, bool notifyChange = true)
        {
            if (!File.Exists(filepath))
            {
                Logger.Warn("Playlist item doesn't exist {0}, skip adding...", filepath);
                return;
            }

            string mimeType = MimeTypesMap.GetMimeType(filepath);

            if (mimeType.StartsWith("playlist/"))
            {
                // TODO: Add support for opening playlist files.
                throw new NotImplementedException();
                //   return;
            }

            Logger.Debug("Adding playlist item {0}", filepath);

            PlaylistItem item = new PlaylistItem(filepath);

            CurrentPlayer.Playlist.Add(item, notifyChange);
        }
Ejemplo n.º 29
0
        public async Task <string> DownloadToFile(string path,
                                                  Uri uri,
                                                  HttpMethod httpMethod,
                                                  [AllowNull] string extension,
                                                  [AllowNull] string data,
                                                  CancellationToken token)
        {
            string tempPath = Path.ChangeExtension(path, "tmp");

            try
            {
                string mediaType = null;
                using (var fileStream = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024 * 1024, true))
                {
                    mediaType = await DownloadToStream(fileStream, uri, httpMethod, data, token).ConfigureAwait(false);
                }
                string fileExtension = extension ?? MimeTypesMap.GetExtension(mediaType);
                string destFileName  = Path.ChangeExtension(path, fileExtension);
                if (File.Exists(destFileName))
                {
                    string destFileNameOld = Path.ChangeExtension(destFileName, "old");
                    File.Move(destFileName, destFileNameOld);
                    File.Delete(destFileNameOld);
                }

                File.Move(tempPath, destFileName);
                return(destFileName);
            }
            finally
            {
                // always delete the tmp file
                if (File.Exists(tempPath))
                {
                    File.Delete(tempPath);
                }
            }
        }
Ejemplo n.º 30
0
        // TODO: Add pipe server for program mutex.
        public FormMain()
        {
            if (!DesignMode)
            {
                Logger.Debug("Initializing LibVLC...");
                Vlc.Initialize();
            }

            Logger.Debug("Initializing windows wallpaper...");
            if (!WindowsWallpaper.Init())
            {
                MessageBox.Show(this, "Failed to initalize windows wallpaper! Failed to acquire desktop window pointer!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }

            MimeTypesMap.AddOrUpdate("playlist/json", "dpp");
            MimeTypesMap.AddOrUpdate("shadertoy/dpst", "dpst");
            MimeTypesMap.AddOrUpdate("shadertoy/shadertoy", "shadertoy");

            MediaPlayerStore.Instance.RegisterPlayer <VlcMediaPlayer>("video/x-matroska", "video/mp4", "video/mov", "video/avi", "video/wmv", "video/gif", "video/webm");
            MediaPlayerStore.Instance.RegisterPlayer <PictureBoxPlayer>("image/jpeg", "image/png", "image/jpg", "image/bmp", "image/tiff", "image/svg");
            MediaPlayerStore.Instance.RegisterPlayer <ShaderToyPlayer>("shadertoy/dpst", "shadertoy/shadertoy");

            settingsManager.OnSettingsChanged += (sender, settings) => {
                CloseToTray    = settings.CloseToTray;
                MinimizeToTray = settings.MinimizeToTray;
            };
            settingsManager.Load(true);

            if (Settings.StartMinimized)
            {
                WindowState = FormWindowState.Minimized;
            }

            InitializeComponent();
            showToolStripMenuItem.Click += trayShowForm_Click; // Connect the show button in the tray with the required method.
        }