Exemple #1
0
        internal async Task <bool> _AddCacheRequest_Internal(NicoVideoCacheRequest req)
        {
            var nicoVideo = await MediaManager.GetNicoVideoAsync(req.RawVideoId);

            var div = nicoVideo.GetDividedQualityNicoVideo(req.Quality);

            if (div.IsCached)
            {
                if (req.IsRequireForceUpdate)
                {
                    Debug.WriteLine($"{req.RawVideoId}<{req.Quality}> is already cached, but enable force update .(re-download)");
                    await RemoveCacheRequest(req.RawVideoId, req.Quality);
                }
                else
                {
                    Debug.WriteLine($"{req.RawVideoId}<{req.Quality}> is already cached. (skip download)");
                    Requested?.Invoke(this, req);
                    DownloadCompleted?.Invoke(this, req, div.CacheFilePath);
                    return(false);
                }
            }

            using (var pendingVideoLockReleaser = await _CacheDownloadPendingVideosLock.LockAsync())
            {
                _CacheDownloadPendingVideos.Add(req);
            }

            Requested?.Invoke(this, req);

            return(true);
        }
Exemple #2
0
        public async Task RequestCache(NicoVideoCacheRequest req)
        {
            var requests = await GetCacheRequest(req.RawVideoId);

            var already = requests.FirstOrDefault(x => x.RawVideoId == req.RawVideoId && x.Quality == req.Quality);

            if (already != null)
            {
                req.RequestAt = already.RequestAt;
            }
            else
            {
                using (var releaser2 = await _CacheRequestProcessingLock.LockAsync())
                {
                    // 画質指定が無い場合はデフォルトのキャッシュ画質を選択
                    if (req.Quality == NicoVideoQuality.Unknown)
                    {
                        req.Quality = _HohoemaApp.UserSettings.CacheSettings.DefaultCacheQuality;
                    }

                    _CacheDownloadPendingVideos.Add(req);

                    Requested?.Invoke(this, req);
                    VideoCacheStateChanged?.Invoke(this, new VideoCacheStateChangedEventArgs()
                    {
                        CacheState = NicoVideoCacheState.Pending,
                        Request    = req
                    });
                }
            }

            await SaveDownloadRequestItems();
        }
Exemple #3
0
        internal void OnRequestCompleted(Servers.RequestAgent agent)
        {
            this.Statistics.Add(agent.Code);
            EventRequestCompletedArgs e = new EventRequestCompletedArgs(agent.Request, agent.Response, agent.Code);

            Requested?.Invoke(this, e);
        }
        // return true if added or changed state, false if already known
        public static bool AddRequested(int PlanetId, int NetId, int NodeId, bool Charging, bool eventFromOtherPlayer)
        {
            if (RequestsSent.TryGetValue(PlanetId, out var requests))
            {
                for (int i = 0; i < requests.Count; i++)
                {
                    if (requests[i].NetId == NetId && requests[i].NodeId == NodeId)
                    {
                        if (requests[i].Charging != Charging)
                        {
                            if (Charging == false)
                            {
                                PlanetFactory factory = GameMain.galaxy.PlanetById(PlanetId)?.factory;

                                if (factory != null && factory.powerSystem != null)
                                {
                                    int   baseDemand = factory.powerSystem.nodePool[NodeId].workEnergyPerTick - factory.powerSystem.nodePool[NodeId].idleEnergyPerTick;
                                    float mult       = factory.powerSystem.networkServes[NetId];

                                    PlayerChargeAmount -= (int)(mult * (float)baseDemand);
                                    ChargerCount--;

                                    if (PlayerChargeAmount < 0)
                                    {
                                        PlayerChargeAmount = 0;
                                    }
                                    if (ChargerCount == 0)
                                    {
                                        PlayerChargeAmount = 0;
                                    }
                                }
                            }
                            if (!eventFromOtherPlayer)
                            {
                                requests[i].Charging = Charging;
                            }
                            return(true);
                        }
                        return(false);
                    }
                }

                Requested req = new Requested();
                req.NetId  = NetId;
                req.NodeId = NodeId;

                requests.Add(req);

                return(true);
            }

            List <Requested> list = new List <Requested>();
            Requested        req2 = new Requested();

            req2.NetId  = NetId;
            req2.NodeId = NodeId;

            list.Add(req2);
            return(RequestsSent.TryAdd(PlanetId, list));
        }
