async Task IJob.Execute(IJobExecutionContext context)
        {
            Logger.Info("Start sending notifications");
            var items = _schedulerCustomers.GetItems().ToArray();

            items = JobHelpers.FilterCustomers(items, context.MergedJobDataMap);
            var token = context.CancellationToken;

            foreach (var customer in items)
            {
                try
                {
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }

                    var notificationIdsStatus = await ProcessCustomer(customer, token);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "There was an error on customer code {customerCode}", customer.CustomerName);
                }
            }

            Logger.Info("End sending notifications");
        }
        public void Execute(PersistBrokerPluginContext context)
        {
            if (context.EntityName != "robot_message_task")
            {
                return;
            }

            var obj = context.Entity as robot_message_task;

            switch (context.Action)
            {
            case EntityAction.PostCreate:
            case EntityAction.PostUpdate:
                JobHelpers.RegisterJob(new RobotMessageTaskJob(obj.name, obj.robotidName, obj.runtime), obj, obj.job_state.ToTriggerState());
                break;

            case EntityAction.PreCreate:
                var jobState = new RobotMessageTaskJob().DefaultTriggerState.ToSelectOption();
                obj.job_state     = jobState.Value.ToString();
                obj.job_stateName = jobState.Name;
                break;

            case EntityAction.PreUpdate:
            case EntityAction.PostDelete:
                JobHelpers.DeleteJob(obj.name, obj.robotidName);
                break;

            default:
                break;
            }
        }
Example #3
0
        public Task Execute(IJobExecutionContext context)
        {
            Logger.Info("Start enabling");

            var customers = _schedulerCustomers.GetItems();
            var dataMap   = context.MergedJobDataMap;

            customers = JobHelpers.FilterCustomers(customers, dataMap);
            var excludedUsers = dataMap.GetString(ExcludedUsersKey)?.Split(',');

            foreach (var customer in customers)
            {
                try
                {
                    if (context.CancellationToken.IsCancellationRequested)
                    {
                        break;
                    }

                    if (!context.CancellationToken.IsCancellationRequested)
                    {
                        ProcessCustomer(customer, excludedUsers, context.CancellationToken);
                    }
                }
                catch (Exception ex)
                {
                    ex.Data.Clear();
                    ex.Data.Add("CustomerCode", customer.CustomerName);
                    Logger.Error(ex, $"There was an error on customer code: {customer.CustomerName}", ex);
                }
            }

            Logger.Info("Finished enabling users");
            return(Task.CompletedTask);
        }
Example #4
0
        public Task Execute(IJobExecutionContext context)
        {
            StartupJobsLogic startupJobsLogic = new StartupJobsLogic();

            startupJobsLogic.CheckForUpdates();
            JobHelpers.SetJobLastRunDateTime(context);
            return(Task.CompletedTask);
        }
Example #5
0
        public Task Execute(IJobExecutionContext context)
        {
            CleanUpDatabase cleanUpDatabase = new CleanUpDatabase();

            cleanUpDatabase.TrimLogs();
            JobHelpers.SetJobLastRunDateTime(context);
            return(Task.CompletedTask);
        }
        public Task Execute(IJobExecutionContext context)
        {
            StartupJobsLogic startupJobs = new StartupJobsLogic();

            startupJobs.CheckForStreamerLiveStatus();
            JobHelpers.SetJobLastRunDateTime(context);
            return(Task.CompletedTask);
        }
Example #7
0
        public void ResumeJob(string id)
        {
            var data = GetData(id);

            JobHelpers.ResumeJob(data.name, data.robotidName);
            data.job_state     = "0";
            data.job_stateName = "正常";
            UpdateData(data);
        }
Example #8
0
        public void PauseJob(string id)
        {
            var data = GetData(id);

            JobHelpers.PauseJob(data.name, data.robotidName);
            data.job_state     = "1";
            data.job_stateName = "暂停";
            UpdateData(data);
        }
Example #9
0
        public Task Execute(IJobExecutionContext context)
        {
            StartupJobsLogic startupJobsLogic = new StartupJobsLogic();
            JobDataMap       jobDataMap       = context.JobDetail.JobDataMap;

            startupJobsLogic.DatabaseBackup(jobDataMap.GetString("database"));
            JobHelpers.SetJobLastRunDateTime(context);
            return(Task.CompletedTask);
        }
