예제 #1
0
        public override XDoc AsEmbeddableXml(bool safe)
        {
            MimeType mime = (Value.Segments.Length > 0) ? MimeType.FromFileExtension(Value.LastSegment ?? string.Empty) : MimeType.BINARY;

            if (StringUtil.EqualsInvariant(mime.MainType, "image"))
            {
                // embed <img> tag
                return(DekiScriptLibrary.WebImage(AsString(), null, null, null));
            }
            else
            {
                // embed <a> tag
                return(DekiScriptLibrary.WebLink(AsString(), null, null, null));
            }
        }
예제 #2
0
        private void AddUri(XmlNode context, DekiScriptUri uri)
        {
            if (context == null)
            {
                ConvertStateToHtml(null);
            }

            // NOTE (steveb): URIs have special embedding rules; either embed it as a <img> and <a> document base on the URI file extension on the last segment

            XUri     url  = uri.Value.AsPublicUri();
            MimeType mime = (url.Segments.Length > 0) ? MimeType.FromFileExtension(url.LastSegment ?? string.Empty) : MimeType.BINARY;
            XDoc     item = mime.MainType.EqualsInvariant("image") ?
                            DekiScriptLibrary.WebImage(url.ToString(), null, null, null) :
                            DekiScriptLibrary.WebLink(url.ToString(), null, null, null);

            AddXDoc(context, item);
        }
예제 #3
0
        private static void ThrowOnBadPreviewImage()
        {
            string filepath = Utils.PathCombine(DekiContext.Current.Deki.ResourcesPath, "images", BADPREVIEWFILENAME);

            try {
                lock (BADPREVIEWFILENAME) {
                    if (_badPreviewImageContent == null || _badPreviewImageContent.Length == 0)
                    {
                        _badPreviewImageContent = System.IO.File.ReadAllBytes(filepath);
                    }
                }
            }
            catch (Exception) { }

            if (_badPreviewImageContent != null && _badPreviewImageContent.Length > 0)
            {
                throw new AttachmentPreviewBadImageFatalException(MimeType.FromFileExtension(BADPREVIEWFILENAME), _badPreviewImageContent);
            }
            throw new AttachmentPreviewNoImageFatalException();
        }
예제 #4
0
            // Override the Invoke() method
            public override void Invoke(INetworkOperationContext context)
            {
                var pathInsideArchive = context.Request.RequestUri.Pathname.TrimStart('/').Replace("\\", "/");
                var stream            = GetFile(pathInsideArchive);

                if (stream != null)
                {
                    // If a resource is found in the archive, then return it as a Response
                    var response = new ResponseMessage(HttpStatusCode.OK);
                    response.Content = new StreamContent(stream);
                    response.Headers.ContentType.MediaType = MimeType.FromFileExtension(context.Request.RequestUri.Pathname);
                    context.Response = response;
                }
                else
                {
                    context.Response = new ResponseMessage(HttpStatusCode.NotFound);
                }

                // Invoke the next message handler in the chain
                Next(context);
            }
예제 #5
0
            // Override the Invoke() method
            public override void Invoke(INetworkOperationContext context)
            {
                // Call the GetFile() method that defines the logic in the Invoke() method
                var buff = GetFile(context.Request.RequestUri.Pathname.TrimStart('/'));

                if (buff != null)
                {
                    // Checking: if a resource is found in the archive, then return it as a Response
                    context.Response = new ResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ByteArrayContent(buff)
                    };
                    context.Response.Headers.ContentType.MediaType = MimeType.FromFileExtension(context.Request.RequestUri.Pathname);
                }
                else
                {
                    context.Response = new ResponseMessage(HttpStatusCode.NotFound);
                }

                // Call the next message handler
                Next(context);
            }