Exemple #5
0
    public T Resolve()
    {
        var args = new ResultEventArgs();

        Requested?.Invoke(this, args);
        return((T)args.Result !);
    }
Exemple #6
0
 public void Clear()
 {
     UtcEarliestEntry = DateTime.MaxValue;
     Found.Clear();
     Unavailable.Clear();
     Requested.Clear();
 }
Exemple #7
0
        /// <summary>
        /// Requests the instance which instantiated this object to take an action.
        /// </summary>
        /// <param name="args">Arguments to that instance</param>
        /// <returns>Response from that instance</returns>
        /// <remarks>This method is to be called by an instance other than that instance.</remarks>
        public object Request(string[] args)
        {
            var e = new StartupRequestEventArgs(args);

            Requested?.Invoke(this, e);
            return(e.Response);
        }
Exemple #8
0
 public void Raise(string title = null, IActionSheetButton cancel = null, IActionSheetButton destruction = null, params IActionSheetButton[] buttons)
 {
     Requested?.Invoke(this, new DisplayActionSheetRequestEventArgs
     {
         Title              = title,
         Cancel             = cancel,
         Destruction        = destruction,
         ActionSheetButtons = buttons
     });
 }
Exemple #9
0
 public void Raise(string title = null, string message = null, IAlertButton accept = null, IAlertButton cancel = null)
 {
     Requested?.Invoke(this, new DisplayAlertRequestEventArgs
     {
         Title   = title,
         Message = message,
         Accept  = accept,
         Cancel  = cancel
     });
 }
Exemple #10
0
        public override object Clone()
        {
            ServiceProvider provider = new ServiceProvider();

            if (null != Requested)
            {
                provider.Requested = Requested.Clone() as ControlTcpRequestEventHandler;
            }

            return(provider);
        }
Exemple #11
0
 public void CancelFriendshipRequest(FriendModel user, [CanBeNull] Action <FriendModel> onSuccess = null, [CanBeNull] Action <Error> onError = null)
 {
     if (!Requested.Contains(user))
     {
         RaiseOnError($"Can not cancel friendship request to = {user.Nickname}. This user doesn't have a friend request.", onError);
     }
     else
     {
         SdkFriendsLogic.Instance.CancelFriendshipRequest(user, u =>
         {
             RemoveUserFromMemory(user);
             onSuccess?.Invoke(u);
         }, onError);
     }
 }
            public override bool Equals(object obj)
            {
                if (obj == null)
                {
                    return(false);
                }

                var map = obj as ConnectionMap;

                if (map == null)
                {
                    return(false);
                }

                return(Requested.Equals(map.Requested));
            }
Exemple #13
0
 protected virtual Task ProcessRequest()
 {
     Requested?.Invoke(this);
     if (Handled)
     {
         return(AsyncHelper.CompletedTask);
     }
     if (server is IHttpRequestAsyncHandler asyncServer)
     {
         return(asyncServer.HandleRequestAsync(this));
     }
     else
     {
         return(Task.Run(() => server.HandleRequest(this)));
     }
 }
        public void Booked()
        {
            if (Requested == null)
            {
                throw new ArgumentNullException("Requested");
            }

            if (Requestee == null)
            {
                throw new ArgumentNullException("Requestee");
            }

            var notification = Notification.AppointmentCreated(this);

            Requested.Notify(notification);
            Requestee.Notify(notification);
        }
        public void Cancel()
        {
            if (Requested == null)
            {
                throw new ArgumentNullException("Requested");
            }

            if (Requestee == null)
            {
                throw new ArgumentNullException("Requestee");
            }

            IsCanceled = true;

            var notification = Notification.ApppointmentCanceled(this);

            Requested.Notify(notification);
            Requestee.Notify(notification);
        }
Exemple #16
0
        public FriendModel GetUserById(string userId)
        {
            Func <FriendModel, bool> predicate = user => user.Id.Equals(userId);
            var result = Friends.FirstOrDefault(predicate);

            if (result == null)
            {
                result = Pending.FirstOrDefault(predicate);
            }
            if (result == null)
            {
                result = Blocked.FirstOrDefault(predicate);
            }
            if (result == null)
            {
                result = Requested.FirstOrDefault(predicate);
            }

            return(result);
        }
