示例#1
0
 protected void StartFile(string relativePath)
 {
     FileHelper.WriteAllText(FileHelper.GetDataFilePath(relativePath),
                             string.Format("<file state=\"{0}\" id=\"{1}\" pid=\"{2}\" />", Type, ID, PID));
     CurrentFile = relativePath;
     Save();
 }
示例#2
0
        private bool CopyFile(string domain, string source, string target, bool logging = true)
        {
            var targetFile = FileHelper.Combine(target, Path.GetFileName(source));

            CurrentFile = targetFile;
            try
            {
                var root = XDocument.Parse(client.DownloadString(
                                               string.Format("http://{0}/Api/Details/{1}", domain, source))).Root;
                if (root.GetAttributeValue("status") != "ok")
                {
                    throw new ExternalException(root.GetAttributeValue("message"));
                }
                Save();
                Program.OfflineDownload(string.Format("http://{0}/Download/{1}", domain, source), target, client);
                var file = root.Element("file");
                FileHelper.SetDefaultMime(FileHelper.GetDataFilePath(targetFile), file.GetAttributeValue("mime"));
                ProcessedFileCount++;
                ProcessedFileLength += file.GetAttributeValue <long>("size");
                Save();
                return(true);
            }
            catch (Exception exc)
            {
                if (logging)
                {
                    ErrorMessage += string.Format("复制 /{0} 时发生了错误:{2}{1}{2}", target, exc.GetMessage(),
                                                  Environment.NewLine);
                    Save();
                }
                return(false);
            }
        }
示例#3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.GetUser().Download)
            {
                Response.StatusCode = 401;
                return;
            }
            string path = RouteData.GetRelativePath(), filePath = FileHelper.GetFilePath(path),
                   dataPath = FileHelper.GetDataFilePath(path);

            if (!File.Exists(dataPath))
            {
                Response.StatusCode = 404;
                return;
            }
            try
            {
                int timeout;
                if (!int.TryParse(Request.QueryString["Timeout"], out timeout))
                {
                    timeout = 10;
                }
                FileHelper.WaitForReady(dataPath, timeout);
                TransmitFile(filePath, Path.GetFileName(filePath));
            }
            catch (ThreadAbortException)
            {
            }
        }
示例#4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.GetUser().Download)
            {
                Response.StatusCode = 401;
                return;
            }
            string path = RouteData.GetRelativePath(), dataPath = FileHelper.GetDataFilePath(path),
                   mime = Request.QueryString["Mime"];

            if (string.IsNullOrWhiteSpace(mime))
            {
                mime = FileHelper.GetDefaultMime(dataPath);
            }
            try
            {
                int timeout;
                if (!int.TryParse(Request.QueryString["Timeout"], out timeout))
                {
                    timeout = 10;
                }
                FileHelper.WaitForReady(dataPath, timeout);
                TransmitFile(FileHelper.GetFilePath(path), mime: mime);
            }
            catch (ThreadAbortException)
            {
            }
        }
示例#5
0
 protected GenerateFileTask(string relativePath, string state)
     : base(FileHelper.GetDataFilePath(relativePath), "file")
 {
     State     = state;
     Mime      = Helper.GetMimeType(RelativePath = relativePath);
     StartTime = DateTime.UtcNow;
     File.WriteAllText(FileHelper.GetFilePath(relativePath), string.Empty);  // temp
 }
示例#6
0
        protected override void ExecuteCore()
        {
            var url = UrlFull;

            Url = Url;  // clear the user account data!!!
            Save();
            var sources = this.GetAllSources().ToArray();

            SourceCount = sources.Length;
            FileLength  = sources.Sum(source => new FileInfo(FileHelper.GetFilePath(source)).Length);
            foreach (var file in sources)
            {
                FileHelper.WaitForReady(FileHelper.GetDataFilePath(file));
            }
            var set = new HashSet <string>(new[] { url });

            foreach (var file in sources)
            {
                CurrentSource = file;
                Save();
                string targetUrl = Path.Combine(url, string.IsNullOrEmpty(BaseFolder)
                                                        ? file : file.Substring(BaseFolder.Length + 1)),
                       targetDir = Path.GetDirectoryName(targetUrl);
                FtpWebRequest request;
                if (!set.Contains(targetDir))
                {
                    request            = (FtpWebRequest)WebRequest.Create(targetDir);
                    request.Timeout    = Timeout.Infinite;
                    request.UseBinary  = true;
                    request.UsePassive = true;
                    request.KeepAlive  = true;
                    request.Method     = WebRequestMethods.Ftp.MakeDirectory;
                    request.GetResponse().Close();
                }
                request            = (FtpWebRequest)WebRequest.Create(Path.Combine(url, file));
                request.Timeout    = Timeout.Infinite;
                request.UseBinary  = true;
                request.UsePassive = true;
                request.KeepAlive  = true;
                request.Method     = WebRequestMethods.Ftp.UploadFile;
                using (var src = File.OpenRead(FileHelper.GetFilePath(file)))
                    using (var dst = request.GetRequestStream())
                    {
                        var byteBuffer = new byte[1048576];
                        var bytesSent  = src.Read(byteBuffer, 0, 1048576);
                        while (bytesSent != 0)
                        {
                            dst.Write(byteBuffer, 0, bytesSent);
                            ProcessedFileLength += bytesSent;
                            Save();
                            bytesSent = src.Read(byteBuffer, 0, 1048576);
                        }
                    }
                request.GetResponse().Close();
                ProcessedSourceCount++;
            }
            Finish();
        }