예제 #6
0
        protected override Yield Start(XDoc config, Result result)
        {
            yield return(Coroutine.Invoke(base.Start, config, new Result()));

            // loop over all resources
            Type   type     = GetType();
            string assembly = type.Assembly.FullName.Split(new char[] { ',' }, 2)[0];

            foreach (DekiExtLibraryFilesAttribute files in Attribute.GetCustomAttributes(type, typeof(DekiExtLibraryFilesAttribute)))
            {
                string prefix = files.Prefix ?? type.Namespace;
                foreach (string filename in files.Filenames)
                {
                    MimeType mime = MimeType.FromFileExtension(filename);
                    _files[filename] = Plug.New(string.Format("resource://{0}/{1}.{2}", assembly, prefix, filename)).With("dream.out.type", mime.FullType);
                }
            }

            // check if a public digital signature key was provided
            string dsaKey = config["deki-signature"].AsText ?? config["dekiwiki-signature"].AsText;

            if (dsaKey != null)
            {
                try {
                    DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
                    dsa.ImportCspBlob(Convert.FromBase64String(dsaKey));
                    _publicDigitalSignature = dsa;
                } catch {
                    throw new ArgumentException("invalid digital signature provided", "deki-signature");
                }
            }

            // loop over all instance methods
            foreach (MethodInfo method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                // check if it has the DekiExtFunction attriute
                DekiExtFunctionAttribute ext = (DekiExtFunctionAttribute)Attribute.GetCustomAttribute(method, typeof(DekiExtFunctionAttribute));
                if (ext != null)
                {
                    // check if function has an associated script
                    XDekiScript script = null;
                    DekiExtFunctionScriptAttribute scriptAttr = (DekiExtFunctionScriptAttribute)Attribute.GetCustomAttribute(method, typeof(DekiExtFunctionScriptAttribute));
                    if (scriptAttr != null)
                    {
                        DreamMessage scriptresource = Plug.New(string.Format("resource://{0}/{1}.{2}", assembly, scriptAttr.Prefix ?? type.Namespace, scriptAttr.Scriptname)).With("dream.out.type", MimeType.XML.FullType).GetAsync().Wait();
                        if (scriptresource.IsSuccessful)
                        {
                            script = new XDekiScript(scriptresource.ToDocument());
                        }
                        if (script == null)
                        {
                            throw new InvalidOperationException(string.Format("method '{0}' is declard as script, but script could not be loaded", method.Name));
                        }
                    }

                    // add function
                    Add(ext, method, script);
                }
            }

            // add configuration settings
            var context = DreamContext.Current;

            _scriptConfig = new DekiScriptMap();
            foreach (KeyValuePair <string, string> entry in Config.ToKeyValuePairs())
            {
                XUri local;
                if (XUri.TryParse(entry.Value, out local))
                {
                    local = context.AsPublicUri(local);
                    _scriptConfig.AddAt(entry.Key.Split('/'), DekiScriptExpression.Constant(local.ToString()));
                }
                else
                {
                    _scriptConfig.AddAt(entry.Key.Split('/'), DekiScriptExpression.Constant(entry.Value));
                }
            }
            result.Return();
        }
