} // constructor public static bool IsRecordSchedulerTask(Task schedulerTask, out RecordTask recordTask) { recordTask = null; if (string.IsNullOrEmpty(schedulerTask.Definition.RegistrationInfo.Documentation)) { return(false); } if (string.IsNullOrEmpty(schedulerTask.Definition.Data)) { return(false); } if (!schedulerTask.Definition.RegistrationInfo.Documentation.StartsWith(Resources.DefinitionRegistrationInfo_Documentation_Begins, StringComparison.InvariantCultureIgnoreCase)) { return(false); } // if try { recordTask = RecordTaskSerialization.LoadFromXmlString(schedulerTask.Definition.Data); return(true); } catch { // ignore, but return a null RecordTask return(false); } // try-catch } // IsRecordSchedulerTask
} // CanRecord public static RecordTask GetRecordTask(UiBroadcastService service, EpgProgram epgProgram, DateTime localReferenceTime) { var channel = GetRecordChannel(service); if (epgProgram == null) { return(RecordTask.CreateWithDefaultValues(channel)); } // if var isCurrent = epgProgram.IsCurrent(localReferenceTime); var program = GetRecordProgram(epgProgram); var schedule = GetRecordSchedule(epgProgram, isCurrent); var duration = GetRecordDuration(epgProgram, isCurrent); var description = GetRecordDescription(epgProgram, channel); var action = GetRecordAction(service, epgProgram); var advanced = GetRecordAdvancedSettings(); var task = new RecordTask() { Channel = channel, Program = program, Schedule = schedule, Duration = duration, Description = description, Action = action, AdvancedSettings = advanced, }; return(task); } // GetRecordTask
} // LaunchRecorderProgram private IDictionary <string, string> CreateParameters(string filename, RecordTask task) { var paramKeys = new string[] { "OutputFile", "Channel.Url", "Channel.Name", "Channel.Description", "Description.Name", "Description.Description", "Duration.TotalSeconds", }; var paramValues = new string[] { filename, task.Channel.ChannelUrl, task.Channel.Name, task.Channel.Description, task.Description.Name, task.Description.Description, ((int)TotalTime.TotalSeconds).ToString(CultureInfo.InvariantCulture), }; return(ArgumentsManager.CreateParameters(paramKeys, paramValues, false)); } // CreateParameters
} // SetSchedule private void SetDescription(TaskDefinition definition, RecordTask task) { string userDescription; _taskName = GetUniqueTaskName(task, "IPTViewr"); task.Description.TaskSchedulerName = _taskName; userDescription = task.Description.Description; if (!task.Description.AddDetails) { if (userDescription.Length > 0) { definition.RegistrationInfo.Description = userDescription; } // if } else { var details = new StringBuilder(); task.BuildDescription(true, false, false, true, true, true, null, details); task.Description.Details = details.ToString(); if (userDescription.Length > 0) { details = new StringBuilder(userDescription.Length + task.Description.Details.Length + 2); details.Append(userDescription); details.AppendLine(); details.Append(task.Description.Details); } // if details.Replace("\r\n", " \r\n"); definition.RegistrationInfo.Description = details.ToString(); } // if-else } // SetDescription
} // DialogRecordChannel_Shown #endregion #region Form events implementation private void DialogRecordChannel_Load_Implementation(object sender, EventArgs e) { BasicGoogleTelemetry.SendScreenHit(this); // Initialize if (Task == null) { if (this.DesignMode) { Task = RecordTask.CreateWithDefaultValues(null); IsNewTask = true; } else { throw new ArgumentNullException(); } // if-else } // if // General InitGeneralData(); // Schedule tab InitScheduleData(); // Duration tab InitDurationData(); // Description tab InitDescriptionData(); // Save tab InitSaveData(); // Advanced tab InitAdvancedData(); } // DialogRecordChannel_Load_Implementation
} // SaveXmlData private static void SetAdditionalData(TaskDefinition definition, RecordTask record, string dbFile) { definition.RegistrationInfo.Author = $"{Assembly.GetEntryAssembly().GetName().Name} {SolutionVersion.ProductVersion}"; definition.RegistrationInfo.Source = Resources.DefinitionRegistrationInfo_Source; definition.RegistrationInfo.Documentation = string.Format(Resources.DefinitionRegistrationInfo_Documentation, record.TaskId, dbFile); definition.RegistrationInfo.Date = DateTime.Now; definition.Data = record.SaveAsString(); } // SetAdditionalData
} // CreateWindowsJob private void DisplayTaskData(RecordTask task, TimeSpan totalRecordTime) { var buffer = new StringBuilder(); task.BuildDescription(false, true, false, true, true, true, totalRecordTime, buffer); buffer.AppendLine(); Console.WriteLine(buffer.ToString()); } // DisplayTaskData
} // GetRecordAdvancedSettings public static bool ScheduleTask(CommonBaseForm ownerForm, RecordTask task) { // schedule task var scheduler = new Scheduler(ownerForm.GetExceptionHandler(), AppUiConfiguration.Current.Folders.RecordTasks, AppUiConfiguration.Current.User.Record.RecorderLauncherPath); if (scheduler.CreateTask(task)) { MessageBox.Show(ownerForm, Properties.Resources.SchedulerCreateTaskOk, ownerForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); return(true); } // if return(false); } // ScheduleTask
} // ProcessTasks private void AddSchedulerTask(Task schedulerTask, RecordTask recordTask) { TaskData taskData; taskData = new TaskData() { Status = TaskStatus.MissingXml, SchedulerName = schedulerTask.Name, SchedulerPath = schedulerTask.Folder.Path, Task = recordTask }; List.Add(taskData); } // AddSchedulerTask
/// <summary> /// /// </summary> /// <param name="db"></param> public RecordManager(SqlSugarScope db, ILogger <RecordManager> logger) { this.db = db; records = new RecordTask(logger); tasks = new RecordTask(logger); last = DateTime.Now; duration = TimeSpan.FromSeconds(2); worker = new Thread(() => { var watch = new Stopwatch(); var count = 0; watch.Start(); while (true) { try { watch.Restart(); lock (records) { if (records.Count > 0) { last = DateTime.Now; records.Switch(tasks); } } count = tasks.Count; if (tasks.Count > 0) { tasks.WriteDown(db); logger.LogInformation("write down final"); } watch.Stop(); if (count > 0) { logger.LogInformation("down: {0}ms {1}", watch.ElapsedMilliseconds, count); } } catch (Exception e) { logger.LogError("write down: {0}", e); } Thread.Sleep(duration); } }); worker.Start(); logger.LogInformation("Start Worker."); this.logger = logger; }
} // SetSchedule private static string GetUniqueTaskName(RecordTask task, string prefix) { string format; string description; description = task.Description.Name; if (task.Description.AddPrefix) { format = (description.Length > 0) ? "{2} ~ {0} {1:P}" : "{2} {1:P}"; } else { format = (description.Length > 0) ? "{0} {1:P}" : "{2} {1:P}"; } // if-else return(string.Format(format, description, task.TaskId, prefix)); } // GetUniqueTaskName
} // GetTaskSchedulerFolder private void GetDuration(RecordTask task) { // set duration if EndDateTime if (task.Duration.EndDateTime != null) { task.Duration.Length = task.Duration.GetDuration(task.Schedule); } // if-else // extract start details _startSafetyMargin = task.Schedule.SafetyMarginTimeSpan; // extract duration details _endSafetyMargin = task.Duration.SafetyMarginTimeSpan; _recordDuration = task.Duration.Length; // do some math _totalRecordTime = _startSafetyMargin + _recordDuration + _endSafetyMargin; } // GetDuration
} // SetAdditionalData private void SetAction(TaskDefinition definition, RecordTask record, string dbFile, string logFolder) { var arguments = new[] { "/Action:Record", $"/TaskId:{record.TaskId}", $"/Database:{dbFile}", $"/LogFolder:{logFolder}" }; var action = new ExecAction() { Path = _recorderLauncherPath, Arguments = ArgumentsManager.JoinArguments(arguments), WorkingDirectory = record.Action.SaveLocationPath, }; definition.Actions.Add(action); } // SetAction
public static void TryUpload(RecordTask task, string path) { if (DoUpload) { ProcessStartInfo ps = new ProcessStartInfo { FileName = "BaiduPCS-Go", Arguments = $"u {path} /{task.TaskName}_archives/", RedirectStandardOutput = true, StandardOutputEncoding = Encoding.UTF8 }; Process p = new Process(); p.StartInfo = ps; p.Start(); p.WaitForExit(); Console.WriteLine(p.StandardOutput.ReadToEnd()); } }
} // IsRecordSchedulerTask public bool CreateTask(RecordTask record) { TaskService taskScheduler; TaskDefinition definition; Task task; bool isOk; _taskFolder = null; _taskName = null; taskScheduler = null; definition = null; task = null; isOk = false; try { taskScheduler = new TaskService(); definition = taskScheduler.NewTask(); // Get folder for new task _taskFolder = GetTaskSchedulerFolder(record.AdvancedSettings, taskScheduler); // "Duration" // Duration 'per-se' is handled by the recording process. // However, we need extract some information GetDuration(record); // "Schedule" SetSchedule(definition, record.Schedule); // "Description" SetDescription(definition, record); // "Save" // Save location is handled by the recording process // "Advanced" SetAdvancedSettings(definition.Settings, record.AdvancedSettings, record.Schedule.Kind == RecordScheduleKind.RightNow); // Save xml data SaveXmlData(record); // Aditional task data SetAdditionalData(definition, record, _dbFile); // Action SetAction(definition, record, _dbFile, _logFolder); // Register task task = _taskFolder.RegisterTaskDefinition(_taskName, definition); isOk = true; // Run task right now? if (record.Schedule.Kind != RecordScheduleKind.RightNow) { return(true); } try { task.Run(); return(true); } catch (Exception ex) { _exceptionHandler(new ExceptionEventData(Texts.TaskRunException, ex)); return(false); } // try-catch } catch (Exception ex) { _exceptionHandler(new ExceptionEventData(Texts.TaskCreationException, ex)); return(false); } finally { if (!isOk) { RecordTaskSerialization.TryDeleteFromDatabase(record.TaskId, _dbFile); } // if if (task != null) { task.Dispose(); task = null; } // if if (definition != null) { definition.Dispose(); definition = null; } // if if (_taskFolder != null) { _taskFolder.Dispose(); _taskFolder = null; } // if if (taskScheduler != null) { taskScheduler.Dispose(); taskScheduler = null; } // if _taskName = null; } // try-finally } // CreateTask
} // SetAdvancedSettings private void SaveXmlData(RecordTask record) { record.SaveToDatabase(_dbFile); } // SaveXmlData
} // DisplayTaskData private Program.Result LaunchRecorderProgram(RecordTask task) { var scheduledStartTime = task.Schedule.GetStartDateTime(); var scheduledTotalTime = task.Schedule.SafetyMarginTimeSpan + task.Duration.GetDuration(task.Schedule) + task.Duration.SafetyMarginTimeSpan; var now = DateTime.Now; // var scheduledDateTime = new DateTime(scheduledStartTime.Year, scheduledStartTime.Month, scheduledStartTime.Day, scheduledStartTime.Hour, scheduledStartTime.Minute, scheduledStartTime.Second); // TODO: determine most probable launch date; we need to account for HUGE delays between scheduled run time and real run time var scheduledDateTime = new DateTime(now.Year, now.Month, now.Day, scheduledStartTime.Hour, scheduledStartTime.Minute, scheduledStartTime.Second); var gap = now - scheduledDateTime; if (gap.TotalSeconds < 1) { gap = TimeSpan.Zero; } TotalTime = scheduledTotalTime - gap; Logger.Log(Logger.Level.Verbose, Properties.Texts.LogVerboseScheduledStartTimeGap, scheduledStartTime, scheduledTotalTime, gap, TotalTime); DisplayTaskData(task, TotalTime); if (TotalTime.TotalSeconds < 1) { Logger.Log(Logger.Level.Error, Properties.Texts.LogErrorTooLate); return(Program.Result.TooLate); } // if if (gap.TotalSeconds < 30) { gap = TimeSpan.Zero; } if (task.Schedule.Kind != RecordScheduleKind.RightNow) { if (gap.TotalSeconds > task.Schedule.SafetyMarginTimeSpan.TotalSeconds) { RecordingLate = true; Logger.Log(Logger.Level.Warning, Properties.Texts.LogWarningRecordingLate, (int)task.Schedule.SafetyMarginTimeSpan.TotalMinutes); Console.WriteLine(Properties.Texts.DisplayWarningRecordingLate, (int)task.Schedule.SafetyMarginTimeSpan.TotalMinutes); } else if (gap.TotalSeconds > 0) { Logger.Log(Logger.Level.Warning, Properties.Texts.LogWarningBehindSchedule, gap); Console.WriteLine(Properties.Texts.DisplayWarningBehindSchedule, gap); } // if-else } // if-else var date = string.Format(Properties.Texts.FormatRecordFileDate, now.Year, now.Month, now.Day, scheduledStartTime.Hour, scheduledStartTime.Minute, scheduledStartTime.Second); var filename = string.Format(Properties.Texts.FormatRecordFileName, task.Action.SaveLocationPath, task.Action.Filename, date, RecordingLate ? Properties.Texts.FormatRecordFileDelayed : null, task.Action.FileExtension); var parameters = CreateParameters(filename, task); LogParameters(parameters); var arguments = ArgumentsManager.ExpandArguments(task.Action.Recorder.Arguments, parameters, Properties.Resources.ArgumentsOpenBrace, Properties.Resources.ArgumentsCloseBrace, StringComparison.CurrentCultureIgnoreCase); var joinedArguments = ArgumentsManager.JoinArguments(arguments); LogArguments(task.Action.Recorder.Path, task.Action.Recorder.Arguments, joinedArguments); try { var info = new ProcessStartInfo() { FileName = task.Action.Recorder.Path, Arguments = joinedArguments, ErrorDialog = false, UseShellExecute = false, }; Logger.Log(Logger.Level.Info, Properties.Texts.LogInfoLaunchingRecorder); Console.Write(Properties.Texts.DisplayLaunchingRecorder); using (var process = Process.Start(info)) { Logger.Log(Logger.Level.Info, Properties.Texts.LogInfoLaunchingRecorderOk, process.Id); Console.WriteLine(Properties.Texts.DisplayLaunchingRecorderOk, process.Id); TimerTickCount = 0; StartTime = DateTime.UtcNow; var timer = new System.Threading.Timer(OnTimerTick, null, 0, 60000); Logger.Log(Logger.Level.Verbose, Properties.Texts.LogVerboseWaitForExit); process.WaitForExit(); timer.Dispose(); Logger.Log(Logger.Level.Info, Properties.Texts.LogInfoRecorderExited, process.ExitCode); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(Properties.Texts.DisplayRecorderFinished); if (process.ExitCode != 0) { return(Program.Result.ExecFailure); } // if } // using } catch (Exception ex) { Logger.Exception(ex, Properties.Texts.LogExceptionLaunchingRecorder); Program.DisplayException(ex); return(Program.Result.ExecProblem); } // try-catch return(Program.Result.Ok); } // LaunchRecorderProgram