William Bowling is sharing code with you

Bitbucket is a code hosting site. Unlimited public and private repositories. Free for small teams.

Don't show this again

wbowling / adium (fork of adium / adium)

Fork of Adium for patches/improvements

Clone this repository (size: 338.7 MB): HTTPS / SSH
hg clone https://bitbucket.org/wbowling/adium
hg clone ssh://hg@bitbucket.org/wbowling/adium

adium / Source / AILoggerPlugin.m

   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
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
/* 
 * Adium is the legal property of its developers, whose names are listed in the copyright file included
 * with this source distribution.
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation; either version 2 of the License,
 * or (at your option) any later version.
 * 
 * This program 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 General
 * Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not,
 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#import "AILoggerPlugin.h"
#import "AIChatLog.h"
#import "AILogFromGroup.h"
#import "AILogToGroup.h"
#import "AILogViewerWindowController.h"
#import "AIXMLAppender.h"
#import <Adium/AIXMLElement.h>
#import <Adium/AIContentControllerProtocol.h>
#import <Adium/AIInterfaceControllerProtocol.h>
#import <Adium/AIChatControllerProtocol.h>
#import <Adium/AILoginControllerProtocol.h>
#import <Adium/AIMenuControllerProtocol.h>
#import <Adium/AIToolbarControllerProtocol.h>
#import <Adium/AIAccount.h>
#import <Adium/AIChat.h>
#import <Adium/AIContentMessage.h>
#import <Adium/AIContentNotification.h>
#import <Adium/AIContentStatus.h>
#import <Adium/AIContentEvent.h>
#import <Adium/AIContentContext.h>
#import <Adium/AIHTMLDecoder.h>
#import <Adium/AIListContact.h>
#import <Adium/AIListBookmark.h>
#import <Adium/AIService.h>
#import <AIUtilities/AIAttributedStringAdditions.h>
#import <AIUtilities/AIDictionaryAdditions.h>
#import <AIUtilities/AIFileManagerAdditions.h>
#import <AIUtilities/AIMenuAdditions.h>
#import <AIUtilities/AIStringAdditions.h>
#import <AIUtilities/AIToolbarUtilities.h>
#import <AIUtilities/AIApplicationAdditions.h>
#import <AIUtilities/AIDateFormatterAdditions.h>
#import <AIUtilities/AIImageAdditions.h>
#import <AIUtilities/NSCalendarDate+ISO8601Unparsing.h>
#import <AIUtilities/NSCalendarDate+ISO8601Parsing.h>

#import <libkern/OSAtomic.h>

#import "AILogFileUpgradeWindowController.h"

#import "AdiumSpotlightImporter.h"

#define LOG_INDEX_NAME                          @"Logs.index"
#define DIRTY_LOG_SET_NAME                      @"DirtyLogs.plist"
#define KEY_LOG_INDEX_VERSION           @"Log Index Version"

#define LOG_INDEX_STATUS_INTERVAL       20      //Interval before updating the log indexing status
#define LOG_CLEAN_SAVE_INTERVAL         500     //Number of logs to index continuously before saving the dirty set and index

#define LOG_VIEWER                                      AILocalizedString(@"Chat Transcript Viewer",nil)
#define VIEW_LOGS_WITH_CONTACT          AILocalizedString(@"View Chat Transcripts",nil)

#define CURRENT_LOG_VERSION                     9       //Version of the log index.  Increase this number to reset everyone's index.

#define LOG_VIEWER_IDENTIFIER           @"LogViewer"

#define NEW_LOGFILE_TIMEOUT                     600             //10 minutes

#define ENABLE_PROXIMITY_SEARCH         TRUE

enum {
        AIIndexFileAvailable = 1,
        AIIndexFileIsClosing
};

@interface AILoggerPlugin ()
+ (NSString *)dereferenceLogFolderAlias;
+ (NSOperationQueue *)operationQueue;
- (void)configureMenuItems;
- (SKIndexRef)createLogIndex;
- (void)closeLogIndex;
- (void)cancelClosingLogIndex;
- (void)resetLogIndex;
- (NSString *)_logIndexPath;
- (void)loadDirtyLogSet;
- (void)_saveDirtyLogSet;
- (NSString *)_dirtyLogSetPath;
- (void)_dirtyAllLogsThread;
- (void)upgradeLogExtensions;
- (void)upgradeLogPermissions;
- (void)reimportLogsToSpotlightIfNeeded;
- (NSString *)keyForChat:(AIChat *)chat;
- (AIXMLAppender *)existingAppenderForChat:(AIChat *)chat;
- (AIXMLAppender *)appenderForChat:(AIChat *)chat;
- (void)closeAppenderForChat:(AIChat *)chat;
- (void)finishClosingAppender:(NSString *)chatKey;
@end

static NSString     *logBasePath = nil;     //The base directory of all logs
static NSString     *logBaseAliasPath = nil;     //If the usual Logs folder path refers to an alias file, this is that path, and logBasePath is the destination of the alias; otherwise, this is nil and logBasePath is the usual Logs folder path.

@implementation AILoggerPlugin

- (void)installPlugin
{
        observingContent = NO;

        activeAppenders = [[NSMutableDictionary alloc] init];
        
        xhtmlDecoder = [[AIHTMLDecoder alloc] initWithHeaders:NO
                                                                                                 fontTags:YES
                                                                                        closeFontTags:YES
                                                                                                colorTags:YES
                                                                                                styleTags:YES
                                                                                   encodeNonASCII:YES
                                                                                         encodeSpaces:NO
                                                                                attachmentsAsText:NO
                                                                onlyIncludeOutgoingImages:NO
                                                                                   simpleTagsOnly:NO
                                                                                   bodyBackground:NO
                                                                          allowJavascriptURLs:YES];
        [xhtmlDecoder setGeneratesStrictXHTML:YES];
        
        statusTranslation = [[NSDictionary alloc] initWithObjectsAndKeys:
                @"away",@"away",
                @"online",@"return_away",
                @"online",@"online",
                @"offline",@"offline",
                @"idle",@"idle",
                @"available",@"return_idle",
                @"away",@"away_message",
                nil];

        //Setup our preferences
        [adium.preferenceController registerDefaults:[NSDictionary dictionaryNamed:LOGGING_DEFAULT_PREFS 
                                                                                                                                                forClass:[self class]] 
                                                                                  forGroup:PREF_GROUP_LOGGING];

        //Install the log viewer menu items
        [self configureMenuItems];
        
        //Create a logs directory
        logBasePath = [[[[adium.loginController userDirectory] stringByAppendingPathComponent:PATH_LOGS] stringByExpandingTildeInPath] retain];
        [[NSFileManager defaultManager] createDirectoryAtPath:logBasePath withIntermediateDirectories:YES attributes:nil error:NULL];

        //Observe preference changes
        [adium.preferenceController addObserver:self
                                                                   forKeyPath:PREF_KEYPATH_LOGGER_ENABLE
                                                                          options:NSKeyValueObservingOptionNew
                                                                          context:NULL];
        [self observeValueForKeyPath:PREF_KEYPATH_LOGGER_ENABLE
                            ofObject:adium.preferenceController
                              change:nil
                             context:NULL];

        //Toolbar item
        NSToolbarItem   *toolbarItem;
        toolbarItem = [AIToolbarUtilities toolbarItemWithIdentifier:LOG_VIEWER_IDENTIFIER
                                                                                                                  label:AILocalizedString(@"Transcripts",nil)
                                                       paletteLabel:AILocalizedString(@"View Chat Transcripts",nil)
                                                            toolTip:AILocalizedString(@"View previous conversations with this contact or chat",nil)
                                                             target:self
                                                    settingSelector:@selector(setImage:)
                                                        itemContent:[NSImage imageNamed:@"LogViewer" forClass:[self class] loadLazily:YES]
                                                             action:@selector(showLogViewerForActiveChat:)
                                                               menu:nil];
        [adium.toolbarController registerToolbarItem:toolbarItem forToolbarType:@"ListObject"];

        dirtyLogSet = [[NSMutableSet alloc] init];
        index_Content = nil;
        stopIndexingThreads = NO;
        suspendDirtySetSaving = NO;             
        indexingThreadLock = [[NSLock alloc] init];
        [indexingThreadLock setName:@"LogIndexingThreadLock"];
        dirtyLogLock = [[NSLock alloc] init];
        [dirtyLogLock setName:@"DirtyLogLock"];
        logWritingLock = [[NSConditionLock alloc] initWithCondition:AIIndexFileAvailable];
        logClosingLock = [[NSConditionLock alloc] initWithCondition:AIIndexFileAvailable];

        //Init index searching
        [self initLogIndexing];
        
        [self upgradeLogExtensions];
        [self upgradeLogPermissions];
        
        [self reimportLogsToSpotlightIfNeeded];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                                   selector:@selector(showLogNotification:)
                                                                           name:AIShowLogAtPathNotification
                                                                         object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                                                         selector:@selector(showLogViewerAndReindex:)
                                                                                                 name:AIShowLogViewerAndReindexNotification
                                                                                           object:nil];
}

- (void)uninstallPlugin
{
        [activeAppenders release]; activeAppenders = nil;
        [xhtmlDecoder release]; xhtmlDecoder = nil;
        [statusTranslation release]; statusTranslation = nil;

        [NSObject cancelPreviousPerformRequestsWithTarget:self];

        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [adium.preferenceController removeObserver:self forKeyPath:PREF_KEYPATH_LOGGER_ENABLE];
}

+ (NSOperationQueue *)operationQueue {
        static OSSpinLock spinLock = OS_SPINLOCK_INIT;
        static NSOperationQueue *loggerQueue = nil;
        
        OSSpinLockLock(&spinLock);
        if (!loggerQueue) {
                loggerQueue = [[NSOperationQueue alloc] init];
                if([loggerQueue respondsToSelector:@selector(setName:)]) {
                        [loggerQueue setName:@"AILoggerPluginOperationQueue"];
                }
        }
        OSSpinLockUnlock(&spinLock);
        
        return loggerQueue;
}

//If logBasePath refers to an alias file, dereference the alias and replace logBasePath with that pathname.
+ (NSString *)dereferenceLogFolderAlias {
        if (!logBaseAliasPath) {
                FSRef ref;

                Boolean isDir = true;
                OSStatus err = FSPathMakeRef((UInt8 *)[logBasePath UTF8String], &ref, &isDir);
                if (err != noErr) {
                        NSLog(@"Warning: Couldn't obtain FSRef for transcripts folder: %s (%i)", GetMacOSStatusCommentString(err), err);
                        return logBasePath;
                }
                if (isDir) {
                        //It's really a folder, not an alias file. No dereferencing to do.
                        return logBasePath;
                }

                //It's a filepresumably an alias file.
                Boolean wasAliased_nobodyCares;
                err = FSResolveAliasFile(&ref, /*resolveAliasChains*/ true, &isDir, &wasAliased_nobodyCares);
                if (err != noErr) {
                        NSLog(@"Warning: Couldn't resolve alias to transcripts folder: %s (%i)", GetMacOSStatusCommentString(err), err);
                } else {
                        //Successfully dereferenced!
                        NSURL *logBaseURL = [(NSURL *)CFURLCreateFromFSRef(kCFAllocatorDefault, &ref) autorelease];
                        logBaseAliasPath = logBasePath;
                        logBasePath = [[logBaseURL path] copy];
                }
        }

        return logBasePath;
}

