aboutsummaryrefslogtreecommitdiffstats
path: root/addressbook/backend/pas/pas-backend-vcf.c
blob: e82fe04f56a95efb6aba44ba089826abc448878e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
 * Author:
 *   Chris Toshok (toshok@ximian.com)
 *
 * Copyright (C) 2003, Ximian, Inc.
 */

#include "config.h"  
#include "pas-backend-vcf.h"
#include "pas-backend-card-sexp.h"
#include "pas-book.h"
#include "pas-book-view.h"

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#include <sys/stat.h>

#include <gal/util/e-util.h>
#include <gal/widgets/e-unicode.h>

#include <ebook/e-contact.h>
#include <libgnome/gnome-i18n.h>

#define PAS_ID_PREFIX "pas-id-"
#define FILE_FLUSH_TIMEOUT 5000

static PASBackendSyncClass *pas_backend_vcf_parent_class;
typedef struct _PASBackendVCFBookView PASBackendVCFBookView;
typedef struct _PASBackendVCFSearchContext PASBackendVCFSearchContext;

struct _PASBackendVCFPrivate {
    char       *uri;
    char       *filename;
    GMutex     *mutex;
    GHashTable *contacts;
    gboolean    dirty;
    int         flush_timeout_tag;
};

static char *
pas_backend_vcf_create_unique_id ()
{
    /* use a 32 counter and the 32 bit timestamp to make an id.
       it's doubtful 2^32 id's will be created in a second, so we
       should be okay. */
    static guint c = 0;
    return g_strdup_printf (PAS_ID_PREFIX "%08lX%08X", time(NULL), c++);
}

typedef struct {
    PASBackendVCF *bvcf;
    PASBook *book;
    PASBookView *view;
} VCFBackendSearchClosure;

static void
free_search_closure (VCFBackendSearchClosure *closure)
{
    g_free (closure);
}

static void
foreach_search_compare (char *id, char *vcard_string, VCFBackendSearchClosure *closure)
{
    EContact *contact;

    contact = e_contact_new_from_vcard (vcard_string);
    pas_book_view_notify_update (closure->view, contact);
    g_object_unref (contact);
}

static gboolean
pas_backend_vcf_search_timeout (gpointer data)
{
    VCFBackendSearchClosure *closure = data;

    g_hash_table_foreach (closure->bvcf->priv->contacts,
                  (GHFunc)foreach_search_compare,
                  closure);

    pas_book_view_notify_complete (closure->view, GNOME_Evolution_Addressbook_Success);

    free_search_closure (closure);

    return FALSE;
}


static void
pas_backend_vcf_search (PASBackendVCF         *bvcf,
            PASBookView           *book_view)
{
    const char *query = pas_book_view_get_card_query (book_view);
    VCFBackendSearchClosure *closure = g_new0 (VCFBackendSearchClosure, 1);

    if ( ! strcmp (query, "(contains \"x-evolution-any-field\" \"\")"))
        pas_book_view_notify_status_message (book_view, _("Loading..."));
    else
        pas_book_view_notify_status_message (book_view, _("Searching..."));

    closure->view = book_view;
    closure->bvcf = bvcf;

    g_idle_add (pas_backend_vcf_search_timeout, closure);
}

static void
insert_contact (PASBackendVCF *vcf, char *vcard)
{
    EContact *contact = e_contact_new_from_vcard (vcard);
    char *id;

    id = e_contact_get (contact, E_CONTACT_UID);
    if (id)
        g_hash_table_insert (vcf->priv->contacts,
                     id,
                     e_vcard_to_string (E_VCARD (contact), EVC_FORMAT_VCARD_30));
}

static void
load_file (PASBackendVCF *vcf, int fd)
{
    FILE *fp;
    GString *str;
    char buf[1024];

    fp = fdopen (fd, "r");
    if (!fp) {
        g_warning ("failed to open `%s' for reading", vcf->priv->filename);
        return;
    }

    str = g_string_new ("");

    while (fgets (buf, sizeof (buf), fp)) {
        if (!strcmp (buf, "\r\n")) {
            /* if the string has accumulated some stuff, create a contact for it and start over */
            if (str->len) {
                insert_contact (vcf, str->str);
                g_string_assign (str, "");
            }
        }
        else {
            g_string_append (str, buf);
        }
    }
    if (str->len) {
        insert_contact (vcf, str->str);
    }

    g_string_free (str, TRUE);

    fclose (fp);
}

