summaryrefslogtreecommitdiff
path: root/telepathy-logger/log-manager.c
blob: cbbfbbcc9188bdecc45694ab2b5276638edfe893 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
 * Copyright (C) 2003-2007 Imendio AB
 * Copyright (C) 2007-2010 Collabora Ltd.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Authors: Xavier Claessens <xclaesse@gmail.com>
 *          Cosimo Alfarano <cosimo.alfarano@collabora.co.uk>
 */

#include "config.h"
#include "log-manager.h"
#include "log-manager-internal.h"

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include <gio/gio.h>
#include <glib/gstdio.h>
#include <telepathy-glib/interfaces.h>
#include <telepathy-glib/util.h>

#include <telepathy-logger/conf-internal.h>
#include <telepathy-logger/entry.h>
#include <telepathy-logger/entry-internal.h>
#include <telepathy-logger/log-store-internal.h>
#include <telepathy-logger/log-store-xml-internal.h>
#include <telepathy-logger/log-store-sqlite-internal.h>

#define DEBUG_FLAG TPL_DEBUG_LOG_MANAGER
#include <telepathy-logger/datetime-internal.h>
#include <telepathy-logger/debug-internal.h>
#include <telepathy-logger/util-internal.h>

/**
 * SECTION:log-manager
 * @title: TplLogManager
 * @short_description: Fetch and search through logs
 *
 * The #TplLogManager object allows user to fetch logs and make searches.
 */

/**
 * TplLogManager:
 *
 * An object used to access logs
 */

/**
 * TplLogMessageFilter:
 * @message: the #TplEntry to filter
 * @user_data: user-supplied data
 *
 * Returns: %TRUE if @message should appear in the result
 */

/**
 * TPL_LOG_MANAGER_ERROR:
 *
 * The error domain for the #TplLogManager.
 */

typedef struct
{
  TplConf *conf;

  GList *stores;
  GList *writable_stores;
  GList *readable_stores;
} TplLogManagerPriv;


typedef void (*TplLogManagerFreeFunc) (gpointer *data);


typedef struct
{
  TpAccount *account;
  gchar *chat_id;
  gboolean is_chatroom;
  GDate *date;
  guint num_messages;
  TplLogMessageFilter filter;
  gchar *search_text;
  gpointer user_data;
  TplEntry *logentry;
} TplLogManagerChatInfo;


typedef struct
{
  TplLogManager *manager;
  TplLogManagerChatInfo *request;
  TplLogManagerFreeFunc request_free;
  GAsyncReadyCallback cb;
  gpointer user_data;
} TplLogManagerAsyncData;



G_DEFINE_TYPE (TplLogManager, tpl_log_manager, G_TYPE_OBJECT);

static TplLogManager *manager_singleton = NULL;

static void
log_manager_finalize (GObject *object)
{
  TplLogManagerPriv *priv;

  priv = TPL_LOG_MANAGER (object)->priv;

  g_object_unref (priv->conf);

  g_list_foreach (priv->stores, (GFunc) g_object_unref, NULL);
  g_list_free (priv->stores);
  /* no unref needed here, the only reference kept is in priv->stores */
  g_list_free (priv->writable_stores);
  g_list_free (priv->readable_stores);

  G_OBJECT_CLASS (tpl_log_manager_parent_class)->finalize (object);
}


/*
 * - Singleton LogManager constructor -
 * Initialises LogStores with LogStoreEmpathy instance
 */
static GObject *
log_manager_constructor (GType type, guint n_props,
    GObjectConstructParam *props)
{
  GObject *retval = NULL;

  if (manager_singleton)
    retval = g_object_ref (manager_singleton);
  else
    {
      retval = G_OBJECT_CLASS (tpl_log_manager_parent_class)->constructor (
          type, n_props, props);
      if (retval == NULL)
        return NULL;

      manager_singleton = TPL_LOG_MANAGER (retval);
      g_object_add_weak_pointer (retval, (gpointer *) &manager_singleton);
    }

  return retval;
}


static void
tpl_log_manager_class_init (TplLogManagerClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->constructor = log_manager_constructor;
  object_class->finalize = log_manager_finalize;

  g_type_class_add_private (object_class, sizeof (TplLogManagerPriv));
}

static TplLogStore *
add_log_store (TplLogManager *self,
    GType type,
    const char *name,
    gboolean readable,
    gboolean writable)
{
  TplLogStore *store;

  g_return_val_if_fail (g_type_is_a (type, TPL_TYPE_LOG_STORE), NULL);

  store = g_object_new (type,
      "name", name,
      "readable", readable,
      "writable", writable,
      NULL);

  if (store == NULL)
    CRITICAL ("Error creating %s (name=%s)", g_type_name (type), name);
  else if (!_tpl_log_manager_register_log_store (self, store))
    CRITICAL ("Failed to register store name=%s", name);

  if (store != NULL)
    /* drop the initial ref */
    g_object_unref (store);

  return store;
}

static void
_globally_enabled_changed (TplConf *conf,
    GParamSpec *pspec,
    gpointer user_data)
{
  DEBUG ("Logging has been globally %s",
      _tpl_conf_is_globally_enabled (conf) ? "enabled" : "disabled");
}

static void
tpl_log_manager_init (TplLogManager *self)
{
  TplLogStore *store;
  TplLogManagerPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
      TPL_TYPE_LOG_MANAGER, TplLogManagerPriv);

  self->priv = priv;

  DEBUG ("Initialising the Log Manager");

  priv->conf = _tpl_conf_dup ();

  g_signal_connect (priv->conf, "notify::globally-enabled",
      G_CALLBACK (_globally_enabled_changed), NULL);

  /* The TPL's default read-write logstore */
  add_log_store (self, TPL_TYPE_LOG_STORE_XML, "TpLogger", TRUE, TRUE);

  /* Load by default the Empathy's legacy 'past coversations' LogStore */
  store = add_log_store (self, TPL_TYPE_LOG_STORE_XML, "Empathy", TRUE, FALSE);
  if (store != NULL)
    g_object_set (store, "empathy-legacy", TRUE, NULL);

  /* Load the message counting cache */
  add_log_store (self, TPL_TYPE_LOG_STORE_SQLITE, "Sqlite", FALSE, TRUE);

  DEBUG ("Log Manager initialised");
}