//Update for the new preferences
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
        BOOL    newLogValue;
        logHTML = YES;

        //Start/Stop logging
        newLogValue = [[object valueForKeyPath:keyPath] boolValue];
        if (newLogValue != observingContent) {
                observingContent = newLogValue;
                                
                if (!observingContent) { //Stop Logging
                        [[NSNotificationCenter defaultCenter] removeObserver:self name:Content_ContentObjectAdded object:nil];
                        
                        [[NSNotificationCenter defaultCenter] removeObserver:self name:Chat_DidOpen object:nil];                        
                        [[NSNotificationCenter defaultCenter] removeObserver:self name:Chat_WillClose object:nil];

                } else { //Start Logging
                        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                                                   selector:@selector(contentObjectAdded:) 
                                                                                           name:Content_ContentObjectAdded 
                                                                                         object:nil];
                                                                                         
                        [[NSNotificationCenter defaultCenter] addObserver:self
                                                                                   selector:@selector(chatOpened:)
                                                                                           name:Chat_DidOpen
                                                                                         object:nil];
                                                                                         
                        [[NSNotificationCenter defaultCenter] addObserver:self
                                                                                   selector:@selector(chatClosed:)
                                                                                           name:Chat_WillClose
                                                                                         object:nil];
                        [[NSNotificationCenter defaultCenter] addObserver:self
                                                                                   selector:@selector(chatWillDelete:)
                                                                                           name:ChatLog_WillDelete
                                                                                         object:nil];
                }
        }
}


//Logging Paths --------------------------------------------------------------------------------------------------------
+ (NSString *)logBasePath
{
        [self dereferenceLogFolderAlias];
        return logBasePath;
}
- (NSString *)logBasePath
{
        return [[self class] logBasePath];
}

//Returns the RELATIVE path to the folder where the log should be written
+ (NSString *)relativePathForLogWithObject:(NSString *)object onAccount:(AIAccount *)account
{       
        return [NSString stringWithFormat:@"%@.%@/%@", account.service.serviceID, [account.UID safeFilenameString], object];
}

+ (NSString *)nameForLogWithObject:(NSString *)object onDate:(NSDate *)date
{
        NSParameterAssert(date != nil);
        NSParameterAssert(object != nil);
        NSString    *dateString = [date descriptionWithCalendarFormat:@"%Y-%m-%dT%H.%M.%S%z" timeZone:nil locale:nil];
        
        NSAssert2(dateString != nil, @"Date string was invalid for the chatlog for %@ on %@", object, date);
                
        return [NSString stringWithFormat:@"%@ (%@)", object, dateString];
}

+ (NSString *)pathForLogsLikeChat:(AIChat *)chat
{
        NSString        *objectUID = chat.name;
        AIAccount       *account = chat.account;
        
        if (!objectUID) objectUID = chat.listObject.UID;
        objectUID = [objectUID safeFilenameString];

        return [[self logBasePath] stringByAppendingPathComponent:[self relativePathForLogWithObject:objectUID onAccount:account]];
}

+ (NSString *)fullPathForLogOfChat:(AIChat *)chat onDate:(NSDate *)date
{
        NSString        *objectUID = chat.name;
        AIAccount       *account = chat.account;

        if (!objectUID) objectUID = chat.listObject.UID;
        objectUID = [objectUID safeFilenameString];

        NSString        *absolutePath = [[self logBasePath] stringByAppendingPathComponent:[self relativePathForLogWithObject:objectUID onAccount:account]];

        NSString        *name = [self nameForLogWithObject:objectUID onDate:date];
        NSString        *fullPath = [[absolutePath stringByAppendingPathComponent:[name stringByAppendingPathExtension:@"chatlog"]]
                                                         stringByAppendingPathComponent:[name stringByAppendingPathExtension:@"xml"]];

        return fullPath;
}

