Debian Codegraph @

Release/samples/WindowsLiveAuth/live_connect.h

raw
1 /***
2 * Copyright (C) Microsoft. All rights reserved.
3 * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
4 *
5 * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
6 *
7 * live_connect.h
8 *
9 * Simple API for connecting to Windows Live services, such as OneDrive and Hotmail.
10 * Only supported for App Store apps.
11 *
12 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
13 ****/
14
15 #pragma once
16
17 #include "cpprest/filestream.h"
18 #include "cpprest/http_client.h"
19 #include "cpprest/streams.h"
20 #include <collection.h>
21
22 namespace web
23 {
24 namespace live
25 {
26 #if defined(__cplusplus_winrt)
27
28 /// <summary>
29 /// This namespace contains symbols for the standard Windows Live permission scopes, which
30 /// determine what privileges the application has to access data. What operations are allowed
31 /// and what details are returned will depend on privileges requested and granted.
32 ///
33 /// See MSDN documentation for Live Connect at http://msdn.microsoft.com/en-us/live/ for details
34 /// on the precise meaning of these scopes.
35 /// </summary>
36 namespace scopes
37 {
38 static const utility::string_t wl_birthday = U("wl.birthday");
39 static const utility::string_t wl_basic = U("wl.basic");
40 static const utility::string_t wl_calendars = U("wl.calendars");
41 static const utility::string_t wl_calendars_update = U("wl.calendars_update");
42 static const utility::string_t wl_contacts_birthday = U("wl.contacts_birthday");
43 static const utility::string_t wl_contacts_create = U("wl.contacts_create");
44 static const utility::string_t wl_contacts_calendars = U("wl.contacts_calendars");
45 static const utility::string_t wl_contacts_photos = U("wl.contacts_photos");
46 static const utility::string_t wl_contacts_skydrive = U("wl.contacts_skydrive");
47 static const utility::string_t wl_emails = U("wl.emails");
48 static const utility::string_t wl_events_create = U("wl.events_create");
49 static const utility::string_t wl_messenger = U("wl.messenger");
50 static const utility::string_t wl_offline_access = U("wl.offline_access");
51 static const utility::string_t wl_phone_numbers = U("wl.phone_numbers");
52 static const utility::string_t wl_photos = U("wl.photos");
53 static const utility::string_t wl_postal_addresses = U("wl.postal_addresses");
54 static const utility::string_t wl_share = U("wl.share");
55 static const utility::string_t wl_signin = U("wl.signin");
56 static const utility::string_t wl_skydrive = U("wl.skydrive");
57 static const utility::string_t wl_skydrive_update = U("wl.skydrive_update");
58 static const utility::string_t wl_work_profile = U("wl.work_profile");
59 } // namespace scopes
60
61 /// <summary>
62 /// Represents a session connected to Windows Live services like Calendar, Contacts, OneDrive, and the
63 /// user profile, by using the Live Connect REST API. It is a thin layer on top of the Casablanca HTTP
64 /// library, tailored to the usage scenarios for Windows Live clients.
65 /// </summary>
66 /// <remarks>
67 /// See http://msdn.microsoft.com/onedrive/ for details on using the OneDrive REST API.
68 ///
69 /// Note: when passing resource paths into the functions in this class, it is not necessary to add the
70 /// leading '/' path character. It will be added automatically when constructing the HTTP request.
71 ///
72 /// Most Windows Live requests will return data in the form of plain text or JSON. The APIs in this
73 /// class will typically return data as JSON. The most significant exception to this is download(),
74 /// which will not return any data to be extracted, it will place the result in the stream or file
75 /// passed into it. Also, remove() will return data only to provide error information: for non-error
76 /// cases, the JSON value will be <c>null</c>.
77 ///
78 /// This class relies on PPL tasks to represent asynchrony: the examples contained within the comments
79 /// show synchronous forms of invoking these APIs. In real use, applications should be relying on
80 /// .then() instead of .get() or .wait().
81 /// </remarks>
82 class live_client
83 {
84 public:
85 /// <summary>
86 /// Constructs a new Windows Live client
87 /// </summary>
88 live_client()
89 : m_client(L"https://apis.live.net/v5.0/")
90 , m_authenticator(ref new Windows::Security::Authentication::OnlineId::OnlineIdAuthenticator)
91 {
92 }
93
94 /// <summary>
95 /// Authenticates the current user and requests permission to access a listed Live services.
96 /// </summary>
97 /// <param name="services">A string containing a space-separated list of access scopes to request</param>
98 /// <returns><c>true</c> if authentication succeeded, <c>false</c> otherwise.</returns>
99 pplx::task<bool> login(utility::string_t scopes)
100 {
101 this->m_token.clear();
102
103 auto request = ref new Windows::Security::Authentication::OnlineId::OnlineIdServiceTicketRequest(
104 ref new Platform::String(scopes.c_str()), "DELEGATION");
105
106 return pplx::create_task(m_authenticator->AuthenticateUserAsync(request))
107 .then([this](Windows::Security::Authentication::OnlineId::UserIdentity ^ ident) {
108 if (ident->Tickets->Size > 0)
109 {
110 auto ticket = ident->Tickets->GetAt(0);
111
112 m_token = std::wstring(ticket->Value->Data());
113 return true;
114 }
115 return false;
116 });
117 }
118
119 /// <summary>
120 /// Authenticates the current user and requests permission to access a listed Live services.
121 /// </summary>
122 /// <param name="begin">
123 /// The starting point of an iterator over a std::string collection, (for example a vector of
124 /// strings), holding the names of scopes to get permission for.
125 /// </param>
126 /// <param name="end">The end point for the same collection.</param>
127 /// <returns><c>true</c> if authentication succeeded, <c>false</c> otherwise.</returns>
128 template<typename Iter>
129 pplx::task<bool> login(Iter begin, Iter end)
130 {
131 utility::string_t services;
132
133 for (Iter iter = begin; iter != end; ++iter)
134 {
135 services.append(*iter);
136 services.append(utility::string_t(L" "));
137 }
138
139 return login(services);
140 }
141
142 /// <summary>
143 /// Dismisses any and all permissions that have been granted to the user.
144 /// </summary>
145 /// <returns><c>true</c> if logout succeeded, <c>false</c> otherwise.</returns>
146 /// <remarks>
147 /// Whether the logout attempt was successful or not, the application will
148 /// be required to log in again, since the access token will be cleared.
149 /// </remarks>
150 pplx::task<bool> logout()
151 {
152 this->m_token.clear();
153
154 if (!m_authenticator->CanSignOut) return pplx::task_from_result(false);
155
156 return pplx::create_task(m_authenticator->SignOutUserAsync()).then([this] { return true; });
157 }
158
159 /// <summary>
160 /// Retrieves the access token in use by this client instance.
161 /// </summary>
162 /// <returns>The current token: a string. An invalid token is indicated by an empty string.</returns>
163 const utility::string_t& access_token() const { return m_token; }
164
165 /// <summary>
166 /// Retrieves data from Windows Live.
167 /// </summary>
168 /// <param name="resource">The Windows Live resource to retrieve.</param>
169 /// <returns>The JSON value resulting from the request.</returns>
170 /// <example>To get the current user profile: <code>json::value profile =
171 /// live_clnt.get(L"me").get().extract_json().get();</code></example>
172 pplx::task<web::json::value> get(const utility::string_t& resource)
173 {
174 return _make_request(web::http::methods::GET, resource).then([](web::http::http_response response) {
175 return _json_extract(response);
176 });
177 }
178
179 /// <summary>
180 /// Deletes data from Windows Live.
181 /// </summary>
182 /// <param name="resource">The Windows Live resource to delete.</param>
183 /// <returns>The JSON value resulting from the request.</returns>
184 /// <example>To delete a file: <code>live_clnt.remove(L"file.NNNNNNNNNNNN").wait();</code>, where file.NNNNNNNNNNNN
185 /// is a file identifier.</example>
186 pplx::task<web::json::value> remove(const utility::string_t& resource)
187 {
188 return _make_request(web::http::methods::DEL, resource).then([](web::http::http_response response) {
189 return _json_extract(response);
190 });
191 }
192
193 /// <summary>
194 /// Modifies data in Windows Live.
195 /// </summary>
196 /// <param name="resource">The Windows Live resource to modify.</param>
197 /// <returns>The JSON value resulting from the request.</returns>
198 /// <remarks>In most cases, the response will contain data about the modified resource.</remarks>
199 pplx::task<web::json::value> put(const utility::string_t& resource, const web::json::value& data)
200 {
201 return _make_request(web::http::methods::PUT, resource, data).then([](web::http::http_response response) {
202 return _json_extract(response);
203 });
204 }
205
206 /// <summary>
207 /// Adds data to Windows Live.
208 /// </summary>
209 /// <param name="resource">The Windows Live resource (such as a folder) where data should be added.</param>
210 /// <returns>The JSON value resulting from the request.</returns>
211 /// <remarks>In most cases, the response will contain data about the added resource.</remarks>
212 /// <example>To add a contact: <code>json::value contact = ...; live_clnt.post(L"me/contacts",
213 /// contact).wait();</code></example>
214 pplx::task<web::json::value> post(const utility::string_t& resource, const web::json::value& data)
215 {
216 return _make_request(web::http::methods::POST, resource, data).then([](web::http::http_response response) {
217 return _json_extract(response);
218 });
219 }
220
221 /// <summary>
222 /// Copies data in Windows Live.
223 /// </summary>
224 /// <param name="resource">The Windows Live resource to copy.</param>
225 /// <param name="destination">The location where the resource copy should be placed.</param>
226 /// <returns>The JSON value resulting from the request.</returns>
227 /// <remarks>In most cases, the response will contain data about the added resource.</remarks>
228 /// <example>To copy a file: <code>live_clnt.copy(L"file.NNNNNNNNNNNN",
229 /// L"folder.MMMMMMMMMMMM").wait();</code></example>
230 pplx::task<web::json::value> copy(const utility::string_t& resource, const utility::string_t& destination)
231 {
232 return _make_request(U("COPY"), resource, destination).then([](web::http::http_response response) {
233 return _json_extract(response);
234 });
235 }
236
237 /// <summary>
238 /// Moves data in Windows Live.
239 /// </summary>
240 /// <param name="resource">The Windows Live resource to move.</param>
241 /// <param name="destination">The location where the resource should be placed.</param>
242 /// <returns>The JSON value resulting from the request.</returns>
243 /// <remarks>In most cases, the response will contain data about the resource in its new location.</remarks>
244 /// <example>To copy a file: <code>live_clnt.copy(L"file.NNNNNNNNNNNN",
245 /// L"folder.MMMMMMMMMMMM").wait();</code></example>
246 pplx::task<web::json::value> move(const utility::string_t& resource, const utility::string_t& destination)
247 {
248 return _make_request(U("MOVE"), resource, destination).then([](web::http::http_response response) {
249 return _json_extract(response);
250 });
251 }
252
253 /// <summary>
254 /// Download a file from OneDrive.
255 /// </summary>
256 /// <param name="file_id">The OneDrive file id to download.</param>
257 /// <param name="stream">A stream into which the contents of the file should be placed.</param>
258 /// <returns>The size of the downloaded resource.</returns>
259 /// <remarks></remarks>
260 /// <example>To download a file: <code>ostream stream = ...; live_clnt.download(L"file.NNNNNNNNNNNN",
261 /// ostream).get().content_ready().wait();</code></example>
262 pplx::task<size_t> download(const utility::string_t& file_id, concurrency::streams::ostream stream)
263 {
264 web::http::uri_builder bldr;
265 bldr.append(file_id);
266 bldr.append_path(U("content"));
267
268 web::http::http_request req(web::http::methods::GET);
269 req.set_request_uri(bldr.to_string());
270
271 return _make_request(req).then([stream](web::http::http_response response) -> pplx::task<size_t> {
272 if (response.status_code() >= 400)
273 {
274 return response.extract_string().then([](utility::string_t message) -> pplx::task<size_t> {
275 return pplx::task_from_exception<size_t>(
276 std::exception(utility::conversions::to_utf8string(message).c_str()));
277 });
278 }
279 return response.body().read_to_end(stream.streambuf());
280 });
281 }
282
283 /// <summary>
284 /// Download a file from OneDrive.
285 /// </summary>
286 /// <param name="file_id">The OneDrive file id to download.</param>
287 /// <param name="file">A StorageFile reference identifying the target for the downloaded data.</param>
288 /// <returns>The size of the downloaded resource.</returns>
289 /// <remarks></remarks>
290 pplx::task<size_t> download(const utility::string_t& file_id, Windows::Storage::StorageFile ^ file)
291 {
292 if (file == nullptr) throw std::invalid_argument("file reference cannot be null");
293
294 return concurrency::streams::file_stream<uint8_t>::open_ostream(file).then(
295 [file_id, this](concurrency::streams::ostream stream) {
296 web::http::uri_builder bldr;
297 bldr.append(file_id);
298 bldr.append_path(U("content"));
299
300 web::http::http_request req(web::http::methods::GET);
301 req.set_request_uri(bldr.to_string());
302
303 return _make_request(req)
304 .then([stream](web::http::http_response response) -> pplx::task<size_t> {
305 if (response.status_code() >= 400)
306 {
307 return response.extract_string().then([](utility::string_t message) -> pplx::task<size_t> {
308 return pplx::task_from_exception<size_t>(
309 std::exception(utility::conversions::to_utf8string(message).c_str()));
310 });
311 }
312 return response.body().read_to_end(stream.streambuf());
313 })
314 .then([stream](pplx::task<size_t> ret_task) {
315 return stream.flush().then([stream, ret_task]() { return stream.close(); }).then([ret_task]() {
316 return ret_task;
317 });
318 });
319 });
320 }
321
322 /// <summary>
323 /// Upload a file to OneDrive.
324 /// </summary>
325 /// <param name="path">The path of the file location in OneDrive. It should be of the form
326 /// "folder.NNNNNNNNNN/files/file_name.ext"</param> <param name="stream">A stream from which data for the file will
327 /// be read.</param> <param name="content_length">The size of the data to upload.</param> <returns>The JSON value
328 /// resulting from the request, containing metadata about the uploaded file.</returns> <remarks>
329 /// The stream must contain at least as many bytes as indicated by 'content_length', starting from its current
330 /// read position.
331 /// </remarks>
332 pplx::task<web::json::value> upload(const utility::string_t& path,
333 concurrency::streams::istream stream,
334 size_t content_length)
335 {
336 web::http::uri_builder bldr;
337 bldr.append(path);
338
339 web::http::http_request req(web::http::methods::PUT);
340 req.set_request_uri(bldr.to_string());
341 req.set_body(stream, content_length, utility::string_t{});
342
343 return _make_request(req).then([](web::http::http_response response) { return _json_extract(response); });
344 }
345
346 /// <summary>
347 /// Upload a file to OneDrive.
348 /// </summary>
349 /// <param name="path">The path of the file location in OneDrive. It should be of the form
350 /// "folder.NNNNNNNNNN/files/file_name.ext"</param> <param name="file">A StorageFile reference identifying the
351 /// source of the uploaded data.</param> <param name="content_length">The size of the data to upload.</param>
352 /// <returns>The JSON value resulting from the request, containing metadata about the uploaded file.</returns>
353 /// <remarks>The entire file will be uploaded.</remarks>
354 pplx::task<web::json::value> upload(const utility::string_t& path, Windows::Storage::StorageFile ^ file)
355 {
356 if (file == nullptr) throw std::invalid_argument("file reference cannot be null");
357
358 return pplx::create_task(file->GetBasicPropertiesAsync())
359 .then([path, this, file](Windows::Storage::FileProperties::BasicProperties ^ props) {
360 if (props == nullptr)
361 throw std::exception("failed to retrieve file properties; cannot determine its size");
362 size_t size = (size_t)props->Size;
363
364 return concurrency::streams::file_stream<uint8_t>::open_istream(file).then(
365 [path, this, size](concurrency::streams::istream stream) {
366 web::http::uri_builder bldr;
367 bldr.append(path);
368
369 web::http::http_request req(web::http::methods::PUT);
370 req.set_request_uri(bldr.to_string());
371 req.set_body(stream, size, utility::string_t{});
372
373 return _make_request(req)
374 .then([](web::http::http_response response) { return response.content_ready(); })
375 .then([stream](pplx::task<web::http::http_response> response) {
376 return stream.close().then([response]() { return _json_extract(response.get()); });
377 });
378 });
379 });
380 }
381
382 private:
383 static pplx::task<web::json::value> _json_extract(web::http::http_response response)
384 {
385 switch (response.status_code())
386 {
387 case web::http::status_codes::NoContent: return pplx::task_from_result(web::json::value::null());
388 default:
389 if (response.status_code() >= 400)
390 {
391 return response.extract_string().then(
392 [](utility::string_t message) -> pplx::task<web::json::value> {
393 return pplx::task_from_exception<web::json::value>(
394 std::exception(utility::conversions::to_utf8string(message).c_str()));
395 });
396 }
397 return response.extract_json();
398 }
399 }
400
401 pplx::task<web::http::http_response> _make_request(web::http::method method, const utility::string_t& path)
402 {
403 web::http::uri_builder bldr;
404 bldr.append(path);
405
406 web::http::http_request req(method);
407 req.set_request_uri(bldr.to_string());
408 return _make_request(req);
409 }
410
411 pplx::task<web::http::http_response> _make_request(web::http::method method,
412 const utility::string_t& path,
413 const web::json::value& data)
414 {
415 web::http::uri_builder bldr;
416 bldr.append(path);
417
418 web::http::http_request req(method);
419 req.set_request_uri(bldr.to_string());
420 req.set_body(data);
421 return _make_request(req);
422 }
423
424 pplx::task<web::http::http_response> _make_request(web::http::method method,
425 const utility::string_t& path,
426 const utility::string_t& destination)
427 {
428 web::http::uri_builder bldr;
429 bldr.append(path);
430
431 web::json::value data;
432 data[U("destination")] = web::json::value::string(destination);
433
434 web::http::http_request req(method);
435 req.set_request_uri(bldr.to_string());
436 req.set_body(data);
437 return _make_request(req);
438 }
439
440 pplx::task<web::http::http_response> _make_request(web::http::http_request req)
441 {
442 if (!m_token.empty()) req.headers().add(U("Authorization"), U("Bearer ") + m_token);
443 return m_client.request(req);
444 }
445
446 Windows::Security::Authentication::OnlineId::OnlineIdAuthenticator ^ m_authenticator;
447 web::http::client::http_client m_client;
448 utility::string_t m_token;
449 };
450 #endif
451 } // namespace live
452 } // namespace web