<commit_before>﻿/**
 *
 * (c) Copyright Ascensio System SIA 2021
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

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.Configuration;
using System.Web.Script.Serialization;
using System.Web.UI;
using ASC.Api.DocumentConverter;

namespace OnlineEditorsExample
{
    internal static class FileType
    {
        // the spreadsheet extension list
        public static readonly List<string> ExtsSpreadsheet = new List<string>
            {
                ".xls", ".xlsx", ".xlsm",
                ".xlt", ".xltx", ".xltm",
                ".ods", ".fods", ".ots", ".csv"
            };

        // the presentation extension list
        public static readonly List<string> ExtsPresentation = new List<string>
            {
                ".pps", ".ppsx", ".ppsm",
                ".ppt", ".pptx", ".pptm",
                ".pot", ".potx", ".potm",
                ".odp", ".fodp", ".otp"
            };

        // the document extension list
        public static readonly List<string> ExtsDocument = new List<string>
            {
                ".doc", ".docx", ".docm",
                ".dot", ".dotx", ".dotm",
                ".odt", ".fodt", ".ott", ".rtf", ".txt",
                ".html", ".htm", ".mht", ".xml",
                ".pdf", ".djvu", ".fb2", ".epub", ".xps", ".oxps", ".oform"
            };

        // get an internal file extension
        public static string GetInternalExtension(string extension)
        {
            extension = Path.GetExtension(extension).ToLower();  // get file extension
            if (ExtsDocument.Contains(extension)) return ".docx";  // .docx for text document extensions
            if (ExtsSpreadsheet.Contains(extension)) return ".xlsx";  // .xlsx for spreadsheet extensions
            if (ExtsPresentation.Contains(extension)) return ".pptx";  // .pptx for presentation extensions
            return string.Empty;
        }
    }

    public partial class _Default : Page
    {

        // get the virtual path
        public static string VirtualPath
        {
            get
            {
                return Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]) ? 
                    WebConfigurationManager.AppSettings["storage-path"] + "/"
                    :
                    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; }
        }

        // get maximum file size
        private static long MaxFileSize
        {
            get
            {
                long size;
                long.TryParse(WebConfigurationManager.AppSettings["filesize-max"], out size);
                return size > 0 ? size : 5*1024*1024;
            }
        }

        // get all the supported file extensions
        private static List<string> FileExts
        {
            get { return ViewedExts.Concat(EditedExts).Concat(ConvertExts).Concat(FillFormsExts).ToList(); }
        }

        // file extensions that can be viewed
        private static List<string> ViewedExts
        {
            get { return (WebConfigurationManager.AppSettings["files.docservice.viewed-docs"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); }
        }
        
        public static List<string> FillFormsExts
        {
            get { return (WebConfigurationManager.AppSettings["files.docservice.fillform-docs"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); }
        }

        // file extensions that can be edited
        public static List<string> EditedExts
        {
            get { return (WebConfigurationManager.AppSettings["files.docservice.edited-docs"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); }
        }

        // file extensions that can be converted
        public static List<string> ConvertExts
        {
            get { return (WebConfigurationManager.AppSettings["files.docservice.convert-docs"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); }
        }

        private static string _fileName;

        // get current user host address
        public static string CurUserHostAddress(string userAddress)
        {
            return Regex.Replace(userAddress ?? HttpContext.Current.Request.UserHostAddress, "[^0-9a-zA-Z.=]", "_");
        }

        // get the storage path of the given file
        public static string StoragePath(string fileName, string userAddress)
        {
            var directory = "";
            if (Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]))
            {
                directory = WebConfigurationManager.AppSettings["storage-path"] + "\\";
            }
            else
            {
                directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(userAddress) + "\\";
            }

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);  // if the file directory doesn't exist, make it
            }
            return directory + (fileName.Contains("\\") ? fileName : Path.GetFileName(fileName));
        }

        // get the path to the history file version
        public static string HistoryPath(string fileName, string userAddress, string version, string file)
        {
            var directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(userAddress) + "\\";
            directory = directory + Path.GetFileName(fileName) + "-hist" + "\\" + version + "\\" + file;
            return directory;
        }
        // get the path to the forcesaved file version
        public static string ForcesavePath(string fileName, string userAddress, Boolean create)
        {
            var directory = "";
            if (Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]))
            {
                directory = WebConfigurationManager.AppSettings["storage-path"] + "\\";
            }
            else
            {
                directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(userAddress) + "\\";
            }
            
            if (!Directory.Exists(directory))  // the directory with host address doesn't exist
            {
                return "";
            }

            directory = directory + Path.GetFileName(fileName) + "-hist" + "\\";  // get the path to the history of the given file
            if (!Directory.Exists(directory))
            {
                if (create)  // create history directory if it doesn't exist
                {
                    Directory.CreateDirectory(directory);
                }
                else  // the history directory doesn't exist and we are not supposed to create it
                {
                    return "";
                }
            }<commit_msg>С#: add absolute path support for document history<commit_after>﻿/**
 *
 * (c) Copyright Ascensio System SIA 2021
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

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.Configuration;
using System.Web.Script.Serialization;
using System.Web.UI;
using ASC.Api.DocumentConverter;

namespace OnlineEditorsExample
{
    internal static class FileType
    {
        // the spreadsheet extension list
        public static readonly List<string> ExtsSpreadsheet = new List<string>
            {
                ".xls", ".xlsx", ".xlsm",
                ".xlt", ".xltx", ".xltm",
                ".ods", ".fods", ".ots", ".csv"
            };

        // the presentation extension list
        public static readonly List<string> ExtsPresentation = new List<string>
            {
                ".pps", ".ppsx", ".ppsm",
                ".ppt", ".pptx", ".pptm",
                ".pot", ".potx", ".potm",
                ".odp", ".fodp", ".otp"
            };

        // the document extension list
        public static readonly List<string> ExtsDocument = new List<string>
            {
                ".doc", ".docx", ".docm",
                ".dot", ".dotx", ".dotm",
                ".odt", ".fodt", ".ott", ".rtf", ".txt",
                ".html", ".htm", ".mht", ".xml",
                ".pdf", ".djvu", ".fb2", ".epub", ".xps", ".oxps", ".oform"
            };

        // get an internal file extension
        public static string GetInternalExtension(string extension)
        {
            extension = Path.GetExtension(extension).ToLower();  // get file extension
            if (ExtsDocument.Contains(extension)) return ".docx";  // .docx for text document extensions
            if (ExtsSpreadsheet.Contains(extension)) return ".xlsx";  // .xlsx for spreadsheet extensions
            if (ExtsPresentation.Contains(extension)) return ".pptx";  // .pptx for presentation extensions
            return string.Empty;
        }
    }

    public partial class _Default : Page
    {

        // get the virtual path
        public static string VirtualPath
        {
            get
            {
                return Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]) ? 
                    WebConfigurationManager.AppSettings["storage-path"] + "/"
                    :
                    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; }
        }

        // get maximum file size
        private static long MaxFileSize
        {
            get
            {
                long size;
                long.TryParse(WebConfigurationManager.AppSettings["filesize-max"], out size);
                return size > 0 ? size : 5*1024*1024;
            }
        }

        // get all the supported file extensions
        private static List<string> FileExts
        {
            get { return ViewedExts.Concat(EditedExts).Concat(ConvertExts).Concat(FillFormsExts).ToList(); }
        }

        // file extensions that can be viewed
        private static List<string> ViewedExts
        {
            get { return (WebConfigurationManager.AppSettings["files.docservice.viewed-docs"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); }
        }
        
        public static List<string> FillFormsExts
        {
            get { return (WebConfigurationManager.AppSettings["files.docservice.fillform-docs"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); }
        }

        // file extensions that can be edited
        public static List<string> EditedExts
        {
            get { return (WebConfigurationManager.AppSettings["files.docservice.edited-docs"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); }
        }

        // file extensions that can be converted
        public static List<string> ConvertExts
        {
            get { return (WebConfigurationManager.AppSettings["files.docservice.convert-docs"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); }
        }

        private static string _fileName;

        // get current user host address
        public static string CurUserHostAddress(string userAddress)
        {
            return Regex.Replace(userAddress ?? HttpContext.Current.Request.UserHostAddress, "[^0-9a-zA-Z.=]", "_");
        }

        // get the storage path of the given file
        public static string StoragePath(string fileName, string userAddress)
        {
            var directory = "";
            if (Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]))
            {
                directory = WebConfigurationManager.AppSettings["storage-path"] + "\\";
            }
            else
            {
                directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(userAddress) + "\\";
            }

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);  // if the file directory doesn't exist, make it
            }
            return directory + (fileName.Contains("\\") ? fileName : Path.GetFileName(fileName));
        }

        // get the path to the history file version
        public static string HistoryPath(string fileName, string userAddress, string version, string file)
        {   
            var directory = "";
            if (Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]))
            {
                directory = WebConfigurationManager.AppSettings["storage-path"] + "\\";
            }else
            {
                directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(userAddress) + "\\";
            }
            var filepath = directory + Path.GetFileName(fileName) + "-hist" + "\\" + version + "\\" + file;
            return filepath;
        }
        // get the path to the forcesaved file version
        public static string ForcesavePath(string fileName, string userAddress, Boolean create)
        {
            var directory = "";
            if (Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]))
            {
                directory = WebConfigurationManager.AppSettings["storage-path"] + "\\";
            }
            else
            {
                directory = HttpRuntime.AppDomainAppPath + WebConfigurationManager.AppSettings["storage-path"] + CurUserHostAddress(userAddress) + "\\";
            }
            
            if (!Directory.Exists(directory))  // the directory with host address doesn't exist
            {
                return "";
            }

            directory = directory + Path.GetFileName(fileName) + "-hist" + "\\";  // get the path to the history of the given file
            if (!Directory.Exists(directory))
            {
                if (create)  // create history directory if it doesn't exist
                {
                    Directory.CreateDirectory(directory);
                }
                else  // the history directory doesn't exist and we are not supposed to create it
                {
                    return "";
                }
            }
{'fraction_non_alphanumeric': 0.1142579312021393, 'fraction_numerical': 0.002552570803452048, 'mean_word_length': 1.9253333333333333, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3827344', 'n_tokens_mistral': 4202, 'n_tokens_neox': 4016, 'n_words': 1072}