1 # Copyright (C) 2010 Google Inc. All rights reserved. 2 # 3 # Redistribution and use in source and binary forms, with or without 4 # modification, are permitted provided that the following conditions are 5 # met: 6 # 7 # * Redistributions of source code must retain the above copyright 8 # notice, this list of conditions and the following disclaimer. 9 # * Redistributions in binary form must reproduce the above 10 # copyright notice, this list of conditions and the following disclaimer 11 # in the documentation and/or other materials provided with the 12 # distribution. 13 # * Neither the name of Google Inc. nor the names of its 14 # contributors may be used to endorse or promote products derived from 15 # this software without specific prior written permission. 16 # 17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 29 import mimetypes 30 import time 31 import urllib2 32 33 from webkitpy.common.net.networktransaction import NetworkTransaction, NetworkTimeout 34 35 36 def get_mime_type(filename): 37 return mimetypes.guess_type(filename)[0] or 'application/octet-stream' 38 39 40 # FIXME: Rather than taking tuples, this function should take more structured data. 41 def _encode_multipart_form_data(fields, files): 42 """Encode form fields for multipart/form-data. 43 44 Args: 45 fields: A sequence of (name, value) elements for regular form fields. 46 files: A sequence of (name, filename, value) elements for data to be 47 uploaded as files. 48 Returns: 49 (content_type, body) ready for httplib.HTTP instance. 50 51 Source: 52 http://code.google.com/p/rietveld/source/browse/trunk/upload.py 53 """ 54 BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' 55 CRLF = '\r\n' 56 lines = [] 57 58 for key, value in fields: 59 lines.append('--' + BOUNDARY) 60 lines.append('Content-Disposition: form-data; name="%s"' % key) 61 lines.append('') 62 if isinstance(value, unicode): 63 value = value.encode('utf-8') 64 lines.append(value) 65 66 for key, filename, value in files: 67 lines.append('--' + BOUNDARY) 68 lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) 69 lines.append('Content-Type: %s' % get_mime_type(filename)) 70 lines.append('') 71 if isinstance(value, unicode): 72 value = value.encode('utf-8') 73 lines.append(value) 74 75 lines.append('--' + BOUNDARY + '--') 76 lines.append('') 77 body = CRLF.join(lines) 78 content_type = 'multipart/form-data; boundary=%s' % BOUNDARY 79 return content_type, body 80 81 82 class FileUploader(object): 83 def __init__(self, url, timeout_seconds): 84 self._url = url 85 self._timeout_seconds = timeout_seconds 86 87 def upload_single_text_file(self, filesystem, content_type, filename): 88 return self._upload_data(content_type, filesystem.read_text_file(filename)) 89 90 def upload_as_multipart_form_data(self, filesystem, files, attrs): 91 file_objs = [] 92 for filename, path in files: 93 file_objs.append(('file', filename, filesystem.read_binary_file(path))) 94 95 # FIXME: We should use the same variable names for the formal and actual parameters. 96 content_type, data = _encode_multipart_form_data(attrs, file_objs) 97 return self._upload_data(content_type, data) 98 99 def _upload_data(self, content_type, data): 100 def callback(): 101 # FIXME: Setting a timeout, either globally using socket.setdefaulttimeout() 102 # or in urlopen(), doesn't appear to work on Mac 10.5 with Python 2.7. 103 # For now we will ignore the timeout value and hope for the best. 104 request = urllib2.Request(self._url, data, {"Content-Type": content_type}) 105 return urllib2.urlopen(request) 106 107 return NetworkTransaction(timeout_seconds=self._timeout_seconds).run(callback) 108