Beispiel #1
0
        public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData)
        {
            Console.WriteLine("POST request: {0}", p.http_url);

            var compnents = p.http_url.Split('?');

            if (compnents.Length != 2)
            {
                Console.WriteLine("invalid url compnents: {0}", compnents.ToString());
                p.writeFailure();
                return;
            }

            var reqUri = compnents[0];

            if (!reqUri.Equals(Uri))
            {
                p.writeFailure();
                return;
            }
            var queryPath = compnents[1];
            var queryDict = new Dictionary <string, string>();

            foreach (var statement in queryPath.Split("&&".ToCharArray()))
            {
                var elements = statement.Split('=');
                if (elements.Length == 2)
                {
                    queryDict[elements[0]] = elements[1];
                }
            }

            var    data       = inputData.ReadToEnd();
            var    jsonReader = new JsonReader();
            var    reqJson    = jsonReader.Read <Dictionary <string, object> >(data);
            object toBuin;
            object toApp;
            object encrypt;

            if (!reqJson.TryGetValue("toBuin", out toBuin) ||
                toBuin is int == false ||
                (int)toBuin <= 0 ||
                !reqJson.TryGetValue("toApp", out toApp) ||
                toApp is string == false ||
                ((string)toApp).Length == 0 ||
                !reqJson.TryGetValue("encrypt", out encrypt) ||
                encrypt is string == false ||
                ((string)encrypt).Length == 0)
            {
                Console.WriteLine("invalid toBuin or toApp or encrypt");
                p.writeFailure();
                return;
            }

            var toBuinValue  = (int)toBuin;
            var toAppValue   = (string)toApp;
            var encryptValue = (string)encrypt;

            string timeStamp;
            string nonce;
            string signature;

            if (!queryDict.TryGetValue("timestamp", out timeStamp) ||
                timeStamp == null ||
                !queryDict.TryGetValue("nonce", out nonce) ||
                nonce == null ||
                !queryDict.TryGetValue("msg_signature", out signature) ||
                signature == null)
            {
                Console.WriteLine("invalid timestamp or nonce or msg_signature");
                p.writeFailure();
                return;
            }

            if (toBuinValue != Buin || !toAppValue.Equals(AppId))
            {
                Console.WriteLine("buin or appId is not matched");
                p.writeFailure();
                return;
            }

            var mySignature = Signature.GenerateSignature(Token, timeStamp, nonce, encryptValue);

            if (!signature.Equals(mySignature))
            {
                Console.WriteLine("signature is not matched");
                p.writeFailure();
                return;
            }

            var decryptContent = m_crypto.Decrypt(encryptValue);
            //var msg = new SessionMessage().FromJson(AESCrypto.ToString(decryptContent));
            var msg = new ReceiveMessage().FromJson(AESCrypto.ToString(decryptContent));

            switch (msg.MsgType)
            {
            case Message.MessageTypeImage:
            {
                var msgBody = msg.MsgBody.ToImageBody();
                m_appClient.DownloadFile(msgBody.MediaId, OutDir);
            }
            break;

            case Message.MessageTypeFile:
            {
                var msgBody = msg.MsgBody.ToFileBody();
                m_appClient.DownloadFile(msgBody.MediaId, OutDir);
            }
            break;

            default:
                break;
            }

            Console.WriteLine(msg.ToString());
            Console.WriteLine("packageId: {0}", msg.PackageId);

            p.writeSuccess();
            p.outputStream.WriteLine(msg.PackageId);
        }
