public ConversationController(ILogger <ConversationController> logger, IConfiguration config, SecretInfo secretInfo, FirestoreDb db)
 {
     _logger     = logger;
     _config     = config;
     _secretInfo = secretInfo;
     _db         = db;
 }
        /// <summary>
        /// Parse the XDocument to RequestMessage, decrypt it if needed.
        /// </summary>
        /// <param name="requestStream">WeChat RequestBody stream.</param>
        /// <param name="secretInfo">The secretInfo used to decrypt the message.</param>
        /// <returns>Decrypted WeChat RequestMessage instance.</returns>
        private IRequestMessageBase GetRequestMessage(Stream requestStream, SecretInfo secretInfo)
        {
            if (requestStream.CanSeek)
            {
                requestStream.Seek(0, SeekOrigin.Begin);
            }

            using (var xr = XmlReader.Create(requestStream))
            {
                var postDataDocument = XDocument.Load(xr);

                // decrypt xml document message and parse to message
                var postDataStr = postDataDocument.ToString();
                var decryptDoc = postDataDocument;

                if (secretInfo != null
                    && !string.IsNullOrWhiteSpace(_settings.Token)
                    && postDataDocument.Root.Element("Encrypt") != null
                    && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value))
                {
                    var msgCrype = new MessageCryptography(secretInfo, _settings);
                    var msgXml = msgCrype.DecryptMessage(postDataStr);

                    decryptDoc = XDocument.Parse(msgXml);
                }

                var requestMessage = WeChatMessageFactory.GetRequestEntity(decryptDoc, _logger);

                return requestMessage;
            }
        }
Esempio n. 3
0
        // 可能会抛出异常
        public static SecretInfo GetSecretInfo(
            string strUserDir,
            string name)
        {
            string      strCfgFileName = Path.Combine(strUserDir, "amazon.xml");
            XmlDocument dom            = new XmlDocument();

            try
            {
                dom.Load(strCfgFileName);
            }
            catch (FileNotFoundException)
            {
                return(null);
            }
            catch (DirectoryNotFoundException)
            {
                return(null);
            }

            SecretInfo info = new SecretInfo();

            if (dom.DocumentElement != null)
            {
                info.AwsAccessKeyID = dom.DocumentElement.GetAttribute("AwsAccessKeyID");
                info.AwsSecretKey   = dom.DocumentElement.GetAttribute("AwsSecretKey");
            }

            return(info);
        }