/**
 * tpl_log_manager_dup_singleton
 *
 * Returns: a new reference on the log manager
 */
TplLogManager *
tpl_log_manager_dup_singleton (void)
{
  return g_object_new (TPL_TYPE_LOG_MANAGER, NULL);
}


/**
 * _tpl_log_manager_add_message
 * @manager: the log manager
 * @message: a TplEntry subclass's instance
 * @error: the memory location of GError, filled if an error occurs
 *
 * It stores @message, sending it to all the registered TplLogStore which have
 * #TplLogStore:writable set to %TRUE.
 * Every TplLogManager is guaranteed to have at least TplLogStore a readable
 * and a writable LogStore regitered.
 *
 * It applies for any registered TplLogStore with #TplLogstore:writable property
 * %TRUE
 *
 * Returns: %TRUE if the message has been successfully added, %FALSE otherwise.
 */
gboolean
_tpl_log_manager_add_message (TplLogManager *manager,
    TplEntry *message,
    GError **error)
{
  TplLogManagerPriv *priv;
  GList *l;
  gboolean retval = FALSE;

  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
  g_return_val_if_fail (TPL_IS_LOG_MANAGER (manager), FALSE);
  g_return_val_if_fail (TPL_IS_ENTRY (message), FALSE);

  priv = manager->priv;

  if (!_tpl_conf_is_globally_enabled (priv->conf))
    {
      /* ignore message, logging is globally disabled */
      return FALSE;
    }

  /* send the message to any writable log store */
  for (l = priv->writable_stores; l != NULL; l = g_list_next (l))
    {
      GError *loc_error = NULL;
      TplLogStore *store = l->data;
      gboolean result;

      result = _tpl_log_store_add_message (store, message, &loc_error);
      if (!result)
        {
          CRITICAL ("logstore name=%s: %s. "
              "Event may not be logged properly.",
              _tpl_log_store_get_name (store), loc_error->message);
          g_clear_error (&loc_error);
        }
      /* TRUE if at least one LogStore succeeds */
      retval = result || retval;
    }
  if (!retval)
    {
      CRITICAL ("Failed to write to all "
          "writable LogStores log-id %s.", _tpl_entry_get_log_id (message));
      g_set_error_literal (error, TPL_LOG_MANAGER_ERROR,
          TPL_LOG_MANAGER_ERROR_ADD_MESSAGE,
          "Not recoverable error occurred during log manager's "
          "add_message() execution");
    }
  return retval;
}


/**
 * _tpl_log_manager_register_log_store
 * @self: the log manager
 * @logstore: a TplLogStore interface implementation
 *
 * It registers @logstore into @manager, the log store has to be an
 * implementation of the TplLogStore interface.
 *
 * @logstore has to properly implement the add_message method if the
 * #TplLogStore:writable is set to %TRUE.
 *
 * @logstore has to properly implement all the search/query methods if the
 * #TplLogStore:readable is set to %TRUE.
 */
gboolean
_tpl_log_manager_register_log_store (TplLogManager *self,
    TplLogStore *logstore)
{
  TplLogManagerPriv *priv = self->priv;
  GList *l;
  gboolean found = FALSE;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (self), FALSE);
  g_return_val_if_fail (TPL_IS_LOG_STORE (logstore), FALSE);

  /* check that the logstore name is not already used */
  for (l = priv->stores; l != NULL; l = g_list_next (l))
    {
      TplLogStore *store = l->data;
      const gchar *name = _tpl_log_store_get_name (logstore);

      if (!tp_strdiff (name, _tpl_log_store_get_name (store)))
        {
          found = TRUE;
          break;
        }
    }
  if (found)
    {
      DEBUG ("name=%s: already registered", _tpl_log_store_get_name (logstore));
      return FALSE;
    }

  if (_tpl_log_store_is_readable (logstore))
    priv->readable_stores = g_list_prepend (priv->readable_stores, logstore);

  if (_tpl_log_store_is_writable (logstore))
    priv->writable_stores = g_list_prepend (priv->writable_stores, logstore);

  /* reference just once, writable/readable lists are kept in sync with the
   * general list and never written separatedly */
  priv->stores = g_list_prepend (priv->stores, g_object_ref (logstore));
  DEBUG ("LogStore name=%s registered", _tpl_log_store_get_name (logstore));

  return TRUE;
}

/**
 * tpl_log_manager_exists:
 * @manager: TplLogManager
 * @account: TpAccount
 * @chat_id: a non-NULL chat id
 * @chatroom: whether @chat_id is a chatroom or not
 *
 * Checks if @chat_id does exist for @account and
 * - is a chatroom, if @chatroom is %TRUE
 * - is not a chatroom, if @chatroom is %FALSE
 *
 * It applies for any registered TplLogStore with the #TplLogStore:readable
 * property %TRUE.

 * Returns: %TRUE if @chat_id exists, %FALSE otherwise
 */
gboolean
tpl_log_manager_exists (TplLogManager *manager,
    TpAccount *account,
    const gchar *chat_id,
    gboolean chatroom)
{
  GList *l;
  TplLogManagerPriv *priv;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (manager), FALSE);
  g_return_val_if_fail (chat_id != NULL, FALSE);

  priv = manager->priv;

  for (l = priv->stores; l != NULL; l = g_list_next (l))
    {
      if (_tpl_log_store_exists (TPL_LOG_STORE (l->data),
            account, chat_id, chatroom))
        return TRUE;
    }

  return FALSE;
}