示例#7
0
        protected override void ExecuteCore()
        {
            SevenZipCompressor compressor = null;

            try
            {
                var files = this.GetAllSources().ToList();
                foreach (var file in files)
                {
                    FileHelper.WaitForReady(FileHelper.GetDataFilePath(file));
                }
                long nextLength = 0, nextFile = 0;
                FileLength = files.Sum(file => new FileInfo(FileHelper.GetFilePath(file)).Length);
                compressor = new SevenZipCompressor
                {
                    CompressionLevel = (CompressionLevel)Enum.Parse(typeof(CompressionLevel),
                                                                    TaskXml.GetAttributeValue("compressionLevel"), true)
                };
                switch (Path.GetExtension(RelativePath).ToLowerInvariant())
                {
                case ".7z":
                    compressor.ArchiveFormat = OutArchiveFormat.SevenZip;
                    break;

                case ".zip":
                    compressor.ArchiveFormat = OutArchiveFormat.Zip;
                    break;

                case ".tar":
                    compressor.ArchiveFormat = OutArchiveFormat.Tar;
                    break;
                }
                var filesStart = Path.GetFullPath(FileHelper.GetFilePath(string.Empty)).Length + 1;
                compressor.FileCompressionStarted += (sender, e) =>
                {
                    ProcessedSourceCount += nextFile;
                    ProcessedFileLength  += nextLength;
                    nextFile              = 1;
                    nextLength            = new FileInfo(e.FileName).Length;
                    CurrentSource         = e.FileName.Substring(filesStart);
                    Save();
                };
                compressor.CompressFiles(FileHelper.GetFilePath(RelativePath),
                                         Path.GetFullPath(FileHelper.GetFilePath(BaseFolder)).Length + 1,
                                         files.Select(file => Path.GetFullPath(FileHelper.GetFilePath(file))).ToArray());
                ProcessedSourceCount += nextFile;
                ProcessedFileLength  += nextLength;
                Finish();
            }
            catch (SevenZipException)
            {
                if (compressor == null)
                {
                    throw;
                }
                throw new AggregateException(compressor.Exceptions);
            }
        }
示例#8
0
 protected void ModifyMime(object sender, EventArgs e)
 {
     if (!CurrentUser.OperateFiles)
     {
         Response.StatusCode = 401;
         return;
     }
     FileHelper.SetDefaultMime(FileHelper.GetDataFilePath(RelativePath), Hidden.Value.UrlDecode());
     Response.Redirect(Request.RawUrl);
 }
示例#9
0
        private void Details(string path, XContainer result)
        {
            var element = FileHelper.GetElement(FileHelper.GetDataFilePath(path));
            var info    = new FileInfo(FileHelper.GetFilePath(path));

            if (element.GetAttributeValue("state") == TaskType.NoTask || element.GetAttributeValue("size") == null)
            {
                element.SetAttributeValue("size", info.Length);
            }
            element.SetAttributeValue("lastWriteTimeUtc", info.LastWriteTimeUtc);
            element.Add(new XElement("ffmpeg", FFmpeg.Analyze(info.FullName)));
            result.Add(element);
        }
示例#10
0
        public static GenerateFileTask Create(string relativePath)
        {
            switch (FileHelper.GetState(FileHelper.GetDataFilePath(relativePath)).ToLowerInvariant())
            {
            case TaskType.UploadTask:
                return(new UploadTask(relativePath));

            case TaskType.OfflineDownloadTask:
                return(new OfflineDownloadTask(relativePath));

            case TaskType.CompressTask:
                return(new CompressTask(relativePath));

            case TaskType.ConvertTask:
                return(new ConvertTask(relativePath));

            default:
                return(null);
            }
        }
