OSDN Git Service

add wp_imgswap2.py for new OSDN Magazine
[otptools/otptools.git] / otpuploader.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # otpuploader.py
4 """otpuploader.py - OpenTechPress Attachment Uploader"""
5
6 from poster.encode import multipart_encode
7 from poster.streaminghttp import register_openers
8 import urllib
9 import urllib2
10 import cookielib
11
12 class OtpUploader(object):
13     "OpenTechPress Attachment Uploader"
14     def __init__(self):
15         self.set_attach_url()
16
17     def set_attach_url(self, url=""):
18         if url == "":
19             url = "http://magazine.sourceforge.jp/fileadmin.pl"
20         self._attach_url = url
21
22     def login(self, username, passwd):
23         c = cookielib.CookieJar()
24         p = urllib2.HTTPCookieProcessor(c)
25         opener = urllib2.build_opener(p)
26
27         login_url = "http://magazine.sourceforge.jp/login.pl"
28         params = urllib.urlencode({
29             "op": "userlogin",
30             "unickname": username,
31             "upasswd": passwd,
32             "userlogin": u"ログイン".encode("utf-8")
33             })
34         req = opener.open(login_url, params)
35         self._cookie = c
36
37     def post_attachment(self, sid, filename):
38         params = {
39             "file_content": open(filename, "rb"),
40             "description": "",
41             "op": "addFileForStory",
42             "sid": sid,
43             "Submit": "Submit"
44             }
45         opener = register_openers()
46         opener.add_handler(urllib2.HTTPCookieProcessor(self._cookie))
47
48         (datagen, headers) = multipart_encode(params)
49         request = urllib2.Request(self._attach_url, datagen, headers)
50         res = opener.open(request)
51         #res = urllib2.urlopen(request)
52         #print res.read()
53
54 if __name__ == "__main__":
55     import getpass
56     import getopt
57     import sys
58
59     (opts, args) = getopt.getopt(sys.argv[1:], "u:")
60     opt_dict = dict(opts)
61     print opt_dict
62     print args
63
64     if not "-u" in opt_dict:
65         uname = raw_input("Username: ")
66     else:
67         uname = opt_dict["-u"]
68
69     if len(args) < 2:
70         sys.exit("usage: cmd sid <filename>")
71     sid = args.pop(0)
72
73     passwd = getpass.getpass()
74     u = OtpUploader()
75     u.login(uname, passwd)
76     print "cookie: ", u._cookie
77
78     for f in args:
79         print "post %s to sid %s" % (f, sid)
80         u.post_attachment(sid, f)
81