Exemple #17
0
        public async void OnMessage(object message)
        {
            var qa = this.FindQuestionAndAnswer(message?.ToString());

            if (qa != null)
            {
                if (qa.IsQuestioner == false)
                {
                    if (qa.IsAnswered)
                    {
                        await this.Answer(qa);//已答复的消息,自动响应
                    }
                    else if (qa.IsAnswering == false)
                    {
                        Requested?.Invoke(this, qa);
                    }
                }
            }

            RefreshQA();
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            Requested.Add(new CommandKey(ShiftState.None, Keys.End, ExecEndKey));
            Requested.Add(new CommandKey(ShiftState.None, Keys.F3, ExecF3Key));
            Requested.Add(new CommandKey(ShiftState.None, Keys.F4, ExecF4Key));
            Requested.Add(new CommandKey(ShiftState.None, Keys.F10, kButton1));
            Requested.Add(new CommandKey(ShiftState.None, Keys.F2, kButton2));
            Requested.Add(new CommandKey(ShiftState.Control, Keys.F12, kButton3));

            dateControl1.DateValue     = DateTime.Now;
            maskedControl1.MaskedValue = "23077955909";
            //longMaskedControl1.Int64MValue = 0;
            nullableIntegerMaskedControl1.NilInt32MValue = null;

            textControl1.KControlValidateEvent += new KControlValidateEventHandler(textControl1_KControlValidateEvent);
            textControl1.KControlLeaveEvent    += new KControlLeaveEventHandler(textControl1_KControlLeaveEvent);

            comboControl1.ComboLoadEvent        += new ComboControlLoadEventHandler(comboControl1_ComboLoadEvent);
            comboControl1.KControlValidateEvent += new KControlValidateEventHandler(comboControl1_KControlValidateEvent);
            comboControl1.KControlLeaveEvent    += new KControlLeaveEventHandler(comboControl1_KControlLeaveEvent);

            dateControl1.KControlValidateEvent += new KControlValidateEventHandler(dateControl1_KControlValidateEvent);
            dateControl1.KControlLeaveEvent    += new KControlLeaveEventHandler(dateControl1_KControlLeaveEvent);

            comboControl1.InitDataSource(); // (List<IComboItem>)source;

            bindingTest           = new BindingTest("Graciela", new DateTime(1950, 04, 24), 26021722966);
            bindingTest.ComboItem = source[2];

            bindingSourceList.Add(bindingTest);
            // bindingSourceList.Add( comboItem );

            configureBinding();

            BindToControls();

            buildQfd();

            queryFieldListControl1.QueryFieldList = qfd;
        }
Exemple #19
0
        public IActionResult GetEvents()
        {
            try {
                var events           = _repository.Opportunity.GetAllOpportunities();
                var user_opportunity = _repository.User_Opportunity.GetAllUserOpportunities();

                List <Opportunity> opportunities = new List <Opportunity> {
                };
                List <User> users          = new List <User> {
                };
                List <Requested> requested = new List <Requested> {
                };
                foreach (var user in user_opportunity)
                {
                    var opp = _repository.Opportunity.GetOpportunityById(user.Opportunity_Id);
                    var usr = _repository.User.GetUserById(user.User_Id);
                    opportunities.Add(opp);
                    users.Add(usr);
                    var requestedOpp = new Requested
                    {
                        user_opportunity_id     = user.user_opportunity_id,
                        Opportunity_Description = opp.OpportunityDescription,
                        User_Name  = usr.UserName,
                        Start_Date = user.Request_Date,
                        Color      = opp.Color
                    };
                    requested.Add(requestedOpp);
                }
                //var x = requested.FindAll(c => c.Start_Date.Equals(Convert.ToDateTime(startDate)));
                return(new JsonResult(requested));

                //return new JsonResult(events);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong inside CreateDate action: {ex.Message}");
                return(StatusCode(500, "Internal server error"));
            }
        }
