Exemple #1
0
        protected string DownloadAsset(string url)
        {
            try
            {
                WebClient wc    = new WebClient();
                byte[]    asset = wc.DownloadData(url);

                string      ext         = Path.GetExtension(url);
                var         ctype       = _mresolver.GetFirstMatching(ext);
                ContentType contentType = _trepo.Load(ctype);

                //TODO: Support destination that should be resolved.
                var assetFile = _repo.GetDefault <MediaData>(SiteDefinition.Current.GlobalAssetsRoot, contentType.ID);
                assetFile.Name = Path.GetFileName(url);

                var blob = _blobFactory.CreateBlob(assetFile.BinaryDataContainer, ext);
                using (var s = blob.OpenWrite())
                {
                    var w = new StreamWriter(s);
                    w.BaseStream.Write(asset, 0, asset.Length);
                    w.Flush();
                }
                assetFile.BinaryData = blob;
                var assetContentRef = _repo.Save(assetFile, SaveAction.Publish);

                OnCommandOutput?.Invoke(this, assetContentRef); //If piped, output the reference that was just created
            } catch (Exception exc)
            {
                return(exc.Message);
            }

            return(null);
        }
Exemple #2
0
        public virtual IHttpActionResult ContentTypeForMedia(string MediaExtension)
        {
            if (!MediaExtension.StartsWith("."))
            {
                MediaExtension = "." + MediaExtension;
            }
            var mediatype   = _mediaDataResolver.GetFirstMatching(MediaExtension.ToLower()); //Extension contains .
            var contentType = _typerepo.Load(mediatype);

            return(ContentTypeInfo(contentType.Name));
        }
        public ContentReference UploadPdf(byte[] fileContent, string fileName, ContentFolder parentFolder)
        {
            try
            {
                PdfFile pdfFile;

                var file = TryGetMedia <PdfFile>(fileName, parentFolder);

                if (file != null)
                {
                    pdfFile =
                        _contentRepository.Get <PdfFile>(file).CreateWritableClone() as
                        PdfFile;
                }
                else
                {
                    var fileExtension = Path.GetExtension(fileName);
                    var mediaType     = _contentMediaResolver.GetFirstMatching(fileExtension);
                    var contentType   = _contentTypeRepository.Load(mediaType);

                    var contentReference = GetFolderReference(parentFolder);

                    pdfFile = _contentRepository.GetDefault <PdfFile>(
                        contentReference,
                        contentType.ID);
                    pdfFile.Name = fileName;
                }

                if (pdfFile == null)
                {
                    throw new Exception();
                }

                pdfFile.BinaryData = _blobFactory.CreateBlob(pdfFile.BinaryDataContainer, Path.GetExtension(fileName));
                var stream = new MemoryStream(fileContent);
                pdfFile.BinaryData.Write(stream);

                return(_contentRepository.Save(pdfFile, SaveAction.Publish, AccessLevel.Read));
            }
            catch (Exception e)
            {
                Log.Warn(
                    $"Failed to upload file {fileName} to folder {parentFolder.RouteSegment} id {parentFolder.ContentLink.ID}",
                    e);
            }

            return(null);
        }
