CrunchBang Linux Pastebin - collaborative debugging

pastebin is a collaborative debugging tool allowing you to share and modify code snippets while chatting on IRC, IM or a message board.

This site is developed to XHTML and CSS2 W3C standards. If you see this paragraph, your browser does not support those standards and you need to upgrade. Visit WaSP for a variety of options.

CrunchBang Linux Pastebin

Posted by iggykoopa on Tue 11th Aug 21:55 (modification of post by iggykoopa view diff)
diff | download | new post

  1. #!/usr/bin/env python
  2.  
  3. import cookielib
  4. import urllib
  5. import urllib2
  6. import mimetools, mimetypes
  7. import os, stat
  8. from cStringIO import StringIO
  9. import gtk, pygtk
  10. from optparse import OptionParser
  11.  
  12. class Callable:
  13.     def __init__(self, anycallable):
  14.         self.__call__ = anycallable
  15.  
  16. # Controls how sequences are uncoded. If true, elements may be given multiple values by
  17. #  assigning a sequence.
  18. doseq = 1
  19.  
  20. class MultipartPostHandler(urllib2.BaseHandler):
  21.     handler_order = urllib2.HTTPHandler.handler_order - 10 # needs to run first
  22.  
  23.     def http_request(self, request):
  24.         data = request.get_data()
  25.         if data is not None and type(data) != str:
  26.             v_files = []
  27.             v_vars = []
  28.             try:
  29.                  for(key, value) in data.items():
  30.                      if type(value) == file:
  31.                          v_files.append((key, value))
  32.                      else:
  33.                          v_vars.append((key, value))
  34.             except TypeError:
  35.                 systype, value, traceback = sys.exc_info()
  36.                 raise TypeError, "not a valid non-string sequence or mapping object", traceback
  37.  
  38.             if len(v_files) == 0:
  39.                 data = urllib.urlencode(v_vars, doseq)
  40.             else:
  41.                 boundary, data = self.multipart_encode(v_vars, v_files)
  42.  
  43.                 contenttype = 'multipart/form-data; boundary=%s' % boundary
  44.                 if(request.has_header('Content-Type')
  45.                    and request.get_header('Content-Type').find('multipart/form-data') != 0):
  46.                     print "Replacing %s with %s" % (request.get_header('content-type'), 'multipart/form-data')
  47.                 request.add_unredirected_header('Content-Type', contenttype)
  48.  
  49.             request.add_data(data)
  50.        
  51.         return request
  52.  
  53.     def multipart_encode(vars, files, boundary = None, buf = None):
  54.         if boundary is None:
  55.             boundary = mimetools.choose_boundary()
  56.         if buf is None:
  57.             buf = StringIO()
  58.         for(key, value) in vars:
  59.             buf.write('--%s\r\n' % boundary)
  60.             buf.write('Content-Disposition: form-data; name="%s"' % key)
  61.             buf.write('\r\n\r\n' + value + '\r\n')
  62.         for(key, fd) in files:
  63.             file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
  64.             filename = fd.name.split('/')[-1]
  65.             contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
  66.             buf.write('--%s\r\n' % boundary)
  67.             buf.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename))
  68.             buf.write('Content-Type: %s\r\n' % contenttype)
  69.             # buffer += 'Content-Length: %s\r\n' % file_size
  70.             fd.seek(0)
  71.             buf.write('\r\n' + fd.read() + '\r\n')
  72.         buf.write('--' + boundary + '--\r\n\r\n')
  73.         buf = buf.getvalue()
  74.         return boundary, buf
  75.     multipart_encode = Callable(multipart_encode)
  76.  
  77.     https_request = http_request
  78.  
  79. def uploader(file_path,method):
  80.     size = os.path.getsize(file_path)
  81.     if size < 1073741824:
  82.         if method == "cli":
  83.             print "uploading... please wait"
  84.         else:
  85.             md = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Uploading... please wait")
  86.             md.run()
  87.             md.destroy()
  88.         try:
  89.             cookies = cookielib.CookieJar()
  90.             opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),MultipartPostHandler)
  91.             params = { "file1" : open(file_path, "rb") }
  92.             results = opener.open("http://omploader.org/upload", params).read()
  93.         except:
  94.             if method == "cli":
  95.                 print "Upload failed"
  96.                 raise SystemExit()
  97.             else:
  98.                 md = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Upload failed")
  99.                 md.run()
  100.                 md.destroy()
  101.                 raise SystemExit()
  102.         path = ""
  103.         for line in results.split("\n"):
  104.             if 'href="/v' in line:
  105.                 line = line.split('"')
  106.                 for section in line:
  107.                     if "/v" in section:
  108.                         path = section
  109.                         break
  110.                 break
  111.         if path:
  112.             if method == "cli":
  113.                 print "Uploaded to: http://omploader.org" + path
  114.             else:
  115.                 md = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Uploaded to http://omploader.org" + path)
  116.                 md.run()
  117.                 md.destroy()
  118.         else:
  119.             if method == "cli":
  120.                 print "Upload failed"
  121.             else:
  122.                 md = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Upload failed")
  123.                 md.run()
  124.                 md.destroy()
  125.     else:
  126.         if method == "cli":
  127.             print "file too big"
  128.         else:
  129.             md = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, "File too big")
  130.             md.run()
  131.             md.destroy()
  132.  
  133.  
  134. def file_chooser():   
  135.     dialog = gtk.FileChooserDialog("Open..",None,gtk.FILE_CHOOSER_ACTION_OPEN,(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN, gtk.RESPONSE_OK))
  136.     dialog.set_default_response(gtk.RESPONSE_OK)
  137.     response = dialog.run()
  138.     if response == gtk.RESPONSE_OK:
  139.         uploader(dialog.get_filename(),"gui")
  140.     elif response == gtk.RESPONSE_CANCEL:
  141.         raise SystemExit()
  142.     dialog.destroy()
  143.  
  144. parser = OptionParser()
  145. (options, args) = parser.parse_args() 
  146. if args:
  147.     if os.path.isfile(args[0]):
  148.         if len(args) > 1:
  149.             uploader(args[0],args[1])
  150.         else:
  151.             uploader(args[0],"cli")
  152.     else:
  153.         print "not a valid file"
  154. else:
  155.     file_chooser()

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with @@


Remember me