Пример #1
0
        protected override void ExecuteCore()
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo("plugins/ffmpeg/ffmpeg.exe",
                                                 string.Format("-i \"{0}\"{2}{3} \"{1}\" -y", FileHelper.GetFilePath(Source),
                                                               FileHelper.GetFilePath(RelativePath), string.IsNullOrWhiteSpace(AudioPath)
                                    ? string.Empty
                                    : " -i \"" + FileHelper.GetFilePath(AudioPath) + "\" -map 0:v -map 1:a",
                                                               Arguments ?? string.Empty))
                {
                    UseShellExecute = false, RedirectStandardError = true
                }
            };

            process.Start();
            while (!process.StandardError.EndOfStream)
            {
                var line  = process.StandardError.ReadLine();
                var match = TimeParser.Match(line);
                if (!match.Success)
                {
                    continue;
                }
                try
                {
                    ProcessedFileLength = long.Parse(match.Groups[1].Value.Trim()) << 10;
                    ProcessedDuration   = TimeSpan.Parse(match.Groups[2].Value.Trim());
                    Save();
                }
                catch { }
            }
            Finish();
        }
Пример #2
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)
            {
            }
        }
Пример #3
0
        protected void Page_PreInit(object sender, EventArgs e)
        {
            RelativePath = RouteData.GetRelativePath();
            var absolutePath = FileHelper.GetFilePath(RelativePath);

            Title         = ("浏览 " + RelativePath).TrimEnd();
            InfoDirectory = new DirectoryInfo(absolutePath);
            InfoFile      = new FileInfo(absolutePath);
            var url = Request.RawUrl.Split('?');

            if (InfoDirectory.Exists && !url[0].EndsWith("/", StringComparison.Ordinal))
            {
                if (url.Length > 1)
                {
                    Response.Redirect(url[0] + "/?" + url[1], true);
                }
                else
                {
                    Response.Redirect(url[0] + '/', true);
                }
            }
            if (InfoFile.Exists && url[0].EndsWith("/", StringComparison.Ordinal))
            {
                if (url.Length > 1)
                {
                    Response.Redirect(url[0].TrimEnd('/') + "?" + url[1], true);
                }
                else
                {
                    Response.Redirect(url[0].TrimEnd('/'), true);
                }
            }
        }
Пример #4
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)
            {
            }
        }
Пример #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
        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);
        }
Пример #9
0
        public static ConvertTask Create(string source, string target, string size = null, string vcodec = null,
                                         string acodec     = null, string scodec   = null, string audioPath = null,
                                         string startPoint = null, string endPoint = null)
        {
            var arguments = string.Empty;

            if (!string.IsNullOrWhiteSpace(size))
            {
                arguments += " -s " + size;
            }
            if (!string.IsNullOrWhiteSpace(vcodec))
            {
                arguments += " -vcodec " + vcodec;
            }
            if (!string.IsNullOrWhiteSpace(acodec))
            {
                arguments += " -acodec " + acodec;
            }
            if (!string.IsNullOrWhiteSpace(scodec))
            {
                arguments += " -scodec " + scodec;
            }
            TimeSpan duration;

            TimeSpan.TryParse(DurationParser.Match(FFmpeg.Analyze(FileHelper.GetFilePath(source))).Groups[1].Value,
                              out duration);    // silent fail with TimeSpan.Zero
            TimeSpan start = FFmpeg.Parse(startPoint), end = FFmpeg.Parse(endPoint, duration);

            if (start <= TimeSpan.Zero)
            {
                start = TimeSpan.Zero;
            }
            else
            {
                arguments += " -ss " + startPoint;
            }
            if (end >= duration)
            {
                end = duration;
            }
            else
            {
                arguments += " -to " + endPoint;
            }
            return(new ConvertTask(source, target, end - start, audioPath, arguments));
        }