/**
 * _tpl_log_manager_get_dates:
 * @manager: a TplLogManager
 * @account: a TpAccount
 * @chat_id: a non-NULL chat identifier
 * @chatroom: whather if the request is related to a chatroom or not.
 *
 * Retrieves a list of #GDate corresponding to each day
 * at least a message was sent to or received from @chat_id.
 * @chat_id may be the id of a buddy or a chatroom, depending on the value of
 * @chatroom.
 *
 * It applies for any registered TplLogStore with the #TplLogStore:readable
 * property %TRUE.
 *
 * Returns: a GList of (GDate *), to be freed using something like
 * g_list_foreach (lst, g_date_free, NULL);
 * g_list_free (lst);
 */
GList *
_tpl_log_manager_get_dates (TplLogManager *manager,
    TpAccount *account,
    const gchar *chat_id,
    gboolean chatroom)
{
  GList *l, *out = NULL;
  TplLogManagerPriv *priv;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (manager), NULL);
  g_return_val_if_fail (chat_id != NULL, NULL);

  priv = manager->priv;

  for (l = priv->readable_stores; l != NULL; l = g_list_next (l))
    {
      TplLogStore *store = TPL_LOG_STORE (l->data);
      GList *new;

      /* Insert dates of each store in the out list. Keep the out list sorted
       * and avoid to insert dups. */
      new = _tpl_log_store_get_dates (store, account, chat_id, chatroom);
      while (new)
        {
          if (g_list_find_custom (out, new->data,
                (GCompareFunc) g_date_compare))
            g_date_free (new->data);
          else
            out =
              g_list_insert_sorted (out, new->data,
                  (GCompareFunc) g_date_compare);

          new = g_list_delete_link (new, new);
        }
    }

  return out;
}


GList *
_tpl_log_manager_get_messages_for_date (TplLogManager *manager,
    TpAccount *account,
    const gchar *chat_id,
    gboolean chatroom,
    const GDate *date)
{
  GList *l, *out = NULL;
  TplLogManagerPriv *priv;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (manager), NULL);
  g_return_val_if_fail (chat_id != NULL, NULL);

  priv = manager->priv;

  for (l = priv->readable_stores; l != NULL; l = g_list_next (l))
    {
      TplLogStore *store = TPL_LOG_STORE (l->data);

      out = g_list_concat (out, _tpl_log_store_get_messages_for_date (store,
          account, chat_id, chatroom, date));
    }

  return out;
}


static gint
log_manager_message_date_cmp (gconstpointer a,
    gconstpointer b)
{
  TplEntry *one = (TplEntry *) a;
  TplEntry *two = (TplEntry *) b;
  gint64 one_time, two_time;

  g_assert (TPL_IS_ENTRY (one));
  g_assert (TPL_IS_ENTRY (two));

  one_time = tpl_entry_get_timestamp (one);
  two_time = tpl_entry_get_timestamp (two);

  /* return -1, o or 1 depending on message1 is newer, the same or older than
   * message2 */
  return CLAMP (one_time - two_time, -1, 1);
}


GList *
_tpl_log_manager_get_filtered_messages (TplLogManager *manager,
    TpAccount *account,
    const gchar *chat_id,
    gboolean chatroom,
    guint num_messages,
    TplLogMessageFilter filter,
    gpointer user_data)
{
  TplLogManagerPriv *priv;
  GList *out = NULL;
  GList *l;
  guint i = 0;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (manager), NULL);
  g_return_val_if_fail (!TPL_STR_EMPTY (chat_id), NULL);

  priv = manager->priv;

  /* Get num_messages from each log store and keep only the
   * newest ones in the out list. Keep that list sorted: Older first. */
  for (l = priv->readable_stores; l != NULL; l = g_list_next (l))
    {
      TplLogStore *store = TPL_LOG_STORE (l->data);
      GList *new;

      new = _tpl_log_store_get_filtered_messages (store, account, chat_id,
          chatroom, num_messages, filter, user_data);
      while (new != NULL)
        {
          if (i < num_messages)
            {
              /* We have less message than needed so far. Keep this message */
              out = g_list_insert_sorted (out, new->data,
                  (GCompareFunc) log_manager_message_date_cmp);
              i++;
            }
          else if (log_manager_message_date_cmp (new->data, out->data) > 0)
            {
              /* This message is newer than the oldest message we have in out
               * list. Remove the head of out list and insert this message */
              g_object_unref (out->data);
              out = g_list_delete_link (out, out);
              out = g_list_insert_sorted (out, new->data,
                  (GCompareFunc) log_manager_message_date_cmp);
            }
          else
            {
              /* This message is older than the oldest message we have in out
               * list. Drop it. */
              g_object_unref (new->data);
            }

          new = g_list_delete_link (new, new);
        }
    }

  return out;
}


/**
 * _tpl_log_manager_search_hit_compare:
 * @a: a TplLogSerachHit
 * @b: a TplLogSerachHit
 *
 * Compare @a and @b, returning an ordered relation between the two.
 * Acts similar to the strcmp family, with the difference that since
 * TplLogSerachHit is not a plain string, but a struct, the order relation
 * will be a coposition of:
 * - the order relation between @a.chat_it and @b.chat_id
 * - the order relation between @a.chatroom and @b.chatroom, being
 *   chatroom = %FALSE > chatroom = %TRUE (meaning: a 1-1 message is greater
 *   than a chatroom one).
 *
 * Returns: -1 if a > b, 1 if a < b or 0 is a == b */
gint
_tpl_log_manager_search_hit_compare (TplLogSearchHit *a,
    TplLogSearchHit *b)
{
  /* if chat_ids differ, just return their sorting return value */
  gint ret;

  g_return_val_if_fail (a != NULL && a->chat_id != NULL, 1);
  g_return_val_if_fail (b != NULL && b->chat_id != NULL, -1);

  ret = g_strcmp0 (a->chat_id, b->chat_id);

  if (ret == 0)
    {
      /* if chat_id are the same, a further check needed: chat_id may be equal
       * but one can refer to a chatroom and the other not.
       * Definition: chatroom < not_chatroom */
      if (a->is_chatroom != b->is_chatroom)
        {
          if (a->is_chatroom)
            ret = 1; /* b > a */
          else
            ret = -1; /* a > b */
        }
      else
        ret = 0; /* a = b */
    }
  /* else original strcmp result is returned */

  return ret;
}


