1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
using FastJSON;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using Top.Api.Parser;
using Top.Api.Util;
using Top.Api;
using Top.Api.DingTalk;
 
namespace DingTalk.Api
{
    /// <summary>
    /// 基于REST的TOP客户端。
    /// </summary>
    public class DefaultDingTalkClient : IDingTalkClient
    {
        internal string serverUrl;
        internal string format = Constants.FORMAT_XML;
        internal DateTime dt1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
 
        internal WebUtils webUtils;
        internal ITopLogger topLogger;
        internal bool disableParser = false; // 禁用响应结果解释
        internal bool disableTrace = false; // 禁用日志调试功能
        internal bool useSimplifyJson = false; // 是否采用精简化的JSON返回
        internal bool useGzipEncoding = true;  // 是否启用响应GZIP压缩
        internal bool useJsonString = false; // 是否采用JsonString生成
        internal IDictionary<string, string> systemParameters; // 设置所有请求共享的系统级参数
 
        #region DefaultDingTalkClient Constructors
 
        public DefaultDingTalkClient(string serverUrl)
        {
            this.serverUrl = serverUrl;
            this.webUtils = new WebUtils();
            this.topLogger = Top.Api.Log.Instance;
        }
 
        public DefaultDingTalkClient(string serverUrl,string format)
            : this(serverUrl)
        {
            this.format = format;
        }
 
        #endregion
 
        public void SetTimeout(int timeout)
        {
            this.webUtils.Timeout = timeout;
        }
 
        public void SetReadWriteTimeout(int readWriteTimeout)
        {
            this.webUtils.ReadWriteTimeout = readWriteTimeout;
        }
 
        public void SetDisableParser(bool disableParser)
        {
            this.disableParser = disableParser;
        }
 
        public void SetDisableTrace(bool disableTrace)
        {
            this.disableTrace = disableTrace;
        }
 
        public void SetUseSimplifyJson(bool useSimplifyJson)
        {
            this.useSimplifyJson = useSimplifyJson;
        }
 
        public void SetUseGzipEncoding(bool useGzipEncoding)
        {
            this.useGzipEncoding = useGzipEncoding;
        }
 
        public void SetIgnoreSSLCheck(bool ignore)
        {
            this.webUtils.IgnoreSSLCheck = ignore;
        }
 
        public void SetSystemParameters(IDictionary<string, string> systemParameters)
        {
            this.systemParameters = systemParameters;
        }
 
        #region IDingTalkClient Members
 
        public virtual T Execute<T>(IDingTalkRequest<T> request) where T : DingTalkResponse
        {
            return DoExecute<T>(request, null, DateTime.Now);
        }
 
        public virtual T Execute<T>(IDingTalkRequest<T> request, string session) where T : DingTalkResponse
        {
            return DoExecute<T>(request, session, DateTime.Now);
        }
 
        public virtual T Execute<T>(IDingTalkRequest<T> request, string session, DateTime timestamp) where T : DingTalkResponse
        {
            return DoExecute<T>(request, session, timestamp);
        }
 
        public T Execute<T>(IDingTalkRequest<T> request, string accessKey, string accessSecret) where T : DingTalkResponse
        {
            return Execute<T>(request, accessKey, accessSecret, null, null);
        }
 
        public T Execute<T>(IDingTalkRequest<T> request, string accessKey, string accessSecret, string suiteTicket) where T : DingTalkResponse
        {
            return Execute<T>(request, accessKey, accessSecret, suiteTicket, null);
        }
 
        public T Execute<T>(IDingTalkRequest<T> request, string accessKey, string accessSecret, string suiteTicket, string corpId) where T : DingTalkResponse
        {
            if (request.GetApiCallType() == null || request.GetApiCallType().Equals(DingTalkConstants.CALL_TYPE_TOP))
            {
                return DoExecuteTop(request, null, DateTime.Now);
            }
            else
            {
                return DoExecuteOApi(request, null, accessKey, accessSecret, suiteTicket, corpId, DateTime.Now);
            }
        }
 
        #endregion
 
        private T DoExecute<T>(IDingTalkRequest<T> request, string session, DateTime timestamp) where T : DingTalkResponse
        {
            if(request.GetApiCallType() == null || request.GetApiCallType().Equals(DingTalkConstants.CALL_TYPE_TOP)) {
                return DoExecuteTop(request, session, timestamp);
            } else {
                return DoExecuteOApi(request, session, null, null, null, null, timestamp);
            }
        }
 
