Files
document-server-integration/web/documentserver-example/csharp/Default.aspx.cs
2017-09-26 13:24:34 +03:00

343 lines
12 KiB
C#

/*
*
* (c) Copyright Ascensio System Limited 2010-2017
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using System.Web.Configuration;
using System.Web.UI;
using ASC.Api.DocumentConverter;
namespace OnlineEditorsExample
{
internal static class FileType
{
public static readonly List<string> ExtsSpreadsheet = new List<string>
{
".xls", ".xlsx", ".xlsm",
".xlt", ".xltx", ".xltm",
".ods", ".fods", ".csv"
};
public static readonly List<string> ExtsPresentation = new List<string>
{
".pps", ".ppsx", ".ppsm",
".ppt", ".pptx", ".pptm",
".pot", ".potx", ".potm",
".odp", ".fodp"
};
public static readonly List<string> ExtsDocument = new List<string>
{
".doc", ".docx", ".docm",
".dot", ".dotx", ".dotm",
".odt", ".fodt", ".rtf", ".txt",
".html", ".htm", ".mht",
".pdf", ".djvu", ".fb2", ".epub", ".xps"
};
public static string GetInternalExtension(string extension)
{
extension = Path.GetExtension(extension).ToLower();
if (ExtsDocument.Contains(extension)) return ".docx";
if (ExtsSpreadsheet.Contains(extension)) return ".xlsx";
if (ExtsPresentation.Contains(extension)) return ".pptx";
return string.Empty;
}
}
public partial class _Default : Page
{
public static UriBuilder Host
{
get
{
var uri = new UriBuilder(HttpContext.Current.Request.Url) {Query = ""};
var requestHost = HttpContext.Current.Request.Headers["Host"];
if (!string.IsNullOrEmpty(requestHost))
uri = new UriBuilder(uri.Scheme + "://" + requestHost);
return uri;
}
}
public static string VirtualPath
{
get
{
return
HttpRuntime.AppDomainAppVirtualPath
+ (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
+ WebConfigurationManager.AppSettings["storage-path"]
+ CurUserHostAddress(null) + "/";
}
}
private static bool? _ismono;
public static bool IsMono
{
get
{
return _ismono.HasValue ? _ismono.Value : (_ismono = (bool?)(Type.GetType("Mono.Runtime") != null)).Value;
}
}
private static long MaxFileSize
{
get
{
long size;
long.TryParse(WebConfigurationManager.AppSettings["filesize-max"], out size);
return size > 0 ? size : 5*1024*1024;
}
}
private static List<string> FileExts
{
get { return ViewedExts.Concat(EditedExts).Concat(ConvertExts).ToList(); }
}
private static List<string> ViewedExts
{
get { return (WebConfigurationManager.AppSettings["files.docservice.viewed-docs"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); }
}
public static List<string> EditedExts
{
get { return (WebConfigurationManager.AppSettings["files.docservice.edited-docs"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); }
}
public static List<string> ConvertExts
{
get { return (WebConfigurationManager.AppSettings["files.docservice.convert-docs"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); }
}
public static bool EditMode
{
get { return (WebConfigurationManager.AppSettings["mode"] ?? "") != "view"; }
}
private static string _fileName;
public static string CurUserHostAddress(string userAddress)
{
return Regex.Replace(userAddress ?? HttpContext.Current.Request.UserHostAddress, "[^0-9a-zA-Z.=]", "_");
}
public static string StoragePath(string fileName, string userAddress)
{
var directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(userAddress) + "\\";
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
return directory + fileName;
}
public static string FileUri(string fileName)
{
var uri = Host;
uri.Path = VirtualPath + fileName;
return uri.ToString();
}
public static string DocumentType(string fileName)
{
var ext = Path.GetExtension(fileName).ToLower();
if (FileType.ExtsDocument.Contains(ext)) return "text";
if (FileType.ExtsSpreadsheet.Contains(ext)) return "spreadsheet";
if (FileType.ExtsPresentation.Contains(ext)) return "presentation";
return string.Empty;
}
protected string UrlPreloadScripts = WebConfigurationManager.AppSettings["files.docservice.url.preloader"];
protected void Page_Load(object sender, EventArgs e)
{
}
public static string DoUpload(HttpContext context)
{
var httpPostedFile = context.Request.Files[0];
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
var files = httpPostedFile.FileName.Split(new char[] { '\\' });
_fileName = files[files.Length - 1];
}
else
{
_fileName = httpPostedFile.FileName;
}
var curSize = httpPostedFile.ContentLength;
if (MaxFileSize < curSize || curSize <= 0)
{
throw new Exception("File size is incorrect");
}
var curExt = (Path.GetExtension(_fileName) ?? "").ToLower();
if (!FileExts.Contains(curExt))
{
throw new Exception("File type is not supported");
}
_fileName = GetCorrectName(_fileName);
var savedFileName = StoragePath(_fileName, null);
httpPostedFile.SaveAs(savedFileName);
return _fileName;
}
public static string DoUpload(string fileUri)
{
_fileName = GetCorrectName(Path.GetFileName(fileUri));
var curExt = (Path.GetExtension(_fileName) ?? "").ToLower();
if (!FileExts.Contains(curExt))
{
throw new Exception("File type is not supported");
}
var req = (HttpWebRequest)WebRequest.Create(fileUri);
try
{
// hack. http://ubuntuforums.org/showthread.php?t=1841740
if (IsMono)
{
ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
}
using (var stream = req.GetResponse().GetResponseStream())
{
if (stream == null) throw new Exception("stream is null");
const int bufferSize = 4096;
using (var fs = File.Open(StoragePath(_fileName, null), FileMode.Create))
{
var buffer = new byte[bufferSize];
int readed;
while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
{
fs.Write(buffer, 0, readed);
}
}
}
}
catch (Exception)
{
}
return _fileName;
}
public static string DoConvert(HttpContext context)
{
_fileName = context.Request["filename"];
var extension = (Path.GetExtension(_fileName) ?? "").Trim('.');
var internalExtension = FileType.GetInternalExtension(_fileName).Trim('.');
if (ConvertExts.Contains("." + extension)
&& !string.IsNullOrEmpty(internalExtension))
{
var key = ServiceConverter.GenerateRevisionId(FileUri(_fileName));
string newFileUri;
var result = ServiceConverter.GetConvertedUri(FileUri(_fileName), extension, internalExtension, key, true, out newFileUri);
if (result != 100)
{
return "{ \"step\" : \"" + result + "\", \"filename\" : \"" + _fileName + "\"}";
}
var fileName = GetCorrectName(Path.GetFileNameWithoutExtension(_fileName) + "." + internalExtension);
var req = (HttpWebRequest)WebRequest.Create(newFileUri);
// hack. http://ubuntuforums.org/showthread.php?t=1841740
if (IsMono)
{
ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
}
using (var stream = req.GetResponse().GetResponseStream())
{
if (stream == null) throw new Exception("Stream is null");
const int bufferSize = 4096;
using (var fs = File.Open(StoragePath(fileName, null), FileMode.Create))
{
var buffer = new byte[bufferSize];
int readed;
while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
{
fs.Write(buffer, 0, readed);
}
}
}
File.Delete(StoragePath(_fileName, null));
_fileName = fileName;
}
return "{ \"filename\" : \"" + _fileName + "\"}";
}
public static string GetCorrectName(string fileName, string userAddress = null)
{
var baseName = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName);
var name = baseName + ext;
for (var i = 1; File.Exists(StoragePath(name, userAddress)); i++)
{
name = baseName + " (" + i + ")" + ext;
}
return name;
}
protected static List<string> GetStoredFiles()
{
var directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(null) + "\\";
if (!Directory.Exists(directory)) return new List<string>();
var directoryInfo = new DirectoryInfo(directory);
var storedFiles = directoryInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly).Select(fileInfo => fileInfo.Name).ToList();
return storedFiles;
}
}
}