Esempio n. 1
0
        /// <summary>
        /// Populates a file with action details from WOPI discovery based on the file extension
        /// </summary>
        public async static Task PopulateActions(this DetailedFileModel file)
        {
            // Get the discovery informations
            var actions = await GetDiscoveryInfo();

            var fileExt = file.BaseFileName.Substring(file.BaseFileName.LastIndexOf('.') + 1).ToLower();

            file.Actions = actions.Where(i => i.ext == fileExt).OrderBy(i => i.isDefault).ToList();
        }
Esempio n. 2
0
        public static void CreateItem(DetailedFileModel item)
        {
            var json       = JsonConvert.SerializeObject(item);
            var dictionary = JsonConvert.DeserializeObject <Dictionary <string, Object> >(json);
            var r          = table().NewRow();

            foreach (var kv in dictionary)
            {
                r[kv.Key] = kv.Value;
            }

            r.AcceptChanges();
            table().Rows.Add(r);
            save();
        }
Esempio n. 3
0
        public async Task <ActionResult> Add()
        {
            try
            {
                // Create the file entity
                DetailedFileModel file = new DetailedFileModel()
                {
                    id           = Guid.NewGuid(),
                    OwnerId      = User.Identity.Name.ToLower(),
                    BaseFileName = HttpUtility.UrlDecode(Request["HTTP_X_FILE_NAME"]),
                    Size         = Convert.ToInt32(Request["HTTP_X_FILE_SIZE"]),
                    Container    = getUserContainer(),
                    Version      = 1
                };

                // Populate valid actions for each of the files
                await file.PopulateActions();

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

                var id = await Utils.AzureStorageUtil.UploadFile(file.id.ToString(), file.Container, bytes);

                // Write the details into documentDB
                await DocumentDBRepository <FileModel> .CreateItemAsync("Files", (FileModel)file);

                // Return json representation of information
                return(Json(new { success = true, file = file }));
            }
            catch (Exception)
            {
                // Something failed...return false
                return(Json(new { success = false }));
            }
        }
Esempio n. 4
0
        public static IEnumerable <DetailedFileModel> GetItems(string Query = "")
        {
            var r = table().Select(Query);
            var l = new List <DetailedFileModel>();

            for (int i = 0; i < r.Length; i++)
            {
                StringBuilder sb = new StringBuilder();
                StringWriter  sw = new StringWriter(sb);

                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.WriteStartObject();

                    foreach (DataColumn c in table().Columns)
                    {
                        writer.WritePropertyName(c.ColumnName);
                        writer.WriteValue(r[i][c.ColumnName]);
                    }
                    writer.WriteEnd();
                    writer.WriteEndObject();
                }

                DetailedFileModel f = JsonConvert.DeserializeObject <DetailedFileModel>(sb.ToString());

                l.Add(f);
            }

            return(l);

            //collectionId = collectionToQuery;
            //return Client.CreateDocumentQuery<T>(Collection.DocumentsLink)
            //    .Where(predicate)
            //    .AsEnumerable();
        }
        /// <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, DetailedFileModel file, List <WopiAction> actions)
        {
            // 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
                DetailedFileModel newFile = new DetailedFileModel()
                {
                    id           = Guid.NewGuid(),
                    OwnerId      = file.OwnerId,
                    BaseFileName = fileName,
                    Size         = context.Request.InputStream.Length,
                    Container    = file.Container,
                    Version      = 1
                };

                // 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 = await Utils.AzureStorageUtil.UploadFile(newFile.id.ToString(), newFile.Container, bytes);

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

                // Get access token for the new file
                WopiSecurity security = new WopiSecurity();
                var          token    = security.GenerateToken(newFile.OwnerId, newFile.Container, newFile.id.ToString());
                var          tokenStr = 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"));
            }
        }