        private T DoExecuteTop<T>(IDingTalkRequest<T> request, string session, DateTime timestamp) where T : DingTalkResponse
        {
            long start = DateTime.Now.Ticks;
 
            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (TopException e)
            {
                return CreateErrorResponse<T>(e.ErrorCode, e.ErrorMsg);
            }
 
            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());
            txtParams.Add(Constants.METHOD, request.GetApiName());
            txtParams.Add(Constants.VERSION, "2.0");
            txtParams.Add(Constants.FORMAT, format);
            txtParams.Add(Constants.PARTNER_ID, GetSdkVersion());
            txtParams.Add(Constants.TIMESTAMP, timestamp);
            txtParams.Add(Constants.SESSION, session);
            txtParams.AddAll(this.systemParameters);
 
            if (this.useSimplifyJson)
            {
                txtParams.Add(Constants.SIMPLIFY, "true");
            }
            // 添加头部参数
            if (this.useGzipEncoding)
            {
                request.GetHeaderParameters()[Constants.ACCEPT_ENCODING] = Constants.CONTENT_ENCODING_GZIP;
            }
 
            string realServerUrl = GetServerUrl(this.serverUrl, request.GetApiName(), session);
            string reqUrl = WebUtils.BuildRequestUrl(realServerUrl, txtParams);
            try
            {
                string body;
 
                if (request is IDingTalkUploadRequest<T>) // 是否需要上传文件
                {
                    IDingTalkUploadRequest<T> uRequest = (IDingTalkUploadRequest<T>)request;
                    IDictionary<string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                    body = webUtils.DoPost(realServerUrl, txtParams, fileParams, request.GetHeaderParameters());
                }
                else
                {
                    body = webUtils.DoPost(realServerUrl, txtParams, request.GetHeaderParameters());
                }
 
                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp = Activator.CreateInstance<T>();
                    rsp.Body = body;
                }
                else
                {
                    if (Constants.FORMAT_XML.Equals(format))
                    {
                        ITopParser<T> tp = new TopXmlParser<T>();
                        rsp = tp.Parse(body);
                    }
                    else
                    {
                        ITopParser<T> tp;
                        if (useSimplifyJson)
                        {
                            tp = new TopSimplifyJsonParser<T>();
                        }
                        else
                        {
                            tp = new TopJsonParser<T>();
                        }
                        rsp = tp.Parse(body);
                    }
                }
 