/**
 * _tpl_log_manager_get_chats
 * @manager: the log manager
 * @account: a TpAccount the query will return data related to
 *
 * It queries the readable TplLogStores in @manager for all the buddies the
 * log store has at least a conversation stored originated using @account.
 *
 * Returns: a list of pointer to TplLogSearchHit, having chat_id and
 * is_chatroom fields filled. the result needs to be freed after use using
 * _tpl_log_manager_search_hit_free
 */
GList *
_tpl_log_manager_get_chats (TplLogManager *manager,
    TpAccount *account)
{
  GList *l, *out = NULL;
  TplLogManagerPriv *priv;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (manager), NULL);
  g_return_val_if_fail (TP_IS_ACCOUNT (account), NULL);

  priv = manager->priv;

  for (l = priv->readable_stores; l != NULL; l = g_list_next (l))
    {
      TplLogStore *store = TPL_LOG_STORE (l->data);
      GList *in;

      /* merge the lists avoiding duplicates */
      for (in = _tpl_log_store_get_chats (store, account);
          in != NULL;
          in = g_list_next (in))
        {
          TplLogSearchHit *hit = in->data;

          if (g_list_find_custom (out, hit,
                (GCompareFunc) _tpl_log_manager_search_hit_compare) == NULL)
            {
              /* add data if not already present */
              out = g_list_prepend (out, hit);
            }
          else
            /* free hit if already present in out */
            _tpl_log_manager_search_hit_free (hit);
        }
      g_list_free (in);
    }

  return out;
}


GList *
_tpl_log_manager_search_in_identifier_chats_new (TplLogManager *manager,
    TpAccount *account,
    gchar const *identifier,
    const gchar *text)
{
  GList *l, *out = NULL;
  TplLogManagerPriv *priv;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (manager), NULL);
  g_return_val_if_fail (TP_IS_ACCOUNT (account), NULL);
  g_return_val_if_fail (!TPL_STR_EMPTY (identifier), NULL);
  g_return_val_if_fail (!TPL_STR_EMPTY (text), NULL);

  priv = manager->priv;

  for (l = priv->readable_stores; l != NULL; l = g_list_next (l))
    {
      TplLogStore *store = TPL_LOG_STORE (l->data);

      out = g_list_concat (out,
          _tpl_log_store_search_in_identifier_chats_new
          (store, account, identifier, text));
    }

  return out;
}


GList *
_tpl_log_manager_search (TplLogManager *manager,
    const gchar *text)
{
  GList *l, *out = NULL;
  TplLogManagerPriv *priv;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (manager), NULL);
  g_return_val_if_fail (!TPL_STR_EMPTY (text), NULL);

  priv = manager->priv;

  for (l = priv->readable_stores; l != NULL; l = g_list_next (l))
    {
      TplLogStore *store = TPL_LOG_STORE (l->data);

      out = g_list_concat (out, _tpl_log_store_search_new (store, text));
    }

  return out;
}

TplLogSearchHit *
_tpl_log_manager_search_hit_new (TpAccount *account,
    const gchar *chat_id,
    gboolean is_chatroom,
    const gchar *filename,
    GDate *date)
{
  TplLogSearchHit *hit = g_slice_new0 (TplLogSearchHit);

  g_assert (chat_id != NULL);

  if (account != NULL)
    hit->account = g_object_ref (account);

  hit->chat_id = g_strdup (chat_id);
  hit->is_chatroom = is_chatroom;

  if (filename != NULL)
    hit->filename = g_strdup (filename);

  if (date != NULL)
    hit->date = g_date_new_dmy (g_date_get_day (date), g_date_get_month (date),
        g_date_get_year (date));

  return hit;
}

void
_tpl_log_manager_search_hit_free (TplLogSearchHit *hit)
{
  if (hit->account != NULL)
    g_object_unref (hit->account);

  if (hit->date != NULL)
    g_date_free (hit->date);

  g_free (hit->filename);
  g_free (hit->chat_id);

  g_slice_free (TplLogSearchHit, hit);
}

/**
 * tpl_log_manager_search_free:
 * @hits: a #GList of #TplLogSearchHit
 *
 * Free @hits and its content.
 */
void
tpl_log_manager_search_free (GList *hits)
{
  GList *l;

  for (l = hits; l != NULL; l = g_list_next (l))
    {
      _tpl_log_manager_search_hit_free (l->data);
    }

  g_list_free (hits);
}

/* start of Async definitions */
static TplLogManagerAsyncData *
tpl_log_manager_async_data_new (void)
{
  return g_slice_new0 (TplLogManagerAsyncData);
}


static void
tpl_log_manager_async_data_free (TplLogManagerAsyncData *data)
{
  if (data->manager != NULL)
    g_object_unref (data->manager);
  data->request_free ((gpointer) data->request);
  g_slice_free (TplLogManagerAsyncData, data);
}


static TplLogManagerChatInfo *
tpl_log_manager_chat_info_new (void)
{
  return g_slice_new0 (TplLogManagerChatInfo);
}


static void
tpl_log_manager_chat_info_free (TplLogManagerChatInfo *data)
{
  if (data->account != NULL)
    g_object_unref (data->account);
  if (data->chat_id != NULL)
    g_free (data->chat_id);
  if (data->date != NULL)
    g_date_free (data->date);
  g_slice_free (TplLogManagerChatInfo, data);
}


static void
_tpl_log_manager_async_operation_cb (GObject *source_object,
    GAsyncResult *result,
    gpointer user_data)
{
  TplLogManagerAsyncData *async_data = (TplLogManagerAsyncData *) user_data;

  if (async_data->cb)
    async_data->cb (G_OBJECT (async_data->manager), result,
        async_data->user_data);

  tpl_log_manager_async_data_free (async_data);
}
/* end of Async common function */


