public static bool HaveExternalIP()
        {
            if (!_haveExternalIP.HasValue)
            {
                string convertUri;
                try
                {
                    var uri = new UriBuilder(HttpContext.Current.Request.Url)
                    {
                        Path  = VirtualPath + "demo.docx",
                        Query = ""
                    };
                    var fileUri = uri.ToString();

                    ServiceConverter.GetConvertedUri(fileUri, "docx", "docx", Guid.NewGuid().ToString(), false, out convertUri);
                }
                catch
                {
                    convertUri = string.Empty;
                }

                _haveExternalIP = !string.IsNullOrEmpty(convertUri);
            }

            return(_haveExternalIP.Value);
        }
Example #2
0
        public static bool HaveExternalIP()
        {
            if (!_haveExternalIP.HasValue)
            {
                string convertUri;
                try
                {
                    var uri = new UriBuilder(HttpContext.Current.Request.Url)
                    {
                        Path = HttpRuntime.AppDomainAppVirtualPath + "/"
                               + WebConfigurationManager.AppSettings["storage-path"]
                               + CurUserHostAddress + "/"
                               + "demo.docx",
                        Query = ""
                    };
                    var fileUri = uri.ToString();

                    ServiceConverter.GetConvertedUri(fileUri, "docx", "docx", Guid.NewGuid().ToString(), false, out convertUri);
                }
                catch
                {
                    convertUri = string.Empty;
                }

                _haveExternalIP = !string.IsNullOrEmpty(convertUri);
            }

            return(_haveExternalIP.Value);
        }
        private static void Convert(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                var fileName = Path.GetFileName(context.Request["filename"]);
                var fileUri  = DocManagerHelper.GetFileUri(fileName, true);

                var extension         = (Path.GetExtension(fileUri) ?? "").Trim('.');
                var internalExtension = DocManagerHelper.GetInternalExtension(FileUtility.GetFileType(fileName)).Trim('.');

                if (DocManagerHelper.ConvertExts.Contains("." + extension) &&
                    !string.IsNullOrEmpty(internalExtension))
                {
                    var key = ServiceConverter.GenerateRevisionId(fileUri);

                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(fileUri, extension, internalExtension, key, true, out newFileUri);
                    if (result != 100)
                    {
                        context.Response.Write("{ \"step\" : \"" + result + "\", \"filename\" : \"" + fileName + "\"}");
                        return;
                    }

                    var correctName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "." + internalExtension);

                    var req = (HttpWebRequest)WebRequest.Create(newFileUri);

                    using (var stream = req.GetResponse().GetResponseStream())
                    {
                        if (stream == null)
                        {
                            throw new Exception("Stream is null");
                        }
                        const int bufferSize = 4096;

                        using (var fs = File.Open(DocManagerHelper.StoragePath(correctName), FileMode.Create))
                        {
                            var buffer = new byte[bufferSize];
                            int readed;
                            while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                            {
                                fs.Write(buffer, 0, readed);
                            }
                        }
                    }

                    Remove(fileName);
                    fileName = correctName;
                    DocManagerHelper.CreateMeta(fileName, context.Request.Cookies.GetOrDefault("uid", ""), context.Request.Cookies.GetOrDefault("uname", ""));
                }

                context.Response.Write("{ \"filename\" : \"" + fileName + "\"}");
            }
            catch (Exception e)
            {
                context.Response.Write("{ \"error\": \"" + e.Message + "\"}");
            }
        }
        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 + "\"}");
        }
Example #5
0
        public static string DoConvert(string fileId)
        {
            _fileName = fileId;

            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);

                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, 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);
                _fileName = fileName;
            }

            return("{ \"filename\" : \"" + _fileName + "\"}");
        }