                // 追踪错误的请求
                if (rsp.IsError)
                {
                    TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                    TraceApiError(request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, rsp.Body);
                }
                return rsp;
            }
            catch (Exception e)
            {
                TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                TraceApiError(request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, e.GetType() + ": " + e.Message);
                throw e;
            }
        }
 
        private T DoExecuteOApi<T>(IDingTalkRequest<T> request, string session, string accessKey, string accessSecret, string suiteTicket, string corpId, DateTime timestamp) where T : DingTalkResponse
        {
            long start = DateTime.Now.Ticks;
 
            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (TopException e)
            {
                return CreateErrorResponse<T>(e.ErrorCode, e.ErrorMsg);
            }
 
            this.format = Constants.FORMAT_JSON;
 
            // 添加协议级请求参数
            TopDictionary txtParams = new TopDictionary(request.GetParameters());
            txtParams.Add(DingTalkConstants.ACCESS_TOKEN, session);
 
            // 添加头部参数
            if (this.useGzipEncoding)
            {
                request.GetHeaderParameters()[Constants.ACCEPT_ENCODING] = Constants.CONTENT_ENCODING_GZIP;
            }
 
            string realServerUrl = null;
            // 签名优先
            if (accessKey != null)
            {
                long dingTimestamp = GetTimestamp(DateTime.UtcNow);
                // 验证签名有效性
                String canonicalString = DingTalkSignatureUtil.GetCanonicalStringForIsv(dingTimestamp, suiteTicket);
                String signature = DingTalkSignatureUtil.ComputeSignature(accessSecret, canonicalString);
                IDictionary<String, String> ps = new Dictionary<String, String>();
                ps.Add("accessKey", accessKey);
                ps.Add("signature", signature);
                ps.Add("timestamp", dingTimestamp + "");
                if (suiteTicket != null)
                {
                    ps.Add("suiteTicket", suiteTicket);
                }
                if (corpId != null)
                {
                    ps.Add("corpId", corpId);
                }
 
                String queryStr = DingTalkSignatureUtil.ParamToQueryString(ps, "utf-8");
                if (this.serverUrl.IndexOf("?") > 0)
                {
                    realServerUrl = this.serverUrl + "&" + queryStr;
                }
                else
                {
                    realServerUrl = this.serverUrl + "?" + queryStr;
                }
            }
            else 
            {
                if (this.serverUrl.IndexOf("?") > 0)
                {
                    realServerUrl = this.serverUrl + (session != null && session != "" ? ("&access_token=" + session) : "");
                }
                else
                {
                    realServerUrl = this.serverUrl + (session != null && session != "" ? ("?access_token=" + session) : "");
                }
            }
 
            try
            {
                string body;
 
                if(request.GetHttpMethod() == "POST")
                {
                    if (request is IDingTalkUploadRequest<T>) // 是否需要上传文件
                    {
                        IDingTalkUploadRequest<T> uRequest = (IDingTalkUploadRequest<T>)request;
                        IDictionary<string, FileItem> fileParams = TopUtils.CleanupDictionary(uRequest.GetFileParameters());
                        body = webUtils.DoPost(realServerUrl, null, fileParams, request.GetHeaderParameters());
                    }
                    else
                    {
                        IDictionary<String, Object> jsonParams = new Dictionary<String, Object>();
                        foreach (string key in request.GetParameters().Keys)
                        {
                            string value = request.GetParameters()[key];
                            if(useJsonString)
                            {
                                jsonParams.Add(key, value);
                            }
                            else
                            {
                                if (value.StartsWith("[") && value.EndsWith("]"))
                                {
                                    IList childMap = (IList)TopUtils.JsonToObject(value);
                                    jsonParams.Add(key, childMap);
                                }
                                else if (value.StartsWith("{") && value.EndsWith("}"))
                                {
                                    IDictionary<string, Object> childMap = (IDictionary<string, Object>)TopUtils.JsonToObject(value);
                                    jsonParams.Add(key, childMap);
                                }
                                else
                                {
                                    jsonParams.Add(key, value);
                                }
                            }
                        }
 
 
                        body = webUtils.DoPostWithJson(realServerUrl, jsonParams, request.GetHeaderParameters());
                    }
                } else 
                {
                    body = webUtils.DoGet(realServerUrl, request.GetParameters());
                }
 
                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp = Activator.CreateInstance<T>();
                    rsp.Body = body;
                }
                else
                {
                    ITopParser<T> tp = new DingTalkJsonParser<T>();
                    rsp = tp.Parse(body);
                }
 
                // 追踪错误的请求
                if (rsp.IsError)
                {
                    TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                    TraceApiError(request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, rsp.Body);
                }
                return rsp;
            }
            catch (Exception e)
            {
                TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                TraceApiError(request.GetApiName(), serverUrl, txtParams, latency.TotalMilliseconds, e.GetType() + ": " + e.Message);
                throw e;
            }
        }
 
        internal virtual string GetServerUrl(string serverUrl, string apiName, string session)
        {
            return serverUrl;
        }
 
        internal virtual string GetSdkVersion()
        {
            return Constants.SDK_VERSION;
        }
 
        internal T CreateErrorResponse<T>(string errCode, string errMsg) where T : DingTalkResponse
        {
            T rsp = Activator.CreateInstance<T>();
            rsp.ErrCode = errCode;
            rsp.ErrMsg = errMsg;
 
            if (Constants.FORMAT_XML.Equals(format))
            {
                XmlDocument root = new XmlDocument();
                XmlElement bodyE = root.CreateElement(Constants.ERROR_RESPONSE);
                XmlElement codeE = root.CreateElement(Constants.ERROR_CODE);
                codeE.InnerText = errCode;
                bodyE.AppendChild(codeE);
                XmlElement msgE = root.CreateElement(Constants.ERROR_MSG);
                msgE.InnerText = errMsg;
                bodyE.AppendChild(msgE);
                root.AppendChild(bodyE);
                rsp.Body = root.OuterXml;
            }
            else
            {
                IDictionary<string, object> errObj = new Dictionary<string, object>();
                errObj.Add(Constants.ERROR_CODE, errCode);
                errObj.Add(Constants.ERROR_MSG, errMsg);
                IDictionary<string, object> root = new Dictionary<string, object>();
                root.Add(Constants.ERROR_RESPONSE, errObj);
 
                string body = JSON.ToJSON(root);
                rsp.Body = body;
            }
            return rsp;
        }
 
        internal void TraceApiError(string apiName, string url, Dictionary<string, string> parameters, double latency, string errorMessage)
        {
            if (!disableTrace)
            {
                this.topLogger.TraceApiError("dingtalk",apiName, url, parameters, latency, errorMessage);
            }
        }
 
        private long GetTimestamp(DateTime dateTime)
        {
            return (dateTime.Ticks - dt1970.Ticks) / 10000;
        }
    }
}