Example #10
0
 /// <summary>
 /// 运行一次job
 /// </summary>
 /// <param name="name"></param>
 public void RunOnceNow(string name)
 {
     ServiceContainer.ResolveAll <IJob>().Each(item =>
     {
         var job = item as JobBase;
         if (job.Name == name)
         {
             JobHelpers.RunOnceNow(job.Name, job.GetType().Namespace);
         }
     });
 }
Example #11
0
        public void RunOnce(string id)
        {
            var data      = GetData(id);
            var paramList = new Dictionary <string, object>()
            {
                { "Entity", data },
                { "User", UserIdentityUtil.GetAdmin() }
            };

            JobHelpers.RunOnceNow(data.name, data.robotidName, paramList);
            var jobState = JobHelpers.GetJobStatus(data.name, data.robotidName).ToSelectOption();

            data.job_state     = jobState.Value.ToString();
            data.job_stateName = jobState.Name;
            UpdateData(data);
        }
Example #12
0
        public Task QuartzDeleteJobLogic(QuartzExecuteJob.QuartzExecuteJobRequest requestBody)
        {
            MethodInfo methodInfo = typeof(QuartzSchedulers).GetMethod(requestBody.scheduler);

            if (methodInfo is not null)
            {
                var        schedulerFactory = new StdSchedulerFactory();
                IScheduler scheduler        = schedulerFactory.GetScheduler().Result;

                var splitJobName = requestBody.name.Split(".");
                return(JobHelpers.CancelJob(splitJobName[1], splitJobName[0], (NameValueCollection)methodInfo.Invoke(this, null)));
            }
            else
            {
                return(Task.FromException(new SchedulerException("Scheduler does not exist.")));
            }
        }
Example #13
0
        public virtual void Configure()
        {
            var logger = LogFactory.GetLogger("startup");

            logger.Info("正在启动机器人作业...");
            try
            {
                new RobotMessageTaskService().GetAllData().Each(item =>
                {
                    JobHelpers.RegisterJob(new RobotMessageTaskJob(item.name, item.robotidName, item.runtime), item, item.job_state.ToTriggerState());
                    logger.Info($"机器人[{item.robotidName}]的[{item.name}]作业已启动");
                });
                logger.Info("机器人启动完毕");
            }
            catch (Exception e)
            {
                logger.Error("注册机器人失败", e);
                throw e;
            }
        }
Example #14
0
        public Task Execute(IJobExecutionContext context)
        {
            Logger.Info("Start cleanup notification queue");
            var items = _schedulerCustomers.GetItems();

            items = JobHelpers.FilterCustomers(items, context.MergedJobDataMap);
            foreach (var customer in items)
            {
                try
                {
                    ProcessCustomer(customer);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "There was an error on customer code {customerCode}", customer.CustomerName);
                }
            }

            Logger.Info("End cleanup notification queue");
            return(Task.CompletedTask);
        }
Example #15
0
        public Task Execute(IJobExecutionContext context)
        {
            Logger.Info("Start users synchronization");
            var items = _schedulerCustomers.GetItems();

            items = JobHelpers.FilterCustomers(items, context.MergedJobDataMap);
            foreach (var customer in items)
            {
                try
                {
                    ProcessCustomer(customer);
                }
                catch (Exception ex)
                {
                    Logger.Warn(ex, "There was an error while processing customer code: {customerCode}", customer.CustomerName);
                }
            }

            Logger.Info("End users synchronization");
            return(Task.CompletedTask);
        }
