Example #1
0
		public ChannelMessage OnChannelMessage(ChannelMessage c, PassableMutableObject v) {
			if (!c.SplitArgs[1].CaseEquals(Def.Keys.First()))
				return null;

			c.Target = c.Nickname;
			string query = c.SplitArgs.Count < 4 ? c.SplitArgs[2] : $"{c.SplitArgs[2]}%20{c.SplitArgs[3]}".Replace(" ", "%20"),
				response =
					HttpGet("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" +
							query);

			if (c.SplitArgs.Count < 3) {
				c.Message = "Insufficient parameters. Type 'eve help lookup' to view correct usage.";
				return c;
			}

			JToken pages = JObject.Parse(response)["query"]["pages"].Values().First();
			if (string.IsNullOrEmpty((string) pages["extract"])) {
				c.Message = "Query failed to return results. Perhaps try a different term?";
				return c;
			}

			c.MultiMessage = new List<string> {
				$"\x02{(string) pages["title"]}\x0F — "
			};
			c.MultiMessage.AddRange(SplitStr(Regex.Replace((string) pages["extract"], @"\n\n?|\n", " "), 440));

			return c;
		}
Example #2
0
		public ChannelMessage OnChannelMessage(ChannelMessage c, PassableMutableObject v) {
			if (!c.SplitArgs[1].CaseEquals(Def.Keys.First()))
				return null;

			if (c.SplitArgs.Count < 3) {
				c.Message = "Insufficient parameters. Type 'eve help lookup' to view correct usage.";
				return c;
			}

			JObject entry =
				JObject.Parse(
					HttpGet(
						$"https://api.pearson.com:443/v2/dictionaries/lasde/entries?headword={c.SplitArgs[2]}&limit=1&part_of_speech={(c.SplitArgs.Count > 3 ? c.SplitArgs[3] : null)}"));
			var _out = new Dictionary<string, string>();

			if ((int) entry.SelectToken("count") < 1) {
				c.Message = "Query returned no results.";
				return c;
			}

			_out.Add("word", (string) entry.SelectToken("results[0].headword"));
			_out.Add("pos", (string) entry.SelectToken("results[0].part_of_speech"));
			_out.Add("def", (string) entry.SelectToken("results[0].senses[0].definition[0]"));
			_out.Add("ex", (string) entry.SelectToken("results[0].senses[0].examples[0].text"));

			string sOut = $"{_out["word"]} [{_out["pos"]}] — {_out["def"]}";
			if (string.IsNullOrEmpty(_out["ex"]))
				sOut += $" (ex. {_out["ex"]})";

			c.Message = sOut;
			return c;
		}
Example #3
0
		public ChannelMessage OnChannelMessage(ChannelMessage c, PassableMutableObject v) {
			Regex youtubeRegex =
				new Regex(@"(?i)http(?:s?)://(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)(?<ID>[\w\-]+)(&(amp;)?[\w\?=‌​]*)?",
					RegexOptions.Compiled);

			if (!youtubeRegex.IsMatch(c.Args)) return null;

			string get =
				HttpGet(
					$"https://www.googleapis.com/youtube/v3/videos?part=snippet&id={youtubeRegex.Match(c.Args).Groups["ID"]}&key=AIzaSyDnKtEZGuv3PgmePOSe6xBvoXKbrEMVxx8");

			JToken video = JObject.Parse(get)["items"][0]["snippet"];
			string channel = (string) video["channelTitle"];
			string title = (string) video["title"];
			string description = video["description"].ToString().Split('\n')[0];
			string[] descArray = description.Split(' ');

			if (description.Length > 200) {
				description = "";

				for (int i = 0; description.Length < 200; i++)
					description += $" {descArray[i]}";

				description += "....";
			}

			c.Message = $"{title} (by {channel}) — {description}";
			return c;
		}
		public virtual string LookupRoutingKey(ChannelMessage message)
		{
			// The current strategy is to have an exchange per message type and then have each application queue
			// bind to the exchange it wants based up the types of messages it wants to receive--this makes the
			// routing key mostly irrelevant.  Even so, it's provided here for easy customization.
			return message.Messages.First().GetType().FullName.NormalizeName();
		}
Example #5
0
        public void Publish(ChannelMessage channelMessage)
        {
            channelMessage.BodyStream.Seek(0, 0);

            InnerMessageHandler?.Invoke(this, new MessageReceivedEventArgs
            {
                Message = channelMessage
            });
        }
Example #6
0
 public void Publish(ChannelMessage channelMessage)
 {
     var messageType = channelMessage.GetHeader(MessageHeaders.MessageType);
     var endpoints = subscriptionStorage.GetSubscribersEndpoints(messageType);
     foreach (var destination in endpoints.Select(EndpointAddress.Parse))
     {
         MsmqUtilities.WriteMessage(destination, channelMessage);
     }
 }
Example #7
0
        public void Send(EndpointAddress destination, ChannelMessage channelMessage)
        {
            var queueName = destination.QueueName;
            if (!namespaceManager.QueueExists(queueName)) throw new Exception(string.Format("Destination {0} does not exist.", destination));

            var sendingClient = QueueClient.Create(queueName);
            var message = CreateBrokeredMessage(channelMessage);
            sendingClient.Send(message);
        }
Example #8
0
 private static byte[] ConvertHeaders(ChannelMessage message)
 {
     var xmlSerializer = new XmlSerializer(typeof(MessageHeader[]));
     var textWriter = new StringWriter();
     xmlSerializer.Serialize(textWriter, message.Headers.ToArray());
     var xml = textWriter.ToString();
     textWriter.Close();
     var encoding = new UTF8Encoding();
     return encoding.GetBytes(xml);
 }
Example #9
0
        public void Send(EndpointAddress destination, ChannelMessage channelMessage)
        {
            channelMessage.BodyStream.Seek(0, 0);
            sentDestinations.Add(destination);
            if (destination.QueueName.EndsWith("error")) return;

            InnerMessageHandler?.Invoke(this, new MessageReceivedEventArgs
            {
                Message = channelMessage
            });
        }
