Example #1
0
        private PublishedContentType CreatePublishedContentType(PublishedItemType itemType, string alias)
        {
            if (GetPublishedContentTypeByAlias != null)
            {
                return(GetPublishedContentTypeByAlias(alias));
            }

            IContentTypeComposition contentType;

            switch (itemType)
            {
            case PublishedItemType.Content:
                contentType = _contentTypeService.Get(alias);
                break;

            case PublishedItemType.Media:
                contentType = _mediaTypeService.Get(alias);
                break;

            case PublishedItemType.Member:
                contentType = _memberTypeService.Get(alias);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(itemType));
            }

            if (contentType == null)
            {
                throw new Exception($"ContentTypeService failed to find a {itemType.ToString().ToLower()} type with alias \"{alias}\".");
            }

            return(_publishedContentTypeFactory.CreateContentType(contentType));
        }
Example #2
0
        protected override ActionResult <MenuItemCollection> GetMenuForNode(string id, FormCollection queryStrings)
        {
            var menu = _menuItemCollectionFactory.Create();

            if (id == Constants.System.RootString)
            {
                // set the default to create
                menu.DefaultMenuAlias = ActionNew.ActionAlias;

                // root actions
                menu.Items.Add <ActionNew>(LocalizedTextService, opensDialog: true);
                menu.Items.Add(new RefreshNode(LocalizedTextService));
                return(menu);
            }

            var container = _entityService.Get(int.Parse(id, CultureInfo.InvariantCulture), UmbracoObjectTypes.MediaTypeContainer);

            if (container != null)
            {
                // set the default to create
                menu.DefaultMenuAlias = ActionNew.ActionAlias;

                menu.Items.Add <ActionNew>(LocalizedTextService, opensDialog: true);

                menu.Items.Add(new MenuItem("rename", LocalizedTextService.Localize("actions", "rename"))
                {
                    Icon = "icon icon-edit"
                });

                if (container.HasChildren == false)
                {
                    // can delete doc type
                    menu.Items.Add <ActionDelete>(LocalizedTextService, opensDialog: true);
                }
                menu.Items.Add(new RefreshNode(LocalizedTextService, true));
            }
            else
            {
                var ct     = _mediaTypeService.Get(int.Parse(id, CultureInfo.InvariantCulture));
                var parent = ct == null ? null : _mediaTypeService.Get(ct.ParentId);

                menu.Items.Add <ActionNew>(LocalizedTextService, opensDialog: true);

                // no move action if this is a child doc type
                if (parent == null)
                {
                    menu.Items.Add <ActionMove>(LocalizedTextService, true, opensDialog: true);
                }

                menu.Items.Add <ActionCopy>(LocalizedTextService, opensDialog: true);
                if (ct.IsSystemMediaType() == false)
                {
                    menu.Items.Add <ActionDelete>(LocalizedTextService, opensDialog: true);
                }
                menu.Items.Add(new RefreshNode(LocalizedTextService, true));
            }

            return(menu);
        }
        public static void AfterMapMediaTypeSaveToEntity <TSource, TDestination>(TSource source, TDestination dest, IMediaTypeService mediaTypeService)
            where TSource : MediaTypeSave
            where TDestination : IContentTypeComposition
        {
            //sync compositions
            var current  = dest.CompositionAliases().ToArray();
            var proposed = source.CompositeContentTypes;

            var remove = current.Where(x => proposed.Contains(x) == false);
            var add    = proposed.Where(x => current.Contains(x) == false);

            foreach (var rem in remove)
            {
                dest.RemoveContentType(rem);
            }

            foreach (var a in add)
            {
                // TODO: Remove N+1 lookup
                var addCt = mediaTypeService.Get(a);
                if (addCt != null)
                {
                    dest.AddContentType(addCt);
                }
            }
        }