示例#11
0
 protected void FinishFile(string relativePath)
 {
     FileHelper.WriteAllText(FileHelper.GetDataFilePath(relativePath),
                             string.Format("<file mime=\"{0}\" state=\"ready\" />", relativePath));
     Save();
 }
示例#12
0
 protected GenerateFileTask(string relativePath) : base(FileHelper.GetDataFilePath(relativePath))
 {
     RelativePath = relativePath;
 }
示例#13
0
 protected void Page_Init(object sender, EventArgs e)
 {
     if (!(CurrentUser = Request.GetUser()).Browse)
     {
         Response.StatusCode = 401;
         return;
     }
     if (InfoDirectory.Exists)
     {
         Views.SetActiveView(DirectoryView);
         if (IsPostBack)
         {
             return;
         }
         var dirs = InfoDirectory.EnumerateDirectories().ToList();
         DirectoryList.DataSource = dirs;
         DirectoryList.DataBind();
         DirectoryCount = dirs.Count.ToString(CultureInfo.InvariantCulture);
         var files = InfoDirectory.EnumerateFiles().ToList();
         FileList.DataSource = files;
         FileList.DataBind();
         FileCount            = files.Count.ToString(CultureInfo.InvariantCulture);
         ArchiveFilePath.Text = string.IsNullOrWhiteSpace(RelativePath) ? "Files.7z" : (RelativePath + ".7z");
     }
     else if (InfoFile.Exists)
     {
         string dataPath = FileHelper.GetDataFilePath(RelativePath), state = FileHelper.GetFileValue(dataPath, "state");
         Task = GenerateFileTask.Create(RelativePath);
         if (Task == null)
         {
             if (state == TaskType.NoTask)
             {
                 if (Request.IsAjaxRequest())
                 {
                     Response.Redirect(Request.RawUrl, true);                          // processing is finished
                 }
                 Views.SetActiveView(FileView);
                 Mime = FileHelper.GetDefaultMime(dataPath);
                 RefreshFile();
             }
             else
             {
                 Views.SetActiveView(GeneralTaskProcessingView);
             }
         }
         else if (state == TaskType.UploadTask)
         {
             Views.SetActiveView(FileUploadingView);
         }
         else
         {
             Viewer.SetTask(Task);
             Views.SetActiveView(FileProcessingView);
         }
     }
     else
     {
         Views.SetActiveView(GoneView);
         Response.StatusCode = 404;
     }
 }
示例#14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var upload = Request.HttpMethod == "POST";

            if (upload && !Request.GetUser().OperateFiles)
            {
                Response.StatusCode = 401;
                return;
            }
            var    data = upload ? Request.Form : Request.QueryString;
            string id = data["resumableIdentifier"], path = FileHelper.Combine
                                                                (RouteData.GetRelativePath(), data["resumableRelativePath"].ToValidPath(false)),
                   filePath = FileHelper.GetFilePath(path), dataPath = FileHelper.GetDataFilePath(path),
                   state = FileHelper.GetState(dataPath);

            Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            Directory.CreateDirectory(Path.GetDirectoryName(dataPath));
            if (state != TaskType.UploadTask || state == TaskType.UploadTask && new UploadTask(path).Identifier != id)
            {
                FileHelper.Delete(path);
                File.WriteAllBytes(filePath, new byte[0]);
                try
                {
                    new UploadTask(path, id, int.Parse(data["resumableTotalChunks"]),
                                   long.Parse(data["resumableTotalSize"])).Save();
                }
                catch (IOException) { } // another save in progress
            }
            var index = int.Parse(data["resumableChunkNumber"]) - 1;

            if (upload)
            {
                string basePath = FileHelper.GetDataPath(path), partSuffix = ".part" + index,
                       partPath = basePath + ".incomplete" + partSuffix;
                try
                {
                    using (var output = new FileStream(partPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                        Request.Files[Request.Files.AllKeys.Single()].InputStream.CopyTo(output);
                    File.Move(partPath, basePath + ".complete" + partSuffix);
                }
                catch
                {
                    FileHelper.DeleteWithRetries(partPath); // delete imcomplete file
                }
                var task = new UploadTask(path);
                if (task.FinishedParts != task.TotalParts)
                {
                    return;
                }
                using (var output = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read))
                    for (var i = 0; i < task.TotalParts; ++i)
                    {
                        using (var input = new FileStream(
                                   partPath = FileHelper.GetDataPath(path + ".complete.part" + i),
                                   FileMode.Open, FileAccess.Read, FileShare.Read)) input.CopyTo(output);
                        FileHelper.DeleteWithRetries(partPath);
                    }
                task.Finish();
            }
            else
            {
                Response.StatusCode = File.Exists(FileHelper.GetDataPath(path + ".complete.part" + index))
                                           ? 200 : 204;  // test
            }
        }