Esempio n. 4
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="secretInfo"></param>
 /// <returns></returns>
 public SecretInfo CheckSecretInfo(SecretInfo secretInfo)
 {
     if (secretInfo == null || this.SecretInfoList == null)
     {
         return(null);
     }
     return(this.SecretInfoList.FirstOrDefault(f => f.AppId == secretInfo.AppId && f.AppSecret == secretInfo.AppSecret));
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageCryptography"/> class.
        /// </summary>
        /// <param name="secretInfo">The secret info provide by WeChat.</param>
        /// <param name="settings">The WeChat settings.</param>
        public MessageCryptography(SecretInfo secretInfo, WeChatSettings settings)
        {
            if (string.IsNullOrEmpty(settings.EncodingAesKey) || settings.EncodingAesKey.Length != 43)
            {
                throw new ArgumentException("Invalid EncodingAESKey.", nameof(secretInfo));
            }

            _token          = settings.Token;
            _appId          = settings.AppId;
            _encodingAesKey = settings.EncodingAesKey;
            _msgSignature   = secretInfo.MessageSignature;
            _timestamp      = secretInfo.Timestamp;
            _nonce          = secretInfo.Nonce;
        }
Esempio n. 6
0
        public static async void DownloadGameTask(Game game, IProgress <string> progress, IProgress <float> progressBar, IProgress <float> progressBarMax)
        {
            List <GameFile>[] filesDownload = CheckGameFiles(game.Title);

            //удаляем лишние файлы
            progress.Report("Removing garbage...");
            foreach (GameFile file in filesDownload[0])
            {
                File.Delete(@"Games\" + file.WinPath);
            }


            progressBarMax.Report(filesDownload[1].Count);

            // пока не знаю как прервать async без гемороя, потому отложу эту тему
            //if (filesDownload[1].Count == 0)
            //    progress.Report("No update required");

            string     pathRemote    = "/var/www/html/public/Games/";
            string     pathLocalFile = @"Games\";
            SecretInfo secretInfo    = new SecretInfo();

            using (SftpClient sftp = new SftpClient(secretInfo.host, secretInfo.username, secretInfo.password))
            {
                try
                {
                    sftp.Connect();

                    int i = 0;
                    foreach (GameFile gameFile in filesDownload[1])
                    {
                        await DownloadFileAsync(pathRemote + gameFile.UnixPath, pathLocalFile + gameFile.WinPath, sftp);

                        progress.Report(gameFile.WinPath);
                        game.DownloadingFile = ++i;
                        progressBar.Report(++i);
                    }
                    sftp.Disconnect();
                }
                catch (Exception er)
                {
                    MessageBox.Show("An exception has been caught " + er.ToString() + "\n" + er.Message, "Error!");
                }
            }
            progress.Report("Download complete!");
            //progressBar.Report(0);
        }
Esempio n. 7
0
    /// <summary>
    /// 加载XML配表
    /// </summary>
    public static XmlDocument LoadXML(TextAsset asset)
    {
        byte[] bytes = asset.bytes;

        SecretInfo.Decrypt(bytes);

        MemoryStream      ms      = new MemoryStream(bytes);
        XmlReaderSettings setting = new XmlReaderSettings();

        setting.IgnoreComments = true;
        XmlReader   reader = XmlReader.Create(ms, setting);
        XmlDocument doc    = new XmlDocument();

        doc.Load(reader);

        return(doc);
    }
 public async Task PostWeChatAsync([FromQuery] SecretInfo postModel)
 {
     // Delegate the processing of the HTTP POST to the adapter.
     // The adapter will invoke the bot.
     await _wechatAdapter.ProcessAsync(Request, Response, _bot, postModel);
 }
        /// <summary>
        /// Process the request from WeChat.
        /// This method can be called from inside a POST method on any Controller implementation.
        /// </summary>
        /// <param name="httpRequest">The HTTP request object, typically in a POST handler by a Controller.</param>
        /// <param name="httpResponse">The HTTP response object.</param>
        /// <param name="bot">The bot implementation.</param>
        /// <param name="secretInfo">The secret info provide by WeChat.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, SecretInfo secretInfo, CancellationToken cancellationToken = default(CancellationToken))
        {
            _logger.LogInformation("Receive a new request from WeChat.");
            if (httpRequest == null)
            {
                throw new ArgumentNullException(nameof(httpRequest));
            }

            if (httpResponse == null)
            {
                throw new ArgumentNullException(nameof(httpResponse));
            }

            if (bot == null)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            if (secretInfo == null)
            {
                throw new ArgumentNullException(nameof(secretInfo));
            }

            if (!VerificationHelper.VerifySignature(secretInfo.WebhookSignature, secretInfo.Timestamp, secretInfo.Nonce, _settings.Token))
            {
                throw new UnauthorizedAccessException("Signature verification failed.");
            }

            // Return echo string when request is setting up the endpoint.
            if (!string.IsNullOrEmpty(secretInfo.EchoString))
            {
                await httpResponse.WriteAsync(secretInfo.EchoString, cancellationToken).ConfigureAwait(false);
                return;
            }

            // Directly return OK header to prevent WeChat from retrying.
            if (!_settings.PassiveResponseMode)
            {
                httpResponse.StatusCode = (int)HttpStatusCode.OK;
                httpResponse.ContentType = "text/event-stream";
                await httpResponse.WriteAsync(string.Empty).ConfigureAwait(false);
                await httpResponse.Body.FlushAsync().ConfigureAwait(false);
            }

            try
            {
                var wechatRequest = GetRequestMessage(httpRequest.Body, secretInfo);
                var wechatResponse = await ProcessWeChatRequest(
                                wechatRequest,
                                bot.OnTurnAsync,
                                cancellationToken).ConfigureAwait(false);

                // Reply WeChat(User) request have two ways, set response in http response or use background task to process the request async.
                if (_settings.PassiveResponseMode)
                {
                    httpResponse.StatusCode = (int)HttpStatusCode.OK;
                    httpResponse.ContentType = "text/xml";
                    var xmlString = WeChatMessageFactory.ConvertResponseToXml(wechatResponse);
                    await httpResponse.WriteAsync(xmlString).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Process WeChat request failed.");
                throw;
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Process the request from WeChat.
        /// This method can be called from inside a POST method on any Controller implementation.
        /// </summary>
        /// <param name="httpRequest">The HTTP request object, typically in a POST handler by a Controller.</param>
        /// <param name="httpResponse">The HTTP response object.</param>
        /// <param name="bot">The bot implementation.</param>
        /// <param name="secretInfo">The secret info provide by WeChat.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, SecretInfo secretInfo, CancellationToken cancellationToken = default(CancellationToken))
        {
            _logger.LogInformation("Receive a new request from WeChat.");
            if (httpRequest == null)
            {
                throw new ArgumentNullException(nameof(httpRequest));
            }

            if (httpResponse == null)
            {
                throw new ArgumentNullException(nameof(httpResponse));
            }

            if (bot == null)
            {
                throw new ArgumentNullException(nameof(bot));
            }

            if (secretInfo == null)
            {
                throw new ArgumentNullException(nameof(secretInfo));
            }

            if (false == string.IsNullOrEmpty(secretInfo.EchoString))
            {
                var wXBizMsgCrypt    = new WXBizMsgCrypt(_settings.Token, _settings.EncodingAesKey, _settings.CorpId);
                var replayEchoString = string.Empty;
                var code             = wXBizMsgCrypt.VerifyURL(secretInfo.MessageSignature, secretInfo.Timestamp, secretInfo.Nonce, secretInfo.EchoString, ref replayEchoString);
                if (code != 0)
                {
                    throw new UnauthorizedAccessException($"Signature verification failed. Code: {code}");
                }

                // Return echo string when request is setting up the endpoint.
                if (!string.IsNullOrEmpty(replayEchoString))
                {
                    await httpResponse.WriteAsync(replayEchoString, cancellationToken).ConfigureAwait(false);

                    return;
                }
            }

            // Directly return OK header to prevent WeChat from retrying.
            if (!_settings.PassiveResponseMode)
            {
                httpResponse.StatusCode  = (int)HttpStatusCode.OK;
                httpResponse.ContentType = "text/event-stream";
                await httpResponse.WriteAsync(string.Empty).ConfigureAwait(false);

                await httpResponse.Body.FlushAsync().ConfigureAwait(false);
            }

            try
            {
                var wechatRequest  = GetRequestMessage(httpRequest.Body, secretInfo);
                var wechatResponse = await ProcessWeChatRequest(
                    wechatRequest,
                    bot.OnTurnAsync,
                    cancellationToken).ConfigureAwait(false);

                // Reply WeChat(User) request have two ways, set response in http response or use background task to process the request async.
                if (_settings.PassiveResponseMode)
                {
                    httpResponse.StatusCode  = (int)HttpStatusCode.OK;
                    httpResponse.ContentType = "text/xml";
                    var xmlString = WeChatMessageFactory.ConvertResponseToXml(wechatResponse);
                    var response  = string.Empty;
                    var timestemp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
                    var nonce     = Guid.NewGuid().ToString("N");
                    new WXBizMsgCrypt(_settings.Token, _settings.EncodingAesKey, _settings.CorpId).EncryptMsg(xmlString, timestemp, nonce, ref response);

                    await httpResponse.WriteAsync(response).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Process WeChat request failed.");
                throw;
            }
        }