Logs a message with attachment.

        The attachment is a dict of:
            name: name of attachment
            data: file content
            mime: content type for attachment
180345
def log(self, time, message, level=None, attachment=None):
        
        logger.debug("log queued")

        args = {
            "time": time,
            "message": message,
            "level": level,
            "attachment": attachment,
        }
        self.queue.put_nowait(("log", args))
68585
def file_data(self):
        """"""
        return {
            'fileContent': self._file_content,
            'fileName': self._group_data.get('fileName'),
            'type': self._group_data.get('type'),
        }
1211446
def attach_binary(self, content, filename):
        
        content_type = guess_content_type(filename)
        payload = {"Name": filename, "Content": b64encode(content).decode("utf-8"), "ContentType": content_type}
        self.attach(payload)
1022085
def to_api_data(self):
        
        data = {'@odata.type': self._gk(
            '{}_attachment_type'.format(self.attachment_type)),
            self._cc('name'): self.name}

        if self.attachment_type == 'file':
            data[self._cc('contentBytes')] = self.content
        else:
            data[self._cc('item')] = self.content

        return data
1089563
def handle_log_data(self, m):
        ''''''
        if self.download_file is None:
            return
        # lose some data
        # import random
        # if random.uniform(0,1) < 0.05:
        #    print('dropping ', str(m))
        #    return
        if m.ofs != self.download_ofs:
            self.download_file.seek(m.ofs)
            self.download_ofs = m.ofs
        if m.count != 0:
            data = m.data[:m.count]
            s = ''.join(str(chr(x)) for x in data)
            self.download_file.write(s)
            self.download_set.add(m.ofs // 90)
            self.download_ofs += m.count
        self.download_last_timestamp = time.time()
        if m.count == 0 or (m.count < 90 and len(self.download_set) == 1 + (m.ofs // 90)):
            dt = time.time() - self.download_start
            self.download_file.close()
            size = os.path.getsize(self.download_filename)
            speed = size / (1000.0 * dt)
            print("Finished downloading %s (%u bytes %u seconds, %.1f kbyte/sec %u retries)" % (
                self.download_filename,
                size,
                dt, speed,
                self.retries))
            self.download_file = None
            self.download_filename = None
            self.download_set = set()
633379
def content(self):
        """"""

        if not self.payload:
            return ''

        if self.payload.is_multipart():
            message_bytes = mime_to_bytes(
                self.payload, 0).replace(b'\n', b'\r\n')
            boundary = b'--' + self.payload.get_boundary().encode('utf-8')
            temp = message_bytes.split(boundary)
            temp.pop(0)
            return boundary + boundary.join(temp)
        else:
            content = self.payload.get_payload()
            if isinstance(content, str_cls):
                content = content.encode('utf-8')
            return content
821436
def post_attachment(self, bugid, attachment):
        ''''''
        assert type(attachment) is DotDict
        assert 'data' in attachment
        assert 'file_name' in attachment
        assert 'summary' in attachment
        if (not 'content_type' in attachment): attachment.content_type = 'text/plain'
        attachment.ids = bugid
        attachment.data = base64.standard_b64encode(bytearray(attachment.data, 'ascii')).decode('ascii')

        return self._post('bug/{bugid}/attachment'.format(bugid=bugid), json.dumps(attachment))
901965
def log_to_file(self, message):
        """"""

        with self.build_fs.open(self.log_file, 'a+') as f:
            f.write(unicode(message + '\n'))
955067
def as_msg(self):
        
        # Based upon http://docs.python.org/2/library/email-examples.html
        # with minimal tweaking

        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(str(self.path))
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        if maintype == 'text':
            # Note: we should handle calculating the charset
            msg = MIMEText(self.path.read(), _subtype=subtype)
        elif maintype == 'image':
            fp = self.path.open('rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = self.path.open('rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = self.path.open('rb')
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            encoders.encode_base64(msg)

        filename = str(self.path[-1])
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        return msg
792151
def send(self):
        
        log = logging.getLogger(self.cls_logger + '.send')

        if self.attachments:
            self.payload['attachments'] = self.attachments

        # Encode payload in JSON
        log.debug('Using payload: %s', self.payload)
        try:
            json_payload = json.JSONEncoder().encode(self.payload)
        except(TypeError, ValueError, OverflowError):
            _, ex, trace = sys.exc_info()
            msg = 'There was a problem encoding the JSON payload\n{e}'.format(e=str(ex))
            raise OSError, msg, trace
        else:
            log.debug('JSON payload: %s', json_payload)

        # Post to Slack!
        log.debug('Posting message to Slack...')
        try:
            result = requests.post(url=self.webhook_url, data=json_payload)
        except requests.exceptions.ConnectionError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem posting to Slack\n{e}'.format(n=ex.__class__.__name__, e=str(ex))
            raise OSError, msg, trace

        # Check return code
        if result.status_code != 200:
            log.error('Slack post to url {u} failed with code: {c}'.format(c=result.status_code, u=self.webhook_url))
        else:
            log.debug('Posted message to Slack successfully.')

        # Clear out attachments after sending
        self.attachments = []
        self.payload.pop('attachments', None)
970595
def upload_attachment(self, location, data):
        
        self.validate_attachment_location(location)
        content = data.read() if hasattr(data, 'read') else data
        orig_content = content
        if isinstance(content, bytes):
            content = base64.b64encode(orig_content).decode('ascii')
        else:
            pass  # Should be base64 encoded already
        apath = '%s/%s' % (self.attachment_location, location)
        url = '%s/contents/%s' % (self.base_url, apath)
        result = requests.put(
            url, auth=(self.user, self.token), data=json.dumps({
                'message': 'file attachment %s' % location,
                'content': content}))
        if result.status_code != 201:
            raise ValueError(
                "Can't upload attachment %s due to error %s." % (
                    location, result.reason))
        return '[%s](https://github.com/%s/%s/blob/master/%s)' % (
            location, self.owner, self.realm, apath)
422187
def create_email(filepaths, collection_name):
    
    outer = MIMEMultipart()
    outer.preamble = 'Here are some files for you'

    def add_file_to_outer(path):
        if not os.path.isfile(path):
            return

        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)

        if maintype == 'image':
            fp = open(path, 'rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(path, 'rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'text':
            # We do this to catch cases where text files have
            # an encoding we can't guess correctly.
            try:
                fp = open(path, 'r')
                msg = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            except UnicodeDecodeError:
                fp = open(path, 'rb')
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                encoders.encode_base64(msg)
                fp.close()
        else:
            fp = open(path, 'rb')
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            encoders.encode_base64(msg)

        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment',
                filename=os.path.basename(path))
        outer.attach(msg)

    outer.attach(MIMEText("Here are some files I've thrown at you."))
    
    for path in filepaths:
        add_file_to_outer(path)

    return outer
783869
def files_content(record, identifier, path, frag_content)
      # preparing attachments
      files = frag_content.split("\n").collect do |filename|
        file_handler = File.open(File.join(path, filename))
        {
          io:           file_handler,
          filename:     filename,
          content_type: MimeMagic.by_magic(file_handler)
        }
      end

      # ensuring that old attachments get removed
      ids_destroy = []
      if (frag = record.fragments.find_by(identifier: identifier))
        ids_destroy = frag.attachments.pluck(:id)
      end

      [files, ids_destroy]
    end
497724
def get_content_type(self):
        
        mime_type, encoding = mimetypes.guess_type(self.filepath)
        if encoding == "gzip":
            return "application/gzip"
        elif encoding is not None:
            return "application/octet-stream"
        elif mime_type is not None:
            return mime_type
        # if mime_type not detected, use application/octet-stream
        else:
            return "application/octet-stream"
41794
def find_attachment
      content_type_name = header[:content_type].filename rescue nil
      content_disp_name = header[:content_disposition].filename rescue nil
      content_loc_name = header[:content_location].location rescue nil

      if content_type && content_type_name
        filename = content_type_name
      elsif content_disposition && content_disp_name
        filename = content_disp_name
      elsif content_location && content_loc_name
        filename = content_loc_name
      elsif self.mime_type == "message/rfc822"
        filename = "#{rand(100000000)}.eml"
      else
        filename = nil
      end

      if filename
        # Normal decode
        filename = Mail::Encodings.decode_encode(filename, :decode) rescue filename
      end
      filename
    end
1301207
def format_log(request, message_type, message):
    
    from django_socketio.settings import MESSAGE_LOG_FORMAT
    if MESSAGE_LOG_FORMAT is None:
        return None
    now = datetime.now().replace(microsecond=0)
    args = dict(request.META, TYPE=message_type, MESSAGE=message, TIME=now)
    return (MESSAGE_LOG_FORMAT % args) + "\n"
1208966
function buildAttMessageFunction(attachment, attachmentloc) {
        let filename = attachment.params.name;
        let encoding = attachment.encoding;

        return function(msg, seqno) {
            let prefix = '(#' + seqno + ') ';
            msg.on('body', function(stream, info) {
                if (attachmentloc) {
                    filename = attachmentloc + filename;
                }
                // Create a write stream so that we can stream the attachment to file;
                console.log(prefix + 'Streaming this attachment to file', filename, info);
                let writeStream = fs.createWriteStream(filename);
                writeStream.on('finish', function() {
                    console.log(prefix + 'Done writing to file %s', filename);
                });

                // stream.pipe(writeStream); this would write base64 data to the file.
                // so we decode during streaming using
                if (toUpper(encoding) === 'BASE64') {
                    // the stream is base64 encoded, so here the stream is decode on the fly and piped to the write stream (file)
                    stream.pipe(base64.decode()).pipe(writeStream);
                } else {
                    // here we have none or some other decoding streamed directly to the file which renders it useless probably
                    stream.pipe(writeStream);
                }
            });
            msg.once('end', function() {
                console.log(prefix + 'Finished attachment %s', filename);
            });
        };
    }