public async Task <IActionResult> PostTicketTask([FromBody] TicketTask task) { var role = StaticHelper.GetCurrentRole(User); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await db.Users.Include(x => x.Role) .Include(x => x.Departament) .FirstOrDefaultAsync(x => x.Email == User.Identity.Name); if (user == null) { return(Unauthorized()); } var taskUser = db.Users.FirstOrDefault(x => x.Id == task.UserId); if (taskUser == null) { return(BadRequest()); } var ticket = await db.Tickets.FirstOrDefaultAsync(x => x.Id == task.TicketId); if (ticket == null) { return(BadRequest()); } if ((role == "user") && !((ticket.UserId == user.Id) || ((ticket.UserId == null) && (ticket.DepartamentId == user.DepartamentId)))) { return(Forbid()); } if ((role == "superuser") && !((taskUser.DepartamentId == ticket.DepartamentId) || !(ticket.DepartamentId == user.DepartamentId))) { return(Forbid()); } task.DateCreated = DateTime.Now; task.StatusId = 1; try { db.TicketTasks.Add(task); await db.SaveChangesAsync(); } catch (DbUpdateException e) { return(BadRequest("Some of the fields are incorrect!")); } catch (Exception e) { throw e; } await StaticHelper.RaiseEvent(EventTypes.TaskAdded, task, db); return(CreatedAtAction("GetTicketTask", new { id = task.Id }, task)); }
private bool CheckTaskByUser(TicketTask task, User user) { if (((user.Role.Name == "user") && (task.UserId != user.Id)) || ((user.Role.Name == "superuser") && (task.User.DepartamentId != user.DepartamentId))) { return(false); } return(true); }
/// <summary> /// 开启定时任务 /// </summary> /// <param name="dto"></param> /// <returns></returns> private async Task StartScheduler(TicketTaskDto dto) { try { // Grab the Scheduler instance from the Factory NameValueCollection props = new NameValueCollection { { "quartz.serializer.type", "binary" } }; IScheduler scheduler = await schedulerFactory.GetScheduler(); // and start it off await scheduler.Start(); string dtoStr = JsonConvert.SerializeObject(dto); var trigger = TriggerBuilder.Create() .WithSimpleSchedule(x => x.WithIntervalInSeconds(60).RepeatForever())//每60秒执行一次 .WithIdentity(dto.UserName) .Build(); //4、创建任务 var jobDetail = JobBuilder.Create <TicketOrderJob>() .UsingJobData("taskRunNum", 0) //通过在Trigger中添加参数值 .UsingJobData("ticketTask", dtoStr) .WithIdentity(new JobKey(dto.UserName)) .Build(); //5、将触发器和任务器绑定到调度器中 await scheduler.ScheduleJob(jobDetail, trigger); } catch (SchedulerException ex) { TicketTask model = ticketTaskRepository.Get(dto.Id); model.Status = 2; ticketTaskRepository.Update(model); LogHelper.Error("启动任务失败,StartScheduler()方法出错 具体异常: " + ex.Message); } }
public static bool CheckTaskByRole(string role, TicketTask task, string email, AppDbContext db) { var user = db.Users.FirstOrDefault(x => x.Email == email); if (role == "admin") { return(true); } if (role == "user") { if (task.UserId == user.Id) { return(true); } } if (role == "superuser") { if (task.User.DepartamentId == user.DepartamentId) { return(true); } } return(false); }
public OrderOutput SubmitOrder(TicketTaskDto input) { TicketTask ticketTaskObj = mapper.Map <TicketTask>(input); ticketTaskObj.CreatedTime = DateTime.Now; ticketTaskObj.ArriveStation = input.ArriveStation.Name; ticketTaskObj.LeftStation = input.LeftStation.Name; ticketTaskObj.TrainCode = string.Join(',', input.TrainCodes.ToArray()); ticketTaskObj.Status = 0; ticketTaskObj = ticketTaskRepository.Insert(ticketTaskObj); ticketTaskObj.TrainCode = string.Join(",", input.TrainCodes.ToArray()); input.Id = ticketTaskObj.Id; StartScheduler(input); return(new OrderOutput() { Flag = true, Msg = "任务提交完成, 请耐心等待结果" }); #region taskExecute //#region Query //var client = new RestClient($"https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={input.LeftDate}&leftTicketDTO.from_station={input.LeftStation.Code}&leftTicketDTO.to_station={input.ArriveStation.Code}&purpose_codes=ADULT"); //var request = new RestRequest(Method.GET); //request.AddHeader("cache-control", "no-cache"); //request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0"); //IRestResponse response = client.Execute(request); //TicketsQueryResponse ticketsResponse = JsonConvert.DeserializeObject<TicketsQueryResponse>(response.Content); //List<TicketDto> tickets = new List<TicketDto>(); //foreach (var item in ticketsResponse.Data.Result) //{ // var props = item.Split('|'); // TicketDto ticket = new TicketDto() // { // SecretStr = props[0], // ButtonTextInfo = props[1], // Train_no = props[2], // Station_train_code = props[3], // Start_station_telecode = props[4], // End_station_telecode = props[5], // From_station_telecode = props[6], // To_station_telecode = props[7], // Start_time = props[8], // Arrive_time = props[9], // Lishi = props[10], // CanWebBuy = props[11], // Yp_info = props[12], // Start_train_data = props[13], // Train_seat_feature = props[14], // Location_code = props[15], // From_station_no = props[16], // To_station_no = props[17], // Is_support_card = props[18], // Controlled_train_flag = props[19], // Gg_num = !string.IsNullOrEmpty(props[20]) ? props[20] : "--", // Gr_num = !string.IsNullOrEmpty(props[21]) ? props[21] : "--", // Qt_num = !string.IsNullOrEmpty(props[22]) ? props[22] : "--", // Rw_num = !string.IsNullOrEmpty(props[23]) ? props[23] : "--", // Rz_num = !string.IsNullOrEmpty(props[24]) ? props[24] : "--", // Tz_num = !string.IsNullOrEmpty(props[25]) ? props[25] : "--", // Wz_num = !string.IsNullOrEmpty(props[26]) ? props[26] : "--", // Yb_num = !string.IsNullOrEmpty(props[27]) ? props[27] : "--", // Yw_num = !string.IsNullOrEmpty(props[28]) ? props[28] : "--", // Yz_num = !string.IsNullOrEmpty(props[29]) ? props[29] : "--", // Ze_num = !string.IsNullOrEmpty(props[30]) ? props[30] : "--", // Zy_num = !string.IsNullOrEmpty(props[31]) ? props[31] : "--", // Swz_num = !string.IsNullOrEmpty(props[32]) ? props[32] : "--", // Srrb_num = !string.IsNullOrEmpty(props[33]) ? props[33] : "--", // Yp_ex = props[34], // Seat_types = props[35], // Exchange_train_flag = props[36], // Houbu_train_flag = props[37], // From_station_name = ticketsResponse.Data.Map.GetValue(props[6]).ToString(), // To_station_name = ticketsResponse.Data.Map.GetValue(props[7]).ToString() // }; // if (props.Length > 38) // { // ticket.Houbu_seat_limit = props[38]; // } // tickets.Add(ticket); //} //var orderTicket = tickets.Where(c => c.Station_train_code == input.TrainCode).FirstOrDefault(); //#endregion //#region submitOrderRequest //var client_1 = new RestClient("https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest"); //var request_1 = new RestRequest(Method.POST); //request_1.AddHeader("cache-control", "no-cache"); //request_1.AddHeader("Content-Type", "application/x-www-form-urlencoded"); //request_1.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0"); //var passenger = GetPassengerDto(input.UserName); //var cookieContainer = CacheHelper.GetCache<IList<RestResponseCookie>>(input.UserName + "_loginStatus"); //if (cookieContainer != null && cookieContainer.Count > 0) //{ // cookieContainer.Add(new RestResponseCookie() // { // Name = "_jc_save_fromDate", // Value = input.LeftDate // }); // cookieContainer.Add(new RestResponseCookie() // { // Name = "_jc_save_fromStation", // Value = UnicodeHelper.String2Unicode(input.LeftStation.Name).Replace("\\", "%") + "%2C" + input.LeftStation.Code // }); // cookieContainer.Add(new RestResponseCookie() // { // Name = "_jc_save_toDate", // Value = input.LeftDate // }); // cookieContainer.Add(new RestResponseCookie() // { // Name = "_jc_save_toStation", // Value = UnicodeHelper.String2Unicode(input.ArriveStation.Name).Replace("\\", "%") + "%2C" + input.ArriveStation.Code // }); // cookieContainer.Add(new RestResponseCookie() // { // Name = "_jc_save_wfdc_flag", // Value = "dc" // }); // CacheHelper.SetCache(input.UserName+ "loginStatus", cookieContainer); // foreach (var item in cookieContainer) // { // request_1.AddParameter(item.Name, item.Value, ParameterType.Cookie); // } //} //request_1.AddParameter("application/x-www-form-urlencoded", // "secretStr=" + // orderTicket.SecretStr + // "&train_date=" + input.LeftDate + "&back_train_date=" + input.LeftDate + "&tour_flag=dc&purpose_codes=ADULT" + // "&query_from_station_name=" + input.LeftStation.Name + "&query_to_station_name=" + input.ArriveStation.Name, // ParameterType.RequestBody); //IRestResponse response_1 = client_1.Execute(request_1); //#endregion //#region https://kyfw.12306.cn/otn/confirmPassenger/initDc //var client_2 = new RestClient("https://kyfw.12306.cn/otn/confirmPassenger/initDc"); //var request_2 = new RestRequest(Method.POST); //request_2.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0"); //if (cookieContainer != null && cookieContainer.Count > 0) //{ // foreach (var item in cookieContainer) // { // request_2.AddParameter(item.Name, item.Value, ParameterType.Cookie); // } //} //IRestResponse response_2 = client_2.Execute(request_2); //int init_seatTypes_index = response_2.Content.IndexOf("init_seatTypes"); //int init_seatTypes_lastIndex = response_2.Content.IndexOf("defaultTicketTypes"); //int FormIndex = response_2.Content.IndexOf("ticketInfoForPassengerForm"); //int FormLastIndex = response_2.Content.LastIndexOf("orderRequestDTO"); //int limit_ticket_num_index = response_2.Content.LastIndexOf("init_limit_ticket_num"); //int SubmitTokenIndex = response_2.Content.IndexOf("globalRepeatSubmitToken"); //int global_lang_index = response_2.Content.IndexOf("global_lang"); //if (init_seatTypes_lastIndex < 0 || init_seatTypes_index < 0 || FormIndex < 0 || FormLastIndex<0 || limit_ticket_num_index<0 || SubmitTokenIndex<0 || global_lang_index<0) //{ // return false; //} //string init_seatTypesTemp = response_2.Content.Substring(init_seatTypes_index, init_seatTypes_lastIndex-init_seatTypes_index); //string init_seatTypesStr = init_seatTypesTemp.Substring(init_seatTypesTemp.IndexOf("=") + 1, // init_seatTypesTemp.LastIndexOf("]") - init_seatTypesTemp.IndexOf("=")); //List<Init_seatType> init_SeatTypes = JsonConvert.DeserializeObject<List<Init_seatType>>(init_seatTypesStr); //StringBuilder passengerForm = new StringBuilder(); //passengerForm.Append(response_2.Content.Substring(FormIndex, FormLastIndex - FormIndex)); //string passengerFormStr = passengerForm.ToString(); //TicketInfoForPassengerForm ticketInfoForPassengerForm = JsonConvert.DeserializeObject<TicketInfoForPassengerForm> // (passengerFormStr.Substring(passengerFormStr.IndexOf("=") + 1, // passengerFormStr.LastIndexOf("}") - passengerFormStr.IndexOf("="))); //string OrderRequestDTOStr = response_2.Content.Substring(FormLastIndex, limit_ticket_num_index - FormLastIndex); //OrderQuestDto orderQuestDTO = JsonConvert.DeserializeObject<OrderQuestDto>( // OrderRequestDTOStr.Substring(OrderRequestDTOStr.IndexOf("=") + 1, // OrderRequestDTOStr.LastIndexOf("}") - OrderRequestDTOStr.IndexOf("="))); //#endregion //#region GetPassengerDto //var client_3 = new RestClient("https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs"); //var request_3 = new RestRequest(Method.POST); //request_3.AddHeader("cache-control", "no-cache"); //request_3.AddHeader("Host", "kyfw.12306.cn"); //request_3.AddHeader("Origin", "https://kyfw.12306.cn"); //request_3.AddHeader("Referer", "https://kyfw.12306.cn/otn/confirmPassenger/initDc"); //request_3.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0"); //if (cookieContainer != null && cookieContainer.Count > 0) //{ // foreach (var item in cookieContainer) // { // request_3.AddParameter(item.Name, item.Value, ParameterType.Cookie); // } //} //IRestResponse response_3 = client_3.Execute(request_3); //CommonResponse<PassengerData> passengerDTOResponse = JsonConvert.DeserializeObject<CommonResponse<PassengerData>>(response_3.Content); //#endregion //#region checkOrderInfo //var client_4 = new RestClient("https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo"); //var request_4 = new RestRequest(Method.POST); //request_4.AddHeader("Cache-Control", "no-cache"); //request_4.AddHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); //request_4.AddHeader("Connection", "true"); //request_4.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0"); //if (cookieContainer != null && cookieContainer.Count > 0) //{ // foreach (var item in cookieContainer) // { // request_4.AddParameter(item.Name, item.Value, ParameterType.Cookie); // } //} //request_4.AddParameter("application/x-www-form-urlencoded; charset=UTF-8", // $"cancel_flag=2&bed_level_order_num=000000000000000000000000000000&passengerTicketStr={input.SeatType},0,1,{passengerDTOResponse.Data.Normal_passengers[0].Passenger_name},1,{passengerDTOResponse.Data.Normal_passengers[0].Passenger_id_no},{passengerDTOResponse.Data.Normal_passengers[0].Mobile_no},N&oldPassengerStr={passengerDTOResponse.Data.Normal_passengers[0].Passenger_name},1,{passengerDTOResponse.Data.Normal_passengers[0].Passenger_id_no},1_&tour_flag=dc&randCode=&whatsSelect=1", ParameterType.RequestBody); //IRestResponse response_4 = client_4.Execute(request_4); //CommonResponse<CheckOrderResponseData> checkOrderResponse = JsonConvert.DeserializeObject<CommonResponse<CheckOrderResponseData>>(response_4.Content); //#endregion //#region getQueueCount //var client_5 = new RestClient("https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount"); //var request_5 = new RestRequest(Method.POST); //request_5.AddHeader("Cache-Control", "no-cache"); //request_5.AddHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); //request_5.AddHeader("Connection", "true"); //request_5.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0"); //if (cookieContainer != null && cookieContainer.Count > 0) //{ // foreach (var item in cookieContainer) // { // request_5.AddParameter(item.Name, item.Value, ParameterType.Cookie); // } //} //string dateStr = input.LeftDateJs.Replace(":", "%3A").Replace("+", "%2B"); //// "Tue%20Apr%2030%202019%2000%3A00%3A00%20GMT%2B0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)" //request_5.AddParameter("application/x-www-form-urlencoded; charset=UTF-8 ", // "train_date=" + dateStr + // "&train_no=" + orderQuestDTO.Train_no + // "&stationTrainCode=" + orderQuestDTO.Station_train_code + // "&seatType=" + input.SeatType + // "&fromStationTelecode=" + orderQuestDTO.From_station_telecode // + "&toStationTelecode=" + orderQuestDTO.To_station_telecode + // "&leftTicket=" + ticketInfoForPassengerForm.QueryLeftTicketRequestDTO.YpInfoDetail + // "&purpose_codes=00&train_location=" + ticketInfoForPassengerForm.Train_location + "&undefined=", ParameterType.RequestBody); //IRestResponse response_5 = client_5.Execute(request_5); //CommonResponse<QueueCountResponseData> queueCountResponseData = JsonConvert.DeserializeObject<CommonResponse<QueueCountResponseData>> // (response_5.Content); //#endregion //#region confirmSingleForQueue //var client_6 = new RestClient("https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue"); //var request_6 = new RestRequest(Method.POST); //request_6.AddHeader("Cache-Control", "no-cache"); //request_6.AddHeader("Connection", "true"); //request_6.AddHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); //request_6.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0"); //if (cookieContainer.Count > 0) //{ // foreach (var item in cookieContainer) // { // request_6.AddParameter(item.Name, item.Value, ParameterType.Cookie); // } //} //string passengerTicketStrEncode = Uri.EscapeDataString($"{input.SeatType},0,1,{passengerDTOResponse.Data.Normal_passengers[0].Passenger_name},1,{passengerDTOResponse.Data.Normal_passengers[0].Passenger_id_no},{passengerDTOResponse.Data.Normal_passengers[0].Mobile_no},N"); //string oldPassengerStrEncode = Uri.EscapeDataString($"{passengerDTOResponse.Data.Normal_passengers[0].Passenger_name},1,{passengerDTOResponse.Data.Normal_passengers[0].Passenger_id_no},1_"); //request_6.AddParameter("undefined", //$"passengerTicketStr={input.SeatType},0,1,{passengerDTOResponse.Data.Normal_passengers[0].Passenger_name},1,{passengerDTOResponse.Data.Normal_passengers[0].Passenger_id_no},{passengerDTOResponse.Data.Normal_passengers[0].Mobile_no},N" + //$"&oldPassengerStr={passengerDTOResponse.Data.Normal_passengers[0].Passenger_name},1,{passengerDTOResponse.Data.Normal_passengers[0].Passenger_id_no},1_" + //$"&randCode=&purpose_codes=00&" + //$"key_check_isChange={ticketInfoForPassengerForm.Key_check_isChange}" + //$"&leftTicketStr={ticketInfoForPassengerForm.LeftTicketStr}&train_location={ticketInfoForPassengerForm.Train_location}" + //$"&choose_seats=&seatDetailType=000&whatsSelect=1&roomType=00&dwAll=N", ParameterType.RequestBody); //IRestResponse response_6 = client_6.Execute(request_6); //CommonResponse<ConfirmSingleResponseData> confirmSingleForQueueResponse = JsonConvert.DeserializeObject<CommonResponse<ConfirmSingleResponseData>>(response_6.Content); //if (confirmSingleForQueueResponse.Data.SubmitStatus) //{ // EmailHelper.Send("*****@*****.**", "订票成功", "恭喜订票成功,登录你的12306完成支付"); //} //#endregion #endregion }