Exemplo n.º 1
0
        /// <summary>
        /// Processes a PutRelativeFile request
        /// </summary>
        /// <remarks>
        /// For full documentation on PutRelativeFile, see https://wopi.readthedocs.org/projects/wopirest/en/latest/files/PutRelativeFile.html
        /// </remarks>
        private async static Task <HttpResponseMessage> PutRelativeFile(this HttpContext context, File file, List <WopiAction> actions, Token AccessToken)
        {
            // Determine the specific mode
            if (context.Request.Headers[WopiRequestHeaders.RELATIVE_TARGET] != null &&
                context.Request.Headers[WopiRequestHeaders.SUGGESTED_TARGET] != null)
            {
                // Theses headers are mutually exclusive, so we should return a 501 Not Implemented
                return(returnStatus(HttpStatusCode.NotImplemented, "Both RELATIVE_TARGET and SUGGESTED_TARGET were present"));
            }
            else if (context.Request.Headers[WopiRequestHeaders.RELATIVE_TARGET] != null ||
                     context.Request.Headers[WopiRequestHeaders.SUGGESTED_TARGET] != null)
            {
                string fileName = "";
                if (context.Request.Headers[WopiRequestHeaders.RELATIVE_TARGET] != null)
                {
                    // Specific mode...use the exact filename
                    fileName = context.Request.Headers[WopiRequestHeaders.RELATIVE_TARGET];
                }
                else
                {
                    // Suggested mode...might just be an extension
                    fileName = context.Request.Headers[WopiRequestHeaders.RELATIVE_TARGET];
                    if (fileName.IndexOf('.') == 0)
                    {
                        fileName = file.BaseFileName.Substring(0, file.BaseFileName.LastIndexOf('.')) + fileName;
                    }
                }

                // Create the file entity
                File newFile = File.Create();
                newFile.OwnerId      = file.OwnerId;
                newFile.BaseFileName = fileName;
                //newFile.Size = context.Request.InputStream.Length;
                newFile.Container = file.Container;
                //newFile.Version = DateTime.Now.ToString("s");

                // First stream the file into blob storage
                var stream = context.Request.InputStream;
                var bytes  = new byte[stream.Length];
                await stream.ReadAsync(bytes, 0, (int)stream.Length);

                //var id = StorageUtil.Save(newFile.id.ToString(), newFile.Container, bytes);

                //// Write the details into documentDB
                ////await DatabaseUtil<FileModel>.CreateItemAsync("Files", (FileModel)newFile);
                //DatabaseUtil<FileModel>.CreateItem("Files", (FileModel)newFile);

                newFile.WriteContent(bytes);

                // Get access token for the new file
                WopiSecurity security = new WopiSecurity();
                var          token    = security.GenerateToken(newFile.id.ToString(), AccessToken.User, AccessToken.UserDisplayName);
                var          tokenStr = token.Identity; //security.WriteToken(token);

                // Prepare the Json response
                string json = String.Format("{ 'Name': '{0}, 'Url': 'https://{1}/wopi/files/{2}?access_token={3}'",
                                            newFile.BaseFileName, context.Request.Url.Authority, newFile.id.ToString(), tokenStr);

                // Add the optional properties to response if applicable (HostViewUrl, HostEditUrl)
                var fileExt = newFile.BaseFileName.Substring(newFile.BaseFileName.LastIndexOf('.') + 1).ToLower();
                var view    = actions.FirstOrDefault(i => i.ext == fileExt && i.name == "view");
                if (view != null)
                {
                    json += String.Format(", 'HostViewUrl': '{0}'", WopiUtil.GetActionUrl(view, newFile, context.Request.Url.Authority));
                }
                var edit = actions.FirstOrDefault(i => i.ext == fileExt && i.name == "edit");
                if (edit != null)
                {
                    json += String.Format(", 'HostEditUrl': '{0}'", WopiUtil.GetActionUrl(edit, newFile, context.Request.Url.Authority));
                }
                json += " }";

                // Write the response and return a success 200
                var response = returnStatus(HttpStatusCode.OK, "Success");
                response.Content = new StringContent(json);
                return(response);
            }
            else
            {
                return(returnStatus(HttpStatusCode.BadRequest, "PutRelativeFile mode was not provided in the request"));
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Processes a WOPI request using the HttpContext of the APIController
        /// </summary>
        public async static Task <HttpResponseMessage> ProcessWopiRequest(this HttpContext context)
        {
            // Parse the request
            var request = ParseRequest(context.Request);
            HttpResponseMessage response = null;

            try
            {
                // Lookup the file in the database
                var itemId = new Guid(request.Id);
                var file   = File.Get(itemId); //DatabaseUtil<DetailedFileModel>.GetItem("Files", i => i.id == itemId);

                // Check for null file
                if (file == null)
                {
                    response = returnStatus(HttpStatusCode.NotFound, "File Unknown/User Unauthorized");
                }
                else
                {
                    // Validate WOPI Proof (ie - ensure request came from Office Online)
                    if (true)  //(await WopiUtil.ValidateWopiProof(context))
                    {
                        // Get discovery information
                        var fileExt = file.BaseFileName.Substring(file.BaseFileName.LastIndexOf('.') + 1).ToLower();
                        var actions = await WopiUtil.GetDiscoveryInfo();

                        // Augments the file with additional properties CloseUrl, HostViewUrl, HostEditUrl
                        file.CloseUrl = String.Format("http://{0}", context.Request.Url.Authority);
                        var view = actions.FirstOrDefault(i => i.ext == fileExt && i.name == "view");
                        if (view != null)
                        {
                            file.HostViewUrl = WopiUtil.GetActionUrl(view, file, context.Request.Url.Authority);
                        }
                        var edit = actions.FirstOrDefault(i => i.ext == fileExt && i.name == "edit");
                        if (edit != null)
                        {
                            file.HostEditUrl = WopiUtil.GetActionUrl(edit, file, context.Request.Url.Authority);
                        }

                        // Get the user from the token (token is already validated)
                        file.UserId = request.AccessToken.User;  //WopiSecurity.GetUserFromToken(request.AccessToken);

                        // Call the appropriate handler for the WOPI request we received

                        ServerUtil.Log(request.RequestType.ToString());

                        switch (request.RequestType)
                        {
                        case WopiRequestType.CheckFileInfo:
                            response = context.CheckFileInfo(file, request.AccessToken);
                            break;

                        case WopiRequestType.GetFile:
                            response = context.GetFile(file, request.AccessToken);
                            break;

                        case WopiRequestType.Lock:
                            response = context.Lock(file, request.AccessToken);
                            break;

                        case WopiRequestType.GetLock:
                            response = context.GetLock(file, request.AccessToken);
                            break;

                        case WopiRequestType.RefreshLock:
                            response = context.RefreshLock(file, request.AccessToken);
                            break;

                        case WopiRequestType.Unlock:
                            response = context.Unlock(file, request.AccessToken);
                            break;

                        case WopiRequestType.UnlockAndRelock:
                            response = context.UnlockAndRelock(file, request.AccessToken);
                            break;

                        case WopiRequestType.PutFile:
                            response = context.PutFile(file, request.AccessToken);
                            break;

                        case WopiRequestType.PutRelativeFile:
                            response = await context.PutRelativeFile(file, actions, request.AccessToken);

                            break;

                        case WopiRequestType.RenameFile:
                            response = context.RenameFile(file, request.AccessToken);
                            break;

                        case WopiRequestType.PutUserInfo:
                            response = await context.PutUserInfo(file, request.AccessToken);

                            break;

                        default:
                            response = returnStatus(HttpStatusCode.NotImplemented, "Unsupported");
                            break;
                        }
                    }
                    //else
                    //{
                    //    // Proof validation failed...return 500
                    //    ServerUtil.Log("Proof validation failed!");

                    //    response = returnStatus(HttpStatusCode.InternalServerError, "Server Error");
                    //}
                }
            }
            catch (Exception ex)
            {
                // An unknown exception occurred...return 500
                ServerUtil.LogException(ex);

                response = returnStatus(HttpStatusCode.InternalServerError, "Server Error");
            }

            return(response);
        }