Example #10
0
 public static ChannelMessage CreateChannelMessage(object message, IMessageSerializer messageSerializer)
 {
     if (messageSerializer == null) throw new ArgumentNullException(nameof(messageSerializer));
     var messageType = message.GetType();
     var stream = messageSerializer.Serialize(message);
     var channelMessage = new ChannelMessage(stream);
     channelMessage.AddHeader(MessageHeaders.MessageType, messageType.FullName);
     channelMessage.AddHeader(MessageHeaders.UserPrincipal, Environment.UserName);
     channelMessage.AddHeader(MessageHeaders.SendingMachine, Environment.MachineName);
     channelMessage.AddHeader(MessageHeaders.SendingModule, ResolveAssemblyFullName());
     return channelMessage;
 }
Example #11
0
        private static BrokeredMessage CreateBrokeredMessage(ChannelMessage channelMessage)
        {
            var message = new BrokeredMessage(channelMessage.BodyStream)
            {
                Label = channelMessage.Headers.First().Value
            };

            foreach (var header in channelMessage.Headers)
            {
                message.Properties.Add(header.Name, header.Value);
            }

            return message;
        }
        public IHttpActionResult SendAnonymousMessage(string channelName, [FromBody]ChannelMessagesBindingModel model)
        {
            var dbChannel = this.Data.Channels.All().FirstOrDefault(c => c.Name == channelName);
            if (dbChannel == null)
            {
                return this.NotFound();
            }
            if (model == null)
            {
                return this.BadRequest("Model cannot be null");
            }

            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }
            var currentUserId = User.Identity.GetUserId();
            var currentUser = this.Data.Users.Find(currentUserId);
            var message = new ChannelMessage()
            {
                Text = model.Text,
                DateSent = DateTime.Now,
                Channel = dbChannel,
                Sender = currentUser
            };
            this.Data.ChannelMessages.Add(message);
            this.Data.SaveChanges();
            if (currentUser == null)
            {
                return this.Ok(
                    new
                    {
                        message.Id,
                        Message = "Anonymous message sent successfully to channel " + channelName + "."
                    });
            }
            else
            {
                return this.Ok(
                    new
                    {
                        message.Id,
                        Sender = message.Sender.UserName,
                        Message = "Message sent to channel " + channelName + "."
                    });
            }
        }
		protected virtual void AppendHeaders(ChannelMessage message, IBasicProperties properties)
		{
			var headers = message.Headers;
			headers[RabbitHeaderFormat.FormatWith("appId")] = properties.AppId;
			headers[RabbitHeaderFormat.FormatWith("clusterId")] = properties.ClusterId;
			headers[RabbitHeaderFormat.FormatWith("userId")] = properties.UserId;
			headers[RabbitHeaderFormat.FormatWith("type")] = properties.Type;
			headers[RabbitHeaderFormat.FormatWith("priority")] = properties.Priority.ToString(CultureInfo.InvariantCulture);

			var encoding = Encoding.UTF8;
			foreach (var key in properties.Headers.Keys.Cast<string>())
			{
				var value = properties.Headers[key];
				if (value is int)
					headers[key] = ((int)value).ToString(CultureInfo.InvariantCulture);
				else
					headers[key] = encoding.GetString((byte[])value);
			}
		}
        private void OnMessage(BrokeredMessage message)
        {
            try
            {
                if (OnMessageReceived != null)
                {
                    var headers = ResolveMessageHeaders(message);
                    var bodyStream = message.GetBody<Stream>();
                    var channelMessage = new ChannelMessage(bodyStream);
                    channelMessage.AddHeader(headers);
                    OnMessageReceived(this, new MessageReceivedEventArgs { Message = channelMessage });
                }

                message.Complete();
            }
            catch (Exception ex)
            {
                message.DeadLetter();
                throw;
            }
        }
        public bool JoinChannel (string channel_id, ChannelMessage handler)
        {
            if (!Connected)
            {
                DebugUtils.Log("Not connected. First connect before join a multicast channel.");
                return false;
            }

            lock (channel_lock_)
            {
                if (channels_.ContainsKey(channel_id))
                {
                    DebugUtils.Log("Already joined the channel: {0}", channel_id);
                    return false;
                }

                channels_.Add (channel_id, handler);
            }

            if (encoding_ == FunEncoding.kJson)
            {
                Dictionary<string, object> mcast_msg = new Dictionary<string, object>();
                mcast_msg[kChannelId] = channel_id;
                mcast_msg[kSender] = sender_;
                mcast_msg[kJoin] = true;
                network_.SendMessage(kMulticastMsgType, mcast_msg);
            }
            else
            {
                FunMulticastMessage mcast_msg = new FunMulticastMessage ();
                mcast_msg.channel = channel_id;
                mcast_msg.sender = sender_;
                mcast_msg.join = true;

                FunMessage fun_msg = network_.CreateFunMessage(mcast_msg, MessageType.multicast);
                network_.SendMessage (kMulticastMsgType, fun_msg);
            }

            return true;
        }
Example #16
0
		void Set (jab.Models.Room room)
		{
			this.Name = room.Name;
			this.Id = room.Name;
			this.Topic = room.Topic;
			this.Private = room.Private;
			
			recentMessages = new TaskCompletionSource<IEnumerable<ChannelMessage>>();
			getChannelInfo = new TaskCompletionSource<Channel>();
			Server.Client.GetRoomInfo (this.Id).ContinueWith (task => {
				if (task.Exception != null) {
					getChannelInfo.SetException (task.Exception);
					recentMessages.SetException (task.Exception);
				}
				else {
					this.Topic = task.Result.Topic;
					this.Private = task.Result.Private;
					
					lock (users) {
						this.users.Clear ();
						foreach (var user in from r in task.Result.Users select new JabbRUser (r))
							this.users.Add (user.Id, user);
					}
					lock (owners) {
						this.owners.Clear ();
						this.owners.AddRange (task.Result.Owners);
					}
					var messages = (from m in task.Result.RecentMessages select CreateMessage(m));
					historyLoaded = true;
					if (firstMessage != null) {
						// filter up to the first already received message
						messages = messages.TakeWhile (r => r.When < firstMessage.When || (r.When == firstMessage.When && r.Content != firstMessage.Content));
						firstMessage = null;
					}
					recentMessages.SetResult (messages);
					getChannelInfo.SetResult (this);
				}
			});
		}