//Menu Items -----------------------------------------------------------------------------------------------------------
#pragma mark Menu Items
//Configure the log viewer menu items
- (void)configureMenuItems
{
    logViewerMenuItem = [[[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:LOG_VIEWER 
                                                                                                                                                          target:self
                                                                                                                                                          action:@selector(showLogViewer:)
                                                                                                                                           keyEquivalent:@"L"] autorelease];
    [adium.menuController addMenuItem:logViewerMenuItem toLocation:LOC_Window_Auxiliary];

    viewContactLogsMenuItem = [[[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:VIEW_LOGS_WITH_CONTACT
                                                                                                                                                                        target:self
                                                                                                                                                                        action:@selector(showLogViewerToSelectedContact:) 
                                                                                                                                                         keyEquivalent:@"l"] autorelease];
    [adium.menuController addMenuItem:viewContactLogsMenuItem toLocation:LOC_Contact_Info];

    viewContactLogsContextMenuItem = [[[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:VIEW_LOGS_WITH_CONTACT
                                                                                                                                                                                   target:self
                                                                                                                                                                                   action:@selector(showLogViewerToSelectedContextContact:) 
                                                                                                                                                                        keyEquivalent:@""] autorelease];
    [adium.menuController addContextualMenuItem:viewContactLogsContextMenuItem toLocation:Context_Contact_Manage];
        
        viewGroupLogsContextMenuItem = [[[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:VIEW_LOGS_WITH_CONTACT
                                                                                                                                                                                 target:self
                                                                                                                                                                                 action:@selector(showLogViewerForGroupChat:) 
                                                                                                                                                                  keyEquivalent:@""] autorelease];
    [adium.menuController addContextualMenuItem:viewGroupLogsContextMenuItem toLocation:Context_GroupChat_Manage];
        
}

//Enable/Disable our view log menus
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
{       
    if (menuItem == viewContactLogsMenuItem) {
        AIListObject    *selectedObject = adium.interfaceController.selectedListObject;
                return adium.interfaceController.activeChat || (selectedObject && [selectedObject isKindOfClass:[AIListContact class]]);

    } else if (menuItem == viewContactLogsContextMenuItem) {
        AIListObject    *selectedObject = adium.menuController.currentContextMenuObject;
                return !adium.interfaceController.activeChat.isGroupChat || (selectedObject && [selectedObject isKindOfClass:[AIListContact class]]);
    }
        
    return YES;
}

/*!
 * @brief Show the log viewer for no contact
 *
 * Invoked from the Window menu
 */
- (void)showLogViewer:(id)sender
{
    [AILogViewerWindowController openForContact:nil  
                                                                                 plugin:self];  
}

/*!
 * @brief Reimport all logs and open the log viewer
 *
 * Invoked from the Import menu to clear the current set of logs.
 * This is useful after a user adds more chats to the Logs folder.
 */
- (void)showLogViewerAndReindex:(id)sender
{
        [self dirtyAllLogs];
        
        [AILogViewerWindowController openForContact:nil plugin:self];
}

/*!
 * @brief Show the log viewer, displaying only the selected contact's logs
 *
 * Invoked from the Contact menu
 */
- (void)showLogViewerToSelectedContact:(id)sender
{
        BOOL openForSelectedObject = YES;
        
        if (sender == viewContactLogsMenuItem) {
                AIChat *activeChat = adium.interfaceController.activeChat;
                
                if (activeChat.isGroupChat) {
                        [AILogViewerWindowController openForChatName:activeChat.name withAccount:activeChat.account plugin:self];
                        openForSelectedObject = NO;
                }
        }
        
        if (openForSelectedObject) {
                AIListObject   *selectedObject = adium.interfaceController.selectedListObject;
                
                if ([selectedObject isKindOfClass:[AIListBookmark class]]) {
                        [AILogViewerWindowController openForChatName:((AIListBookmark *)selectedObject).name
                                                                                         withAccount:((AIListBookmark *)selectedObject).account
                                                                                                  plugin:self];
                } else {
                        [AILogViewerWindowController openForContact:([selectedObject isKindOfClass:[AIListContact class]] ?
                                                                                                                 (AIListContact *)selectedObject : 
                                                                                                                 nil)  
                                                                                                 plugin:self];
                }
        }
}

/*!
 * @brief Show the log viewer for the active chat
 *
 * This is called when a chat is definitely in focus, i.e. the toolbar item.
 */
- (void)showLogViewerForActiveChat:(id)sender
{
        AIChat *activeChat = adium.interfaceController.activeChat;
        
        if(activeChat.isGroupChat) {
                [AILogViewerWindowController openForChatName:activeChat.name withAccount:activeChat.account plugin:self];
        } else {
                [AILogViewerWindowController openForContact:activeChat.listObject plugin:self];
        }
}

/*!
 * @brief Show the log viewer with the menu context chat
 *
 * Opens the log window for a specific AIChat which the context menu is currently referencing.
 * This is called by the group chat's context menu to open its logs.
 */
- (void)showLogViewerForGroupChat:(id)sender
{
        AIChat *contextChat = adium.menuController.currentContextMenuChat;
        
        [NSApp activateIgnoringOtherApps:YES];
        
        [AILogViewerWindowController openForChatName:contextChat.name withAccount:contextChat.account plugin:self];
}

- (void)showLogViewerForLogAtPath:(NSString *)inPath
{
        [AILogViewerWindowController openLogAtPath:inPath plugin:self];
}

- (void)showLogNotification:(NSNotification *)inNotification
{
        [self showLogViewerForLogAtPath:[inNotification object]];
}

/*!
 * @brief Show the log viewer, displaying only the selected contact's logs
 *
 * Invoked from a contextual menu
 */
- (void)showLogViewerToSelectedContextContact:(id)sender
{
        AIListObject* object = adium.menuController.currentContextMenuObject;
        
        AILogViewerWindowController *windowController = nil;
        
        if ([object isKindOfClass:[AIListBookmark class]]) {
                windowController = [AILogViewerWindowController openForChatName:((AIListBookmark *)object).name
                                                                                                                        withAccount:((AIListBookmark *)object).account
                                                                                                                                 plugin:self];
                
        } else if ([object isKindOfClass:[AIListContact class]]) {
                windowController = [AILogViewerWindowController openForContact:(AIListContact *)object plugin:self];
        }
        
        if (windowController) {
                [NSApp activateIgnoringOtherApps:YES];
                [[windowController window] makeKeyAndOrderFront:nil];
        }
}


//Logging --------------------------------------------------------------------------------------------------------------
#pragma mark Logging
//Log any content that is sent or received
- (void)contentObjectAdded:(NSNotification *)notification
{
        AIContentMessage        *content = [[notification userInfo] objectForKey:@"AIContentObject"];
        if ([content postProcessContent]) {
                AIChat                          *chat = [notification object];

                if (![chat shouldLog]) return;  
                
                BOOL                    dirty = NO;
                NSString                *contentType = [content type];
                NSString                *date = [[[content date] dateWithCalendarFormat:nil timeZone:nil] ISO8601DateString];

                if ([contentType isEqualToString:CONTENT_MESSAGE_TYPE] ||
                        [contentType isEqualToString:CONTENT_CONTEXT_TYPE]) {
                        NSMutableArray *attributeKeys = [NSMutableArray arrayWithObjects:@"sender", @"time", nil];
                        NSMutableArray *attributeValues = [NSMutableArray arrayWithObjects:[[content source] UID], date, nil];
                        AIXMLAppender  *appender = [self appenderForChat:chat];
                        if ([content isAutoreply]) {
                                [attributeKeys addObject:@"auto"];
                                [attributeValues addObject:@"true"];
                        }
                        
                        NSString *displayName = [chat displayNameForContact:content.source];
                        
                        if (![[[content source] UID] isEqualToString:displayName]) {
                                [attributeKeys addObject:@"alias"];
                                [attributeValues addObject:displayName];
                        }
                        
                        AIXMLElement *messageElement = [[[AIXMLElement alloc] initWithName:@"message"] autorelease];

                        [messageElement addEscapedObject:[xhtmlDecoder encodeHTML:[content message]
                                                                                                                   imagesPath:[appender.path stringByDeletingLastPathComponent]]];
                        
                        [messageElement setAttributeNames:attributeKeys values:attributeValues];

                        [appender appendElement:messageElement];
                        
                        dirty = YES;
                } else {
                        //XXX: Yucky hack. This is here because we get status and event updates for metas, not for individual contacts. Or something like that.
                        AIListObject    *retardedMetaObject = [content source];
                        AIListObject    *actualObject = nil;
                        
                        if (content.source) {
                                for(AIListContact *participatingListObject in chat) {
                                        if ([participatingListObject parentContact] == retardedMetaObject) {
                                                actualObject = participatingListObject;
                                                break;
                                        }
                                }
                        }

                        //If we can't find it for some reason, we probably shouldn't attempt logging, unless source was nil.
                        if ([contentType isEqualToString:CONTENT_STATUS_TYPE] && actualObject) {
                                NSString *translatedStatus = [statusTranslation objectForKey:[(AIContentStatus *)content status]];
                                if (translatedStatus == nil) {
                                        AILogWithSignature(@"AILogger: Don't know how to translate status: %@", [(AIContentStatus *)content status]);
                                } else {
                                        NSMutableArray *attributeKeys = [NSMutableArray arrayWithObjects:@"type", @"sender", @"time", nil];
                                        NSMutableArray *attributeValues = [NSMutableArray arrayWithObjects:
                                                                                                           translatedStatus, 
                                                                                                           actualObject.UID, 
                                                                                                           date,
                                                                                                           nil];

                                        if (![actualObject.UID isEqualToString:actualObject.displayName]) {
                                                [attributeKeys addObject:@"alias"];
                                                [attributeValues addObject:actualObject.displayName];                           
                                        }
                                        
                                        AIXMLElement *statusElement = [[[AIXMLElement alloc] initWithName:@"status"] autorelease];
                                        
                                        [statusElement addEscapedObject:([(AIContentStatus *)content loggedMessage] ?
                                                                                                         [xhtmlDecoder encodeHTML:[(AIContentStatus *)content loggedMessage] imagesPath:nil] :
                                                                                                         @"")];
                                        
                                        [statusElement setAttributeNames:attributeKeys values:attributeValues];
                                        
                                        [[self appenderForChat:chat] appendElement:statusElement];
                                        
                                        dirty = YES;
                                }

                        } else if ([contentType isEqualToString:CONTENT_EVENT_TYPE] ||
                                           [contentType isEqualToString:CONTENT_NOTIFICATION_TYPE]) {
                                NSMutableArray *attributeKeys = nil, *attributeValues = nil;
                                if (content.source) {
                                        attributeKeys = [NSMutableArray arrayWithObjects:@"type", @"sender", @"time", nil];
                                        attributeValues = [NSMutableArray arrayWithObjects:
                                                                                                           [(AIContentEvent *)content eventType], [[content source] UID], date, nil];   
                                } else {
                                        attributeKeys = [NSMutableArray arrayWithObjects:@"type", @"time", nil];
                                        attributeValues = [NSMutableArray arrayWithObjects:
                                                                                                           [(AIContentEvent *)content eventType], date, nil];
                                }
                                
                                AIXMLAppender  *appender = [self appenderForChat:chat];

                                if (content.source && ![[[content source] UID] isEqualToString:[[content source] displayName]]) {
                                        [attributeKeys addObject:@"alias"];
                                        [attributeValues addObject:[[content source] displayName]];                             
                                }

                                AIXMLElement *statusElement = [[[AIXMLElement alloc] initWithName:@"status"] autorelease];
                                
                                [statusElement addEscapedObject:[xhtmlDecoder encodeHTML:[content message]
                                                                                                                          imagesPath:[[appender path] stringByDeletingLastPathComponent]]];
                                
                                [statusElement setAttributeNames:attributeKeys values:attributeValues];
                                
                                [appender appendElement:statusElement];
                                dirty = YES;
                        }
                }
                //Don't create a new one if not needed
                AIXMLAppender *appender = [self existingAppenderForChat:chat];
                if (dirty && appender)
                        [self markLogDirtyAtPath:[appender path] forChat:chat];
        }
}

- (void)chatOpened:(NSNotification *)notification
{
        AIChat  *chat = [notification object];

        if (![chat shouldLog]) return;  
        
        //Try reusing the appender object
        AIXMLAppender *appender = [self existingAppenderForChat:chat];
        
        //If there is an appender, add the windowOpened event
        if (appender) {
                /* Ensure a timeout isn't set for closing the appender, since we're now using it.
                 * This gives us the desired behavior - if chat #2 opens before the timeout on the
                 * log file, then we want to keep the log continuous until the user has closed the
                 * window. 
                 */
                [NSObject cancelPreviousPerformRequestsWithTarget:self
                                                                                                 selector:@selector(finishClosingAppender:) 
                                                                                                 object:[self keyForChat:chat]];
                
                // Print the windowOpened event in the log
                AIXMLElement *eventElement = [[[AIXMLElement alloc] initWithName:@"event"] autorelease];

                [eventElement setAttributeNames:[NSArray arrayWithObjects:@"type", @"sender", @"time", nil]
                                                                 values:[NSArray arrayWithObjects:@"windowOpened", chat.account.UID, [[[NSDate date] dateWithCalendarFormat:nil timeZone:nil] ISO8601DateString], nil]];
                
                [appender appendElement:eventElement];

                [self markLogDirtyAtPath:[appender path] forChat:chat];
        }
}

- (void)chatClosed:(NSNotification *)notification
{
        AIChat  *chat = [notification object];

        if (![chat shouldLog]) return;  
        
        //Use this method so we don't create a new appender for chat close events
        AIXMLAppender *appender = [self existingAppenderForChat:chat];
        
        //If there is an appender, add the windowClose event
        if (appender) {
                AIXMLElement *eventElement = [[[AIXMLElement alloc] initWithName:@"event"] autorelease];
                
                [eventElement setAttributeNames:[NSArray arrayWithObjects:@"type", @"sender", @"time", nil]
                                                                 values:[NSArray arrayWithObjects:@"windowClosed", chat.account.UID, [[[NSDate date] dateWithCalendarFormat:nil timeZone:nil] ISO8601DateString], nil]];
                
                
                [appender appendElement:eventElement];
                [self closeAppenderForChat:chat];

                [self markLogDirtyAtPath:[appender path] forChat:chat];
        }
}

//Ugly method. Shouldn't this notification post an AIChat, not an AIChatLog?
- (void)chatWillDelete:(NSNotification *)notification
{
        AIChatLog *chatLog = [notification object];
        NSString *chatID = [NSString stringWithFormat:@"%@.%@-%@", [chatLog serviceClass], [chatLog from], [chatLog to]];
        AIXMLAppender *appender = [activeAppenders objectForKey:chatID];
        
        if (appender) {
                if ([[appender path] hasSuffix:[chatLog relativePath]]) {
                        [NSObject cancelPreviousPerformRequestsWithTarget:self
                                                                                                         selector:@selector(finishClosingAppender:) 
                                                                                                           object:chatID];
                        [self finishClosingAppender:chatID];
                }
        }
}

- (NSString *)keyForChat:(AIChat *)chat
{
        AIAccount *account = chat.account;
        NSString *chatID = (chat.isGroupChat ? [chat identifier] : chat.listObject.UID);

        return [NSString stringWithFormat:@"%@.%@-%@", account.service.serviceID, account.UID, chatID];
}

- (AIXMLAppender *)existingAppenderForChat:(AIChat *)chat
{
        //Look up the key for this chat and use it to try to retrieve the appender
        return [activeAppenders objectForKey:[self keyForChat:chat]];   
}

- (AIXMLAppender *)appenderForChat:(AIChat *)chat
{
        //Check if there is already an appender for this chat
        AIXMLAppender   *appender = [self existingAppenderForChat:chat];

        if (appender) {
                //Ensure a timeout isn't set for closing the appender, since we're now using it
                [NSObject cancelPreviousPerformRequestsWithTarget:self
                                                                                                 selector:@selector(finishClosingAppender:) 
                                                                                                   object:[self keyForChat:chat]];
        } else {
                //If there isn't already an appender, create a new one and add it to the dictionary
                NSDate                  *chatDate = [chat dateOpened];
                NSString                *fullPath = [AILoggerPlugin fullPathForLogOfChat:chat onDate:chatDate];

                AIXMLElement *rootElement = [[[AIXMLElement alloc] initWithName:@"chat"] autorelease];
                
                [rootElement setAttributeNames:[NSArray arrayWithObjects:@"xmlns", @"account", @"service", nil]
                                                                values:[NSArray arrayWithObjects:
                                                                                XML_LOGGING_NAMESPACE,
                                                                                chat.account.UID,
                                                                                chat.account.service.serviceID,
                                                                                nil]];
                
                appender = [AIXMLAppender documentWithPath:fullPath rootElement:rootElement];
                
                //Add the window opened event now
                AIXMLElement *eventElement = [[[AIXMLElement alloc] initWithName:@"event"] autorelease];
                
                [eventElement setAttributeNames:[NSArray arrayWithObjects:@"type", @"sender", @"time", nil]
                                                                 values:[NSArray arrayWithObjects:@"windowOpened", chat.account.UID, [[[NSDate date] dateWithCalendarFormat:nil timeZone:nil] ISO8601DateString], nil]];
                
                [appender appendElement:eventElement];
                
                [activeAppenders setObject:appender forKey:[self keyForChat:chat]];
                
                [self markLogDirtyAtPath:[appender path] forChat:chat];
        }
        
        return appender;
}

- (void)closeAppenderForChat:(AIChat *)chat
{
        //Create a new timer to fire after the timeout period, which will close the appender
        NSString *chatKey = [self keyForChat:chat];
        [NSObject cancelPreviousPerformRequestsWithTarget:self
                                                                                         selector:@selector(finishClosingAppender:) 
                                                                                           object:chatKey];
        [self performSelector:@selector(finishClosingAppender:) 
                           withObject:chatKey
                           afterDelay:NEW_LOGFILE_TIMEOUT];
}

- (void)finishClosingAppender:(NSString *)chatKey
{
        //Remove the appender, closing its file descriptor upon dealloc
        [activeAppenders removeObjectForKey:chatKey];
}


//Display a warning to the user that logging failed, and disable logging to prevent additional warnings
//XXX not currently used. We may want to shift these strings for use when xml logging fails, so I'm not removing them -eds
/*
- (void)displayErrorAndDisableLogging
{
        NSRunAlertPanel(AILocalizedString(@"Unable to write log", nil),
                                        [NSString stringWithFormat:
                                                AILocalizedString(@"Adium was unable to write the log file for this conversation. Please ensure you have appropriate file permissions to write to your log directory (%@) for and then re-enable logging in the General preferences.", nil), [self logBasePath]],
                                        AILocalizedString(@"OK", nil), nil, nil);

        //Disable logging
        [adium.preferenceController setPreference:[NSNumber numberWithBool:NO]
                                             forKey:KEY_LOGGER_ENABLE
                                              group:PREF_GROUP_LOGGING];
}
*/

#pragma mark Message History

NSCalendarDate* getDateFromPath(NSString *path)
{
        NSRange openParenRange, closeParenRange;

        if ([path hasSuffix:@".chatlog"] && (openParenRange = [path rangeOfString:@"(" options:NSBackwardsSearch]).location != NSNotFound) {
                openParenRange = NSMakeRange(openParenRange.location, [path length] - openParenRange.location);
                if ((closeParenRange = [path rangeOfString:@")" options:0 range:openParenRange]).location != NSNotFound) {
                        //Add and subtract one to remove the parenthesis
                        NSString *dateString = [path substringWithRange:NSMakeRange(openParenRange.location + 1, (closeParenRange.location - openParenRange.location))];
                        NSCalendarDate *date = [NSCalendarDate calendarDateWithString:dateString timeSeparator:'.'];
                        return date;
                }
        }
        return nil;
}

NSComparisonResult sortPaths(NSString *path1, NSString *path2, void *context)
{
        NSDictionary *cache = (NSDictionary *)context;
        id date1 = [cache objectForKey:path1];
        id date2 = [cache objectForKey:path2];
        NSNull *n = [NSNull null];
        if (date1 == n)
                date1 = nil;
        if (date2 == n)
                date2 = nil;
        
        if(!date1 && !date2)
                return NSOrderedSame;
        else if (date1 && date2)
                return [date2 compare:date1];
        else
                return date2 ? NSOrderedDescending : NSOrderedAscending;
}

+ (NSArray *)sortedArrayOfLogFilesForChat:(AIChat *)chat
{
        NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self pathForLogsLikeChat:chat] error:NULL];
        NSMutableArray *dates = [NSMutableArray arrayWithCapacity:files.count];
        for (NSString *path in files) {
                id date = getDateFromPath(path);
                [dates addObject:date ?: [NSNull null]];
        }
        
        NSDictionary *cache = [NSDictionary dictionaryWithObjects:dates forKeys:files];

        return (files ? [files sortedArrayUsingFunction:&sortPaths context:cache] : nil);
}

#pragma mark Upgrade code
- (void)upgradeLogExtensions
{
        if (![[adium.preferenceController preferenceForKey:@"Log Extensions Updated" group:PREF_GROUP_LOGGING] boolValue]) {
                /* This could all be a simple NSDirectoryEnumerator call on basePath, but we wouldn't be able to show progress,
                * and this could take a bit.
                */
                
                NSMutableSet    *pathsToContactFolders = [NSMutableSet set];
                for (NSString *accountFolderName in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self logBasePath] error:NULL]) {
                        NSString                *contactBasePath = [logBasePath stringByAppendingPathComponent:accountFolderName];
                        
                        for (NSString *contactFolderName in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:contactBasePath error:NULL]) {
                                [pathsToContactFolders addObject:[contactBasePath stringByAppendingPathComponent:contactFolderName]];
                        }
                }
                
                NSUInteger              contactsToProcess = [pathsToContactFolders count];
                NSUInteger              processed = 0;
                
                if (contactsToProcess) {
                        
                        AILogFileUpgradeWindowController *upgradeWindowController = [[AILogFileUpgradeWindowController alloc] initWithWindowNibName:@"LogFileUpgrade"];
                        [[upgradeWindowController window] makeKeyAndOrderFront:nil];

                        for (NSString *pathToContactFolder in pathsToContactFolders) {
                                for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathToContactFolder error:NULL]) {
                                        if (([[file pathExtension] isEqualToString:@"html"]) ||
                                                ([[file pathExtension] isEqualToString:@"adiumLog"]) ||
                                                (([[file pathExtension] isEqualToString:@"bak"]) && ([file hasSuffix:@".html.bak"] || 
                                                                                                                                                         [file hasSuffix:@".adiumLog.bak"]))) {
                                                NSString *fullFile = [pathToContactFolder stringByAppendingPathComponent:file];
                                                NSString *newFile = [[fullFile stringByDeletingPathExtension] stringByAppendingPathExtension:@"AdiumHTMLLog"];
                                                
                                                NSError *err;
                                                [[NSFileManager defaultManager] moveItemAtPath:fullFile
                                                                                                                                toPath:newFile
                                                                                                                                 error:&err];
                                                if (err)
                                                        AILogWithSignature(@"%@", [err localizedDescription]);
                                        }
                                }
                                
                                processed++;
                                [upgradeWindowController setProgress:(processed*100.0)/contactsToProcess];
                        }
                        
                        [upgradeWindowController close];
                        [upgradeWindowController release];
                }
                
                [adium.preferenceController setPreference:[NSNumber numberWithBool:YES]
                                                                                         forKey:@"Log Extensions Updated"
                                                                                          group:PREF_GROUP_LOGGING];
        }
}