Example #6
0
        public static bool HaveExternalIP()
        {
            if (!_haveExternalIP.HasValue)
            {
                string convertUri;
                try
                {
                    var uri = Host;
                    uri.Path = VirtualPath + "demo.docx";
                    var fileUri = uri.ToString();

                    ServiceConverter.GetConvertedUri(fileUri, "docx", "docx", Guid.NewGuid().ToString(), false, out convertUri);
                }
                catch
                {
                    convertUri = string.Empty;
                }

                _haveExternalIP = !string.IsNullOrEmpty(convertUri);
            }

            return(_haveExternalIP.Value);
        }
        // file saving process
        public static int processSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            if (fileData["url"].Equals(null))
            {
                throw new Exception("DownloadUrl is null");
            }
            var downloadUri = (string)fileData["url"];
            var curExt      = Path.GetExtension(fileName).ToLower(); // get current file extension

            var downloadExt = fileData.ContainsKey("filetype")
                ? "." + (string)fileData["filetype"]
                : Path.GetExtension(downloadUri).ToLower() ?? ""; // TODO: Delete in version 7.0 or higher. Support for versions below 7.0

            var newFileName = fileName;

            // convert downloaded file to the file with the current extension if these extensions aren't equal
            if (!downloadExt.Equals(curExt, StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    // convert file and give url to a new file
                    string newFileUri;
                    ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        // get the correct file name if it already exists
                        newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }
            }

            _Default.VerifySSL();

            var storagePath = _Default.StoragePath(newFileName, userAddress); // get the file path
            var histDir     = _Default.HistoryDir(storagePath);               // get the path to the history directory

            if (!Directory.Exists(histDir))
            {
                Directory.CreateDirectory(histDir);
            }

            var versionDir = _Default.VersionDir(histDir, _Default.GetFileVersion(histDir));  // get the path to the file version

            if (!Directory.Exists(versionDir))
            {
                Directory.CreateDirectory(versionDir);                                 // if the path doesn't exist, create it
            }
            // get the path to the previous file version and rename the storage path with it
            File.Copy(_Default.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));

            DownloadToFile(downloadUri, storagePath);                                             // save file to the storage directory
            DownloadToFile((string)fileData["changesurl"], Path.Combine(versionDir, "diff.zip")); // save file changes to the diff.zip archive

            var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;

            if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
            {
                var jss = new JavaScriptSerializer();
                hist = jss.Serialize(fileData["history"]);
            }

            if (!string.IsNullOrEmpty(hist))
            {
                File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist);  // write the history changes to the changes.json file
            }

            File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]); // write the key value to the key.txt file

            string forcesavePath = _Default.ForcesavePath(newFileName, userAddress, false);  // get the path to the forcesaved file version

            if (!forcesavePath.Equals(""))                                                   // if the forcesaved file version exists
            {
                File.Delete(forcesavePath);                                                  // remove it
            }

            return(0);
        }
        // converting a file
        public static string DoConvert(HttpContext context)
        {
            string fileData;

            try
            {
                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        fileData = readStream.ReadToEnd();
                        if (string.IsNullOrEmpty(fileData))
                        {
                            context.Response.Write("{\"error\":1,\"message\":\"Request stream is empty\"}");
                        }
                    }
            }
            catch (Exception e)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            var jss  = new JavaScriptSerializer();
            var body = jss.Deserialize <Dictionary <string, object> >(fileData);

            _fileName = Path.GetFileName(body["filename"].ToString());
            var filePass = body["filePass"] != null ? body["filePass"].ToString() : null;
            var lang     = context.Request.Cookies.GetOrDefault("ulang", null);

            var extension         = (Path.GetExtension(_fileName).ToLower() ?? "").Trim('.');
            var internalExtension = FileType.GetInternalExtension(_fileName).Trim('.');

            // check if the file with such an extension can be converted
            if (ConvertExts.Contains("." + extension) &&
                !string.IsNullOrEmpty(internalExtension))
            {
                // generate document key
                var key = ServiceConverter.GenerateRevisionId(FileUri(_fileName, true));

                var fileUrl = new UriBuilder(_Default.GetServerUrl(true));
                fileUrl.Path = HttpRuntime.AppDomainAppVirtualPath
                               + (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
                               + "webeditor.ashx";
                fileUrl.Query = "type=download&fileName=" + HttpUtility.UrlEncode(_fileName)
                                + "&userAddress=" + HttpUtility.UrlEncode(HttpContext.Current.Request.UserHostAddress);

                // get the url to the converted file
                string newFileUri;
                var    result = ServiceConverter.GetConvertedUri(fileUrl.ToString(), extension, internalExtension, key, true, out newFileUri, filePass, lang);
                if (result != 100)
                {
                    return("{ \"step\" : \"" + result + "\", \"filename\" : \"" + _fileName + "\"}");
                }

                // get a file name of an internal file extension with an index if the file with such a name already exists
                var fileName = GetCorrectName(Path.GetFileNameWithoutExtension(_fileName) + "." + internalExtension);

                var req = (HttpWebRequest)WebRequest.Create(newFileUri);

                VerifySSL();

                using (var stream = req.GetResponse().GetResponseStream())  // get response stream of the converting file
                {
                    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);  // write bytes to the output stream
                        }
                    }
                }

                // remove the original file and its history if it exists
                var storagePath = StoragePath(_fileName, null);
                var histDir     = HistoryDir(storagePath);
                File.Delete(storagePath);
                if (Directory.Exists(histDir))
                {
                    Directory.Delete(histDir, true);
                }

                // create meta information about the converted file with user id and name specified
                _fileName = fileName;
                var id   = context.Request.Cookies.GetOrDefault("uid", null);
                var user = Users.getUser(id);  // get the user
                DocEditor.CreateMeta(_fileName, user.id, user.name, null);
            }

            return("{ \"filename\" : \"" + _fileName + "\"}");
        }