static void
foreach_build_list (char *id, char *vcard_string, GList **list)
{
    *list = g_list_append (*list, vcard_string);
}

static gboolean
save_file (PASBackendVCF *vcf)
{
    GList *vcards = NULL;
    GList *l;
    char *new_path;
    int fd, rv;

    g_warning ("PASBackendVCF flushing file to disk");

    g_mutex_lock (vcf->priv->mutex);
    g_hash_table_foreach (vcf->priv->contacts, (GHFunc)foreach_build_list, &vcards);

    new_path = g_strdup_printf ("%s.new", vcf->priv->filename);

    fd = open (new_path, O_CREAT | O_TRUNC | O_WRONLY, 0666);

    for (l = vcards; l; l = l->next) {
        char *vcard_str = l->data;
        int len = strlen (vcard_str);

        rv = write (fd, vcard_str, len);

        if (rv < len) {
            /* XXX */
            g_warning ("write failed.  we need to handle short writes\n");
            close (fd);
            unlink (new_path);
            return FALSE;
        }

        rv = write (fd, "\r\n\r\n", 4);
        if (rv < 4) {
            /* XXX */
            g_warning ("write failed.  we need to handle short writes\n");
            close (fd);
            unlink (new_path);
            return FALSE;
        }
    }

    if (0 > rename (new_path, vcf->priv->filename)) {
        g_warning ("Failed to rename %s: %s\n", vcf->priv->filename, strerror(errno));
        unlink (new_path);
        return FALSE;
    }

    g_list_free (vcards);
    g_free (new_path);

    vcf->priv->dirty = FALSE;

    g_mutex_unlock (vcf->priv->mutex);

    return TRUE;
}

static gboolean
vcf_flush_file (gpointer data)
{
    PASBackendVCF *bvcf = PAS_BACKEND_VCF (data);

    if (!bvcf->priv->dirty) {
        bvcf->priv->flush_timeout_tag = 0;
        return FALSE;
    }

    if (!save_file (bvcf)) {
        g_warning ("failed to flush the .vcf file to disk, will try again next timeout");
        return TRUE;
    }

    bvcf->priv->flush_timeout_tag = 0;
    return FALSE;
}

static EContact *
do_create(PASBackendVCF  *bvcf,
      const char     *vcard_req,
      gboolean        dirty_the_file)
{
    char           *id;
    EContact       *contact;
    char           *vcard;

    /* at the very least we need the unique_id generation to be
       protected by the lock, even if the actual vcard parsing
       isn't. */
    g_mutex_lock (bvcf->priv->mutex);
    id = pas_backend_vcf_create_unique_id ();

    contact = e_contact_new_from_vcard (vcard_req);
    e_contact_set(contact, E_CONTACT_UID, id);
    vcard = e_vcard_to_string (E_VCARD (contact), EVC_FORMAT_VCARD_30);

    g_hash_table_insert (bvcf->priv->contacts, id, vcard);

    if (dirty_the_file) {
        bvcf->priv->dirty = TRUE;

        if (!bvcf->priv->flush_timeout_tag)
            bvcf->priv->flush_timeout_tag = g_timeout_add (FILE_FLUSH_TIMEOUT,
                                       vcf_flush_file, bvcf);
    }

    g_mutex_unlock (bvcf->priv->mutex);

    return contact;
}

static PASBackendSyncStatus
pas_backend_vcf_process_create_contact (PASBackendSync *backend,
                    PASBook *book,
                    const char *vcard,
                    EContact **contact)
{
    PASBackendVCF *bvcf = PAS_BACKEND_VCF (backend);

    *contact = do_create(bvcf, vcard, TRUE);
    if (*contact) {
        return GNOME_Evolution_Addressbook_Success;
    }
    else {
        /* XXX need a different call status for this case, i
                   think */
        return GNOME_Evolution_Addressbook_ContactNotFound;
    }
}