Пример #10
0
        protected override void ExecuteCore()
        {
            SevenZipExtractor extractor = null;

            try
            {
                string directory = Target.Replace('/', '\\'),
                       filePath = FileHelper.GetFilePath(directory), dataPath = FileHelper.GetDataPath(directory);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                if (!Directory.Exists(dataPath))
                {
                    Directory.CreateDirectory(dataPath);
                }
                extractor = new SevenZipExtractor(FileHelper.GetFilePath(Source));
                var singleFileName = extractor.ArchiveFileNames.Count == 1 &&
                                     extractor.ArchiveFileNames[0] == "[no name]"
                                        ? Path.GetFileNameWithoutExtension(Source) : null;
                FileCount  = extractor.FilesCount;
                FileLength = extractor.ArchiveFileData.Sum(data => (long)data.Size);
                long nextLength = 0, nextFile = 0;
                extractor.FileExtractionStarted += (sender, e) =>
                {
                    ProcessedFileCount  += nextFile;
                    ProcessedFileLength += nextLength;
                    nextLength           = (long)e.FileInfo.Size;
                    nextFile             = 1;
                    StartFile(FileHelper.Combine(directory, singleFileName ?? e.FileInfo.FileName));
                };
                extractor.FileExtractionFinished +=
                    (sender, e) => FinishFile(FileHelper.Combine(directory, singleFileName ?? e.FileInfo.FileName));
                extractor.ExtractArchive(filePath);
                Finish();
            }
            catch (SevenZipException)
            {
                if (extractor == null)
                {
                    throw;
                }
                throw new AggregateException(extractor.Exceptions);
            }
        }
Пример #11
0
        private void List(string path, XElement result)
        {
            var info = new DirectoryInfo(FileHelper.GetFilePath(path));

            if (!info.Exists)
            {
                throw new DirectoryNotFoundException();
            }
            result.SetAttributeValue("lastWriteTimeUtc", info.LastWriteTimeUtc);
            foreach (var dir in info.EnumerateDirectories())
            {
                result.Add(new XElement("directory", new XAttribute("name", dir.Name),
                                        new XAttribute("lastWriteTimeUtc", dir.LastWriteTimeUtc)));
            }
            foreach (var file in info.EnumerateFiles())
            {
                result.Add(new XElement("file", new XAttribute("name", file.Name),
                                        new XAttribute("size", file.Length), new XAttribute("lastWriteTimeUtc", file.LastWriteTimeUtc)));
            }
        }
Пример #12
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Request.GetUser().OperateFiles)
     {
         Response.StatusCode = 401;
         return;
     }
     relativePath = RouteData.GetRelativePath();
     Title        = ("编辑 " + relativePath).TrimEnd();
     absolutePath = FileHelper.GetFilePath(relativePath);
     if (!File.Exists(absolutePath))
     {
         Response.Redirect("/Browse/" + relativePath, true);
         return;
     }
     if (!IsPostBack)
     {
         TextArea.Value = File.ReadAllText(absolutePath);
     }
 }
Пример #13
0
        private void RefreshFile()
        {
            FFmpegResult = FFmpeg.Analyze(FileHelper.GetFilePath(RelativePath));
            foreach (var codec in FFmpeg.Codecs.Where(codec => codec.EncodingSupported))
            {
                var listItem = new ListItem(codec.ToString(), codec.Name);
                switch (codec.Type)
                {
                case FFmpeg.CodecType.Video:
                    ConvertVideoCodecBox.Items.Add(listItem);
                    break;

                case FFmpeg.CodecType.Audio:
                    ConvertAudioCodecBox.Items.Add(listItem);
                    break;

                case FFmpeg.CodecType.Subtitle:
                    ConvertSubtitleCodecBox.Items.Add(listItem);
                    break;
                }
            }
        }
Пример #14
0
        private void CopyDirectory(string domain, string source, string target)
        {
            CurrentFile = FileHelper.Combine(target, Path.GetFileName(source));
            Save();
            try
            {
                var root = XDocument.Parse(client.DownloadString(
                                               string.Format("http://{0}/Api/List/{1}", domain, source))).Root;
                if (root.GetAttributeValue("status") != "ok")
                {
                    throw new ExternalException(root.GetAttributeValue("message"));
                }
                foreach (var element in root.Elements())
                {
                    var name = element.GetAttributeValue("name");
                    switch (element.Name.LocalName)
                    {
                    case "directory":
                        var dir = FileHelper.Combine(target, name);
                        Directory.CreateDirectory(FileHelper.GetFilePath(dir));
                        Directory.CreateDirectory(FileHelper.GetDataPath(dir));
                        CopyDirectory(domain, FileHelper.Combine(source, name), dir);
                        break;

                    case "file":
                        CopyFile(domain, FileHelper.Combine(source, name), target);
                        break;
                    }
                }
            }
            catch (Exception exc)
            {
                ErrorMessage += string.Format("复制 /{0} 时发生了错误:{2}{1}{2}", target, exc.GetMessage(),
                                              Environment.NewLine);
                Save();
            }
        }
Пример #15
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
            }
        }