def add_attachment(message, filename): content_type, encoding = guess_mime_type(filename) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) if main_type == 'text': fp = open(filename, 'rb') msg = MIMEText(fp.read().decode(), _subtype=sub_type) fp.close() elif main_type == 'image': fp = open(filename, 'rb') msg = MIMEImage(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'audio': fp = open(filename, 'rb') msg = MIMEAudio(fp.read(), _subtype=sub_type) fp.close() else: fp = open(filename, 'rb') msg = MIMEBase(main_type, sub_type) msg.set_payload(fp.read()) fp.close() filename = os.path.basename(filename) msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg)
def find_file(self, http_path): p = urllib.request.url2pathname(http_path) for i, f0 in enumerate(self.torrent_info.files()): if "/"+f0.path == p: f1 = torrent_file_bt2p() f1.size = f0.size f1.map_file = lambda offset: self.torrent_info.map_file(i, offset, 1) f1.content_type = guess_mime_type(f0.path) return f1 return None
def find_file(self, http_path): p = urllib.url2pathname(http_path) for i, f0 in enumerate(self.torrent_info.files()): if "/"+f0.path == p: f1 = torrent_file_bt2p() f1.size = f0.size f1.map_file = lambda offset: self.torrent_info.map_file(i, offset, 1) f1.content_type = guess_mime_type(f0.path) return f1 return None
def _attach(self, afile, file_path, minify=False): """ Takes a path to a file, and the name of the attachment, works out it's mime type (assumes text/plain if it can't be determined) and returns the necessary dict to upload to a doc. """ mime = guess_mime_type(file_path)[0] if not mime: msg = 'Assuming text/plain mime type for %s' self.logger.warning(msg % file_path) mime = 'text/plain' if minify and mime == "application/javascript": data = self._minify(file_path) else: f = open(os.path.join(file_path)) data = base64.encodestring(f.read()) f.close() return {afile: {'data': data, 'content_type': mime}}
def _invoke_rest_outconn_callback(self, item_id, request): # type: (str, dict) -> None cid = new_cid() item = self.worker_store.get_outconn_rest_by_id(item_id) ping_response = item.ping(cid, return_response=True, log_verbose=True) # type: Response if ping_response.status_code != OK: logger.warn( 'Could not ping file transfer connection for `%s` (%s); config:`%s`, r:`%s`, h:`%s`', request['full_path'], request['config'].name, item.config, ping_response.text, ping_response.headers) else: file_name = request['file_name'] mime_type = guess_mime_type(file_name, strict=False) mime_type = mime_type[0] if mime_type[ 0] else 'application/octet-stream' payload = request['raw_data'] params = {'file_name': file_name, 'mime_type': mime_type} headers = { 'X-Zato-File-Name': file_name, 'X-Zato-Mime-Type': mime_type, } response = item.conn.post(cid, payload, params, headers=headers) # type: Response if response.status_code != OK: logger.warn( 'Could not send file `%s` (%s) to `%s` (p:`%s`, h:`%s`), r:`%s`, h:`%s`', request['full_path'], request['config'].name, item.config, params, headers, response.text, response.headers)
def _attach(self, afile, file_path, minify=False): """ Takes a path to a file, and the name of the attachment, works out it's mime type (assumes text/plain if it can't be determined) and returns the necessary dict to upload to a doc. """ mime = guess_mime_type(file_path)[0] if not mime: msg = 'Assuming text/plain mime type for %s' self.logger.warning(msg % file_path) mime = 'text/plain' if minify and mime == "application/javascript": data = self._minify(file_path) else: f = open(os.path.join(file_path)) data = base64.encodestring(f.read()) f.close() return {afile: { 'data': data, 'content_type': mime }}
def send( self, request, stream=False, verify=None, cert=None, proxies=None, timeout=None ): """issue request""" fname = url_unquote(request.url[len('file://'):]) if not fname: raise InvalidURL('missing file name') if '/' not in fname: raise InvalidURL( 'hostname without filename (perhaps missing a /?)' ) host, fname = fname.split('/', 1) fname = self.resolve_host(host, fname) response = Response() response.url = request.url response.headers['Date'] = formatdate(timeval=None, localtime=True) try: if request.method in ('GET', 'HEAD'): statdata = stat(fname) etag = '"%s/%s/%s' \ % (statdata.st_dev, statdata.st_ino, statdata.st_mtime) if S_ISLNK(statdata.st_mode): # handle relative symlinks! target_file = abspath(readlink(fname)) response.status_code = 302 response.headers['Status'] = '302 Found' response.headers['Location'] = \ url_quote('file://' + target_file) elif S_ISDIR(statdata.st_mode): response.status_code = 200 response.headers['Status'] = '200 Ok' body = \ """<html><head><title>%s</title></head><body><ul>""" \ % fname for subfname in sorted(listdir(fname)): body += '<li><a href="file://' + \ url_quote(subfname) + '">' + \ html_escape(fname) + '</a></li>' body += '</body></html>' response.headers['ETag'] = 'W/' + etag response.raw = StringIO(body) elif S_ISREG(statdata.st_mode): response.status_code = 200 response.headers['Content-Length'] = statdata.st_size response.headers['Last-Modified'] = formatdate( timeval=statdata.st_mtime, localtime=True ) mt, enc = guess_mime_type(request.url, strict=False) if mt is None: mt = 'application/octet-stream' if enc is not None: response.headers['Content-Encoding'] = enc response.headers['Content-Type'] = mt response.headers['ETag'] = etag if request.method == 'GET': response.raw = open(fname, 'r') else: response.status_code = 500 response.headers['Status'] = '500 Internal Server Error' elif request.method == 'PUT': open(fname, 'w').write(request.body) # FIXME: Is this right? response.status_code = 200 response.headers['Status'] = '200 Ok' elif request.method == 'POST': if exists(fname): # FIXME: Is this right? response.status_code = 409 response.headers['Status'] = '409 Conflict' else: open(fname, 'w').write(request.body) elif request.method == 'DELETE': unlink(fname) response.status_code = 200 response.headers['Status'] = '200 Ok' else: response.status_code = 405 response.headers['Status'] = '405 Method Not Allowed' except OSError as e: if e.errno == errno.ENOENT: if request.method == 'DELETE': response.status_code = 410 response.headers['Status'] = '410 Gone' else: response.status_code = 404 response.headers['Status'] = '404 Not Found' elif e.errno == errno.EISDIR: response.status_code = 405 response.headers['Status'] = '405 Method Not Allowed' response.raw = StringIO('Cannot %r a directory...' % request.method) elif e.errno == errno.EACCES: response.status_code = 403 response.headers['Status'] = '403 Forbidden' else: response.status_code = 500 response.headers['Status'] = '500 Internal Server Error' response.raw = StringIO('OSError: ' + strerror(e.errno)) except Exception: response.status_code = 500 response.headers['Status'] = '500 Internal Server Error' response.raw = StringIO(format_exc()) # context response.request = request response.connection = self # hooks response = dispatch_hook('response', request.hooks, response) # streaming if not stream: response.content return response