public void DeleteFile(AttachmentBE attachment, SizeType size) {
     if (!attachment.IsHeadRevision()) {
         throw new DreamInternalErrorException(DekiResources.CAN_ONLY_DELETE_HEAD_REVISION);
     }
     for (int i = 1; i <= attachment.Content.Revision; i++) {
         string filename = FilePath(attachment, size);
         try {
             File.Delete(filename);                    
         } catch { }
     }
 }
Beispiel #2
0
        private static void FSToS3(AttachmentBE[] attachmentList) {
            XDoc s3config = new XDoc("config")
                .Start("publickey").Value(_public_key).End()
                .Start("privatekey").Value(_private_key).End()
                .Start("bucket").Value(_default_bucket).End()
                .Start("prefix").Value(_prefix).End();
            S3Storage s3 = new S3Storage(s3config);

            XDoc fsconfig = new XDoc("config")
                .Start("path").Value(_attachmentPath).End();
            FSStorage fs = new FSStorage(fsconfig);

            transferFiles(attachmentList, fs, s3);
        }
        //--- Methods ---
        public StreamInfo GetFile(AttachmentBE attachment, SizeType size, bool allowFileLink) {
            MimeType mime;

            switch (size) {
            case SizeType.THUMB:
            case SizeType.WEBVIEW:
                mime = AttachmentPreviewBL.ResolvePreviewMime(attachment.MimeType);
                break;
            default:
                mime = attachment.MimeType;
                break;
            }

            return GetFileInternal(FilePath(attachment, size), mime);
        }
 private string FilePath(AttachmentBE file, SizeType size) {
     return FilePath(file.ResourceId, file.Content.Revision ?? 0, size);
 }
 private void AttachmentChanged(DateTime eventTime, AttachmentBE attachment, params string[] path) {
     try {
         XUri channel = _channel.At(FILES).At(path);
         XUri attachmentUri = AttachmentBL.Instance.GetUri(attachment);
         XUri resource = attachmentUri.WithHost(_wikiid);
         string[] origin = new string[] { attachmentUri.AsServerUri().ToString() };
         Queue(eventTime, channel, resource, origin, new XDoc("deki-event")
             .Elem("channel", channel)
             .Elem("fileid", attachment.FileId ?? 0)
             .Elem("uri", attachmentUri.AsServerUri().ToString())
             .Elem("content.uri", attachmentUri.AsServerUri().ToString())
             .Elem("revision.uri", attachmentUri.At("info").With("revision", attachment.Revision.ToString()).AsServerUri().ToString())
             .Elem("path", attachmentUri.Path));
     } catch(Exception e) {
         _log.WarnExceptionMethodCall(e, "AttachmentChanged", "event couldn't be created");
     }
 }
 public void AttachmentPoke(DateTime eventTime, AttachmentBE attachment) {
     AttachmentChanged(eventTime, attachment, NO_OP);
 }
 public void AttachmentRestore(DateTime eventTime, AttachmentBE attachment, UserBE user) {
     PageDependentChanged(eventTime, ((PageWrapperBE)attachment.ParentResource).Page, user, FILES, RESTORE);
     AttachmentChanged(eventTime, attachment, RESTORE);
 }
 private static StreamInfo GetCachedThumb(AttachmentBE attachment, SizeType size) {
     StreamInfo result = null;
     if(size == SizeType.THUMB || size == SizeType.WEBVIEW) {
         result = DekiContext.Current.Instance.Storage.GetFile(attachment, size, false);
     }                 
     return result;
 }
 private static StreamInfo BuildThumb(AttachmentBE attachment, StreamInfo file, FormatType format, RatioType ratio, uint width, uint height) {
     if (!AttachmentBL.Instance.IsAllowedForImageMagickPreview(attachment)) {
         return file;
     }             
     return BuildThumb(file, format, ratio, width, height);
 }
 public void MoveFile(AttachmentBE attachment, PageBE targetPage) {
     //do nothing.
 }