Example #17
0
 public async Task LoadRoomInfo()
 {
     try
     {
         var roomInfo = await Server.Client.GetRoomInfo(this.Id);
         this.Topic = roomInfo.Topic;
         this.Private = roomInfo.Private;
 
         lock (users)
         {
             this.users.Clear();
             foreach (var user in from r in roomInfo.Users select new JabbRUser (this.Server, r))
                 this.users.Add(user.Id, user);
         }
         lock (owners)
         {
             this.owners.Clear();
             this.owners.AddRange(roomInfo.Owners);
         }
         IEnumerable<ChannelMessage> messages = (from m in roomInfo.RecentMessages select CreateMessage(m)).ToArray();
         historyLoaded = true;
         if (firstMessage != null)
         {
             // filter up to the first already received message
             messages = messages.TakeWhile(r => r.When < firstMessage.When || (r.When == firstMessage.When && r.Content != firstMessage.Content));
             // must call .ToArray() otherwise firstMessage will be null when this is iterated
             messages = messages.ToArray();
             firstMessage = null;
         }
         recentMessages.SetResult(messages);
         getChannelInfo.SetResult(this);
     }
     catch (Exception ex)
     {
         getChannelInfo.SetException(ex);
         recentMessages.SetException(ex);
     }
     ;
 }
Example #18
0
        public static void WriteMessage(EndpointAddress destination, ChannelMessage channelMessage)
        {
            var queueName = destination.GetQueueName();
            var queuePath = destination.GetQueuePath();

            if (!MessageQueue.Exists(queueName)) throw new Exception($"Destination {destination} does not exist.");

            var destinationQueue = new MessageQueue(queuePath);

            var queueMessage = new Message
            {
                BodyStream = channelMessage.BodyStream,
                Label = channelMessage.Headers.First().Value,
                Extension = ConvertHeaders(channelMessage)
            };

            using (var tx = new MessageQueueTransaction())
            {
                tx.Begin();
                destinationQueue.Send(queueMessage, tx);
                tx.Commit();
            }
        }
		public virtual BasicDeliverEventArgs Build(ChannelMessage message, IBasicProperties properties)
		{
			if (message == null)
				throw new ArgumentNullException("message");

			if (properties == null)
				throw new ArgumentNullException("properties");

			try
			{
				return this.Translate(message, properties);
			}
			catch (SerializationException e)
			{
				Log.Error("Unable to serialize message {0}: {1}", message.MessageId, e.Message);
				throw;
			}
			catch (Exception e)
			{
				Log.Error("General serialization failure for message {0}: {1}", message.MessageId, e.Message);
				throw new SerializationException(e.Message, e);
			}
		}
		protected virtual BasicDeliverEventArgs Translate(ChannelMessage message, IBasicProperties properties)
		{
			var serializer = this.configuration.Serializer;

			properties.MessageId = message.MessageId.ToNull() ?? string.Empty;
			properties.CorrelationId = message.CorrelationId.ToNull() ?? string.Empty;
			properties.AppId = this.configuration.ApplicationId;
			properties.ContentEncoding = serializer.ContentEncoding ?? string.Empty;

			properties.ContentType = string.IsNullOrEmpty(serializer.ContentFormat)
				? ContentType : ContentType + "+" + serializer.ContentFormat;

			properties.SetPersistent(message.Persistent);

			var expiration = message.Expiration;
			properties.Expiration = (expiration == DateTime.MinValue || expiration == DateTime.MaxValue)
				? string.Empty : expiration.ToEpochTime().ToString(CultureInfo.InvariantCulture);

			if (message.ReturnAddress != null)
				properties.ReplyTo = message.ReturnAddress.ToString();

			var messages = (message.Messages ?? new object[0]).ToArray();
			var payload = serializer.Serialize(messages);

			properties.Headers = new Hashtable((IDictionary)message.Headers);
			properties.Type = messages[0].GetType().FullName;
			properties.Timestamp = new AmqpTimestamp(SystemTime.UtcNow.ToEpochTime());

			return new BasicDeliverEventArgs
			{
				Body = payload,
				RoutingKey = this.configuration.LookupRoutingKey(message),
				BasicProperties = properties
			};
		}
Example #21
0
 void UpdateMessage(ChannelMessage msg)
 {
     messageId   = msg.messageId;
     editMessage = msg.message;
     editPopup.SetActive(true);
 }
Example #22
0
 private static void Ccc_OnChannelMessage(ChannelMessage obj)
 {
     Interlocked.Increment(ref cmc);
 }
        private object GetResponseObject(ChannelRequest request)
        {
            ChannelMessage channelMessage = GetChannelMessage(request);

            return(channelMessage.Output);
        }
		private static void SetExpiration(IBasicProperties properties, ChannelMessage message)
		{
			var expiration = message.Expiration;
			if (expiration <= DateTime.MinValue || expiration >= DateTime.MaxValue)
				return;

			var dispatch = message.Dispatched > DateTime.MinValue ? message.Dispatched : SystemTime.UtcNow;
			var ttl = (long)(expiration - dispatch).TotalMilliseconds;
			if (ttl > int.MaxValue)
				return;

			if (ttl < 0)
				ttl = 0;

			properties.Expiration = ttl.ToString(CultureInfo.InvariantCulture);
		}
 private void PrintMessage(IMessageSource src, ChannelMessage msg)
 {
     Root._outErrWriter.PrintMessage(src, msg);
 }
