Ejemplo n.º 1
0
        public void ReceiveStartMessage(object?sender, DataEventArgs <Message> eventArgs)
        {
            if (activeMessage != null &&
                !config.SplitClass.ReplacesTeachers.Contains(activeMessage.Teacher))
            {
                logger.Warn("Received new message while last one isn't done");
                logger.Debug("Last message: {0}", activeMessage);
                logger.Debug("New message: {0}", eventArgs.Data);
                logger.Debug("Changing to new message.");
            }
            if (eventArgs.Data != lastMessage)
            {
                activeMessage = eventArgs.Data;
            }

            var bot = sender as ClassroomBot;

            if (bot == null)
            {
                throw new NullReferenceException("Null classroom bot");
            }

            string link = bot.GetClassroomMeetLink();

            if (link != ActiveMeetLink)
            {
                ActiveMeetLink = link;
                logger.Debug("New meet link");
            }
        }
Ejemplo n.º 2
0
    public override async Task <WebSocketReceiveResult> ReceiveAsync(ArraySegment <byte> output, CancellationToken cancellationToken)
    {
        Message?input = this.readingInProgress;

        if (this.readingInProgress == null)
        {
            input = this.readingInProgress = await this.ReadQueue.DequeueAsync(cancellationToken);
        }

        int bytesToCopy = Math.Min(input !.Buffer.Length, output.Count);

        input.Buffer.Slice(0, bytesToCopy).CopyTo(output.Array.AsMemory(output.Offset, output.Count));
        bool finishedMessage = bytesToCopy == input.Buffer.Length;

        if (finishedMessage)
        {
            this.readingInProgress = null;
        }
        else
        {
            input.Buffer = input.Buffer.Slice(bytesToCopy);
        }

        WebSocketReceiveResult result = new WebSocketReceiveResult(
            bytesToCopy,
            WebSocketMessageType.Text,
            finishedMessage,
            bytesToCopy == 0 ? (WebSocketCloseStatus?)WebSocketCloseStatus.Empty : null,
            bytesToCopy == 0 ? "empty" : null);

        return(result);
    }
Ejemplo n.º 3
0
        public ActionResult UserFodmap(Message?message)
        {
            ViewBag.StatusMessage =
                message == Message.AddFodmapSuccess ? "Successfully added new high FODMAP ingredient"
                : message == Message.FodmapExists ? "Ingredient already exists in database"
                : message == Message.AddFodmapFailure ? "Failed to add new entry to database"
                : "";
            List <HighRiskLabelledIngredient> eligibleIngredientList = new List <HighRiskLabelledIngredient>();
            List <int> highRiskList = db.UserIngredients.Where(u => u.Label == "High-Risk").Select(u => u.LabelledIngredientID).Distinct().ToList();

            foreach (int ingredient in highRiskList)
            {
                LabelledIngredient labelIng = db.LabelledIngredients.Where(l => l.ID == ingredient).FirstOrDefault();
                int  count           = db.UserIngredients.Where(u => u.LabelledIngredientID == ingredient && u.Label == "High-Risk").Count();
                bool ingredentExists = db.FODMAPIngredients.FirstOrDefault(x => x.Name.Contains(labelIng.Name)) != null ||
                                       db.FODMAPIngredients.FirstOrDefault(x => x.Aliases.Contains(labelIng.Name)) != null;
                if (count > 9 && !ingredentExists)
                {
                    HighRiskLabelledIngredient newIngredient = new HighRiskLabelledIngredient(labelIng, count);
                    eligibleIngredientList.Add(newIngredient);
                }
            }
            eligibleIngredientList = eligibleIngredientList.OrderByDescending(o => o.countOfLabelOccurences).ToList();
            return(View(eligibleIngredientList));
        }
