Debian Codegraph @

src/EWS/addressbook/e-book-backend-ews.c

raw
1 /*
2 * SPDX-FileCopyrightText: (C) 1999-2008 Novell, Inc. (www.novell.com)
3 * SPDX-FileCopyrightText: (C) 2017 Red Hat, Inc. (www.redhat.com)
4 * SPDX-License-Identifier: LGPL-2.1-or-later
5 */
6
7 #include "evolution-ews-config.h"
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <sys/time.h>
15 #include <time.h>
16 #include <unistd.h>
17 #include <errno.h>
18
19 #include <glib.h>
20 #include <glib/gstdio.h>
21 #include <glib/gi18n-lib.h>
22
23 #define LIBICAL_GLIB_UNSTABLE_API
24 #include <libical-glib/libical-glib.h>
25 #undef LIBICAL_GLIB_UNSTABLE_API
26
27 #include <libedata-book/libedata-book.h>
28
29 #include "common/e-ews-item-change.h"
30 #include "common/e-ews-request.h"
31 #include "common/e-ews-connection.h"
32 #include "common/e-ews-connection-utils.h"
33 #include "common/e-ews-item.h"
34 #include "common/e-ews-query-to-restriction.h"
35 #include "common/e-source-ews-folder.h"
36
37 #include "e-book-backend-ews.h"
38 #include "ews-oab-decoder.h"
39 #include "ews-oab-decompress.h"
40
41 #ifdef G_OS_WIN32
42 #ifdef gmtime_r
43 #undef gmtime_r
44 #endif
45
46 /* The gmtime() in Microsoft's C library is MT-safe */
47 #define gmtime_r(tp,tmp) (gmtime(tp)?(*(tmp)=*gmtime(tp),(tmp)):0)
48 #endif
49
50 #define d(x)
51
52 #define EC_ERROR_EX(_code,_msg) e_client_error_create (_code, _msg)
53 #define EBC_ERROR_EX(_code,_msg) e_book_client_error_create (_code, _msg)
54
55 #define EBB_EWS_DATA_VERSION 1
56 #define EBB_EWS_DATA_VERSION_KEY "ews-data-version"
57
58 #define EBB_EWS_SYNC_TAG_STAMP_KEY "ews-sync-tag-stamp"
59
60 #define X_EWS_ORIGINAL_VCARD "X-EWS-ORIGINAL-VCARD"
61 #define X_EWS_CHANGEKEY "X-EWS-CHANGEKEY"
62 #define X_EWS_GAL_SHA1 "X-EWS-GAL-SHA1"
63 #define X_EWS_PHOTO_CHECK_DATE "X-EWS-PHOTO-CHECK-DATE" /* YYYYMMDD of the last check for photo */
64 #define X_EWS_CERT_KIND "X-EWS-CERT-KIND"
65
66 #define E_EWS_CERT_KIND_USER "UserSMIMECertificate"
67 #define E_EWS_CERT_KIND_MSEX "MSExchangeCertificate"
68
69 #define EWS_MAX_FETCH_COUNT 500
70
71 #define ELEMENT_TYPE_SIMPLE 0x01 /* simple string fields */
72 #define ELEMENT_TYPE_COMPLEX 0x02 /* complex fields while require different get/set functions */
73
74 /* passing field uris for PhysicalAddress, PhoneNumbers causes error, so we
75 * use Default view to fetch them. Thus the summary props just have attachments
76 * and some additional properties that are not return with Default view */
77 #define CONTACT_ITEM_PROPS "item:Attachments "\
78 "item:HasAttachments "\
79 "item:Body "\
80 "item:Categories " \
81 "item:LastModifiedTime "\
82 "contacts:Manager "\
83 "contacts:Department "\
84 "contacts:SpouseName "\
85 "contacts:AssistantName "\
86 "contacts:BusinessHomePage "\
87 "contacts:Birthday"
88 #define CONTACT_ITEM_PROPS_10SP2 CONTACT_ITEM_PROPS " "\
89 "contacts:UserSMIMECertificate "\
90 "contacts:MSExchangeCertificate"
91
92 struct _EBookBackendEwsPrivate {
93 GRecMutex cnc_lock;
94 EEwsConnection *cnc;
95
96 gchar *folder_id;
97 gboolean is_gal;
98 gboolean fetching_gal_photos;
99 gboolean gal_oab_broken; /* to use ResolveNames when OAB cannot be found or is misconfigured */
100
101 guint subscription_key;
102
103 /* The subscription ID is not tight to the actual connection, it survives
104 disconnects, thus remember it and pass it back to the new connection,
105 thus it can eventually unsubscribe from it. */
106 gchar *last_subscription_id;
107
108 /* used for storing attachments */
109 gchar *attachments_dir;
110
111 GHashTable *view_cancellables; /* gpointer view ~> GCancellable; shares cnc_lock */
112 };
113
114 G_DEFINE_TYPE_WITH_PRIVATE (EBookBackendEws, e_book_backend_ews, E_TYPE_BOOK_META_BACKEND)
115
116 static void
117 ebb_ews_remove_x_attribute (EContact *contact,
118 const gchar *xname)
119 {
120 g_return_if_fail (E_IS_CONTACT (contact));
121 g_return_if_fail (xname != NULL);
122
123 e_vcard_remove_attributes (E_VCARD (contact), NULL, xname);
124 }
125
126 static void
127 ebb_ews_store_x_attribute (EContact *contact,
128 const gchar *xname,
129 const gchar *value)
130 {
131 EVCardAttribute *attr;
132
133 g_return_if_fail (E_IS_CONTACT (contact));
134 g_return_if_fail (xname != NULL);
135
136 ebb_ews_remove_x_attribute (contact, xname);
137
138 if (!value)
139 return;
140
141 attr = e_vcard_attribute_new ("", xname);
142 e_vcard_attribute_add_value (attr, value);
143 e_vcard_add_attribute (E_VCARD (contact), attr);
144 }
145
146 static const gchar *
147 ebb_ews_get_x_attribute (EContact *contact,
148 const gchar *xname)
149 {
150 EVCardAttribute *attr;
151 GList *values = NULL;
152 const gchar *value;
153
154 g_return_val_if_fail (E_IS_CONTACT (contact), NULL);
155 g_return_val_if_fail (xname != NULL, NULL);
156
157 attr = e_vcard_get_attribute (E_VCARD (contact), xname);
158 if (!attr)
159 return NULL;
160
161 values = e_vcard_attribute_get_values (attr);
162 if (!values)
163 return NULL;
164
165 value = values->data;
166
167 if (value && *value)
168 return value;
169
170 return NULL;
171 }
172
173 static const gchar *
174 ebb_ews_get_original_vcard (EContact *contact)
175 {
176 g_return_val_if_fail (E_IS_CONTACT (contact), NULL);
177
178 return ebb_ews_get_x_attribute (contact, X_EWS_ORIGINAL_VCARD);
179 }
180
181 static void
182 ebb_ews_store_original_vcard (EContact *contact)
183 {
184 gchar *vcard_str;
185
186 g_return_if_fail (E_IS_CONTACT (contact));
187
188 /* This makes sure it's not saved also in the original vCard */
189 ebb_ews_remove_x_attribute (contact, X_EWS_ORIGINAL_VCARD);
190
191 vcard_str = e_vcard_to_string (E_VCARD (contact), EVC_FORMAT_VCARD_30);
192
193 ebb_ews_store_x_attribute (contact, X_EWS_ORIGINAL_VCARD, vcard_str);
194
195 g_free (vcard_str);
196 }
197
198 static gchar *
199 ebb_ews_get_today_as_string (void)
200 {
201 GDate date;
202
203 g_date_clear (&date, 1);
204 g_date_set_time_t (&date, time (NULL));
205
206 return g_strdup_printf ("%04d%02d%02d", g_date_get_year (&date), g_date_get_month (&date), g_date_get_day (&date));
207 }
208
209 static const gchar *
210 ebb_ews_get_photo_check_date (EContact *contact)
211 {
212 g_return_val_if_fail (E_IS_CONTACT (contact), NULL);
213
214 return ebb_ews_get_x_attribute (contact, X_EWS_PHOTO_CHECK_DATE);
215 }
216
217 static void
218 ebb_ews_store_photo_check_date (EContact *contact,
219 const gchar *value)
220 {
221 gchar *today_str = NULL;
222
223 g_return_if_fail (E_IS_CONTACT (contact));
224
225 if (!value) {
226 today_str = ebb_ews_get_today_as_string ();
227 value = today_str;
228 }
229
230 ebb_ews_store_x_attribute (contact, X_EWS_PHOTO_CHECK_DATE, value);
231
232 g_free (today_str);
233 }
234
235 static gboolean
236 ebb_ews_can_check_user_photo (EContact *contact)
237 {
238 const gchar *last_check;
239 gboolean can;
240
241 g_return_val_if_fail (E_IS_CONTACT (contact), FALSE);
242
243 last_check = ebb_ews_get_photo_check_date (contact);
244 if (last_check && *last_check) {
245 gchar *today_str;
246
247 today_str = ebb_ews_get_today_as_string ();
248 can = g_strcmp0 (last_check, today_str) != 0;
249 g_free (today_str);
250 } else {
251 can = TRUE;
252 }
253
254 return can;
255 }
256
257 static CamelEwsSettings *
258 ebb_ews_get_collection_settings (EBookBackendEws *bbews)
259 {
260 ESource *source;
261 ESource *collection;
262 ESourceCamel *extension;
263 ESourceRegistry *registry;
264 CamelSettings *settings;
265 const gchar *extension_name;
266
267 source = e_backend_get_source (E_BACKEND (bbews));
268 registry = e_book_backend_get_registry (E_BOOK_BACKEND (bbews));
269
270 extension_name = e_source_camel_get_extension_name ("ews");
271 e_source_camel_generate_subtype ("ews", CAMEL_TYPE_EWS_SETTINGS);
272
273 /* The collection settings live in our parent data source. */
274 collection = e_source_registry_find_extension (registry, source, extension_name);
275 g_return_val_if_fail (collection != NULL, NULL);
276
277 extension = e_source_get_extension (collection, extension_name);
278 settings = e_source_camel_get_settings (extension);
279
280 g_object_unref (collection);
281
282 return CAMEL_EWS_SETTINGS (settings);
283 }
284
285 static gboolean
286 ebb_ews_get_sync_tag_stamp_changed (EBookBackendEws *bbews)
287 {
288 CamelEwsSettings *settings;
289 EBookCache *book_cache;
290 guint sync_tag_stamp;
291
292 settings = ebb_ews_get_collection_settings (bbews);
293 g_return_val_if_fail (settings != NULL, FALSE);
294
295 book_cache = e_book_meta_backend_ref_cache (E_BOOK_META_BACKEND (bbews));
296 if (!book_cache)
297 return FALSE;
298
299 sync_tag_stamp = e_cache_get_key_int (E_CACHE (book_cache), EBB_EWS_SYNC_TAG_STAMP_KEY, NULL);
300 if (sync_tag_stamp == (guint) -1)
301 sync_tag_stamp = 0;
302
303 g_clear_object (&book_cache);
304
305 return sync_tag_stamp != camel_ews_settings_get_sync_tag_stamp (settings);
306 }
307
308 static void
309 ebb_ews_update_sync_tag_stamp (EBookBackendEws *bbews)
310 {
311 CamelEwsSettings *settings;
312 EBookCache *book_cache;
313 guint sync_tag_stamp;
314
315 settings = ebb_ews_get_collection_settings (bbews);
316 g_return_if_fail (settings != NULL);
317
318 book_cache = e_book_meta_backend_ref_cache (E_BOOK_META_BACKEND (bbews));
319 if (!book_cache)
320 return;
321
322 sync_tag_stamp = e_cache_get_key_int (E_CACHE (book_cache), EBB_EWS_SYNC_TAG_STAMP_KEY, NULL);
323
324 if (sync_tag_stamp != camel_ews_settings_get_sync_tag_stamp (settings))
325 e_cache_set_key_int (E_CACHE (book_cache), EBB_EWS_SYNC_TAG_STAMP_KEY, camel_ews_settings_get_sync_tag_stamp (settings), NULL);
326
327 g_clear_object (&book_cache);
328 }
329
330 static void
331 ebb_ews_convert_error_to_client_error (GError **perror)
332 {
333 GError *error = NULL;
334
335 if (!perror || !*perror || (*perror)->domain == E_CLIENT_ERROR || (*perror)->domain == E_BOOK_CLIENT_ERROR)
336 return;
337
338 if ((*perror)->domain == EWS_CONNECTION_ERROR) {
339 switch ((*perror)->code) {
340 case EWS_CONNECTION_ERROR_AUTHENTICATION_FAILED:
341 error = EC_ERROR_EX (E_CLIENT_ERROR_AUTHENTICATION_FAILED, (*perror)->message);
342 break;
343 case EWS_CONNECTION_ERROR_FOLDERNOTFOUND:
344 case EWS_CONNECTION_ERROR_MANAGEDFOLDERNOTFOUND:
345 case EWS_CONNECTION_ERROR_PARENTFOLDERNOTFOUND:
346 case EWS_CONNECTION_ERROR_PUBLICFOLDERSERVERNOTFOUND:
347 error = EBC_ERROR_EX (E_BOOK_CLIENT_ERROR_NO_SUCH_BOOK, (*perror)->message);
348 break;
349 case EWS_CONNECTION_ERROR_EVENTNOTFOUND:
350 case EWS_CONNECTION_ERROR_ITEMNOTFOUND:
351 error = EBC_ERROR_EX (E_BOOK_CLIENT_ERROR_CONTACT_NOT_FOUND, (*perror)->message);
352 break;
353 case EWS_CONNECTION_ERROR_UNAVAILABLE:
354 g_set_error_literal (&error, G_IO_ERROR, G_IO_ERROR_HOST_NOT_FOUND, (*perror)->message);
355 break;
356 }
357
358 if (!error)
359 error = EC_ERROR_EX (E_CLIENT_ERROR_OTHER_ERROR, (*perror)->message);
360 }
361
362 if (error) {
363 g_error_free (*perror);
364 *perror = error;
365 }
366 }
367
368 static void
369 ebb_ews_maybe_disconnect_sync (EBookBackendEws *bbews,
370 GError **in_perror,
371 GCancellable *cancellable)
372 {
373 g_return_if_fail (E_IS_BOOK_BACKEND_EWS (bbews));
374
375 if (in_perror && g_error_matches (*in_perror, E_CLIENT_ERROR, E_CLIENT_ERROR_AUTHENTICATION_FAILED)) {
376 e_book_meta_backend_disconnect_sync (E_BOOK_META_BACKEND (bbews), cancellable, NULL);
377 e_backend_schedule_credentials_required (E_BACKEND (bbews), E_SOURCE_CREDENTIALS_REASON_REJECTED, NULL, 0, NULL, NULL, G_STRFUNC);
378 }
379 }
380
381 static const struct phone_field_mapping {
382 EContactField field;
383 const gchar *element;
384 } phone_field_map[] = {
385 {E_CONTACT_PHONE_ASSISTANT, "AssistantPhone"},
386 {E_CONTACT_PHONE_BUSINESS_FAX, "BusinessFax"},
387 {E_CONTACT_PHONE_BUSINESS, "BusinessPhone"},
388 {E_CONTACT_PHONE_BUSINESS_2, "BusinessPhone2"},
389 {E_CONTACT_PHONE_CAR, "CarPhone"},
390 {E_CONTACT_PHONE_COMPANY, "CompanyMainPhone"},
391 {E_CONTACT_PHONE_HOME_FAX, "HomeFax"},
392 {E_CONTACT_PHONE_HOME, "HomePhone"},
393 {E_CONTACT_PHONE_HOME_2, "HomePhone2"},
394 {E_CONTACT_PHONE_ISDN, "Isdn"},
395 {E_CONTACT_PHONE_MOBILE, "MobilePhone"},
396 {E_CONTACT_PHONE_OTHER_FAX, "OtherFax"},
397 {E_CONTACT_PHONE_OTHER, "OtherTelephone"},
398 {E_CONTACT_PHONE_PAGER, "Pager"},
399 {E_CONTACT_PHONE_PRIMARY, "PrimaryPhone"},
400 {E_CONTACT_PHONE_RADIO, "RadioPhone"},
401 {E_CONTACT_PHONE_TELEX, "Telex"},
402 {E_CONTACT_PHONE_TTYTDD, "TtyTddPhone"}
403 };
404
405 static void
406 ebews_populate_rev (EContact *contact,
407 EEwsItem *item)
408 {
409 struct tm stm;
410 time_t tt = 0;
411 gchar time_string[100] = { 0 };
412
413 g_return_if_fail (E_IS_CONTACT (contact));
414
415 if (item) {
416 g_return_if_fail (E_IS_EWS_ITEM (item));
417
418 tt = e_ews_item_get_last_modified_time (item);
419 }
420
421 if (tt <= 0)
422 tt = time (NULL);
423
424 gmtime_r (&tt, &stm);
425 strftime (time_string, 100, "%Y-%m-%dT%H:%M:%SZ", &stm);
426
427 e_contact_set (contact, E_CONTACT_REV, time_string);
428 }
429
430 static void
431 ebews_populate_uid (EBookBackendEws *bbews,
432 EContact *contact,
433 EEwsItem *item,
434 GCancellable *cancellable,
435 GError **error)
436 {
437 const EwsId *id;
438
439 id = e_ews_item_get_id (item);
440 if (id) {
441 e_contact_set (contact, E_CONTACT_UID, id->id);
442 ebews_populate_rev (contact, item);
443 e_vcard_util_set_x_attribute (E_VCARD (contact), X_EWS_CHANGEKEY, id->change_key);
444 }
445 }
446
447 static void
448 ebews_populate_full_name (EBookBackendEws *bbews,
449 EContact *contact,
450 EEwsItem *item,
451 GCancellable *cancellable,
452 GError **error)
453 {
454 const EwsCompleteName *cn;
455
456 cn = e_ews_item_get_complete_name (item);
457 if (cn)
458 e_contact_set (contact, E_CONTACT_FULL_NAME, cn->full_name);
459 }
460
461 static void
462 ebews_populate_nick_name (EBookBackendEws *bbews,
463 EContact *contact,
464 EEwsItem *item,
465 GCancellable *cancellable,
466 GError **error)
467 {
468 const EwsCompleteName *cn;
469
470 cn = e_ews_item_get_complete_name (item);
471 if (cn)
472 e_contact_set (contact, E_CONTACT_NICKNAME, cn->nick_name);
473 }
474
475 static void
476 ebews_populate_date_value (EBookBackendEws *bbews,
477 EContact *contact,
478 EContactField field,
479 EEwsItem *item,
480 time_t (*get_func) (EEwsItem *item, gboolean *out_exists))
481 {
482 time_t value;
483 gboolean exists = FALSE;
484
485 value = get_func (item, &exists);
486
487 if (exists) {
488 ICalTime *itt;
489
490 itt = i_cal_time_new_from_timet_with_zone (value, TRUE, i_cal_timezone_get_utc_timezone ());
491
492 if (itt && i_cal_time_is_valid_time (itt) && !i_cal_time_is_null_time (itt)) {
493 EContactDate edate = { 0 };
494
495 edate.year = i_cal_time_get_year (itt);
496 edate.month = i_cal_time_get_month (itt);
497 edate.day = i_cal_time_get_day (itt);
498
499 e_contact_set (contact, field, &edate);
500 }
501
502 g_clear_object (&itt);
503 }
504 }
505
506 static void
507 ebews_populate_birth_date (EBookBackendEws *bbews,
508 EContact *contact,
509 EEwsItem *item,
510 GCancellable *cancellable,
511 GError **error)
512 {
513 ebews_populate_date_value (bbews, contact, E_CONTACT_BIRTH_DATE, item, e_ews_item_get_birthday);
514 }
515
516 static void
517 ebews_populate_anniversary (EBookBackendEws *bbews,
518 EContact *contact,
519 EEwsItem *item,
520 GCancellable *cancellable,
521 GError **error)
522 {
523 ebews_populate_date_value (bbews, contact, E_CONTACT_ANNIVERSARY, item, e_ews_item_get_wedding_anniversary);
524 }
525
526 static EContactPhoto *
527 get_photo (EBookBackendEws *bbews,
528 EEwsItem *item,
529 GCancellable *cancellable,
530 GError **error)
531 {
532 EContactPhoto *photo = NULL;
533 EEwsAdditionalProps *add_props = NULL;
534 EEwsAttachmentInfo *info;
535 GSList *contact_item_ids = NULL, *new_items = NULL;
536 GSList *attachments = NULL, *attachments_ids = NULL;
537 const guchar *content;
538 const gchar *contact_photo_id;
539 const EwsId *id;
540 gsize len;
541
542 id = e_ews_item_get_id (item);
543 if (!id)
544 return NULL;
545
546 add_props = e_ews_additional_props_new ();
547 add_props->field_uri = g_strdup ("item:Attachments");
548
549 contact_item_ids = g_slist_prepend (contact_item_ids, g_strdup (id->id));
550 if (!e_ews_connection_get_items_sync (
551 bbews->priv->cnc,
552 EWS_PRIORITY_MEDIUM,
553 contact_item_ids,
554 "IdOnly",
555 add_props,
556 FALSE,
557 NULL,
558 E_EWS_BODY_TYPE_TEXT,
559 &new_items,
560 NULL,
561 NULL,
562 cancellable,
563 error))
564 goto exit;
565
566 contact_photo_id = e_ews_item_get_contact_photo_id (new_items->data);
567 if (!contact_photo_id)
568 goto exit;
569
570 attachments_ids = g_slist_prepend (attachments_ids, g_strdup (contact_photo_id));
571 if (!e_ews_connection_get_attachments_sync (
572 bbews->priv->cnc,
573 EWS_PRIORITY_MEDIUM,
574 NULL,
575 attachments_ids,
576 NULL,
577 FALSE,
578 &attachments,
579 NULL,
580 NULL,
581 cancellable,
582 error))
583 goto exit;
584
585 info = attachments->data;
586 content = (guchar *) e_ews_attachment_info_get_inlined_data (info, &len);
587
588 photo = e_contact_photo_new ();
589 photo->type = E_CONTACT_PHOTO_TYPE_INLINED;
590 e_contact_photo_set_inlined (photo, content, len);
591
592 exit:
593 e_ews_additional_props_free (add_props);
594 g_slist_free_full (contact_item_ids, g_free);
595 g_slist_free_full (new_items, g_object_unref);
596 g_slist_free_full (attachments_ids, g_free);
597 g_slist_free_full (attachments, (GDestroyNotify) e_ews_attachment_info_free);
598
599 return photo;
600 }
601
602 static void
603 ebews_populate_photo (EBookBackendEws *bbews,
604 EContact *contact,
605 EEwsItem *item,
606 GCancellable *cancellable,
607 GError **error)
608 {
609 EContactPhoto *photo;
610
611 /*
612 * Support for ContactPhoto was added in Exchange 2010 SP2.
613 * We don't want to try to set/get this property if we are running in older version of the server.
614 */
615 if (!e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2010_SP2))
616 return;
617
618 photo = get_photo (bbews, item, cancellable, error);
619 if (!photo) {
620 return;
621 }
622
623 e_contact_set (contact, E_CONTACT_PHOTO, photo);
624 e_contact_photo_free (photo);
625 }
626
627 static void
628 ebews_populate_cert (EBookBackendEws *bbews,
629 EContact *contact,
630 EEwsItem *item,
631 const gchar *kind,
632 GCancellable *cancellable,
633 GError **error)
634 {
635 EVCardAttribute *attr;
636 EContactCert cert;
637
638 g_return_if_fail (g_str_equal (kind, E_EWS_CERT_KIND_USER) || g_str_equal (kind, E_EWS_CERT_KIND_MSEX));
639
640 /* Support for certificates was added in Exchange 2010 SP2. */
641 if (!e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2010_SP2))
642 return;
643
644 if (g_str_equal (kind, E_EWS_CERT_KIND_USER))
645 cert.data = (gchar *) e_ews_item_get_user_certificate (item, &cert.length);
646 else
647 cert.data = (gchar *) e_ews_item_get_msexchange_certificate (item, &cert.length);
648
649 if (!cert.data || !cert.length)
650 return;
651
652 attr = e_vcard_attribute_new (NULL, EVC_KEY);
653
654 e_vcard_append_attribute (E_VCARD (contact), attr);
655
656 e_vcard_attribute_add_param_with_value (
657 attr,
658 e_vcard_attribute_param_new (EVC_TYPE),
659 "X509");
660
661 e_vcard_attribute_add_param_with_value (
662 attr,
663 e_vcard_attribute_param_new (EVC_ENCODING),
664 "b");
665
666 e_vcard_attribute_add_param_with_value (
667 attr,
668 e_vcard_attribute_param_new (X_EWS_CERT_KIND),
669 kind);
670
671 e_vcard_attribute_add_value_decoded (attr, cert.data, cert.length);
672 }
673
674 static void
675 ebews_populate_user_cert (EBookBackendEws *bbews,
676 EContact *contact,
677 EEwsItem *item,
678 GCancellable *cancellable,
679 GError **error)
680 {
681 ebews_populate_cert (bbews, contact, item, E_EWS_CERT_KIND_USER, cancellable, error);
682 }
683
684 static void
685 ebews_populate_msex_cert (EBookBackendEws *bbews,
686 EContact *contact,
687 EEwsItem *item,
688 GCancellable *cancellable,
689 GError **error)
690 {
691 ebews_populate_cert (bbews, contact, item, E_EWS_CERT_KIND_MSEX, cancellable, error);
692 }
693
694 static EVCardAttribute *
695 ebews_find_cert_attribute (EContact *contact,
696 const gchar *kind,
697 gint fallback_index)
698 {
699 GList *link;
700 EVCardAttribute *fallback_attr = NULL;
701
702 for (link = e_vcard_get_attributes (E_VCARD (contact)); link; link = g_list_next (link)) {
703 EVCardAttribute *attr = link->data;
704 const gchar *attr_name;
705
706 attr_name = e_vcard_attribute_get_name (attr);
707
708 if (attr_name && g_ascii_strcasecmp (attr_name, EVC_KEY) == 0) {
709 GList *values;
710 gboolean is_x509 = FALSE;
711
712 for (values = e_vcard_attribute_get_param (attr, EVC_TYPE); values && !is_x509; values = g_list_next (values)) {
713 is_x509 = values->data && g_ascii_strcasecmp ((gchar *) values->data, "X509") == 0;
714 }
715
716 if (!is_x509)
717 continue;
718
719 if (!fallback_attr) {
720 if (!fallback_index) {
721 fallback_attr = attr;
722 fallback_index = -1;
723 } else if (fallback_index > 0) {
724 fallback_index--;
725 }
726 }
727
728 for (values = e_vcard_attribute_get_param (attr, X_EWS_CERT_KIND); values; values = g_list_next (values)) {
729 if (values->data && g_ascii_strcasecmp ((gchar *) values->data, kind) == 0)
730 return attr;
731 }
732 }
733 }
734
735 return fallback_attr;
736 }
737
738 static const gchar *
739 ebews_find_cert_base64_data (EContact *contact,
740 const gchar *kind,
741 gint fallback_index)
742 {
743 EVCardAttribute *attr;
744 GList *values;
745 const gchar *base64_data;
746
747 attr = ebews_find_cert_attribute (contact, kind, fallback_index);
748 if (!attr)
749 return NULL;
750
751 values = e_vcard_attribute_get_values (attr);
752 base64_data = values ? values->data : NULL;
753
754 if (base64_data && *base64_data)
755 return base64_data;
756
757 return NULL;
758 }
759
760 static void
761 ebews_set_cert (EBookBackendEws *bbews,
762 ESoapRequest *request,
763 EContact *contact,
764 const gchar *kind,
765 gint fallback_index)
766 {
767 const gchar *base64_data;
768
769 /* Support for certificates was added in Exchange 2010 SP2. */
770 if (!e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2010_SP2))
771 return;
772
773 base64_data = ebews_find_cert_base64_data (contact, kind, fallback_index);
774 if (!base64_data)
775 return;
776
777 e_soap_request_start_element (request, kind, NULL, NULL);
778 e_ews_request_write_string_parameter (request, "Base64Binary", NULL, base64_data);
779 e_soap_request_end_element (request);
780 }
781
782 static void
783 ebews_set_user_cert (EBookBackendEws *bbews,
784 ESoapRequest *request,
785 EContact *contact)
786 {
787 ebews_set_cert (bbews, request, contact, E_EWS_CERT_KIND_USER, 0);
788 }
789
790
791 static void
792 ebews_set_msex_cert (EBookBackendEws *bbews,
793 ESoapRequest *request,
794 EContact *contact)
795 {
796 ebews_set_cert (bbews, request, contact, E_EWS_CERT_KIND_MSEX, 1);
797 }
798
799 static void
800 ebews_set_cert_changes (EBookBackendEws *bbews,
801 ESoapRequest *request,
802 EContact *new,
803 EContact *old,
804 const gchar *kind,
805 gint fallback_index)
806 {
807 const gchar *new_base64_data, *old_base64_data;
808
809 /* The first pass */
810 if (!request)
811 return;
812
813 /* Support for certificates was added in Exchange 2010 SP2. */
814 if (!e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2010_SP2))
815 return;
816
817 /* Intentionally search by kind in the old contact, the new can have added cert, which would not have set the kind yet */
818 new_base64_data = ebews_find_cert_base64_data (new, kind, fallback_index);
819 old_base64_data = ebews_find_cert_base64_data (old, kind, -1);
820
821 if (g_strcmp0 (new_base64_data, old_base64_data) == 0)
822 return;
823
824 if (new_base64_data) {
825 e_ews_request_start_set_item_field (request, kind, "contacts", "Contact");
826 e_soap_request_start_element (request, kind, NULL, NULL);
827 e_ews_request_write_string_parameter (request, "Base64Binary", NULL, new_base64_data);
828 e_soap_request_end_element (request);
829 e_ews_request_end_set_item_field (request);
830 } else {
831 e_ews_request_add_delete_item_field (request, kind, "contacts");
832 }
833 }
834
835 static void
836 ebews_set_user_cert_changes (EBookBackendEws *bbews,
837 ESoapRequest *request,
838 EContact *new,
839 EContact *old,
840 gchar **out_new_change_key,
841 GCancellable *cancellable,
842 GError **error)
843 {
844 ebews_set_cert_changes (bbews, request, new, old, E_EWS_CERT_KIND_USER, 0);
845 }
846
847 static void
848 ebews_set_msex_cert_changes (EBookBackendEws *bbews,
849 ESoapRequest *request,
850 EContact *new,
851 EContact *old,
852 gchar **out_new_change_key,
853 GCancellable *cancellable,
854 GError **error)
855 {
856 ebews_set_cert_changes (bbews, request, new, old, E_EWS_CERT_KIND_MSEX, 1);
857 }
858
859 static void
860 set_phone_number (EContact *contact,
861 EContactField field,
862 EEwsItem *item,
863 const gchar *item_field)
864 {
865 const gchar *pn;
866
867 pn = e_ews_item_get_phone_number (item, item_field);
868 if (pn && *pn)
869 e_contact_set (contact, field, pn);
870 }
871
872 static void
873 ebews_populate_phone_numbers (EBookBackendEws *bbews,
874 EContact *contact,
875 EEwsItem *item,
876 GCancellable *cancellable,
877 GError **error)
878 {
879 gint i;
880
881 for (i = 0; i < G_N_ELEMENTS (phone_field_map); i++)
882 set_phone_number (contact, phone_field_map[i].field, item, phone_field_map[i].element);
883 }
884
885 static void
886 copy_ews_address_to_contact_address (EContactAddress *contact_addr,
887 const EwsAddress *address)
888 {
889 contact_addr->address_format = NULL;
890 contact_addr->po = NULL;
891 contact_addr->street = g_strdup (address->street);
892 contact_addr->ext = NULL;
893 contact_addr->locality = g_strdup (address->city);
894 contact_addr->region = g_strdup (address->state);
895 contact_addr->code = g_strdup (address->postal_code);
896 contact_addr->country = g_strdup (address->country);
897 }
898
899 static gboolean
900 ews_address_is_empty (const EwsAddress *address)
901 {
902 if (!address)
903 return TRUE;
904
905 #define is_empty_str(x) (!(x) || (!*(x)))
906
907 return is_empty_str (address->street) &&
908 is_empty_str (address->city) &&
909 is_empty_str (address->state) &&
910 is_empty_str (address->postal_code) &&
911 is_empty_str (address->country);
912
913 #undef is_empty_str
914 }
915
916 static void
917 set_address (EContact *contact,
918 EContactField field,
919 EEwsItem *item,
920 const gchar *item_field)
921 {
922 const EwsAddress *address;
923
924 address = e_ews_item_get_physical_address (item, item_field);
925 if (address && !ews_address_is_empty (address)) {
926 EContactAddress *addr;
927
928 addr = e_contact_address_new ();
929 copy_ews_address_to_contact_address (addr, address);
930 e_contact_set (contact, field, addr);
931 e_contact_address_free (addr);
932 }
933 }
934
935 static void
936 ebews_populate_address (EBookBackendEws *bbews,
937 EContact *contact,
938 EEwsItem *item,
939 GCancellable *cancellable,
940 GError **error)
941 {
942
943 set_address (contact, E_CONTACT_ADDRESS_WORK, item, "Business");
944 set_address (contact, E_CONTACT_ADDRESS_HOME, item, "Home");
945 set_address (contact, E_CONTACT_ADDRESS_OTHER, item, "Other");
946 }
947
948 static void
949 ebews_populate_ims (EBookBackendEws *bbews,
950 EContact *contact,
951 EEwsItem *item,
952 GCancellable *cancellable,
953 GError **error)
954 {
955 /* TODO : The fields returned by server does not match with the EContact fields
956 * for the IMS, handle it later */
957 }
958
959 static void
960 ebews_populate_notes (EBookBackendEws *bbews,
961 EContact *contact,
962 EEwsItem *item,
963 GCancellable *cancellable,
964 GError **error)
965 {
966 const gchar *notes = e_ews_item_get_notes (item);
967 if (!notes)
968 return;
969
970 e_contact_set (contact, E_CONTACT_NOTE, notes);
971 }
972
973 static gboolean
974 set_email_address (EContact *contact,
975 EContactField field,
976 EEwsItem *item,
977 const gchar *item_field,
978 gboolean require_smtp_prefix)
979 {
980 const gchar *ea;
981
982 ea = e_ews_item_get_email_address (item, item_field);
983 if (ea && g_ascii_strncasecmp (ea, "SMTP:", 5) == 0)
984 ea = ea + 5;
985 else if (require_smtp_prefix)
986 ea = NULL;
987
988 if (ea && *ea) {
989 e_contact_set (contact, field, ea);
990 return TRUE;
991 }
992
993 return FALSE;
994 }
995
996 static void
997 ebews_populate_emails_ex (EBookBackendEws *bbews,
998 EContact *contact,
999 EEwsItem *item,
1000 gboolean require_smtp_prefix,
1001 gboolean use_primary_address)
1002 {
1003 if (set_email_address (contact, E_CONTACT_EMAIL_1, item, "EmailAddress1", require_smtp_prefix) && use_primary_address)
1004 return;
1005
1006 if (set_email_address (contact, E_CONTACT_EMAIL_2, item, "EmailAddress2", require_smtp_prefix) && use_primary_address)
1007 return;
1008
1009 if (set_email_address (contact, E_CONTACT_EMAIL_3, item, "EmailAddress3", require_smtp_prefix) && use_primary_address)
1010 return;
1011 }
1012
1013 static void
1014 ebews_populate_emails (EBookBackendEws *bbews,
1015 EContact *contact,
1016 EEwsItem *item,
1017 GCancellable *cancellable,
1018 GError **errror)
1019 {
1020 ebews_populate_emails_ex (bbews, contact, item, FALSE, FALSE);
1021 }
1022
1023 static void
1024 ebews_set_item_id (EBookBackendEws *bbews,
1025 ESoapRequest *request,
1026 EContact *contact)
1027 {
1028
1029 }
1030
1031 static void
1032 ebews_set_full_name (EBookBackendEws *bbews,
1033 ESoapRequest *request,
1034 EContact *contact)
1035 {
1036 EContactName *name;
1037
1038 name = e_contact_get (contact, E_CONTACT_NAME);
1039 if (!name)
1040 return;
1041
1042 if (name->given)
1043 e_ews_request_write_string_parameter (request, "GivenName", NULL, name->given);
1044
1045 if (name->additional && *name->additional)
1046 e_ews_request_write_string_parameter (request, "MiddleName", NULL, name->additional);
1047
1048 e_contact_name_free (name);
1049 }
1050
1051 static void
1052 ebews_set_date_value (ESoapRequest *request,
1053 EContact *contact,
1054 EContactField field,
1055 const gchar *element_name)
1056 {
1057 EContactDate *date;
1058 gchar *value;
1059
1060 date = e_contact_get (contact, field);
1061
1062 if (!date)
1063 return;
1064
1065 value = g_strdup_printf ("%04d-%02d-%02dT00:00:00Z",
1066 date->year, date->month, date->day);
1067
1068 e_ews_request_write_string_parameter (request, element_name, NULL, value);
1069
1070 e_contact_date_free (date);
1071 g_free (value);
1072 }
1073
1074 static void
1075 ebews_set_birth_date (EBookBackendEws *bbews,
1076 ESoapRequest *request,
1077 EContact *contact)
1078 {
1079 ebews_set_date_value (request, contact, E_CONTACT_BIRTH_DATE, "Birthday");
1080 }
1081
1082 static void
1083 ebews_set_anniversary (EBookBackendEws *bbews,
1084 ESoapRequest *request,
1085 EContact *contact)
1086 {
1087 ebews_set_date_value (request, contact, E_CONTACT_ANNIVERSARY, "WeddingAnniversary");
1088 }
1089
1090 static void
1091 ebews_set_photo (EBookBackendEws *bbews,
1092 ESoapRequest *request,
1093 EContact *contact)
1094 {
1095
1096 }
1097
1098 static gboolean
1099 add_entry (ESoapRequest *request,
1100 EContact *contact,
1101 EContactField field,
1102 const gchar *entry_name,
1103 const gchar *include_hdr)
1104 {
1105 gchar *entry_val;
1106
1107 entry_val = e_contact_get (contact, field);
1108
1109 if (entry_val && *entry_val) {
1110 if (include_hdr)
1111 e_soap_request_start_element (request, include_hdr, NULL, NULL);
1112
1113 e_ews_request_write_string_parameter_with_attribute (request, "Entry", NULL, entry_val, "Key", entry_name);
1114
1115 g_free (entry_val);
1116 return TRUE;
1117 }
1118
1119 g_free (entry_val);
1120 return FALSE;
1121 }
1122
1123 static void
1124 ebews_set_phone_numbers (EBookBackendEws *bbews,
1125 ESoapRequest *request,
1126 EContact *contact)
1127 {
1128 gint i;
1129 const gchar *include_hdr = "PhoneNumbers";
1130
1131 for (i = 0; i < G_N_ELEMENTS (phone_field_map); i++) {
1132 if (add_entry (request, contact, phone_field_map[i].field, phone_field_map[i].element, include_hdr))
1133 include_hdr = NULL;
1134 }
1135
1136 if (!include_hdr)
1137 e_soap_request_end_element (request);
1138 }
1139
1140 static gboolean
1141 add_physical_address (ESoapRequest *request,
1142 EContact *contact,
1143 EContactField field,
1144 const gchar *entry_name,
1145 gboolean include_start_hdr)
1146 {
1147 EContactAddress *contact_addr;
1148
1149 contact_addr = e_contact_get (contact, field);
1150 if (!contact_addr)
1151 return FALSE;
1152
1153 if (include_start_hdr)
1154 e_soap_request_start_element (request, "PhysicalAddresses", NULL, NULL);
1155
1156 e_soap_request_start_element (request, "Entry", NULL, NULL);
1157
1158 e_soap_request_add_attribute (request, "Key", entry_name, NULL, NULL);
1159 e_ews_request_write_string_parameter (request, "Street", NULL, contact_addr->street);
1160 e_ews_request_write_string_parameter (request, "City", NULL, contact_addr->locality);
1161 e_ews_request_write_string_parameter (request, "State", NULL, contact_addr->region);
1162 e_ews_request_write_string_parameter (request, "CountryOrRegion", NULL, contact_addr->country);
1163 e_ews_request_write_string_parameter (request, "PostalCode", NULL, contact_addr->code);
1164
1165 e_soap_request_end_element (request);
1166 e_contact_address_free (contact_addr);
1167
1168 return TRUE;
1169 }
1170
1171 static void
1172 ebews_set_address (EBookBackendEws *bbews,
1173 ESoapRequest *request,
1174 EContact *contact)
1175 {
1176 gboolean include_hdr = TRUE;
1177
1178 if (add_physical_address (request, contact, E_CONTACT_ADDRESS_WORK, "Business", include_hdr))
1179 include_hdr = FALSE;
1180 if (add_physical_address (request, contact, E_CONTACT_ADDRESS_HOME, "Home", include_hdr))
1181 include_hdr = FALSE;
1182 if (add_physical_address (request, contact, E_CONTACT_ADDRESS_OTHER, "Other", include_hdr))
1183 include_hdr = FALSE;
1184
1185 if (!include_hdr)
1186 e_soap_request_end_element (request);
1187 }
1188
1189 static void
1190 ebews_set_ims (EBookBackendEws *bbews,
1191 ESoapRequest *request,
1192 EContact *contact)
1193 {
1194
1195 }
1196
1197 static void
1198 ebews_set_notes (EBookBackendEws *bbews,
1199 ESoapRequest *request,
1200 EContact *contact)
1201 {
1202 gchar *notes = e_contact_get (contact, E_CONTACT_NOTE);
1203 if (!notes)
1204 return;
1205
1206 e_ews_request_write_string_parameter_with_attribute (request, "Body", NULL, notes, "BodyType", "Text");
1207
1208 g_free (notes);
1209 }
1210
1211 static void
1212 ebews_set_emails (EBookBackendEws *bbews,
1213 ESoapRequest *request,
1214 EContact *contact)
1215 {
1216 const gchar *include_hdr = "EmailAddresses";
1217
1218 if (add_entry (request, contact, E_CONTACT_EMAIL_1, "EmailAddress1", include_hdr))
1219 include_hdr = NULL;
1220 if (add_entry (request, contact, E_CONTACT_EMAIL_2, "EmailAddress2", include_hdr))
1221 include_hdr = NULL;
1222 if (add_entry (request, contact, E_CONTACT_EMAIL_3, "EmailAddress3", include_hdr))
1223 include_hdr = NULL;
1224
1225 if (!include_hdr)
1226 e_soap_request_end_element (request);
1227 }
1228
1229 static void
1230 convert_contact_property_to_updatexml (ESoapRequest *request,
1231 const gchar *name,
1232 const gchar *value,
1233 const gchar *prefix,
1234 const gchar *attr_name,
1235 const gchar *attr_value)
1236 {
1237 e_ews_request_start_set_item_field (request, name, prefix, "Contact");
1238 e_ews_request_write_string_parameter_with_attribute (request, name, NULL, value, attr_name, attr_value);
1239 e_ews_request_end_set_item_field (request);
1240 }
1241
1242 static void
1243 convert_indexed_contact_property_to_updatexml (ESoapRequest *request,
1244 const gchar *name,
1245 const gchar *value,
1246 const gchar *prefix,
1247 const gchar *element_name,
1248 const gchar *key)
1249 {
1250 gboolean delete_field = FALSE;
1251
1252 if (!value || !*value)
1253 delete_field = TRUE;
1254 e_ews_request_start_set_indexed_item_field (request, name , prefix, "Contact", key, delete_field);
1255
1256 if (!delete_field) {
1257 e_soap_request_start_element (request, element_name, NULL, NULL);
1258 e_ews_request_write_string_parameter_with_attribute (request, "Entry", NULL, value, "Key", key);
1259 e_soap_request_end_element (request);
1260 }
1261 e_ews_request_end_set_indexed_item_field (request, delete_field);
1262 }
1263
1264 static void
1265 ebews_set_full_name_changes (EBookBackendEws *bbews,
1266 ESoapRequest *request,
1267 EContact *new,
1268 EContact *old,
1269 gchar **out_new_change_key,
1270 GCancellable *cancellable,
1271 GError **error)
1272 {
1273 EContactName *name, *old_name;
1274
1275 if (!request)
1276 return;
1277
1278 name = e_contact_get (new, E_CONTACT_NAME);
1279 old_name = e_contact_get (old, E_CONTACT_NAME);
1280 if (!old_name && !name)
1281 return;
1282
1283 if (!old_name) {
1284 convert_contact_property_to_updatexml (request, "GivenName", name->given, "contacts", NULL, NULL);
1285 convert_contact_property_to_updatexml (request, "MiddleName", name->additional, "contacts", NULL, NULL);
1286 } else if (!name) {
1287 convert_contact_property_to_updatexml (request, "GivenName", "", "contacts", NULL, NULL);
1288
1289 convert_contact_property_to_updatexml (request, "MiddleName", "", "contacts", NULL, NULL);
1290 } else {
1291 if (g_strcmp0 (name->given, old_name->given) != 0)
1292 convert_contact_property_to_updatexml (request, "GivenName", name->given, "contacts", NULL, NULL);
1293 if (g_strcmp0 (name->additional, old_name->additional) != 0)
1294 convert_contact_property_to_updatexml (request, "MiddleName", name->additional, "contacts", NULL, NULL);
1295 }
1296
1297 e_contact_name_free (name);
1298 e_contact_name_free (old_name);
1299
1300 }
1301
1302 static void
1303 ebews_set_date_value_changes (ESoapRequest *request,
1304 EContact *new,
1305 EContact *old,
1306 EContactField field,
1307 const gchar *element_name)
1308 {
1309 EContactDate *new_date, *old_date;
1310
1311 if (!request)
1312 return;
1313
1314 new_date = e_contact_get (new, field);
1315 old_date = e_contact_get (old, field);
1316
1317 if (!e_contact_date_equal (new_date, old_date)) {
1318 if (new_date) {
1319 gchar *value;
1320
1321 value = g_strdup_printf ("%04d-%02d-%02dT00:00:00Z",
1322 new_date->year, new_date->month, new_date->day);
1323
1324 convert_contact_property_to_updatexml (request, element_name, value, "contacts", NULL, NULL);
1325
1326 g_free (value);
1327 } else {
1328 e_ews_request_add_delete_item_field (request, element_name, "contacts");
1329 }
1330 }
1331
1332 e_contact_date_free (new_date);
1333 e_contact_date_free (old_date);
1334 }
1335
1336 static void
1337 ebews_set_birth_date_changes (EBookBackendEws *bbews,
1338 ESoapRequest *request,
1339 EContact *new,
1340 EContact *old,
1341 gchar **out_new_change_key,
1342 GCancellable *cancellable,
1343 GError **error)
1344 {
1345 ebews_set_date_value_changes (request, new, old, E_CONTACT_BIRTH_DATE, "Birthday");
1346 }
1347
1348 static void
1349 ebews_set_anniversary_changes (EBookBackendEws *bbews,
1350 ESoapRequest *request,
1351 EContact *new,
1352 EContact *old,
1353 gchar **out_new_change_key,
1354 GCancellable *cancellable,
1355 GError **error)
1356 {
1357 ebews_set_date_value_changes (request, new, old, E_CONTACT_ANNIVERSARY, "WeddingAnniversary");
1358 }
1359
1360 static void
1361 set_photo (EBookBackendEws *bbews,
1362 const EwsId *item_id,
1363 EContact *contact,
1364 EContactPhoto *photo,
1365 gchar **new_change_key,
1366 GCancellable *cancellable,
1367 GError **error)
1368 {
1369 EEwsAttachmentInfo *info;
1370 EwsId *id = NULL;
1371 GSList *files = NULL;
1372 const guchar *data;
1373 gsize len;
1374
1375 if (!item_id) {
1376 id = g_new0 (EwsId, 1);
1377 id->id = e_contact_get (contact, E_CONTACT_UID);
1378 id->change_key = e_vcard_util_dup_x_attribute (E_VCARD (contact), X_EWS_CHANGEKEY);
1379 if (!id->change_key)
1380 id->change_key = e_contact_get (contact, E_CONTACT_REV);
1381
1382 item_id = id;
1383 }
1384
1385 data = e_contact_photo_get_inlined (photo, &len);
1386
1387 info = e_ews_attachment_info_new (E_EWS_ATTACHMENT_INFO_TYPE_INLINED);
1388 e_ews_attachment_info_set_inlined_data (info, data, len);
1389 e_ews_attachment_info_set_mime_type (info, "image/jpeg");
1390 e_ews_attachment_info_set_filename (info, "ContactPicture.jpg");
1391
1392 files = g_slist_append (files, info);
1393
1394 e_ews_connection_create_attachments_sync (
1395 bbews->priv->cnc,
1396 EWS_PRIORITY_MEDIUM,
1397 item_id,
1398 files,
1399 TRUE,
1400 new_change_key,
1401 NULL,
1402 cancellable,
1403 error);
1404
1405 if (id) {
1406 g_free (id->change_key);
1407 g_free (id->id);
1408 g_free (id);
1409 }
1410
1411 g_slist_free_full (files, (GDestroyNotify) e_ews_attachment_info_free);
1412 }
1413
1414 static gboolean
1415 ebb_ews_photo_changed (EBookMetaBackend *meta_backend,
1416 EContact *old_contact,
1417 EContact *new_contact,
1418 GCancellable *cancellable)
1419 {
1420 EContact *old_contact_copy = NULL;
1421 EContactPhoto *old_photo;
1422 EContactPhoto *new_photo;
1423 gboolean changed = FALSE;
1424
1425 old_photo = e_contact_get (old_contact, E_CONTACT_PHOTO);
1426 new_photo = e_contact_get (new_contact, E_CONTACT_PHOTO);
1427
1428 if (!old_photo && new_photo)
1429 changed = TRUE;
1430
1431 if (old_photo && !new_photo)
1432 changed = TRUE;
1433
1434 /* old_photo comes from cache, thus it's always URI (to local file or elsewhere),
1435 while the new_photo is to be saved, which is always inlined. */
1436 if (!changed && old_photo && new_photo &&
1437 old_photo->type == E_CONTACT_PHOTO_TYPE_URI &&
1438 new_photo->type == E_CONTACT_PHOTO_TYPE_INLINED) {
1439 e_contact_photo_free (old_photo);
1440 old_photo = NULL;
1441
1442 old_contact_copy = e_contact_duplicate (old_contact);
1443
1444 if (e_book_meta_backend_inline_local_photos_sync (meta_backend, old_contact_copy, cancellable, NULL))
1445 old_photo = e_contact_get (old_contact_copy, E_CONTACT_PHOTO);
1446 }
1447
1448 if (old_photo && new_photo &&
1449 old_photo->type == E_CONTACT_PHOTO_TYPE_INLINED &&
1450 new_photo->type == E_CONTACT_PHOTO_TYPE_INLINED) {
1451 guchar *old_data;
1452 guchar *new_data;
1453 gsize old_length;
1454 gsize new_length;
1455
1456 old_data = old_photo->data.inlined.data;
1457 new_data = new_photo->data.inlined.data;
1458
1459 old_length = old_photo->data.inlined.length;
1460 new_length = new_photo->data.inlined.length;
1461
1462 changed =
1463 (old_length != new_length) ||
1464 (memcmp (old_data, new_data, old_length) != 0);
1465 }
1466
1467 e_contact_photo_free (old_photo);
1468 e_contact_photo_free (new_photo);
1469 g_clear_object (&old_contact_copy);
1470
1471 return changed;
1472 }
1473
1474 static void
1475 ebews_set_photo_changes (EBookBackendEws *bbews,
1476 ESoapRequest *request,
1477 EContact *new,
1478 EContact *old,
1479 gchar **out_new_change_key,
1480 GCancellable *cancellable,
1481 GError **error)
1482 {
1483 EContactPhoto *new_photo = NULL;
1484 EEwsAdditionalProps *add_props = NULL;
1485 GSList *contact_item_ids = NULL, *new_items = NULL, *attachments_ids = NULL;
1486 gchar *id = NULL;
1487 const gchar *contact_photo_id;
1488 gchar *new_change_key = NULL;
1489
1490 /*
1491 * Support for ContactPhoto was added in Exchange 2010 SP2.
1492 * We don't want to try to set/get this property if we are running in older version of the server.
1493 */
1494 if (!e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2010_SP2)) {
1495 return;
1496 }
1497
1498 if (request) {
1499 /* Photo changes can be done only in pre-flight stage,
1500 because it modifies ChangeKey */
1501 return;
1502 }
1503
1504 if (!ebb_ews_photo_changed (E_BOOK_META_BACKEND (bbews), old, new, cancellable))
1505 return;
1506
1507 new_photo = e_contact_get (new, E_CONTACT_PHOTO);
1508 id = e_contact_get (old, E_CONTACT_UID);
1509
1510 add_props = e_ews_additional_props_new ();
1511 add_props->field_uri = g_strdup ("item:Attachments");
1512
1513 contact_item_ids = g_slist_append (contact_item_ids, id);
1514 if (!e_ews_connection_get_items_sync (
1515 bbews->priv->cnc,
1516 EWS_PRIORITY_MEDIUM,
1517 contact_item_ids,
1518 "IdOnly",
1519 add_props,
1520 FALSE,
1521 NULL,
1522 E_EWS_BODY_TYPE_TEXT,
1523 &new_items,
1524 NULL,
1525 NULL,
1526 cancellable,
1527 error))
1528 goto exit;
1529
1530 contact_photo_id = e_ews_item_get_contact_photo_id (new_items->data);
1531 if (contact_photo_id) {
1532 attachments_ids = g_slist_prepend (attachments_ids, g_strdup (contact_photo_id));
1533 if (!e_ews_connection_delete_attachments_sync (
1534 bbews->priv->cnc,
1535 EWS_PRIORITY_MEDIUM,
1536 attachments_ids,
1537 &new_change_key,
1538 cancellable,
1539 error))
1540 goto exit;
1541 }
1542
1543 if (new_photo) {
1544 EwsId *item_id = NULL;
1545
1546 if (new_change_key) {
1547 item_id = g_new0 (EwsId, 1);
1548 item_id->id = e_contact_get (new, E_CONTACT_UID);
1549 item_id->change_key = new_change_key;
1550
1551 new_change_key = NULL;
1552 }
1553
1554 set_photo (bbews, item_id, new, new_photo, &new_change_key, cancellable, error);
1555
1556 if (item_id) {
1557 if (!new_change_key) {
1558 new_change_key = item_id->change_key;
1559 item_id->change_key = NULL;
1560 }
1561
1562 g_free (item_id->id);
1563 g_free (item_id->change_key);
1564 g_free (item_id);
1565 }
1566 }
1567
1568 exit:
1569 e_ews_additional_props_free (add_props);
1570 e_contact_photo_free (new_photo);
1571 g_slist_free_full (contact_item_ids, g_free);
1572 g_slist_free_full (new_items, g_object_unref);
1573 g_slist_free_full (attachments_ids, g_free);
1574
1575 if (new_change_key && out_new_change_key)
1576 *out_new_change_key = new_change_key;
1577 else
1578 g_free (new_change_key);
1579 }
1580
1581 static void
1582 ebews_set_phone_number_changes (EBookBackendEws *bbews,
1583 ESoapRequest *request,
1584 EContact *new,
1585 EContact *old,
1586 gchar **out_new_change_key,
1587 GCancellable *cancellable,
1588 GError **error)
1589 {
1590 gint i;
1591 gchar *new_value, *old_value;
1592
1593 if (!request)
1594 return;
1595
1596 for (i = 0; i < G_N_ELEMENTS (phone_field_map); i++) {
1597 new_value = e_contact_get (new, phone_field_map[i].field);
1598 old_value = e_contact_get (old, phone_field_map[i].field);
1599
1600 if (g_strcmp0 (new_value, old_value) != 0)
1601 convert_indexed_contact_property_to_updatexml (request, "PhoneNumber", new_value, "contacts", "PhoneNumbers", phone_field_map[i].element);
1602
1603 g_free (new_value);
1604 g_free (old_value);
1605 }
1606 }
1607
1608 static void
1609 convert_indexed_contact_property_to_updatexml_physical_address (ESoapRequest *request,
1610 const gchar *name,
1611 const gchar *uri_element,
1612 const gchar *value,
1613 const gchar *prefix,
1614 const gchar *element_name,
1615 const gchar *key)
1616 {
1617 gchar * fielduri = NULL;
1618 gboolean delete_field = FALSE;
1619
1620 if (!value || !*value)
1621 delete_field = TRUE;
1622
1623 fielduri = g_strconcat (name, ":", uri_element, NULL);
1624
1625 e_ews_request_start_set_indexed_item_field (request, fielduri , prefix, "Contact", key, delete_field);
1626
1627 if (!delete_field) {
1628 e_soap_request_start_element (request, element_name, NULL, NULL);
1629
1630 e_soap_request_start_element (request, "Entry", NULL, NULL);
1631 e_soap_request_add_attribute (request, "Key", key, NULL, NULL);
1632 e_ews_request_write_string_parameter (request, uri_element, NULL, value);
1633 e_soap_request_end_element (request);
1634
1635 e_soap_request_end_element (request);
1636 }
1637 e_ews_request_end_set_indexed_item_field (request, delete_field);
1638
1639 g_free (fielduri);
1640 }
1641
1642 static void
1643 compare_address (ESoapRequest *request,
1644 EContact *new,
1645 EContact *old,
1646 EContactField field,
1647 const gchar *key)
1648 {
1649 EContactAddress *new_address, *old_address;
1650 gboolean set = FALSE;
1651
1652 new_address = e_contact_get (new, field);
1653 old_address = e_contact_get (old, field);
1654
1655 if (!new_address && !old_address)
1656 return;
1657
1658 if (!old_address && new_address)
1659 set = TRUE;
1660
1661 if (!new_address && old_address)
1662 {
1663 set = TRUE;
1664 new_address = e_contact_address_new ();
1665 }
1666
1667 if (set || g_strcmp0 (new_address->street, old_address->street) != 0)
1668 convert_indexed_contact_property_to_updatexml_physical_address (request, "PhysicalAddress", "Street", new_address->street, "contacts", "PhysicalAddresses", key);
1669 if (set || g_strcmp0 (new_address->locality, old_address->locality) != 0)
1670 convert_indexed_contact_property_to_updatexml_physical_address (request, "PhysicalAddress", "City", new_address->locality, "contacts", "PhysicalAddresses", key);
1671 if (set || g_strcmp0 (new_address->region, old_address->region) != 0)
1672 convert_indexed_contact_property_to_updatexml_physical_address (request, "PhysicalAddress", "State", new_address->region, "contacts", "PhysicalAddresses", key);
1673 if (set || g_strcmp0 (new_address->country, old_address->country) != 0)
1674 convert_indexed_contact_property_to_updatexml_physical_address (request, "PhysicalAddress", "CountryOrRegion", new_address->country, "contacts", "PhysicalAddresses", key);
1675 if (set || g_strcmp0 (new_address->code, old_address->code) != 0)
1676 convert_indexed_contact_property_to_updatexml_physical_address (request, "PhysicalAddress", "PostalCode", new_address->code, "contacts", "PhysicalAddresses", key);
1677
1678 e_contact_address_free (old_address);
1679 e_contact_address_free (new_address);
1680 }
1681
1682 static void
1683 ebews_set_address_changes (EBookBackendEws *bbews,
1684 ESoapRequest *request,
1685 EContact *new,
1686 EContact *old,
1687 gchar **out_new_change_key,
1688 GCancellable *cancellable,
1689 GError **error)
1690 {
1691 if (!request)
1692 return;
1693
1694 compare_address (request, new, old, E_CONTACT_ADDRESS_WORK, "Business");
1695 compare_address (request, new, old, E_CONTACT_ADDRESS_HOME, "Home");
1696 compare_address (request, new, old, E_CONTACT_ADDRESS_OTHER, "Other");
1697 }
1698
1699 static void
1700 ebews_set_im_changes (EBookBackendEws *bbews,
1701 ESoapRequest *request,
1702 EContact *new,
1703 EContact *old,
1704 gchar **out_new_change_key,
1705 GCancellable *cancellable,
1706 GError **error)
1707 {
1708
1709 }
1710
1711 static void
1712 ebews_set_notes_changes (EBookBackendEws *bbews,
1713 ESoapRequest *request,
1714 EContact *new,
1715 EContact *old,
1716 gchar **out_new_change_key,
1717 GCancellable *cancellable,
1718 GError **error)
1719 {
1720 gchar *old_notes, *new_notes;
1721
1722 if (!request)
1723 return;
1724
1725 old_notes = e_contact_get (old, E_CONTACT_NOTE);
1726 new_notes = e_contact_get (new, E_CONTACT_NOTE);
1727
1728 if (g_strcmp0 (old_notes, new_notes) != 0) {
1729 convert_contact_property_to_updatexml (
1730 request, "Body", new_notes ? new_notes : "", "item", "BodyType", "Text");
1731 }
1732
1733 g_free (old_notes);
1734 g_free (new_notes);
1735 }
1736
1737 static void
1738 ebews_set_email_changes (EBookBackendEws *bbews,
1739 ESoapRequest *request,
1740 EContact *new,
1741 EContact *old,
1742 gchar **out_new_change_key,
1743 GCancellable *cancellable,
1744 GError **error)
1745 {
1746 gchar *new_value, *old_value;
1747
1748 if (!request)
1749 return;
1750
1751 new_value = e_contact_get (new, E_CONTACT_EMAIL_1);
1752 old_value = e_contact_get (old, E_CONTACT_EMAIL_1);
1753 if (g_strcmp0 (new_value, old_value) != 0)
1754 convert_indexed_contact_property_to_updatexml (request, "EmailAddress", new_value, "contacts", "EmailAddresses", "EmailAddress1");
1755 g_free (new_value);
1756 g_free (old_value);
1757
1758 new_value = e_contact_get (new, E_CONTACT_EMAIL_2);
1759 old_value = e_contact_get (old, E_CONTACT_EMAIL_2);
1760 if (g_strcmp0 (new_value, old_value) != 0)
1761 convert_indexed_contact_property_to_updatexml (request, "EmailAddress", new_value, "contacts", "EmailAddresses", "EmailAddress2");
1762 g_free (new_value);
1763 g_free (old_value);
1764
1765 new_value = e_contact_get (new, E_CONTACT_EMAIL_3);
1766 old_value = e_contact_get (old, E_CONTACT_EMAIL_3);
1767 if (g_strcmp0 (new_value, old_value) != 0)
1768 convert_indexed_contact_property_to_updatexml (request, "EmailAddress", new_value, "contacts", "EmailAddresses", "EmailAddress3");
1769 g_free (new_value);
1770 g_free (old_value);
1771 }
1772
1773 static void
1774 ebews_populate_givenname (EBookBackendEws *bbews,
1775 EContact *contact,
1776 EEwsItem *item,
1777 GCancellable *cancellable,
1778 GError **error)
1779 {
1780 const gchar *givenname;
1781
1782 givenname = e_ews_item_get_givenname (item);
1783 if (givenname && *givenname)
1784 e_contact_set (contact, E_CONTACT_GIVEN_NAME, givenname);
1785 }
1786
1787 static void
1788 ebews_set_givenname (EBookBackendEws *bbews,
1789 ESoapRequest *request,
1790 EContact *contact)
1791 {
1792 /* Does nothing, the "GivenName" is filled by the "FullName" code */
1793 }
1794
1795 static void
1796 ebews_set_givenname_changes (EBookBackendEws *bbews,
1797 ESoapRequest *request,
1798 EContact *new,
1799 EContact *old,
1800 gchar **out_new_change_key,
1801 GCancellable *cancellable,
1802 GError **error)
1803 {
1804 /* Does nothing, the "GivenName" is filled by the "FullName" code */
1805 }
1806
1807 static const gchar *
1808 ebews_get_fileas_or_display_name (EEwsItem *item)
1809 {
1810 const gchar *value;
1811
1812 value = e_ews_item_get_fileas (item);
1813 if (!value || !*value)
1814 value = e_ews_item_get_display_name (item);
1815
1816 return value;
1817 }
1818
1819 static void
1820 ebews_populate_categories (EBookBackendEws *bbews,
1821 EContact *contact,
1822 EEwsItem *item,
1823 GCancellable *cancellable,
1824 GError **error)
1825 {
1826 GList *values = NULL;
1827 GSList *link;
1828
1829 for (link = (GSList *) e_ews_item_get_categories (item); link; link = g_slist_next (link)) {
1830 values = g_list_prepend (values, link->data);
1831 }
1832
1833 values = g_list_reverse (values);
1834
1835 e_contact_set (contact, E_CONTACT_CATEGORY_LIST, values);
1836
1837 g_list_free (values);
1838 }
1839
1840 static void
1841 ebews_set_categories (EBookBackendEws *bbews,
1842 ESoapRequest *request,
1843 EContact *contact)
1844 {
1845 GList *values;
1846
1847 values = e_contact_get (contact, E_CONTACT_CATEGORY_LIST);
1848 if (values) {
1849 GList *link;
1850
1851 e_soap_request_start_element (request, "Categories", NULL, NULL);
1852 for (link = values; link; link = g_list_next (link)) {
1853 const gchar *category = link->data;
1854 if (category && *category)
1855 e_ews_request_write_string_parameter (request, "String", NULL, category);
1856 }
1857 e_soap_request_end_element (request);
1858 }
1859
1860 g_list_free_full (values, g_free);
1861 }
1862
1863 static void
1864 ebews_set_categories_changes (EBookBackendEws *bbews,
1865 ESoapRequest *request,
1866 EContact *new,
1867 EContact *old,
1868 gchar **out_new_change_key,
1869 GCancellable *cancellable,
1870 GError **error)
1871 {
1872 gchar *old_categories, *new_categories;
1873
1874 if (!request)
1875 return;
1876
1877 old_categories = e_contact_get (old, E_CONTACT_CATEGORIES);
1878 new_categories = e_contact_get (new, E_CONTACT_CATEGORIES);
1879
1880 if (g_strcmp0 (old_categories, new_categories) != 0) {
1881 GList *values, *link;
1882
1883 values = e_contact_get (new, E_CONTACT_CATEGORY_LIST);
1884 if (values) {
1885 e_soap_request_start_element (request, "SetItemField", NULL, NULL);
1886
1887 e_soap_request_start_element (request, "FieldURI", NULL, NULL);
1888 e_soap_request_add_attribute (request, "FieldURI", "item:Categories", NULL, NULL);
1889 e_soap_request_end_element (request);
1890
1891 e_soap_request_start_element (request, "Contact", NULL, NULL);
1892 e_soap_request_start_element (request, "Categories", NULL, NULL);
1893
1894 for (link = values; link; link = g_list_next (link)) {
1895 const gchar *category = link->data;
1896
1897 if (category && *category)
1898 e_ews_request_write_string_parameter (request, "String", NULL, category);
1899 }
1900
1901 e_soap_request_end_element (request); /* Categories */
1902 e_soap_request_end_element (request); /* Contact */
1903 e_soap_request_end_element (request); /* SetItemField */
1904 } else {
1905 e_ews_request_add_delete_item_field (request, "Categories", "item");
1906 }
1907
1908 g_list_free_full (values, g_free);
1909 }
1910
1911 g_free (old_categories);
1912 g_free (new_categories);
1913 }
1914
1915 static const struct field_element_mapping {
1916 EContactField field_id;
1917 gint element_type;
1918 const gchar *element_name;
1919 /* set function for simple string type values */
1920 const gchar * (*get_simple_prop_func) (EEwsItem *item);
1921 void (*populate_contact_func)(EBookBackendEws *bbews, EContact *contact, EEwsItem *item, GCancellable *cancellable, GError **error);
1922 void (*set_value_in_soap_request) (EBookBackendEws *bbews, ESoapRequest *request, EContact *contact);
1923 void (*set_changes) (EBookBackendEws *bbews, ESoapRequest *request, EContact *new, EContact *old, gchar **out_new_change_key, GCancellable *cancellable, GError **error);
1924
1925 } mappings[] = {
1926 /* The order should be maintained for create contacts to work */
1927 { E_CONTACT_NOTE, ELEMENT_TYPE_COMPLEX, "Notes", NULL, ebews_populate_notes, ebews_set_notes, ebews_set_notes_changes },
1928 { E_CONTACT_FILE_AS, ELEMENT_TYPE_SIMPLE, "FileAs", ebews_get_fileas_or_display_name },
1929 { E_CONTACT_FULL_NAME, ELEMENT_TYPE_COMPLEX, "CompleteName", NULL, ebews_populate_full_name, ebews_set_full_name, ebews_set_full_name_changes},
1930 { E_CONTACT_NICKNAME, ELEMENT_TYPE_SIMPLE, "Nickname", NULL, ebews_populate_nick_name},
1931 { E_CONTACT_ORG, ELEMENT_TYPE_SIMPLE, "CompanyName", e_ews_item_get_company_name},
1932 /* should take care of all email adresss fields */
1933 { E_CONTACT_EMAIL_1, ELEMENT_TYPE_COMPLEX, "EmailAddresses", NULL, ebews_populate_emails, ebews_set_emails, ebews_set_email_changes },
1934 /* should take care of home, work and other adresss fields */
1935 { E_CONTACT_ADDRESS_HOME, ELEMENT_TYPE_COMPLEX, "PhysicalAddresses", NULL, ebews_populate_address, ebews_set_address, ebews_set_address_changes },
1936 /* should take care of all phone number fields */
1937 { E_CONTACT_PHONE_PRIMARY, ELEMENT_TYPE_COMPLEX , "PhoneNumbers", NULL, ebews_populate_phone_numbers, ebews_set_phone_numbers, ebews_set_phone_number_changes},
1938 { E_CONTACT_ASSISTANT, ELEMENT_TYPE_SIMPLE, "AssistantName", e_ews_item_get_assistant_name},
1939 { E_CONTACT_BIRTH_DATE, ELEMENT_TYPE_COMPLEX, "Birthday", NULL, ebews_populate_birth_date, ebews_set_birth_date, ebews_set_birth_date_changes },
1940 { E_CONTACT_HOMEPAGE_URL, ELEMENT_TYPE_SIMPLE, "BusinessHomePage", e_ews_item_get_business_homepage},
1941 { E_CONTACT_ORG_UNIT, ELEMENT_TYPE_SIMPLE, "Department", e_ews_item_get_department},
1942 /* should take care of all im fields */
1943 { E_CONTACT_IM_AIM, ELEMENT_TYPE_COMPLEX, "ImAddresses", NULL, ebews_populate_ims, ebews_set_ims, ebews_set_im_changes },
1944 { E_CONTACT_TITLE, ELEMENT_TYPE_SIMPLE, "JobTitle", e_ews_item_get_job_title},
1945 { E_CONTACT_MANAGER, ELEMENT_TYPE_SIMPLE, "Manager", e_ews_item_get_manager},
1946 { E_CONTACT_OFFICE, ELEMENT_TYPE_SIMPLE, "OfficeLocation", e_ews_item_get_office_location},
1947 { E_CONTACT_SPOUSE, ELEMENT_TYPE_SIMPLE, "Profession", e_ews_item_get_profession},
1948 { E_CONTACT_SPOUSE, ELEMENT_TYPE_SIMPLE, "SpouseName", e_ews_item_get_spouse_name},
1949 { E_CONTACT_FAMILY_NAME, ELEMENT_TYPE_SIMPLE, "Surname", e_ews_item_get_surname},
1950 { E_CONTACT_GIVEN_NAME, ELEMENT_TYPE_COMPLEX, "GivenName", NULL, ebews_populate_givenname, ebews_set_givenname, ebews_set_givenname_changes},
1951 { E_CONTACT_ANNIVERSARY, ELEMENT_TYPE_COMPLEX, "WeddingAnniversary", NULL, ebews_populate_anniversary, ebews_set_anniversary, ebews_set_anniversary_changes },
1952 { E_CONTACT_PHOTO, ELEMENT_TYPE_COMPLEX, "Photo", NULL, ebews_populate_photo, ebews_set_photo, ebews_set_photo_changes },
1953 { E_CONTACT_X509_CERT, ELEMENT_TYPE_COMPLEX, "UserSMIMECertificate", NULL, ebews_populate_user_cert, ebews_set_user_cert, ebews_set_user_cert_changes },
1954 { E_CONTACT_X509_CERT, ELEMENT_TYPE_COMPLEX, "MSExchangeCertificate", NULL, ebews_populate_msex_cert, ebews_set_msex_cert, ebews_set_msex_cert_changes },
1955 { E_CONTACT_CATEGORIES, ELEMENT_TYPE_COMPLEX, "Categories", NULL, ebews_populate_categories, ebews_set_categories, ebews_set_categories_changes },
1956
1957 /* Should take of uid and changekey (REV) */
1958 { E_CONTACT_UID, ELEMENT_TYPE_COMPLEX, "ItemId", NULL, ebews_populate_uid, ebews_set_item_id},
1959 };
1960
1961 static void
1962 ebb_ews_write_dl_members (ESoapRequest *request,
1963 EContact *contact)
1964 {
1965 GSList *emails, *l;
1966
1967 e_soap_request_start_element (request, "Members", NULL, NULL);
1968
1969 emails = e_contact_get (contact, E_CONTACT_EMAIL);
1970 for (l = emails; l; l = l->next) {
1971 CamelInternetAddress *addr;
1972
1973 if (l->data == NULL)
1974 continue;
1975
1976 addr = camel_internet_address_new ();
1977 if (camel_address_decode (CAMEL_ADDRESS (addr), l->data) > 0) {
1978 const gchar *name = NULL, *email = NULL;
1979
1980 if (camel_internet_address_get (addr, 0, &name, &email) && email) {
1981 e_soap_request_start_element (request, "Member", NULL, NULL);
1982 e_soap_request_start_element (request, "Mailbox", NULL, NULL);
1983 e_ews_request_write_string_parameter (request, "Name", NULL, name ? name : email);
1984 e_ews_request_write_string_parameter (request, "EmailAddress", NULL, email);
1985 e_soap_request_end_element (request); /* Mailbox */
1986 e_soap_request_end_element (request); /* Member */
1987 }
1988 }
1989 g_object_unref (addr);
1990 }
1991
1992 g_slist_free_full (emails, g_free);
1993 e_soap_request_end_element (request); /* Members */
1994 }
1995
1996 typedef struct _CreateItemsData
1997 {
1998 EBookBackendEws *bbews;
1999 EContact *contact;
2000 } CreateItemsData;
2001
2002 static gboolean
2003 ebb_ews_convert_dl_to_xml_cb (ESoapRequest *request,
2004 gpointer user_data,
2005 GError **error)
2006 {
2007 CreateItemsData *cid = user_data;
2008 EContact *contact = cid->contact;
2009 EVCardAttribute *attribute;
2010 GList *values;
2011
2012 /* Prepare DistributionList node in the SOAP request */
2013 e_soap_request_start_element (request, "DistributionList", NULL, NULL);
2014
2015 attribute = e_vcard_get_attribute (E_VCARD (contact), EVC_FN);
2016 values = e_vcard_attribute_get_values (attribute);
2017 e_ews_request_write_string_parameter (request, "DisplayName", NULL, values->data);
2018
2019 ebb_ews_write_dl_members (request, contact);
2020
2021 e_soap_request_end_element (request); /* DistributionList */
2022
2023 return TRUE;
2024 }
2025
2026 static gboolean
2027 ebb_ews_convert_contact_to_xml_cb (ESoapRequest *request,
2028 gpointer user_data,
2029 GError **error)
2030 {
2031 CreateItemsData *cid = user_data;
2032 EContact *contact = cid->contact;
2033 gint i, element_type;
2034
2035 /* Prepare Contact node in the SOAP request */
2036 e_soap_request_start_element (request, "Contact", NULL, NULL);
2037
2038 for (i = 0; i < G_N_ELEMENTS (mappings); i++) {
2039 element_type = mappings[i].element_type;
2040
2041 if (element_type == ELEMENT_TYPE_SIMPLE) {
2042 gchar *val;
2043
2044 /* skip uid while creating contacts */
2045 if (mappings[i].field_id == E_CONTACT_UID)
2046 continue;
2047
2048 val = e_contact_get (contact, mappings[i].field_id);
2049 if (val && *val)
2050 e_ews_request_write_string_parameter (request, mappings[i].element_name, NULL, val);
2051 g_free (val);
2052 } else
2053 mappings[i].set_value_in_soap_request (cid->bbews, request, contact);
2054 }
2055
2056 /* end of "Contact" */
2057 e_soap_request_end_element (request);
2058
2059 return TRUE;
2060 }
2061
2062 typedef struct _ConvertData {
2063 EBookBackendEws *bbews;
2064 GCancellable *cancellable;
2065 GError **error;
2066
2067 EContact *old_contact;
2068 EContact *new_contact;
2069 gchar *change_key;
2070 } ConvertData;
2071
2072 static gboolean
2073 ebb_ews_convert_dl_to_updatexml_cb (ESoapRequest *request,
2074 gpointer user_data,
2075 GError **error)
2076 {
2077 ConvertData *cd = user_data;
2078 EContact *old_contact = cd->old_contact;
2079 EContact *new_contact = cd->new_contact;
2080 gchar *change_key = NULL;
2081
2082 if (!cd->change_key) {
2083 change_key = e_vcard_util_dup_x_attribute (E_VCARD (old_contact), X_EWS_CHANGEKEY);
2084 if (!change_key)
2085 change_key = e_contact_get (old_contact, E_CONTACT_REV);
2086 }
2087
2088 e_ews_request_start_item_change (request, E_EWS_ITEMCHANGE_TYPE_ITEM,
2089 e_contact_get_const (old_contact, E_CONTACT_UID),
2090 cd->change_key ? cd->change_key : change_key,
2091 0);
2092 e_ews_request_start_set_item_field (request, "Members", "distributionlist", "DistributionList");
2093 ebb_ews_write_dl_members (request, new_contact);
2094 e_ews_request_end_set_item_field (request);
2095 e_ews_request_end_item_change (request);
2096
2097 g_free (change_key);
2098
2099 return TRUE;
2100 }
2101
2102 static gboolean
2103 ebb_ews_convert_contact_to_updatexml_cb (ESoapRequest *request,
2104 gpointer user_data,
2105 GError **error)
2106 {
2107 ConvertData *cd = user_data;
2108 EContact *old_contact = cd->old_contact;
2109 EContact *new_contact = cd->new_contact;
2110 gchar *value = NULL, *old_value = NULL;
2111 gchar *change_key = NULL;
2112 gint i, element_type;
2113
2114 /* Pre-flight, to update the ChangeKey if needed */
2115 for (i = 0; i < G_N_ELEMENTS (mappings); i++) {
2116 element_type = mappings[i].element_type;
2117
2118 if (element_type == ELEMENT_TYPE_COMPLEX) {
2119 gchar *new_change_key = NULL;
2120
2121 if (mappings[i].field_id == E_CONTACT_UID)
2122 continue;
2123
2124 mappings[i].set_changes (cd->bbews, NULL, new_contact, old_contact, &new_change_key, cd->cancellable, cd->error);
2125
2126 if (new_change_key) {
2127 g_free (cd->change_key);
2128 cd->change_key = new_change_key;
2129 }
2130 }
2131 }
2132
2133 if (!cd->change_key) {
2134 change_key = e_vcard_util_dup_x_attribute (E_VCARD (old_contact), X_EWS_CHANGEKEY);
2135 if (!change_key)
2136 change_key = e_contact_get (old_contact, E_CONTACT_REV);
2137 }
2138
2139 e_ews_request_start_item_change (request, E_EWS_ITEMCHANGE_TYPE_ITEM,
2140 e_contact_get_const (old_contact, E_CONTACT_UID),
2141 cd->change_key ? cd->change_key : change_key,
2142 0);
2143
2144 /* Iterate for each field in contact */
2145
2146 for (i = 0; i < G_N_ELEMENTS (mappings); i++) {
2147 element_type = mappings[i].element_type;
2148 if (element_type == ELEMENT_TYPE_SIMPLE) {
2149 value = e_contact_get (new_contact, mappings[i].field_id);
2150 old_value = e_contact_get (old_contact, mappings[i].field_id);
2151 if (g_strcmp0 (value, old_value) != 0)
2152 convert_contact_property_to_updatexml (request, mappings[i].element_name, value, "contacts", NULL, NULL);
2153 if (value)
2154 g_free (value);
2155 if (old_value)
2156 g_free (old_value);
2157 } else if (element_type == ELEMENT_TYPE_COMPLEX) {
2158 gchar *new_change_key = NULL;
2159
2160 if (mappings[i].field_id == E_CONTACT_UID)
2161 continue;
2162
2163 mappings[i].set_changes (cd->bbews, request, new_contact, old_contact, &new_change_key, cd->cancellable, cd->error);
2164
2165 if (new_change_key) {
2166 g_free (cd->change_key);
2167 cd->change_key = new_change_key;
2168 }
2169 }
2170 }
2171
2172 e_ews_request_end_item_change (request);
2173
2174 g_free (change_key);
2175
2176 return TRUE;
2177 }
2178
2179 static EContact *
2180 ebb_ews_item_to_contact (EBookBackendEws *bbews,
2181 EEwsItem *item,
2182 gboolean use_primary_address,
2183 GCancellable *cancellable,
2184 GError **error)
2185 {
2186 EContact *contact;
2187 gint ii, element_type;
2188
2189 contact = e_contact_new ();
2190
2191 for (ii = 0; ii < G_N_ELEMENTS (mappings); ii++) {
2192 element_type = mappings[ii].element_type;
2193
2194 /* Skip email, when the primary is supposed to be used only */
2195 if (use_primary_address && mappings[ii].field_id == E_CONTACT_EMAIL_1)
2196 continue;
2197
2198 if (element_type == ELEMENT_TYPE_SIMPLE && !mappings[ii].populate_contact_func) {
2199 const gchar *val = mappings[ii].get_simple_prop_func (item);
2200
2201 if (val != NULL)
2202 e_contact_set (contact, mappings[ii].field_id, val);
2203 } else {
2204 mappings[ii].populate_contact_func (bbews, contact, item, cancellable, error);
2205 }
2206 }
2207
2208 return contact;
2209 }
2210
2211 static void
2212 ebb_ews_items_to_contacts (EBookBackendEws *bbews,
2213 const GSList *new_items,
2214 GSList **contacts,
2215 GCancellable *cancellable,
2216 GError **error)
2217 {
2218 GSList *link;
2219
2220 for (link = (GSList *) new_items; link; link = g_slist_next (link)) {
2221 EContact *contact;
2222 EEwsItem *item = link->data;
2223 EVCardAttribute *attr;
2224
2225 if (e_ews_item_get_item_type (item) == E_EWS_ITEM_TYPE_ERROR)
2226 continue;
2227
2228 contact = ebb_ews_item_to_contact (bbews, item, FALSE, cancellable, error);
2229
2230 attr = e_vcard_attribute_new (NULL, "X-EWS-KIND");
2231 e_vcard_add_attribute_with_value (E_VCARD (contact), attr, "DT_MAILUSER");
2232
2233 *contacts = g_slist_prepend (*contacts, contact);
2234 }
2235 }
2236
2237 static void
2238 ebb_ews_mailbox_to_contact (EBookBackendEws *bbews,
2239 EContact **contact,
2240 GHashTable *values,
2241 const EwsMailbox *mb)
2242 {
2243 CamelInternetAddress *addr;
2244 gchar *value;
2245
2246 if (!mb->name && !mb->email)
2247 return;
2248
2249 addr = camel_internet_address_new ();
2250
2251 camel_internet_address_add (addr, mb->name, mb->email ? mb->email : "");
2252 value = camel_address_encode (CAMEL_ADDRESS (addr));
2253
2254 if (value && (!values || g_hash_table_lookup (values, value) == NULL)) {
2255 EVCardAttribute *attr;
2256
2257 attr = e_vcard_attribute_new (NULL, EVC_EMAIL);
2258 e_vcard_attribute_add_value (attr, value);
2259 e_vcard_append_attribute (E_VCARD (*contact), attr);
2260
2261 if (values) {
2262 g_hash_table_insert (values, value, GINT_TO_POINTER (1));
2263 value = NULL;
2264 }
2265 }
2266
2267 g_free (value);
2268 g_object_unref (addr);
2269 }
2270
2271 static gboolean
2272 ebb_ews_traverse_dl (EBookBackendEws *bbews,
2273 EContact **contact,
2274 GHashTable *items,
2275 GHashTable *values,
2276 EwsMailbox *mb,
2277 GCancellable *cancellable,
2278 GError **error)
2279 {
2280 if (g_strcmp0 (mb->mailbox_type, "PrivateDL") == 0 ||
2281 g_strcmp0 (mb->mailbox_type, "PublicDL") == 0) {
2282 GSList *members = NULL, *l;
2283 gboolean includes_last;
2284 gboolean ret = FALSE;
2285 const gchar *ident;
2286 GError *local_error = NULL;
2287
2288 if (mb->item_id && mb->item_id->id)
2289 ident = mb->item_id->id;
2290 else if (mb->email)
2291 ident = mb->email;
2292 else
2293 return FALSE;
2294
2295 if (g_hash_table_lookup (items, ident) != NULL)
2296 return TRUE;
2297
2298 g_hash_table_insert (items, g_strdup (ident), GINT_TO_POINTER (1));
2299
2300 ret = e_ews_connection_expand_dl_sync (
2301 bbews->priv->cnc,
2302 EWS_PRIORITY_MEDIUM,
2303 mb,
2304 &includes_last,
2305 &members,
2306 cancellable,
2307 &local_error);
2308
2309 if (!ret) {
2310 if (g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_NAMERESOLUTIONNORESULTS)) {
2311 g_clear_error (&local_error);
2312 if (mb->email && *mb->email)
2313 ebb_ews_mailbox_to_contact (bbews, contact, values, mb);
2314
2315 ret = TRUE;
2316 members = NULL;
2317 } else {
2318 if (local_error)
2319 g_propagate_error (error, local_error);
2320
2321 return FALSE;
2322 }
2323 }
2324
2325 for (l = members; l; l = l->next) {
2326 ret = ebb_ews_traverse_dl (bbews, contact, items, values, l->data, cancellable, error);
2327 if (!ret)
2328 break;
2329 }
2330
2331 g_slist_free_full (members, (GDestroyNotify) e_ews_mailbox_free);
2332 return ret;
2333 } else {
2334 ebb_ews_mailbox_to_contact (bbews, contact, values, mb);
2335
2336 return TRUE;
2337 }
2338 }
2339
2340 static EContact *
2341 ebb_ews_get_dl_info (EBookBackendEws *bbews,
2342 EEwsItem *item,
2343 const EwsId *id,
2344 const gchar *d_name,
2345 GSList *members,
2346 GCancellable *cancellable,
2347 GError **error)
2348 {
2349 GHashTable *items, *values;
2350 GSList *l;
2351 EContact *contact;
2352
2353 contact = e_contact_new ();
2354 e_contact_set (contact, E_CONTACT_UID, id->id);
2355 e_vcard_util_set_x_attribute (E_VCARD (contact), X_EWS_CHANGEKEY, id->change_key);
2356 ebews_populate_rev (contact, item);
2357
2358 e_contact_set (contact, E_CONTACT_IS_LIST, GINT_TO_POINTER (TRUE));
2359 e_contact_set (contact, E_CONTACT_LIST_SHOW_ADDRESSES, GINT_TO_POINTER (TRUE));
2360 e_contact_set (contact, E_CONTACT_FULL_NAME, d_name);
2361
2362 items = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
2363 values = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
2364
2365 for (l = members; l != NULL; l = l->next) {
2366 if (!ebb_ews_traverse_dl (bbews, &contact, items, values, l->data, cancellable, error)) {
2367 g_object_unref (contact);
2368 contact = NULL;
2369 goto exit;
2370 }
2371 }
2372
2373 exit:
2374 g_hash_table_destroy (items);
2375 g_hash_table_destroy (values);
2376
2377 return contact;
2378 }
2379
2380 static gboolean
2381 ebb_ews_get_dl_info_gal (EBookBackendEws *bbews,
2382 EContact *contact,
2383 EwsMailbox *mb,
2384 GCancellable *cancellable,
2385 GError **error)
2386 {
2387 GHashTable *items, *values;
2388 gboolean success;
2389
2390 items = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
2391 values = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
2392
2393 success = ebb_ews_traverse_dl (bbews, &contact, items, values, mb, cancellable, error);
2394
2395 if (success) {
2396 e_contact_set (contact, E_CONTACT_IS_LIST, GINT_TO_POINTER (TRUE));
2397 e_contact_set (contact, E_CONTACT_LIST_SHOW_ADDRESSES, GINT_TO_POINTER (TRUE));
2398 }
2399
2400 g_hash_table_destroy (items);
2401 g_hash_table_destroy (values);
2402
2403 return success;
2404 }
2405
2406 static gboolean
2407 ebb_ews_contacts_append_dl (EBookBackendEws *bbews,
2408 EEwsItem *item,
2409 const EwsId *id,
2410 const gchar *d_name,
2411 GSList *members,
2412 GSList **contacts,
2413 GCancellable *cancellable,
2414 GError **error)
2415 {
2416 EContact *contact;
2417 EVCardAttribute *attr;
2418
2419 contact = ebb_ews_get_dl_info (bbews, item, id, d_name, members, cancellable, error);
2420 if (contact == NULL)
2421 return FALSE;
2422
2423 attr = e_vcard_attribute_new (NULL, "X-EWS-KIND");
2424 e_vcard_add_attribute_with_value (E_VCARD (contact), attr, "DT_DISTLIST");
2425
2426 *contacts = g_slist_prepend (*contacts, contact);
2427
2428 return TRUE;
2429 }
2430
2431 static gboolean
2432 ebb_ews_fetch_items_sync (EBookBackendEws *bbews,
2433 const GSList *items, /* EEwsItem * */
2434 GSList **contacts,
2435 GCancellable *cancellable,
2436 GError **error)
2437 {
2438 GSList *contact_item_ids = NULL, *dl_ids = NULL, *link;
2439 GSList *new_items = NULL;
2440 gboolean ret = FALSE;
2441
2442 for (link = (GSList *) items; link; link = g_slist_next (link)) {
2443 EEwsItem *item = link->data;
2444 const EwsId *id = e_ews_item_get_id (item);
2445 EEwsItemType type = e_ews_item_get_item_type (item);
2446
2447 if (type == E_EWS_ITEM_TYPE_CONTACT)
2448 contact_item_ids = g_slist_prepend (contact_item_ids, g_strdup (id->id));
2449 else if (type == E_EWS_ITEM_TYPE_GROUP) {
2450 /* store a list of EwsMailBox's in case of distribution lists */
2451 dl_ids = g_slist_prepend (dl_ids, g_strdup (id->id));
2452 }
2453 }
2454
2455 /* TODO fetch attachments */
2456 if (contact_item_ids) {
2457 EEwsAdditionalProps *add_props;
2458 add_props = e_ews_additional_props_new ();
2459
2460 if (e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2010_SP2))
2461 add_props->field_uri = g_strdup (CONTACT_ITEM_PROPS_10SP2);
2462 else
2463 add_props->field_uri = g_strdup (CONTACT_ITEM_PROPS);
2464
2465 ret = e_ews_connection_get_items_sync (
2466 bbews->priv->cnc, EWS_PRIORITY_MEDIUM,
2467 contact_item_ids, "Default", add_props,
2468 FALSE, NULL, E_EWS_BODY_TYPE_TEXT, &new_items, NULL, NULL,
2469 cancellable, error);
2470
2471 e_ews_additional_props_free (add_props);
2472
2473 if (!ret)
2474 goto cleanup;
2475 }
2476
2477 if (new_items) {
2478 ebb_ews_items_to_contacts (bbews, new_items, contacts, cancellable, error);
2479
2480 g_slist_free_full (new_items, g_object_unref);
2481 new_items = NULL;
2482 }
2483
2484 /* Get the display names of the distribution lists */
2485 if (dl_ids) {
2486 if (!e_ews_connection_get_items_sync (bbews->priv->cnc, EWS_PRIORITY_MEDIUM, dl_ids, "Default", NULL,
2487 FALSE, NULL, E_EWS_BODY_TYPE_TEXT, &new_items, NULL, NULL, cancellable, error))
2488 goto cleanup;
2489 }
2490
2491 for (link = new_items; link; link = g_slist_next (link)) {
2492 EEwsItem *item = link->data;
2493 const gchar *d_name;
2494 const EwsId *id;
2495 EwsMailbox *mb;
2496 GSList *members = NULL;
2497 gboolean includes_last;
2498 GError *local_error = NULL;
2499
2500 if (e_ews_item_get_item_type (item) == E_EWS_ITEM_TYPE_ERROR)
2501 continue;
2502
2503 id = e_ews_item_get_id (item);
2504 mb = g_new0 (EwsMailbox, 1);
2505 mb->item_id = (EwsId *) id;
2506
2507 d_name = e_ews_item_get_subject (item);
2508 if (e_ews_connection_expand_dl_sync (
2509 bbews->priv->cnc, EWS_PRIORITY_MEDIUM, mb, &includes_last, &members,
2510 cancellable, &local_error)) {
2511 ret = ebb_ews_contacts_append_dl (bbews, item, id, d_name, members, contacts, cancellable, error);
2512 g_slist_free_full (members, (GDestroyNotify) e_ews_mailbox_free);
2513 } else {
2514 ret = g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_NAMERESOLUTIONNORESULTS);
2515 if (ret) {
2516 g_clear_error (&local_error);
2517 } else if (local_error) {
2518 g_propagate_error (error, local_error);
2519 }
2520 }
2521
2522 g_free (mb);
2523
2524 if (!ret)
2525 goto cleanup;
2526 }
2527
2528 cleanup:
2529 g_slist_free_full (new_items, g_object_unref);
2530 g_slist_free_full (contact_item_ids, g_free);
2531 g_slist_free_full (dl_ids, g_free);
2532
2533 return ret;
2534 }
2535
2536 static void
2537 ebb_ews_server_notification_cb (EBookBackendEws *bbews,
2538 const GSList *events,
2539 EEwsConnection *cnc)
2540 {
2541 GSList *link;
2542 gboolean update_folder = FALSE;
2543
2544 g_return_if_fail (E_IS_BOOK_BACKEND_EWS (bbews));
2545
2546 for (link = (GSList *) events; link && !update_folder; link = g_slist_next (link)) {
2547 EEwsNotificationEvent *event = link->data;
2548
2549 switch (event->type) {
2550 case E_EWS_NOTIFICATION_EVENT_CREATED:
2551 case E_EWS_NOTIFICATION_EVENT_DELETED:
2552 case E_EWS_NOTIFICATION_EVENT_MODIFIED:
2553 g_rec_mutex_lock (&bbews->priv->cnc_lock);
2554
2555 if (g_strcmp0 (event->folder_id, bbews->priv->folder_id) == 0)
2556 update_folder = TRUE;
2557
2558 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
2559 break;
2560 case E_EWS_NOTIFICATION_EVENT_MOVED:
2561 case E_EWS_NOTIFICATION_EVENT_COPIED:
2562 g_rec_mutex_lock (&bbews->priv->cnc_lock);
2563
2564 if (g_strcmp0 (event->folder_id, bbews->priv->folder_id) == 0 ||
2565 g_strcmp0 (event->old_folder_id, bbews->priv->folder_id) == 0)
2566 update_folder = TRUE;
2567
2568 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
2569 break;
2570 default:
2571 return;
2572 }
2573 }
2574
2575 if (update_folder)
2576 e_book_meta_backend_schedule_refresh (E_BOOK_META_BACKEND (bbews));
2577 }
2578
2579 static void
2580 ebb_ews_unset_connection (EBookBackendEws *bbews,
2581 gboolean is_disconnect)
2582 {
2583 g_return_if_fail (E_IS_BOOK_BACKEND_EWS (bbews));
2584
2585 g_rec_mutex_lock (&bbews->priv->cnc_lock);
2586
2587 if (bbews->priv->cnc) {
2588 if (is_disconnect)
2589 e_ews_connection_set_disconnected_flag (bbews->priv->cnc, TRUE);
2590
2591 g_signal_handlers_disconnect_by_func (bbews->priv->cnc, ebb_ews_server_notification_cb, bbews);
2592
2593 if (bbews->priv->subscription_key != 0) {
2594 e_ews_connection_disable_notifications_sync (
2595 bbews->priv->cnc,
2596 bbews->priv->subscription_key);
2597 bbews->priv->subscription_key = 0;
2598 }
2599 }
2600
2601 g_clear_object (&bbews->priv->cnc);
2602
2603 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
2604 }
2605
2606 static gint
2607 det_sort_func (gconstpointer _a,
2608 gconstpointer _b)
2609 {
2610 const EwsOALDetails *a = _a, *b = _b;
2611
2612 return a->seq - b->seq;
2613 }
2614
2615 static gchar *
2616 ebb_ews_download_gal_file (EBookBackendEws *bbews,
2617 EwsOALDetails *full,
2618 GCancellable *cancellable,
2619 GError **error)
2620 {
2621 gchar *full_url, *oab_url;
2622 gchar *download_path = NULL;
2623 CamelEwsSettings *ews_settings;
2624 const gchar *cache_dir;
2625
2626 ews_settings = ebb_ews_get_collection_settings (bbews);
2627
2628 /* oab url with oab.xml removed from the suffix */
2629 oab_url = camel_ews_settings_dup_oaburl (ews_settings);
2630 if (!oab_url || !*oab_url) {
2631 g_free (oab_url);
2632 return NULL;
2633 }
2634
2635 if (g_str_has_suffix (oab_url, "oab.xml"))
2636 oab_url [strlen (oab_url) - 7] = '\0';
2637
2638 full_url = g_strconcat (oab_url, full->filename, NULL);
2639 cache_dir = e_book_backend_get_cache_dir (E_BOOK_BACKEND (bbews));
2640 download_path = g_build_filename (cache_dir, full->filename, NULL);
2641
2642 if (!e_ews_connection_download_oal_file_sync (bbews->priv->cnc, full_url, download_path, NULL, NULL, cancellable, error)) {
2643 g_free (download_path);
2644 download_path = NULL;
2645 } else {
2646 d (printf ("OAL file downloaded %s\n", download_path));
2647 }
2648
2649 g_free (oab_url);
2650 g_free (full_url);
2651
2652 return download_path;
2653 }
2654
2655 static gchar *
2656 ebb_ews_download_full_gal (EBookBackendEws *bbews,
2657 EwsOALDetails *full,
2658 GCancellable *cancellable,
2659 GError **error)
2660 {
2661 ESource *source;
2662 const gchar *cache_dir;
2663 gchar *lzx_path, *oab_file, *oab_path;
2664
2665 lzx_path = ebb_ews_download_gal_file (bbews, full, cancellable, error);
2666 if (!lzx_path)
2667 return NULL;
2668
2669 source = e_backend_get_source (E_BACKEND (bbews));
2670 oab_file = g_strdup_printf ("%s-%d.oab", e_source_get_display_name (source), full->seq);
2671 cache_dir = e_book_backend_get_cache_dir (E_BOOK_BACKEND (bbews));
2672 oab_path = g_build_filename (cache_dir, oab_file, NULL);
2673
2674 if (!ews_oab_decompress_full (lzx_path, oab_path, error)) {
2675 g_free (oab_path);
2676 oab_path = NULL;
2677 } else {
2678 d (printf ("OAL file decompressed %s\n", oab_path));
2679 }
2680
2681 if (lzx_path) {
2682 g_unlink (lzx_path);
2683 g_free (lzx_path);
2684 }
2685
2686 g_free (oab_file);
2687
2688 return oab_path;
2689 }
2690
2691 static gchar *
2692 ebb_ews_download_gal (EBookBackendEws *bbews,
2693 EBookCache *book_cache,
2694 EwsOALDetails *full,
2695 GSList *deltas,
2696 guint32 seq,
2697 GCancellable *cancellable,
2698 GError **error)
2699 {
2700 #ifdef WITH_MSPACK
2701 GSList *link;
2702 gchar *thisoab;
2703
2704 thisoab = e_cache_dup_key (E_CACHE (book_cache), "oab-filename", NULL);
2705 if (!thisoab)
2706 goto full;
2707
2708 for (link = deltas; link; link = g_slist_next (link)) {
2709 EwsOALDetails *det = link->data;
2710 ESource *source;
2711 gchar *oab_file, *lzx_path, *nextoab;
2712 const gchar *cache_dir;
2713 GError *local_error = NULL;
2714
2715 seq++;
2716 if (det->seq != seq)
2717 break;
2718
2719 lzx_path = ebb_ews_download_gal_file (bbews, det, cancellable, NULL);
2720 if (!lzx_path)
2721 break;
2722
2723 source = e_backend_get_source (E_BACKEND (bbews));
2724 oab_file = g_strdup_printf ("%s-%d.oab", e_source_get_display_name (source), seq);
2725 cache_dir = e_book_backend_get_cache_dir (E_BOOK_BACKEND (bbews));
2726 nextoab = g_build_filename (cache_dir, oab_file, NULL);
2727 g_free (oab_file);
2728
2729 ews_oab_decompress_patch (lzx_path, thisoab, nextoab, &local_error);
2730
2731 /* Free the LZX file */
2732 g_unlink (lzx_path);
2733 g_free (lzx_path);
2734
2735 /* Free the previous OAB file */
2736 g_unlink (thisoab);
2737 g_free (thisoab);
2738
2739 thisoab = nextoab;
2740
2741 /* For once we are *allowed* to use the error instead of having to
2742 * check the return value of the function. It's our *own* error. */
2743 if (local_error) {
2744 d (printf ("Failed to apply incremental patch: %s\n", local_error->message));
2745 g_error_free (local_error);
2746 break;
2747 }
2748
2749 d (printf ("Created %s from delta\n", thisoab));
2750
2751 if (seq == full->seq)
2752 return thisoab;
2753 }
2754
2755 if (thisoab) {
2756 g_unlink (thisoab);
2757 g_free (thisoab);
2758 }
2759 full:
2760 #endif /* WITH_MSPACK */
2761 d (printf ("Ewsgal: Downloading full gal \n"));
2762 return ebb_ews_download_full_gal (bbews, full, cancellable, error);
2763 }
2764
2765 static void
2766 ebb_ews_remove_old_gal_file (EBookCache *book_cache)
2767 {
2768 gchar *filename;
2769
2770 g_return_if_fail (E_IS_BOOK_CACHE (book_cache));
2771
2772 filename = e_cache_dup_key (E_CACHE (book_cache), "oab-filename", NULL);
2773
2774 if (filename)
2775 g_unlink (filename);
2776 g_free (filename);
2777 }
2778
2779 static gboolean
2780 ebb_ews_fetch_gal_photo_sync (EBookBackendEws *bbews,
2781 EContact *contact,
2782 GCancellable *cancellable,
2783 GError **error)
2784 {
2785 const gchar *email;
2786 gboolean success = FALSE;
2787
2788 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (bbews), FALSE);
2789 g_return_val_if_fail (E_IS_CONTACT (contact), FALSE);
2790
2791 email = e_contact_get_const (contact, E_CONTACT_EMAIL_1);
2792 if (!email || !*email)
2793 return FALSE;
2794
2795 g_rec_mutex_lock (&bbews->priv->cnc_lock);
2796
2797 if (bbews->priv->cnc) {
2798 gchar *photo_base64 = NULL;
2799 gboolean backoff_enabled;
2800
2801 backoff_enabled = e_ews_connection_get_backoff_enabled (bbews->priv->cnc);
2802 e_ews_connection_set_backoff_enabled (bbews->priv->cnc, FALSE);
2803
2804 if (e_ews_connection_get_user_photo_sync (bbews->priv->cnc, EWS_PRIORITY_MEDIUM, email,
2805 E_EWS_SIZE_REQUESTED_96X96, &photo_base64, cancellable, error) && photo_base64) {
2806 guchar *bytes;
2807 gsize nbytes;
2808
2809 bytes = g_base64_decode (photo_base64, &nbytes);
2810 if (bytes && nbytes > 0) {
2811 EContactPhoto *photo;
2812
2813 photo = e_contact_photo_new ();
2814 photo->type = E_CONTACT_PHOTO_TYPE_INLINED;
2815 e_contact_photo_set_inlined (photo, bytes, nbytes);
2816 e_contact_set (contact, E_CONTACT_PHOTO, photo);
2817 e_contact_photo_free (photo);
2818
2819 success = TRUE;
2820 }
2821
2822 g_free (photo_base64);
2823 g_free (bytes);
2824 }
2825
2826 e_ews_connection_set_backoff_enabled (bbews->priv->cnc, backoff_enabled);
2827 }
2828
2829 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
2830
2831 return success;
2832 }
2833
2834 static EBookMetaBackendInfo *ebb_ews_contact_to_info (EContact *contact, gboolean is_gal);
2835
2836 static void
2837 ebb_ews_fetch_gal_photos_thread (EBookBackend *book_backend,
2838 gpointer user_data,
2839 GCancellable *cancellable,
2840 GError **error)
2841 {
2842 EBookBackendEws *bbews = E_BOOK_BACKEND_EWS (book_backend);
2843 EBookCache *book_cache;
2844 ESourceEwsFolder *ews_folder;
2845 GSList *uids = user_data;
2846
2847 book_cache = e_book_meta_backend_ref_cache (E_BOOK_META_BACKEND (bbews));
2848 if (!book_cache)
2849 return;
2850
2851 ews_folder = e_source_get_extension (e_backend_get_source (E_BACKEND (bbews)), E_SOURCE_EXTENSION_EWS_FOLDER);
2852 if (e_source_ews_folder_get_fetch_gal_photos (ews_folder)) {
2853 g_rec_mutex_lock (&bbews->priv->cnc_lock);
2854
2855 if (!bbews->priv->fetching_gal_photos && bbews->priv->cnc &&
2856 e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2013)) {
2857 guint counter = 0, percent;
2858 gdouble total_count, current_count;
2859 GSList *link, *modified = NULL;
2860
2861 bbews->priv->fetching_gal_photos = TRUE;
2862
2863 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
2864
2865 percent = (guint) -1;
2866 current_count = 0;
2867 total_count = g_slist_length (uids);
2868
2869 /* Recheck the fetch-gal-photo property every time, in case the user changed it
2870 while the fetching had been ongoing. */
2871 for (link = uids;
2872 link && !g_cancellable_is_cancelled (cancellable) && e_source_ews_folder_get_fetch_gal_photos (ews_folder);
2873 current_count++, link = g_slist_next (link)) {
2874 const gchar *uid = link->data;
2875 guint new_percent;
2876 EContact *contact = NULL;
2877 EBookMetaBackendInfo *nfo;
2878 GError *local_error = NULL;
2879
2880 new_percent = (guint) ((current_count / total_count) * 100.0);
2881 if (new_percent != percent) {
2882 percent = new_percent;
2883 e_book_backend_foreach_view_notify_progress (book_backend, TRUE, (gint) percent, _("Fetching contact photos
"));
2884 }
2885
2886 if (!e_book_cache_get_contact (book_cache, uid, FALSE, &contact, cancellable, NULL) ||
2887 !contact || e_vcard_get_attribute (E_VCARD (contact), EVC_PHOTO) ||
2888 !ebb_ews_can_check_user_photo (contact)) {
2889 g_clear_object (&contact);
2890 continue;
2891 }
2892
2893 if (!ebb_ews_fetch_gal_photo_sync (bbews, contact, cancellable, &local_error))
2894 ebb_ews_store_photo_check_date (contact, NULL);
2895
2896 nfo = ebb_ews_contact_to_info (contact, bbews->priv->is_gal);
2897 if (nfo) {
2898 modified = g_slist_prepend (modified, nfo);
2899 counter++;
2900 }
2901
2902 g_clear_object (&contact);
2903
2904 /* Stop immediately when the server is busy */
2905 if (g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_SERVERBUSY)) {
2906 g_clear_error (&local_error);
2907 break;
2908 }
2909
2910 g_clear_error (&local_error);
2911
2912 if (counter == 100) {
2913 counter = 0;
2914 e_book_meta_backend_process_changes_sync (E_BOOK_META_BACKEND (bbews), NULL, modified, NULL, cancellable, NULL);
2915 g_slist_free_full (modified, e_book_meta_backend_info_free);
2916 modified = NULL;
2917 }
2918
2919 /* Give a chance to other threads to work with the connection, because the photos
2920 are not that important like the other operations. */
2921 g_thread_yield ();
2922 g_usleep (G_USEC_PER_SEC / 4);
2923 g_thread_yield ();
2924 }
2925
2926 if (modified) {
2927 e_book_meta_backend_process_changes_sync (E_BOOK_META_BACKEND (bbews), NULL, modified, NULL, cancellable, NULL);
2928 g_slist_free_full (modified, e_book_meta_backend_info_free);
2929 }
2930
2931 g_rec_mutex_lock (&bbews->priv->cnc_lock);
2932 bbews->priv->fetching_gal_photos = FALSE;
2933 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
2934
2935 if (percent != (guint) -1)
2936 e_book_backend_foreach_view_notify_progress (book_backend, TRUE, -1, NULL);
2937 } else {
2938 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
2939 }
2940 }
2941
2942 g_object_unref (book_cache);
2943 }
2944
2945 static void
2946 ebb_ews_free_string_slist (gpointer ptr)
2947 {
2948 GSList *list = ptr;
2949
2950 g_slist_free_full (list, g_free);
2951 }
2952
2953 static void
2954 ebb_ews_maybe_schedule_fetch_gal_photos (EBookBackendEws *bbews,
2955 GSList **inout_uids) /* gchar * */
2956 {
2957 ESourceEwsFolder *ews_folder;
2958
2959 if (!inout_uids || !*inout_uids)
2960 return;
2961
2962 ews_folder = e_source_get_extension (e_backend_get_source (E_BACKEND (bbews)), E_SOURCE_EXTENSION_EWS_FOLDER);
2963
2964 if (e_source_ews_folder_get_fetch_gal_photos (ews_folder)) {
2965 gboolean can_do_it;
2966
2967 g_rec_mutex_lock (&bbews->priv->cnc_lock);
2968 can_do_it = !bbews->priv->fetching_gal_photos && bbews->priv->cnc &&
2969 e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2013);
2970 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
2971
2972 if (can_do_it) {
2973 e_book_backend_schedule_custom_operation (E_BOOK_BACKEND (bbews), NULL,
2974 ebb_ews_fetch_gal_photos_thread,
2975 *inout_uids,
2976 ebb_ews_free_string_slist);
2977 *inout_uids = NULL;
2978 }
2979 }
2980 }
2981
2982 struct _db_data {
2983 EBookBackendEws *bbews;
2984 GHashTable *uids;
2985 GHashTable *sha1s;
2986 gint unchanged;
2987 gint changed;
2988 gint added;
2989 gint percent;
2990 gboolean fetch_gal_photos;
2991 GSList *fetch_gal_photos_list; /* gchar *uid */
2992 GSList *created_objects;
2993 GSList *modified_objects;
2994 };
2995
2996 static gboolean
2997 ebb_ews_gal_filter_contact (goffset offset,
2998 const gchar *sha1,
2999 gpointer user_data,
3000 GError **error)
3001 {
3002 struct _db_data *data = (struct _db_data *) user_data;
3003 gchar *uid;
3004
3005 /* Is there an existing identical record, with the same SHA1? */
3006 uid = g_hash_table_lookup (data->sha1s, sha1);
3007 if (!uid)
3008 return TRUE;
3009
3010 /* Remove it from the hash tables so it doesn't get deleted at the end. */
3011 g_hash_table_remove (data->sha1s, sha1);
3012 g_hash_table_remove (data->uids, uid);
3013 data->unchanged++;
3014
3015 /* Don't bother to parse and process this record. */
3016 return FALSE;
3017 }
3018
3019 static void
3020 ebb_ews_gal_store_contact (EContact *contact,
3021 goffset offset,
3022 const gchar *sha1,
3023 guint percent,
3024 gpointer user_data,
3025 GCancellable *cancellable,
3026 GError **error)
3027 {
3028 struct _db_data *data = (struct _db_data *) user_data;
3029
3030 if (contact) {
3031 const gchar *uid = e_contact_get_const (contact, E_CONTACT_UID);
3032 EBookMetaBackendInfo *nfo;
3033
3034 ebews_populate_rev (contact, NULL);
3035 e_vcard_util_set_x_attribute (E_VCARD (contact), X_EWS_GAL_SHA1, sha1);
3036
3037 if (data->fetch_gal_photos && !g_cancellable_is_cancelled (cancellable))
3038 data->fetch_gal_photos_list = g_slist_prepend (data->fetch_gal_photos_list, g_strdup (uid));
3039
3040 nfo = e_book_meta_backend_info_new (uid, e_contact_get_const (contact, E_CONTACT_REV), NULL, NULL);
3041 nfo->object = e_vcard_to_string (E_VCARD (contact), EVC_FORMAT_VCARD_30);
3042
3043 if (g_hash_table_remove (data->uids, uid)) {
3044 data->changed++;
3045 data->modified_objects = g_slist_prepend (data->modified_objects, nfo);
3046 } else {
3047 data->added++;
3048 data->created_objects = g_slist_prepend (data->created_objects, nfo);
3049 }
3050 }
3051
3052 if (data->percent != percent) {
3053 data->percent = percent;
3054
3055 d (printf ("GAL processing contacts, %d%% complete (%d added, %d changed, %d unchanged\n",
3056 percent, data->added, data->changed, data->unchanged));
3057 }
3058 }
3059
3060 static gboolean
3061 ebb_ews_gather_existing_uids_cb (EBookCache *book_cache,
3062 const gchar *uid,
3063 const gchar *revision,
3064 const gchar *object,
3065 const gchar *extra,
3066 guint32 custom_flags,
3067 EOfflineState offline_state,
3068 gpointer user_data)
3069 {
3070 struct _db_data *data = user_data;
3071 EVCard *vcard;
3072 gchar *dup_uid, *dup_sha1 = NULL;
3073
3074 g_return_val_if_fail (data != NULL, FALSE);
3075 g_return_val_if_fail (data->uids != NULL, FALSE);
3076 g_return_val_if_fail (data->sha1s != NULL, FALSE);
3077 g_return_val_if_fail (object != NULL, FALSE);
3078
3079 vcard = e_vcard_new_from_string (object);
3080 if (vcard) {
3081 dup_sha1 = e_vcard_util_dup_x_attribute (vcard, X_EWS_GAL_SHA1);
3082 g_object_unref (vcard);
3083 }
3084
3085 dup_uid = g_strdup (uid);
3086 if (!dup_sha1)
3087 dup_sha1 = g_strdup (revision);
3088
3089 g_hash_table_insert (data->uids, dup_uid, dup_sha1);
3090 if (dup_sha1)
3091 g_hash_table_insert (data->sha1s, dup_sha1, dup_uid);
3092
3093 return TRUE;
3094 }
3095
3096 static gboolean
3097 ebb_ews_check_gal_changes (EBookBackendEws *bbews,
3098 EBookCache *book_cache,
3099 const gchar *filename,
3100 GSList **out_created_objects, /*EBookMetaBackendInfo * */
3101 GSList **out_modified_objects, /*EBookMetaBackendInfo * */
3102 GSList **out_removed_objects, /*EBookMetaBackendInfo * */
3103 GCancellable *cancellable,
3104 GError **error)
3105 {
3106 ESourceEwsFolder *ews_folder;
3107 EwsOabDecoder *eod;
3108 gboolean success = TRUE;
3109 struct _db_data data;
3110 #if d(1) + 0
3111 gint64 t1, t2;
3112 #endif
3113 GError *local_error = NULL;
3114
3115 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (bbews), FALSE);
3116 g_return_val_if_fail (E_IS_BOOK_CACHE (book_cache), FALSE);
3117 g_return_val_if_fail (filename != NULL, FALSE);
3118 g_return_val_if_fail (out_created_objects != NULL, FALSE);
3119 g_return_val_if_fail (out_modified_objects != NULL, FALSE);
3120 g_return_val_if_fail (out_removed_objects != NULL, FALSE);
3121
3122 ews_folder = e_source_get_extension (e_backend_get_source (E_BACKEND (bbews)), E_SOURCE_EXTENSION_EWS_FOLDER);
3123
3124 data.bbews = bbews;
3125 data.fetch_gal_photos = e_source_ews_folder_get_fetch_gal_photos (ews_folder);
3126 data.fetch_gal_photos_list = NULL;
3127 data.created_objects = NULL;
3128 data.modified_objects = NULL;
3129 data.unchanged = data.changed = data.added = 0;
3130 data.percent = 0;
3131 data.uids = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
3132 data.sha1s = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
3133
3134 d (t1 = g_get_monotonic_time ());
3135
3136 e_book_cache_search_with_callback (book_cache, NULL, ebb_ews_gather_existing_uids_cb, &data, cancellable, NULL);
3137
3138 eod = ews_oab_decoder_new (filename, bbews->priv->attachments_dir, &local_error);
3139 if (!local_error) {
3140 GHashTableIter iter;
3141 gpointer key;
3142
3143 success = ews_oab_decoder_decode (eod, ebb_ews_gal_filter_contact, ebb_ews_gal_store_contact, &data, cancellable, &local_error);
3144
3145 if (success) {
3146 *out_created_objects = data.created_objects;
3147 *out_modified_objects = data.modified_objects;
3148 *out_removed_objects = NULL;
3149
3150 g_hash_table_iter_init (&iter, data.uids);
3151 while (g_hash_table_iter_next (&iter, &key, NULL)) {
3152 const gchar *uid = key;
3153
3154 *out_removed_objects = g_slist_prepend (*out_removed_objects,
3155 e_book_meta_backend_info_new (uid, NULL, NULL, NULL));
3156 }
3157
3158 ebb_ews_maybe_schedule_fetch_gal_photos (bbews, &data.fetch_gal_photos_list);
3159 } else {
3160 g_slist_free_full (data.created_objects, e_book_meta_backend_info_free);
3161 g_slist_free_full (data.modified_objects, e_book_meta_backend_info_free);
3162 }
3163
3164 g_slist_free_full (data.fetch_gal_photos_list, g_free);
3165 } else {
3166 success = FALSE;
3167 }
3168
3169 d (t2 = g_get_monotonic_time ());
3170 d (printf ("GAL update completed %ssuccessfully in %" G_GINT64_FORMAT " ”s. Added: %d, Changed: %d, Unchanged %d, Removed: %d (%s)\n",
3171 success ? "" : "un", (gint64) (t2 - t1), data.added, data.changed, data.unchanged, g_hash_table_size (data.uids),
3172 local_error ? local_error->message : "no error"));
3173
3174 g_hash_table_destroy (data.sha1s);
3175 g_hash_table_destroy (data.uids);
3176 g_clear_object (&eod);
3177
3178 if (local_error)
3179 g_propagate_error (error, local_error);
3180
3181 return success;
3182 }
3183
3184 typedef struct {
3185 /* For future use */
3186 gpointer restriction;
3187
3188 gboolean is_autocompletion;
3189 gchar *auto_comp_str;
3190 } EBookBackendEwsSExpData;
3191
3192 static ESExpResult *
3193 ebb_ews_func_not (ESExp *f,
3194 gint argc,
3195 ESExpResult **argv,
3196 gpointer data)
3197 {
3198 ESExpResult *r;
3199
3200 if (argc != 1 || argv[0]->type != ESEXP_RES_UNDEFINED) {
3201 e_sexp_fatal_error (f, "parse error");
3202 return NULL;
3203 }
3204
3205 r = e_sexp_result_new (f, ESEXP_RES_BOOL);
3206 r->value.boolean = FALSE;
3207
3208 return r;
3209 }
3210
3211 static ESExpResult *
3212 ebb_ews_func_and_or (ESExp *f,
3213 gint argc,
3214 ESExpResult **argv,
3215 gpointer and)
3216 {
3217 ESExpResult *r;
3218
3219 r = e_sexp_result_new (f, ESEXP_RES_BOOL);
3220 r->value.boolean = FALSE;
3221
3222 return r;
3223 }
3224
3225 /* TODO implement */
3226 static ESExpResult *
3227 ebb_ews_func_is (struct _ESExp *f,
3228 gint argc,
3229 struct _ESExpResult **argv,
3230 gpointer data)
3231 {
3232 ESExpResult *r;
3233
3234 if (argc != 2
3235 && argv[0]->type != ESEXP_RES_STRING
3236 && argv[1]->type != ESEXP_RES_STRING) {
3237 e_sexp_fatal_error (f, "parse error");
3238 return NULL;
3239 }
3240
3241 r = e_sexp_result_new (f, ESEXP_RES_BOOL);
3242 r->value.boolean = FALSE;
3243
3244 return r;
3245 }
3246
3247 /* TODO implement */
3248 static ESExpResult *
3249 ebb_ews_func_endswith (struct _ESExp *f,
3250 gint argc,
3251 struct _ESExpResult **argv,
3252 gpointer data)
3253 {
3254 ESExpResult *r;
3255
3256 if (argc != 2
3257 && argv[0]->type != ESEXP_RES_STRING
3258 && argv[1]->type != ESEXP_RES_STRING) {
3259 e_sexp_fatal_error (f, "parse error");
3260 return NULL;
3261 }
3262
3263 r = e_sexp_result_new (f, ESEXP_RES_BOOL);
3264 r->value.boolean = FALSE;
3265
3266 return r;
3267
3268 }
3269
3270 /* TODO implement */
3271 static ESExpResult *
3272 ebb_ews_func_contains (struct _ESExp *f,
3273 gint argc,
3274 struct _ESExpResult **argv,
3275 gpointer data)
3276 {
3277 ESExpResult *r;
3278 EBookBackendEwsSExpData *sdata = data;
3279 const gchar *propname, *str;
3280
3281 if (argc != 2
3282 && argv[0]->type != ESEXP_RES_STRING
3283 && argv[1]->type != ESEXP_RES_STRING) {
3284 e_sexp_fatal_error (f, "parse error");
3285 return NULL;
3286 }
3287
3288 propname = argv[0]->value.string;
3289 str = argv[1]->value.string;
3290
3291 if (!g_ascii_strcasecmp (propname, "full_name") || !g_ascii_strcasecmp (propname, "email") ||
3292 (str && *str && !g_ascii_strcasecmp (propname, "x-evolution-any-field"))) {
3293 if (!sdata->auto_comp_str) {
3294 sdata->auto_comp_str = g_strdup (str);
3295 sdata->is_autocompletion = TRUE;
3296 }
3297 }
3298
3299 r = e_sexp_result_new (f, ESEXP_RES_BOOL);
3300 r->value.boolean = FALSE;
3301
3302 return r;
3303
3304 }
3305
3306 /* We are just handling for autocompletion now. We need to support other fields after implementing
3307 * Restrictions and find_items request */
3308 static ESExpResult *
3309 ebb_ews_func_beginswith (struct _ESExp *f,
3310 gint argc,
3311 struct _ESExpResult **argv,
3312 gpointer data)
3313 {
3314 ESExpResult *r;
3315 const gchar *propname, *str;
3316 EBookBackendEwsSExpData *sdata = data;
3317
3318 if (argc != 2 ||
3319 argv[0]->type != ESEXP_RES_STRING ||
3320 argv[1]->type != ESEXP_RES_STRING) {
3321 e_sexp_fatal_error (f, "parse error");
3322 return NULL;
3323 }
3324
3325 propname = argv[0]->value.string;
3326 str = argv[1]->value.string;
3327
3328 if (!g_ascii_strcasecmp (propname, "full_name") || !g_ascii_strcasecmp (propname, "email") ||
3329 (str && *str && !g_ascii_strcasecmp (propname, "x-evolution-any-field"))) {
3330 if (!sdata->auto_comp_str) {
3331 sdata->auto_comp_str = g_strdup (str);
3332 sdata->is_autocompletion = TRUE;
3333 }
3334 }
3335
3336 r = e_sexp_result_new (f, ESEXP_RES_BOOL);
3337 r->value.boolean = FALSE;
3338 return r;
3339 }
3340
3341 static ESExpResult *
3342 ebb_ews_func_exists (struct _ESExp *f,
3343 gint argc,
3344 struct _ESExpResult **argv,
3345 gpointer data)
3346 {
3347 ESExpResult *r;
3348
3349 r = e_sexp_result_new (f, ESEXP_RES_BOOL);
3350 r->value.boolean = FALSE;
3351
3352 return r;
3353 }
3354
3355 static struct {
3356 const gchar *name;
3357 ESExpFunc *func;
3358 guint flags;
3359 } symbols[] = {
3360 { "and", ebb_ews_func_and_or, 0 },
3361 { "or", ebb_ews_func_and_or, 0},
3362 { "not", ebb_ews_func_not, 0 },
3363 { "contains", ebb_ews_func_contains, 0},
3364 { "is", ebb_ews_func_is, 0},
3365 { "beginswith", ebb_ews_func_beginswith, 0},
3366 { "endswith", ebb_ews_func_endswith, 0},
3367 { "exists", ebb_ews_func_exists, 0}
3368 };
3369
3370 /* FIXME build a complete filter from the query that can be used by find_items */
3371 static gboolean
3372 ebb_ews_build_restriction (const gchar *query,
3373 gchar **auto_comp_str)
3374 {
3375 ESExp *sexp;
3376 EBookBackendEwsSExpData sdata;
3377 gboolean autocompletion = FALSE;
3378 gint i;
3379
3380 *auto_comp_str = NULL;
3381
3382 sexp = e_sexp_new ();
3383 memset (&sdata, 0, sizeof (EBookBackendEwsSExpData));
3384 sdata.is_autocompletion = FALSE;
3385
3386 for (i = 0; i < G_N_ELEMENTS (symbols); i++) {
3387 e_sexp_add_function (
3388 sexp, 0, (gchar *) symbols[i].name,
3389 symbols[i].func,
3390 &sdata);
3391 }
3392
3393 e_sexp_input_text (sexp, query, strlen (query));
3394 if (e_sexp_parse (sexp) == -1) {
3395 const gchar *errstr = e_sexp_get_error (sexp);
3396
3397 g_printerr ("%s: Failed to parse query '%s': %s\n", G_STRFUNC, query, errstr ? errstr : "Unknown error");
3398 } else {
3399 ESExpResult *r;
3400
3401 r = e_sexp_eval (sexp);
3402 if (r) {
3403 autocompletion = sdata.is_autocompletion;
3404 if (autocompletion)
3405 *auto_comp_str = sdata.auto_comp_str;
3406 else
3407 g_free (sdata.auto_comp_str);
3408 }
3409
3410 e_sexp_result_free (sexp, r);
3411 }
3412
3413 g_object_unref (sexp);
3414
3415 return autocompletion && *auto_comp_str;
3416 }
3417
3418 static gboolean
3419 ebb_ews_update_cache_for_expression (EBookBackendEws *bbews,
3420 const gchar *expr,
3421 GCancellable *cancellable,
3422 GError **error)
3423 {
3424 EBookMetaBackend *meta_backend;
3425 CamelEwsSettings *ews_settings;
3426 gboolean success = TRUE;
3427
3428 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (bbews), FALSE);
3429
3430 /* Resolve names in GAL only for GAL */
3431 if (!bbews->priv->is_gal)
3432 return TRUE;
3433
3434 ews_settings = ebb_ews_get_collection_settings (bbews);
3435
3436 if (!bbews->priv->gal_oab_broken && camel_ews_settings_get_oab_offline (ews_settings))
3437 return TRUE;
3438
3439 meta_backend = E_BOOK_META_BACKEND (bbews);
3440
3441 g_rec_mutex_lock (&bbews->priv->cnc_lock);
3442
3443 /* Search only if not searching for everything */
3444 if (expr && *expr && g_ascii_strcasecmp (expr, "(contains \"x-evolution-any-field\" \"\")") != 0) {
3445 gchar *restriction_expr = NULL;
3446 GSList *mailboxes = NULL, *contacts = NULL, *found_infos = NULL;
3447 gboolean includes_last_item = TRUE;
3448
3449 success = ebb_ews_build_restriction (expr, &restriction_expr) &&
3450 e_book_meta_backend_ensure_connected_sync (meta_backend, cancellable, error) &&
3451 e_ews_connection_resolve_names_sync (bbews->priv->cnc, EWS_PRIORITY_MEDIUM, restriction_expr,
3452 EWS_SEARCH_AD, NULL, TRUE, &includes_last_item, &mailboxes, &contacts, cancellable, error);
3453
3454 if (success) {
3455 EBookCache *book_cache;
3456 ESourceEwsFolder *ews_folder;
3457 gboolean use_primary_address;
3458 GSList *mlink, *clink;
3459
3460 ews_folder = e_source_get_extension (e_backend_get_source (E_BACKEND (bbews)), E_SOURCE_EXTENSION_EWS_FOLDER);
3461 use_primary_address = e_source_ews_folder_get_use_primary_address (ews_folder);
3462 book_cache = e_book_meta_backend_ref_cache (meta_backend);
3463
3464 for (mlink = mailboxes, clink = contacts; mlink; mlink = g_slist_next (mlink), clink = g_slist_next (clink)) {
3465 EwsMailbox *mb = mlink->data;
3466 EEwsItem *contact_item = clink ? clink->data : NULL;
3467 EBookMetaBackendInfo *nfo;
3468 EContact *contact = NULL, *old_contact = NULL;
3469 gboolean is_public_dl = FALSE, mailbox_address_set = FALSE;
3470 const gchar *str;
3471
3472 if (g_strcmp0 (mb->mailbox_type, "PublicDL") == 0) {
3473 contact = e_contact_new ();
3474
3475 if (!ebb_ews_get_dl_info_gal (bbews, contact, mb, cancellable, NULL)) {
3476 g_clear_object (&contact);
3477 } else {
3478 is_public_dl = TRUE;
3479 }
3480 }
3481
3482 if (!contact && contact_item && e_ews_item_get_item_type (contact_item) == E_EWS_ITEM_TYPE_CONTACT)
3483 contact = ebb_ews_item_to_contact (bbews, contact_item, use_primary_address && !is_public_dl, cancellable, NULL);
3484
3485 if (!contact)
3486 contact = e_contact_new ();
3487
3488 /* We do not get an id from the server, so just using email_id as uid for now */
3489 e_contact_set (contact, E_CONTACT_UID, mb->email);
3490
3491 /* There is no ChangeKey provided either, thus make up some revision,
3492 to have the contact always updated in the local cache. */
3493 ebews_populate_rev (contact, NULL);
3494
3495 if (use_primary_address && !is_public_dl && mb->email &&
3496 (!mb->routing_type || g_ascii_strcasecmp (mb->routing_type, "SMTP") == 0)) {
3497 e_contact_set (contact, E_CONTACT_EMAIL_1, mb->email);
3498 mailbox_address_set = TRUE;
3499 }
3500
3501 str = e_contact_get_const (contact, E_CONTACT_FULL_NAME);
3502 if (!str || !*str)
3503 e_contact_set (contact, E_CONTACT_FULL_NAME, mb->name);
3504
3505 str = e_contact_get_const (contact, E_CONTACT_EMAIL_1);
3506 if (!str || !*str || (!is_public_dl && contact_item && !mailbox_address_set &&
3507 e_ews_item_get_item_type (contact_item) == E_EWS_ITEM_TYPE_CONTACT)) {
3508 /* Cleanup first, then re-add only SMTP addresses */
3509 e_contact_set (contact, E_CONTACT_EMAIL_1, NULL);
3510 e_contact_set (contact, E_CONTACT_EMAIL_2, NULL);
3511 e_contact_set (contact, E_CONTACT_EMAIL_3, NULL);
3512 e_contact_set (contact, E_CONTACT_EMAIL_4, NULL);
3513 e_contact_set (contact, E_CONTACT_EMAIL, NULL);
3514
3515 ebews_populate_emails_ex (bbews, contact, contact_item, TRUE, use_primary_address && !is_public_dl);
3516 }
3517
3518 str = e_contact_get_const (contact, E_CONTACT_EMAIL_1);
3519 if (!str || !*str) {
3520 e_contact_set (contact, E_CONTACT_EMAIL_1, mb->email);
3521 } else if (!is_public_dl && !mailbox_address_set && mb->email &&
3522 (!mb->routing_type || g_ascii_strcasecmp (mb->routing_type, "SMTP") == 0)) {
3523 EContactField fields[3] = { E_CONTACT_EMAIL_2, E_CONTACT_EMAIL_3, E_CONTACT_EMAIL_4 };
3524 gchar *emails[3];
3525 gint ii, ff = 0;
3526
3527 emails[0] = e_contact_get (contact, E_CONTACT_EMAIL_1);
3528 emails[1] = e_contact_get (contact, E_CONTACT_EMAIL_2);
3529 emails[2] = e_contact_get (contact, E_CONTACT_EMAIL_3);
3530
3531 /* Make the mailbox email the primary email and skip duplicates */
3532 e_contact_set (contact, E_CONTACT_EMAIL_1, NULL);
3533 e_contact_set (contact, E_CONTACT_EMAIL_2, NULL);
3534 e_contact_set (contact, E_CONTACT_EMAIL_3, NULL);
3535 e_contact_set (contact, E_CONTACT_EMAIL_4, NULL);
3536 e_contact_set (contact, E_CONTACT_EMAIL, NULL);
3537
3538 e_contact_set (contact, E_CONTACT_EMAIL_1, mb->email);
3539
3540 for (ii = 0; ii < 3; ii++) {
3541 if (emails[ii] && g_ascii_strcasecmp (emails[ii], mb->email) != 0) {
3542 e_contact_set (contact, fields[ff], emails[ii]);
3543 ff++;
3544 }
3545
3546 g_free (emails[ii]);
3547 }
3548 }
3549
3550 /* Copy photo information, if any there */
3551 if (e_book_cache_get_contact (book_cache, mb->email, FALSE, &old_contact, cancellable, NULL) && old_contact) {
3552 EContactPhoto *photo;
3553
3554 photo = e_contact_get (old_contact, E_CONTACT_PHOTO);
3555 if (photo) {
3556 e_contact_set (contact, E_CONTACT_PHOTO, photo);
3557 e_contact_photo_free (photo);
3558 } else {
3559 const gchar *photo_check_date;
3560
3561 photo_check_date = ebb_ews_get_photo_check_date (old_contact);
3562 if (photo_check_date)
3563 ebb_ews_store_photo_check_date (contact, photo_check_date);
3564 }
3565
3566 g_clear_object (&old_contact);
3567 }
3568
3569 ebb_ews_store_original_vcard (contact);
3570
3571 nfo = e_book_meta_backend_info_new (e_contact_get_const (contact, E_CONTACT_UID),
3572 e_contact_get_const (contact, E_CONTACT_REV), NULL, NULL);
3573 nfo->object = e_vcard_to_string (E_VCARD (contact), EVC_FORMAT_VCARD_30);
3574
3575 found_infos = g_slist_prepend (found_infos, nfo);
3576
3577 g_object_unref (contact);
3578 }
3579
3580 g_clear_object (&book_cache);
3581 }
3582
3583 g_slist_free_full (mailboxes, (GDestroyNotify) e_ews_mailbox_free);
3584 e_util_free_nullable_object_slist (contacts);
3585
3586 if (success) {
3587 GSList *created_objects = NULL, *modified_objects = NULL;
3588
3589 success = e_book_meta_backend_split_changes_sync (meta_backend, found_infos, &created_objects,
3590 &modified_objects, NULL, cancellable, error);
3591 if (success)
3592 success = e_book_meta_backend_process_changes_sync (meta_backend, created_objects,
3593 modified_objects, NULL, cancellable, error);
3594
3595 g_slist_free_full (created_objects, e_book_meta_backend_info_free);
3596 g_slist_free_full (modified_objects, e_book_meta_backend_info_free);
3597 }
3598
3599 g_slist_free_full (found_infos, e_book_meta_backend_info_free);
3600 g_free (restriction_expr);
3601 }
3602
3603 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
3604
3605 ebb_ews_convert_error_to_client_error (error);
3606 ebb_ews_maybe_disconnect_sync (bbews, error, cancellable);
3607
3608 return success;
3609 }
3610
3611 static GSList * /* the possibly modified 'in_items' */
3612 ebb_ews_verify_changes (EBookCache *book_cache,
3613 GSList *in_items, /* EEwsItem * */
3614 GCancellable *cancellable)
3615 {
3616 GSList *items = NULL, *link;
3617
3618 g_return_val_if_fail (E_IS_BOOK_CACHE (book_cache), in_items);
3619
3620 for (link = in_items; link; link = g_slist_next (link)) {
3621 EEwsItem *item = link->data;
3622 const EwsId *id = e_ews_item_get_id (item);
3623 EEwsItemType type = e_ews_item_get_item_type (item);
3624
3625 if (!g_cancellable_is_cancelled (cancellable) && (
3626 type == E_EWS_ITEM_TYPE_CONTACT ||
3627 type == E_EWS_ITEM_TYPE_GROUP)) {
3628 EContact *existing = NULL;
3629
3630 if (e_book_cache_get_contact (book_cache, id->id, TRUE, &existing, cancellable, NULL) &&
3631 existing) {
3632 gchar *change_key;
3633
3634 change_key = e_vcard_util_dup_x_attribute (E_VCARD (existing), X_EWS_CHANGEKEY);
3635 if (!change_key)
3636 change_key = e_contact_get (existing, E_CONTACT_REV);
3637
3638 if (g_strcmp0 (change_key, id->change_key) == 0) {
3639 g_object_unref (item);
3640 } else {
3641 items = g_slist_prepend (items, item);
3642 }
3643
3644 g_free (change_key);
3645 } else {
3646 items = g_slist_prepend (items, item);
3647 }
3648
3649 g_clear_object (&existing);
3650 } else {
3651 items = g_slist_prepend (items, item);
3652 }
3653 }
3654
3655 g_slist_free (in_items);
3656
3657 return items;
3658 }
3659
3660 static EBookMetaBackendInfo *
3661 ebb_ews_contact_to_info (EContact *contact,
3662 gboolean is_gal)
3663 {
3664 EBookMetaBackendInfo *nfo;
3665
3666 if (!E_IS_CONTACT (contact))
3667 return NULL;
3668
3669 if (!is_gal)
3670 ebb_ews_store_original_vcard (contact);
3671
3672 nfo = e_book_meta_backend_info_new (
3673 e_contact_get_const (contact, E_CONTACT_UID),
3674 e_contact_get_const (contact, E_CONTACT_REV),
3675 NULL, NULL);
3676 nfo->object = e_vcard_to_string (E_VCARD (contact), EVC_FORMAT_VCARD_30);
3677
3678 return nfo;
3679 }
3680
3681 static GSList * /* EBookMetaBackendInfo */
3682 ebb_ews_contacts_to_infos (const GSList *contacts, /* EContact * */
3683 gboolean is_gal)
3684 {
3685 GSList *nfos = NULL, *link;
3686
3687 for (link = (GSList *) contacts; link; link = g_slist_next (link)) {
3688 EContact *contact = link->data;
3689 EBookMetaBackendInfo *nfo;
3690
3691 nfo = ebb_ews_contact_to_info (contact, is_gal);
3692 if (nfo)
3693 nfos = g_slist_prepend (nfos, nfo);
3694 }
3695
3696 return nfos;
3697 }
3698
3699 typedef struct _MigrateData {
3700 gint data_version;
3701 gboolean is_gal;
3702 } MigrateData;
3703
3704 static gboolean
3705 ebb_ews_migrate_data_cb (ECache *cache,
3706 const gchar *uid,
3707 const gchar *revision,
3708 const gchar *object,
3709 EOfflineState offline_state,
3710 gint ncols,
3711 const gchar *column_names[],
3712 const gchar *column_values[],
3713 gchar **out_revision,
3714 gchar **out_object,
3715 EOfflineState *out_offline_state,
3716 ECacheColumnValues **out_other_columns,
3717 gpointer user_data)
3718 {
3719 MigrateData *md = user_data;
3720
3721 g_return_val_if_fail (md != NULL, FALSE);
3722 g_return_val_if_fail (object != NULL, FALSE);
3723 g_return_val_if_fail (out_object != NULL, FALSE);
3724
3725 if (md->data_version < 1) {
3726 EContact *contact;
3727
3728 contact = e_contact_new_from_vcard (object);
3729 if (contact) {
3730 gchar *vcard;
3731
3732 if (md->is_gal) {
3733 /* GAL doesn't store it, it's not writable */
3734 ebb_ews_remove_x_attribute (contact, X_EWS_ORIGINAL_VCARD);
3735 } else {
3736 /* This updates the X_EWS_ORIGINAL_VCARD to not contain itself */
3737 ebb_ews_store_original_vcard (contact);
3738 }
3739
3740 vcard = e_vcard_to_string (E_VCARD (contact), EVC_FORMAT_VCARD_30);
3741 if (vcard && *vcard)
3742 *out_object = vcard;
3743 else
3744 g_free (vcard);
3745
3746 g_object_unref (contact);
3747 }
3748 }
3749
3750 return TRUE;
3751 }
3752
3753 static gboolean
3754 ebb_ews_check_is_gal (EBookBackendEws *bbews)
3755 {
3756 CamelEwsSettings *ews_settings;
3757 ESource *source;
3758 gchar *gal_uid;
3759 gboolean is_gal;
3760
3761 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (bbews), FALSE);
3762
3763 source = e_backend_get_source (E_BACKEND (bbews));
3764 ews_settings = ebb_ews_get_collection_settings (bbews);
3765 gal_uid = camel_ews_settings_dup_gal_uid (ews_settings);
3766 is_gal = g_strcmp0 (e_source_get_uid (source), gal_uid) == 0;
3767 g_free (gal_uid);
3768
3769 return is_gal;
3770 }
3771
3772 static void
3773 ebb_ews_subscription_id_changed_cb (EEwsConnection *cnc,
3774 const gchar *subscription_id,
3775 gpointer user_data)
3776 {
3777 EBookBackendEws *bbews = user_data;
3778
3779 g_return_if_fail (E_IS_BOOK_BACKEND_EWS (bbews));
3780
3781 g_rec_mutex_lock (&bbews->priv->cnc_lock);
3782
3783 if (g_strcmp0 (bbews->priv->last_subscription_id, subscription_id) != 0) {
3784 g_free (bbews->priv->last_subscription_id);
3785 bbews->priv->last_subscription_id = g_strdup (subscription_id);
3786 }
3787
3788 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
3789 }
3790
3791 static gboolean
3792 ebb_ews_connect_sync (EBookMetaBackend *meta_backend,
3793 const ENamedParameters *credentials,
3794 ESourceAuthenticationResult *out_auth_result,
3795 gchar **out_certificate_pem,
3796 GTlsCertificateFlags *out_certificate_errors,
3797 GCancellable *cancellable,
3798 GError **error)
3799 {
3800 EBookBackendEws *bbews;
3801 EBookCache *book_cache;
3802 CamelEwsSettings *ews_settings;
3803 gchar *hosturl;
3804 gboolean success = FALSE;
3805
3806 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (meta_backend), FALSE);
3807 g_return_val_if_fail (out_auth_result != NULL, FALSE);
3808
3809 bbews = E_BOOK_BACKEND_EWS (meta_backend);
3810
3811 bbews->priv->gal_oab_broken = FALSE;
3812
3813 g_rec_mutex_lock (&bbews->priv->cnc_lock);
3814
3815 if (bbews->priv->cnc) {
3816 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
3817
3818 *out_auth_result = E_SOURCE_AUTHENTICATION_ACCEPTED;
3819
3820 return TRUE;
3821 }
3822
3823 book_cache = e_book_meta_backend_ref_cache (E_BOOK_META_BACKEND (bbews));
3824 if (book_cache) {
3825 ECache *cache = E_CACHE (book_cache);
3826 gint data_version;
3827
3828 data_version = e_cache_get_key_int (cache, EBB_EWS_DATA_VERSION_KEY, NULL);
3829
3830 if (data_version != EBB_EWS_DATA_VERSION) {
3831 MigrateData md;
3832
3833 e_cache_set_key_int (cache, EBB_EWS_DATA_VERSION_KEY, EBB_EWS_DATA_VERSION, NULL);
3834
3835 md.data_version = data_version;
3836 md.is_gal = ebb_ews_check_is_gal (bbews);
3837
3838 if (e_cache_foreach_update (cache, E_CACHE_INCLUDE_DELETED, NULL, ebb_ews_migrate_data_cb, &md, cancellable, NULL))
3839 e_cache_sqlite_exec (cache, "vacuum;", cancellable, NULL);
3840 }
3841
3842 g_clear_object (&book_cache);
3843 }
3844
3845 ews_settings = ebb_ews_get_collection_settings (bbews);
3846 hosturl = camel_ews_settings_dup_hosturl (ews_settings);
3847
3848 bbews->priv->cnc = e_ews_connection_new_for_backend (E_BACKEND (bbews), e_book_backend_get_registry (E_BOOK_BACKEND (bbews)), hosturl, ews_settings);
3849
3850 e_binding_bind_property (
3851 bbews, "proxy-resolver",
3852 bbews->priv->cnc, "proxy-resolver",
3853 G_BINDING_SYNC_CREATE);
3854
3855 *out_auth_result = e_ews_connection_try_credentials_sync (bbews->priv->cnc, credentials, NULL,
3856 out_certificate_pem, out_certificate_errors, cancellable, error);
3857
3858 if (*out_auth_result == E_SOURCE_AUTHENTICATION_ACCEPTED) {
3859 ESource *source = e_backend_get_source (E_BACKEND (bbews));
3860 ESourceEwsFolder *ews_folder;
3861
3862 ews_folder = e_source_get_extension (source, E_SOURCE_EXTENSION_EWS_FOLDER);
3863
3864 g_free (bbews->priv->folder_id);
3865 bbews->priv->folder_id = e_source_ews_folder_dup_id (ews_folder);
3866 bbews->priv->is_gal = ebb_ews_check_is_gal (bbews);
3867
3868 g_signal_connect_swapped (bbews->priv->cnc, "server-notification",
3869 G_CALLBACK (ebb_ews_server_notification_cb), bbews);
3870
3871 if (!bbews->priv->is_gal &&
3872 camel_ews_settings_get_listen_notifications (ews_settings) &&
3873 e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2010_SP1) &&
3874 !e_source_ews_folder_get_foreign (ews_folder) &&
3875 !e_source_ews_folder_get_public (ews_folder)) {
3876 GSList *folders = NULL;
3877
3878 folders = g_slist_prepend (folders, bbews->priv->folder_id);
3879
3880 e_ews_connection_set_last_subscription_id (bbews->priv->cnc, bbews->priv->last_subscription_id);
3881
3882 g_signal_connect_object (bbews->priv->cnc, "subscription-id-changed",
3883 G_CALLBACK (ebb_ews_subscription_id_changed_cb), bbews, 0);
3884
3885 e_ews_connection_enable_notifications_sync (bbews->priv->cnc,
3886 folders, &bbews->priv->subscription_key);
3887
3888 g_slist_free (folders);
3889 }
3890
3891 e_book_backend_set_writable (E_BOOK_BACKEND (bbews), !bbews->priv->is_gal);
3892 success = TRUE;
3893 } else {
3894 ebb_ews_convert_error_to_client_error (error);
3895 g_clear_object (&bbews->priv->cnc);
3896 }
3897
3898 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
3899
3900 g_free (hosturl);
3901
3902 return success;
3903 }
3904
3905 static gboolean
3906 ebb_ews_disconnect_sync (EBookMetaBackend *meta_backend,
3907 GCancellable *cancellable,
3908 GError **error)
3909 {
3910 EBookBackendEws *bbews;
3911
3912 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (meta_backend), FALSE);
3913
3914 bbews = E_BOOK_BACKEND_EWS (meta_backend);
3915 bbews->priv->gal_oab_broken = FALSE;
3916
3917 ebb_ews_unset_connection (bbews, TRUE);
3918
3919 return TRUE;
3920 }
3921
3922 static gboolean
3923 ebb_ews_get_changes_sync (EBookMetaBackend *meta_backend,
3924 const gchar *last_sync_tag,
3925 gboolean is_repeat,
3926 gchar **out_new_sync_tag,
3927 gboolean *out_repeat,
3928 GSList **out_created_objects,
3929 GSList **out_modified_objects,
3930 GSList **out_removed_objects,
3931 GCancellable *cancellable,
3932 GError **error)
3933 {
3934 EBookBackendEws *bbews;
3935 EBookCache *book_cache;
3936 gboolean sync_tag_stamp_changed;
3937 gboolean success = TRUE;
3938 GError *local_error = NULL;
3939
3940 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (meta_backend), FALSE);
3941 g_return_val_if_fail (out_new_sync_tag != NULL, FALSE);
3942 g_return_val_if_fail (out_repeat != NULL, FALSE);
3943 g_return_val_if_fail (out_created_objects != NULL, FALSE);
3944 g_return_val_if_fail (out_modified_objects != NULL, FALSE);
3945 g_return_val_if_fail (out_removed_objects != NULL, FALSE);
3946
3947 *out_created_objects = NULL;
3948 *out_modified_objects = NULL;
3949 *out_removed_objects = NULL;
3950
3951 bbews = E_BOOK_BACKEND_EWS (meta_backend);
3952
3953 book_cache = e_book_meta_backend_ref_cache (meta_backend);
3954 g_return_val_if_fail (E_IS_BOOK_CACHE (book_cache), FALSE);
3955
3956 sync_tag_stamp_changed = ebb_ews_get_sync_tag_stamp_changed (bbews);
3957 if (sync_tag_stamp_changed)
3958 last_sync_tag = NULL;
3959
3960 g_rec_mutex_lock (&bbews->priv->cnc_lock);
3961
3962 if (bbews->priv->is_gal) {
3963 CamelEwsSettings *ews_settings;
3964 gchar *oab_url;
3965
3966 ews_settings = ebb_ews_get_collection_settings (bbews);
3967 oab_url = camel_ews_settings_dup_oaburl (ews_settings);
3968
3969 if (oab_url && *oab_url &&
3970 camel_ews_settings_get_oab_offline (ews_settings)) {
3971 GSList *full_l = NULL, *deltas = NULL, *link;
3972 EwsOALDetails *full = NULL;
3973 gchar *etag = NULL;
3974 gint sequence;
3975
3976 sequence = e_cache_get_key_int (E_CACHE (book_cache), "gal-sequence", NULL);
3977 if (sequence == -1)
3978 sequence = 0;
3979
3980 d (printf ("Ewsgal: Fetching oal full details file\n"));
3981 if (!e_ews_connection_get_oal_detail_sync (bbews->priv->cnc, oab_url, bbews->priv->folder_id, NULL, last_sync_tag, &full_l, &etag, cancellable, &local_error)) {
3982 if (g_error_matches (local_error, E_SOUP_SESSION_ERROR, SOUP_STATUS_NOT_MODIFIED)) {
3983 g_clear_error (&local_error);
3984 } else {
3985 success = FALSE;
3986 }
3987 }
3988
3989 if (success && full_l) {
3990 guint32 delta_size = 0;
3991
3992 for (link = full_l; link; link = g_slist_next (link)) {
3993 EwsOALDetails *det = link->data;
3994
3995 /* Throw away anything older than we already have */
3996 if (det->seq <= sequence) {
3997 ews_oal_details_free (det);
3998 } else if (!g_strcmp0 (det->type, "Full")) {
3999 if (full)
4000 ews_oal_details_free (full);
4001 full = det;
4002 } else if (sequence > 0 && !g_strcmp0 (det->type, "Diff")) {
4003 delta_size += det->size;
4004 deltas = g_slist_insert_sorted (deltas, det, det_sort_func);
4005 } else {
4006 ews_oal_details_free (det);
4007 }
4008 }
4009
4010 g_slist_free (full_l);
4011 full_l = NULL;
4012
4013 /* If the deltas would be bigger, just download the new full file */
4014 if (full && delta_size > full->size) {
4015 g_slist_free_full (deltas, (GDestroyNotify) ews_oal_details_free);
4016 deltas = NULL;
4017 }
4018 }
4019
4020 if (full) {
4021 gchar *uncompressed_filename;
4022
4023 uncompressed_filename = ebb_ews_download_gal (bbews, book_cache, full, deltas, sequence, cancellable, &local_error);
4024 if (!uncompressed_filename) {
4025 success = FALSE;
4026 } else {
4027 d (printf ("Ewsgal: Removing old gal\n"));
4028 /* remove old_gal_file */
4029 ebb_ews_remove_old_gal_file (book_cache);
4030
4031 d (printf ("Ewsgal: Check for changes in GAL\n"));
4032 success = ebb_ews_check_gal_changes (bbews, book_cache, uncompressed_filename,
4033 out_created_objects, out_modified_objects, out_removed_objects, cancellable, &local_error);
4034
4035 if (success) {
4036 if (e_cache_set_key (E_CACHE (book_cache), "oab-filename", uncompressed_filename, NULL)) {
4037 /* Don't let it get deleted */
4038 g_free (uncompressed_filename);
4039 uncompressed_filename = NULL;
4040 }
4041
4042 e_cache_set_key_int (E_CACHE (book_cache), "gal-sequence", full->seq, NULL);
4043
4044 d (printf ("Ewsgal: sync successfully completed\n"));
4045 }
4046
4047 ews_oal_details_free (full);
4048 }
4049
4050 if (uncompressed_filename) {
4051 /* preserve the oab file once we are able to decode the differential updates */
4052 g_unlink (uncompressed_filename);
4053 g_free (uncompressed_filename);
4054 }
4055 }
4056
4057 g_slist_free_full (full_l, (GDestroyNotify) ews_oal_details_free);
4058 g_slist_free_full (deltas, (GDestroyNotify) ews_oal_details_free);
4059
4060 bbews->priv->gal_oab_broken = !success && (!local_error || !g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_AUTHENTICATION_FAILED));
4061
4062 if (success)
4063 *out_new_sync_tag = etag;
4064 else
4065 g_free (etag);
4066
4067 if (local_error) {
4068 g_prefix_error (&local_error, "%s", _("Failed to update GAL:"));
4069 g_propagate_error (error, local_error);
4070 }
4071 } else {
4072 bbews->priv->gal_oab_broken = TRUE;
4073 }
4074
4075 g_free (oab_url);
4076 } else {
4077 GSList *items_created = NULL, *items_modified = NULL, *items_deleted = NULL, *link;
4078 gboolean includes_last_item = TRUE;
4079
4080 success = e_ews_connection_sync_folder_items_sync (bbews->priv->cnc, EWS_PRIORITY_MEDIUM,
4081 last_sync_tag, bbews->priv->folder_id, "IdOnly", NULL, EWS_MAX_FETCH_COUNT,
4082 out_new_sync_tag, &includes_last_item, &items_created, &items_modified, &items_deleted,
4083 cancellable, &local_error);
4084
4085 if (!success &&
4086 g_error_matches (local_error, EWS_CONNECTION_ERROR, EWS_CONNECTION_ERROR_INVALIDSYNCSTATEDATA)) {
4087 g_clear_error (&local_error);
4088
4089 e_book_meta_backend_empty_cache_sync (meta_backend, cancellable, NULL);
4090
4091 success = e_ews_connection_sync_folder_items_sync (bbews->priv->cnc, EWS_PRIORITY_MEDIUM,
4092 NULL, bbews->priv->folder_id, "IdOnly", NULL, EWS_MAX_FETCH_COUNT,
4093 out_new_sync_tag, &includes_last_item, &items_created, &items_modified, &items_deleted,
4094 cancellable, &local_error);
4095 }
4096
4097 if (success) {
4098 GSList *contacts_created = NULL, *contacts_modified = NULL;
4099
4100 /* The sync state doesn't cover changes made by save_contact_sync(),
4101 thus verify the changes, instead of re-donwloading the contacts again */
4102 items_created = ebb_ews_verify_changes (book_cache, items_created, cancellable);
4103 items_modified = ebb_ews_verify_changes (book_cache, items_modified, cancellable);
4104
4105 if (items_created) {
4106 success = ebb_ews_fetch_items_sync (bbews, items_created, &contacts_created, cancellable, error);
4107 if (success)
4108 *out_created_objects = ebb_ews_contacts_to_infos (contacts_created, bbews->priv->is_gal);
4109 }
4110
4111 if (items_modified) {
4112 success = ebb_ews_fetch_items_sync (bbews, items_modified, &contacts_modified, cancellable, error);
4113 if (success)
4114 *out_modified_objects = ebb_ews_contacts_to_infos (contacts_modified, bbews->priv->is_gal);
4115 }
4116
4117 for (link = items_deleted; link; link = g_slist_next (link)) {
4118 const gchar *uid = link->data;
4119
4120 *out_removed_objects = g_slist_prepend (*out_removed_objects,
4121 e_book_meta_backend_info_new (uid, NULL, NULL, NULL));
4122 }
4123
4124 g_slist_free_full (contacts_created, g_object_unref);
4125 g_slist_free_full (contacts_modified, g_object_unref);
4126
4127 *out_repeat = !includes_last_item;
4128 } else if (local_error) {
4129 g_propagate_error (error, local_error);
4130 }
4131
4132 g_slist_free_full (items_created, g_object_unref);
4133 g_slist_free_full (items_modified, g_object_unref);
4134 g_slist_free_full (items_deleted, g_free);
4135 }
4136
4137 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
4138
4139 ebb_ews_convert_error_to_client_error (error);
4140 ebb_ews_maybe_disconnect_sync (bbews, error, cancellable);
4141
4142 g_clear_object (&book_cache);
4143
4144 if (success && sync_tag_stamp_changed)
4145 ebb_ews_update_sync_tag_stamp (bbews);
4146
4147 return success;
4148 }
4149
4150 static gboolean
4151 ebb_ews_load_contact_sync (EBookMetaBackend *meta_backend,
4152 const gchar *uid,
4153 const gchar *extra,
4154 EContact **out_contact,
4155 gchar **out_extra,
4156 GCancellable *cancellable,
4157 GError **error)
4158 {
4159 EBookBackendEws *bbews;
4160 GSList *ids, *items = NULL;
4161 gboolean success;
4162
4163 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (meta_backend), FALSE);
4164 g_return_val_if_fail (uid != NULL, FALSE);
4165 g_return_val_if_fail (out_contact, FALSE);
4166
4167 bbews = E_BOOK_BACKEND_EWS (meta_backend);
4168
4169 g_rec_mutex_lock (&bbews->priv->cnc_lock);
4170
4171 ids = g_slist_prepend (NULL, (gpointer) uid);
4172
4173 success = e_ews_connection_get_items_sync (bbews->priv->cnc, EWS_PRIORITY_MEDIUM, ids, "IdOnly",
4174 NULL, FALSE, NULL, E_EWS_BODY_TYPE_TEXT, &items, NULL, NULL, cancellable, error);
4175
4176 g_slist_free (ids);
4177
4178 if (!items)
4179 success = FALSE;
4180
4181 if (success) {
4182 GSList *contacts = NULL;
4183
4184 success = ebb_ews_fetch_items_sync (bbews, items, &contacts, cancellable, error);
4185 if (success && contacts) {
4186 *out_contact = g_object_ref (contacts->data);
4187
4188 ebb_ews_store_original_vcard (*out_contact);
4189 }
4190
4191 g_slist_free_full (contacts, g_object_unref);
4192 }
4193
4194 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
4195
4196 g_slist_free_full (items, g_object_unref);
4197
4198 ebb_ews_convert_error_to_client_error (error);
4199 ebb_ews_maybe_disconnect_sync (bbews, error, cancellable);
4200
4201 return success;
4202 }
4203
4204 static gboolean
4205 ebb_ews_save_contact_sync (EBookMetaBackend *meta_backend,
4206 gboolean overwrite_existing,
4207 EConflictResolution conflict_resolution,
4208 /* const */ EContact *contact,
4209 const gchar *extra,
4210 guint32 opflags,
4211 gchar **out_new_uid,
4212 gchar **out_new_extra,
4213 GCancellable *cancellable,
4214 GError **error)
4215 {
4216 EBookBackendEws *bbews;
4217 EwsFolderId *fid;
4218 GSList *items = NULL;
4219 gboolean is_dl = FALSE;
4220 gboolean success;
4221
4222 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (meta_backend), FALSE);
4223 g_return_val_if_fail (E_IS_CONTACT (contact), FALSE);
4224 g_return_val_if_fail (out_new_uid != NULL, FALSE);
4225 g_return_val_if_fail (out_new_extra != NULL, FALSE);
4226
4227 bbews = E_BOOK_BACKEND_EWS (meta_backend);
4228
4229 g_rec_mutex_lock (&bbews->priv->cnc_lock);
4230
4231 if (e_contact_get (contact, E_CONTACT_IS_LIST)) {
4232 if (!e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2010)) {
4233 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
4234 g_propagate_error (error, EC_ERROR_EX (E_CLIENT_ERROR_NOT_SUPPORTED,
4235 _("Cannot save contact list, it’s only supported on EWS Server 2010 or later")));
4236 return FALSE;
4237 }
4238
4239 is_dl = TRUE;
4240 }
4241
4242 fid = e_ews_folder_id_new (bbews->priv->folder_id, NULL, FALSE);
4243 if (overwrite_existing) {
4244 EBookCache *book_cache;
4245 EContact *old_contact = NULL;
4246
4247 book_cache = e_book_meta_backend_ref_cache (meta_backend);
4248
4249 success = e_book_cache_get_contact (book_cache, e_contact_get_const (contact, E_CONTACT_UID), FALSE, &old_contact, cancellable, error);
4250 if (success) {
4251 const gchar *original_vcard;
4252
4253 /* This is for offline changes, where the EContact in the cache
4254 is already modified, while the original, the one on the server,
4255 is different. Using the cached EContact in this case generates
4256 empty UpdateItem request and nothing is saved. */
4257 original_vcard = ebb_ews_get_original_vcard (old_contact);
4258 if (original_vcard) {
4259 EContact *tmp;
4260
4261 tmp = e_contact_new_from_vcard (original_vcard);
4262 if (tmp) {
4263 g_object_unref (old_contact);
4264 old_contact = tmp;
4265 }
4266 }
4267 }
4268
4269 if (success) {
4270 ConvertData cd;
4271 const gchar *conflict_res = "AlwaysOverwrite";
4272
4273 cd.bbews = bbews;
4274 cd.cancellable = cancellable;
4275 cd.error = error;
4276 cd.old_contact = old_contact;
4277 cd.new_contact = contact;
4278 cd.change_key = NULL;
4279
4280 if (conflict_resolution == E_CONFLICT_RESOLUTION_FAIL)
4281 conflict_res = "NeverOverwrite";
4282
4283 success = e_ews_connection_update_items_sync (bbews->priv->cnc, EWS_PRIORITY_MEDIUM,
4284 conflict_res, "SendAndSaveCopy", "SendToAllAndSaveCopy",
4285 bbews->priv->folder_id, is_dl ? ebb_ews_convert_dl_to_updatexml_cb : ebb_ews_convert_contact_to_updatexml_cb,
4286 &cd, &items, cancellable, error);
4287
4288 g_free (cd.change_key);
4289 }
4290
4291 g_clear_object (&old_contact);
4292 g_clear_object (&book_cache);
4293 } else {
4294 CreateItemsData cid;
4295
4296 cid.bbews = bbews;
4297 cid.contact = contact;
4298
4299 success = e_ews_connection_create_items_sync (bbews->priv->cnc, EWS_PRIORITY_MEDIUM, NULL, NULL,
4300 fid, is_dl ? ebb_ews_convert_dl_to_xml_cb : ebb_ews_convert_contact_to_xml_cb, &cid,
4301 &items, cancellable, error);
4302 }
4303
4304 if (success && items) {
4305 EEwsItem *item = items->data;
4306 const EwsId *item_id;
4307
4308 item_id = e_ews_item_get_id (item);
4309 *out_new_uid = g_strdup (item_id->id);
4310
4311 /*
4312 * Support for ContactPhoto was added in Exchange 2010 SP2.
4313 * We don't want to try to set/get this property if we are running in older version of the server.
4314 */
4315 if (!overwrite_existing &&
4316 e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2010_SP2)) {
4317 EContactPhoto *photo;
4318
4319 /*
4320 * The contact photo is basically an attachment with a special name.
4321 * Considering this, we only can set the contact photo after create the contact itself.
4322 * Then we are able to attach the picture to the "Contact Item".
4323 */
4324 photo = e_contact_get (contact, E_CONTACT_PHOTO);
4325 if (photo) {
4326 GError *local_error = NULL;
4327
4328 set_photo (bbews, item_id, contact, photo, NULL, cancellable, &local_error);
4329 e_contact_photo_free (photo);
4330
4331 if (local_error) {
4332 g_propagate_error (error, local_error);
4333 g_prefix_error (error, "%s", _("Failed to set contact photo:"));
4334 success = FALSE;
4335 }
4336 }
4337 }
4338 }
4339
4340 g_slist_free_full (items, g_object_unref);
4341 e_ews_folder_id_free (fid);
4342
4343 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
4344
4345 ebb_ews_convert_error_to_client_error (error);
4346 ebb_ews_maybe_disconnect_sync (bbews, error, cancellable);
4347
4348 return success;
4349 }
4350
4351 static gboolean
4352 ebb_ews_remove_contact_sync (EBookMetaBackend *meta_backend,
4353 EConflictResolution conflict_resolution,
4354 const gchar *uid,
4355 const gchar *extra,
4356 const gchar *object,
4357 guint32 opflags,
4358 GCancellable *cancellable,
4359 GError **error)
4360 {
4361 EBookBackendEws *bbews;
4362 GSList *ids;
4363 gboolean success;
4364
4365 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (meta_backend), FALSE);
4366
4367 bbews = E_BOOK_BACKEND_EWS (meta_backend);
4368
4369 g_rec_mutex_lock (&bbews->priv->cnc_lock);
4370
4371 ids = g_slist_prepend (NULL, (gpointer) uid);
4372
4373 success = e_ews_connection_delete_items_sync (bbews->priv->cnc, EWS_PRIORITY_MEDIUM, ids, EWS_HARD_DELETE, 0, FALSE, cancellable, error);
4374
4375 g_slist_free (ids);
4376
4377 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
4378
4379 ebb_ews_convert_error_to_client_error (error);
4380 ebb_ews_maybe_disconnect_sync (bbews, error, cancellable);
4381
4382 return success;
4383 }
4384
4385 static gboolean
4386 ebb_ews_search_sync (EBookMetaBackend *meta_backend,
4387 const gchar *expr,
4388 gboolean meta_contact,
4389 GSList **out_contacts,
4390 GCancellable *cancellable,
4391 GError **error)
4392 {
4393 EBookBackendEws *bbews;
4394
4395 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (meta_backend), FALSE);
4396
4397 bbews = E_BOOK_BACKEND_EWS (meta_backend);
4398
4399 /* Ignore errors, just try its best */
4400 ebb_ews_update_cache_for_expression (bbews, expr, cancellable, NULL);
4401
4402 /* Chain up to parent's method */
4403 if (!E_BOOK_META_BACKEND_CLASS (e_book_backend_ews_parent_class)->search_sync (meta_backend, expr, meta_contact,
4404 out_contacts, cancellable, error))
4405 return FALSE;
4406
4407 if (bbews->priv->is_gal && !meta_contact && out_contacts && *out_contacts) {
4408 ESourceEwsFolder *ews_folder;
4409
4410 ews_folder = e_source_get_extension (e_backend_get_source (E_BACKEND (bbews)), E_SOURCE_EXTENSION_EWS_FOLDER);
4411 if (e_source_ews_folder_get_fetch_gal_photos (ews_folder)) {
4412 g_rec_mutex_lock (&bbews->priv->cnc_lock);
4413
4414 if (bbews->priv->cnc && e_ews_connection_satisfies_server_version (bbews->priv->cnc, E_EWS_EXCHANGE_2013)) {
4415 GSList *link, *fetch_gal_photos_list = NULL;
4416
4417 for (link = *out_contacts; link && !g_cancellable_is_cancelled (cancellable); link = g_slist_next (link)) {
4418 EContact *contact = link->data;
4419
4420 if (!contact || e_vcard_get_attribute (E_VCARD (contact), EVC_PHOTO) ||
4421 !ebb_ews_can_check_user_photo (contact))
4422 continue;
4423
4424 fetch_gal_photos_list = g_slist_prepend (fetch_gal_photos_list, e_contact_get (contact, E_CONTACT_UID));
4425 }
4426
4427 if (!g_cancellable_is_cancelled (cancellable))
4428 ebb_ews_maybe_schedule_fetch_gal_photos (bbews, &fetch_gal_photos_list);
4429
4430 g_slist_free_full (fetch_gal_photos_list, g_free);
4431 }
4432
4433 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
4434 }
4435 }
4436
4437 return TRUE;
4438 }
4439
4440 static gboolean
4441 ebb_ews_search_uids_sync (EBookMetaBackend *meta_backend,
4442 const gchar *expr,
4443 GSList **out_uids,
4444 GCancellable *cancellable,
4445 GError **error)
4446 {
4447 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (meta_backend), FALSE);
4448
4449 /* Ignore errors, just try its best */
4450 ebb_ews_update_cache_for_expression (E_BOOK_BACKEND_EWS (meta_backend), expr, cancellable, NULL);
4451
4452 /* Chain up to parent's method */
4453 return E_BOOK_META_BACKEND_CLASS (e_book_backend_ews_parent_class)->search_uids_sync (meta_backend, expr,
4454 out_uids, cancellable, error);
4455 }
4456
4457 static gchar *
4458 ebb_ews_get_backend_property (EBookBackend *book_backend,
4459 const gchar *prop_name)
4460 {
4461 EBookBackendEws *bbews;
4462
4463 g_return_val_if_fail (E_IS_BOOK_BACKEND_EWS (book_backend), NULL);
4464 g_return_val_if_fail (prop_name != NULL, NULL);
4465
4466 bbews = E_BOOK_BACKEND_EWS (book_backend);
4467
4468 if (g_str_equal (prop_name, CLIENT_BACKEND_PROPERTY_CAPABILITIES)) {
4469 CamelEwsSettings *ews_settings;
4470
4471 ews_settings = ebb_ews_get_collection_settings (bbews);
4472
4473 return g_strjoin (",",
4474 "net",
4475 "contact-lists",
4476 e_book_meta_backend_get_capabilities (E_BOOK_META_BACKEND (book_backend)),
4477 (!bbews->priv->is_gal || camel_ews_settings_get_oab_offline (ews_settings)) ? "do-initial-query" : NULL,
4478 NULL);
4479 } else if (g_str_equal (prop_name, E_BOOK_BACKEND_PROPERTY_REQUIRED_FIELDS)) {
4480 return g_strdup (e_contact_field_name (E_CONTACT_FILE_AS));
4481 } else if (g_str_equal (prop_name, E_BOOK_BACKEND_PROPERTY_SUPPORTED_FIELDS)) {
4482 GString *buffer;
4483 gchar *fields;
4484 gint ii;
4485
4486 buffer = g_string_sized_new (1024);
4487
4488 for (ii = 0; ii < G_N_ELEMENTS (mappings); ii++) {
4489 if (mappings[ii].element_type != ELEMENT_TYPE_SIMPLE)
4490 continue;
4491
4492 if (buffer->len > 0)
4493 g_string_append_c (buffer, ',');
4494 g_string_append (buffer, e_contact_field_name (mappings[ii].field_id));
4495 }
4496
4497 for (ii = 0; ii < G_N_ELEMENTS (phone_field_map); ii++) {
4498 if (buffer->len > 0)
4499 g_string_append_c (buffer, ',');
4500 g_string_append (buffer, e_contact_field_name (phone_field_map[ii].field));
4501 }
4502
4503 fields = g_strjoin (
4504 ",",
4505 buffer->str,
4506 e_contact_field_name (E_CONTACT_FULL_NAME),
4507 e_contact_field_name (E_CONTACT_NICKNAME),
4508 e_contact_field_name (E_CONTACT_FAMILY_NAME),
4509 e_contact_field_name (E_CONTACT_EMAIL_1),
4510 e_contact_field_name (E_CONTACT_EMAIL_2),
4511 e_contact_field_name (E_CONTACT_EMAIL_3),
4512 e_contact_field_name (E_CONTACT_ADDRESS_WORK),
4513 e_contact_field_name (E_CONTACT_ADDRESS_HOME),
4514 e_contact_field_name (E_CONTACT_ADDRESS_OTHER),
4515 e_contact_field_name (E_CONTACT_ANNIVERSARY),
4516 e_contact_field_name (E_CONTACT_BIRTH_DATE),
4517 e_contact_field_name (E_CONTACT_NOTE),
4518 e_contact_field_name (E_CONTACT_PHOTO),
4519 e_contact_field_name (E_CONTACT_X509_CERT),
4520 e_contact_field_name (E_CONTACT_CATEGORIES),
4521 NULL);
4522
4523 g_string_free (buffer, TRUE);
4524
4525 return fields;
4526 }
4527
4528 /* Chain up to parent's method. */
4529 return E_BOOK_BACKEND_CLASS (e_book_backend_ews_parent_class)->impl_get_backend_property (book_backend, prop_name);
4530 }
4531
4532 static void
4533 ebb_ews_start_view_gal_search_thread_func (EBookBackend *book_backend,
4534 gpointer user_data,
4535 GCancellable *cancellable,
4536 GError **error)
4537 {
4538 EDataBookView *view = user_data;
4539 EBookBackendEws *bbews;
4540
4541 g_return_if_fail (E_IS_BOOK_BACKEND_EWS (book_backend));
4542 g_return_if_fail (E_IS_DATA_BOOK_VIEW (view));
4543
4544 bbews = E_BOOK_BACKEND_EWS (book_backend);
4545
4546 if (!g_cancellable_set_error_if_cancelled (cancellable, error)) {
4547 EBookBackendSExp *sexp;
4548 GSList *contacts = NULL;
4549 const gchar *expr = NULL;
4550
4551 sexp = e_data_book_view_get_sexp (view);
4552 if (sexp)
4553 expr = e_book_backend_sexp_text (sexp);
4554
4555 /* this is called only for offline GAL and it's enough to search for the contacts,
4556 the rest is done by the notifications when added/discovered a new contact */
4557 if (e_book_meta_backend_search_sync (E_BOOK_META_BACKEND (book_backend), expr, TRUE, &contacts, cancellable, NULL))
4558 g_slist_free_full (contacts, g_object_unref);
4559 }
4560
4561 g_rec_mutex_lock (&bbews->priv->cnc_lock);
4562 g_hash_table_remove (bbews->priv->view_cancellables, view);
4563 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
4564 }
4565
4566 static void
4567 ebb_ews_start_view (EBookBackend *book_backend,
4568 EDataBookView *view)
4569 {
4570 if ((e_data_book_view_get_flags (view) & E_BOOK_CLIENT_VIEW_FLAGS_MANUAL_QUERY) != 0) {
4571 EBookBackendEws *bbews = E_BOOK_BACKEND_EWS (book_backend);
4572
4573 /* Resolve names in GAL only for GAL */
4574 if (bbews->priv->is_gal) {
4575 CamelEwsSettings *ews_settings;
4576
4577 ews_settings = ebb_ews_get_collection_settings (bbews);
4578
4579 if (bbews->priv->gal_oab_broken || !camel_ews_settings_get_oab_offline (ews_settings)) {
4580 GCancellable *cancellable;
4581
4582 cancellable = g_cancellable_new ();
4583
4584 g_rec_mutex_lock (&bbews->priv->cnc_lock);
4585 g_hash_table_insert (bbews->priv->view_cancellables, view, g_object_ref (cancellable));
4586 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
4587
4588 e_book_backend_schedule_custom_operation (book_backend, cancellable,
4589 ebb_ews_start_view_gal_search_thread_func, g_object_ref (view), g_object_unref);
4590
4591 g_clear_object (&cancellable);
4592 }
4593 }
4594 }
4595
4596 /* Chain up to parent's method. */
4597 E_BOOK_BACKEND_CLASS (e_book_backend_ews_parent_class)->impl_start_view (book_backend, view);
4598 }
4599
4600 static void
4601 ebb_ews_stop_view (EBookBackend *book_backend,
4602 EDataBookView *view)
4603 {
4604 if ((e_data_book_view_get_flags (view) & E_BOOK_CLIENT_VIEW_FLAGS_MANUAL_QUERY) != 0) {
4605 EBookBackendEws *bbews = E_BOOK_BACKEND_EWS (book_backend);
4606 GCancellable *cancellable;
4607 gpointer value = NULL;
4608
4609 g_rec_mutex_lock (&bbews->priv->cnc_lock);
4610 if (!g_hash_table_steal_extended (bbews->priv->view_cancellables, view, NULL, &value))
4611 value = NULL;
4612 g_rec_mutex_unlock (&bbews->priv->cnc_lock);
4613
4614 cancellable = value;
4615
4616 if (cancellable) {
4617 g_cancellable_cancel (cancellable);
4618 g_clear_object (&cancellable);
4619 }
4620 }
4621
4622 /* Chain up to parent's method. */
4623 E_BOOK_BACKEND_CLASS (e_book_backend_ews_parent_class)->impl_stop_view (book_backend, view);
4624 }
4625
4626 static gboolean
4627 ebb_ews_get_destination_address (EBackend *backend,
4628 gchar **host,
4629 guint16 *port)
4630 {
4631 CamelEwsSettings *ews_settings;
4632 GUri *uri;
4633 gchar *host_url;
4634 gboolean result = FALSE;
4635
4636 g_return_val_if_fail (port != NULL, FALSE);
4637 g_return_val_if_fail (host != NULL, FALSE);
4638
4639 /* Sanity checking */
4640 if (!e_book_backend_get_registry (E_BOOK_BACKEND (backend)) ||
4641 !e_backend_get_source (backend))
4642 return FALSE;
4643
4644 ews_settings = ebb_ews_get_collection_settings (E_BOOK_BACKEND_EWS (backend));
4645 g_return_val_if_fail (ews_settings != NULL, FALSE);
4646
4647 host_url = camel_ews_settings_dup_hosturl (ews_settings);
4648 g_return_val_if_fail (host_url != NULL, FALSE);
4649
4650 uri = g_uri_parse (host_url, SOUP_HTTP_URI_FLAGS | G_URI_FLAGS_PARSE_RELAXED, NULL);
4651 if (uri) {
4652 *host = g_strdup (g_uri_get_host (uri));
4653 *port = g_uri_get_port (uri) > 0 ? g_uri_get_port (uri) : 0;
4654
4655 result = *host && **host;
4656 if (!result) {
4657 g_free (*host);
4658 *host = NULL;
4659 }
4660
4661 g_uri_unref (uri);
4662 }
4663
4664 g_free (host_url);
4665
4666 return result;
4667 }
4668
4669 static void
4670 e_book_backend_ews_constructed (GObject *object)
4671 {
4672 EBookBackendEws *bbews = E_BOOK_BACKEND_EWS (object);
4673 EBookCache *book_cache;
4674 gchar *cache_dirname;
4675
4676 /* Chain up to parent's method. */
4677 G_OBJECT_CLASS (e_book_backend_ews_parent_class)->constructed (object);
4678
4679 book_cache = e_book_meta_backend_ref_cache (E_BOOK_META_BACKEND (bbews));
4680
4681 cache_dirname = g_path_get_dirname (e_cache_get_filename (E_CACHE (book_cache)));
4682
4683 g_clear_object (&book_cache);
4684
4685 bbews->priv->attachments_dir = g_build_filename (cache_dirname, "attachments", NULL);
4686 g_mkdir_with_parents (bbews->priv->attachments_dir, 0777);
4687
4688 g_free (cache_dirname);
4689 }
4690
4691 static void
4692 e_book_backend_ews_dispose (GObject *object)
4693 {
4694 EBookBackendEws *bbews = E_BOOK_BACKEND_EWS (object);
4695
4696 ebb_ews_unset_connection (bbews, FALSE);
4697
4698 /* Chain up to parent's method. */
4699 G_OBJECT_CLASS (e_book_backend_ews_parent_class)->dispose (object);
4700 }
4701
4702 static void
4703 e_book_backend_ews_finalize (GObject *object)
4704 {
4705 EBookBackendEws *bbews = E_BOOK_BACKEND_EWS (object);
4706
4707 g_free (bbews->priv->folder_id);
4708 g_free (bbews->priv->attachments_dir);
4709 g_free (bbews->priv->last_subscription_id);
4710 g_hash_table_destroy (bbews->priv->view_cancellables);
4711
4712 g_rec_mutex_clear (&bbews->priv->cnc_lock);
4713
4714 /* Chain up to parent's method. */
4715 G_OBJECT_CLASS (e_book_backend_ews_parent_class)->finalize (object);
4716 }
4717
4718 static void
4719 e_book_backend_ews_init (EBookBackendEws *bbews)
4720 {
4721 bbews->priv = e_book_backend_ews_get_instance_private (bbews);
4722
4723 bbews->priv->view_cancellables = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);
4724
4725 g_rec_mutex_init (&bbews->priv->cnc_lock);
4726 }
4727
4728 static void
4729 e_book_backend_ews_class_init (EBookBackendEwsClass *klass)
4730 {
4731 GObjectClass *object_class;
4732 EBackendClass *backend_class;
4733 EBookBackendClass *book_backend_class;
4734 EBookMetaBackendClass *book_meta_backend_class;
4735
4736 book_meta_backend_class = E_BOOK_META_BACKEND_CLASS (klass);
4737 book_meta_backend_class->backend_module_directory = BACKENDDIR;
4738 book_meta_backend_class->backend_module_filename = "libebookbackendews.so";
4739 book_meta_backend_class->backend_factory_type_name = "EBookBackendEwsFactory";
4740 book_meta_backend_class->connect_sync = ebb_ews_connect_sync;
4741 book_meta_backend_class->disconnect_sync = ebb_ews_disconnect_sync;
4742 book_meta_backend_class->get_changes_sync = ebb_ews_get_changes_sync;
4743 book_meta_backend_class->load_contact_sync = ebb_ews_load_contact_sync;
4744 book_meta_backend_class->save_contact_sync = ebb_ews_save_contact_sync;
4745 book_meta_backend_class->remove_contact_sync = ebb_ews_remove_contact_sync;
4746 book_meta_backend_class->search_sync = ebb_ews_search_sync;
4747 book_meta_backend_class->search_uids_sync = ebb_ews_search_uids_sync;
4748
4749 book_backend_class = E_BOOK_BACKEND_CLASS (klass);
4750 book_backend_class->impl_get_backend_property = ebb_ews_get_backend_property;
4751 book_backend_class->impl_start_view = ebb_ews_start_view;
4752 book_backend_class->impl_stop_view = ebb_ews_stop_view;
4753
4754 backend_class = E_BACKEND_CLASS (klass);
4755 backend_class->get_destination_address = ebb_ews_get_destination_address;
4756
4757 object_class = G_OBJECT_CLASS (klass);
4758 object_class->constructed = e_book_backend_ews_constructed;
4759 object_class->dispose = e_book_backend_ews_dispose;
4760 object_class->finalize = e_book_backend_ews_finalize;
4761 }