Example #26
0
        /// <summary>
        /// Trace a TLC environment channel message to the trace source
        /// </summary>
        public static void TraceChannelMessage(this ITracer tracer, IMessageSource source, ChannelMessage channelMessage)
        {
            switch (channelMessage.Kind)
            {
            case ChannelMessageKind.Trace:
                tracer.TraceVerbose($"{source?.FullName}:{channelMessage.Message}");
                break;

            case ChannelMessageKind.Info:
                tracer.TraceInformation($"{source?.FullName}:{channelMessage.Message}");
                break;

            case ChannelMessageKind.Warning:
                tracer.TraceWarning($"{source?.FullName}:{channelMessage.Message}");
                break;

            case ChannelMessageKind.Error:
                tracer.TraceError($"{source?.FullName}:{channelMessage.Message}");
                break;
            }
        }
Example #27
0
 private static void Client_OnChannelMessage2(ChannelMessage msg)
 {
     ConsoleHelper.WriteLine("收到频道消息2:{0}", msg.Content);
 }
Example #28
0
 public override void TriggerMessage(ChannelMessage message)
 {
     if (firstMessage == null && !historyLoaded)
         firstMessage = message;
     base.TriggerMessage(message);
 }
 public ChannelMessageEventArgs(ChannelMessage message)
 {
     this.message = message;
 }
Example #30
0
        private void OnChatMessage(string[] data)
        {
            string fullMessage = data[1];

            string[] chatData = fullMessage.Split(':');

            if (fullMessage.Substring(0, 7) == "*GREEN*")
            {
                fullMessage = fullMessage.Substring(7);
            }
            else if (fullMessage.Substring(0, 5) == "*RED*")
            {
                fullMessage = fullMessage.Substring(5);
            }
            else if (fullMessage.Substring(0, 6) == "*BLUE*")
            {
                fullMessage = fullMessage.Substring(6);
            }
            else if (fullMessage.Substring(0, 8) == "*YELLOW*")
            {
                fullMessage = fullMessage.Substring(8);
            }
            else if (fullMessage.Substring(0, 6) == "*CYAN*")
            {
                fullMessage = fullMessage.Substring(6);
            }
            else if (fullMessage.Substring(0, 7) == "*WHITE*")
            {
                fullMessage = fullMessage.Substring(7);
            }
            string message;

            if (chatData.Length <= 1)
            {
                string channelName;

                int start = fullMessage.IndexOf('(') + 1;
                int end   = fullMessage.IndexOf(')');
                channelName = fullMessage.Substring(start, end - start);

                message = fullMessage.Substring(end + 2);

                ChannelSystemMessage?.Invoke(channelName, message);
                return;
            }
            if (chatData[0] != "*GREEN*System")
            {
                string channelName = null;
                string mode        = null;
                string author;

                int start = (fullMessage[0] == '(' ? 1 : 0);
                int end;
                if (start != 0)
                {
                    end         = fullMessage.IndexOf(')');
                    channelName = fullMessage.Substring(start, end - start);
                }
                start = fullMessage.IndexOf('[') + 1;
                if (start != 0 && fullMessage.ToCharArray()[start] != 'n')
                {
                    end  = fullMessage.IndexOf(']');
                    mode = fullMessage.Substring(start, end - start);
                }
                if (channelName == "PM")
                {
                    end = fullMessage.IndexOf(':');
                    string header = fullMessage.Substring(0, end);
                    start  = header.LastIndexOf(' ') + 1;
                    author = header.Substring(start);
                }
                else
                {
                    start  = fullMessage[0] == '(' ? fullMessage.IndexOf(")") + 2 : 0;
                    end    = fullMessage.IndexOf(":");
                    author = fullMessage.Substring(start, end - start);
                }
                start   = fullMessage.IndexOf(':') + 2;
                message = fullMessage.Substring(start == 1 ? 0 : start);
                if (channelName != null)
                {
                    ChannelMessage?.Invoke(channelName, mode, author, message);
                }
                else
                {
                    ChatMessage?.Invoke(mode, author, message);
                }
                return;
            }
            int offset = fullMessage.IndexOf(':') + 2;

            message = fullMessage.Substring(offset == 1 ? 0 : offset);

            SystemMessage?.Invoke(message);
        }