Example #16
0
        public Task Execute(IJobExecutionContext context)
        {
            Logger.Info($"Start disabling inactive users");
            var customers = _schedulerCustomers.GetItems();

            var dataMap = context.MergedJobDataMap;

            customers = JobHelpers.FilterCustomers(customers, dataMap);
            var diff = dataMap.GetIntValue(InactivePeriodKey);

            if (diff <= 0)
            {
                Logger.Warn($"Task is cancelled because inactive period are {diff} days");
                return(Task.CompletedTask);
            }

            foreach (var customer in customers)
            {
                try
                {
                    if (!context.CancellationToken.IsCancellationRequested)
                    {
                        ProcessCustomer(customer, diff, context.CancellationToken);
                    }
                }
                catch (Exception ex)
                {
                    ex.Data.Clear();
                    ex.Data.Add("CustomerCode", customer.CustomerName);
                    Logger.Error(ex, $"There was an error on customer code: {customer.CustomerName}", ex);
                }
            }

            Logger.Info($"Finished disabling inactive users");
            return(Task.CompletedTask);
        }
Example #17
0
        public Streamer CreateStreamerLogic(Streamer body)
        {
            Streamer returnStreamer;

            using (var context = new MainDataContext()) {
                Streamer streamer = context.Streamers.FirstOrDefault(item => item.streamerId == body.streamerId);

                if (streamer == null)
                {
                    // if streamer does not exist in database and want to add
                    _logger.Info("Adding new streamer...");

                    string etag = "";
                    if (GlobalConfig.GetGlobalConfig("contentRootPath") != null)
                    {
                        CreateFolder($"{GlobalConfig.GetGlobalConfig("contentRootPath")}/streamers/{body.streamerId}/");
                        if (!string.IsNullOrEmpty(body.thumbnailLocation))
                        {
                            etag = DownloadHelpers.DownloadFile(body.thumbnailLocation,
                                                                $"{GlobalConfig.GetGlobalConfig("contentRootPath")}/streamers/{body.streamerId}/thumbnail.png");
                        }
                    }


                    streamer = new Streamer {
                        streamerId        = body.streamerId,
                        displayName       = body.displayName,
                        username          = body.username,
                        isLive            = body.isLive ?? false,
                        quality           = body.quality == "{\"resolution\":0,\"fps\":0}" ? null : body.quality,
                        getLive           = body.getLive ?? false,
                        thumbnailLocation = $"streamers/{body.streamerId}/thumbnail.png",
                        thumbnailETag     = etag
                    };

                    context.Streamers.Add(streamer);
                    returnStreamer = streamer;
                } /*else if (streamer != null) {
                   * // if streamer exists then update
                   * Console.WriteLine("Updating streamer...");
                   * streamer.streamerId = body.streamerId;
                   * streamer.displayName = body.displayName;
                   * streamer.username = body.username;
                   * streamer.description = body.description;
                   * streamer.viewCount = body.viewCount;
                   * streamer.thumbnailLocation = $"streamers/{body.streamerId}/thumbnail.png";
                   * returnStreamer = streamer;
                   *
                   * IList<Parameter> headers = downloadHelpers.GetHeaders(body.thumbnailLocation);
                   * for (var x = 0; x < headers.Count; x++) {
                   *    if (headers[x].Name == "ETag") {
                   *        var etag = headers[x].Value;
                   *        if (etag != null) {
                   *            if (streamer.thumbnailETag != etag.ToString().Replace("\"", "")) {
                   *                if (contentRootPath != null)
                   *                    Console.WriteLine("Detected new thumbnail image, downloading...");
                   *                streamer.thumbnailETag = downloadHelpers.DownloadFile(body.thumbnailLocation,
                   *                    $"{contentRootPath.value}/streamers/{body.streamerId}/thumbnail.png");
                   *            }
                   *        }
                   *    }
                   * }
                   * }*/
                else
                {
                    //something strange has happened
                    returnStreamer = new Streamer();
                }

                //if (isNew) {
                //StartupJobs startupJobs = new StartupJobs();
                List <Streamer> streamers = new List <Streamer> {
                    streamer
                };                                                        //lazy
                JobHelpers.NormalJob <CheckForStreamerLiveStatusJob>("CreateStreamerUpdateLiveStatusJob", "CreateStreamerUpdateLiveStatusTrigger", QuartzSchedulers.PrimaryScheduler());
                IJobDetail job = JobBuilder.Create <UpdateStreamerDetailsJob>()
                                 .WithIdentity("UpdateStreamerDetailsJob")
                                 .Build();

                job.JobDataMap.Put("listOfStreamers", streamers);

                var        schedulerFactory = new StdSchedulerFactory(QuartzSchedulers.PrimaryScheduler());
                IScheduler scheduler        = schedulerFactory.GetScheduler().Result;
                scheduler.Start();

                ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                         .WithIdentity("UpdateStreamerDetailsTrigger")
                                         .StartNow()
                                         .Build();

                scheduler.ScheduleJob(job, trigger);
                //}

                context.SaveChanges();
            }

            return(returnStreamer);
        }
 public void NotifyUsersAndRetireInactiveAccounts()
 {
     JobHelpers.RunAndLogJob(NotifyUsersAndRetireInactiveAccountsAction, nameof(NotifyUsersAndRetireInactiveAccounts));
 }
 public void UpdateDownloadFiles()
 {
     JobHelpers.RunAndLogJob(UpdateDownloadFilesAction, nameof(UpdateDownloadFiles));
 }
 //Remove any unverified users their addresses, UserOrgs, Org and addresses and archive to zip
 public void PurgeUsers()
 {
     JobHelpers.RunAndLogJob(PurgeUsersAction, nameof(PurgeUsers));
 }
