public bool TryFindExistingMedia(int parentNodeId, string fileName, out Media existingMedia)
        {
            var children = parentNodeId == -1 ? Media.GetRootMedias() : new Media(parentNodeId).Children;
            foreach (var childMedia in children)
            {
                if (childMedia.ContentType.Alias == MediaTypeAlias)
                {
                    var prop = childMedia.getProperty(Constants.Conventions.Media.File);
                    if (prop != null && prop.Value != null)
                    {
                        int subfolderId;
                        var currentValue = prop.Value.ToString();

                        var subfolder = UmbracoSettings.UploadAllowDirectories
                            ? currentValue.Replace(FileSystem.GetUrl("/"), "").Split('/')[0]
                            : currentValue.Substring(currentValue.LastIndexOf("/", StringComparison.Ordinal) + 1).Split('-')[0];
                        
                        if (int.TryParse(subfolder, out subfolderId))
                        {
                            var destFilePath = FileSystem.GetRelativePath(subfolderId, fileName);
                            var destFileUrl = FileSystem.GetUrl(destFilePath);

                            if (prop.Value.ToString() == destFileUrl)
                            {
                                existingMedia = childMedia;
                                return true;
                            }
                        }
                    }
                }
            }

            existingMedia = null;
            return false;
        }
        /// <summary>
        ///   Gets the image property.
        /// </summary>
        /// <returns></returns>
        internal static string GetOriginalUrl(int nodeId, ImageResizerPrevalueEditor imagePrevalueEditor)
        {
            Property imageProperty;
            var node = new CMSNode(nodeId);
            if (node.nodeObjectType == Document._objectType)
            {
                imageProperty = new Document(nodeId).getProperty(imagePrevalueEditor.PropertyAlias);
            }
            else if (node.nodeObjectType == Media._objectType)
            {
                imageProperty = new Media(nodeId).getProperty(imagePrevalueEditor.PropertyAlias);
            }
            else
            {
                if (node.nodeObjectType != Member._objectType)
                {
                    throw new Exception("Unsupported Umbraco Node type for Image Resizer (only Document, Media and Members are supported.");
                }
                imageProperty = new Member(nodeId).getProperty(imagePrevalueEditor.PropertyAlias);
            }

            try
            {
                return imageProperty.Value.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
示例#3
0
        public bool TryFindExistingMedia(int parentNodeId, string fileName, out Media existingMedia)
        {
            var children = parentNodeId == -1 ? Media.GetRootMedias() : new Media(parentNodeId).Children;
            foreach (var childMedia in children)
            {
                if (childMedia.ContentType.Alias == MediaTypeAlias)
                {
                    var prop = childMedia.getProperty("umbracoFile");
                    if (prop != null)
                    {
                        var destFilePath = FileSystem.GetRelativePath(prop.Id, fileName);
                        var destFileUrl = FileSystem.GetUrl(destFilePath);

                        if (prop.Value.ToString() == destFileUrl)
                        {
                            existingMedia = childMedia;
                            return true;
                        }
                    }
                }
            }

            existingMedia = null;
            return false;
        }
        public override void DoHandleMedia(Media media, PostedMediaFile uploadedFile, User user)
        {
            // Get umbracoFile property
            var propertyId = media.getProperty(Constants.Conventions.Media.File).Id;

            // Get paths
            var destFilePath = FileSystem.GetRelativePath(propertyId, uploadedFile.FileName);
            var ext = Path.GetExtension(destFilePath).Substring(1);

            //var absoluteDestPath = HttpContext.Current.Server.MapPath(destPath);
            //var absoluteDestFilePath = HttpContext.Current.Server.MapPath(destFilePath);

            // Set media properties
            media.getProperty(Constants.Conventions.Media.File).Value = FileSystem.GetUrl(destFilePath);
            media.getProperty(Constants.Conventions.Media.Bytes).Value = uploadedFile.ContentLength;

            if (media.getProperty(Constants.Conventions.Media.Extension) != null)
                media.getProperty(Constants.Conventions.Media.Extension).Value = ext;

            // Legacy: The 'extensio' typo applied to MySQL (bug in install script, prior to v4.6.x)
            if (media.getProperty("umbracoExtensio") != null)
                media.getProperty("umbracoExtensio").Value = ext;

            FileSystem.AddFile(destFilePath, uploadedFile.InputStream, uploadedFile.ReplaceExisting);

            // Save media
            media.Save();
        }
        public override void DoHandleMedia(Media media, PostedMediaFile uploadedFile, User user)
        {
            // Get umbracoFile property
            var propertyId = media.getProperty("umbracoFile").Id;

            // Get paths
            var destFilePath = FileSystem.GetRelativePath(propertyId, uploadedFile.FileName);
            var ext = Path.GetExtension(destFilePath).Substring(1);

            //var absoluteDestPath = HttpContext.Current.Server.MapPath(destPath);
            //var absoluteDestFilePath = HttpContext.Current.Server.MapPath(destFilePath);

            // Set media properties
            media.getProperty("umbracoFile").Value = FileSystem.GetUrl(destFilePath);
            media.getProperty("umbracoBytes").Value = uploadedFile.ContentLength;

            if (media.getProperty("umbracoExtension") != null)
                media.getProperty("umbracoExtension").Value = ext;

            if (media.getProperty("umbracoExtensio") != null)
                media.getProperty("umbracoExtensio").Value = ext;

            FileSystem.AddFile(destFilePath, uploadedFile.InputStream, uploadedFile.ReplaceExisting);

            // Save media
            media.Save();
        }
示例#6
0
        public void update(mediaCarrier carrier, string username, string password)
        {

            Authenticate(username, password);

            if (carrier == null) throw new Exception("No carrier specified");

            Media m = new Media(carrier.Id);

            if (carrier.MediaProperties != null)
            {
                foreach (mediaProperty updatedproperty in carrier.MediaProperties)
                {
                    if (!(updatedproperty.Key.ToLower().Equals("umbracofile")))
                    {
                        Property property = m.getProperty(updatedproperty.Key);
                        if (property == null)
                            throw new Exception("property " + updatedproperty.Key + " was not found");
                        property.Value = updatedproperty.PropertyValue;
                    }
                }
            }

            m.Save();
        }
        public void Run(IWorkflowInstance workflowInstance, IWorkflowRuntime runtime)
        {
            // Cast to Umbraco worklow instance.
            var umbracoWorkflowInstance = (UmbracoWorkflowInstance) workflowInstance;

            var count = 0;
            var newCmsNodes = new List<int>();

            foreach(var nodeId in umbracoWorkflowInstance.CmsNodes)
            {
                var n = new CMSNode(nodeId);
                if(!n.IsMedia()) continue;

                var d = new Media(nodeId);
                if (!MediaTypes.Contains(d.ContentType.Id)) continue;
                
                newCmsNodes.Add(nodeId);
                count++;
            }

            umbracoWorkflowInstance.CmsNodes = newCmsNodes;

            var transition = (count > 0) ? "contains_media" : "does_not_contain_media";
            runtime.Transition(workflowInstance, this, transition);
        }
示例#8
0
        public bool Save()
        {
            cms.businesslogic.media.MediaType dt = new cms.businesslogic.media.MediaType(TypeID);
            cms.businesslogic.media.Media     m  = cms.businesslogic.media.Media.MakeNew(Alias, dt, BusinessLogic.User.GetUser(_userID), ParentID);
            _returnUrl = "editMedia.aspx?id=" + m.Id.ToString() + "&isNew=true";

            return(true);
        }
示例#9
0
 private static void TrySetProperty(Media m, string propertyName, string ext)
 {
     try
     {
         m.getProperty(propertyName).Value = ext;
     }
     catch
     {
     }
 }
示例#10
0
        public bool Delete()
        {
            cms.businesslogic.media.Media d = new cms.businesslogic.media.Media(ParentID);

            // Log
            LogHelper.Debug <mediaTasks>(string.Format("Delete media item {0} by user {1}", d.Id, User.GetCurrent().Id));

            d.delete();
            return(true);
        }
示例#11
0
        public bool Delete()
        {
            cms.businesslogic.media.Media d = new cms.businesslogic.media.Media(ParentID);

            // Log
            BusinessLogic.Log.Add(BusinessLogic.LogTypes.Delete, User.GetCurrent(), d.Id, "");

            d.delete();
            return(true);
        }
示例#12
0
        public bool Delete()
        {
            cms.businesslogic.media.Media d = new cms.businesslogic.media.Media(ParentID);

            // Log
            BusinessLogic.Log.Add(BusinessLogic.LogTypes.Delete, User.GetCurrent(), d.Id, "");

            d.delete();
            return true;

        }
示例#13
0
		/// <summary>
		/// Functionally similar to the XPath axis 'ancestor'
		/// </summary>
		/// <param name="media">an umbraco.cms.businesslogic.media.Media object</param>
		/// <returns>Media nodes as IEnumerable</returns>
		public static IEnumerable<Media> GetAncestorMedia(this Media media)
		{
			var ancestor = new Media(media.Parent.Id);

			while (ancestor != null)
			{
				yield return ancestor;

				ancestor = new Media(ancestor.Parent.Id);
			}
		}
示例#14
0
        public bool Delete()
        {
            cms.businesslogic.media.Media d = new cms.businesslogic.media.Media(ParentID);

            // Log
            LogHelper.Debug<mediaTasks>(string.Format("Delete media item {0} by user {1}", d.Id, User.GetCurrent().Id));

            d.delete();
            return true;

        }
示例#15
0
        public bool Delete()
        {
            cms.businesslogic.media.Media d = new cms.businesslogic.media.Media(ParentID);

            // Log
            BasePages.UmbracoEnsuredPage bp = new BasePages.UmbracoEnsuredPage();
            BusinessLogic.Log.Add(BusinessLogic.LogTypes.Delete, bp.getUser(), d.Id, "");

            d.delete();
            return(true);
        }
示例#16
0
        public MediaService(string mediaFolder, string installFolder)
        {
            _mediaFolder   = mediaFolder;
            _installFolder = installFolder;

            _defaultFolderName = "avenue-clothing.com";
            _folderType        = MediaType.GetByAlias("folder");
            _imageType         = MediaType.GetByAlias("image");

            _rootMediaNode = GetRootMediaFolder();
        }
        public override void DoHandleMedia(Media media, PostedMediaFile postedFile, BusinessLogic.User user)
        {
            // Get Image object, width and height
            var image = System.Drawing.Image.FromStream(postedFile.InputStream);
            var fileWidth = image.Width;
            var fileHeight = image.Height;

            // Get umbracoFile property
            var propertyId = media.getProperty("umbracoFile").Id;

            // Get paths
            var destFileName = ConstructDestFileName(propertyId, postedFile.FileName);
            var destPath = ConstructDestPath(propertyId);
            var destFilePath = VirtualPathUtility.Combine(destPath, destFileName);
            var ext = VirtualPathUtility.GetExtension(destFileName).Substring(1);

            var absoluteDestPath = HttpContext.Current.Server.MapPath(destPath);
            var absoluteDestFilePath = HttpContext.Current.Server.MapPath(destFilePath);

            // Set media properties
            media.getProperty("umbracoFile").Value = destFilePath;
            media.getProperty("umbracoWidth").Value = fileWidth;
            media.getProperty("umbracoHeight").Value = fileHeight;
            media.getProperty("umbracoBytes").Value = postedFile.ContentLength;

            if (media.getProperty("umbracoExtension") != null)
                media.getProperty("umbracoExtension").Value = ext;

            if (media.getProperty("umbracoExtensio") != null)
                media.getProperty("umbracoExtensio").Value = ext;

            // Create directory
            if (UmbracoSettings.UploadAllowDirectories)
                Directory.CreateDirectory(absoluteDestPath);

            // Generate thumbnail
            var thumbDestFilePath = Path.Combine(absoluteDestPath, Path.GetFileNameWithoutExtension(destFileName) + "_thumb");
            GenerateThumbnail(image, 100, fileWidth, fileHeight, thumbDestFilePath + ".jpg");

            // Generate additional thumbnails based on PreValues set in DataTypeDefinition uploadField
            GenerateAdditionalThumbnails(image, fileWidth, fileHeight, thumbDestFilePath);

            image.Dispose();

            // Save file
            postedFile.SaveAs(absoluteDestFilePath);

            // Close stream
            postedFile.InputStream.Close();

            // Save media
            media.Save();
        }
示例#18
0
		/// <summary>
		/// Gets all sibling Media
		/// </summary>
		/// <param name="media">an umbraco.cms.businesslogic.media.Media object</param>
		/// <returns>Media nodes as IEnumerable</returns>
		public static IEnumerable<Media> GetSiblingMedia(this Media media)
		{
			if (media.Parent != null)
			{
				var parentMedia = new Media(media.Parent.Id);

				foreach (var siblingMedia in parentMedia.GetChildMedia().Where(childMedia => childMedia.Id != media.Id))
				{
					yield return siblingMedia;
				}
			}
		}
示例#19
0
 /// <summary>
 /// Returns the value for a link in WYSIWYG mode, by default only media items that have a 
 /// DataTypeUploadField are linkable, however, a custom tree can be created which overrides
 /// this method, or another GUID for a custom data type can be added to the LinkableMediaDataTypes
 /// list on application startup.
 /// </summary>
 /// <param name="dd"></param>
 /// <param name="nodeLink"></param>
 /// <returns></returns>
 public virtual string GetLinkValue(Media dd, string nodeLink)
 {
     var props = dd.getProperties;
     foreach (Property p in props)
     {
         Guid currId = p.PropertyType.DataTypeDefinition.DataType.Id;
         if (LinkableMediaDataTypes.Contains(currId) &&  !String.IsNullOrEmpty(p.Value.ToString()))
         {
             return p.Value.ToString();
         }
     }
     return "";
 }
        public System.Xml.Linq.XElement GetProperty(umbraco.cms.businesslogic.property.Property prop)
        {
            //get access to media item based on some path.
            try
            {
                var mediaItem = new Media(int.Parse(prop.Value.ToString()));

                return new XElement(prop.PropertyType.Alias, mediaItem.ConfigPath());
            }
            catch { }

            return  new XElement(prop.PropertyType.Alias, "");
        }
        public virtual bool CanHandleMedia(int parentNodeId, PostedMediaFile postedFile, User user)
        {
            try
            {
                var parentNode = new Media(parentNodeId);

                return parentNodeId <= -1 || user.Applications.Any(app => app.alias.ToLower() == Constants.Applications.Media) && (user.StartMediaId <= 0 || ("," + parentNode.Path + ",").Contains("," + user.StartMediaId + ",")) && parentNode.ContentType.AllowedChildContentTypeIDs.Contains(MediaType.GetByAlias(MediaTypeAlias).Id);
            }
            catch
            {
                return false;
            }
        }
示例#22
0
        private void CreateImageProperties(FileInfo file, Media item, string ext)
        {
            using (var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var image      = Image.FromStream(fs);
                int fileWidth  = image.Width;
                int fileHeight = image.Height;

                TrySetProperty(item, "umbracoWidth", fileWidth.ToString());
                TrySetProperty(item, "umbracoHeight", fileHeight.ToString());

                Mini(file, ext, image, fileWidth, fileHeight);
            }
        }
示例#23
0
        public static Media GetMedia(int mediaId)
        {
            Media media = null;

            try
            {
                media = new Media(mediaId);
                if (media.nodeObjectType != Media._objectType)
                {
                    media = null;
                }
            }
            catch { }
            return media;
        }
示例#24
0
        /// <summary>
        /// Creates a new Media
        /// </summary>
        /// <param name="Name">The name of the media</param>
        /// <param name="dct">The type of the media</param>
        /// <param name="u">The user creating the media</param>
        /// <param name="ParentId">The id of the folder under which the media is created</param>
        /// <returns></returns>
        public static Media MakeNew(string Name, MediaType dct, BusinessLogic.User u, int ParentId)
        {
            Guid newId = Guid.NewGuid();
            // Updated to match level from base node
            CMSNode n = new CMSNode(ParentId);
            int newLevel = n.Level;
            newLevel++;
            CMSNode.MakeNew(ParentId, _objectType, u.Id, newLevel, Name, newId);
            Media tmp = new Media(newId);
            tmp.CreateContent(dct);

            NewEventArgs e = new NewEventArgs();
            tmp.OnNew(e);

            return tmp;
        }
 /// <summary>
 ///   Initializes a new instance of the <see cref = "TextImageParameters" /> class.
 /// </summary>
 /// <param name = "textString">The node property.</param>
 /// <param name = "outputFormat">The output format.</param>
 /// <param name = "customFontPath">The custom font path.</param>
 /// <param name = "fontName">Name of the font.</param>
 /// <param name = "fontSize">Size of the font.</param>
 /// <param name = "fontStyles">The font style.</param>
 /// <param name = "foreColor">Color of the fore.</param>
 /// <param name = "backColor">Color of the back.</param>
 /// <param name = "shadowColor">Color of the shadow.</param>
 /// <param name = "hAlign">The h align.</param>
 /// <param name = "vAlign">The v align.</param>
 /// <param name = "canvasHeight">Height of the canvas.</param>
 /// <param name = "canvasWidth">Width of the canvas.</param>
 /// <param name = "backgroundMedia">The background image.</param>
 public TextImageParameters(string textString, OutputFormat outputFormat, string customFontPath, string fontName,
                            int fontSize, FontStyle[] fontStyles, string foreColor, string backColor,
                            string shadowColor, HorizontalAlignment hAlign, VerticalAlignment vAlign,
                            int canvasHeight, int canvasWidth, Media backgroundMedia)
 {
     _text = textString;
     _outputFormat = outputFormat;
     _customFontPath = customFontPath;
     _fontName = fontName;
     _fontSize = fontSize;
     _fontStyles = fontStyles;
     _foreColor = foreColor;
     _backColor = backColor;
     _hAlign = hAlign;
     _vAlign = vAlign;
     _canvasHeight = canvasHeight;
     _canvasWidth = canvasWidth;
     _shadowColor = shadowColor;
     _backgroundMedia = backgroundMedia;
 }
 void Media_AfterSave(Media sender, umbraco.cms.businesslogic.SaveEventArgs e)
 {
     try
     {
         if (Configuration.Settings.Enabled)
             if (Kraken.GetKrakStatus(sender) == EnmIsKrakable.Krakable)
             {
                 // In elkaar krakken
                 var result = Kraken.Compress(sender);
                 // Goed uitgekrakt?
                 if (result != null && result.success)
                     // Opslaan in Umbraco
                     result.Save(sender);
             }
     }
     catch
     {
         // Als de hel los breekt, ga dan in ieder geval door. Anders verpesten we (mogelijK) de media save event voor de gebruiker
     }
 }
示例#27
0
        public void MediaType_Delete_Media_Type_With_Media_And_Children_Of_Diff_Media_Types()
        {
            //System.Diagnostics.Debugger.Break();

            //create the doc types 
            var mt1 = CreateNewMediaType();
            var mt2 = CreateNewMediaType();
            var mt3 = CreateNewMediaType();

            //create the heirarchy
            mt1.AllowedChildContentTypeIDs = new int[] { mt2.Id, mt3.Id };
            mt1.Save();
            mt2.AllowedChildContentTypeIDs = new int[] { mt1.Id };
            mt2.Save();

            //create the content tree
            var node1 = Media.MakeNew("TEST" + Guid.NewGuid().ToString("N"), mt1, m_User, -1);
            var node2 = Media.MakeNew("TEST" + Guid.NewGuid().ToString("N"), mt2, m_User, node1.Id);
            var node3 = Media.MakeNew("TEST" + Guid.NewGuid().ToString("N"), mt1, m_User, node2.Id);
            var node4 = Media.MakeNew("TEST" + Guid.NewGuid().ToString("N"), mt3, m_User, node3.Id);

            //do the deletion of doc type #1
            DeleteMediaType(mt1);

            //do our checks
            Assert.IsFalse(Media.IsNode(node1.Id), "node1 is not deleted"); //this was of doc type 1, should be gone
            Assert.IsFalse(Media.IsNode(node3.Id), "node3 is not deleted"); //this was of doc type 1, should be gone

            Assert.IsTrue(Media.IsNode(node2.Id), "node2 is deleted");
            Assert.IsTrue(Media.IsNode(node4.Id), "node4 is deleted");

            node2 = new Media(node2.Id);//need to re-query the node
            Assert.IsTrue(node2.IsTrashed, "node2 is not in the trash");
            node4 = new Media(node4.Id); //need to re-query the node
            Assert.IsTrue(node4.IsTrashed, "node 4 is not in the trash");

            //remove the old data
            DeleteMediaType(mt2);
            DeleteMediaType(mt3);

        }
		private void LookupData()
		{
            if (MediaId > 0 && Media.IsNode(MediaId))
            {
                Media m = new Media(MediaId);

                // TODO: Remove "Magic strings" from code.
                var pFile = m.getProperty("fileName");
                if (pFile == null) pFile = m.getProperty("umbracoFile");
                if (pFile == null) pFile = m.getProperty("file");
                if (pFile == null)
                {
                    //the media requested does not correspond with the standard umbraco properties
                    return;
                }

                MediaItemPath = pFile.Value != null && !string.IsNullOrEmpty(pFile.Value.ToString())
                    ? IOHelper.ResolveUrl(pFile.Value.ToString())
                    : "#";
                AltText = MediaItemPath != "#" ? m.Text : ui.GetText("no") + " " + ui.GetText("media");

                var pWidth = m.getProperty("umbracoWidth");
                var pHeight = m.getProperty("umbracoHeight");

                if (pWidth != null && pWidth.Value != null && pHeight != null && pHeight.Value != null)
                {
                    int.TryParse(pWidth.Value.ToString(), out m_FileWidth);
                    int.TryParse(pHeight.Value.ToString(), out m_FileHeight);
                }

                string ext = MediaItemPath.Substring(MediaItemPath.LastIndexOf(".") + 1, MediaItemPath.Length - MediaItemPath.LastIndexOf(".") - 1);
                MediaItemThumbnailPath = MediaItemPath.Replace("." + ext, "_thumb.jpg");

                ImageFound = true;
            }
            else
            {
                ImageFound = false;
            }
        }
示例#29
0
        /// <summary>
        /// Gets the HTML for file.
        /// </summary>
        /// <param name="media">The media.</param>
        /// <returns></returns>
        private string GetHtmlForFile(Media media)
        {
            // check that its not null
            if (media != null)
            {
                // get the img src
                var file = media.GetProperty<string>(Constants.Umbraco.Media.File);

                // check that the file has a value
                if (!string.IsNullOrEmpty(file))
                {
                    // define the anchor tag
                    var anchor = "<a href=\"{0}\">{1}</a>";

                    // format the anchor tag
                    return string.Format(anchor, file, media.Text);
                }
            }

            // fall-back return an empty string
            return string.Empty;
        }
示例#30
0
        public DataTable GetRelations(object id)
        {
            var usages = new List<Document>();

            // Media Picker
            using (var reader = Application.SqlHelper.ExecuteReader("SELECT DISTINCT contentNodeId FROM cmsPropertyData WHERE dataInt=@0", new SqlServerParameter("0", id)))
            {
                while (reader.Read())
                {
                    usages.Add(new Document(reader.GetInt("contentNodeId")));
                }
            }

            // RTE
            var media = new Media((int) id);
            if (media != null)
            {
                var file = media.getProperty("umbracoFile");
                if (file != null)
                {
                    var filePath = file.Value;

                    using (var reader = Application.SqlHelper.ExecuteReader("SELECT DISTINCT contentNodeId FROM cmsPropertyData WHERE (dataNtext LIKE '%' + @0 + '%' or dataNvarchar LIKE '%' + @0 + '%') AND contentNodeId <> @1", new SqlServerParameter("0", filePath), new SqlServerParameter("1", id)))
                    {
                        while (reader.Read())
                        {
                            usages.Add(new Document(reader.GetInt("contentNodeId")));
                        }
                    }

                }
            }

            // TODO: MNTP
            // TODO: DAMP

            return UmbracoObject.Content.ToDataTable(usages);
        }
        internal static Kraken Compress(Media umbracoMedia, bool? wait = null)
        {
            if (umbracoMedia == null || umbracoMedia.Id == 0)
                throw new ArgumentException("Invalid Umbraco Media node", "umbracoMedia");

            var p = umbracoMedia.getProperty(Constants.UmbracoPropertyAliasFile);
            if (p != null && p.Value != null)
            {
                string img = p.Value.ToString();
                Kraken result = null;

                try
                {
                    result = Compress(img, wait); // UPLOAD
                }
                catch (KrakenException)
                {
                    try
                    {
                        string imageUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + img;
                        Uri uri;
                        if (Uri.TryCreate(imageUrl, UriKind.Absolute, out uri))
                            result = Compress(uri, wait); // URI
                    }
                    catch (KrakenException)
                    {

                    }
                }
                if (result != null)
                    result.MediaId = umbracoMedia.Id;
                return result;
            }
            else
                throw new Exception("Target Umbraco media item has no file");
        }
示例#32
0
        private Media UmbracoSave(FileInfo file, Media parent)
        {
            if (file == null || !file.Exists)
            {
                return(null);
            }

            var ext  = file.Extension.Replace(".", string.Empty).ToLower();
            var item = CreateMediaImage(file.Name, parent.Id);

            var relativePath = string.Concat("/media/", item.Id, "/" + file.Name);
            var mediaFolder  = Path.Combine(_mediaFolder, item.Id.ToString());

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

            var fullFilePath = Path.Combine(mediaFolder, file.Name);

            file.CopyTo(fullFilePath);

            TrySetProperty(item, "umbracoExtension", ext);
            TrySetProperty(item, "umbracoBytes", file.Length.ToString());
            TrySetProperty(item, "umbracoFile", relativePath);
            item.Save();

            if (_thumbnailExtensions.Contains(ext))
            {
                CreateImageProperties(new FileInfo(fullFilePath), item, ext);
            }

            item.XmlGenerate(new XmlDocument());

            return(item);
        }
示例#33
0
        public void ProcessFolderListRequest(HttpContext context, XmlTextWriter xmlTextWriter)
        {
            xmlTextWriter.WriteStartElement("folder");

            var startMediaId = AuthenticatedUser.StartMediaId;
            if (startMediaId < 1)
            {
                xmlTextWriter.WriteAttributeString("id", "-1");
                xmlTextWriter.WriteAttributeString("name", "Media");

                CreateMediaTree(Media.GetRootMedias(), xmlTextWriter);
            }
            else
            {
                var root = new Media(startMediaId);

                xmlTextWriter.WriteAttributeString("id", root.Id.ToString());
                xmlTextWriter.WriteAttributeString("name", root.Text);

                CreateMediaTree(root.Children, xmlTextWriter);
            }

            xmlTextWriter.WriteEndElement();
        }
示例#34
0
        protected override void OnInit(EventArgs e)
        {
            this.ID = "ImageCropper";
            //base.OnInit(e);

            int propertyId = ((umbraco.cms.businesslogic.datatype.DefaultData)data).PropertyId;

            int currentDocumentId = ((umbraco.cms.businesslogic.datatype.DefaultData)data).NodeId;
            Property uploadProperty;

            // we need this ugly code because there's no way to use a base class
            CMSNode node = new CMSNode(currentDocumentId);
            if (node.nodeObjectType == Document._objectType)
            {
                uploadProperty = new Document(currentDocumentId).getProperty(config.UploadPropertyAlias);
            }
            else if (node.nodeObjectType == umbraco.cms.businesslogic.media.Media._objectType)
            {
                uploadProperty = new Media(currentDocumentId).getProperty(config.UploadPropertyAlias);
            }
            else if (node.nodeObjectType == Member._objectType)
            {
                uploadProperty = new Member(currentDocumentId).getProperty(config.UploadPropertyAlias);
            }
            else
            {
                throw new Exception("Unsupported Umbraco Node type for Image Cropper (only Document, Media and Members are supported.");
            }

            // upload property could be null here if the property wasn't found
            if (uploadProperty != null)
            {
                string relativeImagePath = uploadProperty.Value.ToString();

                ImageInfo imageInfo = new ImageInfo(relativeImagePath);

                imgImage.ImageUrl = relativeImagePath;
                imgImage.ID = String.Format("cropBox_{0}", propertyId);

                StringBuilder sbJson = new StringBuilder();
                StringBuilder sbRaw = new StringBuilder();

                try
                {
                    _xml = new XmlDocument();
                    _xml.LoadXml(data.Value.ToString());
                }
                catch
                {
                    _xml = createBaseXmlDocument();
                }

                sbJson.Append("{ \"current\": 0, \"crops\": [");

                for (int i = 0; i < config.presets.Count; i++)
                {
                    Preset preset = (Preset)config.presets[i];
                    Crop crop;

                    sbJson.Append("{\"name\":'" + preset.Name + "'");

                    sbJson.Append(",\"config\":{" +
                                  String.Format("\"targetWidth\":{0},\"targetHeight\":{1},\"keepAspect\":{2}",
                                                preset.TargetWidth, preset.TargetHeight,
                                                (preset.KeepAspect ? "true" : "false") + "}"));

                    if (imageInfo.Exists)
                    {
                        crop = preset.Fit(imageInfo);
                    }
                    else
                    {
                        crop.X = 0;
                        crop.Y = 0;
                        crop.X2 = preset.TargetWidth;
                        crop.Y2 = preset.TargetHeight;
                    }

                    // stored
                    if (_xml.DocumentElement != null && _xml.DocumentElement.ChildNodes.Count == config.presets.Count)
                    {
                        XmlNode xmlNode = _xml.DocumentElement.ChildNodes[i];

                        int xml_x = Convert.ToInt32(xmlNode.Attributes["x"].Value);
                        int xml_y = Convert.ToInt32(xmlNode.Attributes["y"].Value);
                        int xml_x2 = Convert.ToInt32(xmlNode.Attributes["x2"].Value);
                        int xml_y2 = Convert.ToInt32(xmlNode.Attributes["y2"].Value);

                        // only use xml values if image is the same and different from defaults (document is stored inbetween image upload and cropping)
                        //if (xml_x2 - xml_x != preset.TargetWidth || xml_y2 - xml_y != preset.TargetHeight)
                        //fileDate == imageInfo.DateStamp && (

                        if (crop.X != xml_x || crop.X2 != xml_x2 || crop.Y != xml_y || crop.Y2 != xml_y2)
                        {
                            crop.X = xml_x;
                            crop.Y = xml_y;
                            crop.X2 = xml_x2;
                            crop.Y2 = xml_y2;
                        }
                    }

                    sbJson.Append(",\"value\":{" + String.Format("\"x\":{0},\"y\":{1},\"x2\":{2},\"y2\":{3}", crop.X, crop.Y, crop.X2, crop.Y2) + "}}");
                    sbRaw.Append(String.Format("{0},{1},{2},{3}", crop.X, crop.Y, crop.X2, crop.Y2));

                    if (i < config.presets.Count - 1)
                    {
                        sbJson.Append(",");
                        sbRaw.Append(";");
                    }
                }

                sbJson.Append("]}");

                hdnJson.Value = sbJson.ToString();
                //hdnJson.ID = String.Format("json_{0}", propertyId);
                hdnRaw.Value = sbRaw.ToString();
                //hdnRaw.ID = String.Format("raw_{0}", propertyId);

                Controls.Add(imgImage);

                Controls.Add(hdnJson);
                Controls.Add(hdnRaw);

                string imageCropperInitScript =
                    "initImageCropper('" +
                    imgImage.ClientID + "', '" +
                    hdnJson.ClientID + "', '" +
                    hdnRaw.ClientID +
                    "');";

                Page.ClientScript.RegisterStartupScript(GetType(), ClientID + "_imageCropper", imageCropperInitScript, true);
                Page.ClientScript.RegisterClientScriptBlock(Resources.json2Script.GetType(), "json2Script", Resources.json2Script, true);
                Page.ClientScript.RegisterClientScriptBlock(Resources.jCropCSS.GetType(), "jCropCSS", Resources.jCropCSS);
                Page.ClientScript.RegisterClientScriptBlock(Resources.jCropScript.GetType(), "jCropScript", Resources.jCropScript, true);
                Page.ClientScript.RegisterClientScriptBlock(Resources.imageCropperScript.GetType(), "imageCropperScript", Resources.imageCropperScript, true);

            }

            base.OnInit(e);
        }
示例#35
0
        public FolderListResponse ProcessFolderListRequest(HttpContext context)
        {
            var response = new FolderListResponse
            {
                folder = new FolderListItem()
            };

            var startMediaId = AuthenticatedUser.StartMediaId;
            if (startMediaId < 1)
            {
                response.folder.id = -1;
                response.folder.name = "Media";

                CreateMediaTree(Media.GetRootMedias(), response.folder);
            }
            else
            {
                var root = new Media(startMediaId);

                response.folder.id = root.Id;
                response.folder.name = root.Text;

                CreateMediaTree(root.Children, response.folder);
            }

            return response;
        }
示例#36
0
        private Media GetImageFromFolder(string folder, string filename, Media parent)
        {
            var file = LookForFile(folder, filename);

            return(file == null ? null : UmbracoSave(file, parent));
        }
示例#37
0
        public UploadResponse ProcessUploadRequest(HttpContext context)
        {
            int parentNodeId;
            if (int.TryParse(context.Request["parentNodeId"], out parentNodeId) && context.Request.Files.Count > 0)
            {
                try
                {
                    var parentNode = new Media(parentNodeId);
                    // Check FilePath
                    if (!string.IsNullOrEmpty(context.Request["path"]))
                    {
                        var pathParts = context.Request["path"].Trim('/').Split('/');
                        
                        foreach (var pathPart in pathParts.Where(part => string.IsNullOrWhiteSpace(part) == false))
                                parentNode = GetOrCreateFolder(parentNode, pathPart);

                        parentNodeId = parentNode.Id;
                    }

                    // Check whether to replace existing
                    bool parsed;
                    var replaceExisting = (context.Request["replaceExisting"] == "1" || (bool.TryParse(context.Request["replaceExisting"], out parsed) && parsed));

                    // loop through uploaded files
                    for (var j = 0; j < context.Request.Files.Count; j++)
                    {
                        // get the current file
                        var uploadFile = context.Request.Files[j];

                        using (var inputStream = uploadFile.InputStream)
                        {
                            // if there was a file uploded
                            if (uploadFile.ContentLength > 0)
                            {
                                // Ensure we get the filename without the path in IE in intranet mode 
                                // http://stackoverflow.com/questions/382464/httppostedfile-filename-different-from-ie
                                var fileName = uploadFile.FileName;
                                if (fileName.LastIndexOf(@"\") > 0)
                                    fileName = fileName.Substring(fileName.LastIndexOf(@"\") + 1);

                                fileName = Umbraco.Core.IO.IOHelper.SafeFileName(fileName);

                                var postedMediaFile = new PostedMediaFile
                                {
                                    FileName = fileName,
                                    DisplayName = context.Request["name"],
                                    ContentType = uploadFile.ContentType,
                                    ContentLength = uploadFile.ContentLength,
                                    InputStream = inputStream,
                                    ReplaceExisting = replaceExisting
                                };

                                // Get concrete MediaFactory
                                var factory = MediaFactory.GetMediaFactory(parentNodeId, postedMediaFile, AuthenticatedUser);

                                // Handle media Item
                                var media = factory.HandleMedia(parentNodeId, postedMediaFile, AuthenticatedUser);
                            }
                        }
                    }

                    var scripts = new ClientTools(new Page());
                    scripts.SyncTree(parentNode.Path, true);

                    // log succes
                    LogHelper.Info<MediaUploader>(string.Format("Success uploading to parent {0}", parentNodeId));
                }
                catch (Exception e)
                {
                    // log error
                    LogHelper.Error<MediaUploader>(string.Format("Error uploading to parent {0}", parentNodeId), e);
                }
            }
            else
            {
                // log error
                LogHelper.Warn<MediaUploader>(string.Format("Parent node id is in incorrect format: {0}", parentNodeId));
            }
            
            return new UploadResponse();
        }
示例#38
0
        private Media GetOrCreateFolder(Media parent, string name)
        {
            var children = parent.Id == -1 ? Media.GetRootMedias() : parent.Children;
            if (children.Length > 0)
            {
                foreach (var node in children.Where(node => node.Text.ToLower() == name.ToLower()))
                {
                    return node;
                }
            }

            var media = Media.MakeNew(name, MediaType.GetByAlias(Constants.Conventions.MediaTypes.Folder), User.GetUser(0), parent.Id);
            media.sortOrder = 0;
            media.Save();

            return media;
        }
示例#39
0
        private Media GetOrCreateMediaFolder(string folderName, int parentId)
        {
            var folders = Media.GetMediaOfMediaType(_folderType.Id);

            return(folders.FirstOrDefault(f => f.Text == folderName && (f.ParentId == parentId || parentId == -1)) ?? CreateMediaFolder(folderName, parentId));
        }
 public abstract void DoHandleMedia(Media media, PostedMediaFile uploadedFile, User user);
示例#41
0
        private Media CreateMediaFolder(string folderName, int parentId)
        {
            var media = Media.MakeNew(folderName, _folderType, new User(0), parentId);

            return(media);
        }
示例#42
0
 private Media CreateMediaImage(string imageName, int parentId)
 {
     return(Media.MakeNew(imageName, _imageType, new User(0), parentId));
 }
示例#43
0
 public abstract void DoHandleMedia(Media media, PostedMediaFile uploadedFile, User user);