forked from WeAreMammoth/bcxapi-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Service.cs
678 lines (623 loc) · 26.5 KB
/
Service.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
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Helpers;
using BCXAPI.Extensions;
namespace BCXAPI
{
public class Service
{
private const string _BaseCampAPIURL = "https://basecamp.com/{0}/api/v1/{1}.json";
private const string _AccountsURL = "https://launchpad.37signals.com/authorization.json";
private const string _AuthorizationURL = "https://launchpad.37signals.com/authorization/new?type=web_server&client_id={0}&redirect_uri={1}{2}";
private const string _AccessTokenURL = "https://launchpad.37signals.com/authorization/token?type=web_server&client_id={0}&redirect_uri={1}&client_secret={2}&code={3}";
private const string _RefreshTokenURL = "https://launchpad.37signals.com/authorization/token";
private const string _RefreshTokenPostBody = "type=refresh&client_id={0}&redirect_uri={1}&client_secret={2}&refresh_token={3}";
private readonly string _clientID;//the client id given to you by basecamp
private readonly string _clientSecret;//the client secret given to you by basecamp
private readonly string _redirectURI; //this must match what you've set up in your basecamp integration page
private readonly string _appNameAndContact; //this will go in your User-Agent header when making requests. 37s recommends you add your app name and a contact URL or email.
private static BCXAPI.Providers.IResponseCache _cache;
private dynamic _accessToken;
//get or set the access token here - this way if you just got it back from basecamp you dont need to reconstruct to entire object
public dynamic AccessToken
{
get
{
return _accessToken;
}
set
{
_accessToken = value;
}
}
/// <summary>
/// create a service class with an authorization token retrieved from GetAuthToken (if you have it).
/// If you do not provide one then you will only be able to get the URL to the
/// basecamp authorization requested page and to validate a code returned to you by that authorization.
/// parameters come from the app you set up at integrate.37signals.com
/// </summary>
/// <param name="clientID">your client id from 37s</param>
/// <param name="clientSecret">your client secret from 37s</param>
/// <param name="redirectURI">the redirect URI you set up with 37s - this must match</param>
/// <param name="appNameAndContact">your application name and contact info - added to your request header</param>
/// <param name="cache">an optional cache to use for caching responses from 37s. if you don't provide one, it'll use the System.Runtime.Caching.MemoryCache.Default cache</param>
/// <param name="accessToken">if you have an access token, provide it here. this is the entire json object returned from the call to GetAccessToken</param>
public Service(string clientID,
string clientSecret,
string redirectURI,
string appNameAndContact,
BCXAPI.Providers.IResponseCache cache = null,
dynamic accessToken = null)
{
if (cache == null)
{
_cache = new BCXAPI.Providers.DefaultMemoryCache();
}
else
{
_cache = cache;
}
_clientID = clientID;
_clientSecret = clientSecret;
_redirectURI = redirectURI;
_appNameAndContact = appNameAndContact;
_accessToken = accessToken;
if (string.IsNullOrWhiteSpace(clientID) ||
string.IsNullOrWhiteSpace(clientSecret) ||
string.IsNullOrWhiteSpace(redirectURI) ||
string.IsNullOrWhiteSpace(_appNameAndContact))
{
throw new Exceptions.BaseException("You must provide the client id, client secret, redirect uri, and your app name and contact information to use the API.");
}
}
public bool IsAuthenticated
{
get
{
try
{
return _accessToken != null && !string.IsNullOrWhiteSpace(_accessToken.access_token);
}
catch
{
return false;
}
}
}
/// <summary>
/// step 1: get the URL to redirect your users to
/// </summary>
/// <param name="optionalArguments">pass in this optional parameter to get these key value pairs passed back to your redirect URL in the query string</param>
/// <returns>string of the URL to redirect to - since basecamp requires user authentication then you cannot make this request on the backend</returns>
public string GetRequestAuthorizationURL(Dictionary<string, string> optionalArguments = null)
{
string additionalParams = string.Empty;
if (optionalArguments != null)
{
System.Text.StringBuilder optionalParams = new StringBuilder();
foreach (var kv in optionalArguments)
{
optionalParams = optionalParams.AppendFormat("&{0}={1}", System.Web.HttpUtility.UrlEncode(kv.Key), System.Web.HttpUtility.UrlEncode(kv.Value));
}
additionalParams = optionalParams.ToString();
}
return string.Format(_AuthorizationURL, _clientID, _redirectURI, additionalParams);
}
/// <summary>
///step 2: Given a code that the url from GetRequestAuthorizationURL eventually redirects back to and the clientsecret you can get an access token. store this token somewhere
/// as you need to provide it to this wrapper to make calls.
/// </summary>
/// <param name="code">the code given to you by basecamp</param>
/// <returns>the access token</returns>
public dynamic GetAccessToken(string code)
{
try
{
string url = string.Format(_AccessTokenURL, _clientID, _redirectURI, _clientSecret, code);
var wr = System.Net.HttpWebRequest.Create(url);
wr.Method = "POST";
var resp = (System.Net.HttpWebResponse)wr.GetResponse();
using (var sw = new System.IO.StreamReader(resp.GetResponseStream()))
{
_accessToken = Json.Decode(sw.ReadToEnd());
}
return _accessToken;
}
catch
{
throw new Exceptions.UnauthorizedException();
}
}
/// <summary>
/// helper method to make a get request to basecamp. checks cache first if you've already received that response and checks with basecamp if you
/// need to update your cache.
/// </summary>
/// <param name="url">the api method endpoint being called</param>
/// <exception cref="Exceptions.UnauthorizedException">Will be thrown if you cannot refresh the basecamp token when it has expired</exception>
/// <exception cref="ArgumentException">URLs must end in .json</exception>
/// <exception cref="Exceptions.RateLimitExceeded">Thrown when you exceed the ratelimit - will contain information on when you can retry</exception>
private dynamic _getJSONFromURL(string url)
{
// ensure url ends with .json or .json?xxx
if (!url.ToLower().EndsWith(".json") &&
!(url.Contains("?") && url.ToLower().Substring(0, url.IndexOf("?")).EndsWith(".json")))
{
throw new ArgumentException("Invalid URL. URLs must end in .json", url);
}
string unique_id_to_hash = (_accessToken.access_token + url.ToLower());
var cacheKey = unique_id_to_hash.CalculateMD5();
try
{
//if in cache, check with server and if not modified then return original results
string cached_results = (string)_cache.Get(cacheKey);
if (cached_results != null)
{
string if_none_match = (string)_cache.Get(cacheKey + "etag");
string if_modified_since = (string)_cache.Get(cacheKey + "lastModified");
System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
wr.Method = "HEAD";
wr.Headers.Add(System.Net.HttpRequestHeader.Authorization, string.Format("Bearer {0}", _accessToken.access_token));
wr.UserAgent = _appNameAndContact;
if (!string.IsNullOrWhiteSpace(if_modified_since))
{
wr.IfModifiedSince = DateTime.Parse(if_modified_since);
}
if (!string.IsNullOrWhiteSpace(if_none_match))
{
wr.Headers["If-None-Match"] = if_none_match;
}
var resp = (System.Net.HttpWebResponse)wr.BetterGetResponse();//use extension to properly handle 304
if (resp.StatusCode == System.Net.HttpStatusCode.NotModified)
{
return Json.Decode(cached_results);
}
}
}
catch
{
//if cache check fails just make the real request to basecamp
}
try
{
System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
wr.Method = "GET";
wr.Headers.Add(System.Net.HttpRequestHeader.Authorization, string.Format("Bearer {0}", _accessToken.access_token));
wr.UserAgent = _appNameAndContact;
var resp = (System.Net.HttpWebResponse)wr.BetterGetResponse();
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
using (var sw = new System.IO.StreamReader(resp.GetResponseStream()))
{
var strResp = sw.ReadToEnd();
var json_results = Json.Decode(strResp);
var resp_etag = resp.Headers["ETag"] != null ? resp.Headers["ETag"] : null;
var resp_last_modified = resp.Headers["Last-Modified"] != null ? resp.Headers["Last-Modified"] : null;
if (resp_etag != null || resp_last_modified != null)
{
//cache it
if (!string.IsNullOrWhiteSpace(resp_etag))
{
_cache.Set(cacheKey + "etag", resp_etag);
}
if (!string.IsNullOrWhiteSpace(resp_last_modified))
{
_cache.Set(cacheKey + "lastModified", resp_last_modified);
}
if (!string.IsNullOrWhiteSpace(strResp))
{
_cache.Set(cacheKey, strResp);
}
}
return json_results;
}
}
else if (resp.StatusCode == (System.Net.HttpStatusCode)429)//too many requests
{
throw new Exceptions.RateLimitExceededException(int.Parse(resp.Headers["Retry-After"]));
}
else if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
if (resp.Headers[System.Net.HttpResponseHeader.WwwAuthenticate] != null)
{
string www_auth = resp.Headers[System.Net.HttpResponseHeader.WwwAuthenticate];
int error_start = www_auth.LastIndexOf("error=\"token_expired\"");
if (error_start > -1)
{ //need to refresh token
throw new Exceptions.TokenExpired();
}
}
//throw an unauthorized exception if you get here
throw new Exceptions.UnauthorizedException();
}
else
{
throw new Exceptions.GeneralAPIException("Try again later. Status code returned was " + (int)resp.StatusCode, (int)resp.StatusCode);
}
}
catch (Exceptions.BaseException)
{
throw;
}
catch
{
return null;
}
}
/// <summary>
/// call this when you get a TokenExpired exception and store the new access token for future requests
/// </summary>
/// <returns>the new access token, which you should store for future calls</returns>
public dynamic RefreshAccessToken()
{
try
{
string url = string.Format(_RefreshTokenURL);
string post_body = string.Format(_RefreshTokenPostBody, System.Web.HttpUtility.UrlEncode(_clientID),
System.Web.HttpUtility.UrlEncode(_redirectURI),
System.Web.HttpUtility.UrlEncode(_clientSecret), System.Web.HttpUtility.UrlEncode(_accessToken.refresh_token));
var wr = System.Net.HttpWebRequest.Create(url);
wr.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(post_body);
wr.ContentType = "application/x-www-form-urlencoded";
wr.ContentLength = byteArray.Length;
using (System.IO.Stream dataStream = wr.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
var resp = (System.Net.HttpWebResponse)wr.GetResponse();
using (var sw = new System.IO.StreamReader(resp.GetResponseStream()))
{
_accessToken = Json.Decode(sw.ReadToEnd());
}
return _accessToken;
}
catch
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetAccounts()
{
if (IsAuthenticated)
{
return _getJSONFromURL(_AccountsURL);
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetProjects(int accountID, bool archived = false)
{
if (IsAuthenticated)
{
if (archived)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, "projects/archived"));
}
else
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, "projects"));
}
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetProject(int accountID, int projectID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}", projectID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetAccessesForProject(int accountID, int projectID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/accesses", projectID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetAccessesForCalendar(int accountID, int calendarID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("calendars/{0}/accesses", calendarID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetCalendars(int accountID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, "calendars"));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetCalendar(int accountID, int calendarID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("calendars/{0}", calendarID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetPeople(int accountID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, "people"));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetPerson(int accountID, int personID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("people/{0}", personID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetTodo(int accountID, int projectID, int todoID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/todos/{1}", projectID, todoID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetDocuments(int accountID, int projectID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/documents", projectID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetDocument(int accountID, int projectID, int documentID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/documents/{1}", projectID, documentID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetTopics(int accountID, int projectID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/topics", projectID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetAttachments(int accountID, int projectID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/attachments", projectID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetUpload(int accountID, int projectID, int uploadID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/uploads/{1}", projectID, uploadID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetTodoLists(int accountID, int projectID, bool completed = false)
{
if (IsAuthenticated)
{
if (completed)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/todolists/completed", projectID)));
}
else
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/todolists", projectID)));
}
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetTodoListsWithAssignedTodos(int accountID, int personID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("people/{0}/assigned_todos", personID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetTodoList(int accountID, int projectID, int todoListID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/todolists/{1}", projectID, todoListID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetMessage(int accountID, int projectID, int messageID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/messages/{1}", projectID, messageID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetGlobalEvents(int accountID, DateTime? since = null, int page = 1)
{
if (IsAuthenticated)
{
since = since ?? DateTime.MinValue;
string string_since = since.Value.ToString("yyyy-MM-ddTHH:mmzzz");
string url = string.Format("{0}?since={1}",
string.Format(_BaseCampAPIURL, accountID, "events"),
string_since);
if (page != 1)
{
url = string.Format("&page={1}", url, page);
}
return _getJSONFromURL(url);
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetProjectEvents(int accountID, int projectID, DateTime? since = null, int page = 1)
{
if (IsAuthenticated)
{
since = since ?? DateTime.MinValue;
string string_since = since.Value.ToString("yyyy-MM-ddTHH:mmzzz");
string url = string.Format("{0}?since={1}",
string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/events", projectID)),
string_since);
if (page != 1)
{
url = string.Format("&page={1}", url, page);
}
return _getJSONFromURL(url);
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetPersonEvents(int accountID, int personID, DateTime? since = null, int page = 1)
{
if (IsAuthenticated)
{
since = since ?? DateTime.MinValue;
string string_since = since.Value.ToString("yyyy-MM-ddTHH:mmzzz");
string url = string.Format("{0}?since={1}",
string.Format(_BaseCampAPIURL, accountID, string.Format("people/{0}/events", personID)),
string_since);
if (page != 1)
{
url = string.Format("&page={1}", url, page);
}
return _getJSONFromURL(url);
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetCalendarEventsForProject(int accountID, int projectID, bool past = false)
{
if (IsAuthenticated)
{
if (!past)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/calendar_events", projectID)));
}
else
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/calendar_events/past", projectID)));
}
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetCalendarEvents(int accountID, int calendarID, bool past = false)
{
if (IsAuthenticated)
{
if (!past)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("calendars/{0}/calendar_events", calendarID)));
}
else
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("calendars/{0}/calendar_events/past", calendarID)));
}
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetCalendarEventForProject(int accountID, int projectID, int calendarEventID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("projects/{0}/calendar_events/{1}", projectID, calendarEventID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
public dynamic GetCalendarEvent(int accountID, int calendarID, int calendarEventID)
{
if (IsAuthenticated)
{
return _getJSONFromURL(string.Format(_BaseCampAPIURL, accountID, string.Format("calendars/{0}/calendar_events/{1}", calendarID, calendarEventID)));
}
else
{
throw new Exceptions.UnauthorizedException();
}
}
}
}