예제 #7
0
        public ResourceBE AddAttachment(ResourceBE existingRevision, Stream filestream, long filesize, MimeType mimeType, PageBE targetPage, string userDescription, string fileName, bool isMsWebDav)
        {
            if (_dekiContext.Instance.MaxFileSize < filesize)
            {
                throw new AttachmentMaxFileSizeAllowedInvalidArgumentException(_dekiContext.Instance.MaxFileSize);
            }
            var saveFileName = ValidateFileName(fileName);

            if (existingRevision != null)
            {
                if (!saveFileName.EqualsInvariant(existingRevision.Name))
                {
                    // An existing file is getting renamed. Make sure no file exists with the new name
                    var existingAttachment = GetPageAttachment(targetPage.ID, saveFileName);
                    if (existingAttachment != null)
                    {
                        throw new AttachmentExistsOnPageConflictException(saveFileName, targetPage.Title.AsUserFriendlyName());
                    }
                }
            }

            // If file is found but has been deleted, create a new file.
            if (existingRevision != null && existingRevision.ResourceIsDeleted)
            {
                existingRevision = null;
            }
            if (isMsWebDav)
            {
                _log.DebugFormat("Upload client is MD WebDAV, provided mimetype is: {0}", mimeType);
                var extensionFileType = MimeType.FromFileExtension(Path.GetExtension(saveFileName));
                if (!extensionFileType.Match(mimeType) || extensionFileType == MimeType.DefaultMimeType)
                {
                    mimeType = existingRevision == null ? extensionFileType : existingRevision.MimeType;
                    _log.DebugFormat("using mimetype '{0}' instead", mimeType);
                }
            }
            ResourceBE attachment;
            var        resourceContents = new ResourceContentBE((uint)filesize, mimeType);
            var        isUpdate         = false;

            if (existingRevision == null)
            {
                attachment = _resourceBL.BuildRevForNewResource((uint)targetPage.ID, ResourceBE.ParentType.PAGE, saveFileName, mimeType, (uint)filesize, null, ResourceBE.Type.FILE, _dekiContext.User.ID, resourceContents);
            }
            else
            {
                isUpdate   = true;
                attachment = BuildRevForContentUpdate(existingRevision, mimeType, (uint)filesize, null, saveFileName, resourceContents);
            }

            // rewrite mimetype to text/plain for certain extensions
            string extension = attachment.FilenameExtension;

            if (_dekiContext.Instance.FileExtensionForceAsTextList.Any(forcedExtensions => extension == forcedExtensions))
            {
                attachment.MimeType = MimeType.TEXT;
            }

            // Insert the attachment into the DB
            attachment = SaveResource(attachment);
            try {
                // Save file to storage provider
                _dekiContext.Instance.Storage.PutFile(attachment, SizeType.ORIGINAL, new StreamInfo(filestream, filesize, mimeType));
            } catch (Exception x) {
                _dekiContext.Instance.Log.WarnExceptionFormat(x, "Failed to save attachment to storage provider");

                // Upon save failure, delete the record from the db.
                _session.Resources_DeleteRevision(attachment.ResourceId, attachment.Revision);
                throw;
            }

            // Set description property
            if (!string.IsNullOrEmpty(userDescription))
            {
                attachment = SetDescription(attachment, userDescription);
            }

            // For images resolve width/height (if not in imagemagick's blacklist)
            attachment = IdentifyUnknownImage(attachment);

            // Pre render thumbnails of images
            AttachmentPreviewBL.PreSaveAllPreviews(attachment);
            PageBL.Touch(targetPage, DateTime.UtcNow);

            //TODO MaxM: Connect with transaction
            RecentChangeBL.AddFileRecentChange(targetPage.Touched, targetPage, _dekiContext.User, DekiResources.FILE_ADDED(attachment.Name), 0);
            if (isUpdate)
            {
                _dekiContext.Instance.EventSink.AttachmentUpdate(_dekiContext.Now, attachment, _dekiContext.User);
            }
            else
            {
                _dekiContext.Instance.EventSink.AttachmentCreate(_dekiContext.Now, attachment, _dekiContext.User);
            }
            return(attachment);
        }
예제 #8
0
 public StreamInfo GetSiteFile(string label, bool allowFileLink)
 {
     return(GetFileInternal(SiteFilePath(label), MimeType.FromFileExtension(label)));
 }
