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