static PASBackendSyncStatus
pas_backend_vcf_process_remove_contacts (PASBackendSync *backend,
                     PASBook    *book,
                     GList *id_list,
                     GList **ids)
{
    /* FIXME: make this handle bulk deletes like the file backend does */
    PASBackendVCF *bvcf = PAS_BACKEND_VCF (backend);
    char *id = id_list->data;
    gboolean success;

    g_mutex_lock (bvcf->priv->mutex);
    success = g_hash_table_remove (bvcf->priv->contacts, id);

    if (!success) {
        g_mutex_unlock (bvcf->priv->mutex);
        return GNOME_Evolution_Addressbook_ContactNotFound;
    }
    else {
        bvcf->priv->dirty = TRUE;
        if (!bvcf->priv->flush_timeout_tag)
            bvcf->priv->flush_timeout_tag = g_timeout_add (FILE_FLUSH_TIMEOUT,
                                       vcf_flush_file, bvcf);
        g_mutex_unlock (bvcf->priv->mutex);

        *ids = g_list_append (*ids, id);

        return GNOME_Evolution_Addressbook_Success;
    }
}

static PASBackendSyncStatus
pas_backend_vcf_process_modify_contact (PASBackendSync *backend,
                    PASBook *book,
                    const char *vcard,
                    EContact **contact)
{
    PASBackendVCF *bvcf = PAS_BACKEND_VCF (backend);
    char *old_id, *old_vcard_string;
    const char *id;
    gboolean success;

    /* create a new ecard from the request data */
    *contact = e_contact_new_from_vcard (vcard);
    id = e_contact_get_const (*contact, E_CONTACT_UID);

    g_mutex_lock (bvcf->priv->mutex);
    success = g_hash_table_lookup_extended (bvcf->priv->contacts, id, (gpointer)&old_id, (gpointer)&old_vcard_string);

    if (!success) {
        g_mutex_unlock (bvcf->priv->mutex);
        return GNOME_Evolution_Addressbook_ContactNotFound;
    }
    else {
        g_hash_table_insert (bvcf->priv->contacts, old_id, g_strdup (vcard));
        bvcf->priv->dirty = TRUE;
        if (!bvcf->priv->flush_timeout_tag)
            bvcf->priv->flush_timeout_tag = g_timeout_add (FILE_FLUSH_TIMEOUT,
                                       vcf_flush_file, bvcf);
        g_mutex_unlock (bvcf->priv->mutex);

        g_free (old_vcard_string);

        return GNOME_Evolution_Addressbook_Success;
    }
}

static PASBackendSyncStatus
pas_backend_vcf_process_get_contact (PASBackendSync *backend,
                     PASBook    *book,
                     const char *id,
                     char **vcard)
{
    PASBackendVCF *bvcf = PAS_BACKEND_VCF (backend);
    char *v;

    v = g_hash_table_lookup (bvcf->priv->contacts, id);

    if (v) {
        *vcard = g_strdup (v);
        return GNOME_Evolution_Addressbook_Success;
    } else {
        *vcard = g_strdup ("");
        return GNOME_Evolution_Addressbook_ContactNotFound;
    }
}


typedef struct {
    PASBackendVCF      *bvcf;
    gboolean            search_needed;
    PASBackendCardSExp *card_sexp;
    GList              *list;
} GetContactListClosure;

static void
foreach_get_contact_compare (char *id, char *vcard_string, GetContactListClosure *closure)
{
    if ((!closure->search_needed) || pas_backend_card_sexp_match_vcard  (closure->card_sexp, vcard_string)) {
        closure->list = g_list_append (closure->list, g_strdup (vcard_string));
    }
}

