Пример #1
0
 public void OnDutyChange(bool state)
 {
     if (state && JobHandler.GetPlayerJob() == JobType.Police)
     {
         Game.PlayerPed.Armor = 100;
     }
 }
Пример #2
0
        private void OnDeleteVehicle(bool impound)
        {
            var closeVeh = GTAHelpers.GetClosestVehicle();

            if (closeVeh != null)
            {
                if (closeVeh.HasDecor("Vehicle.ID") /*&& JobHandler.OnDutyAsJob(JobType.Police)*/)
                {
                    var vehId = closeVeh.GetDecor <int>("Vehicle.ID");
                    if (vehId < 1000000 && JobHandler.OnDutyAsJob(JobType.Police))
                    {
                        if (impound)
                        {
                            Client.TriggerServerEvent("Vehicle.ImpoundVehicle", vehId);
                        }
                        closeVeh.Delete();
                    }
                    else if (vehId > 1000000)
                    {
                        closeVeh.Delete();
                    }
                }
                else
                {
                    closeVeh.Delete();
                }
            }
        }
Пример #3
0
        static async Task Main(string[] args)
        {
            // Eventually force the use of a json file
            if (args.Length < 4)
            {
                Console.WriteLine($"Usage is:{Environment.NewLine}FileClassifier.JobManager.Uploader <name> <model type> <path to data> <server url>");

                return;
            }

            if (!Enum.TryParse<ModelType>(args[1], true, out _))
            {
                Console.WriteLine($"Invalid Model Type option ({args[1]})");

                return;
            }

            var jobHandler = new JobHandler(args[3]);

            var result = await jobHandler.AddNewJobAsync(new Jobs
            {
                ModelType = args[1],
                TrainingDataPath = args[2],
                Name = args[0]
            });

            Console.WriteLine(result ? "Job successfully uploaded" : "Failed to upload job");
        }
Пример #4
0
        private void OnBillCommand(Command cmd)
        {
            var targetUser = Sessions.GetPlayer(cmd.GetArgAs(0, 0));
            var billAmount = cmd.GetArgAs(1, 0);

            cmd.Args.RemoveAt(0); cmd.Args.RemoveAt(0);
            var billReason = string.Join(" ", cmd.Args);

            if (targetUser == null || billAmount < 0)
            {
                return;
            }

            Log.ToClient("[Bill]", $"You have been billed ${billAmount} for {billReason}", ConstantColours.Housing, targetUser.Source);
            JobHandler.SendJobAlert(JobType.Police, "[Bill]", $"{targetUser.GetCharacterName()} has been billed ${billAmount} for {billReason}", ConstantColours.Housing);

            targetUser.SetGlobalData("Character.Bill", targetUser.GetGlobalData("Character.Bill", 0) + billAmount);

            MySQL.execute("INSERT INTO player_tickets (`reason`, `amount`, `issuing_officer`, `game_character_id`) VALUES (@reason, @amount, @officer, @charid)", new Dictionary <string, dynamic>
            {
                { "@reason", billReason },
                { "@amount", billAmount },
                { "@officer", cmd.Session.GetCharacterName() },
                { "@charid", targetUser./*GetCharId()*/ CharId }
            }, new Action <int>(rows =>
            {
                Log.Verbose($"Inserted a new bill entry for character {targetUser.GetCharacterName()}");
            }));
        }
Пример #5
0
 private void HandleHalfAutomaticAirlock(TimeSpan timer)
 {
     if (state_ == State.OneSideOpen)
     {
         // on side of the airlock is open. Close all other sides
         closeAllDoors(activeDoor_);
         if (allDoorsClosed(activeDoor_))
         {
             // all doors are closed. Deactivate all of them
             deactivateAllOtherDoors(activeDoor_);
             state_   = State.WaitToClose;
             waitFor_ = timer + config_.delay_;
         }
     }
     else if (state_ == State.WaitToClose)
     {
         if (timer >= waitFor_)
         {
             if (!activeDoor_.IsClosed)
             {
                 activeDoor_.Close();
             }
             else if (activeDoor_.IsClosed)
             {
                 activateAllDoors();
                 job_   = HandleInteraction;
                 state_ = State.Idle;
             }
         }
     }
 }