Exemple #4
0
        public static Guid CreateFileContent(FileInfo assetFile, string parentFolder)
        {
            var catalogRootFolder = GetRootFolderContent(parentFolder);
            var contentType       = _contenttypeRepository.Load(_contentMediaResolver.GetFirstMatching(assetFile.Extension));
            var file = _contentRepository.GetDefault <MediaData>(catalogRootFolder.ContentLink, contentType.ID);

            file.Name = assetFile.Name;
            var        blob = _blobFactory.CreateBlob(file.BinaryDataContainer, assetFile.Extension);
            FileStream fs   = assetFile.OpenRead();

            blob.Write(fs);
            file.BinaryData = blob;
            var content = _contentRepository.Save(file, DataAccess.SaveAction.Publish, EPiServer.Security.AccessLevel.NoAccess);

            fs.Close();
            return(file.ContentGuid);
        }
        public Task <string> SaveAsync(Stream fileStream, string extension, string fileGroups, string owner)
        {
            if (string.IsNullOrWhiteSpace(fileGroups))
            {
                throw new ArgumentNullException(nameof(fileGroups));
            }
            if (string.IsNullOrWhiteSpace(extension))
            {
                throw new ArgumentNullException(nameof(extension));
            }
            if (fileStream == null)
            {
                throw new ArgumentNullException(nameof(fileStream));
            }

            var fileGroupArray = fileGroups.Split('/').Where(n => !string.IsNullOrWhiteSpace(n));
            var groupArray     = fileGroupArray as string[] ?? fileGroupArray.ToArray();
            var groupFolder    = GetGroupFolder(groupArray);

            //Get a suitable MediaData type from extension
            var mediaType   = _mediaResolver.GetFirstMatching(extension);
            var contentType = _contentTypeRepo.Load(mediaType);
            var mediaData   = _contentRepo.GetDefault <MediaData>(groupFolder.ContentLink, contentType.ID);

            var fileName = $"{DateTime.Now.Ticks}_{Guid.NewGuid().ToString()}{extension}";

            mediaData.Name      = fileName;
            mediaData.CreatedBy = owner;

            //Create a blob in the binary container
            var blob = _blobFactory.CreateBlob(mediaData.BinaryDataContainer, extension);

            blob.Write(fileStream);

            //Assign to file and publish changes
            mediaData.BinaryData = blob;
            _contentRepo.Save(mediaData, SaveAction.Publish, AccessLevel.NoAccess);
            return(Task.FromResult($"/globalassets/{string.Join("/", groupArray)}/{fileName}"));
        }
Exemple #6
0
        private MediaData CreateNewFile(InRiverImportResource inriverResource)
        {
            ResourceMetaField resourceFileId = inriverResource.MetaFields.FirstOrDefault(m => m.Id == "ResourceFileId");

            if (String.IsNullOrEmpty(resourceFileId?.Values.FirstOrDefault()?.Data))
            {
                _logger.Debug("ResourceFileId is null, won't do stuff.");
                return(null);
            }

            _logger.Debug($"Attempting to create and import file from path: {inriverResource.Path}");

            var fileInfo = new FileInfo(inriverResource.Path);

            IEnumerable <Type> mediaTypes = _contentMediaResolver.ListAllMatching(fileInfo.Extension).ToList();

            _logger.Debug($"Found {mediaTypes.Count()} matching media types for extension {fileInfo.Extension}.");

            Type contentTypeType = mediaTypes.FirstOrDefault(x => x.GetInterfaces().Contains(typeof(IInRiverResource))) ??
                                   _contentMediaResolver.GetFirstMatching(fileInfo.Extension);

            if (contentTypeType == null)
            {
                _logger.Warning($"Can't find suitable content type when trying to import {inriverResource.Path}");
            }

            else
            {
                _logger.Debug($"Chosen content type-type is {contentTypeType.Name}.");
            }

            ContentType contentType = _contentTypeRepository.Load(contentTypeType);

            var newFile = _contentRepository.GetDefault <MediaData>(GetFolder(fileInfo, contentType), contentType.ID);

            newFile.Name        = fileInfo.Name;
            newFile.ContentGuid = EpiserverEntryIdentifier.EntityIdToGuid(inriverResource.ResourceId);

            // ReSharper disable once SuspiciousTypeConversion.Global
            if (newFile is IInRiverResource resource)
            {
                resource.ResourceFileId = Int32.Parse(resourceFileId.Values.First().Data);
                resource.EntityId       = inriverResource.ResourceId;

                try
                {
                    resource.HandleMetaData(inriverResource.MetaFields);
                }
                catch (Exception exception)
                {
                    _logger.Error($"Error when running HandleMetaData for resource {inriverResource.ResourceId} with contentType {contentType.Name}: {exception.Message}");
                }
            }

            Blob blob = _blobFactory.CreateBlob(newFile.BinaryDataContainer, fileInfo.Extension);

            using (Stream stream = blob.OpenWrite())
            {
                FileStream fileStream = File.OpenRead(fileInfo.FullName);
                fileStream.CopyTo(stream);
                fileStream.Dispose();
            }

            newFile.BinaryData = blob;

            _logger.Debug($"New mediadata is ready to be saved: {newFile.Name}, from path {inriverResource.Path}");

            ContentReference contentReference = _contentRepository.Save(newFile, SaveAction.Publish, AccessLevel.NoAccess);
            var mediaData = _contentRepository.Get <MediaData>(contentReference);

            _logger.Debug($"Saved file {fileInfo.Name} with Content ID {contentReference?.ID}.");

            return(mediaData);
        }