- (void)upgradeLogPermissions
{
        if ([[adium.preferenceController preferenceForKey:@"Log Permissions Updated" group:PREF_GROUP_LOGGING] boolValue])
                return;
        
        /* This is based off of -upgradeLogExtensions. Refer to that. */
        NSMutableSet    *pathsToContactFolders = [NSMutableSet set];
        for (NSString *accountFolderName in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self logBasePath] error:NULL]) {
                //??? isn't this just going to be the same as accountFolderName?
                NSString                *contactBasePath = [[self logBasePath] stringByAppendingPathComponent:accountFolderName];
                
                // Set permissions to prohibit access from other users
                [[NSFileManager defaultManager] setAttributes:[NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedLong:0700UL]
                                                                                                                                                 forKey:NSFilePosixPermissions]
                                                 ofItemAtPath:contactBasePath
                                                                error:NULL];
                
                for (NSString *contactFolderName in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:contactBasePath error:NULL]) {
                        NSString        *contactFolderPath = [contactBasePath stringByAppendingPathComponent:contactFolderName];
                        
                        // Set permissions to prohibit access from other users
                        [[NSFileManager defaultManager] setAttributes:[NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedLong:0700UL]
                                                                                                                                                         forKey:NSFilePosixPermissions]
                                                     ofItemAtPath:contactFolderPath
                                                                        error:NULL];
                        
                        // We'll traverse the contact directories themselves next
                        [pathsToContactFolders addObject:contactFolderPath];
                }
        }
        
        NSUInteger              contactsToProcess = [pathsToContactFolders count];
        NSUInteger              processed = 0;
        
        if (contactsToProcess) {                
                AILogFileUpgradeWindowController *upgradeWindowController = [[AILogFileUpgradeWindowController alloc] initWithWindowNibName:@"LogFileUpgrade"];
                [[upgradeWindowController window] makeKeyAndOrderFront:nil];
                
                for (NSString *pathToContactFolder in pathsToContactFolders) {                  
                        for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathToContactFolder error:NULL]) {
                                NSString        *fullFile = [pathToContactFolder stringByAppendingPathComponent:file];
                                BOOL            isDir;
                                
                                // Some chat logs are bundles
                                [[NSFileManager defaultManager] fileExistsAtPath:fullFile isDirectory:&isDir];
                                
                                if (!isDir) {
                                        [[NSFileManager defaultManager] setAttributes:[NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedLong:0600UL]
                                                                                                                                                                                          forKey:NSFilePosixPermissions]
                                                                                                         ofItemAtPath:fullFile
                                                                                                                        error:NULL];
                                        
                                } else {
                                        [[NSFileManager defaultManager] setAttributes:[NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedLong:0700UL]
                                                                                                                                                                                          forKey:NSFilePosixPermissions] 
                                                                                                         ofItemAtPath:fullFile 
                                                                                                                        error:NULL];
                                        
                                        // We have to enumerate this directory, too, only not as deep                                   
                                        for (NSString *contentFile in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fullFile error:NULL]) {
                                                [[NSFileManager defaultManager] setAttributes:[NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedLong:0600UL]
                                                                                                                                                                                                  forKey:NSFilePosixPermissions]
                                                                                                                 ofItemAtPath:contentFile
                                                                                                                                error:NULL];
                                        }
                                        
                                }
                                
                        }
                        
                        processed++;
                        [upgradeWindowController setProgress:(processed*100.0)/contactsToProcess];
                }
                
                [upgradeWindowController close];
                [upgradeWindowController release];
        }
        
        [adium.preferenceController setPreference:[NSNumber numberWithBool:YES]
         forKey:@"Log Permissions Updated"
         group:PREF_GROUP_LOGGING];
}

