File: Logger.py

package info (click to toggle)
emesene 1.0-dist-4
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 4,596 kB
  • ctags: 3,006
  • sloc: python: 25,171; makefile: 14; sh: 1
file content (1008 lines) | stat: -rw-r--r-- 36,357 bytes parent folder | download
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
# -*- coding: utf-8 -*-

'''Logger module, contains the Logger class and a test case'''

#   This file is part of emesene.
#
#    Emesene 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.
#
#    Emesene 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 emesene; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
#    USA

import os
import gtk
import sys
import time
import urllib
import gobject
import StringIO

import dialog
import emesenelib.common
from htmltextview import HtmlTextView

try:
    from pysqlite2 import dbapi2 as sqlite
except ImportError:
    try:
        import sqlite3.dbapi2 as sqlite 
        #Python 2.5 comes embedded with sqlite
        print 'sqlite3 imported'
    except ImportError:
        sqlite = None
        
import Plugin

class Logger(object):
    '''this class represent a event logger for conversations
    its made for emesene but can be used on any other im application
    or similar'''

    CREATE_USER = '''
    CREATE TABLE user
    (
        id INTEGER PRIMARY KEY,
        account TEXT
 )
    '''

    CREATE_CONVERSATION = '''
    CREATE TABLE conversation
    (
        id INTEGER PRIMARY KEY,
        started INTEGER
 )
    '''

    CREATE_EVENT = '''
    CREATE TABLE event
    (
        id INTEGER PRIMARY KEY,
        stamp INTEGER,
        name TEXT
 )
    '''

    CREATE_USER_EVENT = '''
    CREATE TABLE user_event
    (
        id_event INTEGER,
        id_user INTEGER,
        data TEXT
 )
    '''

    CREATE_CONVERSATION_EVENT = '''
    CREATE TABLE conversation_event
    (
        id_event INTEGER,
        id_conversation INTEGER,
        id_user INTEGER,
        data TEXT
 )
    '''

    USER_EXISTS = 'SELECT id FROM user WHERE account = ?'
    USER_ADD = 'INSERT INTO user(id, account) VALUES(null, ?)'

    USER_EVENT_ADD = '''INSERT INTO user_event(id_event, id_user, data)
        VALUES(?, ?, ?)'''

    EVENT_ADD = 'INSERT INTO event(id, stamp, name) VALUES(null, ?, ?)'

    CONVERSATION_EVENT_ADD = '''INSERT INTO conversation_event(
        id_event, id_conversation, id_user, data) VALUES(?, ?, ?, ?)'''

    CONVERSATION_EXISTS = 'SELECT id FROM conversation WHERE started = ?'
    CONVERSATION_ADD = 'INSERT INTO conversation(id, started) \
                        VALUES(null, ?)'

    def __init__(self, path):
        '''constructor, try to open the database at path, if can not open
        it, then try to create it'''
    
        self.path = path

        if sqlite is None:
            return

        self.connection = sqlite.connect(path)
        self.cursor = self.connection.cursor()
        
        try:
            self._create()
        except sqlite.OperationalError:
            pass

    def _create(self):
        '''create the tables'''

        self.cursor.execute(Logger.CREATE_USER)
        self.cursor.execute(Logger.CREATE_CONVERSATION)
        self.cursor.execute(Logger.CREATE_EVENT)
        self.cursor.execute(Logger.CREATE_USER_EVENT)
        self.cursor.execute(Logger.CREATE_CONVERSATION_EVENT)
        self.connection.commit()
        
    def user_exists(self, account):
        '''return the user id if the account exists -1 otherwise'''

        self.cursor.execute(Logger.USER_EXISTS, (account,))

        result = self.cursor.fetchall() 
        if len(result) >= 1:
            return result[0][0]
        else:
            return -1

    def user_add(self, account):
        '''try to add an user if account exists don't add it,
        return the id in both cases'''

        user_id = self.user_exists(account)

        if user_id == -1:
            self.cursor.execute(Logger.USER_ADD, (account,))
            self.connection.commit()
            return self.cursor.lastrowid

        return user_id

    def user_event_add(self, name, account, data, stamp=None):
        '''add a user event with the event name "name", generated by
        "account" and containing "data", return the id'''

        user_id = self.user_add(account)
        event_id = self.event_add(name, stamp)
        self.cursor.execute(Logger.USER_EVENT_ADD, (event_id, 
                             user_id, data))
        self.connection.commit()
        return self.cursor.lastrowid

    def event_add(self, name, stamp=None):
        '''add an event with name "name", return the id'''
        if stamp is None:
            stamp = time.time()
        self.cursor.execute(Logger.EVENT_ADD, (stamp, name))
        self.connection.commit()
        return self.cursor.lastrowid

    def conversation_event_add(self, name, started, account, data, stamp=None):
        '''add a conversation event with name "name" started at the
        "started" time, with data "data", return the id'''

        conversation_id = self.conversation_add(started)
        event_id = self.event_add(name, stamp)
        user_id = self.user_add(account)
        self.cursor.execute(Logger.CONVERSATION_EVENT_ADD, (event_id,
                                conversation_id, user_id, data))
        self.connection.commit()
        return self.cursor.lastrowid

    def conversation_exists(self, started):
        '''return the id of the conversation if exists, -1 otherwise'''

        self.cursor.execute(Logger.CONVERSATION_EXISTS, (started,))

        result = self.cursor.fetchall() 
        if len(result) >= 1:
            return result[0][0]
        else:
            return -1

    def conversation_add(self, started):
        '''try to add a conversation if exists don't add it,
        return the id in both cases'''

        conversation_id = self.conversation_exists(started)

        if conversation_id == -1:
            self.cursor.execute(Logger.CONVERSATION_ADD, (started,))
            self.connection.commit()
            return self.cursor.lastrowid

        return conversation_id

    def get_mails(self):
        '''return a list of unique mails found on the logs'''
        return [item[0] for item in \
         self.query('select distinct account from user order by account')]
    
    def get_events(self):
        '''return a list of unique events found on the logs'''
        return [item[0] for item in \
            self.query('select distinct name from event order by name')]
    
    def get_user_events(self):
        '''return a list of unique user events found on the logs'''
        return [item[0] for item in \
            self.query('select distinct name from event, user_event where \
            id_event = id order by name')]

    def get_nick_stamp(self, contact, timestamp):
        '''get the closest timestamp for a nick change, return None
        if no stamp is available'''

        result = self.query('select e.stamp \
        from event e, user_event ue, user u \
        where ue.id_user = u.id and \
        ue.id_event = e.id and \
        e.stamp < %s and \
        u.account = "%s" and \
        e.name = "nick-changed" \
        order by e.stamp desc limit 1' % (timestamp, contact))

        if len(result) == 0:
            return None

        return result[0][0]

    def get_next_nick_stamp(self, contact, timestamp):
        '''get the timestamp of the next nick change, method used for
        optimization purposes, to not make a query every time we want
        the nick we get the next stamp and compare it against the actual
        one, when we get to that stamp, we get the new nickname,
        return None if no result'''

        result = self.query('select e.stamp \
        from event e, user_event ue, user u \
        where ue.id_user = u.id and \
        ue.id_event = e.id and \
        e.stamp >= %s and \
        u.account = "%s" and \
        e.name = "nick-changed" limit 1' % (timestamp, contact))

        if len(result) == 0:
            return None

        return result[0][0]

    def get_user_nick(self, contact, timestamp):
        '''return the nick that the contact had on the given timestamp
        if no nick found return contact mail'''
        # first we select the closest nick-changed event to the timestamp

        stamp = self.get_nick_stamp(contact, timestamp)

        if stamp is None:
            return contact

        return self.query('select ue.data \
        from user_event ue, event e \
        where e.stamp = %f and \
        ue.id_event = e.id' % (stamp,))[0][0]
    
    def get_conversation_ids(self, account):
        '''return the ids of the conversations where the contact was present'''
        
        query = '''select distinct c.id, c.started 
        from conversation c, event e, conversation_event ce, user u 
        where c.id = ce.id_conversation and 
        e.id = ce.id_event and 
        ce.id_user = u.id and 
        u.account = "%s"
        order by c.started'''

        return self.query(query % (account,))

    def get_conversation(self, id_conversation, num=1):
        '''return the last message that was said on a conversation where
        account was present, the format of the list is a list of lists
        with the timestamp, email and message'''

        query = '''select e.stamp, u.account, ce.data
        from event e, conversation_event ce, user u 
        where e.id = ce.id_event and 
        u.id = ce.id_user and 
        ce.id_conversation = %s and
        e.name = "message" 
        limit %s'''

        return self.query(query % (id_conversation, num))

    def get_conversation_events(self):
        '''return a list of unique conversation events found on the logs'''
        return [item[0] for item in \
            self.query('select distinct name from event, \
            conversation_event where id_event = id order by name')]

    def query(self, query, args=None):
        '''make a custom query, return a tuple with all the results
        the exception are not handled, because you need to know if a
        query went bad on your plugin not this one, so please use 
        try except blocks'''

        #print query

        if args:
            self.cursor.execute(query, args)
        else:
            self.cursor.execute(query)

        return self.cursor.fetchall()