Пример #6
0
        public async Task <IHttpActionResult> CreateJobHandler(JobHandler entity)
        {
            userId = User.Identity.GetUserId();

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Validate the
            var existingJobHandler = _repo.FindJobHandler(entity.JobTrackerId, entity.JobSplitId, userId, entity.Remark);

            if (existingJobHandler != null)
            {
                var message = string.Format("Issuance exceed Job Quantity");
                var err     = new HttpError(message);
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, err)));
            }

            var newEntity = entity;

            context.JobHandlers.Add(newEntity);
            await context.SaveChangesAsync();

            return(Ok <JobHandler>(newEntity));
        }
        private async void doEmergencyCall(Command cmd, string emergencyNumber)
        {
            var message = string.Join(" ", cmd.Args);

            Log.ToClient($"To {emergencyNumber}", message, ConstantColours.Phone, cmd.Player);
            JobHandler.SendJobAlert(JobType.EMS | JobType.Police, $"{emergencyNumber} | {await cmd.Session.GetLocation()} | #{cmd.Source}", message, ConstantColours.Phone);
            Messages.SendProximityMessage(cmd.Session, "[On phone]", message, ConstantColours.Yellow, 25.0f, false);

            if (emergencyNumber == "911")
            {
                JobHandler.GetPlayersOnJob(JobType.EMS | JobType.Police).ForEach(o =>
                {
                    o.TriggerEvent("Blip.CreateEmergencyBlip", cmd.Source);
                    o.TriggerEvent("Sound.PlaySoundFrontend", "Event_Start_Text", "GTAO_FM_Events_Soundset");
                });
            }

            CADAlerts.CurrentAlerts.Add(new CADAlertData
            {
                AlertType     = emergencyNumber,
                AlertCaller   = $"{cmd.Session.GetGlobalData("Character.FirstName", "")} {cmd.Session.GetGlobalData("Character.LastName", "")}",
                AlertLocation = await cmd.Session.GetLocation(),
                AlertMessage  = message,
            });
        }
Пример #8
0
        private void OnPayTicket(Command cmd)
        {
            var ticketAmount = cmd.Session.GetServerData("Character.Ticket.Amount", 0);

            cmd.Session.SetServerData("Character.Ticket.HasPaid", true);
            cmd.Session.SetServerData("Character.Ticket.Complete", true);

            if (Server.Get <PaymentHandler>().CanPayForItem(cmd.Session, ticketAmount, 1, (int)PaymentType.Debit))
            {
                Log.ToClient("[Info]", $"You paid the ticket", ConstantColours.Info, cmd.Player);
                JobHandler.SendJobAlert(JobType.Police, "[Info]", $"{cmd.Session.GetCharacterName()} paid the ticket", ConstantColours.Info);
                Server.Get <PaymentHandler>().PayForItem(cmd.Session, ticketAmount, "paying ticket", (int)PaymentType.Debit);

                MySQL.execute("INSERT INTO player_tickets (`reason`, `amount`, `issuing_officer`, `game_character_id`) VALUES (@reason, @amount, @officer, @charid)", new Dictionary <string, dynamic>
                {
                    { "@reason", cmd.Session.GetServerData("Character.Ticket.Reason", "") },
                    { "@amount", ticketAmount },
                    { "@officer", cmd.Session.GetServerData("Character.Ticket.IssuingOfficer", "") },
                    { "@charid", cmd.Session./*GetCharId()*/ CharId }
                }, new Action <int>(rows =>
                {
                    Log.Verbose($"Inserted a new ticket entry for character {cmd.Session.GetCharacterName()}");
                }));
            }
            else
            {
                Log.ToClient("[Info]", $"You cannot pay for this ticket", ConstantColours.Info, cmd.Player);
                JobHandler.SendJobAlert(JobType.Police, "[Info]", $"{cmd.Session.GetCharacterName()} cannot afford to pay the ticket", ConstantColours.Info);
            }
        }
