]> www.wagner.pp.ru Git - oss/ljdump.git/blob - ljdump.py
handle more potential non-filename characters in userpic keywords
[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.2
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(username, lastsync, lastmaxid):
92     f = open("%s/.last" % username, "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):
111     m = re.search("(.*)/interface/xmlrpc", Server)
112     if m:
113         Server = m.group(1)
114
115     print "Fetching journal entries for: %s" % Username
116     try:
117         os.mkdir(Username)
118         print "Created subdirectory: %s" % Username
119     except:
120         pass
121
122     ljsession = getljsession(Server, Username, Password)
123
124     server = xmlrpclib.ServerProxy(Server+"/interface/xmlrpc")
125
126     newentries = 0
127     newcomments = 0
128     errors = 0
129
130     lastsync = ""
131     lastmaxid = 0
132     try:
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]
140         if lastmaxid == "":
141             lastmaxid = 0
142         else:
143             lastmaxid = int(lastmaxid)
144         f.close()
145     except:
146         pass
147     origlastsync = lastsync
148
149     r = server.LJ.XMLRPC.login(dochallenge(server, {
150         'username': Username,
151         'ver': 1,
152         'getpickws': 1,
153         'getpickwurls': 1,
154     }, Password))
155     userpics = dict(zip(map(str, r['pickws']), r['pickwurls']))
156     userpics['*'] = r['defaultpicurl']
157
158     while True:
159         r = server.LJ.XMLRPC.syncitems(dochallenge(server, {
160             'username': Username,
161             'ver': 1,
162             'lastsync': lastsync,
163         }, Password))
164         #pprint.pprint(r)
165         if len(r['syncitems']) == 0:
166             break
167         for item in r['syncitems']:
168             if item['item'][0] == 'L':
169                 print "Fetching journal entry %s (%s)" % (item['item'], item['action'])
170                 try:
171                     e = server.LJ.XMLRPC.getevents(dochallenge(server, {
172                         'username': Username,
173                         'ver': 1,
174                         'selecttype': "one",
175                         'itemid': item['item'][2:],
176                     }, Password))
177                     if e['events']:
178                         writedump("%s/%s" % (Username, item['item']), e['events'][0])
179                         newentries += 1
180                     else:
181                         print "Unexpected empty item: %s" % item['item']
182                         errors += 1
183                 except xmlrpclib.Fault, x:
184                     print "Error getting item: %s" % item['item']
185                     pprint.pprint(x)
186                     errors += 1
187             lastsync = item['time']
188             writelast(Username, lastsync, lastmaxid)
189
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.
196
197     #while True:
198     #    r = server.LJ.XMLRPC.getevents(dochallenge(server, {
199     #        'username': Username,
200     #        'ver': 1,
201     #        'selecttype': "syncitems",
202     #        'lastsync': lastsync,
203     #    }, Password))
204     #    pprint.pprint(r)
205     #    if len(r['events']) == 0:
206     #        break
207     #    for item in r['events']:
208     #        writedump("%s/L-%d" % (Username, item['itemid']), item)
209     #        newentries += 1
210     #        lastsync = item['eventtime']
211
212     print "Fetching journal comments for: %s" % Username
213
214     try:
215         f = open("%s/comment.meta" % Username)
216         metacache = pickle.load(f)
217         f.close()
218     except:
219         metacache = {}
220
221     try:
222         f = open("%s/user.map" % Username)
223         usermap = pickle.load(f)
224         f.close()
225     except:
226         usermap = {}
227
228     maxid = lastmaxid
229     while True:
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)
232         r.close()
233         for c in meta.getElementsByTagName("comment"):
234             id = int(c.getAttribute("id"))
235             metacache[id] = {
236                 'posterid': c.getAttribute("posterid"),
237                 'state': c.getAttribute("state"),
238             }
239             if id > maxid:
240                 maxid = id
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):
244             break
245
246     f = open("%s/comment.meta" % Username, "w")
247     pickle.dump(metacache, f)
248     f.close()
249
250     f = open("%s/user.map" % Username, "w")
251     pickle.dump(usermap, f)
252     f.close()
253
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>"
258     for p in 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)
263         try:
264             picfn = codecs.utf_8_decode(picfn)[0]
265             picf = open("%s/%s%s" % (Username, picfn, ext), "wb")
266         except:
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)
271         pic.close()
272         picf.close()
273     print >>f, "</userpics>"
274     f.close()
275
276     newmaxid = maxid
277     maxid = lastmaxid
278     while True:
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)
281         r.close()
282         for c in meta.getElementsByTagName("comment"):
283             id = int(c.getAttribute("id"))
284             jitemid = c.getAttribute("jitemid")
285             comment = {
286                 'id': str(id),
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'],
292             }
293             if usermap.has_key(c.getAttribute("posterid")):
294                 comment["user"] = usermap[c.getAttribute("posterid")]
295             try:
296                 entry = xml.dom.minidom.parse("%s/C-%s" % (Username, jitemid))
297             except:
298                 entry = xml.dom.minidom.getDOMImplementation().createDocument(None, "comments", None)
299             found = False
300             for d in entry.getElementsByTagName("comment"):
301                 if int(d.getElementsByTagName("id")[0].firstChild.nodeValue) == id:
302                     found = True
303                     break
304             if found:
305                 print "Warning: downloaded duplicate comment id %d in jitemid %s" % (id, jitemid)
306             else:
307                 entry.documentElement.appendChild(createxml(entry, "comment", comment))
308                 f = codecs.open("%s/C-%s" % (Username, jitemid), "w", "UTF-8")
309                 entry.writexml(f)
310                 f.close()
311                 newcomments += 1
312             if id > maxid:
313                 maxid = id
314         if maxid >= newmaxid:
315             break
316
317     lastmaxid = maxid
318
319     writelast(Username, lastsync, lastmaxid)
320
321     if origlastsync:
322         print "%d new entries, %d new comments (since %s)" % (newentries, newcomments, origlastsync)
323     else:
324         print "%d new entries, %d new comments" % (newentries, newcomments)
325     if errors > 0:
326         print "%d errors" % errors
327
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
334     else:
335         from getpass import getpass
336         print "ljdump - livejournal archiver"
337         print
338         print "Enter your Livejournal username and password."
339         print
340         server = "http://livejournal.com"
341         username = raw_input("Username: ")
342         password = getpass("Password: ")
343         print
344     ljdump(server, username, password)