Exemple #20
0
 private void RemoveUserFromMemory(FriendModel user)
 {
     if (Friends.Contains(user))
     {
         Friends.Remove(user);
         UserFriendsUpdatedEvent?.Invoke();
     }
     if (Pending.Contains(user))
     {
         Pending.Remove(user);
         PendingUsersUpdatedEvent?.Invoke();
     }
     if (Requested.Contains(user))
     {
         Requested.Remove(user);
         RequestedUsersUpdatedEvent?.Invoke();
     }
     if (Blocked.Contains(user))
     {
         Blocked.Remove(user);
         BlockedUsersUpdatedEvent?.Invoke();
     }
 }
Exemple #21
0
        public virtual OhlcData Include(TimeRange rangeAttempted, OhlcData data, bool acceptLiveRange = false)
        {
            var range = data.GetTimeRange(rangeAttempted.TimeResolution);

            if (!acceptLiveRange)
            {
                range          = range.RemoveLiveRange();
                rangeAttempted = rangeAttempted.RemoveLiveRange();
            }

            if (data.IsNotEmpty())
            {
                Found.Add(range);
            }
            else
            {
                Unavailable.Add(rangeAttempted);
            }

            if (!Unavailable.Covers(rangeAttempted) && !Found.Covers(rangeAttempted))
            {
                Requested.Add(rangeAttempted);
            }

            var foundMin   = Found.MinimumFrom();
            var missingMin = Unavailable.MinimumFrom();

            var minDate = foundMin < missingMin ? foundMin : missingMin;

            if (minDate != DateTime.MaxValue)
            {
                UtcEarliestEntry = UtcEarliestEntry > minDate ? minDate : UtcEarliestEntry;
            }

            return(data);
        }