Example #9
0
        private static void Track(HttpContext context)
        {
            var userAddress = context.Request["userAddress"];
            var fileName    = context.Request["fileName"];

            string body;

            try
            {
                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        body = readStream.ReadToEnd();
                    }
            }
            catch (Exception e)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            var jss = new JavaScriptSerializer();

            if (string.IsNullOrEmpty(body))
            {
                return;
            }
            var fileData = jss.Deserialize <Dictionary <string, object> >(body);

            if (JwtManager.Enabled)
            {
                if (fileData.ContainsKey("token"))
                {
                    fileData = jss.Deserialize <Dictionary <string, object> >(JwtManager.Decode(fileData["token"].ToString()));
                }
                else if (context.Request.Headers.AllKeys.Contains("Authorization", StringComparer.InvariantCultureIgnoreCase))
                {
                    var headerToken = context.Request.Headers.Get("Authorization").Substring("Bearer ".Length);
                    fileData = (Dictionary <string, object>)jss.Deserialize <Dictionary <string, object> >(JwtManager.Decode(headerToken))["payload"];
                }
                else
                {
                    throw new Exception("Expected JWT");
                }
            }

            var status = (TrackerStatus)(int)fileData["status"];

            switch (status)
            {
            case TrackerStatus.MustSave:
            case TrackerStatus.Corrupted:
                var downloadUri = (string)fileData["url"];

                var curExt      = Path.GetExtension(fileName);
                var downloadExt = Path.GetExtension(downloadUri) ?? "";
                if (!downloadExt.Equals(curExt, StringComparison.InvariantCultureIgnoreCase))
                {
                    var key = ServiceConverter.GenerateRevisionId(downloadUri);

                    try
                    {
                        string newFileUri;
                        ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, key, false, out newFileUri);
                        downloadUri = newFileUri;
                    }
                    catch (Exception ex)
                    {
                        fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                }

                // hack. http://ubuntuforums.org/showthread.php?t=1841740
                if (_Default.IsMono)
                {
                    ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                }

                var saved = 1;
                try
                {
                    var storagePath = _Default.StoragePath(fileName, userAddress);
                    var histDir     = _Default.HistoryDir(storagePath);
                    var versionDir  = _Default.VersionDir(histDir, _Default.GetFileVersion(histDir) + 1);

                    if (!Directory.Exists(versionDir))
                    {
                        Directory.CreateDirectory(versionDir);
                    }

                    File.Copy(storagePath, Path.Combine(versionDir, "prev" + curExt));

                    DownloadToFile(downloadUri, _Default.StoragePath(fileName, userAddress));
                    DownloadToFile((string)fileData["changesurl"], Path.Combine(versionDir, "diff.zip"));

                    var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;
                    if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
                    {
                        hist = jss.Serialize(fileData["history"]);
                    }

                    if (!string.IsNullOrEmpty(hist))
                    {
                        File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist);
                    }

                    File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]);
                }
                catch (Exception)
                {
                    saved = 0;
                }

                break;
            }
            context.Response.Write("{\"error\":0}");
        }
        // file force saving process
        public static int processForceSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            if (fileData["url"].Equals(null))
            {
                throw new Exception("DownloadUrl is null");
            }
            var downloadUri = (string)fileData["url"];

            string curExt = Path.GetExtension(fileName).ToLower();  // get current file extension

            var downloadExt = fileData.ContainsKey("filetype")
                ? "." + (string)fileData["filetype"]
                : Path.GetExtension(downloadUri).ToLower(); // TODO: Delete in version 7.0 or higher. Support for versions below 7.0

            Boolean newFileName = false;

            // convert downloaded file to the file with the current extension if these extensions aren't equal
            if (!curExt.Equals(downloadExt))
            {
                try
                {
                    // convert file and give url to a new file
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        newFileName = true;
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = true;
                }
            }

            _Default.VerifySSL();

            string  forcesavePath = "";
            Boolean isSubmitForm  = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm

            if (isSubmitForm)                                                         // if the form is submitted
            {
                if (newFileName)
                {
                    fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress);  // get the correct file name if it already exists
                }
                else
                {
                    fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + curExt, userAddress);
                }
                forcesavePath = _Default.StoragePath(fileName, userAddress);
            }
            else
            {
                if (newFileName)
                {
                    fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }

                forcesavePath = _Default.ForcesavePath(fileName, userAddress, false);
                if (forcesavePath.Equals(""))  // create forcesave path if it doesn't exist
                {
                    forcesavePath = _Default.ForcesavePath(fileName, userAddress, true);
                }
            }

            DownloadToFile(downloadUri, forcesavePath);

            if (isSubmitForm)
            {
                var jss     = new JavaScriptSerializer();
                var actions = jss.Deserialize <List <object> >(jss.Serialize(fileData["actions"]));
                var action  = jss.Deserialize <Dictionary <string, object> >(jss.Serialize(actions[0]));
                var user    = action["userid"].ToString();                         // get the user id
                DocEditor.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for the forcesaved file
            }

            return(0);
        }
        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);
                        }
                    }
                }

                var storagePath = StoragePath(_fileName, null);
                var histDir     = HistoryDir(storagePath);
                File.Delete(storagePath);
                if (Directory.Exists(histDir))
                {
                    Directory.Delete(histDir, true);
                }

                _fileName = fileName;
                histDir   = HistoryDir(StoragePath(_fileName, null));
                Directory.CreateDirectory(histDir);
                File.WriteAllText(Path.Combine(histDir, "createdInfo.json"), new JavaScriptSerializer().Serialize(new Dictionary <string, object> {
                    { "created", DateTime.Now.ToString() },
                    { "id", context.Request.Cookies.GetOrDefault("uid", "uid-1") },
                    { "name", context.Request.Cookies.GetOrDefault("uname", "John Smith") }
                }));
            }

            return("{ \"filename\" : \"" + _fileName + "\"}");
        }
        private static void Track(HttpContext context)
        {
            var userAddress = context.Request["userAddress"];
            var fileName    = context.Request["fileName"];

            string body;

            try
            {
                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        body = readStream.ReadToEnd();
                    }
            }
            catch (Exception e)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            var jss = new JavaScriptSerializer();

            if (string.IsNullOrEmpty(body))
            {
                return;
            }
            var fileData = jss.Deserialize <Dictionary <string, object> >(body);
            var status   = (TrackerStatus)(int)fileData["status"];

            switch (status)
            {
            case TrackerStatus.MustSave:
            case TrackerStatus.Corrupted:
                var downloadUri = (string)fileData["url"];

                var curExt      = Path.GetExtension(fileName);
                var downloadExt = Path.GetExtension(downloadUri) ?? "";
                if (!downloadExt.Equals(curExt, StringComparison.InvariantCultureIgnoreCase))
                {
                    var key = ServiceConverter.GenerateRevisionId(downloadUri);

                    try
                    {
                        string newFileUri;
                        ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, key, false, out newFileUri);
                        downloadUri = newFileUri;
                    }
                    catch (Exception ex)
                    {
                        fileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                }

                var req = (HttpWebRequest)WebRequest.Create(downloadUri);

                // hack. http://ubuntuforums.org/showthread.php?t=1841740
                if (_Default.IsMono)
                {
                    ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                }

                var saved = 1;
                try
                {
                    using (var stream = req.GetResponse().GetResponseStream())
                    {
                        if (stream == null)
                        {
                            throw new Exception("stream is null");
                        }
                        const int bufferSize = 4096;

                        var storagePath = _Default.StoragePath(fileName, userAddress);
                        using (var fs = File.Open(storagePath, FileMode.Create))
                        {
                            var buffer = new byte[bufferSize];
                            int readed;
                            while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                            {
                                fs.Write(buffer, 0, readed);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    saved = 0;
                }

                break;
            }
            context.Response.Write("{\"error\":0}");
        }
Example #13
0
        private static void Save(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var downloadUri = context.Request["fileuri"];
            var fileName    = context.Request["filename"];

            if (string.IsNullOrEmpty(downloadUri) || string.IsNullOrEmpty(fileName))
            {
                context.Response.Write("error");
                return;
            }

            var newType     = Path.GetExtension(downloadUri).Trim('.');
            var currentType = (context.Request["filetype"] ?? Path.GetExtension(fileName)).Trim('.');

            if (newType.ToLower() != currentType.ToLower())
            {
                var key = ServiceConverter.GenerateRevisionId(downloadUri);

                string newFileUri;
                try
                {
                    var result = ServiceConverter.GetConvertedUri(downloadUri, newType, currentType, key, false, out newFileUri);
                    if (result != 100)
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    context.Response.Write("error");
                    return;
                }
                downloadUri = newFileUri;
                newType     = currentType;
            }

            fileName = Path.GetFileNameWithoutExtension(fileName) + "." + newType;

            var req = (HttpWebRequest)WebRequest.Create(downloadUri);

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (_Default.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            try
            {
                using (var stream = req.GetResponse().GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(_Default.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)
            {
                context.Response.Write("error");
                return;
            }

            context.Response.Write("success");
        }
        // convert a file
        private static void Convert(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                string fileData;

                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        fileData = readStream.ReadToEnd();
                        if (string.IsNullOrEmpty(fileData))
                        {
                            context.Response.Write("{\"error\":1,\"message\":\"Request stream is empty\"}");
                        }
                    }

                var jss  = new JavaScriptSerializer();
                var body = jss.Deserialize <Dictionary <string, object> >(fileData);

                var fileName = Path.GetFileName(body["filename"].ToString());
                var lang     = context.Request.Cookies.GetOrDefault("ulang", null);
                var filePass = body["filePass"] != null ? body["filePass"].ToString() : null;
                var fileUri  = DocManagerHelper.GetDownloadUrl(fileName);

                var extension         = (Path.GetExtension(fileName).ToLower() ?? "").Trim('.');
                var internalExtension = DocManagerHelper.GetInternalExtension(FileUtility.GetFileType(fileName)).Trim('.');

                // check if the file with such an extension can be converted
                if (DocManagerHelper.ConvertExts.Contains("." + extension) &&
                    !string.IsNullOrEmpty(internalExtension))
                {
                    // generate document key
                    var key = ServiceConverter.GenerateRevisionId(fileUri);

                    var downloadUri = new UriBuilder(DocManagerHelper.GetServerUrl(true))
                    {
                        Path = HttpRuntime.AppDomainAppVirtualPath
                               + (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
                               + "webeditor.ashx",
                        Query = "type=download&fileName=" + HttpUtility.UrlEncode(fileName)
                    };

                    // get the url to the converted file
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri.ToString(), extension, internalExtension, key, true, out newFileUri, filePass, lang);
                    if (result != 100)
                    {
                        context.Response.Write("{ \"step\" : \"" + result + "\", \"filename\" : \"" + fileName + "\"}");
                        return;
                    }

                    // get a file name of an internal file extension with an index if the file with such a name already exists
                    var correctName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "." + internalExtension);

                    var req = (HttpWebRequest)WebRequest.Create(newFileUri);

                    DocManagerHelper.VerifySSL();

                    using (var stream = req.GetResponse().GetResponseStream())  // get response stream of the converting file
                    {
                        if (stream == null)
                        {
                            throw new Exception("Stream is null");
                        }
                        const int bufferSize = 4096;

                        using (var fs = File.Open(DocManagerHelper.StoragePath(correctName), FileMode.Create))
                        {
                            var buffer = new byte[bufferSize];
                            int readed;
                            while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                            {
                                fs.Write(buffer, 0, readed);  // write bytes to the output stream
                            }
                        }
                    }

                    Remove(fileName);       // remove the original file and its history if it exists
                    fileName = correctName; // create meta information about the converted file with user id and name specified
                    var id   = context.Request.Cookies.GetOrDefault("uid", null);
                    var user = Users.getUser(id);
                    DocManagerHelper.CreateMeta(fileName, user.id, user.name);
                }

                var documentType = FileUtility.GetFileType(fileName).ToString().ToLower();
                context.Response.Write("{ \"filename\" : \"" + fileName + "\", \"documentType\": \"" + documentType + "\" }");
            }
            catch (Exception e)
            {
                context.Response.Write("{ \"error\": \"" + e.Message + "\"}");
            }
        }
        public static int processSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            var downloadUri = (string)fileData["url"];
            var curExt      = Path.GetExtension(fileName);
            var downloadExt = Path.GetExtension(downloadUri) ?? "";
            var newFileName = fileName;

            if (!downloadExt.Equals(curExt, StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    string newFileUri;
                    ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }
            }

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (_Default.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            var storagePath = _Default.StoragePath(newFileName, userAddress);
            var histDir     = _Default.HistoryDir(storagePath);

            if (!Directory.Exists(histDir))
            {
                Directory.CreateDirectory(histDir);
            }

            var versionDir = _Default.VersionDir(histDir, _Default.GetFileVersion(histDir));

            if (!Directory.Exists(versionDir))
            {
                Directory.CreateDirectory(versionDir);
            }

            File.Copy(_Default.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));

            DownloadToFile(downloadUri, storagePath);
            DownloadToFile((string)fileData["changesurl"], Path.Combine(versionDir, "diff.zip"));

            var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;

            if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
            {
                var jss = new JavaScriptSerializer();
                hist = jss.Serialize(fileData["history"]);
            }

            if (!string.IsNullOrEmpty(hist))
            {
                File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist);
            }

            File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]);

            string forcesavePath = _Default.ForcesavePath(newFileName, userAddress, false);

            if (!forcesavePath.Equals(""))
            {
                File.Delete(forcesavePath);
            }

            return(0);
        }
        public static int processForceSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            var downloadUri = (string)fileData["url"];

            string curExt      = Path.GetExtension(fileName);
            string downloadExt = Path.GetExtension(downloadUri);
            var    newFileName = fileName;

            if (!curExt.Equals(downloadExt))
            {
                try
                {
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }
            }

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (_Default.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            string  forcesavePath = "";
            Boolean isSubmitForm  = fileData["forcesavetype"].ToString().Equals("3");

            if (isSubmitForm)
            {
                if (newFileName.Equals(fileName))
                {
                    newFileName = _Default.GetCorrectName(fileName, userAddress);
                }
                forcesavePath = _Default.StoragePath(newFileName, userAddress);
            }
            else
            {
                forcesavePath = _Default.ForcesavePath(newFileName, userAddress, false);
                if (forcesavePath.Equals(""))
                {
                    forcesavePath = _Default.ForcesavePath(newFileName, userAddress, true);
                }
            }

            DownloadToFile(downloadUri, forcesavePath);

            if (isSubmitForm)
            {
                var jss     = new JavaScriptSerializer();
                var actions = jss.Deserialize <List <object> >(jss.Serialize(fileData["actions"]));
                var action  = jss.Deserialize <Dictionary <string, object> >(jss.Serialize(actions[0]));
                var user    = action["userid"].ToString();
                DocEditor.CreateMeta(newFileName, user, "Filling Form", userAddress);
            }

            return(0);
        }
        private static void Save(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var downloadUri = context.Request["fileuri"].Replace(":80/", ":80/office/");
            var fileName    = context.Request["filename"];

            if (string.IsNullOrEmpty(downloadUri) || string.IsNullOrEmpty(fileName))
            {
                context.Response.Write("error");
                return;
            }

            var newType     = Path.GetExtension(downloadUri).Trim('.');
            var currentType = (context.Request["filetype"] ?? Path.GetExtension(fileName)).Trim('.');

            if (newType.ToLower() != currentType.ToLower())
            {
                var key = ServiceConverter.GenerateRevisionId(downloadUri);

                string newFileUri;
                try
                {
                    var result = ServiceConverter.GetConvertedUri(downloadUri, newType, currentType, key, false, out newFileUri);
                    if (result != 100)
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    context.Response.Write("error");
                    return;
                }
                downloadUri = newFileUri;
                newType     = currentType;
            }

            fileName = Path.GetFileNameWithoutExtension(fileName) + "." + newType;

            var req = (HttpWebRequest)WebRequest.Create(downloadUri);

            try
            {
                using (var stream = req.GetResponse().GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(DocumentService.StoragePath + fileName, FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);
                        }
                    }
                }
            }
            catch (Exception)
            {
                context.Response.Write("error");
                return;
            }

            context.Response.Write("success");
        }