gboolean
_tpl_log_manager_add_message_finish (TplLogManager *self,
    GAsyncResult *result,
    GError **error)
{
  GSimpleAsyncResult *simple;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (self), FALSE);
  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
  g_return_val_if_fail (g_simple_async_result_is_valid (result,
        G_OBJECT (self), _tpl_log_manager_add_message_async), FALSE);

  simple = G_SIMPLE_ASYNC_RESULT (result);

  if (g_simple_async_result_propagate_error (simple, error))
    return FALSE;

  return TRUE;
}


static void
_add_message_async_thread (GSimpleAsyncResult *simple,
    GObject *object,
    GCancellable *cancellable)
{
  TplLogManagerAsyncData *async_data;
  TplLogManagerChatInfo *chat_info;
  GError *error = NULL;

  async_data = g_async_result_get_user_data (G_ASYNC_RESULT (simple));
  chat_info = async_data->request;

  _tpl_log_manager_add_message (async_data->manager, chat_info->logentry,
      &error);
  if (error != NULL)
    {
      DEBUG ("synchronous operation error: %s", error->message);
      g_simple_async_result_set_from_error (simple, error);
      g_error_free (error);
    }
}

void
_tpl_log_manager_add_message_async (TplLogManager *manager,
    TplEntry *message,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  TplLogManagerChatInfo *chat_info = tpl_log_manager_chat_info_new ();
  TplLogManagerAsyncData *async_data = tpl_log_manager_async_data_new ();
  GSimpleAsyncResult *simple;

  g_return_if_fail (TPL_IS_LOG_MANAGER (manager));
  g_return_if_fail (TPL_IS_ENTRY (message));

  chat_info->logentry = g_object_ref (message);

  async_data->manager = g_object_ref (manager);
  async_data->request = chat_info;
  async_data->request_free =
    (TplLogManagerFreeFunc) tpl_log_manager_chat_info_free;
  async_data->cb = callback;
  async_data->user_data = user_data;

  simple = g_simple_async_result_new (G_OBJECT (manager),
      _tpl_log_manager_async_operation_cb, async_data,
      _tpl_log_manager_add_message_async);

  g_simple_async_result_run_in_thread (simple, _add_message_async_thread, 0,
      NULL);

  g_object_unref (simple);
}

/* There is no g_date_copy() */
static GDate *
copy_date (const GDate *date)
{
  return g_date_new_julian (g_date_get_julian (date));
}

/**
 * tpl_log_manager_get_dates_finish:
 * @self: a #TplLogManager
 * @result: a #GAsyncResult
 * @dates: a pointer to a #GList used to return the list of #GDate
 * @error: a #GError to fill
 *
 * Returns: #TRUE if the operation was successful, otherwise #FALSE
 */
gboolean
tpl_log_manager_get_dates_finish (TplLogManager *self,
    GAsyncResult *result,
    GList **dates,
    GError **error)
{
  GSimpleAsyncResult *simple;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (self), FALSE);
  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
  g_return_val_if_fail (g_simple_async_result_is_valid (result,
        G_OBJECT (self), tpl_log_manager_get_dates_async), FALSE);

  simple = G_SIMPLE_ASYNC_RESULT (result);

  if (g_simple_async_result_propagate_error (simple, error))
    return FALSE;

  if (dates != NULL)
    *dates = g_simple_async_result_get_op_res_gpointer (simple);

  return TRUE;
}

static void
_get_dates_async_result_free (gpointer data)
{
  GList *lst = data; /* list of (GDate *) */
  g_return_if_fail (data != NULL);

  g_list_foreach (lst, (GFunc) g_date_free, NULL);
  g_list_free (lst);
}


static void
_get_dates_async_thread (GSimpleAsyncResult *simple,
    GObject *object,
    GCancellable *cancellable)
{
  TplLogManagerAsyncData *async_data;
  TplLogManagerChatInfo *chat_info;
  GList *lst = NULL;

  async_data = g_async_result_get_user_data (G_ASYNC_RESULT (simple));
  chat_info = async_data->request;

  lst = _tpl_log_manager_get_dates (async_data->manager,
      chat_info->account, chat_info->chat_id,
      chat_info->is_chatroom);

  g_simple_async_result_set_op_res_gpointer (simple, lst,
      _get_dates_async_result_free);
}

/**
 * tpl_log_manager_get_dates_async:
 * @manager: a #TplLogManager
 * @account: a #TpAccount
 * @chat_id: the chat identifier (can't be %NULL)
 * @is_chatroom: whather if the request is related to a chatroom or not.
 * @callback: a callback to call when the request is satisfied
 * @user_data: data to pass to @callback
 *
 * Retrieves a list of #GDate corresponding to each day
 * at least a message was sent to or received from @chat_id.
 * @chat_id may be the id of a buddy or a chatroom, depending on the value of
 * @is_chatroom.
 *
 * It applies for any registered TplLogStore with the #TplLogStore:readable
 * property %TRUE.
 */
void
tpl_log_manager_get_dates_async (TplLogManager *manager,
    TpAccount *account,
    const gchar *chat_id,
    gboolean is_chatroom,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  TplLogManagerChatInfo *chat_info = tpl_log_manager_chat_info_new ();
  TplLogManagerAsyncData *async_data = tpl_log_manager_async_data_new ();
  GSimpleAsyncResult *simple;

  g_return_if_fail (TPL_IS_LOG_MANAGER (manager));
  g_return_if_fail (TP_IS_ACCOUNT (account));
  g_return_if_fail (!TPL_STR_EMPTY (chat_id));

  chat_info->account = g_object_ref (account);
  chat_info->chat_id = g_strdup (chat_id);
  chat_info->is_chatroom = is_chatroom;

  async_data->manager = g_object_ref (manager);
  async_data->request = chat_info;
  async_data->request_free =
    (TplLogManagerFreeFunc) tpl_log_manager_chat_info_free;
  async_data->cb = callback;
  async_data->user_data = user_data;

  simple = g_simple_async_result_new (G_OBJECT (manager),
      _tpl_log_manager_async_operation_cb, async_data,
      tpl_log_manager_get_dates_async);

  g_simple_async_result_run_in_thread (simple, _get_dates_async_thread, 0,
      NULL);

  g_object_unref (simple);
}

