From 503d28ae920229e9979b9712b83fa084a9da0103 Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 18 Sep 2013 15:35:52 +1000 Subject: [PATCH] Fixes up entity resource to use the correct methods of entity controller and anything that was referencing those methods. --- .../common/mocks/resources/entity.mocks.js | 13 +- .../src/common/resources/entity.resource.js | 247 +++--------------- .../contentpicker/contentpicker.controller.js | 12 +- src/Umbraco.Web/Editors/EntityController.cs | 154 +++-------- 4 files changed, 85 insertions(+), 341 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/mocks/resources/entity.mocks.js b/src/Umbraco.Web.UI.Client/src/common/mocks/resources/entity.mocks.js index e69aefd100..cad3b0490b 100644 --- a/src/Umbraco.Web.UI.Client/src/common/mocks/resources/entity.mocks.js +++ b/src/Umbraco.Web.UI.Client/src/common/mocks/resources/entity.mocks.js @@ -36,20 +36,13 @@ angular.module('umbraco.mocks'). return { register: function () { + $httpBackend - .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/Entity/GetEntitiesByIds')) + .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/Entity/GetByIds')) .respond(returnEntitybyIds); $httpBackend - .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/Entity/GetEntityById?')) - .respond(returnEntitybyId); - - $httpBackend - .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/Entity/GetDocumentsByIds')) - .respond(returnEntitybyIds); - - $httpBackend - .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/Entity/GetDocumentById?')) + .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/Entity/GetById?')) .respond(returnEntitybyId); } }; diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/entity.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/entity.resource.js index 30b039e622..bae4ed2749 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/entity.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/entity.resource.js @@ -34,7 +34,7 @@ function entityResource($q, $http, umbRequestHelper) { /** * @ngdoc method - * @name umbraco.resources.entityResource#getEntityById + * @name umbraco.resources.entityResource#getById * @methodOf umbraco.resources.entityResource * * @description @@ -42,14 +42,8 @@ function entityResource($q, $http, umbRequestHelper) { * * ##usage *
-         * entityResource.getEntityById(1234)
-         *    .then(function(ent) {
-         *        var myDoc = ent; 
-         *        alert('its here!');
-         *    });
-         *
-         * //Only return users
-         * entityResource.getEntityById(0, "User")
+         * //get media by id
+         * entityResource.getEntityById(0, "Media")
          *    .then(function(ent) {
          *        var myDoc = ent; 
          *        alert('its here!');
@@ -73,7 +67,7 @@ function entityResource($q, $http, umbRequestHelper) {
         
         /**
          * @ngdoc method
-         * @name umbraco.resources.entityResource#getEntitiesByIds
+         * @name umbraco.resources.entityResource#getByIds
          * @methodOf umbraco.resources.entityResource
          *
          * @description
@@ -81,13 +75,7 @@ function entityResource($q, $http, umbRequestHelper) {
          *
          * ##usage
          * 
-         * entityResource.getEntitiesByIds( [1234,2526,28262])
-         *    .then(function(contentArray) {
-         *        var myDoc = contentArray; 
-         *        alert('they are here!');
-         *    });
-         * 
-         * //Only return templates
+         * //Get templates for ids
          * entityResource.getEntitiesByIds( [1234,2526,28262], "Template")
          *    .then(function(templateArray) {
          *        var myDoc = contentArray; 
@@ -100,20 +88,21 @@ function entityResource($q, $http, umbRequestHelper) {
          * @returns {Promise} resourcePromise object containing the entity array.
          *
          */
-        getByIds: function (ids) {
+        getByIds: function (ids, type) {
             
-            var idQuery = "";
+            var query = "";
             _.each(ids, function(item) {
-                idQuery += "ids=" + item + "&";
+                query += "ids=" + item + "&";
             });
+            query += "type=" + type;
 
             return umbRequestHelper.resourcePromise(
                $http.get(
                    umbRequestHelper.getApiUrl(
                        "entityApiBaseUrl",
                        "GetByIds",
-                       idQuery)),
-               'Failed to retreive entity data for ids ' + idQuery);
+                       query)),
+               'Failed to retreive entity data for ids ' + ids);
         },
 
         /**
@@ -126,15 +115,9 @@ function entityResource($q, $http, umbRequestHelper) {
          *
          * ##usage
          * 
-         * //returns all entities, you should NEVER do that
-         * entityResource.getAll()
-         *    .then(function(ent) {
-         *        var myDoc = ent; 
-         *        alert('its here!');
-         *    });
          *
-         * //Only return users
-         * entityResource.getAll("User")
+         * //Only return media
+         * entityResource.getAll("Media")
          *    .then(function(ent) {
          *        var myDoc = ent; 
          *        alert('its here!');
@@ -157,223 +140,61 @@ function entityResource($q, $http, umbRequestHelper) {
 
         /**
          * @ngdoc method
-         * @name umbraco.resources.entityResource#getEntityById
+         * @name umbraco.resources.entityResource#getAncestors
          * @methodOf umbraco.resources.entityResource
          *
          * @description
-         * Gets an entity with a given id
-         *
-         * ##usage
-         * 
-         * //returns all entities, you should NEVER do that
-         * entityResource.getAll()
-         *    .then(function(ent) {
-         *        var myDoc = ent; 
-         *        alert('its here!');
-         *    });
-         *
-         * //Only return users
-         * entityResource.getAll("User")
-         *    .then(function(ent) {
-         *        var myDoc = ent; 
-         *        alert('its here!');
-         *    });
-         * 
+ * Gets ancestor entities for a given item + * * * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the entity. * */ - getAncestors: function (id) { + getAncestors: function (id, type) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetAncestors", - [{id: id}])), - 'Failed to retreive entity data for id ' + id); - }, - - - /** - * @ngdoc method - * @name umbraco.resources.entityResource#getDocumentById - * @methodOf umbraco.resources.entityResource - * - * @description - * Gets a content entity with a given id - * - * ##usage - *
-         * entityResource.getDocumentById(1234)
-         *    .then(function(ent) {
-         *        var myDoc = ent; 
-         *        alert('its here!');
-         *    });
-         * 
- * - * @param {Int} id id of document to return - * @returns {Promise} resourcePromise object containing the document. - * - */ - getDocumentById: function (id) { - return umbRequestHelper.resourcePromise( - $http.get( - umbRequestHelper.getApiUrl( - "entityApiBaseUrl", - "GetDocumentById", - [{ id: id }])), - 'Failed to retreive entity data for id ' + id); + [{id: id}, {type: type}])), + 'Failed to retreive ancestor data for id ' + id); }, /** * @ngdoc method - * @name umbraco.resources.entityResource#getDocumentsByIds + * @name umbraco.resources.entityResource#getAncestors * @methodOf umbraco.resources.entityResource * * @description - * Gets an array of content entities, given a collection of ids - * - * ##usage - *
-         * entityResource.getDocumentsByIds( [1234,2526,28262])
-         *    .then(function(contentArray) {
-         *        var myDoc = contentArray; 
-         *        alert('they are here!');
-         *    });
-         * 
+ * Gets children entities for a given item + * * - * @param {Array} ids ids of entities to return as an array - * @returns {Promise} resourcePromise object containing the entity array. + * @param {string} type Object type name + * @returns {Promise} resourcePromise object containing the entity. * */ - getDocumentsByIds: function (ids) { - - var idQuery = ""; - _.each(ids, function(item) { - idQuery += "ids=" + item + "&"; - }); - + getChildren: function (id, type) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", - "GetDocumentsByIds", - idQuery)), - 'Failed to retreive document data for ids ' + idQuery); + "GetChildren", + [{ id: id }, { type: type }])), + 'Failed to retreive child data for id ' + id); }, - - /** - * @ngdoc method - * @name umbraco.resources.entityResource#searchDocuments - * @methodOf umbraco.resources.entityResource - * - * @description - * Gets an array of content entities, given a query - * - * ##usage - *
-         * entityResource.searchDocuments("news")
-         *    .then(function(contentArray) {
-         *        var myDoc = contentArray; 
-         *        alert('they are here!');
-         *    });
-         * 
- * - * @param {String} Query search query - * @returns {Promise} resourcePromise object containing the entity array. - * - */ - searchDocuments: function (query) { - - return umbRequestHelper.resourcePromise( - $http.get( - umbRequestHelper.getApiUrl( - "entityApiBaseUrl", - "SearchDocuments", - query)), - 'Failed to retreive document data for query ' + query); - }, - - /** - * @ngdoc method - * @name umbraco.resources.entityResource#getMediaById - * @methodOf umbraco.resources.entityResource - * - * @description - * Gets a media entity with a given id - * - * ##usage - *
-         * entityResource.getMediaById(1234)
-         *    .then(function(ent) {
-         *        var myDoc = ent; 
-         *        alert('its here!');
-         *    });
-         * 
- * - * @param {Int} id id of media to return - * @returns {Promise} resourcePromise object containing the media. - * - */ - getMediaById: function (id) { - return umbRequestHelper.resourcePromise( - $http.get( - umbRequestHelper.getApiUrl( - "entityApiBaseUrl", - "GetMediaById", - [{ id: id }])), - 'Failed to retreive media data for id ' + id); - }, - - /** - * @ngdoc method - * @name umbraco.resources.entityResource#getMediaByIds - * @methodOf umbraco.resources.entityResource - * - * @description - * Gets an array of media entities, given a collection of ids - * - * ##usage - *
-         * entityResource.getMediaByIds( [1234,2526,28262])
-         *    .then(function(mediaArray) {
-         *        var myDoc = contentArray; 
-         *        alert('they are here!');
-         *    });
-         * 
- * - * @param {Array} ids ids of entities to return as an array - * @returns {Promise} resourcePromise object containing the entity array. - * - */ - getMediaByIds: function (ids) { - - var idQuery = ""; - _.each(ids, function(item) { - idQuery += "ids=" + item + "&"; - }); - - return umbRequestHelper.resourcePromise( - $http.get( - umbRequestHelper.getApiUrl( - "entityApiBaseUrl", - "GetMediaByIds", - idQuery)), - 'Failed to retreive media data for ids ' + idQuery); - }, - + /** * @ngdoc method * @name umbraco.resources.entityResource#searchMedia * @methodOf umbraco.resources.entityResource * * @description - * Gets an array of medoa entities, given a query + * Gets an array of entities, given a lucene query * * ##usage *
-         * entityResource.searchMedia("news")
+         * entityResource.search("news")
          *    .then(function(mediaArray) {
          *        var myDoc = mediaArray; 
          *        alert('they are here!');
@@ -384,15 +205,15 @@ function entityResource($q, $http, umbRequestHelper) {
          * @returns {Promise} resourcePromise object containing the entity array.
          *
          */
-        searchMedia: function (query) {
+        search: function (query, type) {
             
             return umbRequestHelper.resourcePromise(
                $http.get(
                    umbRequestHelper.getApiUrl(
                        "entityApiBaseUrl",
                        "SearchMedia",
-                       query)),
-               'Failed to retreive media data for query ' + query);
+                       [{ query: query }, {type: type}])),
+               'Failed to retreive entity data for query ' + query);
         }
             
     };
diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js
index 6c107bb94f..c623865994 100644
--- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js
+++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js
@@ -8,7 +8,7 @@ angular.module('umbraco')
 		$scope.renderModel = [];
 		$scope.multipicker = true;
 
-		entityResource.getDocumentsByIds($scope.ids).then(function(data){
+		entityResource.getByIds($scope.ids, "Document").then(function(data){
 			$(data).each(function(i, item){
 				item.icon = iconHelper.convertFromLegacyIcon(item.icon);
 				$scope.renderModel.push({name: item.name, id: item.id, icon: item.icon});
@@ -34,11 +34,11 @@ angular.module('umbraco')
 			}	
 		};
 
-		$scope.clear = function(){
-			$scope.ids = [];
-			$scope.model.value = "";
-			$scope.renderModel = [];
-		}
+	    $scope.clear = function() {
+	        $scope.ids = [];
+	        $scope.model.value = "";
+	        $scope.renderModel = [];
+	    };
 
 		function trim(str, chr) {
 			var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^'+chr+'+|'+chr+'+$', 'g');
diff --git a/src/Umbraco.Web/Editors/EntityController.cs b/src/Umbraco.Web/Editors/EntityController.cs
index 8b97fbc551..68cc1f9262 100644
--- a/src/Umbraco.Web/Editors/EntityController.cs
+++ b/src/Umbraco.Web/Editors/EntityController.cs
@@ -6,6 +6,7 @@ using System.Web.Http.Controllers;
 using System.Web.Http.ModelBinding;
 using AutoMapper;
 using Newtonsoft.Json;
+using Umbraco.Core;
 using Umbraco.Core.Logging;
 using Umbraco.Core.Services;
 using Umbraco.Web.Models.ContentEditing;
@@ -39,114 +40,19 @@ namespace Umbraco.Web.Editors
     /// 
     [PluginController("UmbracoApi")]
     public class EntityController : UmbracoAuthorizedJsonController
-    {
-        //[EnsureUserPermissionForContent("id")]
-        //[UmbracoApplicationAuthorize(Constants.Applications.Content)]
-        //public EntityBasic GetDocumentById(int id)
-        //{
-        //    return Mapper.Map(Services.EntityService.Get(id, UmbracoObjectTypes.Document));
-        //}
-
-        //[EnsureUserPermissionForContent("id")]
-        //[UmbracoApplicationAuthorizeAttribute(Constants.Applications.Content)]
-        //[FilterAllowedOutgoingContent(typeof(IEnumerable))]
-        //public IEnumerable GetDocumentChildren(int id)
-        //{
-        //    return GetChildren(id, UmbracoObjectTypes.Document);
-        //}
-
-        //[FilterAllowedOutgoingContent(typeof(IEnumerable))]
-        //[UmbracoApplicationAuthorizeAttribute(Constants.Applications.Content)]
-        //public IEnumerable GetDocumentsByIds([FromUri]int[] ids)
-        //{
-        //    if (ids == null) throw new ArgumentNullException("ids");
-        //    return GetEntitiesById(ids, UmbracoObjectTypes.Document);
-        //}
-
-        //[FilterAllowedOutgoingContent(typeof(IEnumerable))]
-        //[UmbracoApplicationAuthorizeAttribute(Constants.Applications.Content)]
-        //public IEnumerable SearchDocuments([FromUri]string query)
-        //{
-        //    var internalSearcher = ExamineManager.Instance.SearchProviderCollection[Constants.Examine.InternalSearcher];
-        //    var criteria = internalSearcher.CreateSearchCriteria("content", BooleanOperation.Or);
-        //    var fields = new[] { "id", "__nodeName", "bodyText" };
-        //    var term = new[] { query.ToLower().Escape() };
-        //    var operation = criteria.GroupedOr(fields, term).Compile();
-
-        //    var results = internalSearcher.Search(operation)
-        //        .Select(x =>  int.Parse(x["id"]));
-
-        //    return GetDocumentsByIds(results.ToArray());
-        //}
-
-        ///// 
-        ///// The user must have access to either content or media for this to return data
-        ///// 
-        ///// 
-        ///// 
-        //[UmbracoApplicationAuthorizeAttribute(
-        //    Constants.Applications.Media, 
-        //    Constants.Applications.Content)]
-        //[EnsureUserPermissionForMedia("id")]
-        //public EntityBasic GetMediaById(int id)
-        //{
-        //    return GetEntityById(id, UmbracoObjectTypes.Media);
-        //}
-
-        ///// 
-        ///// The user must have access to either content or media for this to return data
-        ///// 
-        ///// 
-        ///// 
-        //[UmbracoApplicationAuthorizeAttribute(
-        //    Constants.Applications.Media,
-        //    Constants.Applications.Content)]
-        //[EnsureUserPermissionForMedia("id")]
-        //[FilterAllowedOutgoingMedia(typeof(IEnumerable))]
-        //public IEnumerable GetMediaChildren(int id)
-        //{
-        //    return GetChildren(id, UmbracoObjectTypes.Media);
-        //}
-
-
-        ///// 
-        ///// The user must have access to either content or media for this to return data
-        ///// 
-        ///// 
-        ///// 
-        //[UmbracoApplicationAuthorizeAttribute(
-        //    Constants.Applications.Media,
-        //    Constants.Applications.Content)]
-        //[EnsureUserPermissionForMedia("id")]
-        //[FilterAllowedOutgoingMedia(typeof(IEnumerable))]
-        //public IEnumerable SearchMedia([FromUri]string query)
-        //{
-        //    var internalSearcher = ExamineManager.Instance.SearchProviderCollection[Constants.Examine.InternalSearcher];
-        //    var criteria = internalSearcher.CreateSearchCriteria("media", BooleanOperation.Or);
-        //    var fields = new[] { "id", "__nodeName"};
-        //    var term = new[] { query.ToLower().Escape() };
-        //    var operation = criteria.GroupedOr(fields, term).Compile();
-
-        //    var results = internalSearcher.Search(operation)
-        //        .Select(x => int.Parse(x["id"]));
-
-        //    return GetMediaByIds(results.ToArray());
-        //}
-
-        ///// 
-        ///// The user must have access to either content or media for this to return data
-        ///// 
-        ///// 
-        ///// 
-        //[UmbracoApplicationAuthorizeAttribute(
-        //    Constants.Applications.Media,
-        //    Constants.Applications.Content)]
-        //[FilterAllowedOutgoingMedia(typeof(IEnumerable))]
-        //public IEnumerable GetMediaByIds([FromUri]int[] ids)
-        //{
-        //    if (ids == null) throw new ArgumentNullException("ids");
-        //    return GetEntitiesById(ids, UmbracoObjectTypes.Media);
-        //}
+    {       
+        public IEnumerable Search([FromUri] string query, UmbracoEntityTypes type)
+        {
+            switch (type)
+            {
+                case UmbracoEntityTypes.Document:
+                    return ExamineSearch(query, true);
+                case UmbracoEntityTypes.Media:
+                    return ExamineSearch(query, false);
+                default:
+                    throw new NotSupportedException("The " + typeof(EntityController) + " currently does not support searching against object type " + type);
+            }
+        } 
 
         public EntityBasic GetById(int id, UmbracoEntityTypes type)
         {
@@ -176,6 +82,26 @@ namespace Umbraco.Web.Editors
         {
             return GetResultForAll(type);
         }
+        
+        private IEnumerable ExamineSearch(string query, bool isContent)
+        {
+            //TODO: WE should really just allow passing in a lucene raw query
+            
+            var internalSearcher = ExamineManager.Instance.SearchProviderCollection[Constants.Examine.InternalSearcher];
+            var criteria = internalSearcher.CreateSearchCriteria(isContent ? "content" : "media", BooleanOperation.Or);
+            var fields = new[] { "id", "__nodeName", "bodyText" };
+            
+            var term = new[] { query.ToLower().Escape() };
+            var operation = criteria.GroupedOr(fields, term).Compile();
+
+            var results = internalSearcher.Search(operation)
+                .Select(x =>  int.Parse(x["id"]));
+
+            //TODO: Just create a basic entity from the results!! why double handling and going to the database... this will be ultra slow.
+
+            return GetResultForIds(results.ToArray(), isContent ? UmbracoEntityTypes.Document : UmbracoEntityTypes.Media)
+                .WhereNotNull();
+        }
 
         private IEnumerable GetResultForChildren(int id, UmbracoEntityTypes entityType)
         {
@@ -184,7 +110,8 @@ namespace Umbraco.Web.Editors
             {
                 //TODO: Need to check for Object types that support heirarchy here, some might not.
 
-                return Services.EntityService.GetChildren(id).Select(Mapper.Map);
+                return Services.EntityService.GetChildren(id, objectType.Value).Select(Mapper.Map)
+                    .WhereNotNull();
             }
             //now we need to convert the unknown ones
             switch (entityType)
@@ -210,7 +137,8 @@ namespace Umbraco.Web.Editors
                 //TODO: Need to check for Object types that support heirarchy here, some might not.
 
                 var ids = Services.EntityService.Get(id).Path.Split(',').Select(int.Parse);
-                return ids.Select(m => Mapper.Map(Services.EntityService.Get(m)));
+                return ids.Select(m => Mapper.Map(Services.EntityService.Get(m, objectType.Value)))
+                    .WhereNotNull();
             }
             //now we need to convert the unknown ones
             switch (entityType)
@@ -233,7 +161,8 @@ namespace Umbraco.Web.Editors
             var objectType = ConvertToObjectType(entityType);
             if (objectType.HasValue)
             {
-                return Services.EntityService.GetAll(objectType.Value).Select(Mapper.Map);
+                return Services.EntityService.GetAll(objectType.Value).Select(Mapper.Map)
+                    .WhereNotNull();
             }
             //now we need to convert the unknown ones
             switch (entityType)
@@ -256,7 +185,8 @@ namespace Umbraco.Web.Editors
             var objectType = ConvertToObjectType(entityType);
             if (objectType.HasValue)
             {
-                return ids.Select(id => Mapper.Map(Services.EntityService.Get(id)));
+                return ids.Select(id => Mapper.Map(Services.EntityService.Get(id, objectType.Value)))
+                          .WhereNotNull();
             }
             //now we need to convert the unknown ones
             switch (entityType)