Example #21
0
        public static async Task <HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "HttpTriggerCSharp/name/{name}")] HttpRequestMessage req, string name, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            // Read values from the App.config file.
            string _storageAccountName        = Environment.GetEnvironmentVariable("MediaServicesStorageAccountName");
            string _storageAccountKey         = Environment.GetEnvironmentVariable("MediaServicesStorageAccountKey");
            string _AADTenantDomain           = Environment.GetEnvironmentVariable("AMSAADTenantDomain");
            string _RESTAPIEndpoint           = Environment.GetEnvironmentVariable("AMSRESTAPIEndpoint");
            string _mediaservicesClientId     = Environment.GetEnvironmentVariable("AMSClientId");
            string _mediaservicesClientSecret = Environment.GetEnvironmentVariable("AMSClientSecret");

            // Field for cloud media context
            CloudMediaContext   _context = null;
            CloudStorageAccount _destinationStorageAccount = null;

            int    taskindex = 0;
            bool   useEncoderOutputForAnalytics = false;
            IAsset outputEncoding = null;

            log.Info($"Webhook was triggered!");

            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            log.Info(jsonContent);

            log.Info($"asset id : {data.assetId}");

            if (data.assetId == null)
            {
                // for test
                // data.assetId = "nb:cid:UUID:2d0d78a2-685a-4b14-9cf0-9afb0bb5dbfc";

                return(req.CreateResponse(HttpStatusCode.BadRequest, new
                {
                    error = "Please pass asset ID in the input object (assetId)"
                }));
            }

            // for test
            // data.WorkflowAssetId = "nb:cid:UUID:44fe8196-616c-4490-bf80-24d1e08754c5";
            // if data.WorkflowAssetId is passed, then it means a Premium Encoding task is asked

            log.Info($"Using Azure Media Service Rest API Endpoint : {_RESTAPIEndpoint}");

            IJob  job          = null;
            ITask taskEncoding = null;

            int OutputMES           = -1;
            int OutputMEPW          = -1;
            int OutputIndex1        = -1;
            int OutputIndex2        = -1;
            int OutputOCR           = -1;
            int OutputFaceDetection = -1;
            int OutputMotion        = -1;
            int OutputSummarization = -1;
            int OutputHyperlapse    = -1;
            int OutputFaceRedaction = -1;
            int NumberJobsQueue     = 0;

            try
            {
                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(_AADTenantDomain,
                                                                                       new AzureAdClientSymmetricKey(_mediaservicesClientId, _mediaservicesClientSecret),
                                                                                       AzureEnvironments.AzureCloudEnvironment);

                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);

                _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider);


                // find the Asset
                string assetid = (string)data.assetId;
                IAsset asset   = _context.Assets.Where(a => a.Id == assetid).FirstOrDefault();

                if (asset == null)
                {
                    log.Info($"Asset not found {assetid}");
                    return(req.CreateResponse(HttpStatusCode.BadRequest, new
                    {
                        error = "Asset not found"
                    }));
                }

                if (data.useEncoderOutputForAnalytics != null && (data.mesPreset != null || data.mesPreset != null))  // User wants to use encoder output for media analytics
                {
                    useEncoderOutputForAnalytics = (bool)data.useEncoderOutputForAnalytics;
                }


                // Declare a new encoding job with the Standard encoder
                int priority = 10;
                if (data.priority != null)
                {
                    priority = (int)data.priority;
                }
                job = _context.Jobs.Create(((string)data.jobName) ?? "Azure Functions Job", priority);

                if (data.mesPreset != null)  // MES Task
                {
                    // Get a media processor reference, and pass to it the name of the
                    // processor to use for the specific task.
                    IMediaProcessor processorMES = mediaServiceHelper.GetLatestMediaProcessorByName("Media Encoder Standard", _context);

                    string preset = data.mesPreset;

                    if (preset.ToUpper().EndsWith(".JSON"))
                    {
                        // Change or modify the custom preset JSON used here.
                        //  preset = File.ReadAllText(@"D:\home\site\wwwroot\Presets\" + preset);

                        // Read in custom preset string
                        string homePath = Environment.GetEnvironmentVariable("HOME", EnvironmentVariableTarget.Process);
                        log.Info("Home= " + homePath);
                        string presetPath;

                        if (homePath == String.Empty)
                        {
                            presetPath = @"../presets/" + preset;
                        }
                        else
                        {
                            presetPath = Path.Combine(homePath, @"site\repository\media-functions-for-logic-app\presets\" + preset);
                        }
                        log.Info($"Preset path : {presetPath}");
                        preset = File.ReadAllText(presetPath);
                    }

                    // Create a task with the encoding details, using a string preset.
                    // In this case "H264 Multiple Bitrate 720p" system defined preset is used.
                    taskEncoding = job.Tasks.AddNew("MES encoding task",
                                                    processorMES,
                                                    preset,
                                                    TaskOptions.None);

                    // Specify the input asset to be encoded.
                    taskEncoding.InputAssets.Add(asset);
                    OutputMES = taskindex++;

                    // Add an output asset to contain the results of the job.
                    // This output is specified as AssetCreationOptions.None, which
                    // means the output asset is not encrypted.
                    outputEncoding = taskEncoding.OutputAssets.AddNew(asset.Name + " MES encoded", AssetCreationOptions.None);
                }

                if (data.workflowAssetId != null)// Premium Encoder Task
                {
                    //find the workflow asset
                    string workflowassetid = (string)data.workflowAssetId;
                    IAsset workflowAsset   = _context.Assets.Where(a => a.Id == workflowassetid).FirstOrDefault();

                    if (workflowAsset == null)
                    {
                        log.Info($"Workflow not found {workflowassetid}");
                        return(req.CreateResponse(HttpStatusCode.BadRequest, new
                        {
                            error = "Workflow not found"
                        }));
                    }

                    // Get a media processor reference, and pass to it the name of the
                    // processor to use for the specific task.
                    IMediaProcessor processorMEPW = mediaServiceHelper.GetLatestMediaProcessorByName("Media Encoder Premium Workflow", _context);

                    string premiumConfiguration = "";
                    if (data.workflowConfig != null)
                    {
                        premiumConfiguration = (string)data.workflowConfig;
                    }
                    // In some cases, a configuration can be loaded and passed it to the task to tuned the workflow
                    // premiumConfiguration=File.ReadAllText(@"D:\home\site\wwwroot\Presets\SetRuntime.xml").Replace("VideoFileName", VideoFile.Name).Replace("AudioFileName", AudioFile.Name);

                    // Create a task
                    taskEncoding = job.Tasks.AddNew("Premium Workflow encoding task",
                                                    processorMEPW,
                                                    premiumConfiguration,
                                                    TaskOptions.None);

                    log.Info("task created");

                    // Specify the input asset to be encoded.
                    taskEncoding.InputAssets.Add(workflowAsset); // first add the Workflow
                    taskEncoding.InputAssets.Add(asset);         // Then add the video asset
                    OutputMEPW = taskindex++;

                    // Add an output asset to contain the results of the job.
                    // This output is specified as AssetCreationOptions.None, which
                    // means the output asset is not encrypted.
                    outputEncoding = taskEncoding.OutputAssets.AddNew(asset.Name + " Premium encoded", AssetCreationOptions.None);
                }

                IAsset an_asset = useEncoderOutputForAnalytics ? outputEncoding : asset;

                // Media Analytics
                JobHelpers helpers = new JobHelpers();
                OutputIndex1        = helpers.AddTask(job, an_asset, (string)data.indexV1Language, "Azure Media Indexer", "IndexerV1.xml", "English", ref taskindex, _context);
                OutputIndex2        = helpers.AddTask(job, an_asset, (string)data.indexV2Language, "Azure Media Indexer 2 Preview", "IndexerV2.json", "EnUs", ref taskindex, _context);
                OutputOCR           = helpers.AddTask(job, an_asset, (string)data.ocrLanguage, "Azure Media OCR", "OCR.json", "AutoDetect", ref taskindex, _context);
                OutputFaceDetection = helpers.AddTask(job, an_asset, (string)data.faceDetectionMode, "Azure Media Face Detector", "FaceDetection.json", "PerFaceEmotion", ref taskindex, _context);
                OutputFaceRedaction = helpers.AddTask(job, an_asset, (string)data.faceRedactionMode, "Azure Media Redactor", "FaceRedaction.json", "combined", ref taskindex, _context);
                OutputMotion        = helpers.AddTask(job, an_asset, (string)data.motionDetectionLevel, "Azure Media Motion Detector", "MotionDetection.json", "medium", ref taskindex, _context);
                OutputSummarization = helpers.AddTask(job, an_asset, (string)data.summarizationDuration, "Azure Media Video Thumbnails", "Summarization.json", "0.0", ref taskindex, _context);

                // Hyperlapse
                OutputHyperlapse = helpers.AddTask(job, asset, (string)data.hyperlapseSpeed, "Azure Media Hyperlapse", "Hyperlapse.json", "8", ref taskindex, _context);

                job.Submit();
                log.Info("Job Submitted");
                NumberJobsQueue = _context.Jobs.Where(j => j.State == JobState.Queued).Count();
            }
            catch (Exception ex)
            {
                log.Info($"Exception {ex}");
                return(req.CreateResponse(HttpStatusCode.InternalServerError, new
                {
                    Error = ex.ToString()
                }));
            }

            job = _context.Jobs.Where(j => j.Id == job.Id).FirstOrDefault(); // Let's refresh the job
            log.Info("Job Id: " + job.Id);
            log.Info("OutputAssetMESId: " + JobHelpers.ReturnId(job, OutputMES));
            log.Info("OutputAssetMEPWId: " + JobHelpers.ReturnId(job, OutputMEPW));
            log.Info("OutputAssetIndexV1Id: " + JobHelpers.ReturnId(job, OutputIndex1));
            log.Info("OutputAssetIndexV2Id: " + JobHelpers.ReturnId(job, OutputIndex2));
            log.Info("OutputAssetOCRId: " + JobHelpers.ReturnId(job, OutputOCR));
            log.Info("OutputAssetFaceDetectionId: " + JobHelpers.ReturnId(job, OutputFaceDetection));
            log.Info("OutputAssetFaceRedactionId: " + JobHelpers.ReturnId(job, OutputFaceRedaction));
            log.Info("OutputAssetMotionDetectionId: " + JobHelpers.ReturnId(job, OutputMotion));
            log.Info("OutputAssetSummarizationId: " + JobHelpers.ReturnId(job, OutputSummarization));
            log.Info("OutputAssetHyperlapseId: " + JobHelpers.ReturnId(job, OutputHyperlapse));

            return(req.CreateResponse(HttpStatusCode.OK, new
            {
                jobId = job.Id,
                otherJobsQueue = NumberJobsQueue,
                mes = new
                {
                    assetId = JobHelpers.ReturnId(job, OutputMES),
                    taskId = JobHelpers.ReturnTaskId(job, OutputMES)
                },
                mepw = new
                {
                    assetId = JobHelpers.ReturnId(job, OutputMEPW),
                    taskId = JobHelpers.ReturnTaskId(job, OutputMEPW)
                },
                indexV1 = new
                {
                    assetId = JobHelpers.ReturnId(job, OutputIndex1),
                    taskId = JobHelpers.ReturnTaskId(job, OutputIndex1),
                    language = (string)data.indexV1Language
                },
                indexV2 = new
                {
                    assetId = JobHelpers.ReturnId(job, OutputIndex2),
                    taskId = JobHelpers.ReturnTaskId(job, OutputIndex2),
                    language = (string)data.indexV2Language
                },
                ocr = new
                {
                    assetId = JobHelpers.ReturnId(job, OutputOCR),
                    taskId = JobHelpers.ReturnTaskId(job, OutputOCR)
                },
                faceDetection = new
                {
                    assetId = JobHelpers.ReturnId(job, OutputFaceDetection),
                    taskId = JobHelpers.ReturnTaskId(job, OutputFaceDetection)
                },
                faceRedaction = new
                {
                    assetId = JobHelpers.ReturnId(job, OutputFaceRedaction),
                    taskId = JobHelpers.ReturnTaskId(job, OutputFaceRedaction)
                },
                motionDetection = new
                {
                    assetId = JobHelpers.ReturnId(job, OutputMotion),
                    taskId = JobHelpers.ReturnTaskId(job, OutputMotion)
                },
                summarization = new
                {
                    assetId = JobHelpers.ReturnId(job, OutputSummarization),
                    taskId = JobHelpers.ReturnTaskId(job, OutputSummarization)
                },
                hyperlapse = new
                {
                    assetId = JobHelpers.ReturnId(job, OutputHyperlapse),
                    taskId = JobHelpers.ReturnTaskId(job, OutputHyperlapse)
                }
            }));

            // Fetching the name from the path parameter in the request URL
            return(req.CreateResponse(HttpStatusCode.OK, "Hello " + name));
        }