/**
 * tpl_log_manager_get_messages_for_date_finish
 * @self: a #TplLogManager
 * @result: a #GAsyncResult
 * @messages: a pointer to a #GList used to return the list of #GDate
 * @error: a #GError to fill
 *
 * Returns: #TRUE if the operation was successful, otherwise #FALSE
 */
gboolean
tpl_log_manager_get_messages_for_date_finish (TplLogManager *self,
    GAsyncResult *result,
    GList **messages,
    GError **error)
{
  GSimpleAsyncResult *simple;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (self), FALSE);
  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
  g_return_val_if_fail (g_simple_async_result_is_valid (result,
        G_OBJECT (self), tpl_log_manager_get_messages_for_date_async), FALSE);

  simple = G_SIMPLE_ASYNC_RESULT (result);

  if (g_simple_async_result_propagate_error (simple, error))
    return FALSE;

  if (messages != NULL)
    *messages = g_simple_async_result_get_op_res_gpointer (simple);

  return TRUE;
}


static void
_get_messages_for_date_async_result_free (gpointer data)
{
  GList *lst = data; /* list of TPL_ENTRY */
  g_return_if_fail (data != NULL);

  g_list_foreach (lst, (GFunc) g_object_unref, NULL);
  g_list_free (lst);
}


static void
_get_messages_for_date_async_thread (GSimpleAsyncResult *simple,
    GObject *object,
    GCancellable *cancellable)
{
  TplLogManagerAsyncData *async_data;
  TplLogManagerChatInfo *chat_info;
  GList *lst;

  async_data = g_async_result_get_user_data (G_ASYNC_RESULT (simple));
  chat_info = async_data->request;

  lst = _tpl_log_manager_get_messages_for_date (async_data->manager,
      chat_info->account,
      chat_info->chat_id,
      chat_info->is_chatroom,
      chat_info->date);

  g_simple_async_result_set_op_res_gpointer (simple, lst,
      _get_messages_for_date_async_result_free);
}

/**
 * tpl_log_manager_get_messages_for_date_async
 * @manager: a #TplLogManager
 * @account: a #TpAccount
 * @chat_id: the chat identifier (can't be %NULL)
 * @is_chatroom: %TRUE if the request is related to a chatroom
 * @date: a #GDate
 * @callback: a callback to call when the request is satisfied
 * @user_data: data to pass to @callback
 *
 * Retrieve a list of #TplEntry exchanged at @date with @chat_id.
 */
void
tpl_log_manager_get_messages_for_date_async (TplLogManager *manager,
    TpAccount *account,
    const gchar *chat_id,
    gboolean is_chatroom,
    const GDate *date,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  TplLogManagerChatInfo *chat_info = tpl_log_manager_chat_info_new ();
  TplLogManagerAsyncData *async_data = tpl_log_manager_async_data_new ();
  GSimpleAsyncResult *simple;

  g_return_if_fail (TPL_IS_LOG_MANAGER (manager));
  g_return_if_fail (TP_IS_ACCOUNT (account));
  g_return_if_fail (!TPL_STR_EMPTY (chat_id));
  g_return_if_fail (date != NULL);

  chat_info->account = g_object_ref (account);
  chat_info->chat_id = g_strdup (chat_id);
  chat_info->is_chatroom = is_chatroom;
  chat_info->date = copy_date (date);

  async_data->manager = g_object_ref (manager);
  async_data->request = chat_info;
  async_data->request_free =
    (TplLogManagerFreeFunc) tpl_log_manager_chat_info_free;
  async_data->cb = callback;
  async_data->user_data = user_data;

  simple = g_simple_async_result_new (G_OBJECT (manager),
      _tpl_log_manager_async_operation_cb, async_data,
      tpl_log_manager_get_messages_for_date_async);

  g_simple_async_result_run_in_thread (simple,
      _get_messages_for_date_async_thread, 0, NULL);

  g_object_unref (simple);
}

/**
 * tpl_log_manager_get_filtered_messages_finish:
 * @self: a #TplLogManager
 * @result: a #GAsyncResult
 * @messages: a pointer to a #GList used to return the list #TplEntry
 * @error: a #GError to fill
 *
 * Returns: #TRUE if the operation was successful, otherwise #FALSE
 */
gboolean
tpl_log_manager_get_filtered_messages_finish (TplLogManager *self,
    GAsyncResult *result,
    GList **messages,
    GError **error)
{
  GSimpleAsyncResult *simple;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (self), FALSE);
  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
  g_return_val_if_fail (g_simple_async_result_is_valid (result,
        G_OBJECT (self), tpl_log_manager_get_filtered_messages_async), FALSE);

  simple = G_SIMPLE_ASYNC_RESULT (result);

  if (g_simple_async_result_propagate_error (simple, error))
    return FALSE;

  if (messages != NULL)
    *messages = g_simple_async_result_get_op_res_gpointer (simple);

  return TRUE;
}


static void
_get_filtered_messages_async_result_free (gpointer data)
{
  GList *lst = data; /* list of TPL_ENTRY */
  g_return_if_fail (data != NULL);

  g_list_foreach (lst, (GFunc) g_object_unref, NULL);
  g_list_free (lst);
}

static void
_get_filtered_messages_async_thread (GSimpleAsyncResult *simple,
    GObject *object,
    GCancellable *cancellable)
{
  TplLogManagerAsyncData *async_data;
  TplLogManagerChatInfo *chat_info;
  GList *lst;

  async_data = g_async_result_get_user_data (G_ASYNC_RESULT (simple));
  chat_info = async_data->request;

  lst = _tpl_log_manager_get_filtered_messages (async_data->manager,
      chat_info->account, chat_info->chat_id, chat_info->is_chatroom,
      chat_info->num_messages, chat_info->filter, chat_info->user_data);

  g_simple_async_result_set_op_res_gpointer (simple, lst,
      _get_filtered_messages_async_result_free);
}

