3 # ljdump.py - livejournal archiver
4 # Greg Hewgill <greg@hewgill.com> http://hewgill.com
9 # This software is provided 'as-is', without any express or implied
10 # warranty. In no event will the author be held liable for any damages
11 # arising from the use of this software.
13 # Permission is granted to anyone to use this software for any purpose,
14 # including commercial applications, and to alter it and redistribute it
15 # freely, subject to the following restrictions:
17 # 1. The origin of this software must not be misrepresented; you must not
18 # claim that you wrote the original software. If you use this software
19 # in a product, an acknowledgment in the product documentation would be
20 # appreciated but is not required.
21 # 2. Altered source versions must be plainly marked as such, and must not be
22 # misrepresented as being the original software.
23 # 3. This notice may not be removed or altered from any source distribution.
25 # Copyright (c) 2005-2009 Greg Hewgill
27 import codecs, md5, os, pickle, pprint, re, shutil, sys, urllib2, xml.dom.minidom, xmlrpclib
28 from xml.sax import saxutils
36 def calcchallenge(challenge, password):
37 return md5.new(challenge+md5.new(password).hexdigest()).hexdigest()
39 def flatresponse(response):
42 name = response.readline()
46 name = name[:len(name)-1]
47 value = response.readline()
49 value = value[:len(value)-1]
53 def getljsession(server, username, password):
54 r = urllib2.urlopen(server+"/interface/flat", "mode=getchallenge")
55 response = flatresponse(r)
57 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)))
58 response = flatresponse(r)
60 return response['ljsession']
62 def dochallenge(server, params, password):
63 challenge = server.LJ.XMLRPC.getchallenge()
65 'auth_method': "challenge",
66 'auth_challenge': challenge['challenge'],
67 'auth_response': calcchallenge(challenge['challenge'], password)
71 def dumpelement(f, name, e):
72 f.write("<%s>\n" % name)
74 if isinstance(e[k], {}.__class__):
75 dumpelement(f, k, e[k])
78 s = unicode(str(e[k]), "UTF-8")
79 except UnicodeDecodeError:
80 # fall back to Latin-1 for old entries that aren't UTF-8
81 s = unicode(str(e[k]), "cp1252")
82 f.write("<%s>%s</%s>\n" % (k, saxutils.escape(s), k))
83 f.write("</%s>\n" % name)
85 def writedump(fn, event):
86 f = codecs.open(fn, "w", "UTF-8")
87 f.write("""<?xml version="1.0"?>\n""")
88 dumpelement(f, "event", event)
91 def writelast(username, lastsync, lastmaxid):
92 f = open("%s/.last" % username, "w")
93 f.write("%s\n" % lastsync)
94 f.write("%s\n" % lastmaxid)
97 def createxml(doc, name, map):
98 e = doc.createElement(name)
100 me = doc.createElement(k)
101 me.appendChild(doc.createTextNode(map[k]))
108 return e[0].firstChild.nodeValue
110 def ljdump(Server, Username, Password):
111 m = re.search("(.*)/interface/xmlrpc", Server)
115 print "Fetching journal entries for: %s" % Username
118 print "Created subdirectory: %s" % Username
122 ljsession = getljsession(Server, Username, Password)
124 server = xmlrpclib.ServerProxy(Server+"/interface/xmlrpc")
133 f = open("%s/.last" % Username, "r")
134 lastsync = f.readline()
135 if lastsync[-1] == '\n':
136 lastsync = lastsync[:len(lastsync)-1]
137 lastmaxid = f.readline()
138 if len(lastmaxid) > 0 and lastmaxid[-1] == '\n':
139 lastmaxid = lastmaxid[:len(lastmaxid)-1]
143 lastmaxid = int(lastmaxid)
147 origlastsync = lastsync
149 r = server.LJ.XMLRPC.login(dochallenge(server, {
150 'username': Username,
155 userpics = dict(zip(map(str, r['pickws']), r['pickwurls']))
156 userpics['*'] = r['defaultpicurl']
159 r = server.LJ.XMLRPC.syncitems(dochallenge(server, {
160 'username': Username,
162 'lastsync': lastsync,
165 if len(r['syncitems']) == 0:
167 for item in r['syncitems']:
168 if item['item'][0] == 'L':
169 print "Fetching journal entry %s (%s)" % (item['item'], item['action'])
171 e = server.LJ.XMLRPC.getevents(dochallenge(server, {
172 'username': Username,
175 'itemid': item['item'][2:],
178 writedump("%s/%s" % (Username, item['item']), e['events'][0])
181 print "Unexpected empty item: %s" % item['item']
183 except xmlrpclib.Fault, x:
184 print "Error getting item: %s" % item['item']
187 lastsync = item['time']
188 writelast(Username, lastsync, lastmaxid)
190 # The following code doesn't work because the server rejects our repeated calls.
191 # http://www.livejournal.com/doc/server/ljp.csp.xml-rpc.getevents.html
192 # contains the statement "You should use the syncitems selecttype in
193 # conjuntions [sic] with the syncitems protocol mode", but provides
194 # no other explanation about how these two function calls should
195 # interact. Therefore we just do the above slow one-at-a-time method.
198 # r = server.LJ.XMLRPC.getevents(dochallenge(server, {
199 # 'username': Username,
201 # 'selecttype': "syncitems",
202 # 'lastsync': lastsync,
205 # if len(r['events']) == 0:
207 # for item in r['events']:
208 # writedump("%s/L-%d" % (Username, item['itemid']), item)
210 # lastsync = item['eventtime']
212 print "Fetching journal comments for: %s" % Username
215 f = open("%s/comment.meta" % Username)
216 metacache = pickle.load(f)
222 f = open("%s/user.map" % Username)
223 usermap = pickle.load(f)
230 r = urllib2.urlopen(urllib2.Request(Server+"/export_comments.bml?get=comment_meta&startid=%d" % (maxid+1), headers = {'Cookie': "ljsession="+ljsession}))
231 meta = xml.dom.minidom.parse(r)
233 for c in meta.getElementsByTagName("comment"):
234 id = int(c.getAttribute("id"))
236 'posterid': c.getAttribute("posterid"),
237 'state': c.getAttribute("state"),
241 for u in meta.getElementsByTagName("usermap"):
242 usermap[u.getAttribute("id")] = u.getAttribute("user")
243 if maxid >= int(meta.getElementsByTagName("maxid")[0].firstChild.nodeValue):
246 f = open("%s/comment.meta" % Username, "w")
247 pickle.dump(metacache, f)
250 f = open("%s/user.map" % Username, "w")
251 pickle.dump(usermap, f)
254 print "Fetching userpics for: %s" % Username
255 f = open("%s/userpics.xml" % Username, "w")
256 print >>f, """<?xml version="1.0"?>"""
257 print >>f, "<userpics>"
259 print >>f, """<userpic keyword="%s" url="%s" />""" % (p, userpics[p])
260 pic = urllib2.urlopen(userpics[p])
261 ext = MimeExtensions.get(pic.info()["Content-Type"], "")
262 picfn = re.sub(r"[\/]", "_", p)
264 picfn = codecs.utf_8_decode(picfn)[0]
265 picf = open("%s/%s%s" % (Username, picfn, ext), "wb")
267 # for installations where the above utf_8_decode doesn't work
268 picfn = "".join([ord(x) < 128 and x or "?" for x in picfn])
269 picf = open("%s/%s%s" % (Username, picfn, ext), "wb")
270 shutil.copyfileobj(pic, picf)
273 print >>f, "</userpics>"
279 r = urllib2.urlopen(urllib2.Request(Server+"/export_comments.bml?get=comment_body&startid=%d" % (maxid+1), headers = {'Cookie': "ljsession="+ljsession}))
280 meta = xml.dom.minidom.parse(r)
282 for c in meta.getElementsByTagName("comment"):
283 id = int(c.getAttribute("id"))
284 jitemid = c.getAttribute("jitemid")
287 'parentid': c.getAttribute("parentid"),
288 'subject': gettext(c.getElementsByTagName("subject")),
289 'date': gettext(c.getElementsByTagName("date")),
290 'body': gettext(c.getElementsByTagName("body")),
291 'state': metacache[id]['state'],
293 if usermap.has_key(c.getAttribute("posterid")):
294 comment["user"] = usermap[c.getAttribute("posterid")]
296 entry = xml.dom.minidom.parse("%s/C-%s" % (Username, jitemid))
298 entry = xml.dom.minidom.getDOMImplementation().createDocument(None, "comments", None)
300 for d in entry.getElementsByTagName("comment"):
301 if int(d.getElementsByTagName("id")[0].firstChild.nodeValue) == id:
305 print "Warning: downloaded duplicate comment id %d in jitemid %s" % (id, jitemid)
307 entry.documentElement.appendChild(createxml(entry, "comment", comment))
308 f = codecs.open("%s/C-%s" % (Username, jitemid), "w", "UTF-8")
314 if maxid >= newmaxid:
319 writelast(Username, lastsync, lastmaxid)
322 print "%d new entries, %d new comments (since %s)" % (newentries, newcomments, origlastsync)
324 print "%d new entries, %d new comments" % (newentries, newcomments)
326 print "%d errors" % errors
328 if __name__ == "__main__":
329 if os.access("ljdump.config", os.F_OK):
330 config = xml.dom.minidom.parse("ljdump.config")
331 server = config.documentElement.getElementsByTagName("server")[0].childNodes[0].data
332 username = config.documentElement.getElementsByTagName("username")[0].childNodes[0].data
333 password = config.documentElement.getElementsByTagName("password")[0].childNodes[0].data
335 from getpass import getpass
336 print "ljdump - livejournal archiver"
338 print "Enter your Livejournal username and password."
340 server = "http://livejournal.com"
341 username = raw_input("Username: ")
342 password = getpass("Password: ")
344 ljdump(server, username, password)