Пример #9
0
        public async void StartJob()
        {
            currentTowTruck = await CreateJobVehicle(VehicleHash.Flatbed, towDropoffPoint, 0.0f);

            JobHandler.SetPlayerJob(JobType.Tow);
            JobHandler.SetDutyState(true);
            Client.Get <InteractionUI>().RegisterInteractionMenuItem(returnVehicleItem, inRangeOfTowPickup, 500);
        }
 public bool TryGetHandlerByQueueId(string queueId, out JobHandler handler)
 {
     if (_handlers.TryGetValue(queueId, out handler))
     {
         return(true);
     }
     return(false);
 }
Пример #11
0
 public void Open(JobHandler pJob)
 {
     GetComponent <AutoTransferItemCapability>().PrepareAutoTransferTarget();
     UpdateSubmitButton();
     job = pJob;
     UpdateJobDetails();
     UpdateItemSubmissionInfoText();
 }
Пример #12
0
        protected internal virtual JobHandler resolveJobHandler()
        {
            JobHandler jobHandler = Context.ProcessEngineConfiguration.JobHandlers[jobHandlerType];

            ensureNotNull("Cannot find job handler '" + jobHandlerType + "' from job '" + this + "'", "jobHandler", jobHandler);

            return(jobHandler);
        }
Пример #13
0
        private void OnRefuseTicket(Command cmd)
        {
            cmd.Session.SetServerData("Character.Ticket.HasPaid", true);
            cmd.Session.SetServerData("Character.Ticket.Complete", true);

            Log.ToClient("[Info]", $"You refused to pay the ticket", ConstantColours.Info, cmd.Session.Source);
            JobHandler.SendJobAlert(JobType.Police, "[Info]", $"{cmd.Session.GetCharacterName()} refused to pay the ticket", ConstantColours.Info);
        }
Пример #14
0
 private void HandleManualllyAirlock(TimeSpan timer)
 {
     // there is no need to do something. Al actions are done by
     // the user himself
     job_        = HandleInteraction;
     state_      = State.Idle;
     activeDoor_ = null;
 }
Пример #15
0
 public void ScheduleJobsTest()
 {
     using (JobHandler jobHandler = new JobHandler())
     {
         jobHandler.ScheduleJobs();
         IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
         Assert.IsTrue(scheduler.CheckExists(new JobKey("Delete_Old_Job", "Cleanup")));
     }
 }
 public override void EndJob()
 {
     base.EndJob();
     CurrentDestinationBlip?.Delete();
     CurrentDestinationBlip = null;
     JobHandler.SetDutyState(false);
     JobHandler.SetPlayerJob(JobType.Civillian);
     Client.DeregisterTickHandler(JobTick);
 }
Пример #17
0
 public void EndJob()
 {
     currentTowTruck?.Delete();
     currentTowTruck = null;
     currentJobVehicle?.AttachedBlips.ToList().ForEach(o => o.Delete());
     currentJobVehicle = null;
     JobHandler.SetDutyState(false);
     JobHandler.SetPlayerJob(JobType.Civillian);
     RemoveJobVehicle();
 }
        /// <summary>
        /// Submits the request to the JobHandler and asynchronously awaits the result.
        /// </summary>
        /// <param name="data">The input data to be processd.</param>
        /// <returns></returns>
        public async Task <TOutput> SubmitRequest(TInput data)
        {
            var taggedData = TagInputData(data);
            var job        = CreateJob(taggedData);

            Jobs.TryAdd(job.Key, job.Value);
            await JobHandler.SendAsync(taggedData);

            return(await job.Value.Task);
        }
Пример #19
0
 internal JobWorker(Gateway.GatewayClient client, ActivateJobsRequest request, TimeSpan pollInterval,
                    IJobClient jobClient, JobHandler jobHandler)
 {
     source            = new CancellationTokenSource();
     this.client       = client;
     activeRequest     = request;
     this.pollInterval = pollInterval;
     this.jobClient    = jobClient;
     this.jobHandler   = jobHandler;
 }