/**
 * tpl_log_manager_get_filtered_messages_async:
 * @manager: a #TplLogManager
 * @account: a #TpAccount
 * @chat_id: the chat identifier (can't be %NULL)
 * @is_chatroom: %TRUE if the request is related to a chatroom
 * @num_messages: number of maximum messages to fetch
 * @filter: an optionnal filter function
 * @filter_user_data: user data to pass to @filter
 * @callback: a callback to call when the request is satisfied
 * @user_data: data to pass to @callback
 *
 * Retrieve the @num_messages most recent messages exchanged with @chat_id.
 */
void
tpl_log_manager_get_filtered_messages_async (TplLogManager *manager,
    TpAccount *account,
    const gchar *chat_id,
    gboolean is_chatroom,
    guint num_messages,
    TplLogMessageFilter filter,
    gpointer filter_user_data,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  TplLogManagerChatInfo *chat_info = tpl_log_manager_chat_info_new ();
  TplLogManagerAsyncData *async_data = tpl_log_manager_async_data_new ();
  GSimpleAsyncResult *simple;

  g_return_if_fail (TPL_IS_LOG_MANAGER (manager));
  g_return_if_fail (TP_IS_ACCOUNT (account));
  g_return_if_fail (!TPL_STR_EMPTY (chat_id));
  g_return_if_fail (num_messages > 0);

  chat_info->account = g_object_ref (account);
  chat_info->chat_id = g_strdup (chat_id);
  chat_info->is_chatroom = is_chatroom;
  chat_info->num_messages = num_messages;
  chat_info->filter = filter;
  chat_info->user_data = filter_user_data;

  async_data->manager = g_object_ref (manager);
  async_data->request = chat_info;
  async_data->request_free =
    (TplLogManagerFreeFunc) tpl_log_manager_chat_info_free;
  async_data->cb = callback;
  async_data->user_data = user_data;

  simple = g_simple_async_result_new (G_OBJECT (manager),
      _tpl_log_manager_async_operation_cb, async_data,
      tpl_log_manager_get_filtered_messages_async);

  g_simple_async_result_run_in_thread (simple,
      _get_filtered_messages_async_thread, 0, NULL);

  g_object_unref (simple);
}

/**
 * tpl_log_manager_get_chats_finish:
 * @self: a #TplLogManager
 * @result: a #GAsyncResult
 * @chats: a pointer to a #GList used to return the list of chats
 * @error: a #GError to fill
 *
 * Returns: #TRUE if the operation was successful, otherwise #FALSE
 */
gboolean
tpl_log_manager_get_chats_finish (TplLogManager *self,
    GAsyncResult *result,
    GList **chats,
    GError **error)
{
  GSimpleAsyncResult *simple;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (self), FALSE);
  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
  g_return_val_if_fail (g_simple_async_result_is_valid (result,
        G_OBJECT (self), tpl_log_manager_get_chats_async), FALSE);

  simple = G_SIMPLE_ASYNC_RESULT (result);

  if (g_simple_async_result_propagate_error (simple, error))
    return FALSE;

  if (chats != NULL)
    *chats = g_simple_async_result_get_op_res_gpointer (simple);

  return TRUE;
}

static void
_get_chats_async_result_free (gpointer data)
{
  GList *lst = data; /* list of (gchar *) */
  g_return_if_fail (data != NULL);

  g_list_foreach (lst, (GFunc) g_free, NULL);
  g_list_free (lst);
}


static void
_get_chats_async_thread (GSimpleAsyncResult *simple,
    GObject *object,
    GCancellable *cancellable)
{
  TplLogManagerAsyncData *async_data;
  TplLogManagerChatInfo *chat_info;
  GList *lst;

  async_data = g_async_result_get_user_data (G_ASYNC_RESULT (simple));
  chat_info = async_data->request;

  lst = _tpl_log_manager_get_chats (async_data->manager, chat_info->account);

  g_simple_async_result_set_op_res_gpointer (simple, lst,
      _get_chats_async_result_free);
}

/**
 * tpl_log_manager_get_chats_async:
 * @self: a #TplLogManager
 * @account: a #TpAccount
 * @callback: a callback to call when the request is satisfied
 * @user_data: data to pass to @callback
 *
 * Start a query looking for all the conversations on @account.
 */
void
tpl_log_manager_get_chats_async (TplLogManager *self,
    TpAccount *account,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  TplLogManagerChatInfo *chat_info = tpl_log_manager_chat_info_new ();
  TplLogManagerAsyncData *async_data = tpl_log_manager_async_data_new ();
  GSimpleAsyncResult *simple;

  g_return_if_fail (TPL_IS_LOG_MANAGER (self));
  g_return_if_fail (TP_IS_ACCOUNT (account));

  chat_info->account = g_object_ref (account);

  async_data->manager = g_object_ref (self);
  async_data->request = chat_info;
  async_data->request_free =
    (TplLogManagerFreeFunc) tpl_log_manager_chat_info_free;
  async_data->cb = callback;
  async_data->user_data = user_data;

  simple = g_simple_async_result_new (G_OBJECT (self),
      _tpl_log_manager_async_operation_cb, async_data,
      tpl_log_manager_get_chats_async);

  g_simple_async_result_run_in_thread (simple, _get_chats_async_thread, 0,
      NULL);

  g_object_unref (simple);
}

gboolean
_tpl_log_manager_search_in_identifier_chats_new_finish (TplLogManager *self,
    GAsyncResult *result,
    GList **chats,
    GError **error)
{
  GSimpleAsyncResult *simple;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (self), FALSE);
  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
  g_return_val_if_fail (g_simple_async_result_is_valid (result,
        G_OBJECT (self),
        _tpl_log_manager_search_in_identifier_chats_new_async),
      FALSE);

  simple = G_SIMPLE_ASYNC_RESULT (result);

  if (g_simple_async_result_propagate_error (simple, error))
    return FALSE;

  if (chats != NULL)
    *chats = g_simple_async_result_get_op_res_gpointer (simple);

  return TRUE;
}

