]> www.wagner.pp.ru Git - oss/ljdump.git/blob - ljdump.py
handle unexpected empty item
[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, shutil, sys, urllib2, xml.dom.minidom, xmlrpclib
50 from xml.sax import saxutils
51
52 MimeExtensions = {
53     "image/gif": ".gif",
54     "image/jpeg": ".jpg",
55     "image/png": ".png",
56 }
57
58 def calcchallenge(challenge, password):
59     return md5.new(challenge+md5.new(password).hexdigest()).hexdigest()
60
61 def flatresponse(response):
62     r = {}
63     while True:
64         name = response.readline()
65         if len(name) == 0:
66             break
67         if name[-1] == '\n':
68             name = name[:len(name)-1]
69         value = response.readline()
70         if value[-1] == '\n':
71             value = value[:len(value)-1]
72         r[name] = value
73     return r
74
75 def getljsession(username, password):
76     r = urllib2.urlopen(Server+"/interface/flat", "mode=getchallenge")
77     response = flatresponse(r)
78     r.close()
79     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)))
80     response = flatresponse(r)
81     r.close()
82     return response['ljsession']
83
84 def dochallenge(params, password):
85     challenge = server.LJ.XMLRPC.getchallenge()
86     params.update({
87         'auth_method': "challenge",
88         'auth_challenge': challenge['challenge'],
89         'auth_response': calcchallenge(challenge['challenge'], password)
90     })
91     return params
92
93 def dumpelement(f, name, e):
94     f.write("<%s>\n" % name)
95     for k in e.keys():
96         if isinstance(e[k], {}.__class__):
97             dumpelement(f, k, e[k])
98         else:
99             s = unicode(str(e[k]), "UTF-8")
100             f.write("<%s>%s</%s>\n" % (k, saxutils.escape(s), k))
101     f.write("</%s>\n" % name)
102
103 def writedump(fn, event):
104     f = codecs.open(fn, "w", "UTF-8")
105     f.write("""<?xml version="1.0"?>\n""")
106     dumpelement(f, "event", event)
107     f.close()
108
109 def createxml(doc, name, map):
110     e = doc.createElement(name)
111     for k in map.keys():
112         me = doc.createElement(k)
113         me.appendChild(doc.createTextNode(map[k]))
114         e.appendChild(me)
115     return e
116
117 def gettext(e):
118     if len(e) == 0:
119         return ""
120     return e[0].firstChild.nodeValue
121
122 config = xml.dom.minidom.parse("ljdump.config")
123 Server = config.documentElement.getElementsByTagName("server")[0].childNodes[0].data
124 Username = config.documentElement.getElementsByTagName("username")[0].childNodes[0].data
125 Password = config.documentElement.getElementsByTagName("password")[0].childNodes[0].data
126
127 m = re.search("(.*)/interface/xmlrpc", Server)
128 if m:
129     Server = m.group(1)
130
131 print "Fetching journal entries for: %s" % Username
132 try:
133     os.mkdir(Username)
134     print "Created subdirectory: %s" % Username
135 except:
136     pass
137
138 ljsession = getljsession(Username, Password)
139
140 server = xmlrpclib.ServerProxy(Server+"/interface/xmlrpc")
141
142 newentries = 0
143 newcomments = 0
144 errors = 0
145
146 lastsync = ""
147 lastmaxid = 0
148 try:
149     f = open("%s/.last" % Username, "r")
150     lastsync = f.readline()
151     if lastsync[-1] == '\n':
152         lastsync = lastsync[:len(lastsync)-1]
153     lastmaxid = f.readline()
154     if len(lastmaxid) > 0 and lastmaxid[-1] == '\n':
155         lastmaxid = lastmaxid[:len(lastmaxid)-1]
156     if lastmaxid == "":
157         lastmaxid = 0
158     else:
159         lastmaxid = int(lastmaxid)
160     f.close()
161 except:
162     pass
163 origlastsync = lastsync
164
165 r = server.LJ.XMLRPC.login(dochallenge({
166     'username': Username,
167     'ver': 1,
168     'getpickws': 1,
169     'getpickwurls': 1,
170 }, Password))
171 userpics = dict(zip(map(str, r['pickws']), r['pickwurls']))
172 userpics['*'] = r['defaultpicurl']
173
174 while True:
175     r = server.LJ.XMLRPC.syncitems(dochallenge({
176         'username': Username,
177         'ver': 1,
178         'lastsync': lastsync,
179     }, Password))
180     #pprint.pprint(r)
181     if len(r['syncitems']) == 0:
182         break
183     for item in r['syncitems']:
184         if item['item'][0] == 'L':
185             print "Fetching journal entry %s (%s)" % (item['item'], item['action'])
186             try:
187                 e = server.LJ.XMLRPC.getevents(dochallenge({
188                     'username': Username,
189                     'ver': 1,
190                     'selecttype': "one",
191                     'itemid': item['item'][2:],
192                 }, Password))
193                 if e['events']:
194                     writedump("%s/%s" % (Username, item['item']), e['events'][0])
195                     newentries += 1
196                 else:
197                     print "Unexpected empty item: %s" % item['item']
198                     errors += 1
199             except xmlrpclib.Fault, x:
200                 print "Error getting item: %s" % item['item']
201                 pprint.pprint(x)
202                 errors += 1
203         lastsync = item['time']
204
205 # The following code doesn't work because the server rejects our repeated calls.
206 # http://www.livejournal.com/doc/server/ljp.csp.xml-rpc.getevents.html
207 # contains the statement "You should use the syncitems selecttype in
208 # conjuntions [sic] with the syncitems protocol mode", but provides
209 # no other explanation about how these two function calls should
210 # interact. Therefore we just do the above slow one-at-a-time method.
211
212 #while True:
213 #    r = server.LJ.XMLRPC.getevents(dochallenge({
214 #        'username': Username,
215 #        'ver': 1,
216 #        'selecttype': "syncitems",
217 #        'lastsync': lastsync,
218 #    }, Password))
219 #    pprint.pprint(r)
220 #    if len(r['events']) == 0:
221 #        break
222 #    for item in r['events']:
223 #        writedump("%s/L-%d" % (Username, item['itemid']), item)
224 #        newentries += 1
225 #        lastsync = item['eventtime']
226
227 print "Fetching journal comments for: %s" % Username
228
229 try:
230     f = open("%s/comment.meta" % Username)
231     metacache = pickle.load(f)
232     f.close()
233 except:
234     metacache = {}
235
236 try:
237     f = open("%s/user.map" % Username)
238     usermap = pickle.load(f)
239     f.close()
240 except:
241     usermap = {}
242
243 maxid = lastmaxid
244 while True:
245     r = urllib2.urlopen(urllib2.Request(Server+"/export_comments.bml?get=comment_meta&startid=%d" % (maxid+1), headers = {'Cookie': "ljsession="+ljsession}))
246     meta = xml.dom.minidom.parse(r)
247     r.close()
248     for c in meta.getElementsByTagName("comment"):
249         id = int(c.getAttribute("id"))
250         metacache[id] = {
251             'posterid': c.getAttribute("posterid"),
252             'state': c.getAttribute("state"),
253         }
254         if id > maxid:
255             maxid = id
256     for u in meta.getElementsByTagName("usermap"):
257         usermap[u.getAttribute("id")] = u.getAttribute("user")
258     if maxid >= int(meta.getElementsByTagName("maxid")[0].firstChild.nodeValue):
259         break
260
261 f = open("%s/comment.meta" % Username, "w")
262 pickle.dump(metacache, f)
263 f.close()
264
265 f = open("%s/user.map" % Username, "w")
266 pickle.dump(usermap, f)
267 f.close()
268
269 print "Fetching userpics for: %s" % Username
270 f = open("%s/userpics.xml" % Username, "w")
271 print >>f, """<?xml version="1.0"?>"""
272 print >>f, "<userpics>"
273 for p in userpics:
274     print >>f, """<userpic keyword="%s" url="%s" />""" % (p, userpics[p])
275     pic = urllib2.urlopen(userpics[p])
276     ext = MimeExtensions.get(pic.info()["Content-Type"], "")
277     picf = open("%s/%s%s" % (Username, codecs.utf_8_decode(p)[0], ext), "wb")
278     shutil.copyfileobj(pic, picf)
279     pic.close()
280     picf.close()
281 print >>f, "</userpics>"
282 f.close()
283
284 newmaxid = maxid
285 maxid = lastmaxid
286 while True:
287     r = urllib2.urlopen(urllib2.Request(Server+"/export_comments.bml?get=comment_body&startid=%d" % (maxid+1), headers = {'Cookie': "ljsession="+ljsession}))
288     meta = xml.dom.minidom.parse(r)
289     r.close()
290     for c in meta.getElementsByTagName("comment"):
291         id = int(c.getAttribute("id"))
292         jitemid = c.getAttribute("jitemid")
293         comment = {
294             'id': str(id),
295             'parentid': c.getAttribute("parentid"),
296             'subject': gettext(c.getElementsByTagName("subject")),
297             'date': gettext(c.getElementsByTagName("date")),
298             'body': gettext(c.getElementsByTagName("body")),
299             'state': metacache[id]['state'],
300         }
301         if usermap.has_key(c.getAttribute("posterid")):
302             comment["user"] = usermap[c.getAttribute("posterid")]
303         try:
304             entry = xml.dom.minidom.parse("%s/C-%s" % (Username, jitemid))
305         except:
306             entry = xml.dom.minidom.getDOMImplementation().createDocument(None, "comments", None)
307         found = False
308         for d in entry.getElementsByTagName("comment"):
309             if int(d.getElementsByTagName("id")[0].firstChild.nodeValue) == id:
310                 found = True
311                 break
312         if found:
313             print "Warning: downloaded duplicate comment id %d in jitemid %s" % (id, jitemid)
314         else:
315             entry.documentElement.appendChild(createxml(entry, "comment", comment))
316             f = codecs.open("%s/C-%s" % (Username, jitemid), "w", "UTF-8")
317             entry.writexml(f)
318             f.close()
319             newcomments += 1
320         if id > maxid:
321             maxid = id
322     if maxid >= newmaxid:
323         break
324
325 lastmaxid = maxid
326
327 f = open("%s/.last" % Username, "w")
328 f.write("%s\n" % lastsync)
329 f.write("%s\n" % lastmaxid)
330 f.close()
331
332 if origlastsync:
333     print "%d new entries, %d new comments (since %s)" % (newentries, newcomments, origlastsync)
334 else:
335     print "%d new entries, %d new comments" % (newentries, newcomments)
336 if errors > 0:
337     print "%d errors" % errors