Example #31
0
 public virtual void TriggerMessage(ChannelMessage message)
 {
     UnreadCount++;
     OnMessageReceived(new MessageEventArgs(message));
 }
        public void Send(ChannelMessage message)
        {
            var creds = CredentialsProvider.GetCredentials().ToNetworkCredential();

            Mail_Message msg = new Mail_Message();

            msg.MimeVersion = "1.0";
            msg.MessageID   = MIME_Utils.CreateMessageID();
            msg.Subject     = message.Context;
            msg.From        = message.From.ToMailBoxList();
            msg.ReplyTo     = message.ReturnTo == null?
                              message.From.ToAddressList() : message.ReturnTo.ToAddressList();

            if (String.IsNullOrEmpty(message.InReplyTo) == false)
            {
                msg.InReplyTo = message.InReplyTo;
            }

            msg.To = new Mail_t_AddressList();
            foreach (var address in message.To)
            {
                msg.To.Add(address.ToMailBox());
            }

            msg.Cc = new Mail_t_AddressList();
            foreach (var address in message.CC)
            {
                msg.Cc.Add(address.ToMailBox());
            }

            //--- multipart/mixed -------------------------------------------------------------------------------------------------
            MIME_h_ContentType contentType_multipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed);

            contentType_multipartMixed.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartMixed multipartMixed = new MIME_b_MultipartMixed(contentType_multipartMixed);

            msg.Body = multipartMixed;

            //--- multipart/alternative -----------------------------------------------------------------------------------------
            MIME_Entity        entity_multipartAlternative      = new MIME_Entity();
            MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative);

            contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
            MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative);

            entity_multipartAlternative.Body = multipartAlternative;
            multipartMixed.BodyParts.Add(entity_multipartAlternative);

            //--- text/plain ----------------------------------------------------------------------------------------------------
            MIME_Entity entity_text_plain = new MIME_Entity();
            MIME_b_Text text_plain        = new MIME_b_Text(MIME_MediaTypes.Text.plain);

            entity_text_plain.Body = text_plain;
            // Add text body if there is any
            if (message.BodyText != null && message.BodyText.Length > 0)
            {
                var bodyText = message.BodyText.ReadString();

                // Make sure there is a newline at the end of our text, otherwise it will screw up
                // our multipart data format
                if (!bodyText.EndsWith(Environment.NewLine))
                {
                    bodyText = bodyText + Environment.NewLine;
                }

                text_plain.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyText);
            }

            multipartAlternative.BodyParts.Add(entity_text_plain);

            //--- text/html ------------------------------------------------------------------------------------------------------
            MIME_Entity entity_text_html = new MIME_Entity();
            MIME_b_Text text_html        = new MIME_b_Text(MIME_MediaTypes.Text.html);

            entity_text_html.Body = text_html;
            if (message.BodyHtml != null && message.BodyHtml.Length > 0)
            {
                var bodyHtml = message.BodyHtml.ReadString();

                // Make sure there is a newline at the end of our text, otherwise it will screw up
                // our multipart data format
                if (!bodyHtml.EndsWith(Environment.NewLine))
                {
                    bodyHtml = bodyHtml + Environment.NewLine;
                }

                text_html.SetText(MIME_TransferEncodings.SevenBit, Encoding.UTF8, bodyHtml);
            }

            multipartAlternative.BodyParts.Add(entity_text_html);

            foreach (var channelAttachment in message.Attachments)
            {
                MIME_b_Application attachmentBody = new MIME_b_Application(MIME_MediaTypes.Application.octet_stream);
                MIME_Entity        attachment     = new MIME_Entity();
                attachment.Body = attachmentBody;

                // Has to happen before the following lines of code
                multipartMixed.BodyParts.Add(attachment);

                attachment.ContentType            = new MIME_h_ContentType(MimeHelper.GetMimeType(channelAttachment.Filename));
                attachment.ContentType.Param_Name = channelAttachment.Filename;

                MIME_h_ContentDisposition contentDisposition = new MIME_h_ContentDisposition(DispositionTypeNames.Attachment);
                contentDisposition.Param_FileName = channelAttachment.Filename;

                attachment.ContentDisposition      = contentDisposition;
                attachment.ContentTransferEncoding = TransferEncoding.Base64.ToString();

                attachmentBody.SetData(channelAttachment.ContentStream, MIME_TransferEncodings.Base64);
            }

            // Inject headers
            if (!String.IsNullOrEmpty(message.MessageIdentifier))
            {
                msg.Header.Add(new MIME_h_Unstructured("x-i2mp-messageid", message.MessageIdentifier));
            }

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpFlow))
            //    msg.Header.Add(new MIME_h_Unstructured("x-i2mp-flow", message.Metadata.i2mpFlow));

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpReference))
            //    mailMessage.Headers.Add("X-i2mp-ref", message.Metadata.i2mpReference);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpSequence))
            //    mailMessage.Headers.Add("X-i2mp-seq", message.Metadata.i2mpSequence);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelation))
            //    mailMessage.Headers.Add("X-i2mp-rel", message.Metadata.i2mpRelation);

            //if (!String.IsNullOrEmpty(message.Metadata.i2mpRelationId))
            //    mailMessage.Headers.Add("X-i2mp-rel-id", message.Metadata.i2mpRelationId);


            // Send message
            try
            {
                SMTP_Client client = new SMTP_Client();

                if ("/Settings/Channels/LoggerEnabled".AsKey(false))
                {
                    client.Logger = new LumiSoft.Net.Log.Logger();
                }

                // todo push this logic into the smtp client implementation itself
                if (Hostname == "smtp.live.com")
                {
                    // Hack for hotmail, first do a connect with no secured channel,
                    // then a STARTTLS
                    client.Connect(Hostname, Port, false);
                    client.StartTLS();
                }
                else
                {
                    client.Connect(Hostname, Port, IsSecured);
                }

                client.Authenticate(creds.UserName, creds.Password);

                using (MemoryStream ms = new MemoryStream())
                {
                    client.MailFrom(msg.From[0].Address, -1);

                    msg.ToStream(ms,
                                 new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);

                    // Reset stream
                    ms.Seek(0, SeekOrigin.Begin);

                    foreach (var address in message.To)
                    {
                        client.RcptTo(address.Address);
                    }

                    foreach (var address in message.CC)
                    {
                        client.RcptTo(address.Address);
                    }

                    foreach (var address in message.BCC)
                    {
                        client.RcptTo(address.Address);
                    }

                    try
                    {
                        client.SendMessage(ms);
                    }
                    finally
                    {
                        client.Dispose();
                    }
                }
            }
            catch (SmtpFailedRecipientsException e)
            {
                throw new ChannelFunctionalException(e.Message, e)
                      {
                          DoNotRetry = true
                      };
            }
            catch (SmtpException e)
            {
                throw new ChannelFunctionalException(e.Message, e);
            }
            catch (Exception e)
            {
                throw new ChannelFunctionalException(e.Message, e);
            }
        }
Example #33
0
 public void Publish(ChannelMessage channelMessage)
 {
     throw new NotImplementedException();
 }