/*!
 * @brief Instruct spotlight to reimport logs
 *
 * Adium 1.0.2 and earlier had a bug which made spotlight import not work properly.
 * New logs are properly indexed, but previously created logs are not. On first launch of Adium 1.1,
 * Adium will tell Spotlight to reimport those old logs.
 *
 * We also reindex in Adium 1.3.3 to help capture logs in Mac OS X 10.5.6 which indexes logs in our default location.
 */
- (void)reimportLogsToSpotlightIfNeeded
{
        if (![[NSUserDefaults standardUserDefaults] boolForKey:@"Adium 1.3.3:Reimported Spotlight Logs"]) {
                @try {
                        NSArray *arguments;
                        
                        arguments = [NSArray arrayWithObjects:
                                                 @"-r",
                                                 [[[[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"Library"]
                                                   stringByAppendingPathComponent:@"Spotlight"] stringByAppendingPathComponent:[@"AdiumSpotlightImporter" stringByAppendingPathExtension:@"mdimporter"]],
                                                 nil];
                        [NSTask launchedTaskWithLaunchPath:@"/usr/bin/mdimport" arguments:arguments];
                }
                @catch (NSException *e) {
                        NSLog(@"Exception caught while reimporting Spotlight logs: %@", e);
                }
                
                [[NSUserDefaults standardUserDefaults] setBool:YES
                                                                                                forKey:@"Adium 1.3.3:Reimported Spotlight Logs"];
        }
}

//Log Indexing ---------------------------------------------------------------------------------------------------------
#pragma mark Log Indexing
/***** Everything below this point is related to log index generation and access ****/

/* For the log content searching, we are required to re-index a log whenever it changes.  The solution below to
 * this problem is along the lines of:
 *              - Keep a set of logs that need to be re-indexed
 *              - Whenever a log is changed, add it to this set
 *              - When the log viewer is opened, re-index all the logs in the set
 */

/*!
 * @brief Initialize log indexing
 */
- (void)initLogIndexing
{
        //Load the list of logs that need re-indexing
        [self loadDirtyLogSet];
}

/*!
 * @brief Prepare the log index for searching.
 *
 * Must call before attempting to use the logSearchIndex.
 */
- (void)prepareLogContentSearching
{
    /* Load the index and start indexing to make it current
         * If we're going to need to re-index all our logs from scratch, it will make
         * things faster if we start with a fresh log index as well.
         */
        BOOL reindex = ![[NSFileManager defaultManager] fileExistsAtPath:[self _dirtyLogSetPath]];
        if (reindex) {
                [self resetLogIndex];
        }

        //Load the contentIndex immediately; this will clear dirtyLogSet if necessary
        [self logContentIndex];

        stopIndexingThreads = NO;
        if (reindex) {
                [self dirtyAllLogs];
        } else {
                [self cleanDirtyLogs];
        }
}

//Close down and clean up the log index  (Call when finished using the logSearchIndex)
- (void)cleanUpLogContentSearching
{
        [self stopIndexingThreads];
        [self closeLogIndex];
}

//Returns the Search Kit index for log content searching
- (SKIndexRef)logContentIndex
{
        SKIndexRef      returnIndex;

        AILogWithSignature(@"Got %@", logClosingLock);
        /* We shouldn't have to lock here except in createLogIndex.  However, a 'window period' exists after an SKIndex has been closed via SKIndexClose()
         * in which an attempt to load the index from disk returns NULL (presumably because it's still being written-to asynchronously).  We therefore lock
         * around the full access to make the process reliable.  The documentation says that SKIndex is thread-safe, but that seems to assume that you keep
         * a single instance of SKIndex open at all times... which is a major memory hit for a large index of a significant number of logs. We only keep the index
         * open as long as the transcript viewer window is open.
         */
        [logClosingLock lockWhenCondition:AIIndexFileAvailable];
        [self cancelClosingLogIndex];
        if (!index_Content) {
                index_Content = [self createLogIndex];
        }
        returnIndex = (SKIndexRef)[[(NSObject *)index_Content retain] autorelease];
        [logClosingLock unlockWithCondition:AIIndexFileAvailable];

        return returnIndex;
}

//Mark a log as needing a re-index
- (void)markLogDirtyAtPath:(NSString *)path forChat:(AIChat *)chat
{       
        NSParameterAssert(path != nil);
        NSParameterAssert(chat != nil);
        [dirtyLogLock lock];
        if (![dirtyLogSet containsObject:path]) {
                //Add to dirty set (Lock to ensure that no one changes its content while we are)
                [dirtyLogSet addObject:path];
                [dirtyLogLock unlock];

                //Save the dirty set immediately
                [self _saveDirtyLogSet];
        } else {
                [dirtyLogLock unlock];
        }
}

- (void)markLogDirtyAtPath:(NSString *)path
{
        if(!path) return;
        [dirtyLogLock lock];
        if (![dirtyLogSet containsObject:path]) {
                [dirtyLogSet addObject:path];
        }
        [dirtyLogLock unlock];  
}

//Get the current status of indexing.  Returns NO if indexing is not occuring
- (BOOL)getIndexingProgress:(NSUInteger *)indexNumber outOf:(NSUInteger *)total
{
        //logsIndexed + 1 is the log we are currently indexing
        if (indexNumber) *indexNumber = (logsIndexed + 1 <= logsToIndex) ? logsIndexed + 1 : logsToIndex;
        if (total) *total = logsToIndex;
        return (logsToIndex > 0);
}


//Log index ------------------------------------------------------------------------------------------------------------
//Search kit index used to searching log content
#pragma mark Log Index
/*!
 * @brief Create the log index
 *
 * Should be called within logAccessLock being locked
 */
- (SKIndexRef)createLogIndex
{
    NSString    *logIndexPath = [self _logIndexPath];
    NSURL       *logIndexPathURL = [NSURL fileURLWithPath:logIndexPath];
        SKIndexRef      newIndex = NULL;

    if ([[NSFileManager defaultManager] fileExistsAtPath:logIndexPath]) {
                newIndex = SKIndexOpenWithURL((CFURLRef)logIndexPathURL, (CFStringRef)@"Content", true);
                AILogWithSignature(@"Opened index %x from %@",newIndex,logIndexPathURL);
                
                if (!newIndex) {
                        //It appears our index was somehow corrupt, since it exists but it could not be opened. Remove it so we can create a new one.
                        AILogWithSignature(@"*** Warning: The Chat Transcript searching index at %@ was corrupt. Removing it and starting fresh; transcripts will be re-indexed automatically.",
                                  logIndexPath);
                        [[NSFileManager defaultManager] removeItemAtPath:logIndexPath error:NULL];
                }
    }
    if (!newIndex) {
                NSDictionary *textAnalysisProperties;
                
                textAnalysisProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                        [NSNumber numberWithInteger:0], kSKMaximumTerms,
                        [NSNumber numberWithInteger:2], kSKMinTermLength,
#if ENABLE_PROXIMITY_SEARCH
                        kCFBooleanTrue, kSKProximityIndexing, 
#endif
                        nil];

                //Create the index if one doesn't exist or it couldn't be opened.
                [[NSFileManager defaultManager] createDirectoryAtPath:[logIndexPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:NULL];

                newIndex = SKIndexCreateWithURL((CFURLRef)logIndexPathURL,
                                                                                (CFStringRef)@"Content", 
                                                                                kSKIndexInverted,
                                                                                (CFDictionaryRef)textAnalysisProperties);
                if (newIndex) {
                        AILogWithSignature(@"Created a new log index %x at %@ with textAnalysisProperties %@. Will reindex all logs.",newIndex,logIndexPathURL,textAnalysisProperties);
                        //Clear the dirty log set in case it was loaded (this can happen if the user mucks with the cache directory)
                        [[NSFileManager defaultManager] removeItemAtPath:[self _dirtyLogSetPath] error:NULL];
                        [dirtyLogSet removeAllObjects];
                } else {
                        AILogWithSignature(@"AILoggerPlugin warning: SKIndexCreateWithURL() returned NULL");
                }
    }

        return newIndex;
}

- (void)finishClosingIndex
{
        if (isFlushingIndex) {
                if (index_Content) {
                        [self cancelClosingLogIndex];
                        [self performSelector:@selector(finishClosingIndex)
                                           withObject:nil
                                           afterDelay:30];
                }

        } else {
                //No writing or opening/closing while we call SKIndexClose()
                [logWritingLock lockWhenCondition:AIIndexFileAvailable];
                [logClosingLock lockWhenCondition:AIIndexFileAvailable];
                
                AILogWithSignature(@"finishClosingIndex: %p",index_Content);
                
                if (index_Content) {
                        SKIndexClose(index_Content);
                        index_Content = nil;
                }
                
                [logWritingLock unlockWithCondition:AIIndexFileAvailable];
                [logClosingLock unlockWithCondition:AIIndexFileAvailable];
        }
}
        
- (void)cancelClosingLogIndex
{
        AILogWithSignature(@"Canceled closing");
        [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(finishClosingIndex) object:nil];
}

- (void)flushIndex:(SKIndexRef)inIndex
{
    NSAutoreleasePool   *pool = [[NSAutoreleasePool alloc] init];
        [logWritingLock lockWhenCondition:AIIndexFileIsClosing];
        if (inIndex) {
                AILogWithSignature(@"**** Flushing index %p",inIndex);
                CFRetain(inIndex);
                SKIndexFlush(inIndex);
                CFRelease(inIndex);
                AILogWithSignature(@"**** Finished flushing index %p, and released it",inIndex);
        }
        [logWritingLock unlockWithCondition:AIIndexFileAvailable];

        [pool release];
}

//Close the log index
- (void)closeLogIndex
{
        if (isFlushingIndex) {
                if (index_Content) {
                        AILogWithSignature(@"Still flushing... will try again in 30 seconds");
                        [self cancelClosingLogIndex];
                        [self performSelector:@selector(finishClosingIndex)
                                           withObject:nil
                                           afterDelay:30];
                }
                
        } else {
                [logWritingLock lockWhenCondition:AIIndexFileAvailable];
                
                if (index_Content) {
                        AILogWithSignature(@"Triggerring the flushIndex thread and queuing index closing");
                        
                        [[AILoggerPlugin operationQueue] addOperation:
                         [[NSInvocationOperation alloc] initWithTarget:self
                                                                                                  selector:@selector(flushIndex:)
                                                                                                        object:(id)index_Content]];
                        
                        [self cancelClosingLogIndex];
                        [self performSelector:@selector(finishClosingIndex)
                                           withObject:nil
                                           afterDelay:30];
                }
                
                /* Note that we're waiting on the index file to close.  An attempt to open the index file before
                 * it closes will return nil and make us think that we have a corrupt index file.
                 */
                [logWritingLock unlockWithCondition:AIIndexFileIsClosing];
        }
}

//Delete the log index
- (void)resetLogIndex
{
        if ([[NSFileManager defaultManager] fileExistsAtPath:[self _logIndexPath]]) {
                [[NSFileManager defaultManager] removeItemAtPath:[self _logIndexPath] error:NULL];
        }       

        if ([[NSFileManager defaultManager] fileExistsAtPath:[self _dirtyLogSetPath]]) {
                [[NSFileManager defaultManager] removeItemAtPath:[self _dirtyLogSetPath] error:NULL];
        }
}

//Path of log index file
- (NSString *)_logIndexPath
{
    return [[adium cachesPath] stringByAppendingPathComponent:LOG_INDEX_NAME];
}


//Dirty Log Array ------------------------------------------------------------------------------------------------------
//Stores the absolute paths of logs that need to be re-indexed
#pragma mark Dirty Log Set
//Load the dirty log set
- (void)loadDirtyLogSet
{
        if ([dirtyLogSet count] == 0) {
                NSInteger logVersion = [[adium.preferenceController preferenceForKey:KEY_LOG_INDEX_VERSION
                                                                                                                                   group:PREF_GROUP_LOGGING] integerValue];

                //If the log version has changed, we reset the index and don't load the dirty set (So all the logs are marked dirty)
                if (logVersion >= CURRENT_LOG_VERSION) {
                        [dirtyLogLock lock];
                        [dirtyLogSet addObjectsFromArray:[NSArray arrayWithContentsOfFile:[self _dirtyLogSetPath]]];
                        AILogWithSignature(@"Loaded dirty log set with %i logs",[dirtyLogSet count]);
                        [dirtyLogLock unlock];
                } else {
                        AILogWithSignature(@"**** Log version upgrade. Resetting");
                        [self resetLogIndex];
                        [adium.preferenceController setPreference:[NSNumber numberWithInteger:CURRENT_LOG_VERSION]
                                                             forKey:KEY_LOG_INDEX_VERSION
                                                              group:PREF_GROUP_LOGGING];
                }
        }
}

//Save the dirty lod set
- (void)_saveDirtyLogSet
{
    if ([dirtyLogSet count] > 0 && !suspendDirtySetSaving) {
                [dirtyLogLock lock];
                [[dirtyLogSet allObjects] writeToFile:[self _dirtyLogSetPath] atomically:NO];
                [dirtyLogLock unlock];
    }
}

//Path of the dirty log set file
- (NSString *)_dirtyLogSetPath
{
    return [[adium cachesPath] stringByAppendingPathComponent:DIRTY_LOG_SET_NAME];
}


//Threaded Indexing ----------------------------------------------------------------------------------------------------
#pragma mark Threaded Indexing
//Stop any indexing related threads
- (void)stopIndexingThreads
{
    //Let any indexing threads know it's time to stop, and wait for them to finish.
    stopIndexingThreads = YES;
}

//The following methods will be run in a separate thread to avoid blocking the interface during index operations
//THREAD: Flag every log as dirty (Do this when there is no log index)
- (void)dirtyAllLogs
{
    //Reset and rebuild the dirty set
        [dirtyLogLock lock];
    [dirtyLogSet removeAllObjects];
        [dirtyLogLock unlock];
        //[self _dirtyAllLogsThread];
        [[AILoggerPlugin operationQueue] addOperation:[[NSInvocationOperation alloc]
                                                                                                   initWithTarget:self
                                                                                                   selector:@selector(_dirtyAllLogsThread)
                                                                                                   object:nil]];
}
- (void)_dirtyAllLogsThread
{
    NSAutoreleasePool   *pool = [[NSAutoreleasePool alloc] init];

    [indexingThreadLock lock];
    suspendDirtySetSaving = YES;    //Prevent saving of the dirty set until we're finished building it
    
    //Create a fresh dirty log set
    [dirtyLogLock lock];
    [dirtyLogSet removeAllObjects];
        AILogWithSignature(@"Dirtying all logs.");
    [dirtyLogLock unlock];
        
    //Process each from folder
        NSArray *fromNames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self logBasePath]
                                                                                                                                                         error:NULL];

    for (NSString *fromName in fromNames) {
                AILogFromGroup *fromGroup = fromGroup = [[AILogFromGroup alloc] initWithPath:fromName fromUID:fromName serviceClass:nil];

                //Walk through every 'to' group
                for (AILogToGroup *toGroup in [fromGroup toGroupArray]) {
                        NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init];
                        //Walk through every log
                        for (AIChatLog *theLog in [toGroup logEnumerator]) {
                                //Add this log's path to our dirty set.  The dirty set is guarded with a lock
                                //since it will be accessed from outside this thread as well
                                [dirtyLogLock lock];
                                if (theLog != nil) {
                                        [dirtyLogSet addObject:[logBasePath stringByAppendingPathComponent:[theLog relativePath]]];
                                }
                                [dirtyLogLock unlock];
                        }
                        
                        //Flush our pool
                        [innerPool release];
                }
                
                [fromGroup release];
    }
        
        AILogWithSignature(@"Finished dirtying all logs");
        
    //Save the dirty set we just built
        [self _saveDirtyLogSet];
        suspendDirtySetSaving = NO; //Re-allow saving of the dirty set
    
    //Begin cleaning the logs (If the log viewer is open)
    if (!stopIndexingThreads && [AILogViewerWindowController existingWindowController]) {
                [self cleanDirtyLogs];
    }
    
    [indexingThreadLock unlock];
    [pool release];
}

