]> www.wagner.pp.ru Git - oss/ljdump.git/blob - ljdump.py
version 1.4
[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.4
6 #
7 # LICENSE
8 #
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.
12 #
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:
16 #
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.
24 #
25 # Copyright (c) 2005-2009 Greg Hewgill
26
27 import codecs, md5, os, pickle, pprint, re, shutil, sys, urllib2, xml.dom.minidom, xmlrpclib
28 from xml.sax import saxutils
29
30 MimeExtensions = {
31     "image/gif": ".gif",
32     "image/jpeg": ".jpg",
33     "image/png": ".png",
34 }
35
36 def calcchallenge(challenge, password):
37     return md5.new(challenge+md5.new(password).hexdigest()).hexdigest()
38
39 def flatresponse(response):
40     r = {}
41     while True:
42         name = response.readline()
43         if len(name) == 0:
44             break
45         if name[-1] == '\n':
46             name = name[:len(name)-1]
47         value = response.readline()
48         if value[-1] == '\n':
49             value = value[:len(value)-1]
50         r[name] = value
51     return r
52
53 def getljsession(server, username, password):
54     r = urllib2.urlopen(server+"/interface/flat", "mode=getchallenge")
55     response = flatresponse(r)
56     r.close()
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)
59     r.close()
60     return response['ljsession']
61
62 def dochallenge(server, params, password):
63     challenge = server.LJ.XMLRPC.getchallenge()
64     params.update({
65         'auth_method': "challenge",
66         'auth_challenge': challenge['challenge'],
67         'auth_response': calcchallenge(challenge['challenge'], password)
68     })
69     return params
70
71 def dumpelement(f, name, e):
72     f.write("<%s>\n" % name)
73     for k in e.keys():
74         if isinstance(e[k], {}.__class__):
75             dumpelement(f, k, e[k])
76         else:
77             try:
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)
84
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)
89     f.close()
90
91 def writelast(journal, lastsync, lastmaxid):
92     f = open("%s/.last" % journal, "w")
93     f.write("%s\n" % lastsync)
94     f.write("%s\n" % lastmaxid)
95     f.close()
96
97 def createxml(doc, name, map):
98     e = doc.createElement(name)
99     for k in map.keys():
100         me = doc.createElement(k)
101         me.appendChild(doc.createTextNode(map[k]))
102         e.appendChild(me)
103     return e
104
105 def gettext(e):
106     if len(e) == 0:
107         return ""
108     return e[0].firstChild.nodeValue
109
110 def ljdump(Server, Username, Password, Journal):
111     m = re.search("(.*)/interface/xmlrpc", Server)
112     if m:
113         Server = m.group(1)
114     if Username != Journal:
115         authas = "&authas=%s" % Journal
116     else:
117         authas = ""
118
119     print "Fetching journal entries for: %s" % Journal
120     try:
121         os.mkdir(Journal)
122         print "Created subdirectory: %s" % Journal
123     except:
124         pass
125
126     ljsession = getljsession(Server, Username, Password)
127
128     server = xmlrpclib.ServerProxy(Server+"/interface/xmlrpc")
129
130     newentries = 0
131     newcomments = 0
132     errors = 0
133
134     lastsync = ""
135     lastmaxid = 0
136     try:
137         f = open("%s/.last" % Journal, "r")
138         lastsync = f.readline()
139         if lastsync[-1] == '\n':
140             lastsync = lastsync[:len(lastsync)-1]
141         lastmaxid = f.readline()
142         if len(lastmaxid) > 0 and lastmaxid[-1] == '\n':
143             lastmaxid = lastmaxid[:len(lastmaxid)-1]
144         if lastmaxid == "":
145             lastmaxid = 0
146         else:
147             lastmaxid = int(lastmaxid)
148         f.close()
149     except:
150         pass
151     origlastsync = lastsync
152
153     r = server.LJ.XMLRPC.login(dochallenge(server, {
154         'username': Username,
155         'ver': 1,
156         'getpickws': 1,
157         'getpickwurls': 1,
158     }, Password))
159     userpics = dict(zip(map(str, r['pickws']), r['pickwurls']))
160     userpics['*'] = r['defaultpicurl']
161
162     while True:
163         r = server.LJ.XMLRPC.syncitems(dochallenge(server, {
164             'username': Username,
165             'ver': 1,
166             'lastsync': lastsync,
167             'usejournal': Journal,
168         }, Password))
169         #pprint.pprint(r)
170         if len(r['syncitems']) == 0:
171             break
172         for item in r['syncitems']:
173             if item['item'][0] == 'L':
174                 print "Fetching journal entry %s (%s)" % (item['item'], item['action'])
175                 try:
176                     e = server.LJ.XMLRPC.getevents(dochallenge(server, {
177                         'username': Username,
178                         'ver': 1,
179                         'selecttype': "one",
180                         'itemid': item['item'][2:],
181                         'usejournal': Journal,
182                     }, Password))
183                     if e['events']:
184                         writedump("%s/%s" % (Journal, item['item']), e['events'][0])
185                         newentries += 1
186                     else:
187                         print "Unexpected empty item: %s" % item['item']
188                         errors += 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             writelast(Journal, lastsync, lastmaxid)
195
196     # The following code doesn't work because the server rejects our repeated calls.
197     # http://www.livejournal.com/doc/server/ljp.csp.xml-rpc.getevents.html
198     # contains the statement "You should use the syncitems selecttype in
199     # conjuntions [sic] with the syncitems protocol mode", but provides
200     # no other explanation about how these two function calls should
201     # interact. Therefore we just do the above slow one-at-a-time method.
202
203     #while True:
204     #    r = server.LJ.XMLRPC.getevents(dochallenge(server, {
205     #        'username': Username,
206     #        'ver': 1,
207     #        'selecttype': "syncitems",
208     #        'lastsync': lastsync,
209     #    }, Password))
210     #    pprint.pprint(r)
211     #    if len(r['events']) == 0:
212     #        break
213     #    for item in r['events']:
214     #        writedump("%s/L-%d" % (Journal, item['itemid']), item)
215     #        newentries += 1
216     #        lastsync = item['eventtime']
217
218     print "Fetching journal comments for: %s" % Journal
219
220     try:
221         f = open("%s/comment.meta" % Journal)
222         metacache = pickle.load(f)
223         f.close()
224     except:
225         metacache = {}
226
227     try:
228         f = open("%s/user.map" % Journal)
229         usermap = pickle.load(f)
230         f.close()
231     except:
232         usermap = {}
233
234     maxid = lastmaxid
235     while True:
236         try:
237             try:
238                 r = urllib2.urlopen(urllib2.Request(Server+"/export_comments.bml?get=comment_meta&startid=%d%s" % (maxid+1, authas), headers = {'Cookie': "ljsession="+ljsession}))
239                 meta = xml.dom.minidom.parse(r)
240             except:
241                 print "*** Error fetching comment meta, possibly not community maintainer?"
242                 break
243         finally:
244             r.close()
245         for c in meta.getElementsByTagName("comment"):
246             id = int(c.getAttribute("id"))
247             metacache[id] = {
248                 'posterid': c.getAttribute("posterid"),
249                 'state': c.getAttribute("state"),
250             }
251             if id > maxid:
252                 maxid = id
253         for u in meta.getElementsByTagName("usermap"):
254             usermap[u.getAttribute("id")] = u.getAttribute("user")
255         if maxid >= int(meta.getElementsByTagName("maxid")[0].firstChild.nodeValue):
256             break
257
258     f = open("%s/comment.meta" % Journal, "w")
259     pickle.dump(metacache, f)
260     f.close()
261
262     f = open("%s/user.map" % Journal, "w")
263     pickle.dump(usermap, f)
264     f.close()
265
266     newmaxid = maxid
267     maxid = lastmaxid
268     while True:
269         try:
270             try:
271                 r = urllib2.urlopen(urllib2.Request(Server+"/export_comments.bml?get=comment_body&startid=%d%s" % (maxid+1, authas), headers = {'Cookie': "ljsession="+ljsession}))
272                 meta = xml.dom.minidom.parse(r)
273             except:
274                 print "*** Error fetching comment body, possibly not community maintainer?"
275                 break
276         finally:
277             r.close()
278         for c in meta.getElementsByTagName("comment"):
279             id = int(c.getAttribute("id"))
280             jitemid = c.getAttribute("jitemid")
281             comment = {
282                 'id': str(id),
283                 'parentid': c.getAttribute("parentid"),
284                 'subject': gettext(c.getElementsByTagName("subject")),
285                 'date': gettext(c.getElementsByTagName("date")),
286                 'body': gettext(c.getElementsByTagName("body")),
287                 'state': metacache[id]['state'],
288             }
289             if usermap.has_key(c.getAttribute("posterid")):
290                 comment["user"] = usermap[c.getAttribute("posterid")]
291             try:
292                 entry = xml.dom.minidom.parse("%s/C-%s" % (Journal, jitemid))
293             except:
294                 entry = xml.dom.minidom.getDOMImplementation().createDocument(None, "comments", None)
295             found = False
296             for d in entry.getElementsByTagName("comment"):
297                 if int(d.getElementsByTagName("id")[0].firstChild.nodeValue) == id:
298                     found = True
299                     break
300             if found:
301                 print "Warning: downloaded duplicate comment id %d in jitemid %s" % (id, jitemid)
302             else:
303                 entry.documentElement.appendChild(createxml(entry, "comment", comment))
304                 f = codecs.open("%s/C-%s" % (Journal, jitemid), "w", "UTF-8")
305                 entry.writexml(f)
306                 f.close()
307                 newcomments += 1
308             if id > maxid:
309                 maxid = id
310         if maxid >= newmaxid:
311             break
312
313     lastmaxid = maxid
314
315     writelast(Journal, lastsync, lastmaxid)
316
317     if Username == Journal:
318         print "Fetching userpics for: %s" % Username
319         f = open("%s/userpics.xml" % Username, "w")
320         print >>f, """<?xml version="1.0"?>"""
321         print >>f, "<userpics>"
322         for p in userpics:
323             print >>f, """<userpic keyword="%s" url="%s" />""" % (p, userpics[p])
324             pic = urllib2.urlopen(userpics[p])
325             ext = MimeExtensions.get(pic.info()["Content-Type"], "")
326             picfn = re.sub(r'[*?\\/:<>"|]', "_", p)
327             try:
328                 picfn = codecs.utf_8_decode(picfn)[0]
329                 picf = open("%s/%s%s" % (Username, picfn, ext), "wb")
330             except:
331                 # for installations where the above utf_8_decode doesn't work
332                 picfn = "".join([ord(x) < 128 and x or "_" for x in picfn])
333                 picf = open("%s/%s%s" % (Username, picfn, ext), "wb")
334             shutil.copyfileobj(pic, picf)
335             pic.close()
336             picf.close()
337         print >>f, "</userpics>"
338         f.close()
339
340     if origlastsync:
341         print "%d new entries, %d new comments (since %s)" % (newentries, newcomments, origlastsync)
342     else:
343         print "%d new entries, %d new comments" % (newentries, newcomments)
344     if errors > 0:
345         print "%d errors" % errors
346
347 if __name__ == "__main__":
348     if os.access("ljdump.config", os.F_OK):
349         config = xml.dom.minidom.parse("ljdump.config")
350         server = config.documentElement.getElementsByTagName("server")[0].childNodes[0].data
351         username = config.documentElement.getElementsByTagName("username")[0].childNodes[0].data
352         password = config.documentElement.getElementsByTagName("password")[0].childNodes[0].data
353         journals = config.documentElement.getElementsByTagName("journal")
354         if journals:
355             for e in journals:
356                 ljdump(server, username, password, e.childNodes[0].data)
357         else:
358             ljdump(server, username, password, username)
359     else:
360         from getpass import getpass
361         print "ljdump - livejournal archiver"
362         print
363         print "Enter your Livejournal username and password."
364         print
365         server = "http://livejournal.com"
366         username = raw_input("Username: ")
367         password = getpass("Password: ")
368         print
369         print "You may back up either your own journal, or a community."
370         print "If you are a community maintainer, you can back up both entries and comments."
371         print "If you are not a maintainer, you can back up only entries."
372         print
373         journal = raw_input("Journal to back up (or hit return to back up '%s'): " % username)
374         print
375         if journal:
376             ljdump(server, username, password, journal)
377         else:
378             ljdump(server, username, password, username)