Exemple #22
0
        public void UdpListener_Received(byte[] data, IPEndPoint endPoint)
        {
            try
            {
                var dhcpData = new DhcpData(data)
                {
                    RelatedServer = this
                };
                var msgType = dhcpData.GetCurrentMessageType();
                var client  = dhcpData.GetClientInfo();
                switch (msgType)
                {
                case DhcpMessgeType.DHCP_DISCOVER:
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPDISCOVER received."
                    });
                    Discovered?.Invoke(client);
                    var newIp = ownedIpAddressPool.Find(x => (x.AuthorizedClientMac == client.MacAddress) || (x.IsAllocated == false && x.AuthorizedClientMac == null));
                    if (newIp.Ip == null)
                    {
                        MessageRaised?.Invoke(this, new MessageEventArgs {
                            Message = "No ip is available to allocate."
                        });
                        return;
                    }
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPOFFER sent."
                    });
                    // MUST be unicast over raw socket (unimplemented)
                    // broadcast used
                    SendDhcpMessage(DhcpMessgeType.DHCP_OFFER, dhcpData, newIp);
                    break;

                case DhcpMessgeType.DHCP_REQUEST:
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPREQUEST received."
                    });
                    Requested?.Invoke(client);
                    switch (GetDhcpRequestType(client, endPoint))
                    {
                    // respond to client which has responded to DHCPOFFER message from this server
                    case DhcpRequestType.Selecting:
                        MessageRaised?.Invoke(this, new MessageEventArgs {
                            Message = "Response to DHCPREQUEST generated during SELECTING state."
                        });
                        if (_settings.ServerIp.Equals(client.ServerAddress))
                        {
                            var allocatedIp = ownedIpAddressPool.Find(x => x.Ip.Equals(client.RequestAddress));
                            if (allocatedIp.Ip != null && !allocatedIp.IsAllocated)
                            {
                                allocatedIp.IsAllocated         = true;
                                allocatedIp.AuthorizedClientMac = client.MacAddress;
                                MessageRaised?.Invoke(this, new MessageEventArgs {
                                    Message = "DHCPACK sent."
                                });
                                // broadcast
                                SendDhcpMessage(DhcpMessgeType.DHCP_ACK, dhcpData, allocatedIp);
                            }
                        }
                        break;

                    case DhcpRequestType.InitReboot:
                        MessageRaised?.Invoke(this, new MessageEventArgs {
                            Message = "Response to DHCPREQUEST generated during INIT-REBOOT state."
                        });
                        if (!client.RelayAgentAddress.Equals(IPAddress.Any))
                        {
                            MessageRaised?.Invoke(this, new MessageEventArgs {
                                Message = "Relay agent is not supported in this version."
                            });
                        }
                        var rebootIp = ownedIpAddressPool.Find(x => x.Ip.Equals(client.RequestAddress));
                        if (rebootIp.Ip != null && rebootIp.AuthorizedClientMac == client.MacAddress)
                        {
                            // broadcast
                            SendDhcpMessage(DhcpMessgeType.DHCP_ACK, dhcpData, rebootIp);
                            MessageRaised?.Invoke(this, new MessageEventArgs {
                                Message = "DHCPACK sent."
                            });
                        }
                        break;

                    case DhcpRequestType.ReNewing:
                        MessageRaised?.Invoke(this, new MessageEventArgs {
                            Message = "Response to DHCPREQUEST generated during RENEWING state."
                        });
                        var reNewIp = ownedIpAddressPool.Find(x => x.Ip.Equals(client.ClientAddress));
                        if (reNewIp.Ip != null && reNewIp.AuthorizedClientMac == client.MacAddress)
                        {
                            // unicast
                            SendDhcpMessage(client.ClientAddress.ToString(), DhcpMessgeType.DHCP_ACK, dhcpData, reNewIp);
                            MessageRaised?.Invoke(this, new MessageEventArgs {
                                Message = "DHCPACK sent."
                            });
                        }
                        break;

                    case DhcpRequestType.ReBinding:
                        MessageRaised?.Invoke(this, new MessageEventArgs {
                            Message = "Response to DHCPREQUEST generated during REBINDING state."
                        });
                        var reBindIp = ownedIpAddressPool.Find(x => x.IsAllocated == false);
                        if (reBindIp.Ip != null)
                        {
                            reBindIp.IsAllocated         = true;
                            reBindIp.AuthorizedClientMac = client.MacAddress;
                            // broadcast
                            SendDhcpMessage(DhcpMessgeType.DHCP_ACK, dhcpData, reBindIp);
                            MessageRaised?.Invoke(this, new MessageEventArgs {
                                Message = "DHCPACK sent."
                            });
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    break;

                case DhcpMessgeType.DHCP_DECLINE:
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPDECLINE received."
                    });
                    var declinedIp = ownedIpAddressPool.Find(x => x.Ip.Equals(client.ClientAddress));
                    if (declinedIp.Ip != null)
                    {
                        ownedIpAddressPool.Remove(declinedIp);
                    }
                    break;

                case DhcpMessgeType.DHCP_RELEASE:
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPRELESE received."
                    });
                    var releasedIp = ownedIpAddressPool.Find(x => x.Ip.Equals(client.ClientAddress));
                    if (releasedIp.Ip != null)
                    {
                        releasedIp.IsAllocated = false;
                    }
                    break;

                case DhcpMessgeType.DHCP_INFORM:
                    MessageRaised?.Invoke(this, new MessageEventArgs {
                        Message = "DHCPINFORM received."
                    });
                    // unicast
                    SendDhcpMessage(client.ClientAddress.ToString(), DhcpMessgeType.DHCP_ACK, dhcpData, null);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (Exception e)
            {
                ErrorRaised?.Invoke(this, new ErrorMessageEventArgs {
                    Message = e.Message
                });
                Terminate();
                throw e;
            }
        }
 internal static void RaiseRequested(int index)
 {
     Requested?.Invoke(null, index);
 }
Exemple #24
0
 /// <summary>
 /// Increment reference count.
 /// </summary>
 internal void AddRef()
 {
     Interlocked.Increment(ref _reference);
     Requested?.Invoke(this, null);
 }