Example #22
0
 //Remove any incomplete registrations
 public void PurgeRegistrations()
 {
     JobHelpers.RunAndLogJob(PurgeRegistrationsAction, nameof(PurgeRegistrations));
 }
 //Set presumed scope of previous years and current years
 public void SetPresumedScopes()
 {
     JobHelpers.RunAndLogJob(SetPresumedScopesAction, nameof(SetPresumedScopes));
 }
 public void SendNotifyEmail(NotifyEmail notifyEmail)
 {
     JobHelpers.RunAndLogJob(() => SendNotifyEmailAction(notifyEmail), nameof(SendNotifyEmail), JobErrorsLogged.Manually);
 }
 public void FetchCompaniesHouseData()
 {
     JobHelpers.RunAndLogJob(UpdateFromCompaniesHouse, nameof(FetchCompaniesHouseData));
 }
Example #26
0
        public static void SetDownloadToFinished(long streamId, bool isLive)
        {
            Logger _logger = new NLog.LogFactory().GetCurrentClassLogger();

            using (var context = new MainDataContext()) {
                Stream dbStream;

                dbStream = context.Streams.FirstOrDefault(item => item.streamId == streamId);

                string streamFile = GlobalConfig.GetGlobalConfig("contentRootPath") + dbStream.location + dbStream.fileName;
                dbStream.size        = new FileInfo(streamFile).Length;
                dbStream.downloading = false;

                NotificationHub.Current.Clients.All.SendAsync($"{streamId}-completed",
                                                              dbStream);

                if (isLive)
                {
                    _logger.Info("Stopping live chat download...");
                    if (dbStream.chatDownloadJobId.Contains("."))
                    {
                        var splitJobKey = dbStream.chatDownloadJobId.Split(".");
                        JobHelpers.CancelJob(splitJobKey[1], splitJobKey[0], QuartzSchedulers.PrimaryScheduler());
                    }
                    else
                    {
                        JobHelpers.CancelJob(dbStream.chatDownloadJobId, null,
                                             QuartzSchedulers.PrimaryScheduler());
                    }

                    dbStream.chatDownloading = false;
                    dbStream.duration        = getStreamDuration(streamFile);
                    GenerateThumbnailDuration(streamId);
                }
                else
                {
                    _logger.Info("Stopping VOD chat download.");
                }

                context.SaveChanges();

                // make another background job for this
                string checkVideoThumbnailsEnabled = GlobalConfig.GetGlobalConfig("generateVideoThumbnails");

                if (checkVideoThumbnailsEnabled != null && checkVideoThumbnailsEnabled == "True")
                {
                    _logger.Info("Queueing video thumbnail creation job...");
                    IJobDetail job = JobBuilder.Create <GenerateVideoThumbnailJob>()
                                     .WithIdentity("GenerateVideoThumbnail" + streamId)
                                     .UsingJobData("streamId", streamId)
                                     .UsingJobData("streamFile", streamFile)
                                     .Build();

                    var        schedulerFactory = new StdSchedulerFactory(QuartzSchedulers.PrimaryScheduler());
                    IScheduler scheduler        = schedulerFactory.GetScheduler().Result;
                    scheduler.Start();

                    ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                             .WithIdentity("GenerateVideoThumbnail" + streamId)
                                             .StartNow()
                                             .Build();

                    scheduler.ScheduleJob(job, trigger);
                    //BackgroundJob.Enqueue(() => GenerateVideoThumbnail(streamId, streamFile));
                }
            }
        }
 public void AnonymiseFeedback()
 {
     JobHelpers.RunAndLogJob(GetAndAnonymiseFeedback, nameof(AnonymiseFeedback));
 }