static void
_search_in_identifier_chats_new_async_result_free (gpointer data)
{
  GList *lst = data; /* list of TplSearchHit */
  g_return_if_fail (data != NULL);

  g_list_foreach (lst, (GFunc) _tpl_log_manager_search_hit_free, NULL);
  g_list_free (lst);
}


static void
_search_in_identifier_chats_new_async_thread (GSimpleAsyncResult *simple,
    GObject *object,
    GCancellable *cancellable)
{
  TplLogManagerAsyncData *async_data;
  TplLogManagerChatInfo *chat_info;
  GList *lst;

  async_data = g_async_result_get_user_data (G_ASYNC_RESULT (simple));
  chat_info = async_data->request;

  lst = _tpl_log_manager_search_in_identifier_chats_new (async_data->manager,
      chat_info->account, chat_info->chat_id, chat_info->search_text);

  g_simple_async_result_set_op_res_gpointer (simple, lst,
      _search_in_identifier_chats_new_async_result_free);
}


void
_tpl_log_manager_search_in_identifier_chats_new_async (TplLogManager *manager,
    TpAccount *account,
    gchar const *identifier,
    const gchar *text,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  TplLogManagerChatInfo *chat_info = tpl_log_manager_chat_info_new ();
  TplLogManagerAsyncData *async_data = tpl_log_manager_async_data_new ();
  GSimpleAsyncResult *simple;

  g_return_if_fail (TPL_IS_LOG_MANAGER (manager));
  g_return_if_fail (TP_IS_ACCOUNT (account));

  chat_info->account = g_object_ref (account);
  chat_info->chat_id = g_strdup (identifier);
  chat_info->search_text = g_strdup (text);

  async_data->manager = g_object_ref (manager);
  async_data->request = chat_info;
  async_data->request_free =
    (TplLogManagerFreeFunc) tpl_log_manager_chat_info_free;
  async_data->cb = callback;
  async_data->user_data = user_data;

  simple = g_simple_async_result_new (G_OBJECT (manager),
      _tpl_log_manager_async_operation_cb, async_data,
      _tpl_log_manager_search_in_identifier_chats_new_async);

  g_simple_async_result_run_in_thread (simple,
      _search_in_identifier_chats_new_async_thread, 0, NULL);

  g_object_unref (simple);
}

/**
 * tpl_log_manager_search_finish:
 * @self: a #TplLogManager
 * @result: a #GAsyncResult
 * @chats: a pointer to a #GList used to return the list of #TplLogSearchHit
 * @error: a #GError to fill
 *
 * Returns: #TRUE if the operation was successful, otherwise #FALSE
 */
gboolean
tpl_log_manager_search_finish (TplLogManager *self,
    GAsyncResult *result,
    GList **chats,
    GError **error)
{
  GSimpleAsyncResult *simple;

  g_return_val_if_fail (TPL_IS_LOG_MANAGER (self), FALSE);
  g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);
  g_return_val_if_fail (g_simple_async_result_is_valid (result,
        G_OBJECT (self), tpl_log_manager_search_async), FALSE);

  simple = G_SIMPLE_ASYNC_RESULT (result);

  if (g_simple_async_result_propagate_error (simple, error))
    return FALSE;

  if (chats != NULL)
    *chats = g_simple_async_result_get_op_res_gpointer (simple);

  return TRUE;
}

static void
_search_new_async_result_free (gpointer data)
{
  GList *lst = data; /* list of TplSearchHit */
  g_return_if_fail (data != NULL);

  g_list_foreach (lst, (GFunc) _tpl_log_manager_search_hit_free, NULL);
  g_list_free (lst);
}


static void
_search_async_thread (GSimpleAsyncResult *simple,
    GObject *object,
    GCancellable *cancellable)
{
  TplLogManagerAsyncData *async_data;
  TplLogManagerChatInfo *chat_info;
  GList *lst;

  async_data = g_async_result_get_user_data (G_ASYNC_RESULT (simple));
  chat_info = async_data->request;

  lst = _tpl_log_manager_search (async_data->manager,
      chat_info->search_text);

  g_simple_async_result_set_op_res_gpointer (simple, lst,
      _search_new_async_result_free);
}

/**
 * tpl_log_manager_search_async:
 * @manager: a #TplLogManager
 * @text: the pattern to search
 * @callback: a callback to call when the request is satisfied
 * @user_data: data to pass to @callback
 *
 * Search for all the conversations containing @text.
 */
void
tpl_log_manager_search_async (TplLogManager *manager,
    const gchar *text,
    GAsyncReadyCallback callback,
    gpointer user_data)
{
  TplLogManagerChatInfo *chat_info = tpl_log_manager_chat_info_new ();
  TplLogManagerAsyncData *async_data = tpl_log_manager_async_data_new ();
  GSimpleAsyncResult *simple;

  g_return_if_fail (TPL_IS_LOG_MANAGER (manager));

  chat_info->search_text = g_strdup (text);

  async_data->manager = g_object_ref (manager);
  async_data->request = chat_info;
  async_data->request_free =
    (TplLogManagerFreeFunc) tpl_log_manager_chat_info_free;
  async_data->cb = callback;
  async_data->user_data = user_data;

  simple = g_simple_async_result_new (G_OBJECT (manager),
      _tpl_log_manager_async_operation_cb, async_data,
      tpl_log_manager_search_async);

  g_simple_async_result_run_in_thread (simple, _search_async_thread, 0,
      NULL);

  g_object_unref (simple);
}

/**
 * tpl_log_manager_errors_quark:
 *
 * Returns: the #GQuark associated with the error domain of #TplLogManager
 */
GQuark
tpl_log_manager_errors_quark (void)
{
  static gsize quark = 0;

  if (g_once_init_enter (&quark))
    {
      GQuark domain = g_quark_from_static_string (
          "tpl_log_manager_errors");

      g_once_init_leave (&quark, domain);
    }

  return (GQuark) quark;
}

TplLogSearchHit *
_tpl_log_manager_search_hit_copy (TplLogSearchHit *hit)
{
  return _tpl_log_manager_search_hit_new (hit->account, hit->chat_id,
      hit->is_chatroom, hit->filename, hit->date);
}