Beispiel #11
0
        private static void transferFiles(AttachmentBE[] attachmentList, IStorageProvider source, IStorageProvider dest) {
            foreach(AttachmentBE attachment in attachmentList) {
                StreamInfo sourceInfo;

                try {
                    if(attachment.Revision > 1) {
                        // loop through all the attachments
                        foreach(AttachmentBE attRev in GetRevisions(attachment)) {
                            Console.WriteLine("Migrating: " + attachment.Name + ", rev: " + attRev.Revision);
                            sourceInfo = source.GetFile(attRev, SizeType.ORIGINAL, false);
                            if(sourceInfo != null) {
                                dest.PutFile(attRev, SizeType.ORIGINAL, sourceInfo);
                            }
                        }
                    } else {
                        Console.WriteLine("Migrating: " + attachment.Name + ", rev: 1");
                        sourceInfo = source.GetFile(attachment, SizeType.ORIGINAL, false);
                        if(sourceInfo != null) {
                            dest.PutFile(attachment, SizeType.ORIGINAL, sourceInfo);
                        }
                    }
                } catch(Exception e) {
                    Console.WriteLine(e.Message);
                }
            }
        }
        private void PropertyExport(PageBE page, AttachmentBE file, PropertyBE property) {

            // Export the property
            XUri propertyUri = null;
            string filename = null;
            if(null != file) {
                propertyUri = property.UriContent(AttachmentBL.Instance.GetUri(file));
                filename = file.Name;
            } else {
                propertyUri = property.UriContent(PageBL.GetUriCanonical(page));
            }
            if(!_uris.ContainsKey(propertyUri)) {
                _uris.Add(propertyUri, null);
                XDoc manifestDoc = new XDoc("property").Elem("name", property.Name)
                                                       .Elem("filename", filename)
                                                       .Elem("path", page.Title.AsRelativePath(_relToTitle))
                                                       .Start("contents").Attr("type", property.MimeType.ToString()).End();
                Add(propertyUri, manifestDoc);
            }
        }
        private void AttachmentExport(ExportExcludeType exclude, PageBE page, AttachmentBE file) {

            // Export the file
            if(!_uris.ContainsKey(AttachmentBL.Instance.GetUriContent(file))) {
                _uris.Add(AttachmentBL.Instance.GetUriContent(file), null);
                XDoc manifestDoc = new XDoc("file").Elem("filename", file.Name)
                                                   .Elem("path", page.Title.AsRelativePath(_relToTitle))
                                                   .Start("contents").Attr("type", file.MimeType.ToString()).End();
                Add(AttachmentBL.Instance.GetUriContent(file), manifestDoc);
            }

            // Export the file properties (if not excluded)
            if(ExportExcludeType.NONE == (ExportExcludeType.PROPS & exclude)) {
                IList<PropertyBE> properties = PropertyBL.Instance.GetResources(file.ResourceId, ResourceBE.Type.FILE, null, DeletionFilter.ACTIVEONLY);
                foreach(PropertyBE property in properties) {
                    PropertyExport(page, file, property);
                }
            }
        }
 internal Hashtable MakeFileObject(AttachmentBE file) {
     Hashtable result = new Hashtable(StringComparer.OrdinalIgnoreCase);
     if((file != null) && PermissionsBL.IsUserAllowed(DekiContext.Current.User, PageBL.GetPageById(file.ParentPageId), Permissions.READ)) {
         result.Add("editsummary", file.ChangeDescription);
         result.Add("description", PropertyAt("$filedesc", file.ResourceId));
         result.Add("name", file.Name);
         result.Add("id", file.FileId);
         result.Add("size", file.Size);
         result.Add("page", PropertyAt("$page", file.ParentPageId));
         result.Add("mime", file.MimeType.FullType);
         result.Add("date", DekiScriptLibrary.CultureDateTime(file.Timestamp));
         result.Add("author", PropertyAt("$user", file.UserId));
         result.Add("api", Utils.AsPublicApiUri("files", file.FileId ?? 0).ToString());
         result.Add("uri", Utils.AsPublicApiUri("files", file.FileId ?? 0).At("=" + XUri.DoubleEncodeSegment(file.Name)).ToString());
         int? width = file.ImageWidth;
         result.Add("imagewidth", width);
         result.Add("imageheight", file.ImageHeight);
         result.Add("imageframes", width.HasValue ? (object)(file.ImageFrames ?? 1) : null);
         result.Add("thumburi", width.HasValue ? AttachmentBL.Instance.GetUriContent(file).With("size", "thumb") : null);
         result.Add("webviewuri", width.HasValue ? AttachmentBL.Instance.GetUriContent(file).With("size", "webview") : null);
         result.Add("properties", PropertyAt("$fileprops", file.ResourceId));
     }
     return result;
 }
        public static StreamInfo RetrievePreview(AttachmentBE attachment, uint height, uint width, RatioType ratio, SizeType size, FormatType format, out string filename) {
            if (!AttachmentBL.Instance.IsAllowedForImageMagickPreview(attachment)) {
                throw new DreamAbortException(DreamMessage.NotImplemented(string.Format(DekiResources.FAILED_WITH_MIME_TYPE, attachment.MimeType)));
            }
            if(format != FormatType.UNDEFINED && size != SizeType.UNDEFINED && size != SizeType.ORIGINAL && size != SizeType.CUSTOM) {
                throw new DreamAbortException(DreamMessage.NotImplemented(DekiResources.FORMAT_CONVERSION_WITH_SIZE_UNSUPPORTED));
            }

            // check that attachment has a width and height defined
            AttachmentBL.Instance.IdentifyUnknownImages(new AttachmentBE[] { attachment });

            #region check validity of size, width, and height parameters

            // NOTE (steveb): following table describes the possible state-transitions; note that the resulting graph must acyclic to avoid infinite loops.
            //      BESTFIT
            //          -> THUMB
            //          -> WEBVIEW
            //          -> ORIGINAL
            //      UNDEFINED
            //          -> CUSTOM
            //          -> ORIGINAL
            //      THUMB
            //          -> ORIGINAL
            //      WEBVIEW
            //          -> ORIGINAL
            //      CUSTOM
            //          -> ORIGINAL
            //      ORIGINAL
        again:
            switch(size) {
            case SizeType.BESTFIT:
                if(width == 0 && height == 0) {

                    // no dimensions specified, use original
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                if(width <= DekiContext.Current.Instance.ImageThumbPixels && height <= DekiContext.Current.Instance.ImageThumbPixels) {

                    // thumbnail is big enough
                    size = SizeType.THUMB;
                    goto again;
                } else if(width <= DekiContext.Current.Instance.ImageWebviewPixels && height <= DekiContext.Current.Instance.ImageWebviewPixels) {

                    // webview is big enough
                    size = SizeType.WEBVIEW;
                    goto again;
                } else {

                    // use original
                    size = SizeType.ORIGINAL;
                    goto again;
                }
            case SizeType.CUSTOM:
                if(height == 0 && width == 0) {

                    // no dimensions specified, use original
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                if((attachment.ImageWidth <= width && attachment.ImageHeight <= height) && (attachment.ImageWidth >= 0 && attachment.ImageHeight >= 0)) {

                    // requested dimensions are larger than original, use original (we don't scale up!)
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                break;
            case SizeType.ORIGINAL:
                width = 0;
                height = 0;
                break;
            case SizeType.UNDEFINED:
                if(height != 0 || width != 0) {
                    size = SizeType.CUSTOM;
                    goto again;
                } else {
                    size = SizeType.ORIGINAL;
                    goto again;
                }
            case SizeType.THUMB:
                width = DekiContext.Current.Instance.ImageThumbPixels;
                height = DekiContext.Current.Instance.ImageThumbPixels;
                if((attachment.ImageWidth <= width && attachment.ImageHeight <= height) && (attachment.ImageWidth >= 0 && attachment.ImageHeight >= 0)) {
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                break;
            case SizeType.WEBVIEW:
                width = DekiContext.Current.Instance.ImageWebviewPixels;
                height = DekiContext.Current.Instance.ImageWebviewPixels;
                if((attachment.ImageWidth <= width && attachment.ImageHeight <= height) && (attachment.ImageWidth >= 0 && attachment.ImageHeight >= 0)) {
                    size = SizeType.ORIGINAL;
                    goto again;
                }
                break;
            }
            #endregion


            // Asking to convert to the same format as original
            if(format != FormatType.UNDEFINED && format == ResolvePreviewFormat(attachment.MimeType)) {
                format = FormatType.UNDEFINED;
            }

            //Determine if the result is capable of being cached
            bool cachable = (
                format == FormatType.UNDEFINED       //No format conversion
                && ratio != RatioType.VARIABLE       //must be a fixed aspect ratio or not provided
                && (size == SizeType.THUMB || size == SizeType.WEBVIEW)  //must be one of the known cached thumb sizes.
            );

            // load image
            StreamInfo result = null;
            try {
                if(size == SizeType.ORIGINAL && format == FormatType.UNDEFINED) {
                    result = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
                } else {
                    bool cached = false;

                    //The type of image is based on uploaded file's mimetype
                    if(format == FormatType.UNDEFINED) {
                        format = ResolvePreviewFormat(attachment.MimeType);
                    }

                    // check if image can be taken from the cache
                    if(cachable) {
                        result = GetCachedThumb(attachment, size);
                        cached = (result != null);
                    }

                    // load image if we haven't yet
                    if(result == null) {
                        result = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
                        if(result != null) {
                            result = BuildThumb(attachment, result, format, ratio, width, height);
                        }
                    }

                    // store result if possible and needed
                    if(cachable && !cached && (result != null)) {
                        SaveCachedThumb(attachment, size, result);
                        result = GetCachedThumb(attachment, size);
                    }
                }
                if(result == null) {
                    throw new DreamAbortException(BadPreviewImageMsg());
                }

                // full filename for response content-disposition header
                switch(size) {
                case SizeType.CUSTOM:
                    filename = string.Format("{0}_({1}x{2}){3}", attachment.Name, width == 0 ? "" : width.ToString(), height == 0 ? "" : height.ToString(), attachment.Extension == string.Empty ? string.Empty : "." + attachment.Extension);
                    break;
                case SizeType.ORIGINAL:
                    filename = attachment.Name;
                    break;
                case SizeType.BESTFIT:
                case SizeType.THUMB:
                case SizeType.UNDEFINED:
                case SizeType.WEBVIEW:
                default:
                    filename = string.Format("{0}_({1}){2}", attachment.Name, size.ToString().ToLowerInvariant(), attachment.Extension == string.Empty ? string.Empty : "." + attachment.Extension);
                    break;
                }
                if(format != FormatType.UNDEFINED) {
                    filename = Path.ChangeExtension(filename, format.ToString().ToLowerInvariant());
                }
                return result;
            } catch {
                if(result != null) {
                    result.Close();
                }
                throw;
            }
        }
 //--- Class Methods ---
 public static StreamInfo RetrievePreview(AttachmentBE attachment, uint height, uint width, RatioType ratio, SizeType size, FormatType format) {
     string filename;
     return RetrievePreview(attachment, height, width, ratio, size, format, out filename);
 }
 public void PutFile(AttachmentBE attachment, SizeType size, StreamInfo file) {
     PutFileInternal(BuildS3Filename(attachment, size), attachment.Name, file);
 }
 public void PutFile(AttachmentBE attachment, SizeType size, StreamInfo file) {
     PutFileInternal(FilePath(attachment, size), file, false);
 }
 public void DeleteFile(AttachmentBE attachment, SizeType size) {
     DeleteFileInternal(BuildS3Filename(attachment, size));
 }
Beispiel #20
0
 private static AttachmentBE[] GetRevisions(AttachmentBE attach) {
     ResourceBE[] resources = DbUtils.CurrentSession.Resources_GetRevisions(attach.ResourceId, ResourceBE.ChangeOperations.CONTENT, SortDirection.DESC,null).ToArray();
     return Array.ConvertAll<ResourceBE, AttachmentBE>(resources, delegate(ResourceBE res) { return (AttachmentBE) res; });
 }
 private static void SaveCachedThumb(AttachmentBE attachment, SizeType size, StreamInfo file) {
     if(file != null) {
         DekiContext.Current.Instance.Storage.PutFile(attachment, size, file);
     }
 }
 public void MoveFile(AttachmentBE attachment, PageBE targetPage) {
     //Nothing to do here.
 }
 public void AttachmentMove(DateTime eventTime, AttachmentBE attachment, PageBE sourcePage, UserBE user) {
     PageDependentChanged(eventTime, sourcePage, user, FILES, DELETE);
     PageDependentChanged(eventTime, ((PageWrapperBE)attachment.ParentResource).Page, user, FILES, CREATE);
     AttachmentChanged(eventTime, attachment, MOVE);
 }
        private string BuildS3Filename(AttachmentBE attachment, SizeType size) {
            string id;

            //Legacy pre-Lyons S3 paths are based on fileid. If the fileid is present in the resource then use it otherwise base on resourceid.
            if(attachment.FileId == null) {
                id = string.Format("r{0}", attachment.ResourceId);
            } else {
                id = attachment.FileId.ToString();
            }

            switch(size) {
            case SizeType.THUMB:
            case SizeType.WEBVIEW:
                return string.Format("{0}/{1}/{2}/{3}", _prefix, id, attachment.Content.Revision - 1, size.ToString().ToLowerInvariant());
            default:
                return string.Format("{0}/{1}/{2}", _prefix, id, attachment.Content.Revision - 1);
            }
        }
        public static void PreSaveAllPreviews(AttachmentBE attachment) {
            if (AttachmentBL.Instance.IsAllowedForImageMagickPreview(attachment)) {

                //The type of preview based on uploaded mimetype
                FormatType previewFormat = ResolvePreviewFormat(attachment.MimeType);

                // generate thumbnail
                StreamInfo file = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
                if(file != null) {
                    SaveCachedThumb(attachment, SizeType.THUMB, BuildThumb(attachment, file, previewFormat, RatioType.UNDEFINED, DekiContext.Current.Instance.ImageThumbPixels, DekiContext.Current.Instance.ImageThumbPixels));
                }

                // generate webview
                file = DekiContext.Current.Instance.Storage.GetFile(attachment, SizeType.ORIGINAL, false);
                if(file != null) {
                    SaveCachedThumb(attachment, SizeType.WEBVIEW, BuildThumb(attachment, file, previewFormat, RatioType.UNDEFINED, DekiContext.Current.Instance.ImageWebviewPixels, DekiContext.Current.Instance.ImageWebviewPixels));
                }
            }
        }