Example #1
0
        //Constructor
        public UploadPluginWindow(UploadMode _mode = UploadMode.Normal)
        {
            InitializeComponent();

            userAccount = PluginStoreManager.UserName;
            mode        = _mode;
        }
Example #2
0
 /// <summary>
 /// 实例化上传票据实体
 /// </summary>
 /// <param name="host">主机名</param>
 /// <param name="name">登录用户名</param>
 /// <param name="pwd">登录密码</param>
 /// <param name="mode">上传模式</param>
 public TacketBase(string host, string name, string pwd, UploadMode mode)
 {
     this.Host     = host;
     this.UserName = name;
     this.PassWord = pwd;
     this.mode     = mode;
 }
        private static void UploadFile(string localFilePath, UploadMode mode)
        {
            if (_currentFolder == null)
            {
                return;
            }

            Console.WriteLine();

            if (!System.IO.File.Exists(localFilePath))
            {
                Console.WriteLine($"Unable to find local file {localFilePath}.  Content APIs will not be able to continue.");
                throw new ConfigurationErrorsException("Cannot find the file defined as the value of \"uploadFile\" configuration");
            }

            Console.WriteLine("Start File Uploading...");

            try
            {
                var uploadClient = new UploadClient(_currentFolder, localFilePath, UploadCallBack);
                switch (mode)
                {
                case UploadMode.Chunked:
                    uploadClient.UploadFileUsingChunks();
                    break;

                case UploadMode.Simple:
                default:
                    uploadClient.UploadFileWithoutChunking();
                    break;
                }

                UploadFinished.WaitOne();
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.WriteLine("Uploading file failed.");
                Console.WriteLine("Exception caught:");
                Console.WriteLine(e);
                UploadFinished.Set();
                throw;
            }

            Console.WriteLine();

            if (_lastException != null)
            {
                Console.WriteLine("Uploading file failed.");
                throw new InvalidOperationException("Uploading file failed", _lastException);
            }

            Console.WriteLine($"File {localFilePath} uploaded successfully to folder {_currentFolder.Name}.");
        }
Example #4
0
        /// <summary>
        /// Verify the list of serial folders to be uploaded by checking if a folder of the same name already exists in the iPortal repository
        /// </summary>
        /// <param name="progressIndicator">Used to report back progress</param>
        /// <param name="ct">Used to cancel the upload</param>
        /// <returns>The list of serial folders that will not be uploaded</returns>
        public async Task <IEnumerable <String> > VerifySerialFoldersAsync(IProgress <Feedback> progressIndicator, CancellationToken ct)
        {
            IEnumerable <DirectoryInfo> selectedSerials;

            // Upload a single serial folder
            if (UploadMode.Equals(UploadModes.SingleSerial))
            {
                selectedSerials = new List <DirectoryInfo> {
                    serials[selectedSerial]
                }
            }
            ;
            else
            {
                selectedSerials = serials.Values;
            }

            // Progress indicator used to recompute percentage
            int total = selectedSerials.Count(), i = 0;
            IProgress <Feedback> singleSerialDataFetchProgress = new Progress <Feedback>((feedback) =>
            {
                progressIndicator.Report(new Feedback
                {
                    Message = feedback.Message,
                    Value   = 95 / total * (i * 100 + feedback.Value) / 100
                });
            });

            // Get the list of data files to upload in the serial folders
            selectedDataFiles = new List <IEnumerable <FileInfo> >();
            var ignoredSerialFolders = new List <String>();

            foreach (DirectoryInfo serialFolder in selectedSerials)
            {
                // If serial folder does not exist in the server fetch the list of data files to upload
                if (!Directory.Exists(Path.Combine(currentSubmissionDestinationPath, serialFolder.Name)))
                {
                    try
                    {
                        selectedDataFiles.AddRange(await currentSubmission.FetchDataFilesAsync(serialFolder, singleSerialDataFetchProgress, ct));
                        i++;
                    }
                    catch (OperationCanceledException) { throw; }
                }
                // If the serial folder already exists, add it to the list of ignored folders
                else
                {
                    ignoredSerialFolders.Add(serialFolder.Name);
                }
            }

            return(ignoredSerialFolders);
        }