Exemple #25
0
        public bool RawObject_Received(object rawObject)
        {
            var handled = false;

            if (!(rawObject is string rawJson))
            {
                return(handled);
            }

            dynamic obj = JsonConvert.DeserializeObject(rawJson);

            try
            {
                if (obj.post_type == "message")
                {
                    if (obj.message_type == "private") // 私聊
                    {
                        CoolQPrivateMessageApi parsedObj = JsonConvert.DeserializeObject <CoolQPrivateMessageApi>(rawJson);
                        var arg = new MessageEventArgs(parsedObj);
                        PrivateMessageReceived?.Invoke(this, arg);
                        MessageReceived?.Invoke(this, arg);
                    }
                    else if (obj.message_type == "group") // 群聊
                    {
                        CoolQGroupMessageApi parsedObj = JsonConvert.DeserializeObject <CoolQGroupMessageApi>(rawJson);
                        var arg = new MessageEventArgs(parsedObj);
                        DiscussMessageReceived?.Invoke(this, arg);
                        MessageReceived?.Invoke(this, arg);
                    }
                    else if (obj.message_type == "discuss") // 讨论组
                    {
                        CoolQDiscussMessageApi parsedObj = JsonConvert.DeserializeObject <CoolQDiscussMessageApi>(rawJson);
                        var arg = new MessageEventArgs(parsedObj);
                        GroupMessageReceived?.Invoke(this, arg);
                        MessageReceived?.Invoke(this, arg);
                    }
                }
                else
                {
                    EventReceived?.Invoke(this, new EventEventArgs(rawJson));
                    if (obj.post_type == "notice")
                    {
                        if (obj.notice_type == "group_upload") // 群文件上传
                        {
                            GroupFileUpload parsedObj = JsonConvert.DeserializeObject <GroupFileUpload>(rawJson);
                            var             arg       = new NoticeEventArgs(parsedObj);
                            GroupFileUploaded?.Invoke(this, arg);
                            Noticed?.Invoke(this, arg);
                        }
                        else if (obj.notice_type == "group_admin") // 群管理员变动
                        {
                            GroupAdminChange parsedObj = JsonConvert.DeserializeObject <GroupAdminChange>(rawJson);
                            var arg = new NoticeEventArgs(parsedObj);
                            GroupAdminChanged?.Invoke(this, arg);
                            Noticed?.Invoke(this, arg);
                        }
                        else if (obj.notice_type == "group_decrease" || obj.notice_type == "group_increase") // 群成员增加/减少
                        {
                            GroupMemberChange parsedObj = JsonConvert.DeserializeObject <GroupMemberChange>(rawJson);
                            var arg = new NoticeEventArgs(parsedObj);
                            Noticed?.Invoke(this, arg);
                            GroupMemberChanged?.Invoke(this, arg);
                        }
                        else if (obj.notice_type == "friend_add") // 好友添加
                        {
                            FriendAdd parsedObj = JsonConvert.DeserializeObject <FriendAdd>(rawJson);
                            var       arg       = new NoticeEventArgs(parsedObj);
                            FriendAdded?.Invoke(this, arg);
                            Noticed?.Invoke(this, arg);
                        }
                    }
                    else if (obj.post_type == "request")
                    {
                        if (obj.request_type == "friend") // 加好友请求
                        {
                            FriendRequest parsedObj = JsonConvert.DeserializeObject <FriendRequest>(rawJson);
                            var           arg       = new RequestEventArgs(parsedObj);
                            FriendRequested?.Invoke(this, arg);
                            Requested?.Invoke(this, arg);

                            //// TODO,临时
                            //CqApi.SendPrivateMessage("2241521134",
                            //    string.Format("{0} ({1})邀请加我为好友",
                            //        CqApi.GetStrangerInfo(parsedObj.UserId.ToString()).Data?.Nickname, parsedObj.UserId));
                        }
                        else if (obj.request_type == "group") // 加群请求/邀请
                        {
                            GroupInvite parsedObj = JsonConvert.DeserializeObject <GroupInvite>(rawJson);
                            var         arg       = new RequestEventArgs(parsedObj);
                            GroupRequested?.Invoke(this, arg);
                            Requested?.Invoke(this, arg);

                            //// TODO,临时
                            //if (parsedObj.SubType == "invite")
                            //{
                            //    CqApi.SendPrivateMessage("2241521134",
                            //        string.Format("{0} ({1})邀请我加入群{2}",
                            //            CqApi.GetStrangerInfo(parsedObj.UserId.ToString()).Data?.Nickname, parsedObj.UserId,
                            //            parsedObj.GroupId));
                            //}
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorOccured?.Invoke(this, new ExceptionEventArgs(null, ex));
            }

            return(handled);
        }
Exemple #26
0
 public void Raise()
 {
     Requested?.Raise(this);
 }
Exemple #27
0
 public void RaiseRequested()
 {
     Requested?.Invoke(this, EventArgs.Empty);
 }
Exemple #28
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="e"></param>
        /// <param name="clientId">客户端ID,如有值,覆盖其他数据</param>
        /// <param name="clientIp">客户端IP,如有值,覆盖其他数据</param>
        /// <returns></returns>
        public async Task Invoke(EventRequestingArgs e, string clientId = null, string clientIp = null)
        {
            HttpRequest httpRequest = e.Request;
            // compute identity from request
            var identity = ResolveIdentity(httpRequest);

            if (!String.IsNullOrEmpty(clientId))
            {
                identity.ClientId = clientId;
            }
            if (!String.IsNullOrEmpty(clientIp))
            {
                identity.ClientIp = clientIp;
            }

            // check white list
            if (_processor.IsWhitelisted(identity))
            {
                return;
            }


            var rules = await _processor.GetMatchingRulesAsync(identity);

            var rulesDict = new Dictionary <RateLimitRule, RateLimitCounter>();

            foreach (var rule in rules)
            {
                // increment counter
                var rateLimitCounter = await _processor.ProcessRequestAsync(identity, rule);

                if (rule.Limit > 0)
                {
                    // check if key expired
                    if (rateLimitCounter.Timestamp + rule.PeriodTimespan.Value < DateTime.UtcNow)
                    {
                        continue;
                    }

                    // check if limit is reached
                    if (rateLimitCounter.Count > rule.Limit)
                    {
                        //compute retry after value
                        var retryAfter = rateLimitCounter.Timestamp.RetryAfterFrom(rule);

                        //// log blocked request
                        //LogBlockedRequest(context, identity, rateLimitCounter, rule);

                        //if (_options.RequestBlockedBehavior != null)
                        //{
                        //    await _options.RequestBlockedBehavior(context, identity, rateLimitCounter, rule);
                        //}
                        // RequestBlocked?.Invoke(identity, rateLimitCounter, rule);
                        if (RequestBlocked != null)
                        {
                            RequestBlocked.Invoke(this, new EventRequestBlockedArgs()
                            {
                                identity = identity, rateLimitCounter = rateLimitCounter, rateLimitRule = rule
                            });
                        }
                        //// break execution
                        ReturnQuotaExceededResponse(e, rule, retryAfter).Wait();


                        return;
                    }
                }
                // if limit is zero or less, block the request.
                else
                {
                    //// log blocked request
                    //LogBlockedRequest(context, identity, rateLimitCounter, rule);

                    //if (_options.RequestBlockedBehavior != null)
                    //{
                    //    await _options.RequestBlockedBehavior(context, identity, rateLimitCounter, rule);
                    //}
                    if (RequestBlocked != null)
                    {
                        RequestBlocked.Invoke(this, new EventRequestBlockedArgs()
                        {
                            identity = identity, rateLimitCounter = rateLimitCounter, rateLimitRule = rule
                        });
                    }



                    //// break execution (Int32 max used to represent infinity)
                    await ReturnQuotaExceededResponse(e, rule, int.MaxValue.ToString(System.Globalization.CultureInfo.InvariantCulture));

                    return;
                }

                rulesDict.Add(rule, rateLimitCounter);
            }

            // set X-Rate-Limit headers for the longest period
            if (rulesDict.Any() && !_options.DisableRateLimitHeaders)
            {
                var rule    = rulesDict.OrderByDescending(x => x.Key.PeriodTimespan).FirstOrDefault();
                var headers = _processor.GetRateLimitHeaders(rule.Value, rule.Key);

                //  headers.Context = context;

                // context.Response.OnStarting(SetRateLimitHeaders, state: headers);
                await SetRateLimitHeaders(e, headers);
            }

            if (rulesDict.Any())
            {
                //Requested?.Invoke(identity, rulesDict);
                if (Requested != null)
                {
                    Requested.Invoke(this, new EventRequestedArgs()
                    {
                        identity = identity, rules = rulesDict
                    });
                }
            }

            await Task.CompletedTask;
        }
Exemple #29
0
 public void Request() => Requested?.Invoke(this, EventArgs.Empty);
Exemple #30
0
 public bool Covers(TimeRange range)
 {
     return(Found.Covers(range) || Unavailable.Covers(range) || Requested.Covers(range));
 }