static PASBackendSyncStatus
pas_backend_vcf_process_get_contact_list (PASBackendSync *backend,
                       PASBook    *book,
                       const char *query,
                       GList **contacts)
{
    PASBackendVCF *bvcf = PAS_BACKEND_VCF (backend);
    const char *search = query;
    GetContactListClosure closure;

    closure.bvcf = bvcf;
    closure.search_needed = strcmp (search, "(contains \"x-evolution-any-field\" \"\")");
    closure.card_sexp = pas_backend_card_sexp_new (search);
    closure.list = NULL;

    g_hash_table_foreach (bvcf->priv->contacts, (GHFunc)foreach_get_contact_compare, &closure);

    g_object_unref (closure.card_sexp);

    *contacts = closure.list;
    return GNOME_Evolution_Addressbook_Success;
}

static void
pas_backend_vcf_start_book_view (PASBackend  *backend,
                 PASBookView *book_view)
{
    pas_backend_vcf_search (PAS_BACKEND_VCF (backend), book_view);
}

static void
pas_backend_vcf_stop_book_view (PASBackend  *backend,
                PASBookView *book_view)
{
    /* XXX nothing here yet, and there should be. */
}

static char *
pas_backend_vcf_extract_path_from_uri (const char *uri)
{
    g_assert (strncasecmp (uri, "vcf://", 6) == 0);

    return g_strdup (uri + 6);
}

static PASBackendSyncStatus
pas_backend_vcf_process_authenticate_user (PASBackendSync *backend,
                       PASBook    *book,
                       const char *user,
                       const char *passwd,
                       const char *auth_method)
{
    return GNOME_Evolution_Addressbook_Success;
}

static PASBackendSyncStatus
pas_backend_vcf_process_get_supported_fields (PASBackendSync *backend,
                          PASBook    *book,
                          GList **fields_out)
{
    GList *fields = NULL;
    int i;

    /* XXX we need a way to say "we support everything", since the
       vcf backend does */
    for (i = 0; i < E_CONTACT_FIELD_LAST; i ++)
        fields = g_list_append (fields, (char*)e_contact_field_name (i));       

    *fields_out = fields;
    return GNOME_Evolution_Addressbook_Success;
}

#include "ximian-vcard.h"

static GNOME_Evolution_Addressbook_CallStatus
pas_backend_vcf_load_uri (PASBackend             *backend,
              const char             *uri,
              gboolean                only_if_exists)
{
    PASBackendVCF *bvcf = PAS_BACKEND_VCF (backend);
    char           *dirname;
    gboolean        writable = FALSE;
    int fd;

    g_free(bvcf->priv->uri);
    bvcf->priv->uri = g_strdup (uri);

    dirname = pas_backend_vcf_extract_path_from_uri (uri);
    bvcf->priv->filename = g_build_filename (dirname, "addressbook.vcf", NULL);

    fd = open (bvcf->priv->filename, O_RDWR);

    bvcf->priv->contacts = g_hash_table_new_full (g_str_hash, g_str_equal,
                              g_free, g_free);

    if (fd != -1) {
        writable = TRUE;
    } else {
        fd = open (bvcf->priv->filename, O_RDONLY);

        if (fd == -1) {
            fd = open (bvcf->priv->filename, O_CREAT, 0666);

            if (fd != -1 && !only_if_exists) {
                EContact *contact;

                contact = do_create(bvcf, XIMIAN_VCARD, FALSE);
                save_file (bvcf);

                /* XXX check errors here */
                g_object_unref (contact);

                writable = TRUE;
            }
        }
    }

    if (fd == -1) {
        g_warning ("Failed to open addressbook at uri `%s'", uri);
        g_warning ("error == %s", strerror(errno));
        return GNOME_Evolution_Addressbook_OtherError;
    }

    load_file (bvcf, fd);

    pas_backend_set_is_loaded (backend, TRUE);
    pas_backend_set_is_writable (backend, writable);

    return GNOME_Evolution_Addressbook_Success;
}

static char *
pas_backend_vcf_get_static_capabilities (PASBackend *backend)
{
    return g_strdup("local,do-initial-query");
}

static GNOME_Evolution_Addressbook_CallStatus
pas_backend_vcf_cancel_operation (PASBackend *backend, PASBook *book)
{
    return GNOME_Evolution_Addressbook_CouldNotCancel;
}

static gboolean
pas_backend_vcf_construct (PASBackendVCF *backend)
{
    g_assert (backend != NULL);
    g_assert (PAS_IS_BACKEND_VCF (backend));

    if (! pas_backend_construct (PAS_BACKEND (backend)))
        return FALSE;

    return TRUE;
}

