-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSpark.cs
227 lines (203 loc) · 8.94 KB
/
Spark.cs
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
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using static Newtonsoft.Json.JsonConvert;
using Newtonsoft.Json.Linq;
using System.Linq;
using System;
using static System.Net.WebUtility;
using System.Text;
using Newtonsoft.Json;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;
namespace SparkDotNet
{
public partial class Spark
{
private string accessToken { get; set; }
private static string baseURL = "https://webexapis.com";
private HttpClient client = new HttpClient();
public Spark(string accessToken)
{
this.accessToken = accessToken;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.accessToken);
}
#region Private Helper Methods
private async Task<bool> DeleteItemAsync(string path)
{
HttpResponseMessage response = await client.DeleteAsync(path);
return response.StatusCode == HttpStatusCode.NoContent;
}
private async Task<T> PostItemAsync<T>(string path, Dictionary<string, object> bodyParams)
{
HttpContent content;
if (bodyParams.ContainsKey("files") && IsLocalPath(bodyParams["files"]))
{
MultipartFormDataContent multiPartContent = new MultipartFormDataContent("----SparkDotNetBoundary");
string[] filelist = (string[])bodyParams["files"];
bodyParams.Remove("files");
foreach (KeyValuePair<string, object> kv in bodyParams)
{
StringContent stringContent = new StringContent((string)kv.Value);
multiPartContent.Add(stringContent, kv.Key);
}
foreach (string file in filelist)
{
FileInfo fi = new FileInfo(file);
string fileName = fi.Name;
byte[] fileContents = File.ReadAllBytes(fi.FullName);
ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);
byteArrayContent.Headers.Add("Content-Type", MimeTypes.GetMimeType(fileName));
multiPartContent.Add(byteArrayContent, "files", fileName);
}
content = multiPartContent;
}
else
{
string jsonBody = "";
if (bodyParams.ContainsKey("attachments"))
{
var attachments = JObject.Parse((string)bodyParams["attachments"]);
bodyParams.Remove("attachments");
var jsonParams = JsonConvert.SerializeObject(bodyParams);
var json = JObject.Parse(jsonParams);
json["attachments"] = attachments;
jsonBody = JsonConvert.SerializeObject(json);
}
else
{
jsonBody = JsonConvert.SerializeObject(bodyParams);
}
content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
}
HttpResponseMessage response = await client.PostAsync(path, content);
await CheckForErrorResponse(response);
return DeserializeObject<T>(await response.Content.ReadAsStringAsync());
}
private string getURL(string path, Dictionary<string, string> dict)
{
return getURL(path, dict, baseURL);
}
private string getURL(string path, Dictionary<string, string> dict, string basePath)
{
UriBuilder uriBuilder = new UriBuilder(basePath);
uriBuilder.Path = path;
string queryString = "";
if (dict.Count > 0)
{
foreach (KeyValuePair<string, string> kv in dict)
{
queryString += UrlEncode(kv.Key);
queryString += "=";
queryString += UrlEncode(kv.Value);
queryString += "&";
}
}
uriBuilder.Query = queryString;
return uriBuilder.Uri.ToString();
}
private async Task<T> UpdateItemAsync<T>(string path, Dictionary<string, object> bodyParams)
{
var jsonBody = JsonConvert.SerializeObject(bodyParams);
StringContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PutAsync(path, content);
await CheckForErrorResponse(response);
return DeserializeObject<T>(await response.Content.ReadAsStringAsync());
}
private async Task<T> GetItemAsync<T>(string path)
{
HttpResponseMessage response = await client.GetAsync(path);
await CheckForErrorResponse(response);
return DeserializeObject<T>(await response.Content.ReadAsStringAsync());
}
private async Task<List<T>> GetItemsAsync<T>(string path, string rootNode = "items")
{
HttpResponseMessage response = await client.GetAsync(path);
await CheckForErrorResponse(response);
List<T> items = new List<T>();
JObject requestResult = JObject.Parse(await response.Content.ReadAsStringAsync());
List<JToken> results = requestResult[rootNode].Children().ToList();
foreach (JToken result in results)
{
T item = DeserializeObject<T>(result.ToString());
items.Add(item);
}
return items;
}
private static bool IsLocalPath(object files)
{
string[] filelist = (string[])files;
var p = filelist[0];
try
{
return new System.Uri(p).IsFile;
}
catch (Exception)
{
return true; // assume it's a local file if we can't create a URI out of it...
}
}
#endregion
public async Task<PaginationResult<T>> GetItemsWithLinksAsync<T>(string path)
{
HttpResponseMessage response = await client.GetAsync(path);
await CheckForErrorResponse(response);
PaginationResult<T> paginationResult = new PaginationResult<T>();
List<T> items = new List<T>();
Links links = new Links();
JObject requestResult = JObject.Parse(await response.Content.ReadAsStringAsync());
List<JToken> results = requestResult["items"].Children().ToList();
foreach (JToken result in results)
{
T item = DeserializeObject<T>(result.ToString());
items.Add(item);
}
if (response.Headers.Contains("Link"))
{
var link = response.Headers.GetValues("Link").FirstOrDefault();
if (link != null && !"".Equals(link))
{
// borrowed regex from spark-java-sdk https://github.com/ciscospark/spark-java-sdk/blob/master/src/main/java/com/ciscospark/LinkedResponse.java
Regex r = new Regex("\\s*<(\\S+)>\\s*;\\s*rel=\"(\\S+)\",?", RegexOptions.Compiled);
MatchCollection regmatch = r.Matches(link);
foreach (Match item in regmatch)
{
var linktype = item.Groups[2].ToString().ToLower();
Uri linkUrl = new Uri(item.Groups[1].ToString());
switch (linktype)
{
case "next":
links.Next = linkUrl.PathAndQuery;
break;
case "prev":
links.Prev = linkUrl.PathAndQuery;
break;
case "first":
links.First = linkUrl.PathAndQuery;
break;
default:
break;
}
}
}
}
paginationResult.Items = items;
paginationResult.Links = links;
return paginationResult;
}
private async Task CheckForErrorResponse(HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
return;
}
SparkErrorContent errorContent = DeserializeObject<SparkErrorContent>(await response.Content.ReadAsStringAsync());
string errorMessage = errorContent?.Message ?? response.ReasonPhrase;
throw new SparkException((int)response.StatusCode, errorMessage, errorContent, response.Headers);
}
}
}