Пример #20
0
        public void TestSetup()
        {
            state = new SchedulerState(Task.CompletedTask, CancellationToken.None);

            job = Substitute.For <IStreamJob>();

            launcher = Substitute.For <IJobLauncher>();

            handler = new JobHandler(launcher);
        }
        public async Task <IHttpActionResult> UpdateJobHandleCEAnalysis(int id, JobSplitCEAnalysis entity)
        {
            string userId = User.Identity.GetUserId();

            var existingEntity = await context.JobSplitCEAnalysis.FindAsync(entity.Id);

            if (entity == null)
            {
                return(NotFound());
            }
            if (id != entity.Id)
            {
                return(BadRequest(ModelState));
            }
            if (entity == null)
            {
                var       message = string.Format("Entry is empty");
                HttpError err     = new HttpError(message);
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, err)));
            }

            if (existingEntity != null && context.Entry(existingEntity).State != EntityState.Detached)
            {
                context.Entry(existingEntity).State = EntityState.Detached;
            }

            var local = context.Set <JobSplitCEAnalysis>().Local.FirstOrDefault(f => f.Id == entity.Id);

            if (local != null)
            {
                context.Entry(local).State = EntityState.Detached;
            }

            existingEntity.IsJobHandleByCE = true;


            context.Entry(existingEntity).State = EntityState.Modified;
            await context.SaveChangesAsync();


            var jobHandler = new JobHandler()
            {
                JobTrackerId = existingEntity.JobTrackerId,
                JobSplitId   = existingEntity.JobSplitId,
                HandlerId    = userId,
                CreatedOn    = DateTime.Now,
                ModifiedOn   = DateTime.Now,
                Remark       = "CE"
            };

            //Create JobHandle
            var tx = CreateJobHandler(jobHandler);

            return(Ok());
        }
Пример #22
0
        private void OnTaxiMessage(Command cmd)
        {
            var message = string.Join(" ", cmd.Args);

            Log.ToClient("[To taxi]", message, ConstantColours.Yellow, cmd.Player);
            JobHandler.SendJobAlert(JobType.Taxi, $"[Taxi request #{cmd.Source}]", message, ConstantColours.Yellow);
            JobHandler.GetPlayersOnJob(JobType.Taxi).ForEach(o =>
            {
                o.TriggerEvent("Blip.CreateJobBlip", $"Taxi call #{cmd.Source}", cmd.Source, 66);
            });
        }
Пример #23
0
 internal JobWorker(JobWorkerBuilder builder)
 {
     source         = new CancellationTokenSource();
     activator      = new JobActivator(builder.Client);
     activeRequest  = builder.Request;
     maxJobsActive  = activeRequest.MaxJobsToActivate;
     pollInterval   = builder.PollInterval();
     jobClient      = new JobClientWrapper(builder.JobClient);
     jobHandler     = builder.Handler();
     autoCompletion = builder.AutoCompletionEnabled();
 }
Пример #24
0
            private void HandleInit(TimeSpan timer)
            {
                closeAllDoors();

                if (allDoorsClosed())
                {
                    job_        = HandleInteraction;
                    activeDoor_ = null;
                    state_      = State.Idle;
                }
            }
Пример #25
0
 public void OnDutyChangeState(Session.Session playerSession)
 {
     // draw marker if on duty remove if not
     if (JobHandler.OnDutyAs(playerSession, JobType.EMS | JobType.Police))
     {
         resupplyLocations.ForEach(o =>
         {
             playerSession.TriggerEvent("Markers.AddMarker", o.ToArray());
         });
     }
 }
Пример #26
0
        public ResponseModel <string> AddOrUpdateCycleJob(string jobId)
        {
            if (!string.IsNullOrEmpty(jobId))
            {
                throw new Exception("dfgfdgfd");
            }
            Expression <Action> expression = () => JobHandler.Invoke(jobId);

            CycleJob.AddOrUpdate(jobId, expression, CycleCronType.Minute());
            return(string.Empty.ToResponseModel());
        }
 private void _createWorker(String jobType, JobHandler handleJob)
 {
     _client.NewWorker()
     .JobType(jobType)
     .Handler(handleJob)
     .MaxJobsActive(5)
     .Name(jobType)
     .PollInterval(TimeSpan.FromSeconds(50))
     .PollingTimeout(TimeSpan.FromSeconds(50))
     .Timeout(TimeSpan.FromSeconds(10))
     .Open();
 }