/**
 * pas_backend_vcf_new:
 */
PASBackend *
pas_backend_vcf_new (void)
{
    PASBackendVCF *backend;

    backend = g_object_new (PAS_TYPE_BACKEND_VCF, NULL);

    if (! pas_backend_vcf_construct (backend)) {
        g_object_unref (backend);

        return NULL;
    }

    return PAS_BACKEND (backend);
}

static void
pas_backend_vcf_dispose (GObject *object)
{
    PASBackendVCF *bvcf;

    bvcf = PAS_BACKEND_VCF (object);

    if (bvcf->priv) {

        g_mutex_lock (bvcf->priv->mutex);

        if (bvcf->priv->flush_timeout_tag) {
            g_source_remove (bvcf->priv->flush_timeout_tag);
            bvcf->priv->flush_timeout_tag = 0;
        }

        if (bvcf->priv->dirty)
            save_file (bvcf);

        g_hash_table_destroy (bvcf->priv->contacts);

        g_free (bvcf->priv->uri);
        g_free (bvcf->priv->filename);

        g_mutex_unlock (bvcf->priv->mutex);

        g_mutex_free (bvcf->priv->mutex);

        g_free (bvcf->priv);
        bvcf->priv = NULL;
    }

    G_OBJECT_CLASS (pas_backend_vcf_parent_class)->dispose (object);    
}

static void
pas_backend_vcf_class_init (PASBackendVCFClass *klass)
{
    GObjectClass    *object_class = G_OBJECT_CLASS (klass);
    PASBackendSyncClass *sync_class;
    PASBackendClass *backend_class;

    pas_backend_vcf_parent_class = g_type_class_peek_parent (klass);

    sync_class = PAS_BACKEND_SYNC_CLASS (klass);
    backend_class = PAS_BACKEND_CLASS (klass);

    /* Set the virtual methods. */
    backend_class->load_uri                = pas_backend_vcf_load_uri;
    backend_class->get_static_capabilities = pas_backend_vcf_get_static_capabilities;
    backend_class->start_book_view         = pas_backend_vcf_start_book_view;
    backend_class->stop_book_view          = pas_backend_vcf_stop_book_view;
    backend_class->cancel_operation        = pas_backend_vcf_cancel_operation;

    sync_class->create_contact_sync        = pas_backend_vcf_process_create_contact;
    sync_class->remove_contacts_sync       = pas_backend_vcf_process_remove_contacts;
    sync_class->modify_contact_sync        = pas_backend_vcf_process_modify_contact;
    sync_class->get_contact_sync           = pas_backend_vcf_process_get_contact;
    sync_class->get_contact_list_sync      = pas_backend_vcf_process_get_contact_list;
    sync_class->authenticate_user_sync     = pas_backend_vcf_process_authenticate_user;
    sync_class->get_supported_fields_sync  = pas_backend_vcf_process_get_supported_fields;

    object_class->dispose = pas_backend_vcf_dispose;
}

static void
pas_backend_vcf_init (PASBackendVCF *backend)
{
    PASBackendVCFPrivate *priv;

    priv                 = g_new0 (PASBackendVCFPrivate, 1);
    priv->uri            = NULL;
    priv->mutex = g_mutex_new();

    backend->priv = priv;
}

/**
 * pas_backend_vcf_get_type:
 */
GType
pas_backend_vcf_get_type (void)
{
    static GType type = 0;

    if (! type) {
        GTypeInfo info = {
            sizeof (PASBackendVCFClass),
            NULL, /* base_class_init */
            NULL, /* base_class_finalize */
            (GClassInitFunc)  pas_backend_vcf_class_init,
            NULL, /* class_finalize */
            NULL, /* class_data */
            sizeof (PASBackendVCF),
            0,    /* n_preallocs */
            (GInstanceInitFunc) pas_backend_vcf_init
        };

        type = g_type_register_static (PAS_TYPE_BACKEND_SYNC, "PASBackendVCF", &info, 0);
    }

    return type;
}