class MainClass(Plugin.Plugin):
    '''Main plugin class'''
    
    def __init__(self, controller, msn):
        '''Contructor'''
        Plugin.Plugin.__init__(self, controller, msn, 1000)
        
        self.description = 'Log all events to a file'
        self.authors = {'Mariano Guerra' : 
            'luismarianoguerra at gmail dot com'}
        self.website = 'http://emesene.org'
        self.displayName =  'Logger'
        self.name = 'Logger'
        
        self.controller = controller
        
        self.config = controller.config
        self.config.readPluginConfig(self.name)
        self.path = self.config.getPluginValue(self.name, 
            'path', self.msn.cacheDir)

        self.file_name = os.path.join(self.path, self.msn.user + '.db')
        self.logger = Logger(self.file_name)
        self.ids = []

        self.signals = {}
        self.signals['self-nick-changed'] = self._cb_self_nick_changed
        self.signals['personal-message-changed'] = \
            self._cb_personal_message_changed
        self.signals['self-status-changed'] = self._cb_self_status_changed
        self.signals['self-personal-message-changed'] = \
            self._cb_self_personal_message_changed
        self.signals['self-current-media-changed'] = \
            self._cb_self_current_media_changed
        self.signals['nick-changed'] = self._cb_nick_changed
        self.signals['contact-status-change'] = \
            self._cb_contact_status_change
        self.signals['initial-status-change'] = \
            self._cb_initial_status_change
        self.signals['user-offline'] = self._cb_user_offline
        self.signals['display-picture-changed'] = \
            self._cb_display_picture_changed

        self.signals['switchboard::message'] = self._cb_sb_message
        self.signals['switchboard::ink-message'] = self._cb_sb_ink_message
        self.signals['switchboard::nudge'] = self._cb_sb_nudge
        self.signals['switchboard::message-sent'] = self._cb_sb_message_sent
        self.signals['switchboard::ink-sent'] = self._cb_sb_ink_message_sent
        self.signals['switchboard::nudge-sent'] = self._cb_sb_nudge_sent
        self.signals['switchboard::action-message'] = \
            self._cb_sb_action_message
        self.signals['switchboard::action-sent'] = \
            self._cb_sb_action_message_sent
        self.signals['switchboard::custom-emoticon-received'] = \
            self._cb_sb_custom_emoticon_received
        
        # functions to be called on mainloop idleness
        self.queued = [] 
        self.queuedtag = 0

        # timeout source to disconect it
        self.to_source = None
        all_events = ','.join(self.signals.keys())

        self.menuItemId = 0
    
    def start(self):
        '''start the plugin'''
        if sqlite is None:
            return
        self.enabled = True
        
        self.events_enabled = []
        for signal in self.signals.keys():
            if bool(int(self.config.getPluginValue( self.name, signal, True ))):
                self.events_enabled.append(signal)
        
        for (key, value) in self.signals.iteritems():
            if key in self.events_enabled:
                self.ids.append(self.msn.connect(key, self.callback, value))
        
        
        self.menuItemId = self.controller.connect("usermenu-item-add", self.add_usermenu_item)

    def stop(self):    
        '''stop the plugin'''
       
        # disconnect msn signals
        for identifier in self.ids:
            self.msn.disconnect(identifier)
        self.ids = []
        
        self.controller.disconnect(self.menuItemId)

        self.enabled = False
        
    def callback(self, *args):  # sorry, pylint, i know you don't like this
        '''Adds the function in the last argument to the queue, to be called
        later when the mainloop is idle. sqlite isn't exactly fast'''

        params, func = args[:-1], args[-1]

        # add the stamp parameter
        params += (time.time(), )

        self.queued.append((func, params))

        # if the process_queue loop is dead, start it
        if self.queuedtag == 0:
            self.queuedtag = gobject.idle_add(self.process_queue)

    def process_queue(self):
        '''Takes the signal queue and calls one function.
        It's called on a idle_add loop. If there are no function, it
        quits the loop returning false and removing the queuedtag'''

        if self.queued:
            func, params = self.queued.pop(0)
            func(*params)
            return True
        else:
            self.queuedtag = 0
            return False
        
    def check(self):
        '''check if everything is OK to start the plugin
        return a tuple whith a boolean and a message
        if OK -> (True , 'some message')
        else -> (False , 'error message')'''
       
        if sqlite is None:
            return (False, 'sqlite not available, please install it.')
        else:
            return (True, 'Ok')
        
    def get_last_status(self, account, num = 1):
        '''return the last status of a contact, if num is > 1
        then return the last num status, the format of the list is
        a list of lists with the timestamp and the status'''

        query = '''
        select e.stamp, ue.data 
        from event e, user_event ue, user u
        where e.id = ue.id_event and
        u.id = ue.id_user and
        e.name = "status-changed" and
        u.account = "%s"
        order by e.stamp desc
        limit %s
        '''

        return self.logger.query(query % (account, num))
            
    def get_last_nick(self, account, num = 1):
        '''return the last nick of a contact, if num is > 1
        then return the last num nicks, the format of the list is
        a list of lists with the timestamp and the nick'''

        query = '''
        select e.stamp, ue.data 
        from event e, user_event ue, user u
        where e.id = ue.id_event and
        u.id = ue.id_user and
        e.name = "nick-changed" and
        u.account = "%s"
        order by e.stamp desc
        limit %s
        '''

        return self.logger.query(query % (account, num))
            
    def get_last_personal_message(self, account, num = 1):
        '''return the last pm of a contact, if num is > 1
        then return the last num pms, the format of the list is
        a list of lists with the timestamp and the pm'''

        query = '''
        select e.stamp, ue.data 
        from event e, user_event ue, user u
        where e.id = ue.id_event and
        u.id = ue.id_user and
        e.name = "personal-message-changed" and
        u.account = "%s"
        order by e.stamp desc
        limit %s
        '''

        return self.logger.query(query % (account, num))

    def get_just_last_personal_message(self, account):
        '''return the last personal message as a string or 
        None rather than a list'''

        result = self.get_last_personal_message(account)

        if result:
            return result[0][1]

        return None
    
    def get_just_last_nick(self, account):
        '''return the last nick as a string or 
        None rather than a list'''

        result = self.get_last_nick(account)

        if result:
            return result[0][1]

        return None
    
    def get_just_last_status(self, account):
        '''return the last status as a string or 
        None rather than a list'''

        result = self.get_last_status(account)

        if result:
            return result[0][1]

        return None
    
    def get_last_message(self, account, num = 1):
        '''return the last message of a contact, if num is > 1
        then return the last num messages, the format of the list is
        a list of lists with the timestamp and the message'''

        query = '''
        select e.stamp, ce.data 
        from event e, conversation_event ce, user u
        where e.id = ce.id_event and
        u.id = ce.id_user and
        e.name = "message" and
        u.account = "%s"
        order by e.stamp desc
        limit %s
        '''

        return self.logger.query(query % (account, num))
            
    def get_last_display_picture(self, account, num = 1):
        '''return the last dp of a contact, if num is > 1
        then return the last num dps, the format of the list is
        a list of lists with the timestamp and the dp'''

        query = '''
        select e.stamp, ue.data 
        from event e, user_event ue, user u
        where e.id = ue.id_event and
        u.id = ue.id_user and
        e.name = "display-picture" and
        u.account = "%s"
        order by e.stamp desc
        limit %s
        '''

        return self.logger.query(query % (account, num))
    
    def get_last_custom_emoticon(self, account, num = 1):
        '''return the last ce of a contact, if num is > 1
        then return the last num ces, the format of the list is
        a list of lists with the timestamp and the ce'''

        query = '''
        select e.stamp, ce.data 
        from event e, conversation_event ce, user u
        where e.id = ce.id_event and
        u.id = ce.id_user and
        e.name = "custom-emoticon" and
        u.account = "%s"
        order by e.stamp desc
        limit %s
        '''

        return self.logger.query(query % (account, num))

    def get_last_conversation(self, account, num = 1):
        '''return the last message that was said on a conversation where
        account was present, the format of the list is a list od lists
        with the timestamp, email and message'''

        # in the inner select we select all the id of conversations
        # where account was present, then on the outer conversation
        # we select all the messages from that conversations
        query = '''
        select e.stamp, u.account, ce.data
        from event e, conversation_event ce, user u 
        where e.id = ce.id_event and 
        u.id = ce.id_user and 
        ce.id_conversation in 
        (select distinct c.id 
        from conversation c, event e, conversation_event ce, user u 
        where c.id = ce.id_conversation and 
        e.id = ce.id_event and 
        ce.id_user = u.id and 
        u.account = "%s") and 
        e.name = "message" 
        order by e.stamp desc
        limit %s
        '''

        return self.logger.query(query % (account, num))

    def add_usermenu_item(self, controller, userMenu):
        self.logMenuItem = userMenu.newImageMenuItem( _( "View conversation _log" ),
            gtk.STOCK_FILE )
        userMenu.add( self.logMenuItem )
        self.logMenuItem.show()
        self.logMenuItem.connect( 'activate', self.on_menuitem_activate, userMenu.user.email )

    def on_menuitem_activate(self, widget, email):
        self.window = gtk.Window()
        self.window.set_border_width(5)
        self.window.set_title(_("Conversation log for %s" % email))
        self.window.set_default_size(650,350)
        
        textview = gtk.TextView()
        self.textBuffer = textview.get_buffer()
        
        scroll = gtk.ScrolledWindow()
        scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        
        self.textview = HtmlTextView(self.controller, self.textBuffer, scroll)
        self.textview.set_wrap_mode(gtk.WRAP_WORD_CHAR)
        self.textview.set_left_margin(6)
        self.textview.set_right_margin(6)
        self.textview.set_editable(False)
        self.textview.set_cursor_visible(False)
        
        scroll.add_with_viewport(self.textview)
        
        hbox = gtk.HBox(False, 5)
        saveButton = gtk.Button(stock=gtk.STOCK_SAVE)
        saveButton.connect("clicked", self.on_save_logs)
        
        refreshButton = gtk.Button(stock=gtk.STOCK_REFRESH)
        refreshButton.connect("clicked", self.on_refresh_log, email)
        
        closeButton = gtk.Button(stock=gtk.STOCK_CLOSE)
        closeButton.connect("clicked", lambda w: self.window.hide())
        
        hbox.pack_end(saveButton, False, False)
        hbox.pack_end(refreshButton, False, False)
        hbox.pack_end(closeButton, False, False)
        
        textRenderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("Date"), textRenderer, markup=0)
        self.datesListstore = gtk.ListStore(str)
        
        self.datesTree = gtk.TreeView(self.datesListstore)
        self.datesTree.connect("cursor-changed", self.on_dates_cursor_change)
        self.datesTree.append_column(column)
        self.datesTree.set_headers_visible(False)
        
        datesScroll = gtk.ScrolledWindow()
        datesScroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        datesScroll.add_with_viewport(self.datesTree)
        datesScroll.set_size_request(210, -1)
        
        hPaned = gtk.HPaned()
        hPaned.pack1(datesScroll)
        hPaned.pack2(scroll)
        
        vbox = gtk.VBox(spacing=5)
        vbox.pack_start(hPaned)
        vbox.pack_start(hbox, False, False)
        vbox.pack_start(gtk.Statusbar(), False, False)
        
        self.datesStamps = {}
        logsCant = len(self.fill_dates_tree(email))
        if not logsCant > 0:
            dialog.information(_("No logs were found for %s" % (email) ))
        else:
            self.window.add(vbox)
            self.window.show_all()
    
    def fill_dates_tree(self, mail):
        '''fill the treeview with the logs dates'''
        for (id_conversation, stamp) in self.logger.get_conversation_ids(mail):
            ctime = str(time.ctime(float(stamp)))
            self.datesListstore.append([ctime])
            self.datesStamps[ctime] =  id_conversation
        
        return self.datesStamps
    
    def on_dates_cursor_change(self, *args):
        try:
            selected = self.datesListstore.get(
                self.datesTree.get_selection().get_selected()[1], 0)[0]
        except (TypeError, AttributeError):
            return

        id_conversation = self.datesStamps[selected]
        put_new_line = False
        nick_cache = {}
        self.textview.get_buffer().set_text("")
        
        for (stamp, mail, message) in \
             self.logger.get_conversation(id_conversation, 10000):

            if mail in nick_cache:
                if nick_cache[mail]['next'] is not None and \
                    nick_cache[mail]['next'] <= stamp:
                    nick = self.logger.get_user_nick(mail, stamp)
                    next = self.logger.get_next_nick_stamp(mail, stamp) 
                    nick_cache[mail] = {'nick': nick, 'next' : next}
                else:
                    nick = nick_cache[mail]['nick']
            else:
                nick = self.logger.get_user_nick(mail, stamp)
                next = self.logger.get_next_nick_stamp(mail, stamp) 
                nick_cache[mail] = {'nick': nick, 'next' : next}
                
            date = time.ctime(float(stamp))
            (_format, encoding, text) = message.split('\r\n', 2)
            style = parse_format(_format)
            nick = self.controller.unifiedParser.getParser(nick).get()
            text = self.controller.unifiedParser.getParser(text).get()
            text = text.replace("\r\n", "\n").replace("\n", "<br />")

            try:
                self.textview.display_html('<body><b>%s: </b>'
                    '<span style="%s">%s</span></body>' % (nick, style, text))
            except:
                # hide messages that we can't display
                pass
            put_new_line = True
    
    
    def on_save_logs(self, button):
    
        title = (_("Save conversation log"))
    
        dialog = gtk.FileChooserDialog(title, None, \
                                gtk.FILE_CHOOSER_ACTION_SAVE, \
                                (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, \
                                gtk.STOCK_SAVE, gtk.RESPONSE_OK))
        
        dialog.set_default_response(gtk.RESPONSE_OK)
        dialog.show_all()
        
        response = dialog.run()
        
        while True:    
            if response != gtk.RESPONSE_OK:
                break
                
            if dialog.get_filename():
                path = dialog.get_filename()
                f = open(path, "w")
                f.write(self.textBuffer.get_text(self.textBuffer.get_start_iter(),\
                      self.textBuffer.get_end_iter() ))
                f.close()
                
                break
                
        
        dialog.hide()
    
    def on_refresh_log(self, button, email):
        self.on_dates_cursor_change()
    
    def _cb_self_nick_changed(self, msn, old, new, stamp=None):
        '''called when we change our own nick'''
        if new != self.get_last_nick(self.msn.user):
            self.logger.user_event_add('nick-changed', self.msn.user,
                                        new, stamp)

    def _cb_personal_message_changed(self, msn, email, personal_message,
                                     stamp=None):
        '''called when an user changes the personal message'''
        
        if personal_message != '' and \
            self.get_just_last_personal_message(email) != personal_message:
            self.logger.user_event_add('personal-message-changed', email, 
                                        personal_message, stamp)

    def _cb_self_status_changed(self, msn, status, stamp=None):
        '''called when we change the status'''
        if self.get_last_status(msn.user) != status:
            self.logger.user_event_add('status-changed', 
                self.msn.user, status, stamp)

    def _cb_self_personal_message_changed(self, msn, ourmail, 
                                          personal_message, stamp=None):
        '''called when we change our personal message'''
        if personal_message != '' and \
            self.get_just_last_personal_message(ourmail) != personal_message:
            self.logger.user_event_add('personal-message-changed', ourmail, 
                                        personal_message, stamp)

    def _cb_self_current_media_changed(self, msn, ourmail, personal_message,
                                       dict_, stamp=None):
        '''called when we change our current media'''
        if personal_message != '' and \
            self.get_just_last_personal_message(ourmail) != personal_message:
            self.logger.user_event_add('personal-message-changed', ourmail, 
                                        personal_message, stamp)

    def _cb_nick_changed(self, msn, email, nick, stamp=None):
        '''called when someone change his nick'''
        if nick != self.get_last_nick(email):
            self.logger.user_event_add('nick-changed', email, nick, stamp)

    def _cb_contact_status_change(self, msn, email, status, stamp=None):
        '''called when someone change his status'''
        if self.get_last_status(email) != status:
            self.logger.user_event_add('status-changed', email, status, stamp)
    
    def _cb_initial_status_change(self, msn, command, tid, params, stamp=None):
        '''called when someone change his status when we come online'''
        data = params.split(' ')
        status = data[0]
        email = data[1].lower()

        if self.get_last_status(email) != status:
            self.logger.user_event_add('status-changed', email, status, stamp)

    def _cb_user_offline(self, msn, email, stamp=None):
        '''called when someone goes offline'''
        self.logger.user_event_add('status-changed', email, 'FLN', stamp)

    def _cb_sb_user_join(self, msn, switchboard, signal, args, stamp=None):
        '''called when an user join to the conversation'''
        mail = args[0]
        self.logger.conversation_event_add('user-join',  
            switchboard.started, mail, '', stamp)

    def _cb_sb_user_leave(self, msn, switchboard, signal, args, stamp=None):
        '''called when an user leaves the conversation'''
        mail = args[0]
        self.logger.conversation_event_add('user-leave',  
            switchboard.started, mail, '', stamp)

    def _cb_sb_message(self, msn, switchboard, signal, args, stamp=None):
        '''called when we receive a message'''
        mail, nick, body, format, charset = args
        message = '%s\r\n%s\r\n%s' % (format, charset,
            body.replace('\\', '\\\\'))
        self.logger.conversation_event_add('message',  
            switchboard.started, mail, message, stamp)

    def _cb_sb_action_message(self, msn, switchboard, signal, args, stamp=None):
        '''called when an action message is received'''
        mail, data = args
        self.logger.conversation_event_add('action-message', 
            switchboard.started, mail, data, stamp)

    def _cb_sb_ink_message(self, msn, switchboard, signal, args, stamp=None):
        '''called when an ink message is received'''
        signal, filename = args
        self.logger.conversation_event_add('ink-message', 
            switchboard.started, mail, filename, stamp)

    def _cb_sb_nudge(self, msn, switchboard, signal, args, stamp=None):
        '''called when a nudge is received'''
        mail = args[0]
        self.logger.conversation_event_add('nudge', switchboard.started,
            mail, '', stamp)

    def _cb_sb_message_sent(self, msn, switchboard, signal, args, stamp=None):
        '''called when we send a message'''
        body, format, charset = args
        try:
            format = format.split('X-MMS-IM-Format: ')[1]
        except IndexError:
            format = ''
        message = '%s\r\n%s\r\n%s' % (format, charset, body)
        self.logger.conversation_event_add('message',  
            switchboard.started, self.msn.user, message, stamp)

    def _cb_sb_action_message_sent(self, msn, switchboard, signal,
                                   args, stamp=None):
        '''called when an action message is received'''
        data = args[0]
        self.logger.conversation_event_add('action-message', 
            switchboard.started, self.msn.user, data, stamp)

    def _cb_sb_ink_message_sent(self, msn, switchboard, signal,
                                args, stamp=None):
        '''called when an ink message is sent'''
        self.logger.conversation_event_add('ink-message',  
            switchboard.started, self.msn.user, '', stamp)

    def _cb_sb_nudge_sent(self, msn, switchboard, signal, args, stamp=None):
        '''called when a nudge is sent'''
        self.logger.conversation_event_add('nudge', 
            switchboard.started, self.msn.user, '', stamp)

    def _cb_sb_custom_emoticon_received(self, msn, switchboard, signal,
                                        args, stamp=None):
        '''called when a custom emoticon is received (du'h)'''
        shortcut, msnobj = args
        filename = shortcut + '_' + msnobj.sha1d + '.tmp'
        filename = urllib.quote(filename).replace('/', '_')
        complete_filename = self.msn.cacheDir + os.sep + filename
        self.logger.conversation_event_add('custom-emoticon', 
            switchboard.started, self.msn.user, 
            shortcut + ' ' + complete_filename, stamp)

    def _cb_display_picture_changed(self, msn, switchboard, msnobj, mail,
                                    stamp=None):
        '''called when a new display picture is received'''
        contact = self.msn.contactManager.getContact(mail)
        if contact is None:
            return
        filename = contact.displayPicturePath

        result = self.get_last_display_picture(mail)

        if result:
            old_filename = result[0][1]
        else:
            old_filename = None

        if old_filename != filename:
            self.logger.user_event_add('display-picture', mail, \
                                       filename, stamp)
    

    def configure( self ):
        configuration = []
        configuration.append(Plugin.Option('', gtk.Widget, '', '', gtk.Label("Enable/disable events")))
        for signal in self.signals:
            configuration.append(Plugin.Option(signal, bool, signal.replace('-',' '), \
            '', bool(int(self.config.getPluginValue(self.name, signal, True)))))
        
        configWindow = Plugin.ConfigWindow( 'Logger', configuration )
        response = configWindow.run()
        if response != None:
            for signal in self.signals:
                if response.has_key(signal):
                    self.config.setPluginValue( self.name, signal, str(int(response[signal].value)) )
            self.stop()
            self.start()
            return True


def parse_format(format):
    '''parse the format and return the style'''

    # FN=Sans; EF=; CO=000000; PF=0
 
    style = ''
 
    if format.find("FN=") != -1:
        font = format.split('FN=')[1].split(';')[0].replace('%20', ' ')
        style += 'font-family: ' + emesenelib.common.escape(font) + ';'

    if format.find("CO=") != -1:
        color = format.split('CO=')[1].split(';')[0]
             
        if len(color) == 3:
            color = color[2] + color[1] + color[0]
            style += 'color: #' + emesenelib.common.escape(color) + ';'
        else:
            color = color.zfill(6)
            
        if len(color) == 6:
            color = color[4:6] + color[2:4] + color[:2]
            style += 'color: #' + emesenelib.common.escape(color) + ';'

    if format.find("EF=") != -1:
        effect = set(format.split('EF=')[1].split(';')[0])

        if "B" in effect: 
            style += 'font-weight: bold;'
        if "I" in effect: 
            style += 'font-style: italic;'
        if "U" in effect: 
            style += 'text-decoration: underline;'
        if "S" in effect: 
            style += 'text-decoration: line-through;'
    
    return style