Ejemplo n.º 1
0
        public override async Task <WopiResponse> UnlockAndRelock(UnlockAndRelockRequest unlockAndRelockRequest)
        {
            var userId = WopiSecurity.GetIdentityNameFromToken(unlockAndRelockRequest.AccessToken);

            var wopiFileRepository = new WopiFileRepository();
            var response           = await wopiFileRepository.LockFile(unlockAndRelockRequest.ResourceId, userId, unlockAndRelockRequest.Lock, unlockAndRelockRequest.OldLock);

            if (response.Item1 == HttpStatusCode.BadRequest)
            {
                return(unlockAndRelockRequest.ResponseBadRequest());
            }
            // Check for file not found or no permissions
            else if (response.Item1 == HttpStatusCode.NotFound)
            {
                return(unlockAndRelockRequest.ResponseNotFound());
            }
            // Ensure the file isn't already locked
            else if (response.Item1 == HttpStatusCode.Conflict)
            {
                return(unlockAndRelockRequest.ResponseLockConflict(response.Item2));
            }
            // File successfully locked
            else if (response.Item1 == HttpStatusCode.OK)
            {
                return(unlockAndRelockRequest.ResponseOK());
            }
            else
            {
                return(unlockAndRelockRequest.ResponseServerError(string.Format("Unknown HTTPStatusCode from WopiFileRepository.LockFile: {0}", response.Item1)));
            }
        }