Example #4
0
        private string GetIcon(LogDto logItem)
        {
            switch (logItem.EntityType.ToLower())
            {
            case "document":
                return(_contentService.GetById(logItem.NodeId).ContentType.Icon);

            case "media":
                return(_mediaService.GetById(logItem.NodeId).ContentType.Icon);

            case "member":
                return(_memberTypeService.Get(_memberService.GetById(logItem.NodeId).ContentTypeAlias).Icon);

            case "documenttype":
                return(_contentTypeService.Get(logItem.NodeId).Icon);

            case "mediatype":
                return(_mediaTypeService.Get(logItem.NodeId).Icon);

            case "membertype":
                return(_memberTypeService.Get(logItem.NodeId).Icon);

            case "datatype":
                return(_dataTypeService.GetAll(new[] { logItem.NodeId }).FirstOrDefault().Editor.Icon);

            case "dictionaryitem":
                return("icon-book-alt");

            default:
                return("icon-newspaper");
            }
        }
        public ActionResult <MediaTypeDisplay> GetById(int id)
        {
            var ct = _mediaTypeService.Get(id);

            if (ct == null)
            {
                return(NotFound());
            }

            var dto = _umbracoMapper.Map <IMediaType, MediaTypeDisplay>(ct);

            return(dto);
        }
        public ActionResult <MediaItemDisplay> GetEmpty(string contentTypeAlias, int parentId)
        {
            var contentType = _mediaTypeService.Get(contentTypeAlias);

            if (contentType == null)
            {
                return(NotFound());
            }

            var emptyContent = _mediaService.CreateMedia("", parentId, contentType.Alias, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
            var mapped       = _umbracoMapper.Map <MediaItemDisplay>(emptyContent);

            //remove the listview app if it exists
            mapped.ContentApps = mapped.ContentApps.Where(x => x.Alias != "umbListView").ToList();

            return(mapped);
        }
Example #7
0
        private IPublishedContentType CreatePublishedContentType(PublishedItemType itemType, Guid key)
        {
            IContentTypeComposition contentType = itemType switch
            {
                PublishedItemType.Content => _contentTypeService.Get(key),
                PublishedItemType.Media => _mediaTypeService.Get(key),
                PublishedItemType.Member => _memberTypeService.Get(key),
                _ => throw new ArgumentOutOfRangeException(nameof(itemType)),
            };

            if (contentType == null)
            {
                throw new Exception($"ContentTypeService failed to find a {itemType.ToString().ToLower()} type with key \"{key}\".");
            }

            return(_publishedContentTypeFactory.CreateContentType(contentType));
        }
Example #8
0
        private IMedia CreateNew(MediaItemSave model)
        {
            var mediaType = _mediaTypeService.Get(model.ContentTypeAlias);

            if (mediaType == null)
            {
                throw new InvalidOperationException("No media type found with alias " + model.ContentTypeAlias);
            }
            return(new Cms.Core.Models.Media(model.Name, model.ParentId, mediaType));
        }
        public async Task GetUrlsByIds_MediaWithIntegerIds_ReturnsValidMap()
        {
            IMediaTypeService mediaTypeService = Services.GetRequiredService <IMediaTypeService>();
            IMediaService     mediaService     = Services.GetRequiredService <IMediaService>();

            var mediaItems = new List <Media>();

            using (ScopeProvider.CreateScope(autoComplete: true))
            {
                IMediaType mediaType = mediaTypeService.Get("image");
                mediaTypeService.Save(mediaType);

                mediaItems.Add(MediaBuilder.CreateMediaImage(mediaType, -1));
                mediaItems.Add(MediaBuilder.CreateMediaImage(mediaType, -1));

                foreach (Media media in mediaItems)
                {
                    mediaService.Save(media);
                }
            }

            var queryParameters = new Dictionary <string, object>
            {
                ["type"] = Constants.UdiEntityType.Media
            };

            var url = LinkGenerator.GetUmbracoControllerUrl("GetUrlsByIds", typeof(EntityController), queryParameters);

            var payload = new
            {
                ids = new[]
                {
                    mediaItems[0].Id,
                    mediaItems[1].Id,
                }
            };

            HttpResponseMessage response = await HttpClientJsonExtensions.PostAsJsonAsync(Client, url, payload);

            // skip pointless un-parseable cruft.
            (await response.Content.ReadAsStreamAsync()).Seek(AngularJsonMediaTypeFormatter.XsrfPrefix.Length, SeekOrigin.Begin);

            IDictionary <int, string> results = await response.Content.ReadFromJsonAsync <IDictionary <int, string> >();

            Assert.Multiple(() =>
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                Assert.IsTrue(results ![payload.ids[0]].StartsWith("/media"));
                Assert.IsTrue(results ![payload.ids[1]].StartsWith("/media"));
        /// <summary>
        /// Initializes a new instance of the <see cref="PublishedModelFactory" /> class.
        /// </summary>
        /// <param name="models">The models.</param>
        /// <param name="contentTypeService">The content type service.</param>
        /// <param name="mediaTypeService">The media type service.</param>
        public PublishedModelFactory(ModelMappingCollection models, IContentTypeService contentTypeService, IMediaTypeService mediaTypeService)
        {
            this.models             = models;
            this.contentTypeService = contentTypeService;
            this.mediaTypeService   = mediaTypeService;

            var forAllModelMaps = models.Values.Where(m => m.IsForAll).ToDictionary(keySelector: m => m.Type);

            foreach (var map in models)
            {
                if (map.Value.IsForAll)
                {
                    continue;
                }

                map.Value.Build((IContentTypeComposition)contentTypeService.Get(map.Key) ?? mediaTypeService.Get(map.Key), forAllModelMaps);
            }
        }
Example #11
0
 // no MapAll - take care
 private void Map(MediaTypeSave source, IMediaType target, MapperContext context)
 {
     MapSaveToTypeBase <MediaTypeSave, PropertyTypeBasic>(source, target, context);
     MapComposition(source, target, alias => _mediaTypeService.Get(alias));
 }
Example #12
0
        private int CreateMediaItem(IMediaService service, IMediaTypeService mediaTypeService,
                                    int parentFolderId, string nodeTypeAlias, Guid key, string nodeName, string mediaPath, bool checkForDuplicateName = false)
        {
            //if the item with the exact id exists we cannot install it (the package was probably already installed)
            if (service.GetById(key) != null)
            {
                return(-1);
            }

            //cannot continue if the media type doesn't exist
            var mediaType = mediaTypeService.Get(nodeTypeAlias);

            if (mediaType == null)
            {
                Current.Logger.Warn <OnInstall>("Media type does not exist", nodeTypeAlias);
                return(-1);
            }

            var isDuplicate = false;

            if (checkForDuplicateName)
            {
                IEnumerable <IMedia> children;
                if (parentFolderId == -1)
                {
                    children = service.GetRootMedia();
                }
                else
                {
                    var parentFolder = service.GetById(parentFolderId);
                    if (parentFolder == null)
                    {
                        Current.Logger.Warn <OnInstall>("No media parent found by Id {ParentFolderId} the media item {NodeName} cannot be installed", parentFolderId, nodeName);
                        return(-1);
                    }

                    children = service.GetPagedChildren(parentFolderId, 0, int.MaxValue, out long totalRecords);
                }
                foreach (var m in children)
                {
                    if (m.Name == nodeName)
                    {
                        isDuplicate = true;
                        break;
                    }
                }
            }

            if (isDuplicate)
            {
                return(-1);
            }

            if (parentFolderId != -1)
            {
                var parentFolder = service.GetById(parentFolderId);
                if (parentFolder == null)
                {
                    Current.Logger.Warn <OnInstall>("No media parent found by Id {ParentFolderId} the media item {NodeName} cannot be installed", parentFolderId, nodeName);
                    return(-1);
                }
            }

            var media = service.CreateMedia(nodeName, parentFolderId, nodeTypeAlias);

            if (nodeTypeAlias != "folder")
            {
                var fileName = Path.GetFileName(mediaPath);
                using (var fs = System.IO.File.OpenRead(HostingEnvironment.MapPath(mediaPath)))
                {
                    media.SetValue(Current.Services.ContentTypeBaseServices, "umbracoFile", fileName, fs);
                }
            }

            if (key != Guid.Empty)
            {
                media.Key = key;
            }

            service.Save(media);
            return(media.Id);
        }
Example #13
0
        private int CreateMediaItem(IMediaService service, IMediaTypeService mediaTypeService,
                                    int parentFolderId, string nodeTypeAlias, Guid key, string nodeName, string mediaPath, bool checkForDuplicateName = false)
        {
            //if the item with the exact id exists we cannot install it (the package was probably already installed)
            if (service.GetById(key) != null)
            {
                return(-1);
            }

            //cannot continue if the media type doesn't exist
            var mediaType = mediaTypeService.Get(nodeTypeAlias);

            if (mediaType == null)
            {
                Current.Logger.Warn <CleanStarterKitInstallPackageAction>("Could not create media, the {NodeTypeAlias} media type is missing, the Clean Starter Kit package will not function correctly", nodeTypeAlias);
                return(-1);
            }

            var isDuplicate = false;

            if (checkForDuplicateName)
            {
                IEnumerable <IMedia> children;
                if (parentFolderId == -1)
                {
                    children = service.GetRootMedia();
                }
                else
                {
                    var parentFolder = service.GetById(parentFolderId);
                    if (parentFolder == null)
                    {
                        Current.Logger.Warn <CleanStarterKitInstallPackageAction>("No media parent found by Id {ParentFolderId} the media item {NodeName} cannot be installed", parentFolderId, nodeName);
                        return(-1);
                    }

                    children = service.GetPagedChildren(parentFolderId, 0, int.MaxValue, out long totalRecords);
                }
                foreach (var m in children)
                {
                    if (m.Name == nodeName)
                    {
                        isDuplicate = true;
                        break;
                    }
                }
            }

            if (isDuplicate)
            {
                return(-1);
            }

            if (parentFolderId != -1)
            {
                var parentFolder = service.GetById(parentFolderId);
                if (parentFolder == null)
                {
                    Current.Logger.Warn <CleanStarterKitInstallPackageAction>("No media parent found by Id {ParentFolderId} the media item {NodeName} cannot be installed", parentFolderId, nodeName);
                    return(-1);
                }
            }

            var media = service.CreateMedia(nodeName, parentFolderId, nodeTypeAlias);

            if (nodeTypeAlias != "folder")
            {
                media.SetValue("umbracoFile", JsonConvert.SerializeObject(new ImageCropperValue {
                    Src = mediaPath
                }));
            }
            if (key != Guid.Empty)
            {
                media.Key = key;
            }
            service.Save(media);
            return(media.Id);
        }
        public void ProcessMediaSaved(IMediaService sender, SaveEventArgs <IMedia> args)
        {
            var newMedia = args
                           .SavedEntities
                           .Where(m => m.WasPropertyDirty("Id")).ToList();

            foreach (var media in newMedia)
            {
                var convertInProgress = _videoConverter.IsConverting(media);
                if (convertInProgress || media.ContentType.Alias == UmbracoAliases.Media.ImageTypeAlias)
                {
                    continue;
                }

                var umbracoFile = media.GetValue <string>(UmbracoAliases.Media.UmbracoFilePropertyAlias);

                if (_videoConverter.IsVideo(umbracoFile))
                {
                    var videoContentType = _mediaTypeService.Get(UmbracoAliases.Media.VideoTypeAlias); // BECOME

                    //media.ChangeContentType(videoContentType, false);// TODO Resolve changeContentType umbraco v8

                    // Due to ChangeContentType is internal
                    var method = typeof(Media)
                                 .GetMethod(
                        name: "ChangeContentType",
                        bindingAttr: BindingFlags.NonPublic | BindingFlags.Instance,
                        binder: null,
                        types: new Type[] { typeof(IMediaType), typeof(bool) },
                        modifiers: null
                        );

                    method?.Invoke(media, new object[]
                    {
                        videoContentType,
                        false
                    });

                    _mediaService.Save(media);

                    var video = _mediaService.GetById(media.Id);

                    if (_videoConverter.IsMp4(umbracoFile))
                    {
                        var thumbnailUrl = _videoHelper.CreateThumbnail(video);
                        video.SetValue(UmbracoAliases.Video.ThumbnailUrlPropertyAlias, thumbnailUrl);
                        _mediaService.Save(video);

                        continue;
                    }

                    video.SetValue(UmbracoAliases.Video.ThumbnailUrlPropertyAlias, _videoHelper.CreateConvertingThumbnail());
                    _mediaService.Save(video);

                    var fileBytes = System.IO.File.ReadAllBytes(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + umbracoFile));

                    System.Threading.Tasks.Task.Run(() =>
                    {
                        _videoConverter.Convert(new MediaConvertModel()
                        {
                            File = new TempFile {
                                FileName = umbracoFile, FileBytes = fileBytes
                            },
                            MediaId = media.Id
                        });
                    });
                }
            }
        }