Example #28
0
 public void SendReminderEmails()
 {
     JobHelpers.RunAndLogJob(SendReminderEmailsAction, nameof(SendReminderEmails));
 }
Example #29
0
        public DeleteStreamReturn DeleteSingleStreamLogic(long streamId)
        {
            using (var context = new MainDataContext()) {
                var stream = context.Streams.FirstOrDefault(item => item.streamId == streamId);
                if (stream == null)
                {
                    stream = context.Streams.FirstOrDefault(item => item.vodId == streamId); // add live stream delete capabilities
                }

                if (stream != null)
                {
                    if (stream.downloadJobId != null)
                    {
                        var splitJobKey = stream.downloadJobId.Split(".");
                        try {
                            JobHelpers.CancelJob(splitJobKey[1], splitJobKey[0], QuartzSchedulers.PrimaryScheduler(), true);
                        } catch (MissingJobException e) {
                            _logger.Info(e.Message);
                        }
                    }

                    if (stream.vodId != 0)
                    {
                        try {
                            CleanUpStreamFiles(GlobalConfig.GetGlobalConfig("contentRootPath"), stream.vodId, stream.streamerId);
                        } catch (DirectoryNotFoundException) {
                            CleanUpStreamFiles(GlobalConfig.GetGlobalConfig("contentRootPath"), stream.streamId, stream.streamerId);
                        }
                    }
                    else
                    {
                        CleanUpStreamFiles(GlobalConfig.GetGlobalConfig("contentRootPath"), stream.streamId, stream.streamerId);
                    }

                    context.Remove(stream);

                    if (stream.chatDownloadJobId != null)
                    {
                        var splitJobKey = stream.chatDownloadJobId.Split(".");
                        try {
                            JobHelpers.CancelJob(splitJobKey[1], splitJobKey[0], QuartzSchedulers.PrimaryScheduler(), true);
                        } catch (MissingJobException e) {
                            _logger.Info(e.Message);
                        }
                    }

                    using (var chatContext = new ChatDataContext()) {
                        chatContext.Chats.RemoveRange(chatContext.Chats.Where(item => item.streamId == streamId));
                        chatContext.SaveChanges();
                    }
                }

                context.SaveChanges();
            }

            TwitchApiHelpers twitchApiHelpers = new TwitchApiHelpers();
            var request =
                twitchApiHelpers.TwitchRequest("https://api.twitch.tv/helix/videos?id=" + streamId, Method.GET);

            if (request.StatusCode == HttpStatusCode.OK)
            {
                return(new DeleteStreamReturn {
                    isStillAvailable = true
                });
            }

            return(new DeleteStreamReturn {
                isStillAvailable = false
            });
        }
Example #30
0
 //Remove any unverified users their addresses, UserOrgs, Org and addresses and archive to zip
 public void PurgeOrganisations()
 {
     JobHelpers.RunAndLogJob(PurgeOrganisationsAction, nameof(PurgeOrganisations));
 }