Ejemplo n.º 4
0
        /// <summary></summary>
        public static void CheckLLRPResponse(
            Message?message,
            MSG_ERROR_MESSAGE?error)
        {
            if (message == null && error == null)
            {
                throw new Exception("timeout");
            }


            PARAM_LLRPStatus?llrpStatus = null;

            // message を優先
            llrpStatus = (PARAM_LLRPStatus?)message?
                         .GetType()
                         .GetField(name: "LLRPStatus")?
                         .GetValue(message);

            if (llrpStatus == null && error != null)
            {
                llrpStatus = error.LLRPStatus;
            }

            if (llrpStatus == null)
            {
                throw new InvalidOperationException();
            }

            if (llrpStatus.StatusCode != ENUM_StatusCode.M_Success)
            {
                throw new LLRPException(
                          llrpStatus.StatusCode,
                          llrpStatus.ErrorDescription);
            }
        }
Ejemplo n.º 5
0
    public ActionResult Remove(int?id)
    {
        if (id == null || id <= 0)
        {
            return(BadRequest(new Msg {
                Result = "Error", Message = "Remove: id invalid or null."
            }));
        }

        Message?message = _dbContext.Messages.Find(id);

        if (message == null)
        {
            return(BadRequest(new Msg {
                Result = "Error", Message = "Remove: id invalid or null."
            }));
        }

        _dbContext.Messages.Remove(message);
        int numChanges = _dbContext.SaveChanges();

        return(Ok(new Msg {
            Result = "Success", Message = $"{numChanges} record(s) removed."
        }));
    }
Ejemplo n.º 6
0
    public ActionResult Update([FromBody] Message message)
    {
        if (message == null)
        {
            return(BadRequest(new Msg {
                Result = "Error", Message = "Update: null message."
            }));
        }

        Message?dbMessage = _dbContext.Messages.Find(message.Id);

        if (dbMessage == null)
        {
            return(BadRequest(new Msg {
                Result = "Error", Message = "Update: invalid id"
            }));
        }

        dbMessage.Copy(message);

        if (ModelState.IsValid)
        {
            int numChanges = _dbContext.SaveChanges();
            return(Ok(new Msg {
                Result = "Success", Message = $"{numChanges} record(s) updated."
            }));
        }

        return(BadRequest(new Msg {
            Result = "Error", Message = "Update: ModelState invalid."
        }));
    }
Ejemplo n.º 7
0
        public static void CheckError(Message?msg, MSG_ERROR_MESSAGE?msgErr)
        {
            if (msg == null && msgErr == null)
            {
                throw new LLRPTimeoutException();
            }

            PARAM_LLRPStatus?status = (PARAM_LLRPStatus?)msg?.GetType()
                                      .GetField(name: "LLRPStatus")
                                      .GetValue(msg);

            if (msgErr != null)
            {
                status = msgErr.LLRPStatus;
            }

            if (status == null)
            {
                throw new InvalidOperationException();
            }

            if (status.StatusCode != ENUM_StatusCode.M_Success)
            {
                throw new LLRPException(status.StatusCode, status.ErrorDescription);
            }
        }
Ejemplo n.º 8
0
        public async Task <ActionResult> Index(Message?message)
        {
            ViewBag.StatusMessage = MessageGenerator(message);
            var news = await _newsPageLogic.GetAllNews();

            return(View(news));
        }
