-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLibCalClient.cs
216 lines (201 loc) · 7.99 KB
/
LibCalClient.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
using Flurl.Http;
using LibCalTypes;
using Newtonsoft.Json.Linq;
class LibCalClient
{
public LibCalClient()
{
Client = new FlurlClient("https://pitt.libcal.com");
}
IFlurlClient Client { get; }
/// <summary>
/// Send a client id and secret to get an access token and save it to the client.
/// </summary>
/// <param name="clientId"></param>
/// <param name="clientSecret"></param>
/// <exception cref="Exception"></exception>
public async Task Authorize(string clientId, string clientSecret)
{
var response = await Client.Request("/1.1/oauth/token")
.PostUrlEncodedAsync(new
{
client_id = clientId,
client_secret = clientSecret,
grant_type = "client_credentials"
}).ReceiveJson<JObject>();
var accessToken = response["access_token"]?.ToString() ??
throw new Exception("Auth response missing access token.");
Client.WithOAuthBearerToken(accessToken);
}
/// <summary>
/// Get all calendar ids.
/// </summary>
/// <returns></returns>
public async Task<List<int>> GetCalendarIds()
{
var response = await Client.Request("/1.1/calendars")
.GetJsonAsync<JObject>();
return response["calendars"].Select(cal => (int)cal["calid"]).ToList();
}
/// <summary>
/// Get events from a calendar between two given dates, inclusive.
/// </summary>
/// <param name="calendarId"></param>
/// <param name="fromDate"></param>
/// <param name="toDate"></param>
/// <returns></returns>
public async Task<List<Event>> GetEvents(int calendarId, DateTime fromDate, DateTime toDate)
{
return await GetInDateInterval<EventsResponse, Event>(
Client.Request("1.1/events").SetQueryParam("cal_id", calendarId),
fromDate,
toDate,
resp => resp.Events);
}
/// <summary>
/// Given a list of event ids, gets registrant info for those events.
/// </summary>
/// <param name="eventIds">
/// List of event ids.
/// Unclear from the API docs what the upper limit is on the number of ids per call.
/// </param>
/// <returns></returns>
public async Task<List<RegistrationsResponse>> GetRegistrations(IEnumerable<long> eventIds)
{
return await Client.Request("api/1.1/events", string.Join(',', eventIds), "registrations")
.GetJsonAsync<List<RegistrationsResponse>>();
}
/// <summary>
/// Get details for an Appointments user.
/// </summary>
/// <returns></returns>
public async Task<AppointmentUser> GetAppointmentUser(long userId)
{
return await Client.Request("/1.1/appointments")
.SetQueryParam("user_id", userId)
.GetJsonAsync<AppointmentUser>();
}
/// <summary>
/// Gets all appointment bookings between two dates, inclusive.
/// </summary>
/// <param name="fromDate"></param>
/// <param name="toDate"></param>
/// <returns></returns>
public Task<List<AppointmentBooking>> GetAppointmentBookings(DateTime fromDate, DateTime toDate)
{
return GetInDateInterval<AppointmentBooking>(Client.Request("/1.1/appointments/bookings"), fromDate, toDate);
}
/// <summary>
/// Get the questions associated with an appointment
/// </summary>
/// <param name="questionIds"></param>
/// <returns></returns>
public Task<List<AppointmentQuestion>> GetAppointmentQuestions(IEnumerable<long> questionIds)
{
return Client.Request("/api/1.1/appointments/question", string.Join(',', questionIds))
.GetJsonAsync<List<AppointmentQuestion>>();
}
/// <summary>
/// Get the space bookings for a given date interval.
/// </summary>
/// <returns></returns>
public Task<List<SpaceBooking>> GetSpaceBookings(DateTime fromDate, DateTime toDate)
{
return GetInDateIntervalPaged<SpaceBooking>(Client.Request("/1.1/space/bookings"), fromDate, toDate);
}
/// <summary>
/// Get all data between two given dates by splitting them into periods.
/// Each individual call has a limit of 500, so if you are hitting that limit, try reducing the period.
/// </summary>
/// <param name="request"></param>
/// <param name="fromDate"></param>
/// <param name="toDate"></param>
/// <param name="mapFunc"></param>
/// <param name="periodLengthInDays"></param>
/// <typeparam name="TResponse"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <returns></returns>
static async Task<List<TResult>> GetInDateInterval<TResponse, TResult>(IFlurlRequest request, DateTime fromDate,
DateTime toDate, Func<TResponse, IEnumerable<TResult>> mapFunc, int periodLengthInDays = 30)
{
var results = new List<TResult>();
var currentDate = fromDate;
do
{
// Period length -1 because otherwise it would double-count some days
var days = Math.Min((toDate - currentDate).Days, periodLengthInDays - 1);
var response = await request
.SetQueryParams(new
{
date = currentDate.ToString("yyyy-M-d"),
days,
limit = 500
})
.GetJsonAsync<TResponse>();
results.AddRange(mapFunc(response));
currentDate = currentDate.AddDays(periodLengthInDays);
} while (currentDate < toDate);
return results;
}
/// <summary>
/// Get all data between two given dates by splitting them into periods.
/// Each individual call has a limit of 500, so if you are hitting that limit, try reducing the period.
/// </summary>
/// <param name="request"></param>
/// <param name="fromDate"></param>
/// <param name="toDate"></param>
/// <param name="periodLengthInDays"></param>
/// <typeparam name="TResponse"></typeparam>
/// <returns></returns>
static Task<List<TResponse>> GetInDateInterval<TResponse>(IFlurlRequest request, DateTime fromDate, DateTime toDate,
int periodLengthInDays = 30)
{
return GetInDateInterval<List<TResponse>, TResponse>(request, fromDate, toDate, x => x, periodLengthInDays);
}
/// <summary>
/// Get all data between two given dates using pagination.
/// </summary>
/// <param name="request"></param>
/// <param name="fromDate"></param>
/// <param name="toDate"></param>
/// <param name="mapFunc"></param>
/// <typeparam name="TResponse"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <returns></returns>
static async Task<List<TResult>> GetInDateIntervalPaged<TResponse, TResult>(IFlurlRequest request, DateTime fromDate,
DateTime toDate, Func<TResponse, IEnumerable<TResult>> mapFunc)
{
var results = new List<TResult>();
var page = 1;
while (true) {
var response = await request
.SetQueryParams(new
{
date = fromDate.ToString("yyyy-M-d"),
days = (toDate - fromDate).Days,
page,
limit = 500
})
.GetJsonAsync<TResponse>();
var resultCount = results.Count;
results.AddRange(mapFunc(response));
if (resultCount == results.Count) {
// no new results were returned, i.e. no more pages.
return results;
}
page++;
}
}
/// <summary>
/// Get all data between two given dates using pagination.
/// </summary>
/// <param name="request"></param>
/// <param name="fromDate"></param>
/// <param name="toDate"></param>
/// <typeparam name="TResponse"></typeparam>
/// <returns></returns>
static Task<List<TResponse>> GetInDateIntervalPaged<TResponse>(IFlurlRequest request, DateTime fromDate, DateTime toDate)
{
return GetInDateIntervalPaged<List<TResponse>, TResponse>(request, fromDate, toDate, x => x);
}
}