예제 #9
0
 public StreamInfo GetSiteFile(string label, bool allowFileLink)
 {
     CheckDisposed();
     return(GetFileInternal(BuildS3SiteFilename(label), MimeType.FromFileExtension(label), allowFileLink));
 }
        public void MoveAttachments(XDoc spaceManifest, int dekiPageID, long confluencePageId)
        {
            RemoteAttachment[] attachments = _confluenceService.GetAttachments(confluencePageId);

            int count = attachments.Length;

            foreach (RemoteAttachment attachment in attachments)
            {
                // This was when a single attachment (the latest) was being handled
                // byte[] attachmentData;
                Log.DebugFormat("Processing file: {0} size: {1} #remaining: {2}", attachment.fileName, attachment.fileSize, --count);

                Plug         p   = (attachment.creator == null) ? _dekiPlug : GetPlugForConvertedUser(attachment.creator);
                DreamMessage res = p.At("pages", dekiPageID.ToString(), "files", "=" + Utils.DoubleUrlEncode(attachment.fileName), "info")
                                   .GetAsync().Wait();

                if (res.Status == DreamStatus.Ok)
                {
                    Log.DebugFormat("Already converted: {0} MindTouch URL: {1}", attachment.fileName, res.AsDocument()["contents/@href"].AsText);
                }
                else
                {
                    MimeType attachmentMimeType;
                    if (!MimeType.TryParse(attachment.contentType, out attachmentMimeType))
                    {
                        attachmentMimeType = MimeType.FromFileExtension(attachment.fileName);
                    }

                    // The attachment URL contains the latest actual version of this attachment e.g.
                    // http://confluencesite.com/download/attachments/3604492/excelspreadsheet.xls?version=1

                    int latestVersion = 1, oldestVersion = 1;
                    if (attachment.url.Contains("version="))
                    {
                        try
                        {
                            latestVersion = ParseVersionFromUri(attachment.url);
                        }
                        catch {}
                    }

                    try
                    {
                        if (latestVersion > 1)
                        {
                            if ((latestVersion - 5) > 1)
                            {
                                oldestVersion = latestVersion - 5;
                            }
                        }

                        for (int x = oldestVersion; x <= latestVersion; x++)
                        {
                            try
                            {
                                byte[]       ThisAttachmentData = _confluenceService.GetAttachmentData(confluencePageId, attachment.fileName, x);
                                DreamMessage msg = new DreamMessage(DreamStatus.Ok, null, attachmentMimeType, ThisAttachmentData);
                                string       AttachmentTimeStampComment = attachment.comment + " - attachment version " + x + " originally created on " + attachment.created.Value.ToShortDateString() + " " + attachment.created.Value.ToShortTimeString();

                                res = p.At("pages", dekiPageID.ToString(), "files", "=" + Utils.DoubleUrlEncode(attachment.fileName))
                                      .With("description", AttachmentTimeStampComment)
                                      .PutAsync(msg).Wait();

                                if (res.Status != DreamStatus.Ok)
                                {
                                    Log.WarnFormat("File '{0}' version '{1}' on Confluence pageid '{2}' not converted: {3}", attachment.fileName, x, attachment.pageId, res.ToString());
                                    // added as suggested by Max on the list created here http://projects.mindtouch.com/User:emilyp/Booze_Allen/Conversion_Issues
                                    throw new DreamAbortException(res);
                                }

                                XDoc   resDoc     = res.ToDocument();
                                string contentUrl = resDoc["contents/@href"].AsText;

                                LogFileConversion(spaceManifest, attachment, contentUrl);
                            }
                            catch (DreamAbortException dEx)
                            {
                                WriteLineToConsole("Error on moving attachment " + attachment.fileName + "version " + x);
                                if (!String.IsNullOrEmpty(dEx.Message))
                                {
                                    WriteLineToLog(dEx.Message);
                                }
                                continue;
                            }
                            catch (System.Web.Services.Protocols.SoapException e)
                            {
                                WriteLineToConsole("Error obtaining attachment data from confluence " + attachment.fileName + "version " + x);
                                if ((e.Detail != null) && (e.Detail.OuterXml != null))
                                {
                                    WriteLineToLog(e.Detail.OuterXml);
                                }
                                continue;
                            }
                        } // for loop to submit revisions
                    }
                    catch (System.Web.Services.Protocols.SoapException e)
                    {
                        WriteLineToConsole("Error on moving attachment " + attachment.fileName);
                        if ((e.Detail != null) && (e.Detail.OuterXml != null))
                        {
                            WriteLineToLog(e.Detail.OuterXml);
                        }
                        continue;
                    }
                }
            }
        }