Example #34
0
    void Start()
    {
        InitComponents();

        SendBirdClient.ChannelHandler channelHandler = new SendBirdClient.ChannelHandler();
        channelHandler.OnMessageReceived = (BaseChannel channel, BaseMessage message) => {
            // Draw new messages if user is on the channel.
            if (currentChannel.Url == channel.Url)
            {
                if (message is UserMessage)
                {
                    if (channel.IsOpenChannel())
                    {
                        txtOpenChannelContent.text = txtOpenChannelContent.text + (UserMessageRichText((UserMessage)message) + "\n");
                    }
                    else
                    {
                        GameObject objMessage = Instantiate(messageListItemPrefab, editableGridPannel.transform) as GameObject;

                        ChannelMessage msg = objMessage.GetComponent <ChannelMessage>();
                        if (SendBirdClient.CurrentUser.UserId != msg.userId)
                        {
                            objMessage.GetComponent <Button>().enabled = false;
                        }
                        msg.message          = (UserMessageRichText((UserMessage)message));
                        msg.messageId        = message.MessageId;
                        msg.messageText.text = (UserMessageRichText((UserMessage)message));

                        btnMessage.Add(objMessage);
                    }
                }
                else if (message is FileMessage)
                {
                    if (channel.IsOpenChannel())
                    {
                        txtOpenChannelContent.text = txtOpenChannelContent.text + (FileMessageRichText((FileMessage)message) + "\n");
                    }
                    else
                    {
                        txtGroupChannelContent.text = txtGroupChannelContent.text + (FileMessageRichText((FileMessage)message) + "\n");
                    }
                }
                else if (message is AdminMessage)
                {
                    GameObject objMessage = Instantiate(messageListItemPrefab, editableGridPannel.transform) as GameObject;

                    ChannelMessage msg = objMessage.GetComponent <ChannelMessage>();
                    if (SendBirdClient.CurrentUser.UserId != msg.userId)
                    {
                        objMessage.GetComponent <Button>().enabled = false;
                    }
                    msg.message          = (AdminMessageRichText((AdminMessage)message));
                    msg.messageId        = message.MessageId;
                    msg.messageText.text = (AdminMessageRichText((AdminMessage)message));

                    btnMessage.Add(objMessage);
                }

                ScrollToBottom();
            }
        };

        channelHandler.OnUserReceivedInvitation = (GroupChannel channel, User inviter, List <User> invitees) =>
        {
            for (int i = 0; i < invitees.Count; i++)
            {
                if (invitees[i].UserId == SendBirdClient.CurrentUser.UserId)
                {
                    // to do
                }
            }
        };

        channelHandler.OnMessageUpdated = (BaseChannel channel, BaseMessage message) =>
        {
            if (currentChannel.Url == channel.Url)
            {
                if (channel.IsGroupChannel())
                {
                    for (int i = 0; i < btnMessage.Count; i++)
                    {
                        GameObject     objMessage = btnMessage[i] as GameObject;
                        ChannelMessage msg        = objMessage.GetComponent <ChannelMessage>();
                        if (message is UserMessage)
                        {
                            if (msg.messageId == message.MessageId)
                            {
                                if (SendBirdClient.CurrentUser.UserId != msg.userId)
                                {
                                    objMessage.GetComponent <Button>().enabled = false;
                                }
                                msg.message          = ((UserMessage)message).Message;
                                msg.messageId        = message.MessageId;
                                msg.messageText.text = (UserMessageRichText((UserMessage)message));
                            }
                        }
                        else if (message is AdminMessage)
                        {
                            if (msg.messageId == message.MessageId)
                            {
                                objMessage.GetComponent <Button>().enabled = false;
                                msg.message          = ((AdminMessage)message).Message;
                                msg.messageId        = message.MessageId;
                                msg.messageText.text = (AdminMessageRichText((AdminMessage)message));
                            }
                        }
                    }
                }
                else
                {
                    LoadOpenChannelChatHistory();
                }
            }
        };

        SendBirdClient.AddChannelHandler("default", channelHandler);
    }
Example #35
0
        public void MessageReceived(ChannelMessage msg)
        {
            switch (msg.Type)
            {
            default:
                Log("Unknown message: " + msg);
                break;

            case MessageType.HelloResponse:
            {
                var response = (HelloResponse)msg;
                if (!SeenHello)
                {
                    SeenHello = true;
                    Log(response.MachineName + " connected to " + Environment.MachineName);
                    OnConnected(response.MachineName);
                }
            }
            break;

            case MessageType.ListenResponse:
            {
                var            response = (ListenResponse)msg;
                ClientListener listener = null;
                lock (clientListeners)
                {
                    if (clientListeners.ContainsKey(response.ListenIndex))
                    {
                        listener = clientListeners[response.ListenIndex];
                    }
                }
                if (listener != null)
                {
                    listener.ListenResponse(response);
                }
            }
            break;

            case MessageType.AcceptRequest:
            {
                var            request  = (AcceptRequest)msg;
                ClientListener listener = null;
                lock (clientListeners)
                {
                    if (clientListeners.ContainsKey(request.ListenIndex))
                    {
                        listener = clientListeners[request.ListenIndex];
                    }
                }
                if (listener != null)
                {
                    listener.AcceptRequest(request);
                }
            }
            break;

            case MessageType.ConnectResponse:
                ((ConnectResponse)msg).Process(this);
                break;

            case MessageType.StreamData:
                ((StreamData)msg).Process(this);
                break;

            case MessageType.StreamError:
            {
                var            error    = (StreamError)msg;
                ClientListener listener = null;
                lock (clientListeners)
                {
                    if (clientListeners.ContainsKey(error.StreamIndex))
                    {
                        listener = clientListeners[error.StreamIndex];
                    }
                }
                if (listener != null)
                {
                    listener.StreamError(error);
                }
                else
                {
                    ((StreamError)msg).Process(this);
                }
            }
            break;
            }
        }
