OSDN Git Service

in response of submit, same encoding as dat files is supposed.
[fukui-no-namari/fukui-no-namari.git] / src / FukuiNoNamari / submit_window.py
index f64426f..a45ede7 100644 (file)
@@ -25,17 +25,17 @@ import urllib
 import urllib2
 import cookielib
 import os.path
-import time
+import sys
+import htmlentitydefs
 
 from BbsType import bbs_type_judge_uri
 from BbsType import bbs_type_exception
 from HTMLParserEx import HTMLParserEx
 import datfile
 import uri_opener
+import config
 from http_sub import HTTPDebugHandler
 
-GLADE_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)),
-                         "..", "data")
 GLADE_FILENAME = "submit_window.glade"
 
 cookie_jar = cookielib.CookieJar()
@@ -56,12 +56,19 @@ class ConfirmationHTMLParser(HTMLParserEx):
         self.message = ""
         self.inputs = []
         self.complete = False
+        self.title = ""
+        self.in_head = False
+        self.in_title = False
 
     def handle_starttag(self, tag, attr):
         if tag == "br":
             self.message += "\n"
         elif tag == "input":
             self.inputs.append(dict(attr))
+        elif tag == "title":
+            self.in_title = True
+        elif tag == "head":
+            self.in_head = True
         elif tag == "meta":
             attr_dict = dict(attr)
             if "http-equiv" in attr_dict \
@@ -69,13 +76,19 @@ class ConfirmationHTMLParser(HTMLParserEx):
                 self.complete = True
 
     def handle_endtag(self, tag):
-        pass
+        if tag == "title":
+            self.in_title = False
+        elif tag == "head":
+            self.in_head = False
 
     def handle_comment(self, comment):
-        print comment.strip()
+        pass
 
     def handle_data(self, data):
-        self.message += data
+        if self.in_title:
+            self.title = data
+        elif not self.in_head:
+            self.message += data.rstrip()
 
     def handle_charref(self, ref):
         data = None
@@ -102,20 +115,13 @@ class WinWrap:
             raise bbs_type_exception.BbsTypeError, \
                   "the uri does not represent thread: " + uri
 
-        glade_path = os.path.join(GLADE_DIR, GLADE_FILENAME)
+        glade_path = os.path.join(config.glade_dir, GLADE_FILENAME)
         self.widget_tree = gtk.glade.XML(glade_path)
         self.window = self.widget_tree.get_widget("submit_window")
         self.entry_name = self.widget_tree.get_widget("entry_name")
         self.entry_mail = self.widget_tree.get_widget("entry_mail")
         self.textbuffer = self.widget_tree.get_widget("textview").get_buffer()
 
-        self.post_dict = {}
-        self.post_dict["bbs"] = self.bbs_type.board
-        self.post_dict["key"] = self.bbs_type.thread
-        self.post_dict["time"] = str(int(time.time()))
-        self.post_dict["submit"] = u"\u66f8\u304d\u8fbc\u3080".encode(
-            "cp932", "replace")
-
         sigdic = {"on_submit_activate": self.on_submit_activate,
                   "on_close_activate": self.on_close_activate}
 
@@ -134,37 +140,55 @@ class WinWrap:
         msg = self.textbuffer.get_text(
             self.textbuffer.get_start_iter(), self.textbuffer.get_end_iter())
 
-        self.post_dict["FROM"] = name.encode("cp932", "replace")
-        self.post_dict["mail"] = mail.encode("cp932", "replace")
-        self.post_dict["MESSAGE"] = msg.encode("cp932", "replace")
-
+        self.post_dict = self.bbs_type.build_post_dict(name, mail, msg)
         self.post_dict = self.bbs_type.set_extra_post(self.post_dict)
 
         self.do_submit()
 
     def do_submit(self):
+        for name, value in self.post_dict.iteritems():
+            print "%s: %s" \
+                  % (name, value.decode(self.bbs_type.encoding, "replace"))
         post_encoded = urllib.urlencode(self.post_dict)
-        print post_encoded
 
-        req = urllib2.Request("http://" + self.bbs_type.host + "/test/bbs.cgi",
-                              post_encoded)
+        req = urllib2.Request(self.bbs_type.get_post_uri(), post_encoded)
         req.add_header("Referer", self.uri)
+        req.add_header("User-agent", config.User_Agent)
 
         res = opener.open(req)
         self.on_response(res)
 
     def on_response(self, response):
         data = response.read()
-
+        info = response.info()
+
+        # suppose same encoding used in dat files.
+        encoding = self.bbs_type.encoding
+        # if there is charset in response headers, use it.
+        if "Content-Type" in info:
+            import re
+            match = re.search(
+                "charset=(?P<charset>[a-zA-Z0-9_\-]+)", info["Content-Type"])
+            if match:
+                charset = match.group("charset").lower()
+
+                if charset in ("x-sjis", "x_sjis", "sjis", "shiftjis",
+                               "shift-jis", "shift_jis", "s-jis", "s_jis"):
+                    encoding = "cp932"
+                elif charset in ("euc-jp", "euc_jp", "eucjp"):
+                    encoding = "euc-jp"
+        data = data.decode(encoding, "replace")
         p = ConfirmationHTMLParser()
-        p.feed(data.decode("cp932", "replace"))
+        p.feed(data)
         p.close()
 
-        print data.decode("cp932")
+        print data
 
         window = gtk.Window()
         if not p.complete:
             window.set_default_size(500, 500)
+        if p.title:
+            window.set_title(p.title)
         textview = gtk.TextView()
         textview.set_wrap_mode(gtk.WRAP_CHAR)
         textview.set_editable(False)
@@ -175,9 +199,11 @@ class WinWrap:
             if "type" in input and input["type"] == "submit":
                 button = gtk.Button(input["value"])
                 button.connect("clicked",
-                               self.on_button_submit_clicked, p.inputs)
+                               lambda widget: self.on_button_submit_clicked(
+                    widget, p.inputs, encoding))
                 anchor = buf.create_child_anchor(buf.get_end_iter())
                 textview.add_child_at_anchor(button, anchor)
+                button.grab_focus()
                 break
 
         window.add(textview)
@@ -188,16 +214,19 @@ class WinWrap:
             def on_timeout(widget):
                 widget.destroy()
                 uri_opener.open_uri(self.bbs_type.get_thread_uri(), True)
+                self.window.destroy()
 
             gobject.timeout_add(2 * 1000, on_timeout, window)
 
-    def on_button_submit_clicked(self, widget, inputs=None):
+    def on_button_submit_clicked(self, widget, inputs, encoding):
         widget.get_toplevel().destroy()
         self.post_dict = {}
         for input in inputs:
             if "name" in input and "value" in input:
                 name = input["name"]
-                value = input["value"]
-                self.post_dict[name] = value.encode("cp932", "replace")
+                value = input["value"].replace("&#10;", "\n");
+                if encoding:
+                    value = value.encode(encoding, "replace")
+                self.post_dict[name] = value
 
         self.do_submit()