/*!
 * @brief Index all dirty logs
 *
 * Indexing will occur on a thread
 */
- (void)cleanDirtyLogs
{
        //Do nothing if we're paused
        if (logIndexingPauses) return;

    //Reset the cleaning progress
    [dirtyLogLock lock];
    logsToIndex = [dirtyLogSet count];
    [dirtyLogLock unlock];
    logsIndexed = 0;
        AILogWithSignature(@"cleanDirtyLogs: logsToIndex is %i",logsToIndex);
        if (logsToIndex > 0) {
                [[AILoggerPlugin operationQueue] addOperation:
                 [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_cleanDirtyLogsThread:) object:(id)[self logContentIndex]]];
        }
}

- (void)didCleanDirtyLogs
{
        [dirtyLogLock lock];
    logsToIndex = [dirtyLogSet count];
    [dirtyLogLock unlock];

        [[AILogViewerWindowController existingWindowController] logIndexingProgressUpdate];

        //Clear the dirty status of all open chats so they will be marked dirty if they receive another message
        for (AIChat *chat in adium.chatController.openChats) {
                NSString *existingAppenderPath = [[self existingAppenderForChat:chat] path];
                if (existingAppenderPath) {
                        NSString *dirtyKey = [@"LogIsDirty_" stringByAppendingString:existingAppenderPath];

                        if ([chat integerValueForProperty:dirtyKey]) {
                                [chat setValue:nil
                                   forProperty:dirtyKey
                                                notify:NotifyNever];
                        }
                }
        }
}