Ejemplo n.º 9
0
        public async IAsyncEnumerable <MessageResponse> HandleMessageAsync(Message message, NextHandler nextHandler)
        {
            Message?respondedMessage = null;

            await using var enumerator = nextHandler().GetAsyncEnumerator();

            while (true)
            {
                MessageResponse response;

                try
                {
                    if (!await enumerator.MoveNextAsync())
                    {
                        break;
                    }

                    response = enumerator.Current;
                }
                catch (HandlerException e)
                {
                    response = e.Message.ToString();
                }

                await _client.SendChatActionAsync(message.Chat, ChatAction.Typing);

                if (respondedMessage is null || response.ForceNewMessage)
                {
                    respondedMessage = await _client.SendTextMessageAsync(message.Chat, response.ToString(),
                                                                          parseMode : response.ParseMode,
                                                                          disableWebPagePreview : true,
                                                                          replyToMessageId : message.Chat.Type != ChatType.Private?message.MessageId : 0,
                                                                          replyMarkup : GetReplyMarkup(response.ExtraMarkup));
                }
Ejemplo n.º 10
0
        /// <summary></summary>
        protected void CheckLLRPError(
            Message?msg             = null,
            MSG_ERROR_MESSAGE?error = null)
        {
            if (msg == null && error == null)
            {
                throw new NullReferenceException();
            }

            PARAM_LLRPStatus?status = error?.LLRPStatus;

            if (status == null)
            {
                status = msg?.GetType().GetField("LLRPStatus")?.GetValue(msg) as PARAM_LLRPStatus;
            }

            if (status == null)
            {
                throw new NullReferenceException();
            }

            if (status.StatusCode != ENUM_StatusCode.M_Success)
            {
                throw new Exception($"{status.ErrorDescription ?? string.Empty}");
            }
        }
Ejemplo n.º 11
0
        public Message?ReadLine()
        {
            Message?message = null;

            try
            {
                char direction = ReadChar();

                if (direction != '<' && direction != '>')
                {
                    throw new Exception($"Invalid direction prefix, expected '<' or '>', received '{direction}'");
                }

                message          = Read();
                message.Incoming = direction == '<';

                for (; ;)
                {
                    char c = PeekChar();
                    if (c == '\r' || c == '\n')
                    {
                        ReadChar();
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (EndOfStreamException)
            {
            }
            return(message);
        }
        public override Task SendAsync(ArraySegment <byte> input, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
        {
            if (this.writingInProgress == null)
            {
                var bufferCopy = new byte[input.Count];
                Buffer.BlockCopy(input.Array !, input.Offset, bufferCopy, 0, input.Count);
                this.writingInProgress = new Message {
                    Buffer = new ArraySegment <byte>(bufferCopy)
                };
            }
            else
            {
                byte[] bufferCopy = this.writingInProgress.Buffer.Array !;
                Array.Resize(ref bufferCopy, bufferCopy.Length + input.Count);
                Buffer.BlockCopy(input.Array !, input.Offset, bufferCopy, this.writingInProgress.Buffer.Count, input.Count);
                this.writingInProgress.Buffer = new ArraySegment <byte>(bufferCopy);
            }

            if (endOfMessage)
            {
                this.WrittenQueue.Enqueue(this.writingInProgress);
                this.writingInProgress = null;
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 13
0
        public static Message Get(Message Original, Message?Override, string Key,
                                  string SenderName, string ReceiverName, string AnotherPlayerName = null)
        {
            Message message = Get(Original, Override);

            bool   hasSender = !(SenderName is null);
            string msg       = (hasSender
                            ? message.MessageWithSenderName
                            : message.MessageWithoutSenderName);

            if (msg is null)
            {
                return(message);
            }

            if (Key != null)
            {
                msg = msg.Replace("{KEY}", Key);
            }
            if (ReceiverName != null)
            {
                msg = msg.Replace("{RECEIVER}", ReceiverName);
            }
            if (hasSender)
            {
                msg = msg.Replace("{SENDER}", SenderName);
            }
            if (AnotherPlayerName != null)
            {
                msg = msg.Replace("{ANOTHERPLAYER}", AnotherPlayerName);
            }
            message.ResultingMessage = msg;

            return(message);
        }
Ejemplo n.º 14
0
 public PlayerCheckin(CheckinLister lister, Message checkinEvent,
                      Predicate allCheckedInPredicate = null,
                      EventPredicate checkinPredicate = null,
                      Callback onCheckin    = null,
                      Callback onReset      = null,
                      Message?checkoutEvent = null)
 {
     this.lister = lister;
     if (allCheckedInPredicate != null)
     {
         this.allCheckedInPredicate = allCheckedInPredicate;
     }
     if (checkinPredicate != null)
     {
         this.checkinPredicate = checkinPredicate;
     }
     if (onCheckin != null)
     {
         this.onCheckin = onCheckin;
     }
     if (onReset != null)
     {
         this.onReset = onReset;
     }
     GameManager.instance.notificationManager.CallOnMessageWithSender(checkinEvent, Checkin);
     if (checkoutEvent.HasValue)
     {
         GameManager.instance.notificationManager.CallOnMessageWithSender(checkoutEvent.Value, Checkout);
     }
 }
Ejemplo n.º 15
0
    public static PlayerCheckin TextCountCheckin(
        CheckinLister lister, Message checkinEvent,
        Text textBox, Predicate allCheckedInPredicate = null,
        EventPredicate checkinPredicate = null,
        Callback onCheckin    = null,
        Callback onReset      = null,
        Message?checkoutEvent = null)
    {
        PlayerCheckin result = new PlayerCheckin(
            lister, checkinEvent, allCheckedInPredicate,
            checkinPredicate, checkoutEvent: checkoutEvent);

        Callback modifyText = () =>
        {
            textBox.text = string.Format("{0}/{1}", result.NumberCheckedIn(), lister().Count);
        };

        onCheckin  = onCheckin ?? delegate { };
        onCheckin += modifyText;

        onReset  = onReset ?? delegate { };
        onReset += modifyText;

        result.onCheckin = onCheckin;
        result.onReset   = onReset;
        return(result);
    }
        protected void UpdateLoop()
        {
            while (!abort)
            {
                EstablishConnectionLoop();
                try {
                    while (!abort)
                    {
                        Message?message = ReadMessage();

                        if (message != null)
                        {
                            ReadData((Message)message);
                            waiting = false;
                        }

                        Thread.Sleep(timeout);

                        if (!NeedsToWait())
                        {
                            pendingWrite?.Invoke();
                            pendingWrite = null;
                        }
                    }
                }
                //For this to work all writes must occur in this thread
                catch (NeedsResetException e) {
                    ForceReset(e);
                }
            }
        }
Ejemplo n.º 17
0
    public void showModal(string modalText, string okText, UnityAction okEvent, bool prior = false)
    {
        Message message = new Message(modalText, okText, okEvent);

        if (GameController.waitModal == true && !displayMessage.Equals(message))
        {
            if (!messages.Contains(message) && !prior)
            {
                messages.Enqueue(message);
            }
            if (!messages.Contains(message) && prior)
            {
                addToFrontOfQueue(message);
                GameController.waitModal = false;
            }
            return;
        }
        GameController.waitModal = true;
        displayMessage           = message;
        text.SetText(modalText);
        noButtonText.SetText(okText);

        noButton.GetComponent <Button>().onClick.RemoveAllListeners();
        noButton.GetComponent <Button>().onClick.AddListener(closeModal);
        noButton.GetComponent <Button>().onClick.AddListener(okEvent);

        yesButton.SetActive(false);
        noButton.SetActive(true);
        modal.SetActive(true);
        iTween.MoveFrom(modal, modal.transform.position + new Vector3(0, 200, 0), 1);
        iTween.FadeFrom(modal, 0, 0.2f);
    }
Ejemplo n.º 18
0
    public override Task SendAsync(ArraySegment <byte> input, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
    {
        if (this.writingInProgress == null)
        {
            byte[] bufferCopy = new byte[input.Count];
            Buffer.BlockCopy(input.Array !, input.Offset, bufferCopy, 0, input.Count);
            this.writingInProgress = new Message {
                Buffer = new ArraySegment <byte>(bufferCopy)
            };
        }
        else
        {
            Memory <byte> memory = new byte[this.writingInProgress.Buffer.Length + input.Count];
            this.writingInProgress.Buffer.CopyTo(memory);
            input.Array.CopyTo(memory.Slice(this.writingInProgress.Buffer.Length));
            this.writingInProgress.Buffer = memory;
        }

        if (endOfMessage)
        {
            this.WrittenQueue.Enqueue(this.writingInProgress);
            this.writingInProgress = null;
        }

        return(Task.FromResult(0));
    }
Ejemplo n.º 19
0
 public Message(
     Snowflake id,
     MessageType type,
     User author,
     DateTimeOffset timestamp,
     DateTimeOffset?editedTimestamp,
     DateTimeOffset?callEndedTimestamp,
     bool isPinned,
     string content,
     IReadOnlyList <Attachment> attachments,
     IReadOnlyList <Embed> embeds,
     IReadOnlyList <Reaction> reactions,
     IReadOnlyList <User> mentionedUsers,
     MessageReference?messageReference,
     Message?referencedMessage)
 {
     Id                 = id;
     Type               = type;
     Author             = author;
     Timestamp          = timestamp;
     EditedTimestamp    = editedTimestamp;
     CallEndedTimestamp = callEndedTimestamp;
     IsPinned           = isPinned;
     Content            = content;
     Attachments        = attachments;
     Embeds             = embeds;
     Reactions          = reactions;
     MentionedUsers     = mentionedUsers;
     Reference          = messageReference;
     ReferencedMessage  = referencedMessage;
 }
Ejemplo n.º 20
0
        public override void UpdateAfterSimulation()
        {
            if (!MySandboxGame.IsGameReady)
            {
                return;
            }
            if (Game.IsDedicated)
            {
                return;
            }

            if (_currentDisplayTime <= 0 && MessageQueue.Count > 0)
            {
                _currentDisplayTime = 200;
                _currentMessage     = MessageQueue.Dequeue();
                MyAudio.Static.PlaySound(MySoundPair.GetCueId(_currentMessage.Value.Sound));
            }
            else if (_currentDisplayTime > 0)
            {
                _currentDisplayTime--;
                if (_currentDisplayTime <= 0)
                {
                    _currentMessage = null;
                }
            }
        }
Ejemplo n.º 21
0
        public Message GetMessage(MessageType Type, object Sender, object Receiver, string Key)
        {
            if (Receiver is null)
            {
                throw new ArgumentNullException(nameof(Receiver));
            }
            if (Key is null)
            {
                throw new ArgumentNullException(nameof(Key));
            }

            Message?messageOverride = null;

            if (OtherFormatOverrides.TryGetValue(Type, out Message msg))
            {
                messageOverride = msg;
            }

            string senderName = ((Sender == null || Sender.Equals(RequestsManager.EmptySender))
                                    ? null
                                    : RequestsManager.GetPlayerNameFunc?.Invoke(Sender));
            string receiverName = RequestsManager.GetPlayerNameFunc?.Invoke(Receiver);

            return(Message.Get(GetDefaultOtherMessageFormat(Type),
                               messageOverride, Key, senderName, receiverName, null));
        }
Ejemplo n.º 22
0
    public async Task OnMessageReceived(Message?message)
    {
        _logger.LogInformation(MessageLogMsg, message?.Chat.Id, message?.From?.Username, message?.Text);

        if (message?.Text is null || message.Type != MessageType.Text)
        {
            return;
        }

        var    command = new CommandParser(message.Text).Parse();
        var    chatId  = message.Chat.Id;
        string username;

        if (message.From is null)
        {
            username = "******";
        }
        else
        {
            username = string.IsNullOrEmpty(message.From.Username)
                ? $"{message.From.FirstName} {message.From.LastName}"
                : message.From.Username;
        }

        IAction cmd;

        if (_botService.IsPrivateMode && chatId != _botService.PrivateChetId)
        {
            cmd = new NoCommand();
        }
        else
        {
            cmd = command.Name switch
            {
                "echo" => new Echo(_botService, chatId, command.Arguments),
                "hey" => new Hey(_botService, chatId),
                "ex" => new CurrencyExchange(_botService, chatId, command.Arguments, _configuration["apiForexKey"]),
                "ud" => new UrbanDictionary(_botService, _clientFactory, chatId, command.Arguments),
                "go" => new DuckDuckGo(_botService, _clientFactory, chatId, command.Arguments),
                "dice" => new RollDice(_botService, chatId, command.Arguments, username),
                "l" => new GoogleMaps(_botService, _clientFactory, chatId, command.Arguments,
                                      _configuration["googleApiKey"]),
                "weekday" => new WeekDay(_botService, chatId),
                "timein" => new TimeInPlace(_botService, _clientFactory, chatId, command.Arguments,
                                            _configuration["googleApiKey"]),
                "ball" => new MagicBall(_botService, chatId, command.Arguments),
                "weather" => new Weather(_botService, _clientFactory, chatId, command.Arguments),
                _ => new NoCommand()
            }
        };

        try
        {
            await cmd.HandleAsync();
        }
        catch (Exception e)
        {
            _logger.LogError("Cannot execute command, error {Message}", e.Message);
        }
    }
Ejemplo n.º 23
0
        /// <inheritdoc />
        public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            Requires.NotNull(buffer, nameof(buffer));
            Requires.Range(offset >= 0, nameof(offset));
            Requires.Range(count >= 0, nameof(count));
            Requires.Range(offset + count <= buffer.Length, nameof(count));

            cancellationToken.ThrowIfCancellationRequested();
            Message?message = null;

            while (message is null)
            {
                Task?waitTask = null;
                lock (this.readQueue)
                {
                    if (this.readQueue.Count > 0)
                    {
                        message = this.readQueue[0];
                    }
                    else
                    {
                        waitTask = this.enqueuedSource.Task;
                    }
                }

                if (waitTask is not null)
                {
                    if (cancellationToken.CanBeCanceled)
                    {
                        // Arrange to wake up when a new message is posted, or when the caller's CancellationToken is canceled.
                        var wakeUpEarly = new TaskCompletionSource <object?>();
                        using (cancellationToken.Register(state => ((TaskCompletionSource <object?>)state !).SetResult(null), wakeUpEarly, false))
                        {
                            await Task.WhenAny(waitTask, wakeUpEarly.Task).ConfigureAwait(false);
                        }

                        cancellationToken.ThrowIfCancellationRequested();
                    }
                    else
                    {
                        // The caller didn't pass in a CancellationToken. So just do the cheapest thing.
                        await waitTask.ConfigureAwait(false);
                    }
                }
            }

            int copiedBytes = message.Consume(buffer, offset, count);

            if (message.IsConsumed)
            {
                lock (this.readQueue)
                {
                    Assumes.True(this.readQueue[0] == message); // if this fails, the caller is calling Read[Async] in a non-sequential way.
                    this.readQueue.RemoveAt(0);
                }
            }

            return(copiedBytes);
        }
Ejemplo n.º 24
0
        private Task RunAsync([NotNull] MessageDeletePayload payload, [CanBeNull] Message?message)
        {
            Client.Logger.Information(
                "Received Deleted Message [{Id}] with content '{Content}'.", payload.Id,
                message?.Content ?? "Unknown.");

            return(Task.CompletedTask);
        }
Ejemplo n.º 25
0
        public async Task MessageHandlerReturnsExceptionWhenNullServiceBusMessageSupplied()
        {
            // arrange
            Message?serviceBusMessage = null;

            // act
            await Assert.ThrowsAsync <ArgumentNullException>(async() => await MessageHandler.Run(serviceBusMessage, messageProcessor, messagePropertiesService, logger).ConfigureAwait(false)).ConfigureAwait(false);
        }
Ejemplo n.º 26
0
 private string MessageGenerator(Message?message)
 {
     return(message == Message.AddVacancySuccess ? ""
         : message == Message.EditVacancySuccess ? ""
         : message == Message.RemoveVacancySuccess ? ""
         : message == Message.Error ? ""
         : null);
 }
Ejemplo n.º 27
0
 private string MessageGenerator(Message?message)
 {
     return(message == Message.createSuccess ? "Новость успешно создана"
         : message == Message.editSuccess ? "Новость обновлена"
         : message == Message.removeSuccess ? "Новость успешно удалена"
         : message == Message.error ? "Произошла ошибка"
         : null);
 }
Ejemplo n.º 28
0
        public static void Post(string text, User user, Channel channel, Message?parentMessage = null)
        {
            MessageDAO.Post(text, user.Id, channel.Id, parentMessage?.Id);

            onMessagesFetchedAsSubject.OnNext(Get(channel));

            onMessagePostedAsSubject.OnNext(Unit.Default);
        }
Ejemplo n.º 29
0
 public void RaiseMouseDownIfNeeded()
 {
     if (postponedMessage != null)
     {
         //  Activate();
         OnNCMouseDown((Message)postponedMessage);
         postponedMessage = null;
     }
 }
Ejemplo n.º 30
0
 public ActionResult AddFodmap(Message?message)
 {
     ViewBag.StatusMessage =
         message == Message.AddFodmapSuccess ? "Successfully added new high FODMAP ingredient"
         : message == Message.FodmapExists ? "Ingredient already exists in database"
         : message == Message.AddFodmapFailure ? "Failed to add new entry to database"
         : "";
     return(View());
 }