feedwarrior

Slim, portable tooling for creating and distributing decentralized append logs
git clone git://git.defalsify.org/logwarrior.git
Info | Log | Files | Refs | README | LICENSE

attach.py (1826B)


      1 # standard imports
      2 import sys
      3 import os
      4 from email.message import EmailMessage
      5 from email.mime.multipart import MIMEMultipart
      6 import email
      7 import logging
      8 import uuid
      9 import json
     10 import gzip
     11 import tempfile
     12 import base64
     13 import uuid
     14 
     15 # external imports
     16 import magic
     17 from mime_parser import parse_mime
     18 
     19 # local imports
     20 import feedwarrior
     21 from feedwarrior import entry as feedentry
     22 from feedwarrior.adapters import fileadapter
     23 from feedwarrior.entry import from_multipart
     24 #from feedwarrior.common import task_ids_to_uuids, check_task_uuids
     25 
     26 logg = logging.getLogger()
     27 
     28 
     29 def parse_args(argparser):
     30     argparser.add_argument('-e', '--entry', type=str, help='entry uuid to modify')
     31     argparser.add_argument('file', type=str, help='file to attach')
     32     return True
     33 
     34 
     35 def check_args(args):
     36     pass
     37 
     38 
     39 def from_file(m, fp):
     40     mg = magic.Magic(flags=magic.MAGIC_MIME_TYPE)
     41     mime_type_str = mg.id_filename(fp)
     42     mime_type = parse_mime(mime_type_str)
     43     logg.info('detected {} type for {}'.format(mime_type, fp))
     44 
     45     part = EmailMessage()
     46     part.add_header('Content-Type', mime_type_str)
     47     part.add_header('Content-Transfer-Encoding', 'BASE64')
     48     f = open(fp, 'rb')
     49     v = f.read()
     50     f.close()
     51     vb = base64.b64encode(v)
     52     part.set_payload(vb.decode('utf-8'))
     53 
     54     fn = os.path.basename(fp)
     55     part.add_header('Content-Disposition', 'attachment', filename=fn)
     56 
     57     m.attach(part)
     58     return m
     59 
     60 
     61 def execute(config, feed, args):
     62     fa = fileadapter(config.data_dir, None)
     63     (v, fm) = fa.get_with_type(args.entry) #, compress=args.z)
     64     j = json.loads(v)
     65     m = email.message_from_string(j['payload'])
     66 
     67     fp = os.path.realpath(args.file)
     68     attachment = from_file(m, fp)
     69     
     70     entry = from_multipart(attachment)
     71     compress = fm == 'gzip'
     72     fa.put(args.entry, entry, replace=True, compress=compress)