Example #5
0
        public static IHtmlContent Uploader(this IHtmlHelper target, UploadMode mode, string uploaderModule, string uploadReason, string callbackMethod, int height = 0, int width = 0, Dictionary<string, string> customAttributes = null)
        {
            string uniqueDivId;
            uniqueDivId = CustomActionHelper.RandomName("uploadDiv");
            string template = $@"<div purpose='{mode}' id='{uniqueDivId}' nameTarget='{uniqueDivId}' uploadModule='{uploaderModule}' uploadReason='{uploadReason}' class='dropzone dropzone-flexi' {(height != 0 || width != 0 ? $"style=\"display:table-cell;position:relative;{(height != 0 ? $"height:{height}px;" : "")}{(width != 0 ? $"width:{width}px;" : "")}\"" : "")} {(customAttributes != null ? string.Join(" ", from t in customAttributes select $"{t.Key}='{t.Value}'") : "")}></div>
<script>ITVenture.Tools.Uploader.prepareUploadRegion({{
    {uniqueDivId}: {callbackMethod}
}});
</script>";

            return target.Raw(template);
        }
Example #6
0
        public static IHtmlContent UploaderFor<TModel, TResult>(this IHtmlHelper<TModel> target,
                Expression<Func<TModel, TResult>> expression,
                UploadMode mode,
                string uploaderModule,
                string uploadReason,
                bool preserveOriginal,
                string originalFieldName,
                string uploadHint,
                string customUploadCallback,
                bool setOriginalOnlyIfNull)
            {
                string uniqueDivId, uniqueInputId, uniqueOrigId, uniqueDummyId;
                uniqueDivId = CustomActionHelper.RandomName("uploadDiv");
                uniqueInputId = CustomActionHelper.RandomName("valueBox");
                uniqueOrigId = CustomActionHelper.RandomName("oriValueBox");
                uniqueDummyId = CustomActionHelper.RandomName("dummyDiv");
                var notNullOrig = $@"""var $ori = $(\""\\#{uniqueOrigId}\"").val();""
.concat(        ""if ($ori === null || $ori.trim() === \""\""){{"")
.concat(""$(\""\\#{uniqueOrigId}\"").val(oriValue).change();"")
.concat(""}}"")";
                var additionalCallback = $@"""{(!string.IsNullOrEmpty(customUploadCallback)?$"{customUploadCallback}(value{(preserveOriginal ? ", oriValue" : "")});":"")}""";
                string template = $@"<div id=""{uniqueDummyId}""></div>
<script>
var tmpl = ""\u003Cdiv purpose=\""{mode}\"" nameTarget=\""{uniqueDivId}\"" uploadModule=\""{uploaderModule}\"" uploadReason=\""{uploadReason}\"" uploadHint=\""{uploadHint}\"" class=\""dropzone\""\u003E""
.concat(""\u003C/div\u003E"")
.concat(""{target.HiddenFor(expression, new {id = uniqueInputId}).GetString().Replace("#", @"\\#").Replace(@"""", @"\""").Replace(@"<", @"\u003C").Replace(@">", @"\u003E")}"")
.concat({(preserveOriginal ? $@"""\u003Cinput data-bind=\""value:{originalFieldName}\"" id=\""{uniqueOrigId}\"" name=\""{originalFieldName}\"" type=\""hidden\"" value=\""\""  /\u003E""" : "\"\"")})
.concat(""\u003Cscript>ITVenture.Tools.Uploader.prepareUploadRegion({{"")
.concat(    ""{uniqueDivId}: function(value{(preserveOriginal ? ", oriValue" : "")}){{"")
.concat(        ""$(\""\\#{uniqueInputId}\"").val(value).change();"")
.concat({(preserveOriginal ? $@"{(setOriginalOnlyIfNull ? notNullOrig : "\"\"")}":"\"\"")})
.concat({additionalCallback})
.concat(""}}"")
.concat(""}});\u003C/script\u003E"");
var template = kendo.template(tmpl);
var data = $(""#{uniqueDummyId}"").parent().parent().data(""kendoEditable"").options.model;
var result = template(data);
$(""#{uniqueDummyId}"").replaceWith(result);
</script>";
                return target.Raw(template);
            }
Example #7
0
 public bool UploadVideo(UploadMode uploadMode, out string remoteFilename, string localfilename, string serviceName, string reference, string[] tags, UploadVideoProgress progressCallback)
 {
     this.currentFilename         = localfilename;
     this.currentProgressCallback = progressCallback;
     if (uploadMode == UploadMode.Youtube)
     {
         Task <bool> uploadVideoTask = UploadVideoYoutube(localfilename, serviceName, reference, tags, progressCallback);
         uploadVideoTask.Wait();
         remoteFilename = "youtube:" + this.youtubeVideoID;
         return(uploadVideoTask.Result);
     }
     else if (uploadMode == UploadMode.Facebook)
     {
         object result = UploadVideoFacebook(localfilename, serviceName, reference, tags, progressCallback);
         remoteFilename = "facebook:" + localfilename;
         return(true);
     }
     else
     {
         remoteFilename = new FileInfo(localfilename).Name;
         return(true);
     }
 }
Example #8
0
 /// <summary>
 /// 实例化上传票据实体
 /// </summary>
 /// <param name="mode"></param>
 public TacketBase(UploadMode mode)
 {
     this.mode = mode;
 }
Example #9
0
        public ISendStreamRequest <FileItem> Upload(string name, string dir = null, string dir_id = null, UploadMode mode = UploadMode.CreateOnly)
        {
            var request = new SendStreamRequest <FileItem>(this.RequestUrl, this.Client);

            switch (mode)
            {
            case UploadMode.CreateOnly:
                request.Method = "POST";
                break;

            case UploadMode.CreateOrUpdate:
                request.Method = "PUT";
                break;

            default:
                throw new NotImplementedException();
            }

            request.QueryOptions.Add(new KeyValuePair <string, string>("name", Uri.EscapeDataString(name)));
            if (dir != null)
            {
                request.QueryOptions.Add(new KeyValuePair <string, string>("dir", Uri.EscapeDataString(dir)));
            }
            if (dir_id != null)
            {
                request.QueryOptions.Add(new KeyValuePair <string, string>("dir_id", dir_id));
            }

            return(request);
        }
Example #10
0
        public ISendStreamRequest <FileItem> Upload(string name, string dir = null, string dir_id = null, DateTime modificationTime = default(DateTime), DateTime dirModificationTime = default(DateTime), UploadMode mode = UploadMode.CreateOnly)
        {
            var request = new SendStreamRequest <FileItem>(RequestUrl, Client);

            switch (mode)
            {
            case UploadMode.CreateOnly:
                request.Method = "POST";
                break;

            case UploadMode.CreateOrUpdate:
                request.Method = "PUT";
                break;

            default:
                throw new NotImplementedException();
            }

            request.QueryOptions.Add(new KeyValuePair <string, string>("name", Uri.EscapeDataString(name)));
            if (dir != null)
            {
                request.QueryOptions.Add(new KeyValuePair <string, string>("dir", Uri.EscapeDataString(dir)));
            }
            if (dir_id != null)
            {
                request.QueryOptions.Add(new KeyValuePair <string, string>("dir_id", dir_id));
            }
            if (modificationTime != default(DateTime))
            {
                request.QueryOptions.Add(new KeyValuePair <string, string>("mtime", new DateTimeOffset(modificationTime).ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)));
            }
            if (dirModificationTime != default(DateTime))
            {
                request.QueryOptions.Add(new KeyValuePair <string, string>("parent_mtime", new DateTimeOffset(dirModificationTime).ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)));
            }

            return(request);
        }
Example #11
0
        /// <summary>
        /// 用指定的控制器上下文和绑定上下文将模型绑定到AttachmentInfo
        /// </summary>
        /// <param name="controllerContext">ControllerContext</param>
        /// <param name="bindingContext">ModelBindingContext</param>
        /// <returns>绑定后的数据</returns>
        /// <remarks>
        /// 应登明要求 重写此绑定上传方法 由原来的站点目录上传改写为FTP远程上传
        /// <para>
        /// 2014-02-13
        /// </para>
        /// <para>
        /// 唐鑫
        /// </para>
        /// </remarks>
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request    = controllerContext.HttpContext.Request;
            string          modelName  = bindingContext.ModelName;
            bool            isDb       = IsDB(request, modelName);
            bool            isMultiple = IsMultiple(request, modelName);
            bool            isRequired = IsRequired(request, modelName);
            bool            isValid    = true;

            string uploadDir = UploadDir(request, modelName);

            UploadMode     mode       = (UploadMode)IsMode(request, modelName);
            AttachmentInfo attachment = BuildAttachmentInfo(request, modelName);

            HttpFileCollectionBase     files      = controllerContext.HttpContext.Request.Files;
            IList <HttpPostedFileBase> modelFiles = files.GetMultiple(modelName)
                                                    .Where(m => !m.FileName.IsNullOrEmpty())
                                                    .ToList();

            if (!isMultiple && isRequired && (modelFiles.Count == 0 || modelFiles.Count(m => m.ContentLength > 0) == 0))
            {
                bindingContext.ModelState.AddModelError(modelName, "必填项");
                isValid = false;
            }


            #region   员工照片 做特殊处理
            if (modelFiles.Count > 0 && !string.IsNullOrEmpty(request.QueryString["empPhoto"]) && request.QueryString["empPhoto"] == "1")
            {
                if (Path.GetExtension(modelFiles[0].FileName).Trim('.').ToLower() != "jpg")
                {
                    bindingContext.ModelState.AddModelError(modelName, "仅支持如下文件格式:jpg");
                    isValid = false;
                }
                else if (modelFiles.Any(m => m.ContentLength / 1024 >= 20))
                {
                    bindingContext.ModelState.AddModelError(modelName, "超过文件大小限定:9KB ~ 20KB");
                    isValid = false;
                }
                else if (modelFiles.Any(m => m.ContentLength / 1024 < 9))
                {
                    bindingContext.ModelState.AddModelError(modelName, "超过文件大小限定:9KB ~ 20KB");
                    isValid = false;
                }
                Image pic = null;
                if (isValid)
                {
                    pic = System.Drawing.Image.FromStream(modelFiles[0].InputStream);
                }
                if (isValid && pic.Width != 358)
                {
                    bindingContext.ModelState.AddModelError(modelName, "照版的宽度必须是:358像素");
                    isValid = false;
                }
                else if (isValid && pic.Height != 441)
                {
                    bindingContext.ModelState.AddModelError(modelName, "照版的高度必须是:441像素");
                    isValid = false;
                }
            }
            #endregion

            if (modelFiles.Any(m => !SiteConfig.FileExts.Contains(Path.GetExtension(m.FileName).Trim('.').ToLower())))
            {
                bindingContext.ModelState.AddModelError(modelName, "仅支持如下文件格式:" + SiteConfig.FileExt);
                isValid = false;
            }

            if (modelFiles.Any(m => m.ContentLength > SiteConfig.MaxFileSize))
            {
                bindingContext.ModelState.AddModelError(modelName, "超过文件大小限定:" + SiteConfig.MaxFileSizeText);
                isValid = false;
            }

            if (!isValid)
            {
                return(new AttachmentInfo());
            }

            if (modelFiles.Count > 0)
            {
                if (!isMultiple)
                {
                    var items = attachment.Items.Remove();
                }

                foreach (var item in modelFiles.Select(file => BuildAttachmentItem(file, isDb, uploadDir)))
                {
                    attachment.Items.Add(item);
                }
            }

            TacketBase tacketBase = null;

            switch (mode)
            {
            case UploadMode.FTP:     //FTP远程上传
                tacketBase = new FtpTacket(SiteConfig.FtpHost, SiteConfig.FtpUsername, SiteConfig.FtpPassword);
                break;

            case UploadMode.UNC:     //共享目录上传
                tacketBase = new UncTacket(@"" + SiteConfig.UncHost, SiteConfig.UncUsername, SiteConfig.UncPassword);
                break;

            case UploadMode.LOC:     //本地上传测试
                tacketBase = new LocTacket()
                {
                    Host = SiteConfig.UploadFolderPhysicalPath
                };
                break;

            default:
                UploadMode defaultMode = (UploadMode)SiteConfig.DefaultMode;
                switch (defaultMode)
                {
                case UploadMode.FTP:         //FTP远程上传
                    tacketBase = new FtpTacket(SiteConfig.FtpHost, SiteConfig.FtpUsername,
                                               SiteConfig.FtpPassword);
                    break;

                case UploadMode.UNC:         //共享目录上传
                    tacketBase = new UncTacket(@"" + SiteConfig.UncHost, SiteConfig.UncUsername,
                                               SiteConfig.UncPassword);
                    break;

                case UploadMode.LOC:         //本地上传测试
                default:
                    tacketBase = new LocTacket()
                    {
                        Host = SiteConfig.UploadFolderPhysicalPath
                    };
                    break;
                }
                break;
            }
            //FileUploader fileUploader = new FileUploader(tacketBase);
            NewAttachmentInfo newInfo = AttachmentConvert.Convert(attachment);

            //if ((CheckFile(files) && isValid) && newInfo.Items != null && newInfo.Items.Any())
            //{
            //fileUploader.Upload(newInfo, isMultiple);
            var info = Upload(newInfo, isMultiple, tacketBase);
            //}

            attachment = AttachmentConvert.Convert(info);

            return(attachment);
        }
Example #12
0
        private string ExecuteConversion(string commandTemplateFile, UploadMode uploadMode1, UploadMode uploadMode2, FileInfo inputFileInfo, string outputFile, string serviceName, string scriptureReference, string[] tags, DateTime serviceDate, int skipMinutes, int skipSeconds, bool visible)
        {
            string errors           = "";
            int    totalSkipSeconds = (60 * skipMinutes) + skipSeconds;
            int    endTime          = 0;

            if ((int)numericEndMinutes.Value != 0 || (int)numericEndSeconds.Value != 0)
            {
                endTime = (60 * (int)numericEndMinutes.Value) + (int)numericEndSeconds.Value;
            }
            string commandTemplate = LoadCommandTemplate(commandTemplateFile).Trim();

            string[]      commandTemplateArr = commandTemplate.Split(' ');
            List <string> args    = new List <string>();
            string        command = commandTemplateArr[0];

            foreach (string arg in commandTemplateArr.ToList().Skip(1))
            {
                switch (arg)
                {
                case "${inputFile}":
                    args.Add(inputFileInfo.FullName);
                    break;

                case "${outputFile}":
                    args.Add(outputFile);
                    break;

                case "${skipSeconds}":
                    args.Add("" + totalSkipSeconds);

                    if (endTime != 0)
                    {
                        args.Add("-to");
                        args.Add("" + endTime);
                    }

                    break;

                default:
                    args.Add(arg);
                    break;
                }
            }
            try
            {
                this.Invoke((MethodInvoker) delegate
                {
                    setControlsEnabled(false);
                });

                FileInfo outputFileInfo = new FileInfo(outputFile);
                outputFileInfo.Delete();
                VideoManagerClient client = new VideoManagerClient();

                string homePath = Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
                using (StreamWriter outWriter = new StreamWriter(homePath + @"\videoconversionout_" + uploadMode1 + ".log"))
                {
                    // Start the child process.
                    Process p = new Process();
                    // Redirect the output stream of the child process.
                    p.StartInfo.CreateNoWindow         = true;
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardError  = true;
                    p.StartInfo.FileName  = command;
                    p.StartInfo.Arguments = ArgvToCommandLine(args);
                    outWriter.WriteLine("Arguments: " + p.StartInfo.Arguments);

                    p.Start();

                    // make sure to kill it if we are closed
                    MainForm.FormClosing += delegate(Object sender, FormClosingEventArgs e)
                    {
                        p.Refresh();
                        if (!p.HasExited)
                        {
                            p.Kill();
                        }
                    };

                    // Do not wait for the child process to exit before
                    // reading to the end of its redirected stream.
                    // p.WaitForExit();
                    // Read the output stream first and then wait.
                    string line;
                    string totalDurationString = null;


                    Regex durationRegex  = new Regex(".*Duration: (.*?), ");
                    Regex frameLineRegex = new Regex(".*time=(.*?) .*");

                    int totalSeconds = 0;
                    while ((line = p.StandardError.ReadLine()) != null)
                    {
                        if (line.Contains("Duration: "))
                        {
                            string durationString = durationRegex.Match(line).Groups[1].Value;
                            totalDurationString = durationString;
                            outWriter.WriteLine("DURATION: " + durationString);
                            string[] durationArray = durationString.Split(':');

                            //00:00:49.55
                            float hours   = float.Parse(durationArray[0]);
                            float minutes = float.Parse(durationArray[1]);
                            float seconds = float.Parse(durationArray[2]);

                            totalSeconds = (int)(seconds + (minutes * 60) + (hours * 60 * 60));
                        }
                        else if (frameLineRegex.IsMatch(line))
                        {
                            // 00:00:00.30
                            string currentPositionString = frameLineRegex.Match(line).Groups[1].Value;
                            this.Invoke((MethodInvoker) delegate
                            {
                                lblProgressText.Text = currentPositionString + "/" + totalDurationString;
                            });
                            string[] currentPositionArray = currentPositionString.Split(':');
                            float    hours   = float.Parse(currentPositionArray[0]);
                            float    minutes = float.Parse(currentPositionArray[1]);
                            float    seconds = float.Parse(currentPositionArray[2]);

                            int currentSeconds = (int)(seconds + (minutes * 60) + (hours * 60 * 60));

                            int currentPercentage = (int)(((double)currentSeconds / (double)totalSeconds) * 100d);
                            outWriter.WriteLine("PERCENTAGE: " + currentPercentage);
                            this.Invoke((MethodInvoker) delegate
                            {
                                progressBar1.Value = currentPercentage > 100 ? 100 : currentPercentage;
                            });
                        }
                        outWriter.WriteLine("LINE: " + line);
                        outWriter.Flush();
                    }
                    while ((line = p.StandardOutput.ReadLine()) != null)
                    {
                        outWriter.WriteLine(line);
                    }
                    p.WaitForExit();
                }

                if (uploadMode1 != UploadMode.No_Upload || uploadMode2 != UploadMode.No_Upload)
                {
                    this.Invoke((MethodInvoker) delegate
                    {
                        lblProgressText.Text = "Beginning File Upload";
                        progressBar1.Value   = 0;
                    });


                    UploadMode currentUploadMode = uploadMode1;
                    VideoManagerClient.UploadVideoProgress progressCallback = delegate(string filename, long currentProgress, long totalLength)
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            lblProgressText.Text = "(" + currentUploadMode + ") Uploading " + filename + " " + currentProgress + "/" + totalLength;
                            int percentage       = (int)(((double)currentProgress / (double)totalLength) * 100d);
                            progressBar1.Value   = percentage > 100 ? 100 : percentage;
                        });
                    };
                    string remoteFilename;

                    try
                    {
                        if (uploadMode1 != UploadMode.No_Upload)
                        {
                            currentUploadMode = uploadMode1;
                            client.UploadVideo(uploadMode1, out remoteFilename, outputFileInfo.FullName, serviceName, scriptureReference, tags, progressCallback);
                        }
                    }
                    catch (Exception e)
                    {
                        errors += "Conversion for " + uploadMode1 + " failed due to: " + e.Message;
                    }

                    try
                    {
                        if (uploadMode2 != UploadMode.No_Upload)
                        {
                            currentUploadMode = uploadMode2;
                            client.UploadVideo(uploadMode2, out remoteFilename, outputFileInfo.FullName, serviceName, scriptureReference, tags, progressCallback);
                        }
                    }
                    catch (Exception e)
                    {
                        errors += "Conversion for " + uploadMode2 + " failed due to: " + e.Message;
                    }

                    if (uploadMode1 != UploadMode.No_Upload || uploadMode2 != UploadMode.No_Upload)
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            lblProgressText.Text = "Upload complete!";
                        });
                    }
                    else
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            lblProgressText.Text = UploadMode.No_Upload + " Video Update Complete!";
                        });
                    }
                }
            }
            catch (Exception e)
            {
                errors += "Conversion for " + uploadMode1 + " failed due to: " + e.Message;
            }
            return(errors);
        }
Example #13
0
        private void btnConvert_Click(object sender, EventArgs e)
        {
            lblProgressText.Text = "";
            string   inputFile          = txtInputFIle.Text;
            string   outputDir          = txtOutputDir.Text;
            string   serviceName        = txtServiceName.Text;
            string   scriptureReference = txtScriptureReference.Text;
            DateTime serviceDate        = dateTimePicker1.Value;

            if (inputFile == null || inputFile.Trim().Length == 0)
            {
                ShowMessageBox("Must select an input file!");
            }
            else if (!File.Exists(inputFile.Trim()))
            {
                ShowMessageBox("ERROR: Selected input file does not exist!");
            }
            else if (outputDir == null || outputDir.Trim().Length == 0)
            {
                ShowMessageBox("Must select an output directory!");
            }
            else if (!Directory.Exists(outputDir))
            {
                ShowMessageBox("ERROR: Output directory does not exist!");
            }
            else if (serviceName == null || serviceName.Trim().Length == 0)
            {
                ShowMessageBox("ERROR: Service Name must be specified!");
            }
            else
            {
                FileInfo inputFileInfo  = new FileInfo(inputFile);
                FileInfo outputFileInfo = new FileInfo(inputFileInfo.FullName.Replace(inputFileInfo.Extension, ".mp4"));
                string   outputFile     = txtOutputDir.Text + @"\" + outputFileInfo.Name;
                if (File.Exists(outputFile))
                {
                    File.Delete(outputFile);
                }

                progressBar1.Value      = 0;
                lblProgress.Visible     = true;
                progressBar1.Visible    = true;
                lblProgressText.Visible = true;

                Action action = () =>
                {
                    string errors = "";

                    if (checkboxFullUpload.Checked)
                    {
                        string   title     = "(Full Service) " + serviceName;
                        string[] tags      = new string[] { "Tri-City Baptist Church", "Goose Creek", "Moncks Corner", "Summerville", "full" };
                        string   newErrors = ExecuteConversion(YOUTUBE_COMMAND_TEMPLATE_FILE, UploadMode.Youtube, UploadMode.No_Upload, inputFileInfo, outputFile, title, scriptureReference, tags, serviceDate, (int)numericSkipMinutesWebsite.Value, (int)numericSkipSecondsWebsite.Value, true);
                        if (newErrors != "")
                        {
                            errors += newErrors + "\n\n";
                        }
                    }

                    if (checkBoxYouTubeUpload.Checked || checkboxFacebook.Checked)
                    {
                        string     outputFileYoutube = txtOutputDir.Text + @"\" + inputFileInfo.Name.Replace(inputFileInfo.Extension, "_ytandfb.mp4");
                        string[]   tags        = new string[] { "Tri-City Baptist Church", "Goose Creek", "Moncks Corner", "Summerville", "trimmed" };
                        UploadMode uploadMode1 = this.checkBoxYouTubeUpload.Checked ? UploadMode.Youtube : UploadMode.No_Upload;
                        UploadMode uploadMode2 = this.checkboxFacebook.Checked ? UploadMode.Facebook : UploadMode.No_Upload;
                        string     newErrors   = ExecuteConversion(YOUTUBE_COMMAND_TEMPLATE_FILE, uploadMode1, uploadMode2, inputFileInfo, outputFileYoutube, serviceName, scriptureReference, tags, serviceDate, (int)numericSkipMinutesYouTube.Value, (int)numericSkipSecondsYouTube.Value, true);
                        if (newErrors != "")
                        {
                            errors += newErrors + "\n\n";
                        }
                    }

                    if (!checkboxFullUpload.Checked && !checkBoxYouTubeUpload.Checked)
                    {
                        string[] tags      = new string[] { };
                        string   newErrors = ExecuteConversion(WEBSITE_COMMAND_TEMPLATE_FILE, UploadMode.No_Upload, UploadMode.No_Upload, inputFileInfo, outputFile, serviceName, scriptureReference, tags, serviceDate, (int)numericSkipMinutesYouTube.Value, (int)numericSkipSecondsYouTube.Value, false);
                        if (newErrors != "")
                        {
                            errors += newErrors + "\n\n";
                        }
                    }

                    this.Invoke((MethodInvoker) delegate
                    {
                        if (errors != "")
                        {
                            ShowMessageBox("Process completed with errors: \n\n" + errors);
                        }
                        else
                        {
                            ShowMessageBox("Conversion Complete!");
                        }

                        lblProgress.Visible     = false;
                        progressBar1.Visible    = false;
                        lblProgressText.Visible = false;
                        setControlsEnabled(true);
                    });
                };

                Task task = new Task(action);
                task.Start();
            }
        }
        /// <summary>
        ///		Crea una tarea de subida de archivos
        /// </summary>
        private void CreateTaskUpload(int taskId, FtpConnectionModel ftpConnection, string pathLocal, string pathRemote, List <string> files, UploadMode mode)
        {
            if (files.Count > 0)
            {
                FtpUploadTask ftpUpload          = new FtpUploadTask(taskId, this, ftpConnection, pathLocal, files, pathRemote, mode);
                System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(() => ftpUpload.Upload());

                try
                {
                    task.Start();
                }
                catch (Exception exception)
                {
                    RaiseMessageEvent($"Error al generar el proceso de subida de archivos: {exception.Message}", true);
                }
            }
        }
        /// <summary>
        ///		Sube los archivos de un directorio
        /// </summary>
        public void Upload(FtpConnectionModel ftpConnection, string pathLocal, string pathRemote, int processors, UploadMode mode)
        {
            List <string> files = LoadRecursive(pathLocal);

            // Normaliza el número de procesadores
            if (processors < 1)
            {
                processors = 1;
            }
            // Procesa los archivos
            if (files.Count > 0)
            {
                int filesPerProcessor = (int)Math.Ceiling(((double)files.Count) / ((double)processors));
                int start = 0, taskId = 0;

                // Ordena los archivos
                files.Sort();
                // Crea las tareas
                while (start < files.Count)
                {
                    // Crea la tarea de subida
                    CreateTaskUpload(++taskId, ftpConnection, pathLocal, pathRemote, Split(files, start, filesPerProcessor), mode);
                    // Incrementa el inicio
                    start += filesPerProcessor;
                }
            }
        }
Example #16
0
        private async Task <string> InternalUpload(UploadMode mode, Stream stream, CancellationToken cancelToken, ProgressMonitorBase progress, FtpOptions options = null)
        {
            cancelToken.ThrowIfCancellationRequested();
            options = options ?? Handler.Options;
            long size = -1;

            if (progress != null)
            {
                if (progress.AskForSize)
                {
                    try {
                        size = stream.Length;
                    } catch (NotSupportedException) { }
                }
                progress.Progress = new FtpProgress(size);
                progress.OnInit();
            }
            byte[] buffer    = new byte[options.BufferSize];
            int    readCount = 0;
            var    protocol  = string.Empty;

            switch (mode)
            {
            case UploadMode.Upload:
                protocol = WebRequestMethods.Ftp.UploadFile;
                break;

            case UploadMode.UploadAsUnique:
                protocol = WebRequestMethods.Ftp.UploadFileWithUniqueName;
                break;

            case UploadMode.Append:
                protocol = WebRequestMethods.Ftp.AppendFile;
                break;
            }
            ;
            FtpWebRequest request = Handler.MakeRequest(cancelToken, options, Target, protocol);

            if (size != -1)
            {
                request.ContentLength = size;
            }
            using (var requestStream = await request.GetRequestStreamAsync()) {
                cancelToken.ThrowIfCancellationRequested();
                do
                {
                    readCount = await stream.ReadAsync(buffer, 0, options.BufferSize, cancelToken);

                    await requestStream.WriteAsync(buffer, 0, readCount, cancelToken);

                    cancelToken.ThrowIfCancellationRequested();
                    if (progress != null)
                    {
                        progress.Progress.CurrentCount += readCount;
                        progress.Progressed();
                    }
                } while (readCount > 0);
            }
            if (mode == UploadMode.UploadAsUnique)
            {
                using (var response = (FtpWebResponse)await request.GetResponseAsync()) {
                    cancelToken.ThrowIfCancellationRequested();
                    return(Path.GetFileName(response.ResponseUri.ToString()));
                }
            }
            return(null);
        }