Пример #28
0
        private void RegisterQueueForHandler(JobHandler handler)
        {
            handler.ProcessingCompleted += OnProcessingCompleted;
            handler.ProcessingFailed    += OnProcessingFailed;

            foreach (var strategy in handler.GetRedirectStrategies().Where(h => h != null))
            {
                AddRedirectStrategy(handler, strategy);
            }

            _jobQueueFactory.Create(handler.Configuration).JobReceived += Listener_JobReceived;
        }
Пример #29
0
        private void OnSeizeVehItems(Command cmd)
        {
            if (JobHandler.OnDutyAsJob(JobType.Police))
            {
                var closeVeh = GTAHelpers.GetClosestVehicle(3.0f, o => o.HasDecor("Vehicle.ID"));

                if (closeVeh != null)
                {
                    Client.TriggerServerEvent("Items.SeizeVehicleItems", closeVeh.GetDecor <int>("Vehicle.ID"), string.Join(" ", cmd.Args));
                }
            }
        }
Пример #30
0
 internal JobWorker(Gateway.GatewayClient client, ActivateJobsRequest request, TimeSpan pollInterval,
                    IJobClient jobClient, JobHandler jobHandler)
 {
     this.source        = new CancellationTokenSource();
     this.client        = client;
     this.activator     = new JobActivator(client);
     this.activeRequest = request;
     this.maxJobsActive = request.MaxJobsToActivate;
     this.pollInterval  = pollInterval;
     this.jobClient     = jobClient;
     this.jobHandler    = jobHandler;
 }
Пример #31
0
        public void Begin()
        {
            try
            {
                log.Debug("Starting processoring");
                config = ConfigurationManager.AppSettings;
                host = ConfigurationManager.AppSettings["bindhost"];
                port = int.Parse(ConfigurationManager.AppSettings["bindport"]);
                stats = new Stats();
                //BT = new BatchTranscoder();
                //LS = new ListenServer(host, port, BT);
                presets = new Presets();
                Dictionary<string, IHttpRequestHandler> handlers = new Dictionary<string, IHttpRequestHandler>();

                jobs = new ConcurrentDictionary<string, TranscodeJob>();

                expireCancelToken = new CancellationTokenSource();
                TaskExecutorFactory.Begin(ExpireJobs, 300000, 100, Timeout.Infinite, -1, expireCancelToken.Token);

                transcodingPool = new Sprite.ThreadPool(int.Parse(ConfigurationManager.AppSettings["maxtasks"]), Sprite.WaitStrategy.MODERATE);

                Directory.CreateDirectory(FFRest.config["file-root"] + Path.DirectorySeparatorChar + FFRest.config["thumb-destination"]);
                Directory.CreateDirectory(FFRest.config["file-root"] + Path.DirectorySeparatorChar + FFRest.config["video-destination"]);

                // Initialize all the endpoint handlers
                var jobHandler = new JobHandler(jobs, transcodingPool);
                var presetHandler = new PresetHandler(presets);
                var thumbHandler = new ThumbnailHandler();
                var adaptiveHandler = new AdaptiveHandler(jobHandler.Jobs);
                var metaHandler = new MetaHandler();
                var videoHandler = new VideoHandler();
                handlers.Add("/stats", stats);
                handlers.Add("/jobs", jobHandler);
                handlers.Add("/presets", presetHandler);
                handlers.Add("/thumbs", thumbHandler);
                handlers.Add("/videos", videoHandler);
                handlers.Add("/playlist", adaptiveHandler);
                handlers.Add("/metadata", metaHandler);
                Server server = new Server(host, port, handlers);

                //server = new Httpd(5120, handlers);
                thread = new Thread(new ThreadStart(server.Listen));
                thread.Start();
                transcodingPool.StartPool();
            }
            catch (Exception ex)
            {
                log.Fatal("A fatal exception has occured", ex);
            }
        }
Пример #32
0
    // Use this for initialization
    void Start()
    {
        _driver = new PLCDriver ();

        IP=Settings.Instance.GetValue ("PLC", "IP",IP);
        //int.TryParse (Settings.Instance.GetValue ("PLC", "Port",Port.ToString()), out Port);

        _driver.Connect (IP, Port);

        _jobHandler = new JobHandler (this);
        _jobHandler.Start ();
    }