- (void)pauseIndexing
{
        if (logsToIndex) {
                [self stopIndexingThreads];
                logsToIndex = 0;
                logIndexingPauses++;
                AILogWithSignature(@"Pausing %i",logIndexingPauses);
        }
}

- (void)resumeIndexing
{
        if (logIndexingPauses)
                logIndexingPauses--;
        AILogWithSignature(@"Told to resume; log indexing paauses is now %i",logIndexingPauses);
        if (logIndexingPauses == 0) {
                stopIndexingThreads = NO;
                [self cleanDirtyLogs];
        }
}

- (void)_cleanDirtyLogsThread:(SKIndexRef)searchIndex
{
    NSAutoreleasePool   *pool = [[NSAutoreleasePool alloc] init];

        [indexingThreadLock lock];

        //If log indexing was already in progress, we can just cancel since it is now complete
        if (logsToIndex == 0) {
                [indexingThreadLock unlock];
                AILogWithSignature(@"Nothing to clean!");
                [self performSelectorOnMainThread:@selector(didCleanDirtyLogs)
                                                           withObject:nil
                                                        waitUntilDone:NO];
                [pool release];
                return;
        }

        if (!searchIndex) {
                [indexingThreadLock unlock];
                AILogWithSignature(@"*** Warning: Called -[%@ _cleanDirtyLogsThread:] with a NULL searchIndex. That shouldn't happen!", self);
                [pool release];
                return;
        }

        CFRetain(searchIndex);
    logsIndexed = 0;

    //Start cleaning (If we're still supposed to go)
    if (!stopIndexingThreads) {
                UInt32  lastUpdate = TickCount();
                NSInteger               unsavedChanges = 0;

                AILogWithSignature(@"Cleaning %i dirty logs", [dirtyLogSet count]);

                //Scan until we're done or told to stop
                while (!stopIndexingThreads) {
                        NSString        *logPath = nil;
                        
                        //Get the next dirty log
                        [dirtyLogLock lock];
                        if ([dirtyLogSet count]) {
                                logPath = [[[dirtyLogSet anyObject] retain] autorelease]; //retain to prevent deallocation when removing from the set
                                [dirtyLogSet removeObject:logPath];
                        }
                        [dirtyLogLock unlock];

                        if (logPath) {
                                SKDocumentRef   document;
                                
                                document = SKDocumentCreateWithURL((CFURLRef)[NSURL fileURLWithPath:logPath]);
                                if (document) {
                                        /* We _could_ use SKIndexAddDocument() and depend on our Spotlight plugin for importing.
                                         * However, this has three problems:
                                         *      1. Slower, especially to start initial indexing, which is the most common use case since the log viewer
                                         *         indexes recently-modified ("dirty") logs when it opens.
                                         *  2. Sometimes logs don't appear to be associated with the right URI type and therefore don't get indexed.
                                         *  3. On 10.3, this means that logs' markup is indexed in addition to their text, which is undesireable.
                                         */
                                        CFStringRef documentText = CopyTextContentForFile(NULL, (CFStringRef)logPath);
                                        if (documentText) {
                                                SKIndexAddDocumentWithText(searchIndex,
                                                                                                   document,
                                                                                                   documentText,
                                                                                                   YES);
                                                CFRelease(documentText);
                                        }
                                        CFRelease(document);
                                } else {
                                        AILogWithSignature(@"Could not create document for %@ [%@]",logPath,[NSURL fileURLWithPath:logPath]);
                                }
                                
                                //Update our progress
                                logsIndexed++;
                                if (lastUpdate == 0 || TickCount() > lastUpdate + LOG_INDEX_STATUS_INTERVAL) {
                                        [[AILogViewerWindowController existingWindowController]
                                            performSelectorOnMainThread:@selector(logIndexingProgressUpdate) 
                                                             withObject:nil
                                                          waitUntilDone:NO];
                                        lastUpdate = TickCount();
                                }
                                
                                //Save the dirty set
                                if (unsavedChanges++ > LOG_CLEAN_SAVE_INTERVAL) {
                                        [self _saveDirtyLogSet];

                                        unsavedChanges = 0;

                                        //Flush ram
                                        [pool release]; pool = [[NSAutoreleasePool alloc] init];
                                }
                                
                        } else {
                                break; //Exit when we run out of logs
                        }
                }
                
                //Save the slimmed down dirty log set
                if (unsavedChanges) {
                        [self _saveDirtyLogSet];
                }

                isFlushingIndex = YES;
                [logWritingLock lockWhenCondition:AIIndexFileAvailable];
                SKIndexFlush(searchIndex);
                AILogWithSignature(@"After cleaning dirty logs, the search index has a max ID of %i and a count of %i",
                          SKIndexGetMaximumDocumentID(searchIndex),
                          SKIndexGetDocumentCount(searchIndex));
                [logWritingLock unlockWithCondition:AIIndexFileAvailable];
                isFlushingIndex = NO;
                
                [self performSelectorOnMainThread:@selector(didCleanDirtyLogs)
                                                           withObject:nil
                                                        waitUntilDone:NO];
    }

        CFRelease(searchIndex);

        [indexingThreadLock unlock];

    [pool release];
}

- (void)_removePathsFromIndexThread:(NSDictionary *)userInfo
{
        NSAutoreleasePool   *pool = [[NSAutoreleasePool alloc] init];

        [indexingThreadLock lock];

        SKIndexRef logSearchIndex = (SKIndexRef)[userInfo objectForKey:@"SKIndexRef"];
        
        for (NSString *logPath in [userInfo objectForKey:@"Paths"]) {
                SKDocumentRef document = SKDocumentCreateWithURL((CFURLRef)[NSURL fileURLWithPath:logPath]);
                if (document) {
                        SKIndexRemoveDocument(logSearchIndex, document);
                        CFRelease(document);
                }
        }

        [indexingThreadLock unlock];

        [pool release];
}

- (void)removePathsFromIndex:(NSSet *)paths
{
        [[AILoggerPlugin operationQueue] addOperation:[[NSInvocationOperation alloc]
                                                                                                   initWithTarget:self
                                                                                                   selector:@selector(_removePathsFromIndexThread:)
                                                                                                   object:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                                                                   (id)[self logContentIndex], @"SKIndexRef",
                                                                                                                   paths, @"Paths",
                                                                                                                   nil]]];
}


@end