Ejemplo n.º 2
0
        public override async Task <WopiResponse> GetLock(GetLockRequest getLockRequest)
        {
            var userId             = WopiSecurity.GetIdentityNameFromToken(getLockRequest.AccessToken);
            var wopiFileRepository = new WopiFileRepository();
            var response           = await wopiFileRepository.GetLockStatus(getLockRequest.ResourceId, userId);

            // Check for file not found or no permissions
            if (response.Item1 == HttpStatusCode.NotFound)
            {
                return(getLockRequest.ResponseNotFound());
            }
            // Ensure the file isn't already locked
            else if (response.Item1 == HttpStatusCode.Conflict)
            {
                return(getLockRequest.ResponseLockConflict(response.Item2));
            }
            // File successfully locked
            else if (response.Item1 == HttpStatusCode.OK)
            {
                if (response.Item2 != null)
                {
                    return(getLockRequest.ResponseFileLocked(response.Item2));
                }
                else
                {
                    return(getLockRequest.ResponseFileNotLocked());
                }
            }
            else
            {
                return(getLockRequest.ResponseServerError(string.Format("Unknown HTTPStatusCode from WopiFileRepository.GetLockStatus: {0}", response.Item1)));
            }
        }
        public async Task TestRename()
        {
            var fileRepository = new WopiFileRepository();
            var fileName       = Path.GetFileName(this.fileName);

            using (var fileStream = new FileStream(this.fileName, FileMode.Open))
            {
                var wopiFile = await fileRepository.AddFile(tenant1User1, tenant1, fileStream, fileName);

                var result = await fileRepository.RenameFile(wopiFile.FileId, tenant1User1, lockId, renamedFileName);

                Assert.AreEqual(HttpStatusCode.OK, result);
                using (var wopiContext = new WopiContext())
                {
                    var file = await wopiContext.Files.Where(f => f.FileId == wopiFile.FileId).FirstOrDefaultAsync();

                    Assert.AreEqual(renamedFileName, Path.GetFileNameWithoutExtension(file.FileName));
                }
                var deleteResponse = await fileRepository.DeleteFile(wopiFile.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
            }

            //await userRepository.DeleteUser(tenant1User1);
        }
Ejemplo n.º 4
0
        public async Task <ActionResult> Delete(string id)
        {
            // This method is called by JavaScript, so use try/catch block to make sure an error gets returned
            try
            {
                var userId             = User.Identity.Name;
                var wopiFileRepository = new WopiFileRepository();
                var statusCode         = await wopiFileRepository.DeleteFile(id, userId);

                if (statusCode == HttpStatusCode.OK)
                {
                    //return json representation of information
                    return(Json(new { success = true, id = id.ToString() }));
                }
                else
                {
                    // Something failed...return false
                    return(Json(new { success = false, id = id.ToString() }));
                }
            }
            catch (Exception)
            {
                // Something failed...return false
                return(Json(new { success = false, id = id.ToString() }));
            }
        }
        public async Task TestLockFileAndExpiration()
        {
            var fileRepository = new WopiFileRepository();

            using (var fileStream = new FileStream(fileName, FileMode.Open))
            {
                var fileName = Path.GetFileName(this.fileName);
                var wopiFile = await fileRepository.AddFile(tenant1User1, tenant1, fileStream, fileName);

                // lock for 3 seconds
                var lockResponse = await fileRepository.LockFile(wopiFile.FileId, tenant1User1, lockId, null, 0.05);

                Assert.AreEqual(HttpStatusCode.OK, lockResponse.Item1);
                using (var wopiContext = new WopiContext())
                {
                    var file = await wopiContext.Files.Where(f => f.FileId == wopiFile.FileId).FirstOrDefaultAsync();

                    Assert.AreEqual(lockId, file.LockValue);
                    Assert.IsTrue(file.LockExpires.Value > DateTime.UtcNow);
                }

                // wait 5 seconds for lock to expire
                await Task.Delay(5000);

                var response2 = await fileRepository.GetLockStatus(wopiFile.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, response2.Item1);

                var deleteResponse = await fileRepository.DeleteFile(wopiFile.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
            }
        }
Ejemplo n.º 6
0
        public async Task <ActionResult> Add()
        {
            // This method is called by JavaScript, so use try/catch block to make sure an error gets returned
            try
            {
                var userId = User.Identity.Name;
                var tenant = new MailAddress(userId).Host.Replace(".", "-");

                var fileName = HttpUtility.UrlDecode(Request["HTTP_X_FILE_NAME"]);
                var size     = Convert.ToInt32(Request["HTTP_X_FILE_SIZE"]);


                var wopiFileRepository = new WopiFileRepository();
                var wopiFile           = await wopiFileRepository.AddFile(userId, tenant, Request.InputStream, fileName);

                if (wopiFile != null)
                {
                    // Return json representation of information
                    return(Json(new { success = true, file = await wopiFile.ToWopiFileModel() }));
                }
                else
                {
                    // Something failed...return false
                    return(Json(new { success = false }));
                }
            }
            catch (Exception)
            {
                // Something failed...return false
                return(Json(new { success = false }));
            }
        }
Ejemplo n.º 7
0
        public override async Task <WopiResponse> RenameFile(RenameFileRequest renameFileRequest)
        {
            var userId = WopiSecurity.GetIdentityNameFromToken(renameFileRequest.AccessToken);

            var wopiFileRepository = new WopiFileRepository();
            var response           = await wopiFileRepository.RenameFile(renameFileRequest.ResourceId, userId, renameFileRequest.Lock, renameFileRequest.RequestedName);

            if (response.Item1 == HttpStatusCode.NotFound)
            {
                return(renameFileRequest.ResponseNotFound());
            }
            else if (response.Item1 == HttpStatusCode.Conflict)
            {
                return(renameFileRequest.ResponseLockConflict(response.Item2));
            }
            else if (response.Item1 == HttpStatusCode.BadRequest)
            {
                return(renameFileRequest.ResponseBadRequest(response.Item2));
            }
            else if (response.Item1 == HttpStatusCode.OK)
            {
                return(renameFileRequest.ResponseOK(response.Item2));
            }
            else
            {
                return(renameFileRequest.ResponseServerError(string.Format("Unknown HTTPStatusCode from WopiFileRepository.RenameFile: {0}", response.Item1)));
            }
        }
Ejemplo n.º 8
0
        public async Task <ActionResult> Detail(string id)
        {
            var userId = User.Identity.Name;
            var tenant = new MailAddress(userId).Host.Replace(".", "-");

            // Make sure an action was passed in
            if (String.IsNullOrEmpty(Request["action"]))
            {
                return(RedirectToAction("Error", "Home", new { error = "No action provided" }));
            }

            var wopiFileRepository = new WopiFileRepository();
            var result             = await wopiFileRepository.GetFileInfoByTenantUser(id, userId, tenant);

            // Check for null file
            if (result.Item1 == HttpStatusCode.NotFound)
            {
                return(RedirectToAction("Error", "Home", new { error = "Files does not exist" }));
            }
            else if (result.Item1 == HttpStatusCode.Unauthorized)
            {
                return(RedirectToAction("Error", "Home", new { error = "Not authorized to access file" }));
            }
            else if (result.Item1 == HttpStatusCode.OK)
            {
                var wopiFile = result.Item2;
                // Use discovery to determine endpoint to leverage
                List <WopiAction> discoData = await WopiDiscovery.GetActions();

                var fileExt = wopiFile.FileName.Substring(wopiFile.FileName.LastIndexOf('.') + 1).ToLower();
                var action  = discoData.FirstOrDefault(i => i.name == Request["action"] && i.ext == fileExt);

                // Make sure the action isn't null
                if (action != null)
                {
                    string urlsrc = WopiDiscovery.GetActionUrl(action, wopiFile.FileId.ToString(), Request.Url.Authority);

                    // Generate JWT token for the user/document
                    WopiSecurity wopiSecurity = new WopiSecurity();
                    var          token        = wopiSecurity.GenerateToken(User.Identity.Name.ToLower());
                    ViewData["access_token"]     = wopiSecurity.WriteToken(token);
                    ViewData["access_token_ttl"] = token.ValidTo.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
                    ViewData["wopi_urlsrc"]      = urlsrc;
                    return(View());
                }
                else
                {
                    // This will only hit if the extension isn't supported by WOPI
                    return(RedirectToAction("Error", "Home", new { error = "File is not a supported WOPI extension" }));
                }
            }
            else
            {
                return(RedirectToAction("Error", "Home", new { error = "Internal server error" }));
            }
        }
        public async Task TestCreateCopy()
        {
            var fileRepository = new WopiFileRepository();
            var fileName       = Path.GetFileName(this.fileName);

            using (var fileStream = new FileStream(this.fileName, FileMode.Open))
            {
                var originalFile = await fileRepository.AddFile(tenant1User1, tenant1, fileStream, fileName);

                // Test owner copy
                var ownerCopyResult = await fileRepository.CreateCopy(originalFile.FileId, tenant1User1, copyFileName);

                Assert.AreEqual(HttpStatusCode.OK, ownerCopyResult.Item1);
                Assert.IsNotNull(ownerCopyResult.Item2);

                // Test copy to an existing file without overwrite
                var result = await fileRepository.CreateCopy(originalFile.FileId, tenant1User1, copyFileName);

                Assert.AreEqual(HttpStatusCode.Conflict, result.Item1);

                // obtain access rights to original file for tenant1User2 in same tenant
                var result1 = await fileRepository.GetFileInfoByTenantUser(ownerCopyResult.Item2.FileId, tenant1User2, tenant1);

                Assert.AreEqual(HttpStatusCode.OK, result1.Item1);

                // Get lock for tenantUser1
                var result2 = await fileRepository.LockFile(ownerCopyResult.Item2.FileId, tenant1User1, lockId, null);

                Assert.AreEqual(HttpStatusCode.OK, result2.Item1);

                // Test copy to an existing file by tenantUser2 when locked by tenant1User1
                var result3 = await fileRepository.CreateCopy(ownerCopyResult.Item2.FileId, tenant1User2, copyFileName, true);

                Assert.AreEqual(HttpStatusCode.Conflict, result3.Item1);

                // release lock for tenant1User2
                var result4 = await fileRepository.UnlockFile(ownerCopyResult.Item2.FileId, tenant1User1, lockId);

                Assert.AreEqual(HttpStatusCode.OK, result4.Item1);

                // Try copy again on existing file with overwrite
                var tenantCopyResult = await fileRepository.CreateCopy(ownerCopyResult.Item2.FileId, tenant1User2, copyFileName, true);

                Assert.AreEqual(HttpStatusCode.OK, tenantCopyResult.Item1);

                var deleteResponse = await fileRepository.DeleteFile(originalFile.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
                deleteResponse = await fileRepository.DeleteFile(tenantCopyResult.Item2.FileId, tenant1User2);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
            }
        }
Ejemplo n.º 10
0
        public override async Task <WopiResponse> PutRelativeFileSpecific(PutRelativeFileSpecificRequest putRelativeFileSpecificRequest)
        {
            var userId = WopiSecurity.GetIdentityNameFromToken(putRelativeFileSpecificRequest.AccessToken);

            var wopiFileRepository = new WopiFileRepository();
            var response           = await wopiFileRepository.CreateCopy(putRelativeFileSpecificRequest.ResourceId, userId, putRelativeFileSpecificRequest.RelativeTarget, putRelativeFileSpecificRequest.OverwriteRelativeTarget);

            if (response.Item1 == HttpStatusCode.NotFound)
            {
                return(putRelativeFileSpecificRequest.ResponseNotFound());
            }
            else if (response.Item1 == HttpStatusCode.BadRequest)
            {
                return(putRelativeFileSpecificRequest.ResponseBadRequest());
            }
            else if (response.Item1 == HttpStatusCode.Conflict)
            {
                return(putRelativeFileSpecificRequest.ResponseLockConflict(response.Item3));
            }
            else if (response.Item1 == HttpStatusCode.OK)
            {
                // Get access token for the new file
                WopiSecurity security = new WopiSecurity();
                var          token    = security.GenerateToken(response.Item2.OwnerId);
                var          tokenStr = security.WriteToken(token);

                var url = new Uri(string.Format("https://{0}/wopi/files/{1}?access_token={2}",
                                                putRelativeFileSpecificRequest.RequestUri.Authority, response.Item2.FileId, tokenStr));

                Uri hostViewUrl = null;
                Uri hostEditUrl = null;
                var actions     = await WopiDiscovery.GetActions();

                var view = actions.FirstOrDefault(i => i.ext == response.Item2.FileExtension && i.name == "view");
                if (view != null)
                {
                    hostViewUrl = new Uri(WopiDiscovery.GetActionUrl(view, response.Item2.FileId, putRelativeFileSpecificRequest.RequestUri.Authority));
                }
                var edit = actions.FirstOrDefault(i => i.ext == response.Item2.FileExtension && i.name == "edit");
                if (edit != null)
                {
                    hostEditUrl = new Uri(WopiDiscovery.GetActionUrl(edit, response.Item2.FileId, putRelativeFileSpecificRequest.RequestUri.Authority));
                }

                return(putRelativeFileSpecificRequest.ResponseOK(response.Item2.FileName, url, hostViewUrl, hostEditUrl));
            }
            else
            {
                return(putRelativeFileSpecificRequest.ResponseServerError(string.Format("Unknown HTTPStatusCode from WopiFileRepository.CreateCopy: {0}", response.Item1)));
            }
        }
        public async Task TestCreateCopySuggested()
        {
            var fileRepository = new WopiFileRepository();
            var fileName       = Path.GetFileName(this.fileName);

            using (var fileStream = new FileStream(this.fileName, FileMode.Open))
            {
                var wopiFile = await fileRepository.AddFile(tenant1User1, tenant1, fileStream, fileName);

                // Test suggested file extension
                var result1 = await fileRepository.CreateCopySuggested(wopiFile.FileId, tenant1User1, suggestedFileExtension);

                Assert.AreEqual(HttpStatusCode.OK, result1.Item1);
                Assert.IsNotNull(result1.Item2);

                // test full file name no conflict
                var result2 = await fileRepository.CreateCopySuggested(wopiFile.FileId, tenant1User1, copyFileName);

                Assert.AreEqual(HttpStatusCode.OK, result2.Item1);

                // test full file name conflict
                var result3 = await fileRepository.CreateCopySuggested(wopiFile.FileId, tenant1User1, copyFileName);

                Assert.AreEqual(HttpStatusCode.OK, result3.Item1);


                // test second full file name conflict
                var result4 = await fileRepository.CreateCopySuggested(wopiFile.FileId, tenant1User1, copyFileName);

                Assert.AreEqual(HttpStatusCode.OK, result4.Item1);

                var deleteResponse = await fileRepository.DeleteFile(wopiFile.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
                deleteResponse = await fileRepository.DeleteFile(result1.Item2.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
                deleteResponse = await fileRepository.DeleteFile(result2.Item2.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
                deleteResponse = await fileRepository.DeleteFile(result3.Item2.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
                deleteResponse = await fileRepository.DeleteFile(result4.Item2.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
            }
        }
Ejemplo n.º 12
0
        public override async Task <WopiResponse> PutRelativeFileSuggested(PutRelativeFileSuggestedRequest putRelativeFileSuggestedRequest)
        {
            var userId = WopiSecurity.GetIdentityNameFromToken(putRelativeFileSuggestedRequest.AccessToken);

            var wopiFileRepository = new WopiFileRepository();
            var response           = await wopiFileRepository.CreateCopySuggested(putRelativeFileSuggestedRequest.ResourceId, userId, putRelativeFileSuggestedRequest.SuggestedTarget);

            if (response.Item1 == HttpStatusCode.NotFound)
            {
                return(putRelativeFileSuggestedRequest.ResponseNotFound());
            }
            else if (response.Item1 == HttpStatusCode.OK)
            {
                // Get access token for the new file
                WopiSecurity security = new WopiSecurity();
                var          token    = security.GenerateToken(response.Item2.OwnerId);
                var          tokenStr = security.WriteToken(token);

                //var name = newFile.BaseFileName;

                var url = new Uri(string.Format("https://{0}/wopi/files/{1}?access_token={2}",
                                                putRelativeFileSuggestedRequest.RequestUri.Authority, response.Item2.FileId, tokenStr));

                // Add the optional properties to response if applicable (HostViewUrl, HostEditUrl)
                Uri hostViewUrl = null;
                Uri hostEditUrl = null;
                var actions     = await WopiDiscovery.GetActions();

                var view = actions.FirstOrDefault(i => i.ext == response.Item2.FileExtension && i.name == "view");
                if (view != null)
                {
                    hostViewUrl = new Uri(WopiDiscovery.GetActionUrl(view, response.Item2.FileId, putRelativeFileSuggestedRequest.RequestUri.Authority));
                }
                var edit = actions.FirstOrDefault(i => i.ext == response.Item2.FileExtension && i.name == "edit");
                if (edit != null)
                {
                    hostEditUrl = new Uri(WopiDiscovery.GetActionUrl(edit, response.Item2.FileId, putRelativeFileSuggestedRequest.RequestUri.Authority));
                }
                // Write the response and return a success 200
                return(putRelativeFileSuggestedRequest.ResponseOK(response.Item2.FileName, url, hostViewUrl, hostEditUrl));
            }
            else
            {
                return(putRelativeFileSuggestedRequest.ResponseServerError(string.Format("Unknown HTTPStatusCode from WopiFileRepository.CreateCopySuggested: {0}", response.Item1)));
            }
        }
Ejemplo n.º 13
0
        public override async Task <WopiResponse> GetFile(GetFileRequest getFileRequest)
        {
            var userId = WopiSecurity.GetIdentityNameFromToken(getFileRequest.AccessToken);

            // Lookup the file in the database
            var wopiFileRepository = new WopiFileRepository();
            var response           = await wopiFileRepository.GetFileContent(getFileRequest.ResourceId, userId);

            // Check for null file
            if (response.Item1 == HttpStatusCode.NotFound)
            {
                return(getFileRequest.ResponseNotFound());
            }
            else
            {
                // Write the response and return success 200
                return(getFileRequest.ResponseOK(new StreamContent(response.Item2), response.Item3));
            }
        }
Ejemplo n.º 14
0
        public async Task <ActionResult> Index()
        {
            var userId = User.Identity.Name;
            var tenant = new MailAddress(userId).Host.Replace(".", "-");

            var wopiFileRepository = new WopiFileRepository();
            var wopiFiles          = await wopiFileRepository.GetFilesByTenant(tenant);

            var wopiFileModels = new List <WopiFileModel>();

            foreach (var wopiFile in wopiFiles)
            {
                wopiFileModels.Add(await wopiFile.ToWopiFileModel());
            }


            // Return the view with the files
            return(View(wopiFileModels));
        }
        public async Task TestAddFileGetFileDeleteFile()
        {
            var fileRepository = new WopiFileRepository();

            using (var fileStream = new FileStream(fileName, FileMode.Open))
            {
                var fileName  = Path.GetFileName(this.fileName);
                var wopiFile1 = await fileRepository.AddFile(tenant1User1, tenant1, fileStream, fileName);

                var wopiFile2 = await fileRepository.GetFileInfo(wopiFile1.FileId, tenant1User1);

                Assert.IsNotNull(wopiFile2);
                Assert.AreEqual(wopiFile1.FileId, wopiFile2.FileId);
                Assert.IsTrue(wopiFile2.FilePermissions.Count == 1);

                var contentResponse = await fileRepository.GetFileContent(wopiFile1.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, contentResponse.Item1);
                using (var stream = contentResponse.Item2)
                {
                    Assert.IsNotNull(stream);
                    Assert.IsTrue(stream.Length > 0);
                }

                var deleteResponse = await fileRepository.DeleteFile(wopiFile1.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
                using (var wopiContext = new WopiContext())
                {
                    var file = await wopiContext.Files.Where(f => f.FileId == wopiFile1.FileId).FirstOrDefaultAsync();

                    Assert.IsNull(file);
                    var filePermission = await wopiContext.FilePermissions.Where(f => f.FileId == wopiFile1.FileId).FirstOrDefaultAsync();

                    Assert.IsNull(filePermission);

                    contentResponse = await fileRepository.GetFileContent(wopiFile1.FileId, wopiFile1.Container);

                    Assert.AreEqual(HttpStatusCode.NotFound, contentResponse.Item1);
                    Assert.IsNull(contentResponse.Item2);
                }
            }
        }
Ejemplo n.º 16
0
        public override async Task <WopiResponse> DeleteFile(DeleteFileRequest deleteFileRequest)
        {
            var userId = WopiSecurity.GetIdentityNameFromToken(deleteFileRequest.AccessToken);
            var wopiFileRespository = new WopiFileRepository();
            var response            = await wopiFileRespository.DeleteFile(deleteFileRequest.ResourceId, userId);

            if (response == HttpStatusCode.NotFound)
            {
                return(deleteFileRequest.ResponseNotFound());
            }
            else if (response == HttpStatusCode.OK)
            {
                return(deleteFileRequest.ResponseOK());
            }
            else
            {
                return(deleteFileRequest.ResponseServerError(string.Format("Unknown HTTPStatusCode from WopiFileRepository.UpdateFileContent: {0}", response)));
            }
        }
Ejemplo n.º 17
0
        public override async Task <WopiResponse> PutUserInfo(PutUserInfoRequest putUserInfoRequest)
        {
            var userId = WopiSecurity.GetIdentityNameFromToken(putUserInfoRequest.AccessToken);
            var wopiFileRespository = new WopiFileRepository();
            var response            = await wopiFileRespository.SaveWopiUserInfo(putUserInfoRequest.ResourceId, userId, putUserInfoRequest.UserInfo);

            if (response == HttpStatusCode.NotFound)
            {
                return(putUserInfoRequest.ResponseNotFound());
            }
            else if (response == HttpStatusCode.OK)
            {
                return(putUserInfoRequest.ResponseOK());
            }
            else
            {
                return(putUserInfoRequest.ResponseServerError(string.Format("Unknown HTTPStatusCode from WopiFileRepository.SaveWopiUserInfo: {0}", response)));
            }
        }
Ejemplo n.º 18
0
        public override async Task <WopiResponse> PutFile(PutFileRequest putFileRequest)
        {
            var userId = WopiSecurity.GetIdentityNameFromToken(putFileRequest.AccessToken);
            var wopiFileRespository = new WopiFileRepository();
            var response            = await wopiFileRespository.UpdateFileContent(putFileRequest.ResourceId, userId, putFileRequest.Lock, await putFileRequest.Content.ReadAsStreamAsync());

            if (response.Item1 == HttpStatusCode.NotFound)
            {
                return(putFileRequest.ResponseNotFound());
            }
            else if (response.Item1 == HttpStatusCode.Conflict)
            {
                return(putFileRequest.ResponseLockConflict(response.Item2));
            }
            else if (response.Item1 == HttpStatusCode.OK)
            {
                return(putFileRequest.ResponseOK(response.Item3));
            }
            else
            {
                return(putFileRequest.ResponseServerError(string.Format("Unknown HTTPStatusCode from WopiFileRepository.UpdateFileContent: {0}", response.Item1)));
            }
        }
        public async Task TestLockAndUnlockFile()
        {
            var fileRepository = new WopiFileRepository();

            using (var fileStream = new FileStream(fileName, FileMode.Open))
            {
                var fileName = Path.GetFileName(this.fileName);
                var wopiFile = await fileRepository.AddFile(tenant1User1, tenant1, fileStream, fileName);

                var lockResponse = await fileRepository.LockFile(wopiFile.FileId, tenant1User1, lockId, null, 0.10);

                Assert.AreEqual(HttpStatusCode.OK, lockResponse.Item1);

                using (var wopiContext = new WopiContext())
                {
                    var file = await wopiContext.Files.Where(f => f.FileId == wopiFile.FileId).FirstOrDefaultAsync();

                    Assert.AreEqual(lockId, file.LockValue);
                    Assert.IsTrue(file.LockExpires.Value > DateTime.UtcNow);
                }

                var unlockResponse = await fileRepository.UnlockFile(wopiFile.FileId, tenant1User1, lockId);

                Assert.AreEqual(HttpStatusCode.OK, unlockResponse.Item1);

                using (var wopiContext = new WopiContext())
                {
                    var file = await wopiContext.Files.Where(f => f.FileId == wopiFile.FileId).FirstOrDefaultAsync();

                    Assert.IsNull(file.LockValue);
                }
                var deleteResponse = await fileRepository.DeleteFile(wopiFile.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
            }
        }
        public async Task TestSaveWopiUserInfo()
        {
            var fileName = Path.GetFileName(this.fileName);

            using (var fileStream = new FileStream(this.fileName, FileMode.Open))
            {
                var fileRepository = new WopiFileRepository();

                var wopiFile = await fileRepository.AddFile(tenant1User1, tenant1, fileStream, fileName);

                await fileRepository.SaveWopiUserInfo(wopiFile.FileId, tenant1User1, wopiUserInfo);

                using (var wopiContext = new WopiContext())
                {
                    var filePermission = await wopiContext.FilePermissions.Where(fp => fp.UserId == tenant1User1 && fp.FileId == wopiFile.FileId).FirstOrDefaultAsync();

                    Assert.AreEqual(wopiUserInfo, filePermission.UserInfo);
                }

                var deleteResponse = await fileRepository.DeleteFile(wopiFile.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
            }
        }
        public async Task TestAddFileGetFileTenantUserDeleteFile()
        {
            var fileRepository = new WopiFileRepository();

            using (var fileStream = new FileStream(fileName, FileMode.Open))
            {
                var fileName = Path.GetFileName(this.fileName);
                var wopiFile = await fileRepository.AddFile(tenant1User1, tenant1, fileStream, fileName);

                Assert.IsNotNull(wopiFile);

                var fileInfoResponse1 = await fileRepository.GetFileInfoByTenantUser(wopiFile.FileId, tenant1User2, tenant1);

                Assert.AreEqual(HttpStatusCode.OK, fileInfoResponse1.Item1);

                var fileInfoResponse2 = await fileRepository.GetFileInfoByTenantUser(wopiFile.FileId, tenant2User1, tenant2);

                Assert.AreEqual(HttpStatusCode.Unauthorized, fileInfoResponse2.Item1);

                var deleteResponse = await fileRepository.DeleteFile(wopiFile.FileId, tenant1User1);

                Assert.AreEqual(HttpStatusCode.OK, deleteResponse);
            }
        }
Ejemplo n.º 22
0
        public override async Task <WopiResponse> CheckFileInfo(CheckFileInfoRequest checkFileInfoRequest)
        {
            var userId = WopiSecurity.GetIdentityNameFromToken(checkFileInfoRequest.AccessToken);

            // For this demo server, determine tenant by host part of email address
            var tenant = new MailAddress(userId).Host.Replace(".", "-");

            // Lookup the file in the database using special repository method which grants access limited access to users in same tenant (same email domain)
            var wopiFileRepository = new WopiFileRepository();
            var response           = await wopiFileRepository.GetFileInfoByTenantUser(checkFileInfoRequest.ResourceId, userId, tenant);

            // Check for null file
            if (response.Item1 == HttpStatusCode.NotFound)
            {
                return(checkFileInfoRequest.ResponseNotFound());
            }

            else if (response.Item1 == HttpStatusCode.OK)
            {
                var wopiFile = response.Item2;
                // Get discovery information
                var actions = await WopiDiscovery.GetActions();

                string hostViewUrl = null, hostEditUrl = null;

                var closeUrl = String.Format("https://{0}", checkFileInfoRequest.RequestUri.Authority);

                var view = actions.FirstOrDefault(i => i.ext == wopiFile.FileExtension && i.name == "view");
                if (view != null)
                {
                    hostViewUrl = WopiDiscovery.GetActionUrl(view, wopiFile.FileId.ToString(), checkFileInfoRequest.RequestUri.Authority);
                }

                var edit = actions.FirstOrDefault(i => i.ext == wopiFile.FileExtension && i.name == "edit");
                if (edit != null)
                {
                    hostEditUrl = WopiDiscovery.GetActionUrl(edit, wopiFile.FileId.ToString(), checkFileInfoRequest.RequestUri.Authority);
                }

                // Write the response and return a success 200
                var wopiResponse = checkFileInfoRequest.ResponseOK(wopiFile.FileName, wopiFile.OwnerId, wopiFile.Size, userId, wopiFile.Version.ToString());
                // Add optional items
                wopiResponse.CloseUrl = new Uri(closeUrl);
                if (hostViewUrl != null)
                {
                    wopiResponse.HostViewUrl = new Uri(hostViewUrl);
                }
                if (hostEditUrl != null)
                {
                    wopiResponse.HostEditUrl = new Uri(hostEditUrl);
                }

                wopiResponse.UserInfo = wopiFile.FilePermissions.First().UserInfo;

                return(wopiResponse);
            }
            else
            {
                return(checkFileInfoRequest.ResponseServerError(string.Format("Unknown response from WopiFileRepository.GetFileInfoByTenantUser: {0}", response.Item1)));
            }
        }