Example #36
0
    void LoadGroupChannelPreviousChatHistory()
    {
        PreviousMessageListQuery query = currentChannel.CreatePreviousMessageListQuery();

        ResetGroupChannelContent();
        query.Load(15, false, (List <BaseMessage> queryResult, SendBirdException e) => {
            if (e != null)
            {
                Debug.Log(e.Code + ": " + e.Message);
                return;
            }

            ChannelMessage msg = null;

            foreach (BaseMessage message in queryResult)
            {
                GameObject objMessage = Instantiate(messageListItemPrefab, editableGridPannel.transform) as GameObject;
                msg = objMessage.GetComponent <ChannelMessage>();

                if (message is UserMessage)
                {
                    msg.message          = ((UserMessage)message).Message;
                    msg.userId           = message.UserId;
                    msg.messageId        = message.MessageId;
                    msg.messageText.text = (UserMessageRichText((UserMessage)message));
                    if (SendBirdClient.CurrentUser.UserId == msg.userId)
                    {
                        objMessage.GetComponent <Button>().enabled = true;
                    }

                    btnMessage.Add(objMessage);
                }
                else if (message is FileMessage)
                {
                    msg.message          = ((FileMessage)message).Name;
                    msg.messageId        = message.MessageId;
                    msg.messageText.text = (FileMessageRichText((FileMessage)message));
                    if (SendBirdClient.CurrentUser.UserId == msg.userId)
                    {
                        objMessage.GetComponent <Button>().enabled = true;
                    }

                    btnMessage.Add(objMessage);
                }
                else if (message is AdminMessage)
                {
                    msg.message          = ((AdminMessage)message).Message;
                    msg.messageId        = message.MessageId;
                    msg.messageText.text = (AdminMessageRichText((AdminMessage)message));
                    if (SendBirdClient.CurrentUser.UserId == msg.userId)
                    {
                        objMessage.GetComponent <Button>().enabled = true;
                    }

                    btnMessage.Add(objMessage);
                }

                objMessage.GetComponent <Button>().onClick.AddListener(() =>
                {
                    msg = objMessage.GetComponent <ChannelMessage>();
                    UpdateMessage(msg);
                });
            }
        });
    }
Example #37
0
 protected virtual void ChannelMessageReceived(ChannelMessage message)
 {
 }
Example #38
0
 public void Send(EndpointAddress destination, ChannelMessage channelMessage)
 {
     throw new NotImplementedException();
 }
		protected static ChannelEnvelope BuildEnvelope(object message, params Uri[] recipients)
		{
			if (recipients == null || recipients.Length == 0)
				recipients = new[] { new Uri("direct://default/" + DefaultReceiverInputQueue) };

			var channelMessage = new ChannelMessage(
				Guid.NewGuid(), Guid.NewGuid(), null, null, new[] { message });
			return new ChannelEnvelope(channelMessage, recipients);
		}
Example #40
0
 public ChannelMessage CreateMessage(jab.Models.Message m)
 {
     var content = m.Content;
     if (!m.HtmlEncoded)
         content = ParseContent(content);
     var message = new ChannelMessage(m.Id, m.When, m.User.Name, content);
     message.DetectHighlights(Server.HighlightRegex);
     return message;
 }
Example #41
0
 public virtual void TriggerMessage(ChannelMessage message)
 {
     UnreadCount ++;
     OnMessageReceived(new MessageEventArgs(message));
 }
Example #42
0
 public void Send(ChannelMessage message)
 {
     if(message.Command == ChannelCommand.NoteOn &&
         message.Data1 >= LowNoteID && message.Data1 <= HighNoteID)
     {
         if(InvokeRequired)
         {
             BeginInvoke(noteOnCallback, message);
         }
         else
         {
             noteOnCallback(message);
         }
     }
     else if(message.Command == ChannelCommand.NoteOff &&
         message.Data1 >= LowNoteID && message.Data1 <= HighNoteID)
     {
         if(InvokeRequired)
         {
             BeginInvoke(noteOffCallback, message);
         }
         else
         {
             noteOffCallback(message);
         }
     }
 }
		protected virtual BasicDeliverEventArgs Translate(ChannelMessage message, IBasicProperties properties)
		{
			var serializer = this.configuration.Serializer;

			properties.MessageId = message.MessageId.ToNull() ?? string.Empty;
			properties.CorrelationId = message.CorrelationId.ToNull() ?? string.Empty;
			properties.AppId = this.configuration.ApplicationId;
			properties.ContentEncoding = serializer.ContentEncoding ?? string.Empty;

			properties.ContentType = string.IsNullOrEmpty(serializer.ContentFormat)
				? ContentType : ContentType + "+" + serializer.ContentFormat;

			properties.SetPersistent(message.Persistent);
			SetExpiration(properties, message);

			if (message.ReturnAddress != null)
				properties.ReplyTo = message.ReturnAddress.ToString();

			var messages = (message.Messages ?? new object[0]).ToArray();
			var payload = messages.Length > 1 ? serializer.Serialize(messages) : serializer.Serialize(messages[0]);
			properties.Headers = new Dictionary<string, object>(message.Headers.Count);
			foreach (var item in message.Headers)
				properties.Headers[item.Key] = item.Value;

			var type = messages[0].GetType();
			properties.Type = MessageTypeFormat.FormatWith(type.FullName, type.Assembly.GetName().Name);
			properties.Timestamp = new AmqpTimestamp(SystemTime.UtcNow.ToEpochTime());

			return new BasicDeliverEventArgs
			{
				Body = payload,
				RoutingKey = this.configuration.LookupRoutingKey(message),
				BasicProperties = properties
			};
		}
    public void setUnpinched()
    {
        ChannelMessage message = new ChannelMessage(ChannelCommand.NoteOff, 0, activeSwitch.channelGroup + offset + 2, 127);

        outputDevice.Send(message);
    }
