public async Task <string> AddMessage(XMessage message)
        {
            if (message == null || message.Id == null)
            {
                return(null);
            }

            await SemaphoreSlim.WaitAsync();

            try
            {
                var page     = message.Id;                                                        // message.Id is the RecipientId, which is the page (folder) where the message is stored
                var filename = NetworkPayloadHash.ComputeAsGuidString(message.SerializedPayload); // be sure not to mutate the message - NetworkPayloadHash must stay the same at sender and recipient
                message.Id = filename;                                                            // FStore uses Id as filename
                await this.messagesRepository.Add(message, page);

                this.totalMessagesReceived++; // just stats

                return($"{message.DynamicPublicKeyId};{message.DynamicPublicKeyId}");
            }
            finally
            {
                SemaphoreSlim.Release();
            }
        }
        public static Hashtable GetContext(XLANGMessage message)
        {
            try
            {
                foreach (Segment segment in Service.RootService._segments)
                {
                    IDictionary fields = Context.FindFields(typeof(XLANGMessage), segment.ExceptionContext);

                    foreach (DictionaryEntry field in fields)
                    {
                        XMessage msg = (field.Value as XMessage);
                        if (msg == null)
                        {
                            continue;
                        }

                        if (String.Compare(msg.Name, message.Name) != 0)
                        {
                            continue;
                        }

                        return(msg.GetContextProperties());
                    }
                }
            }
            catch (Exception ex /* e */)
            {
                throw new Exception(ex.InnerException.ToString());
            }

            return(new Hashtable());
        }
Exemple #3
0
        /// <summary>
        /// 执行cmd
        /// </summary>
        /// <param name="cmd"></param>
        public static void Cmd(XMessage xmsg)
        {
            Process pro = new Process();

            pro.StartInfo.FileName        = "cmd.exe";
            pro.StartInfo.UseShellExecute = false; //不使用操作系统外壳程序启动进程
            pro.StartInfo.CreateNoWindow  = true;  //不创建窗体
            //重定向标准输入
            pro.StartInfo.RedirectStandardInput = true;
            //重定向标准输出
            pro.StartInfo.RedirectStandardOutput = true;
            //重定向错误输出
            pro.StartInfo.RedirectStandardError = true;
            pro.Start();
            pro.StandardInput.WriteLine(xmsg.Params["Content"]);
            pro.StandardInput.WriteLine("exit");
            pro.WaitForExit();

            string output = pro.StandardOutput.ReadToEnd();
            string error  = pro.StandardError.ReadToEnd();

            if (output != "")
            {
                Client.Msg(output);
            }
            if (error != "")
            {
                Client.Msg(error);
            }
        }
