]> www.wagner.pp.ru Git - oss/ljdump.git/blob - ljdump.py
add some todo entries
[oss/ljdump.git] / ljdump.py
1 #!/usr/bin/python
2 #
3 # ljdump.py - livejournal archiver
4 # Greg Hewgill <greg@hewgill.com> http://hewgill.com
5 # Version 1.2
6 #
7 # $Id$
8 #
9 # This program reads the journal entries from a livejournal (or compatible)
10 # blog site and archives them in a subdirectory named after the journal name.
11 #
12 # The configuration is read from "ljdump.config". A sample configuration is
13 # provided in "ljdump.config.sample", which should be copied and then edited.
14 # The configuration settings are:
15 #
16 #   server - The XMLRPC server URL. This should only need to be changed
17 #            if you are dumping a journal that is livejournal-compatible
18 #            but is not livejournal itself.
19 #
20 #   username - The livejournal user name. A subdirectory will be created
21 #              with this same name to store the journal entries.
22 #
23 #   password - The account password. This password is never sent in the
24 #              clear; the livejournal "challenge" password mechanism is used.
25 #
26 # This program may be run as often as needed to bring the backup copy up
27 # to date. Both new and updated items are downloaded.
28 #
29 # LICENSE
30 #
31 # This software is provided 'as-is', without any express or implied
32 # warranty.  In no event will the author be held liable for any damages
33 # arising from the use of this software.
34 #
35 # Permission is granted to anyone to use this software for any purpose,
36 # including commercial applications, and to alter it and redistribute it
37 # freely, subject to the following restrictions:
38 #
39 # 1. The origin of this software must not be misrepresented; you must not
40 #    claim that you wrote the original software. If you use this software
41 #    in a product, an acknowledgment in the product documentation would be
42 #    appreciated but is not required.
43 # 2. Altered source versions must be plainly marked as such, and must not be
44 #    misrepresented as being the original software.
45 # 3. This notice may not be removed or altered from any source distribution.
46 #
47 # Copyright (c) 2005-2006 Greg Hewgill
48
49 import codecs, md5, os, pickle, pprint, re, sys, urllib2, xml.dom.minidom, xmlrpclib
50 from xml.sax import saxutils
51
52 def calcchallenge(challenge, password):
53     return md5.new(challenge+md5.new(password).hexdigest()).hexdigest()
54
55 def flatresponse(response):
56     r = {}
57     while True:
58         name = response.readline()
59         if len(name) == 0:
60             break
61         if name[-1] == '\n':
62             name = name[:len(name)-1]
63         value = response.readline()
64         if value[-1] == '\n':
65             value = value[:len(value)-1]
66         r[name] = value
67     return r
68
69 def getljsession(username, password):
70     r = urllib2.urlopen(Server+"/interface/flat", "mode=getchallenge")
71     response = flatresponse(r)
72     r.close()
73     r = urllib2.urlopen(Server+"/interface/flat", "mode=sessiongenerate&user=%s&auth_method=challenge&auth_challenge=%s&auth_response=%s" % (username, response['challenge'], calcchallenge(response['challenge'], password)))
74     response = flatresponse(r)
75     r.close()
76     return response['ljsession']
77
78 def dochallenge(params, password):
79     challenge = server.LJ.XMLRPC.getchallenge()
80     params.update({
81         'auth_method': "challenge",
82         'auth_challenge': challenge['challenge'],
83         'auth_response': calcchallenge(challenge['challenge'], password)
84     })
85     return params
86
87 def dumpelement(f, name, e):
88     f.write("<%s>\n" % name)
89     for k in e.keys():
90         if isinstance(e[k], {}.__class__):
91             dumpelement(f, k, e[k])
92         else:
93             s = unicode(str(e[k]), "UTF-8")
94             f.write("<%s>%s</%s>\n" % (k, saxutils.escape(s), k))
95     f.write("</%s>\n" % name)
96
97 def writedump(fn, event):
98     f = codecs.open(fn, "w", "UTF-8")
99     f.write("""<?xml version="1.0"?>\n""")
100     dumpelement(f, "event", event)
101     f.close()
102
103 def createxml(doc, name, map):
104     e = doc.createElement(name)
105     for k in map.keys():
106         me = doc.createElement(k)
107         me.appendChild(doc.createTextNode(map[k]))
108         e.appendChild(me)
109     return e
110
111 def gettext(e):
112     if len(e) == 0:
113         return ""
114     return e[0].firstChild.nodeValue
115
116 config = xml.dom.minidom.parse("ljdump.config")
117 Server = config.documentElement.getElementsByTagName("server")[0].childNodes[0].data
118 Username = config.documentElement.getElementsByTagName("username")[0].childNodes[0].data
119 Password = config.documentElement.getElementsByTagName("password")[0].childNodes[0].data
120
121 m = re.search("(.*)/interface/xmlrpc", Server)
122 if m:
123     Server = m.group(1)
124
125 print "Fetching journal entries for: %s" % Username
126 try:
127     os.mkdir(Username)
128     print "Created subdirectory: %s" % Username
129 except:
130     pass
131
132 ljsession = getljsession(Username, Password)
133
134 server = xmlrpclib.ServerProxy(Server+"/interface/xmlrpc")
135
136 newentries = 0
137 newcomments = 0
138 errors = 0
139
140 lastsync = ""
141 lastmaxid = 0
142 try:
143     f = open("%s/.last" % Username, "r")
144     lastsync = f.readline()
145     if lastsync[-1] == '\n':
146         lastsync = lastsync[:len(lastsync)-1]
147     lastmaxid = f.readline()
148     if len(lastmaxid) > 0 and lastmaxid[-1] == '\n':
149         lastmaxid = lastmaxid[:len(lastmaxid)-1]
150     if lastmaxid == "":
151         lastmaxid = 0
152     else:
153         lastmaxid = int(lastmaxid)
154     f.close()
155 except:
156     pass
157 origlastsync = lastsync
158
159 r = server.LJ.XMLRPC.login(dochallenge({
160     'username': Username,
161     'ver': 1,
162     'getpickws': 1,
163     'getpickwurls': 1,
164 }, Password))
165 userpics = dict(zip(r['pickws'], r['pickwurls']))
166 userpics['*'] = r['defaultpicurl']
167
168 while True:
169     r = server.LJ.XMLRPC.syncitems(dochallenge({
170         'username': Username,
171         'ver': 1,
172         'lastsync': lastsync,
173     }, Password))
174     #pprint.pprint(r)
175     if len(r['syncitems']) == 0:
176         break
177     for item in r['syncitems']:
178         if item['item'][0] == 'L':
179             print "Fetching journal entry %s (%s)" % (item['item'], item['action'])
180             try:
181                 e = server.LJ.XMLRPC.getevents(dochallenge({
182                     'username': Username,
183                     'ver': 1,
184                     'selecttype': "one",
185                     'itemid': item['item'][2:],
186                 }, Password))
187                 writedump("%s/%s" % (Username, item['item']), e['events'][0])
188                 newentries += 1
189             except xmlrpclib.Fault, x:
190                 print "Error getting item: %s" % item['item']
191                 pprint.pprint(x)
192                 errors += 1
193         lastsync = item['time']
194
195 # The following code doesn't work because the server rejects our repeated calls.
196 # http://www.livejournal.com/doc/server/ljp.csp.xml-rpc.getevents.html
197 # contains the statement "You should use the syncitems selecttype in
198 # conjuntions [sic] with the syncitems protocol mode", but provides
199 # no other explanation about how these two function calls should
200 # interact. Therefore we just do the above slow one-at-a-time method.
201
202 #while True:
203 #    r = server.LJ.XMLRPC.getevents(dochallenge({
204 #        'username': Username,
205 #        'ver': 1,
206 #        'selecttype': "syncitems",
207 #        'lastsync': lastsync,
208 #    }, Password))
209 #    pprint.pprint(r)
210 #    if len(r['events']) == 0:
211 #        break
212 #    for item in r['events']:
213 #        writedump("%s/L-%d" % (Username, item['itemid']), item)
214 #        newentries += 1
215 #        lastsync = item['eventtime']
216
217 print "Fetching journal comments for: %s" % Username
218
219 try:
220     f = open("%s/comment.meta" % Username)
221     metacache = pickle.load(f)
222     f.close()
223 except:
224     metacache = {}
225
226 try:
227     f = open("%s/user.map" % Username)
228     usermap = pickle.load(f)
229     f.close()
230 except:
231     usermap = {}
232
233 maxid = lastmaxid
234 while True:
235     r = urllib2.urlopen(urllib2.Request(Server+"/export_comments.bml?get=comment_meta&startid=%d" % (maxid+1), headers = {'Cookie': "ljsession="+ljsession}))
236     meta = xml.dom.minidom.parse(r)
237     r.close()
238     for c in meta.getElementsByTagName("comment"):
239         id = int(c.getAttribute("id"))
240         metacache[id] = {
241             'posterid': c.getAttribute("posterid"),
242             'state': c.getAttribute("state"),
243         }
244         if id > maxid:
245             maxid = id
246     for u in meta.getElementsByTagName("usermap"):
247         usermap[u.getAttribute("id")] = u.getAttribute("user")
248     if maxid >= int(meta.getElementsByTagName("maxid")[0].firstChild.nodeValue):
249         break
250
251 f = open("%s/comment.meta" % Username, "w")
252 pickle.dump(metacache, f)
253 f.close()
254
255 f = open("%s/user.map" % Username, "w")
256 pickle.dump(usermap, f)
257 f.close()
258
259 f = open("%s/userpics.xml" % Username, "w")
260 print >>f, """<?xml version="1.0"?>"""
261 print >>f, "<userpics>"
262 for p in userpics:
263     print >>f, """<userpic keyword="%s" url="%s" />""" % (p, userpics[p])
264 print >>f, "</userpics>"
265 f.close()
266
267 newmaxid = maxid
268 maxid = lastmaxid
269 while True:
270     r = urllib2.urlopen(urllib2.Request(Server+"/export_comments.bml?get=comment_body&startid=%d" % (maxid+1), headers = {'Cookie': "ljsession="+ljsession}))
271     meta = xml.dom.minidom.parse(r)
272     r.close()
273     for c in meta.getElementsByTagName("comment"):
274         id = int(c.getAttribute("id"))
275         jitemid = c.getAttribute("jitemid")
276         comment = {
277             'id': str(id),
278             'parentid': c.getAttribute("parentid"),
279             'subject': gettext(c.getElementsByTagName("subject")),
280             'date': gettext(c.getElementsByTagName("date")),
281             'body': gettext(c.getElementsByTagName("body")),
282             'state': metacache[id]['state'],
283         }
284         if usermap.has_key(c.getAttribute("posterid")):
285             comment["user"] = usermap[c.getAttribute("posterid")]
286         try:
287             entry = xml.dom.minidom.parse("%s/C-%s" % (Username, jitemid))
288         except:
289             entry = xml.dom.minidom.getDOMImplementation().createDocument(None, "comments", None)
290         found = False
291         for d in entry.getElementsByTagName("comment"):
292             if int(d.getElementsByTagName("id")[0].firstChild.nodeValue) == id:
293                 found = True
294                 break
295         if found:
296             print "Warning: downloaded duplicate comment id %d in jitemid %s" % (id, jitemid)
297         else:
298             entry.documentElement.appendChild(createxml(entry, "comment", comment))
299             f = codecs.open("%s/C-%s" % (Username, jitemid), "w", "UTF-8")
300             entry.writexml(f)
301             f.close()
302             newcomments += 1
303         if id > maxid:
304             maxid = id
305     if maxid >= newmaxid:
306         break
307
308 lastmaxid = maxid
309
310 f = open("%s/.last" % Username, "w")
311 f.write("%s\n" % lastsync)
312 f.write("%s\n" % lastmaxid)
313 f.close()
314
315 if origlastsync:
316     print "%d new entries, %d new comments (since %s)" % (newentries, newcomments, origlastsync)
317 else:
318     print "%d new entries, %d new comments" % (newentries, newcomments)
319 if errors > 0:
320     print "%d errors" % errors