This repository has been archived by the owner on Mar 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathKopeteChatRenderer.py
executable file
·207 lines (162 loc) · 5.4 KB
/
KopeteChatRenderer.py
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
#!/usr/bin/python
##############################################################################
#
# Copyright (C) 2005-2007 Kevin Deldycke <[email protected]>
#
# 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 getopt, sys, os
from datetime import datetime
from xml.dom import Node
from xml.dom.ext.reader import PyExpat
def usage():
print """Usage : kopete_log [options]
** Input/Output options
-i [input_file], --input=[input_file]
The XML kopete log file where the chat is extracted.
Default location: ~/.kde/share/apps/kopete/logs/XXXProtocol/ID/ID.YYYYMM.xml
** Sorting options [default: --ascending]
-a, --ascending
Ascending sorting of messages.
-d, --descending
Descending sorting of messages.
** General options
--silent
No informations will be printed on the standard output.
-h, --help
Show this screen.
"""
def output(string):
if not silent:
print string
def getFileContent(file_path):
# Verify that the file exist
if not os.path.isfile(file_path):
output("ERROR: " + file_path + " doesn't exist.")
return None
# Get file content
file_path = os.path.abspath(file_path)
file_object = open(file_path, 'r')
return file_object.read()
def getKopeteHistory(xml_string):
# Create the PyExpat reader
reader = PyExpat.Reader()
# Create DOM tree from the xml string
dom_tree = reader.fromString(xml_string)
# Check the type of the file
if dom_tree.doctype.name != 'kopete-history':
output("ERROR: " + file_path + " is not a kopete chat history file.")
return None
dom_root = dom_tree.documentElement
# Get month and year
year = None
month = None
headers = dom_root.getElementsByTagName("head")
for header_item in headers[0].childNodes:
if header_item.nodeName == 'date':
for attribute in header_item.attributes:
if attribute.nodeName == 'year':
year = int(attribute.nodeValue)
if attribute.nodeName == 'month':
month = int(attribute.nodeValue)
# Get all the messages
history = []
message_list = dom_root.getElementsByTagName("msg")
for message in message_list:
msg_item = {}
for attribute in message.attributes:
if attribute.nodeName == 'from':
msg_item['user'] = attribute.nodeValue
if attribute.nodeName == 'time':
raw_str = attribute.nodeValue.split(' ')
day = int(raw_str[0])
time = raw_str[1].split(':')
hour = int(time[0])
minute = int(time[1])
second = int(time[2])
msg_item['date'] = datetime(year, month, day, hour, minute, second)
for k in range(message.childNodes.length):
text = message.childNodes[k]
if text.nodeType == Node.TEXT_NODE:
msg_item['text'] = text.nodeValue
history.append(msg_item)
return history
def sortHistory(dict, sort='ASC'):
def datetimeCmp(a, b):
datetime_a = a['date']
datetime_b = b['date']
if datetime_a > datetime_b:
return 1
if datetime_a < datetime_b:
return -1
else:
return 0
if sort == 'DESC':
history.sort(lambda a, b: datetimeCmp(b, a))
else:
history.sort(lambda a, b: datetimeCmp(a, b))
return history
def renderHistory(history, sep='|'):
string = ''
# Get the lenght of the longuest user name
max_lenght = 0
for message in history:
name_len = len(message['user'])
if name_len > max_lenght:
max_lenght = name_len
# Render the chat
sep = ' ' + sep + ' '
for message in history:
string += sep.join([ str(message['date'])
, message['user'].ljust(max_lenght)
, message['text']
]) + '\n'
return string
if __name__ == "__main__":
# Get all parameters
try:
opts, args = getopt.getopt(sys.argv[1:], "hadi:", ["help", "ascending", "descending", "input=", "silent"])
except getopt.GetoptError:
# print help information and exit:
usage()
sys.exit(2)
# Get all user's options and define internal variables
global silent
input_file = None
silent = False
sort = 'ASC'
for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-d", "--descending"):
sort = 'DESC'
if o == "--silent":
silent = True
if o in ("-i", "--input"):
input_file = a
if input_file == None:
print "No input file found."
# TODO : Try to get the file automatically
usage()
sys.exit()
xml_string = getFileContent(input_file)
if xml_string == None:
sys.exit()
history = getKopeteHistory(xml_string)
history = sortHistory(history, sort)
output_string = renderHistory(history)
print output_string.encode('latin-1')