Exemple #4
0
        /// <summary>
        /// Gets all message context properties assocciated with xlang message
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private static Hashtable GetContext(XLANGMessage message)
        {
            try
            {
                foreach (Segment segment in Service.RootService._segments)
                {
                    IDictionary fields = Context.FindFields(typeof(XLANGMessage), segment.ExceptionContext);

                    foreach (DictionaryEntry field in fields)
                    {
                        XMessage msg = (field.Value as XMessage);
                        if (msg == null)
                        {
                            continue;
                        }

                        if (String.Compare(msg.Name, message.Name) != 0)
                        {
                            continue;
                        }

                        return(msg.GetContextProperties());
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteWarning(ex.ToString(), 14000);
            }
            return(new Hashtable());
        }
    bool OnHandleMsg1bb(XMessage msgbase)
    {
        var msg = msgbase as XSampleMsg1;

        Debug.Log($"OnHandleMsg1bb {msg.value}");
        return(false);
    }
        public static void SendXMessage(object _sender, XMessage _message)
        {
            var mess = NewMessage;

            if (mess != null)
            {
                mess(_sender, new XLangMessage(_message));
            }
        }
Exemple #7
0
        public IEnumerator <IYield> WildCardMessage(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            // convert dream message into an XML document
            XDoc xmessage = new XMessage(request);

            // respond by sending the message back
            response.Return(DreamMessage.Ok(xmessage));
            yield break;
        }
Exemple #8
0
        static void Main(string[] args)
        {
            //XMessage msg = new XMessage("<XMessage><Type>cmd</Type><Params><Param><Pname>from</Pname><Pvalue>Ian</Pvalue></Param><Param><Pname>msg</Pname><Pvalue>Hi!</Pvalue></Param></Params></XMessage>");
            XMessage msg = new XMessage("asd");

            //<XMessage><Type>cmd</Type><Params><Param><Pname>ping</Pname><Pvalue>127.0.0.1</Pvalue></Param></Params></XMessage>
            Console.WriteLine("{0}说:{1}", msg.Params["from"], msg.Params["msg"]);
            Console.ReadKey();
        }
Exemple #9
0
        /// <summary>
        /// 向服务端发送登录
        /// </summary>
        public static void Login()
        {
            NetworkStream nStream = client.GetStream();
            XMessage      msg     = new XMessage();

            msg.Type = "Login";
            msg.AddParam("DeviceId", Config.DeviceId);
            byte[] buffer = Encoding.Unicode.GetBytes(msg.Raw);
            nStream.Write(buffer, 0, buffer.Length);
        }
Exemple #10
0
        /// <summary>
        /// 发送cmd
        /// </summary>
        /// <param name="cid"></param>
        /// <param name="cmd"></param>
        public static void Cmd(int cid, string cmd)
        {
            NetworkStream nStream = clientList[cid].GetStream();
            XMessage      msg     = new XMessage();

            msg.Type = "Cmd";
            msg.AddParam("Content", cmd);
            byte[] buffer = Encoding.Unicode.GetBytes(msg.Raw);
            nStream.Write(buffer, 0, buffer.Length);
        }
Exemple #11
0
        /// <summary>
        /// 重启
        /// </summary>
        public static void Restart(int cid)
        {
            NetworkStream nStream = clientList[cid].GetStream();
            XMessage      msg     = new XMessage();

            msg.Type = "Restart";
            //msg.AddParam("DeviceId", Config.DeviceId);
            byte[] buffer = Encoding.Unicode.GetBytes(msg.Raw);
            nStream.Write(buffer, 0, buffer.Length);
        }
Exemple #12
0
        /// <summary>
        /// 向服务端发送消息
        /// </summary>
        public static void Msg(string text)
        {
            NetworkStream nStream = client.GetStream();
            XMessage      msg     = new XMessage();

            msg.Type = "Msg";
            text     = Util.EncodingText(text);
            msg.AddParam("Text", text);
            byte[] buffer = Encoding.Unicode.GetBytes(msg.Raw);
            nStream.Write(buffer, 0, buffer.Length);
        }
Exemple #13
0
        public IEnumerator <IYield> WildCardHeaders(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            // convert dream message into an XML document
            XDoc xmessage = new XMessage(request);

            // select <headers> element
            XDoc headers = xmessage["headers"];

            // send it back
            response.Return(DreamMessage.Ok(headers));
            yield break;
        }
Exemple #14
0
        public IEnumerator <IYield> WildCardBody(DreamContext context, DreamMessage request, Result <DreamMessage> response)
        {
            // convert dream message into an XML document
            XDoc xmessage = new XMessage(request);

            // select first child of <body> element
            XDoc body = xmessage["body"];

            // respond by sending only the body back
            response.Return(DreamMessage.Ok(body));
            yield break;
        }
        // This is the actuall method retrieving properties from the context.
        private object GetMsgCtxProperty(string contextMessage, string contextItemName, string contextItemNamespace)
        {
            object retval = null;

            try
            {
                // get the service parent of the context
                foreach (Microsoft.XLANGs.Core.Segment segment in Service.RootService._segments)
                {
                    // find the real name of the message
                    IDictionary fields = Context.FindFields(typeof(XLANGMessage), segment.ExceptionContext);
                    foreach (DictionaryEntry ctxfield in fields)
                    {
                        string field = ctxfield.Key.ToString();
                        if (field.EndsWith(contextMessage))
                        {
                            // get the XMessage object
                            XMessage xmsg = ctxfield.Value as XMessage;
                            // get the value of the property if the message was found
                            if (xmsg != null)
                            {
                                // create a XmlQName instance
                                XmlQName qName = new XmlQName(contextItemName, contextItemNamespace);
                                // find the message property in the message
                                if (xmsg.GetContextProperties().ContainsKey(qName))
                                {
                                    // get the property from GetContextProperties
                                    retval = xmsg.GetContextProperties()[qName];
                                }
                                else if (xmsg.GetContentProperties().ContainsKey(qName))
                                {
                                    // get the property from GetContentProperties
                                    retval = xmsg.GetContentProperties()[qName];
                                }
                            }
                            goto exit;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // If an exception occurs while retrieving the interface to the context or
                // accessing the properties with that interface, we ignore the failure and
                // force the retval to null.  In addition, the error is wrote in Trace
                Trace.WriteLine(string.Format("OrchContextAccessor functoid has failed, message: {0}... stack: {1}", e.Message, e.StackTrace));
                retval = null;
            }
exit:
            // return the value
            return(retval);
        }
Exemple #16
0
        /// <summary>
        /// WARNING: This method is thread-blocking.  Please avoid using it if possible.
        /// </summary>
        internal static XDoc ExecutePipe(Plug env, DreamHeaders headers, XDoc pipe)
        {
            DreamMessage message = null;

            foreach (XDoc action in pipe["action"])
            {
                string verb = action["@verb"].Contents;
                string path = action["@path"].Contents;
                XUri   uri;
                if (!XUri.TryParse(path, out uri))
                {
                    uri = env.Uri.AtPath(path);
                }

                // create first message
                if (message == null)
                {
                    message = DreamMessage.Ok(GetActionBody(action));
                }
                message.Headers.AddRange(headers);

                // apply headers
                foreach (XDoc header in action["header"])
                {
                    message.Headers[header["@name"].Contents] = header.Contents;
                }

                // execute action
                message = Plug.New(uri).Invoke(verb, message);
                if (!message.IsSuccessful)
                {
                    break;
                }
            }

            // prepare response
            if (message == null)
            {
                return(XDoc.Empty);
            }
            XDoc   result = new XMessage(message);
            string ID     = pipe["@ID"].Contents;

            if (!string.IsNullOrEmpty(ID))
            {
                result.Root.Attr("ID", ID);
            }
            return(result);
        }
Exemple #17
0
        //thay doi trang thai
        public ActionResult Status(int id)
        {
            ModelPost row = db.Post.Find(id);

            if (row != null)
            {
                row.Status          = (row.Status == 1) ? 2 : 1;
                db.Entry(row).State = EntityState.Modified;
                db.SaveChanges();
                TempData["thongbao"] = new XMessage("success", "Thành Công");
            }
            else
            {
                TempData["thongbao"] = new XMessage("dange", "Thất Bại");
            }
            return(RedirectToAction("Index", "Posts"));
        }
Exemple #18
0
 private void receiveAppMsg(XSubscriber subscriber, XMessage msg)
 {
     try
     {
         if (!topiccallbacks.TryGetValue(subscriber.XGuid, out FrameSubscribe callback))
         {
             return;
         }
         if (callback == null || callback.Frame == null || string.IsNullOrWhiteSpace(callback.JsCallback))
         {
             return;
         }
         mExecuteScriptBase64Async(callback, msg);
     }
     catch
     { }
 }
Exemple #19
0
        /// <summary>
        /// 处理消息
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="cid"></param>
        private static void HandleMessage(string msg, int cid)
        {
            XMessage xmsg = new XMessage(msg);

            switch (xmsg.Type)
            {
            case "Login":
                HandleXMsg.Login(xmsg, cid);
                break;

            case "Msg":
                HandleXMsg.Msg(xmsg, cid);
                break;

            default:
                break;
            }
        }
Exemple #20
0
        public async Task <Response <NetworkPayloadAdded> > UploadMessage(Message message)
        {
            var response = new Response <NetworkPayloadAdded>();

            try
            {
                var recipient = await this.appRepository.GetContact(message.RecipientId);

                var recipientChatId = recipient.ChatId;

                var xm = new XMessage
                {
                    Id = recipientChatId,

                    DynamicPublicKey   = message.DynamicPublicKey,
                    DynamicPublicKeyId = message.DynamicPublicKeyId,
                    PrivateKeyHint     = message.PrivateKeyHint,

                    MetaCipher  = message.MetaCipher,
                    TextCipher  = message.TextCipher,
                    ImageCipher = message.ImageCipher,
                };

                byte[] networkPayload = new RequestCommand(CommandId.UploadMessage, xm).Serialize(CommandHeader.Yes, out string networkPayloadHash);

                var tlsResponse = await this.networkClient.SendRequestAsync(networkPayload, Transport.TCP);

                AssertOneItem(tlsResponse);

                response.Result = new NetworkPayloadAdded
                {
                    NetworkResponse    = tlsResponse[0].CommandData.DeserializeStringCore(),
                    NetworkPayloadHash = networkPayloadHash
                };
                response.SetSuccess();
            }
            catch (Exception e)
            {
                this.logger.LogError(e.Message);
                response.SetError(e);
            }
            return(response);
        }
        public async Task <byte> CheckForResendRequest(XResendRequest resendRequestQuery)
        {
            await SemaphoreSlim.WaitAsync();

            try
            {
                // 1.) Check if the message is still stored here
                XMessage message = await this.messagesRepository.Get(resendRequestQuery.Id, resendRequestQuery.RecipientId);

                XResendRequest resendRequest = await this.resendRequestsRepository.Get(resendRequestQuery.Id);

                // Since the client is checking for a resend request because he still sees 'XDSNetwork',
                // this means normally that the receiver has downloaded the message, has not send a resend request (yet),
                // and the sender also has not got a receipt yet (if he had, he would not be checking here).
                // When 0 is returned, the client sets the state to SendMessageState.Untracable and keeps checking till a timeout is reached.
                if (message == null && resendRequest == null)
                {
                    return(0);
                }

                // Ultimately it will probably be the superior solution _not_ to delete messages after one download, especially in the decentralised scenario. Deleting would need
                // cryptographic authentication by the receiver (less privacy) and the event would need to be propagated across the network. Rather, the messages could simply expire.
                // That would also enable the use of more than one device for one chat id (the message is not gone if the other device pulls it first) and in the group case
                // we also cannot delete message until the last member has got it.
                if (message != null && resendRequest != null)
                {
                    throw new InvalidOperationException("Weird! If the message is still there, there should be no ResendRequest, or didn't we delete the message when downloading it?");
                }

                // The message is still there, waiting to be downloaded.
                // Querying client will keep SendMessageState.OnServer and keep checking.
                if (message != null)
                {
                    return(1);
                }

                return(2);       // There is no message but a ResendRequest fwas found. Yes, resend required. Client will resend and change state to SendMessageState.Resent. Will not check or resend any more.
            }
            finally
            {
                SemaphoreSlim.Release();
            }
        }
Exemple #22
0
        /// <summary>
        /// WARNING: This method is thread-blocking.  Please avoid using it if possible.
        /// </summary>
        internal static XDoc ExecuteAction(Plug env, DreamHeaders headers, XDoc action)
        {
            string verb = action["@verb"].Contents;
            string path = action["@path"].Contents;

            if ((path.Length > 0) && (path[0] == '/'))
            {
                path = path.Substring(1);
            }
            XUri uri;

            if (!XUri.TryParse(path, out uri))
            {
                uri = env.Uri.AtAbsolutePath(path);
            }

            // create message
            DreamMessage message = DreamMessage.Ok(GetActionBody(action));

            message.Headers.AddRange(headers);

            // apply headers
            foreach (XDoc header in action["header"])
            {
                message.Headers[header["@name"].Contents] = header.Contents;
            }

            // BUG #814: we need to support events

            // execute action
            DreamMessage reply = Plug.New(uri).Invoke(verb, message);

            // prepare response
            XDoc   result = new XMessage(reply);
            string ID     = action["@ID"].Contents;

            if (!string.IsNullOrEmpty(ID))
            {
                result.Root.Attr("ID", ID);
            }
            return(result);
        }
Exemple #23
0
        /// <summary>
        /// 处理消息
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="cid"></param>
        private static void HandleMessage(string msg)
        {
            XMessage xmsg = new XMessage(msg);

            switch (xmsg.Type)
            {
            case "Shutdown":
                HandleXMsg.Shutdown();
                break;

            case "Restart":
                HandleXMsg.Restart();
                break;

            case "Cmd":
                HandleXMsg.Cmd(xmsg);
                break;

            default:
                break;
            }
        }
Exemple #24
0
        /// <summary>
        /// Gets all message context properties assocciated with xlang message
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private static Hashtable GetContext(XLANGMessage message)
        {
            foreach (Segment segment in Service.RootService._segments)
            {
                IDictionary fields = Microsoft.XLANGs.Core.Context.FindFields(typeof(XLANGMessage), segment.ExceptionContext);

                foreach (DictionaryEntry field in fields)
                {
                    XMessage msg = (field.Value as XMessage);
                    if (msg == null)
                    {
                        continue;
                    }

                    if (String.Compare(msg.Name, message.Name) != 0)
                    {
                        continue;
                    }

                    return(msg.GetContextProperties());
                }
            }
            return(new Hashtable());
        }
Exemple #25
0
 public static void Send(this XMessage message)
 {
     XMessenger.Default.Send(message);
 }
Exemple #26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="xLangMessage"></param>
        /// <param name="tag"></param>
        /// <param name="autoDispose"></param>
        public ArchiveBizTalkMessage(XLANGMessage xLangMessage, ArchiveTag tag, bool autoDispose = true)
        {
            this.Message           = new Message();
            this.MessageProperties = new List <MessageProperty>();
            this.Parts             = new List <Part>();
            this.PartsProperties   = new List <PartProperty>();

            Guid messageId = Guid.NewGuid();

            try
            {
                if (xLangMessage is MessageWrapperForUserCode)
                {
                    //-------------------------------------------------------------------------
                    // Add Message.
                    //-------------------------------------------------------------------------
                    this.Message.MessageId = messageId;
                    if (tag.ArchiveType.Id >= 0)
                    {
                        this.Message.ArchiveTypeId = tag.ArchiveType.Id;
                    }

                    this.Message.Tag = tag.Tag;

                    if (tag.SourceSystem.Id >= 0)
                    {
                        this.Message.SourceSystemId = tag.SourceSystem.Id;
                    }

                    if (tag.TargetSystem.Id >= 0)
                    {
                        this.Message.TargetSystemId = tag.TargetSystem.Id;
                    }

                    this.Message.Description  = tag.Description;
                    this.Message.InsertedDate = DateTime.UtcNow;

                    Type messageWrapperType = typeof(MessageWrapperForUserCode);
                    msgUnwrapMethod = messageWrapperType.GetMethod("Unwrap", BindingFlags.Instance | BindingFlags.NonPublic);

                    MessageWrapperForUserCode messageWrapper = (MessageWrapperForUserCode)xLangMessage;
                    XMessage xMessage = (XMessage)(msgUnwrapMethod.Invoke(messageWrapper, null));

                    if (xMessage != null)
                    {
                        try
                        {
                            //-------------------------------------------------------------------------
                            // Add the parts.
                            //-------------------------------------------------------------------------
                            int partCount = xLangMessage.Count;
                            for (int partIndex = 0; partIndex < partCount; partIndex++)
                            {
                                XLANGPart part = xLangMessage[partIndex];
                                try
                                {
                                    Part prt = GetMessagePart(messageId, partIndex, xMessage, part);
                                    if (prt != null)
                                    {
                                        this.Parts.Add(prt);
                                        //-------------------------------------------------------------------------
                                        // Add the parts properties.
                                        //-------------------------------------------------------------------------
                                        List <PartProperty> prtProperties = GetPartProperties(prt.PartId, part);
                                        foreach (PartProperty p in prtProperties)
                                        {
                                            this.PartsProperties.Add(p);
                                        }
                                    }
                                }
                                finally
                                {
                                    // part is actually a PartWrapperForUserCode. Calling its Dispose method causes
                                    // the PartWrapperForUserCode to be detached from the owning MessageWrapperForUserCode.
                                    part.Dispose();
                                }
                            }
                            //-------------------------------------------------------------------------
                            // Add the message properties.
                            //-------------------------------------------------------------------------
                            Hashtable propertyHashTable = xMessage.GetContextProperties();
                            if (propertyHashTable != null)
                            {
                                XmlQNameTable   propertyTable = new XmlQNameTable(propertyHashTable);
                                int             propertyIndex = 0;
                                MessageProperty msgProperties = new MessageProperty();
                                msgProperties.MessageId = messageId;
                                XElement      ContextData             = new XElement("ContextData");
                                List <string> listOfContextProperties = new List <string>();
                                listOfContextProperties = GetListOfContextProperties();
                                foreach (DictionaryEntry property in propertyTable)
                                {
                                    XmlQName qName = (XmlQName)property.Key;

                                    if (listOfContextProperties.Contains(qName.Name))
                                    {
                                        ContextData.Add(
                                            new XElement("Property", new XAttribute("Name", qName.Name),
                                                         new XAttribute("Namespace", qName.Namespace),
                                                         new XAttribute("Value", property.Value.ToString())));
                                    }

                                    if (qName.Namespace == "http://schemas.microsoft.com/BizTalk/2003/system-properties")
                                    {
                                        if (qName.Name == "InterchangeID")
                                        {
                                            string value = property.Value.ToString().Trim();
                                            this.Message.InterchangeId = GetGUIDWithoutBraces(value);
                                        }
                                        else if (qName.Name == "MessageType")
                                        {
                                            this.Message.MessageType = property.Value.ToString();
                                        }
                                    }
                                    else if (qName.Namespace == "http://schemas.microsoft.com/BizTalk/2003/messagetracking-properties")
                                    {
                                        if (qName.Name == "ActivityIdentity")
                                        {
                                            string value = property.Value.ToString().Trim();
                                            this.Message.ActivityId = GetGUIDWithoutBraces(value);
                                        }
                                    }
                                    propertyIndex++;
                                }
                                msgProperties.ContextData = ContextData.ToString();
                                this.MessageProperties.Add(msgProperties);
                                // If the message type is still unknown, try to get it from part[0].
                                if (string.IsNullOrEmpty(this.Message.MessageType) || this.Message.MessageType == "Unknown")
                                {
                                    if (!string.IsNullOrEmpty(partType))
                                    {
                                        this.Message.MessageType = partType;
                                    }
                                }
                            }
                        }
                        finally
                        {
                            // When the MessageWrapperForUserCode is unrwapped the reference count
                            // for the message is incremented, so we must release it now.
                            xMessage.Release();
                        }
                    }
                    else
                    {
                        throw new Exception("Could not unwrap XMessage from MessageWrapperForUserCode.");
                    }
                }
                else
                {
                    throw new Exception("Expected XLANGMessage to be a MessageWrapperForUserCode. " + xLangMessage.GetType().FullName + " is not a recognized XLANGMessage type.");
                }
            }
            catch (Exception ex)
            {
                Logger.WriteTrace(string.Format("Error constructing BizTalkMessage from XLangMessage {0} \r\n Details: {1}", this.GetType().Name, ex.ToString()));
                throw ex;
            }
            finally
            {
                if (autoDispose)
                {
                    xLangMessage.Dispose();
                }
            }
        }
Exemple #27
0
		public override EActResults Do(Creature _creature)
		{
			Point delta;
			if (!TryGetParameter(out delta))
			{
				delta = KeyTranslator.GetDirection(GetFirstParameter<ConsoleKey>());
			}

			if (delta.QLenght > 1)
			{
				throw new ApplicationException("Элементарное перемещение длиннее чем 1");
			}

			if (delta == Point.Zero)
			{
				_creature.AddActToPool(new WaitAct());
				return EActResults.ACT_REPLACED;
			}

			var cell = _creature[delta];

			if (cell.GetIsPassableBy(_creature) > 0)
			{
				World.TheWorld.CreatureManager.MoveCreatureOnDelta(_creature, delta);

				var mess = "";
				if (_creature.IsAvatar)
				{
					var thing = cell.Thing;
					if (thing != null)
					{
						mess += EALSentence.NONE.GetString(thing.GetName(_creature));
					}
					var items = cell.Items.ToArray();
					if (items.Length > 0)
					{
						if (items.Length == 1)
						{
							mess += (mess == "" ? "" : ", ") + EALSentence.NONE.GetString(items[0].GetName(_creature));
						}
						else
						{
							mess += (mess == "" ? "" : ", ") + "вещи";
						}
					}
					if (mess != "")
					{
						MessageManager.SendMessage(this, mess);
					}
				}
				return EActResults.DONE;
			}
			{
				var thing = cell.Thing;
				if (thing != null && thing.Is<ClosedDoor>() && thing.IsLockedFor(cell, _creature))
				{
					_creature.InsertActToPool(new OpenAct(), delta);
					return EActResults.ACT_REPLACED;
				}

				if (_creature.IsAvatar)
				{
					var creature = cell.Creature;
					XMessage mess;
					if (creature != null && World.TheWorld.Avatar.Tactic != ETactics.PEACEFULL)
					{
						bool isMoveToAct;
						if(!TryGetParameter(out isMoveToAct) || !isMoveToAct)
						{
							_creature.AddActToPool(new AtackAct(), delta);
							return EActResults.ACT_REPLACED;

							////Если это не перемещение на дальнее расстояние
							//return World.TheWorld.BattleProcessor.Atack(_creature, creature);
						}
					}
					else
					{
						if (creature != null)
						{
							mess = new XMessage(EALTurnMessage.CELL_IS_OCCUPIED_BY, _creature, creature);
						}
						else if (thing != null)
						{
							mess = new XMessage(EALTurnMessage.CELL_IS_OCCUPIED_BY, _creature, thing);
						}
						else
						{
							mess = new XMessage(EALTurnMessage.CELL_IS_OCCUPIED_BY, _creature, cell.Terrain.AsNoun());
						}
						MessageManager.SendXMessage(this, mess);
					}
				}
				return EActResults.QUICK_FAIL;
			}
		}
Exemple #28
0
 public override string ToString()
 {
     return(XMessage.ToString());
 }
Exemple #29
0
 public XLangMessage(XMessage _xMessage)
 {
     XMessage = _xMessage;
 }
Exemple #30
0
        async Task DecryptDownloadedMessage(XMessage xMessage)
        {
            Message decryptedMessage = await TryDecryptMessageToFindSenderEnryptDecryptionKeyAndSaveIt(xMessage);

            if (decryptedMessage == null) // TODO: we'll be here also when Ratchet mismatch error is happening. Then, the message should not be just dropped. Do we have the sender's Id so that we can notify him?
            {
                return;                   // Ignore the message - it was truely garbled or a resend request was already queued. In both cases we are done with it here.
            }
            if (decryptedMessage.MessageType.IsReceipt())
            {
                Message messageToConfirm = await this.repo.GetMessage(decryptedMessage.SenderLocalMessageId, decryptedMessage.SenderId);

                if (messageToConfirm != null) // the message could have already been deleted
                {
                    messageToConfirm.SendMessageState = decryptedMessage.MessageType == MessageType.DeliveryReceipt ? SendMessageState.Delivered : SendMessageState.Read;
                    await this.repo.UpdateMessage(messageToConfirm);

                    SendMessageStateUpdated?.Invoke(this, messageToConfirm);
                }
                return;
            }

            if (decryptedMessage.MessageType.IsContent())
            {
                if (this.contactListManager.CurrentContact == null || this.contactListManager.CurrentContact.Id != decryptedMessage.SenderId)
                {
                    await SendReceipt(decryptedMessage, MessageType.DeliveryReceipt);

                    // This message will become an UNREAD message and not be displayed
                    await this.contactListManager.HandelUnreadAndChatPreviewForIncomingMessageFromChatWorker(decryptedMessage, countAsUnread : true);
                }
                else
                {
                    await SendReceipt(decryptedMessage, MessageType.ReadReceipt);

                    // this message will become an READ message and display immediately
                    await this.contactListManager.HandelUnreadAndChatPreviewForIncomingMessageFromChatWorker(decryptedMessage, countAsUnread : false);

                    IncomingMessageDecrypted?.Invoke(this, decryptedMessage);
                }
            }

            #region Incoming Contact Logic
            // Check if the sender is in our contacts
            // OLD: Identity contactInList = existingContacts.SingleOrDefault(c => c.ChatId == msg.SenderId);

            /*
             *          Identity contactInList = existingContacts.SingleOrDefault(c => c.ChatId == msg.SenderId);
             *          if (contactInList != null && contactInList.ContactState == ContactState.Valid)
             *                  continue; // Yes, proceed checking the nex message
             *
             *          if (contactInList != null && contactInList.ContactState == ContactState.Added)
             *          {
             *                  await VerifyContactInAddedState(contactInList);
             *
             *                  // Check if the contact is valid now
             *                  existingContacts = await repo.GetAllContacts();
             *                  contactInList = existingContacts.SingleOrDefault(c => c.ChatId == msg.SenderId);
             *                  if (contactInList.ContactState == ContactState.Valid)
             *                          continue; // Yes, proceed checking the nex message
             *
             *                  // If still not valid, drop the message
             *                  msg.MessageType = MessageType.None; // MessageType.None will be ignored by the code below
             *                  continue; // Proceed checking the nex message
             *          }
             *          var incomingContact = new Identity { Id = Guid.NewGuid().ToString(), UnverifiedId=msg.SenderId, ContactState = ContactState.Added, Name = "Incoming Contact" };
             *          await repo.AddContact(incomingContact);
             *          await VerifyContactInAddedState(incomingContact);
             *
             *          // Check if the incoming contact is valid now
             *          existingContacts = await repo.GetAllContacts();
             *          contactInList = existingContacts.SingleOrDefault(c => c.ChatId == msg.SenderId);
             *          if (contactInList.ContactState == ContactState.Valid)
             *                  continue; // Yes, proceed checking the next message
             *
             *          // If still not valid, drop the message
             *          msg.MessageType = MessageType.None; // MessageType.None will be ignored by the code below
             */
            #endregion
        }
Exemple #31
0
        /// <summary>
        /// Fully decrypts a message of all types, both control and content messages (including images), if an end-to-en-encryption key can be determined.
        /// </summary>
        async Task <Message> TryDecryptMessageToFindSenderEnryptDecryptionKeyAndSaveIt(XMessage xmessage)
        {
            try
            {
                IReadOnlyList <Identity> contacts = await this.repo.GetAllContacts();

                var decryptedMessage = new Message
                {
                    // XMessage fields
                    RecipientId = "1", // drop my Id

                    TextCipher  = xmessage.TextCipher,
                    ImageCipher = xmessage.ImageCipher,

                    DynamicPublicKey   = xmessage.DynamicPublicKey,
                    DynamicPublicKeyId = xmessage.DynamicPublicKeyId,
                    PrivateKeyHint     = xmessage.PrivateKeyHint,

                    LocalMessageState = LocalMessageState.JustReceived,
                    SendMessageState  = SendMessageState.None,
                    Side = MessageSide.You,

                    // This is what we try to decrypt here
                    MessageType = MessageType.None,
                    SenderId    = null,
                };


                Response <CipherV2> decodeMetaResponse = this.ixdsCryptoService.BinaryDecodeXDSSec(xmessage.MetaCipher, null);
                if (!decodeMetaResponse.IsSuccess)
                {
                    return(null); // garbled, no chance, ignore!
                }
                foreach (Identity identity in contacts)
                {
                    GetE2EDecryptionKeyResult getE2EDecryptionKeyResult = await this.e2eRatchet.GetEndToEndDecryptionKeyAsync(identity.Id, xmessage.DynamicPublicKey, xmessage.PrivateKeyHint);

                    if (getE2EDecryptionKeyResult.E2EDecryptionKeyType == E2EDecryptionKeyType.UnavailableDynamicPrivateKey)
                    {
                        continue; // there was a privateKeyHint != 0 in the message, but the dynamic private key was not in the ratchet for user in the loop
                    }
                    KeyMaterial64 keyMaterial64 = getE2EDecryptionKeyResult.E2EDecryptionKeyMaterial;

                    var decryptMetaResponse = this.ixdsCryptoService.BinaryDecrypt(decodeMetaResponse.Result, keyMaterial64, null);
                    if (!decryptMetaResponse.IsSuccess)
                    {
                        continue;
                    }

                    await this.e2eRatchet.SaveIncomingDynamicPublicKeyOnSuccessfulDecryptionAsync(identity.Id, xmessage.DynamicPublicKey,
                                                                                                  xmessage.DynamicPublicKeyId);

                    XMessageMetaData metadata = decryptMetaResponse.Result.GetBytes().DeserializeMessageMetadata();

                    decryptedMessage.SenderId             = identity.Id;
                    decryptedMessage.MessageType          = metadata.MessageType;
                    decryptedMessage.SenderLocalMessageId = metadata.SenderLocalMessageId.ToString();


                    if (decryptedMessage.MessageType.IsReceipt())
                    {
                        return(decryptedMessage);
                    }

                    if (decryptedMessage.MessageType.IsContent())
                    {
                        if (decryptedMessage.MessageType == MessageType.Text || decryptedMessage.MessageType == MessageType.TextAndMedia || decryptedMessage.MessageType == MessageType.File)
                        {
                            // if the message has text, decrypt all text
                            var decodeTextResponse = this.ixdsCryptoService.BinaryDecodeXDSSec(xmessage.TextCipher, null);
                            if (!decodeTextResponse.IsSuccess)
                            {
                                return(null); // something is wrong, should have worked
                            }
                            var decrpytTextResponse = this.ixdsCryptoService.Decrypt(decodeTextResponse.Result, keyMaterial64, null);
                            if (!decrpytTextResponse.IsSuccess)
                            {
                                return(null); // something is wrong, should have worked
                            }
                            decryptedMessage.ThreadText = decrpytTextResponse.Result.Text;
                        }

                        if (decryptedMessage.MessageType == MessageType.Media || decryptedMessage.MessageType == MessageType.TextAndMedia || decryptedMessage.MessageType == MessageType.File)
                        {
                            // if the message has image content, decrypt the image content
                            var decodeImageResponse = this.ixdsCryptoService.BinaryDecodeXDSSec(xmessage.ImageCipher, null);
                            if (!decodeImageResponse.IsSuccess)
                            {
                                return(null); // something is wrong, should have worked
                            }
                            var decrpytImageResponse = this.ixdsCryptoService.BinaryDecrypt(decodeImageResponse.Result, keyMaterial64, null);
                            if (!decrpytImageResponse.IsSuccess)
                            {
                                return(null); // something is wrong, should have worked
                            }
                            decryptedMessage.ThreadMedia = decrpytImageResponse.Result.GetBytes();
                        }

                        decryptedMessage.EncryptedE2EEncryptionKey = this.ixdsCryptoService.DefaultEncrypt(keyMaterial64.GetBytes(), this.ixdsCryptoService.SymmetricKeyRepository.GetMasterRandomKey());
                        decryptedMessage.LocalMessageState         = LocalMessageState.Integrated;
                        await this.repo.AddMessage(decryptedMessage);
                    }
                    else
                    {
                        throw new Exception($"Invalid MessageType {decryptedMessage.MessageType}");
                    }

                    return(decryptedMessage);
                } // foreach



                // If we are here, assume it's a new contact's message or RESENT message:
                CipherV2      encryptedMetaData          = decodeMetaResponse.Result;
                KeyMaterial64 initialKey                 = this.e2eRatchet.GetInitialE2EDecryptionKey(xmessage.DynamicPublicKey);
                var           decryptInitialMetaResponse = this.ixdsCryptoService.BinaryDecrypt(encryptedMetaData, initialKey, null);
                if (decryptInitialMetaResponse.IsSuccess)
                {
                    XMessageMetaData initialMessageMetadata =
                        decryptInitialMetaResponse.Result.GetBytes().DeserializeMessageMetadata();
                    var incomingPublicKey = initialMessageMetadata.SenderPublicKey;

                    // If we received several resent messages, the first from that incoming contact has already produced that contact:
                    var  contact           = contacts.SingleOrDefault(c => ByteArrays.AreAllBytesEqual(c.StaticPublicKey, incomingPublicKey));
                    bool isIncomingContact = false;

                    if (contact == null)
                    {
                        // Create new contact and save it to make the ratchet work normally
                        isIncomingContact = true;
                        var date            = DateTime.UtcNow;
                        var incomingContact = new Identity
                        {
                            Id = Guid.NewGuid().ToString(),
                            StaticPublicKey = incomingPublicKey,
                            ContactState    = ContactState.Valid,
                            Name            = "Anonymous",
                            FirstSeenUtc    = date,
                            LastSeenUtc     = date
                        };

                        await this.repo.AddContact(incomingContact);

                        contact = incomingContact;
                    }



                    await this.e2eRatchet.SaveIncomingDynamicPublicKeyOnSuccessfulDecryptionAsync(contact.Id, xmessage.DynamicPublicKey,
                                                                                                  xmessage.DynamicPublicKeyId);

                    // add metadata to message
                    decryptedMessage.SenderId             = contact.Id;
                    decryptedMessage.MessageType          = initialMessageMetadata.MessageType;
                    decryptedMessage.SenderLocalMessageId = initialMessageMetadata.SenderLocalMessageId.ToString();

                    if (decryptedMessage.MessageType.IsContent())
                    {
                        var success = true;

                        GetE2EDecryptionKeyResult getE2EDecryptionKeyResult = await this.e2eRatchet.GetEndToEndDecryptionKeyAsync(contact.Id, xmessage.DynamicPublicKey, xmessage.PrivateKeyHint);

                        KeyMaterial64 keyMaterial64 = getE2EDecryptionKeyResult.E2EDecryptionKeyMaterial;
                        await this.e2eRatchet.GetEndToEndDecryptionKeyAsync(contact.Id, xmessage.DynamicPublicKey, xmessage.PrivateKeyHint);

                        if (decryptedMessage.MessageType == MessageType.Text || decryptedMessage.MessageType == MessageType.TextAndMedia)
                        {
                            // if the message has text, decrypt all text
                            var decodeTextResponse = this.ixdsCryptoService.BinaryDecodeXDSSec(xmessage.TextCipher, null);
                            if (!decodeTextResponse.IsSuccess)
                            {
                                success = false; // something is wrong, should have worked
                            }
                            else
                            {
                                var decrpytTextResponse = this.ixdsCryptoService.Decrypt(decodeTextResponse.Result, keyMaterial64, null);
                                if (!decrpytTextResponse.IsSuccess)
                                {
                                    success = false; // something is wrong, should have worked
                                }
                                else
                                {
                                    decryptedMessage.ThreadText = decrpytTextResponse.Result.Text;
                                }
                            }
                        }

                        if (decryptedMessage.MessageType == MessageType.Media || decryptedMessage.MessageType == MessageType.TextAndMedia)
                        {
                            // if the message has image content, decrypt the image content
                            var decodeImageResponse = this.ixdsCryptoService.BinaryDecodeXDSSec(xmessage.ImageCipher, null);
                            if (!decodeImageResponse.IsSuccess)
                            {
                                success = false; // something is wrong, should have worked
                            }
                            else
                            {
                                var decrpytImageResponse = this.ixdsCryptoService.BinaryDecrypt(decodeImageResponse.Result, keyMaterial64, null);
                                if (!decrpytImageResponse.IsSuccess)
                                {
                                    success = false; // something is wrong, should have worked
                                }
                                else
                                {
                                    decryptedMessage.ThreadMedia = decrpytImageResponse.Result.GetBytes();
                                }
                            }
                        }

                        if (success)
                        {
                            decryptedMessage.EncryptedE2EEncryptionKey = this.ixdsCryptoService.DefaultEncrypt(keyMaterial64.GetBytes(), this.ixdsCryptoService.SymmetricKeyRepository.GetMasterRandomKey());
                            decryptedMessage.LocalMessageState         = LocalMessageState.Integrated;
                            await this.contactListManager.ChatWorker_ContactUpdateReceived(null, contact.Id);

                            await this.repo.AddMessage(decryptedMessage);

                            return(decryptedMessage);
                        }
                        else
                        {
                            if (isIncomingContact)
                            {
                                await this.repo.DeleteContacts(new[] { contact.Id }); // delete the just incoming contact if the was an error anyway.
                            }

                            return(null);
                        }
                    }
                    else
                    {
                        return(null);
                    }
                }

                // nope, resend request (I hope we don't loop here!)
                string networkPayloadHash = NetworkPayloadHash.ComputeAsGuidString(xmessage.SerializedPayload);
                if (!this._resendsRequested.Contains(networkPayloadHash))
                {
                    var response = await this.chatClient.UploadResendRequest(new XResendRequest { Id = networkPayloadHash, RecipientId = null });

                    if (response.IsSuccess)
                    {
                        this._resendsRequested.Add(networkPayloadHash);
                    }
                }
            }
            catch (Exception e)
            {
                this.logger.LogError(e.Message);
            }

            return(null);
        }
		public XLangMessage(XMessage _xMessage)
		{
			XMessage = _xMessage;
		}
		public static void SendXMessage(object _sender, XMessage _message)
		{
			var mess = NewMessage;
			if (mess != null) mess(_sender, new XLangMessage(_message));
		}