Example #45
0
        private void importMIDIToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (importDlg.ShowDialog(this)
                == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            List <PNote> notes   = new List <PNote>();
            PNote        curNote = PNote.Default;
            float        tempo   = 1;
            float        timeSig = 4f;

            // first, we pull midi data
            Sequence s = new Sequence(importDlg.FileName);

            // quickly see if there's a piano track first
            // and get the tempo as well
            int piano = -1;

            for (int it = 0; it < s.Count; it++)
            {
                Track t = s[it];
                foreach (MidiEvent me in t.Iterator())
                {
                    switch (me.MidiMessage.MessageType)
                    {
                    case MessageType.Channel:
                    {
                        ChannelMessage m = (ChannelMessage)me.MidiMessage;
                        if (m.Command == ChannelCommand.ProgramChange)
                        {
                            if ((GeneralMidiInstrument)m.Data1 == GeneralMidiInstrument.AcousticGrandPiano)
                            {
                                piano = it;
                            }
                        }
                    }
                    break;

                    case MessageType.Meta:
                    {
                        MetaMessage m = (MetaMessage)me.MidiMessage;
                        if (m.MetaType == MetaType.Tempo)
                        {
                            tempo = (new TempoChangeBuilder(m)).Tempo;
                        }
                        else if (m.MetaType == MetaType.TimeSignature)
                        {
                            timeSig = new TimeSignatureBuilder(m).Denominator;
                        }
                    }
                    break;
                    }
                    if (piano >= 0)
                    {
                        break;
                    }
                }
                if (piano >= 0)
                {
                    break;
                }
            }

            // didn't find one, so just try 0th track anyway
            if (piano == -1)
            {
                piano = 0;
            }

            // now, pull all notes (and tempo)
            // and make sure it's a channel that has content
            for (int it = piano; it < s.Count; it++)
            {
                Track t = s[it];

                int delta = 0;
                foreach (MidiEvent me in t.Iterator())
                {
                    delta += me.DeltaTicks;

                    switch (me.MidiMessage.MessageType)
                    {
                    case MessageType.Channel:
                    {
                        ChannelMessage m = (ChannelMessage)me.MidiMessage;
                        switch (m.Command)
                        {
                        case ChannelCommand.NoteOn:
                            if (curNote.Note != "")
                            {
                                curNote.Length = delta / 1000F;
                                delta          = 0;
                                notes.Add(curNote);
                            }

                            curNote.Note = note2Piano(m.Data1);
                            break;
                        }
                    }
                    break;

                    case MessageType.Meta:
                    {
                        MetaMessage m = (MetaMessage)me.MidiMessage;
                        if (m.MetaType == MetaType.Tempo)
                        {
                            tempo = (new TempoChangeBuilder(m)).Tempo;
                        }
                    }
                    break;
                    }
                }

                // make sure we get last note
                if (curNote.Note != "")
                {
                    curNote.Length = delta / 1000F;
                    notes.Add(curNote);
                }

                // we found a track with content!
                if (notes.Count > 0)
                {
                    break;
                }
            }

            // compress redundant accidentals/octaves
            char[] notemods = new char[7];
            int[]  noteocts = new int[7];
            for (int i = 0; i < 7; i++)
            {
                notemods[i] = 'n';
                noteocts[i] = 3;
            }
            for (int i = 0; i < notes.Count; i++)
            {
                string noteStr  = notes[i].Note;
                int    cur_note = noteStr[0] - 0x41;
                char   mod      = noteStr[1];
                int    oct      = int.Parse(noteStr.Substring(2));

                noteStr = noteStr.Substring(0, 1);
                if (mod != notemods[cur_note])
                {
                    noteStr           += new string(mod, 1);
                    notemods[cur_note] = mod;
                }
                if (oct != noteocts[cur_note])
                {
                    noteStr           += oct.ToString();
                    noteocts[cur_note] = oct;
                }

                notes[i] = new PNote(notes[i].Length, noteStr);
            }

            // now, we find what the "beat" length should be,
            // by counting numbers of times for each length, and finding statistical mode
            Dictionary <float, int> scores = new Dictionary <float, int>();

            foreach (PNote n in notes)
            {
                if (n.Length != 0)
                {
                    if (scores.Keys.Contains(n.Length))
                    {
                        scores[n.Length]++;
                    }
                    else
                    {
                        scores.Add(n.Length, 1);
                    }
                }
            }
            float winner = 1;
            int   score  = 0;

            foreach (KeyValuePair <float, int> kv in scores)
            {
                if (kv.Value > score)
                {
                    winner = kv.Key;
                    score  = kv.Value;
                }
            }
            // realign all of them to match beat length
            for (int i = 0; i < notes.Count; i++)
            {
                notes[i] = new PNote(notes[i].Length / winner, notes[i].Note);
            }

            // compress chords down
            for (int i = 0; i < notes.Count; i++)
            {
                if (notes[i].Length == 0 && i < notes.Count - 1)
                {
                    notes[i + 1] = new PNote(notes[i + 1].Length, notes[i].Note + "-" + notes[i + 1].Note);
                    notes.RemoveAt(i);
                    i--;
                }
            }

            // add in time
            for (int i = 0; i < notes.Count; i++)
            {
                float len = notes[i].Length;
                notes[i] = new PNote(len, notes[i].Note + (len != 1 ? "/" + (1 / len).ToString("0.##") : ""));
            }

            // what is the bpm, anyway?
            int rpm = (int)(28800000 / tempo / winner); // 60 * 1,000,000 * .48  the .48 is because note lengths for some reason midi makes the beat note be .48 long

            // now, output!
            string line      = "";
            string output    = "";
            int    lineCount = 1;

            foreach (PNote n in notes)
            {
                if (line.Length + n.Note.Length + 1 > 51)
                {
                    output += line.Substring(0, line.Length - 1) + "\r\n";
                    line    = "";
                    if (lineCount == 350)
                    {
                        break;
                    }
                    lineCount++;
                }
                line += n.Note + ",";
            }
            if (line.Length > 0)
            {
                output += line.Substring(0, line.Length - 1);
            }
            OutputTxt.Text = "BPM: " + rpm.ToString() + "\r\n" + output;
            OutputTxt.SelectAll();
        }