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