Beispiel #2
0
        /// <summary>
        /// 查询会话信息
        /// </summary>
        /// <param name="sessionId">会话Id</param>
        /// <returns>Session</returns>
        /// <exception cref="AESCryptoException">加解密失败</exception>
        /// <exception cref="ParamParserException">参数解析失败</exception>
        /// <exception cref="HttpRequestException">http请求失败</exception>
        /// <exception cref="UnexpectedException">其它可能的错误</exception>
        public Session GetSession(string sessionId)
        {
            this.checkAndRefreshToken();

            try
            {
                var client = new HttpClient();
                var rsp    = client.Get(this.apiGetSession(), new { accessToken = m_tokenInfo.token, sessionId = sessionId });

                Helper.CheckHttpStatus(rsp);
                var body = rsp.StaticBody <Dictionary <string, object> >(overrideContentType: HttpContentTypes.ApplicationJson);
                Helper.CheckApiStatus(body);

                var decryptBuffer = m_crypto.Decrypt(Helper.GetEncryptJsonValue(body));
                var decryptStr    = AESCrypto.ToString(decryptBuffer);
                var sessInfo      = new JsonReader().Read <Dictionary <string, object> >(AESCrypto.ToString(decryptBuffer));

                object title;
                object owner;
                object version;
                object type;
                object member;
                object lastMsgId;
                object activeTime;
                if (!sessInfo.TryGetValue("title", out title) || title is string == false ||
                    !sessInfo.TryGetValue("owner", out owner) || owner is string == false ||
                    !sessInfo.TryGetValue("version", out version) || (version is int == false && version is long == false) ||
                    !sessInfo.TryGetValue("type", out type) || type is string == false ||
                    !sessInfo.TryGetValue("member", out member) || member is string[] == false ||
                    !sessInfo.TryGetValue("lastMsgId", out lastMsgId) || (lastMsgId is int == false && lastMsgId is long == false) ||
                    !sessInfo.TryGetValue("activeTime", out activeTime) || (activeTime is int == false && activeTime is long == false))
                {
                    throw new ParamParserException("invalid session info", null);
                }
                var memberList = new List <string>();
                foreach (var m in (string[])member)
                {
                    memberList.Add(m);
                }
                return(new Session(sessionId,
                                   (string)title,
                                   (string)owner,
                                   Convert.ToInt64(version),
                                   (string)type,
                                   memberList,
                                   Convert.ToInt64(lastMsgId),
                                   Convert.ToInt64(activeTime)));
            }
            catch (WebException e)
            {
                throw new HttpRequestException(0, e.Message, e);
            }
            catch (Exception e)
            {
                if (e is GeneralEntAppException)
                {
                    throw e;
                }
                else
                {
                    throw new UnexpectedException(e.Message, e);
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// 搜索文件信息
        /// </summary>
        /// <param name="mediaId">资源Id</param>
        /// <returns>(文件名, 字节数大小)</returns>
        /// <exception cref="AESCryptoException">加解密失败</exception>
        /// <exception cref="ParamParserException">参数解析失败</exception>
        /// <exception cref="HttpRequestException">http请求失败</exception>
        /// <exception cref="UnexpectedException">其它可能的错误</exception>
        public Tuple <string, long> SearchFile(string mediaId)
        {
            this.checkAndRefreshToken();

            try
            {
                var mediaInfo = new Dictionary <string, string>()
                {
                    { "mediaId", mediaId }
                };
                var cipherMediaInfo = m_crypto.Encrypt(AESCrypto.ToBytes(new JsonWriter().Write(mediaInfo)));
                var param           = new Dictionary <string, object>()
                {
                    { "buin", m_buin },
                    { "appId", m_appId },
                    { "encrypt", cipherMediaInfo }
                };
                var client = new HttpClient();
                var rsp    = client.Post(this.apiSearchFile(), param, HttpContentTypes.ApplicationJson, this.tokenQuery());

                Helper.CheckHttpStatus(rsp);
                var body = rsp.StaticBody <Dictionary <string, object> >(overrideContentType: HttpContentTypes.ApplicationJson);
                Helper.CheckApiStatus(body);

                var    decryptBuffer = m_crypto.Decrypt(Helper.GetEncryptJsonValue(body));
                var    existsInfo    = new JsonReader().Read <Dictionary <string, object> >(AESCrypto.ToString(decryptBuffer));
                object name;
                object size;
                if (!existsInfo.TryGetValue("name", out name) ||
                    name is string == false ||
                    ((string)name).Length == 0 ||
                    !existsInfo.TryGetValue("size", out size) ||
                    ((size is int && (int)size > 0) == false && (size is long && (long)size > 0) == false))
                {
                    throw new ParamParserException("invalid file info", null);
                }
                return(new Tuple <string, long>((string)name, Convert.ToInt64(size)));
            }
            catch (WebException e)
            {
                throw new HttpRequestException(0, e.Message, e);
            }
            catch (Exception e)
            {
                if (e is GeneralEntAppException)
                {
                    throw e;
                }
                else
                {
                    throw new UnexpectedException(e.Message, e);
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="mediaId">文件的资源ID</param>
        /// <param name="destDir">目标存储目录</param>
        /// <returns>(文件名, 文件字节数大小, 文件内容)</returns>
        /// <exception cref="AESCryptoException">加解密失败</exception>
        /// <exception cref="ParamParserException">参数解析失败</exception>
        /// <exception cref="HttpRequestException">http请求失败</exception>
        /// <exception cref="UnexpectedException">其它可能的错误</exception>
        public Tuple <String, long, byte[]> DownloadFile(string mediaId, string destDir)
        {
            this.checkAndRefreshToken();

            try
            {
                var mediaInfo = new Dictionary <string, string>()
                {
                    { "mediaId", mediaId }
                };
                var cipherMediaInfo = m_crypto.Encrypt(AESCrypto.ToBytes(new JsonWriter().Write(mediaInfo)));
                var param           = new Dictionary <string, object>()
                {
                    { "buin", m_buin },
                    { "appId", m_appId },
                    { "encrypt", cipherMediaInfo }
                };
                var client = new HttpClient();
                client.StreamResponse = true;
                var rsp = client.Post(this.apiDownloadFile(), param, HttpContentTypes.ApplicationJson, this.tokenQuery());

                Helper.CheckHttpStatus(rsp);

                var encryptFileInfo = rsp.RawHeaders["encrypt"];
                if (encryptFileInfo == null)
                {
                    var body = new JsonReader().Read <Dictionary <string, object> >(AESCrypto.ToString(Helper.ReadStream(rsp.ResponseStream)));
                    Helper.CheckApiStatus(body);
                    throw new ParamParserException("encrypt content not exists", null);
                }

                var    decryptFileInfo = m_crypto.Decrypt(encryptFileInfo);
                var    fileInfo        = new JsonReader().Read <Dictionary <string, object> >(AESCrypto.ToString(decryptFileInfo));
                object name;
                object size;
                if (!fileInfo.TryGetValue("name", out name) ||
                    name is string == false ||
                    ((string)name).Length == 0 ||
                    !fileInfo.TryGetValue("size", out size) ||
                    ((size is int && (int)size > 0) == false && (size is long && (long)size > 0) == false))
                {
                    throw new ParamParserException("invalid file name or size", null);
                }

                var encryptBuffer = Helper.ReadStream(rsp.ResponseStream);
                var decryptFile   = m_crypto.Decrypt(AESCrypto.ToString(encryptBuffer));
                Helper.WriteStream(new FileStream(Path.Combine(destDir, (string)name), FileMode.OpenOrCreate, FileAccess.Write), decryptFile);
                return(new Tuple <string, long, byte[]>((string)name, Convert.ToInt64(size), decryptFile));
            }
            catch (IOException e)
            {
                throw new HttpRequestException(0, e.Message, e);
            }
            catch (WebException e)
            {
                throw new HttpRequestException(0, e.Message, e);
            }
            catch (Exception e)
            {
                if (e is GeneralEntAppException)
                {
                    throw e;
                }
                else
                {
                    throw new UnexpectedException(e.Message, e);
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="type">文件类型</param>
        /// <param name="name">文件名称</param>
        /// <param name="path">文件路径</param>
        /// <returns>文件的资源ID</returns>
        /// <exception cref="AESCryptoException">加解密失败</exception>
        /// <exception cref="ParamParserException">参数解析失败</exception>
        /// <exception cref="HttpRequestException">http请求失败</exception>
        /// <exception cref="UnexpectedException">其它可能的错误</exception>
        public string UploadFile(string type, string name, string path)
        {
            this.checkAndRefreshToken();

            try
            {
                var encryptFile    = m_crypto.Encrypt(Helper.ReadStream(new FileStream(path, FileMode.Open, FileAccess.Read)));
                var fileInfo       = new { type = type, name = name };
                var cipherFileInfo = m_crypto.Encrypt(AESCrypto.ToBytes(new JsonWriter().Write(fileInfo)));

                var tempFileName = Path.GetTempFileName();
                Helper.WriteStream(new FileStream(tempFileName, FileMode.Open, FileAccess.Write), AESCrypto.ToBytes(encryptFile));

                var formData = new Dictionary <string, object>();
                formData["buin"]    = String.Format("{0}", m_buin);
                formData["appId"]   = m_appId;
                formData["encrypt"] = cipherFileInfo;

                var fileData = new FileData();
                fileData.ContentType = HttpContentTypes.TextPlain;
                fileData.FieldName   = "file";
                fileData.Filename    = tempFileName;
                var fileList = new List <FileData>();
                fileList.Add(fileData);

                var client = new HttpClient();
                var rsp    = client.Post(this.apiUploadFile(), formData, fileList, query: this.tokenQuery());
                File.Delete(tempFileName);

                Helper.CheckHttpStatus(rsp);
                var body = rsp.StaticBody <Dictionary <string, object> >(overrideContentType: HttpContentTypes.ApplicationJson);
                Helper.CheckApiStatus(body);

                var    decryptBuffer = m_crypto.Decrypt(Helper.GetEncryptJsonValue(body));
                var    mediaInfo     = new JsonReader().Read <Dictionary <string, string> >(AESCrypto.ToString(decryptBuffer));
                string mediaId;
                if (!mediaInfo.TryGetValue("mediaId", out mediaId) ||
                    mediaId == null ||
                    mediaId.Length == 0)
                {
                    throw new ParamParserException("invalid mediaId", null);
                }
                return(mediaId);
            }
            catch (IOException e)
            {
                throw new HttpRequestException(0, e.Message, e);
            }
            catch (WebException e)
            {
                throw new HttpRequestException(0, e.Message, e);
            }
            catch (Exception e)
            {
                if (e is GeneralEntAppException)
                {
                    throw e;
                }
                else
                {
                    throw new UnexpectedException(e.Message, e);
                }
            }
        }
Beispiel #6
0
 private Token getToken()
 {
     try
     {
         var now         = Helper.GetSecondTimeStamp();
         var timestamp   = AESCrypto.ToBytes(string.Format("{0}", now));
         var encryptTime = m_crypto.Encrypt(timestamp);
         var param       = new Dictionary <string, object>()
         {
             { "buin", m_buin },
             { "appId", m_appId },
             { "encrypt", encryptTime }
         };
         var client = new HttpClient();
         var rsp    = client.Post(this.apiGetToken(), param, HttpContentTypes.ApplicationJson);
         Helper.CheckHttpStatus(rsp);
         var body = rsp.StaticBody <Dictionary <string, object> >(overrideContentType: HttpContentTypes.ApplicationJson);
         Helper.CheckApiStatus(body);
         var    encrypt   = Helper.GetEncryptJsonValue(body);
         var    buffer    = m_crypto.Decrypt(encrypt);
         var    tokenInfo = new JsonReader().Read <Dictionary <string, object> >(AESCrypto.ToString(buffer));
         object accessToken;
         object expireIn;
         if (!tokenInfo.TryGetValue("accessToken", out accessToken) ||
             accessToken is string == false ||
             ((string)accessToken).Length == 0 ||
             !tokenInfo.TryGetValue("expireIn", out expireIn) ||
             expireIn is int == false ||
             (int)expireIn <= 0)
         {
             throw new ParamParserException("invalid token or expireIn", null);
         }
         return(new Token((string)accessToken, now, (int)expireIn));
     }
     catch (WebException e)
     {
         throw new HttpRequestException(0, e.Message, e);
     }
     catch (Exception e)
     {
         if (e is GeneralEntAppException)
         {
             throw e;
         }
         else
         {
             throw new UnexpectedException(e.Message, e);
         }
     }
 }