Esempio n. 1
0
    def on_generate(self, event):
        today = datetime.date.today()
        bills = []
        item = -1
        while True:
            item = self.reminders.GetNextSelected(item)
            if item == -1:
                break
            id_bill = self.data[item][0]
            self.cursor.execute(
                """INSERT INTO reminders (id_bill, amount_cts, reminder_date) VALUES (%s, %s, %s)""",
                [id_bill, custo.MONTANT_RAPPEL_CTS, today])

            bills.append(Bill.load(self.cursor, id_bill))
        consults = [b for b in bills if b.type == BILL_TYPE_CONSULTATION]
        if consults:
            filename = normalize_filename(datetime.datetime.now().strftime(
                'rappels_consultations_%F_%Hh%Mm%Ss.pdf'))
            pdf_bills.consultations(filename, consults)
            cmd, cap = mailcap.findmatch(mailcap.getcaps(), 'application/pdf',
                                         'view', filename)
            os.system(cmd)
        manuals = [b for b in bills if b.type == BILL_TYPE_MANUAL]
        if manuals:
            filename = normalize_filename(datetime.datetime.now().strftime(
                'rappels_factures_manuelles_%F_%Hh%Mm%Ss.pdf'))
            pdf_bills.manuals(filename, manuals)
            cmd, cap = mailcap.findmatch(mailcap.getcaps(), 'application/pdf',
                                         'view', filename)
            os.system(cmd)
        self.Close()
Esempio n. 2
0
def get_mime_handler(mime_type, key='view', interactive=True):
    """
    get shellcomand defined in the users `mailcap` as handler for files of
    given `mime_type`.

    :param mime_type: file type
    :type mime_type: str
    :param key: identifies one of possibly many commands for this type by
                naming the intended usage, e.g. 'edit' or 'view'. Defaults
                to 'view'.
    :type key: str
    :param interactive: choose the "interactive session" handler rather than
                        the "print to stdout and immediately return" handler
    :type interactive: bool
    """
    if interactive:
        mc_tuple = mailcap.findmatch(mailcaps,
                                     mime_type,
                                     key=key)
    else:
        mc_tuple = mailcap.findmatch(mailcaps,
                                     mime_type,
                                     key='copiousoutput')
    if mc_tuple:
        if mc_tuple[1]:
            return mc_tuple[1][key]
    else:
        return None
Esempio n. 3
0
 def on_print_again(self, event):
     bill_ids = [
         id for i, id in enumerate(self.data) if self.payments.IsSelected(i)
     ]
     if bill_ids:
         bills = [Bill.load(self.cursor, id_bill) for id_bill in bill_ids]
         consults = [b for b in bills if b.type == BILL_TYPE_CONSULTATION]
         if consults:
             filename_consult = normalize_filename(
                 datetime.datetime.now().strftime(
                     'consultations_%F_%Hh%Mm%Ss.pdf'))
             pdf_bills.consultations(filename_consult, consults)
             cmd, cap = mailcap.findmatch(mailcap.getcaps(),
                                          'application/pdf', 'view',
                                          filename_consult)
             os.system(cmd + '&')
         manuals = [b for b in bills if b.type == BILL_TYPE_MANUAL]
         if manuals:
             filename_manual = normalize_filename(
                 datetime.datetime.now().strftime(
                     'fact_manuelles_%F_%Hh%Mm%Ss.pdf'))
             pdf_bills.manuals(filename_manual, manuals)
             cmd, cap = mailcap.findmatch(mailcap.getcaps(),
                                          'application/pdf', 'view',
                                          filename_manual)
             os.system(cmd + '&')
Esempio n. 4
0
def get_mime_handler(mime_type, key='view', interactive=True):
    if interactive:
        mc_tuple = mailcap.findmatch(mailcaps,
                                     mime_type,
                                     key=key)
    else:
        mc_tuple = mailcap.findmatch(mailcaps,
                                     mime_type,
                                     key='copiousoutput')
    if mc_tuple:
        if mc_tuple[1]:
            return mc_tuple[1][key]
    else:
        return None
Esempio n. 5
0
    def spawn_external_viewer(self, data, contenttype):
        if contenttype:
            contenttype = contenttype.split(";")[0]
            ext = mimetypes.guess_extension(contenttype) or ""
        else:
            ext = ""
        fd, name = tempfile.mkstemp(ext, "mproxy")
        os.write(fd, data)
        os.close(fd)

        # read-only to remind the user that this is a view function
        os.chmod(name, stat.S_IREAD)

        cmd = None
        shell = False

        if contenttype:
            c = mailcap.getcaps()
            cmd, _ = mailcap.findmatch(c, contenttype, filename=name)
            if cmd:
                shell = True
        if not cmd:
            # hm which one should get priority?
            c = os.environ.get("PAGER") or os.environ.get("EDITOR")
            if not c:
                c = "less"
            cmd = shlex.split(c)
            cmd.append(name)
        self.ui.stop()
        try:
            subprocess.call(cmd, shell=shell)
        except:
            signals.status_message.send(message="Can't start external viewer: %s" % " ".join(c))
        self.ui.start()
        os.unlink(name)
Esempio n. 6
0
    def spawn_external_viewer(self, data, contenttype):
        if contenttype:
            contenttype = contenttype.split(";")[0]
            ext = mimetypes.guess_extension(contenttype) or ""
        else:
            ext = ""
        fd, name = tempfile.mkstemp(ext, "mproxy")
        os.write(fd, data)
        os.close(fd)

        # read-only to remind the user that this is a view function
        os.chmod(name, stat.S_IREAD)

        cmd = None
        shell = False

        if contenttype:
            c = mailcap.getcaps()
            cmd, _ = mailcap.findmatch(c, contenttype, filename=name)
            if cmd:
                shell = True
        if not cmd:
            # hm which one should get priority?
            c = os.environ.get("PAGER") or os.environ.get("EDITOR")
            if not c:
                c = "less"
            cmd = shlex.split(c)
            cmd.append(name)
        with self.uistopped():
            try:
                subprocess.call(cmd, shell=shell)
            except:
                signals.status_message.send(
                    message="Can't start external viewer: %s" % " ".join(c))
        os.unlink(name)
Esempio n. 7
0
def get_file_handler(file_path, default=None):
    mtype, _ = mimetypes.guess_type(file_path)
    if not mtype:
        return default
    caps = mailcap.getcaps()
    handler, view = mailcap.findmatch(caps, mtype, filename=file_path)
    if not handler:
        return config.DEFAULT_OPEN.format(file_path=shlex.quote(file_path))
    return handler
Esempio n. 8
0
 def on_validate(self, event):
     if self.payment_method.StringSelection == 'BVR':
         bill = self.data[self.selected_idx]
         if bill.status == STATUS_OPENED:
             filename_consult = normalize_filename(datetime.datetime.now().strftime('consultation_%F_%Hh%Mm%Ss.pdf'))
             bills.consultations(filename_consult, [bill])
             cmd, cap = mailcap.findmatch(mailcap.getcaps(), 'application/pdf', 'view', filename_consult)
             os.system(cmd + '&')
     self.real_validate()
     self.on_refresh(None)
Esempio n. 9
0
def get_file_handler(file_path: str) -> str:
    mtype, _ = mimetypes.guess_type(file_path)
    if not mtype:
        return config.DEFAULT_OPEN.format(file_path=shlex.quote(file_path))

    caps = get_mailcap()
    handler, view = mailcap.findmatch(caps, mtype, filename=file_path)
    if not handler:
        return config.DEFAULT_OPEN.format(file_path=shlex.quote(file_path))
    return handler
Esempio n. 10
0
def run_server(args):
    sv = Server(path=args.socket, dir=args.dir)
    caps = mailcap.getcaps()
    open(args.pid, "w+").write(str(os.getpid()))
    while True:
        rv = sv.next_file()
        if rv:
            f, mime = rv
            print(f, mime)
            match = mailcap.findmatch(caps, mime.split(';')[0], filename=f)
            if match and match[0]:
                os.system(match[0])
Esempio n. 11
0
def mailcap_view(path, content_type=None, background=False):
    if content_type is None:
        content_type, encoding = _mimetypes.guess_type(path)
        if content_type is None:
            return 1
        _LOG.debug("guessed {} for {}".format(content_type, path))
    match = _mailcap.findmatch(_CAPS, content_type, filename=_shlex.quote(path))
    if match[0] is None:
        _LOG.warn("no mailcap viewer found for {}".format(content_type))
        raise NotImplementedError(content_type)
    _LOG.debug("view {} with: {}".format(path, match[0]))
    process = _subprocess.Popen(match[0], shell=True)
    if background:
        return process
    return process.wait()
Esempio n. 12
0
def get_viewer_cmd(aMimeType = None, aFileName = None, aToken = None):
	"""Return command for viewer for this mime type complete with this file"""

	if aFileName is None:
		_log.error("You should specify a file name for the replacement of %s.")
		# last resort: if no file name given replace %s in original with literal '%s'
		# and hope for the best - we certainly don't want the module default "/dev/null"
		aFileName = """%s"""

	mailcaps = mailcap.getcaps()
	(viewer, junk) = mailcap.findmatch(mailcaps, aMimeType, key = 'view', filename = '%s' % aFileName)
	# FIXME: we should check for "x-token" flags

	_log.debug("<%s> viewer: [%s]" % (aMimeType, viewer))

	return viewer
Esempio n. 13
0
def get_editor_cmd(mimetype=None, filename=None):

	if filename is None:
		_log.error("You should specify a file name for the replacement of %s.")
		# last resort: if no file name given replace %s in original with literal '%s'
		# and hope for the best - we certainly don't want the module default "/dev/null"
		filename = """%s"""

	mailcaps = mailcap.getcaps()
	(editor, junk) = mailcap.findmatch(mailcaps, mimetype, key = 'edit', filename = '%s' % filename)

	# FIXME: we should check for "x-token" flags

	_log.debug("<%s> editor: [%s]" % (mimetype, editor))

	return editor
Esempio n. 14
0
def get_viewer_cmd(aMimeType = None, aFileName = None, aToken = None):
	"""Return command for viewer for this mime type complete with this file"""

	if aFileName is None:
		_log.error("You should specify a file name for the replacement of %s.")
		# last resort: if no file name given replace %s in original with literal '%s'
		# and hope for the best - we certainly don't want the module default "/dev/null"
		aFileName = """%s"""

	mailcaps = mailcap.getcaps()
	(viewer, junk) = mailcap.findmatch(mailcaps, aMimeType, key = 'view', filename = '%s' % aFileName)
	# FIXME: we should check for "x-token" flags

	_log.debug("<%s> viewer: [%s]" % (aMimeType, viewer))

	return viewer
Esempio n. 15
0
    def test_backwards_compatible(self):
        os.environ['MAILCAPS'] = TRIVIAL

        d = mailcap.getcaps()
        d_lineno = mailcap_fix.getcaps()

        # Note: Both of these cases should not break, but they will exhibit the
        # old, incorrect behavior and return the second entry

        # Call the patched findmatch() using an  dict without ``lineno``
        command, entry = mailcap_fix.findmatch(d, 'image/jpeg', filename='a')
        self.assertEqual(command, 'eog a')

        # Call the original findmatch() using a dict with the added ``lineno``
        command, entry = mailcap.findmatch(d_lineno, 'image/jpeg', filename='a')
        self.assertEqual(command, 'eog a')
Esempio n. 16
0
 def on_change_payment(self, event):
     bill = self.data[self.selected_idx]
     if self.payment_method.StringSelection == 'BVR':
         if not askyesno(windows_title.confirm_change, labels_text.ask_confirm_payment_method_change_to_BVR):
             return
         bill.bv_ref = gen_bvr_ref(self.cursor, bill.firstname, bill.lastname, bill.timestamp)
     else:
         bill.bv_ref = None
     bill.payment_method = self.payment_method.StringSelection
     bill.save(self.cursor)
     filename_consult = normalize_filename(datetime.datetime.now().strftime('consultation_%F_%Hh%Mm%Ss.pdf'))
     bills.consultations(filename_consult, [bill])
     cmd, cap = mailcap.findmatch(mailcap.getcaps(), 'application/pdf', 'view', filename_consult)
     os.system(cmd + '&')
     self.real_validate()
     self.on_refresh(None)
Esempio n. 17
0
def get_editor_cmd(mimetype=None, filename=None):

	if filename is None:
		_log.error("You should specify a file name for the replacement of %s.")
		# last resort: if no file name given replace %s in original with literal '%s'
		# and hope for the best - we certainly don't want the module default "/dev/null"
		filename = """%s"""

	mailcaps = mailcap.getcaps()
	(editor, junk) = mailcap.findmatch(mailcaps, mimetype, key = 'edit', filename = '%s' % filename)

	# FIXME: we should check for "x-token" flags

	_log.debug("<%s> editor: [%s]" % (mimetype, editor))

	return editor
Esempio n. 18
0
def run_viewer(file_):
    """Run PDF viewer on given file.

    Run it on a remote station if requested in configuration and the remote
    station is available.

    Arguments:

      file_ -- tempfile.NamedTemporaryFile instance

    """
    import subprocess
    file_name = file_.name
    viewer = config.postscript_viewer
    remote = (config.rpc_remote_view and pytis.remote.client_available())
    if remote:
        suffix = (os.path.splitext(file_name)[1] or '.pdf')
        try:
            remote_file = pytis.remote.make_temporary_file(suffix=suffix)
            if remote_file is None:
                remote = False
        except:
            remote = False
    if remote:
        try:
            f = open(file_name)
            while True:
                data = f.read(10000000)
                if not data:
                    break
                remote_file.write(data)
            f.close()
        finally:
            remote_file.close()
        pytis.remote.launch_file(remote_file.name())
    elif viewer:
        call_args = viewer.split()
        subprocess.call(call_args + [file_name])
    else:
        import mailcap
        match = mailcap.findmatch(mailcap.getcaps(), 'application/pdf')[1]
        if match:
            command = match['view'] % (file_name,)
            os.system(command)
        else:
            from pytis.form import run_dialog
            run_dialog(Error, _("No PDF viewer found."))
Esempio n. 19
0
def run_viewer(file_):
    """Run PDF viewer on given file.

    Run it on a remote station if requested in configuration and the remote
    station is available.

    Arguments:

      file_ -- tempfile.NamedTemporaryFile instance

    """
    import subprocess
    file_name = file_.name
    viewer = config.postscript_viewer
    remote = (config.rpc_remote_view and pytis.remote.client_available())
    if remote:
        suffix = (os.path.splitext(file_name)[1] or '.pdf')
        try:
            remote_file = pytis.remote.make_temporary_file(suffix=suffix)
            if remote_file is None:
                remote = False
        except:
            remote = False
    if remote:
        try:
            f = open(file_name)
            while True:
                data = f.read(10000000)
                if not data:
                    break
                remote_file.write(data)
            f.close()
        finally:
            remote_file.close()
        pytis.remote.launch_file(remote_file.name())
    elif viewer:
        call_args = viewer.split()
        subprocess.call(call_args + [file_name])
    else:
        import mailcap
        match = mailcap.findmatch(mailcap.getcaps(), 'application/pdf')[1]
        if match:
            command = match['view'] % (file_name, )
            os.system(command)
        else:
            from pytis.form import run_dialog
            run_dialog(Error, _("No PDF viewer found."))
Esempio n. 20
0
 def open_file(filename):
     if not os.path.isfile(filename):
         msg = 'File %s not found.' % filename
         raise Exception(msg)
     
     # Add mime types that may not be officially recognized
     mimetypes.add_type('text/csv', '.csv', strict=False)
     
     mime_type = mimetypes.guess_type(filename, strict=0)[0]
     if not mime_type:
         raise Exception(
             'File type has no association. Check your mailcap file.'
             )
     cap = mailcap.findmatch(
         mailcap.getcaps(),
         mime_type,
         filename="'%s'" % (filename)
         )
     command = cap[0]
     os.system(command + ' &')
Esempio n. 21
0
 def on_change_payment(self, event):
     bill = self.data[self.selected_idx]
     if self.payment_method.StringSelection == 'BVR':
         if not askyesno(
                 "Confirmer le changement",
                 "Voulez-vous vraiment changer la méthode de paiement vers BVR ?"
         ):
             return
         bill.bv_ref = gen_bvr_ref(self.cursor, bill.firstname,
                                   bill.lastname, bill.timestamp)
     else:
         bill.bv_ref = None
     bill.payment_method = self.payment_method.StringSelection
     bill.save(self.cursor)
     filename_consult = normalize_filename(
         datetime.datetime.now().strftime('consultation_%F_%Hh%Mm%Ss.pdf'))
     bills.consultations(filename_consult, [bill])
     cmd, cap = mailcap.findmatch(mailcap.getcaps(), 'application/pdf',
                                  'view', filename_consult)
     os.system(cmd + '&')
     self.real_validate()
     self.on_refresh(None)
Esempio n. 22
0
    def GetMimeCommands(self, mimeType=None, ext=None):
        """
        """
        cdict = dict()
        view = 'view'

        if mimeType == None:
            mimeType = self.GetMimeType(extension=ext)

        # We only care about mapping view to Open
        caps = mailcap.getcaps()

        # This always returns a tuple, so this should be safe
        if mimeType != None:
            match = mailcap.findmatch(caps, mimeType, view)[1]
        else:
            return cdict

        if match != None:
            cdict['Open'] = match[view]

        return cdict
Esempio n. 23
0
    def GetMimeCommands(self, mimeType = None, ext = None):
        """
        """
        cdict = dict()
        view = 'view'
        
        if mimeType == None:
            mimeType = self.GetMimeType(extension = ext)
            
        # We only care about mapping view to Open
        caps = mailcap.getcaps()

        # This always returns a tuple, so this should be safe
        if mimeType != None:
            match = mailcap.findmatch(caps, mimeType, view)[1]
        else:
            return cdict

        if match != None:
            cdict['Open'] = match[view]

        return cdict
Esempio n. 24
0
 def handle_eof(self):
     if not self.save_file:
         if self.fragment:
             self.viewer.scroll_to(self.fragment)
         elif self.scrollpos:
             self.viewer.scroll_to_position(self.scrollpos)
         return
     self.save_file.close()
     self.save_file = None
     if not self.save_mailcap:
         self.last_context.message("Saved.")
         return
     import mailcap
     command, entry = mailcap.findmatch(
         caps, self.save_content_type, 'view',
         self.save_filename, self.save_plist)
     if not command:
         command = self.save_mailcap
     self.last_context.message("Mailcap: %s" % command)
     command = "(%s; rm -f %s)&" % (command, self.save_filename)
     sts = os.system(command)
     if sts:
         print "Exit status", sts, "from command", command
Esempio n. 25
0
 def handle_eof(self):
     if not self.save_file:
         if self.fragment:
             self.viewer.scroll_to(self.fragment)
         elif self.scrollpos:
             self.viewer.scroll_to_position(self.scrollpos)
         return
     self.save_file.close()
     self.save_file = None
     if not self.save_mailcap:
         self.last_context.message("Saved.")
         return
     import mailcap
     command, entry = mailcap.findmatch(
         caps, self.save_content_type, 'view',
         self.save_filename, self.save_plist)
     if not command:
         command = self.save_mailcap
     self.last_context.message("Mailcap: %s" % command)
     command = "(%s; rm -f %s)&" % (command, self.save_filename)
     sts = os.system(command)
     if sts:
         print "Exit status", sts, "from command", command
Esempio n. 26
0
    def displayFile(self, filerec):
        """Uses a new method of file storage with blobs"""
        #now we just get the blob from the filerecord object...
        from PILView import PILViewer
        from PEATDB.Record import FileRecord
        #check class
        if not type(filerec) is FileRecord:
            return False
        myblob = filerec.blob
        ext = filerec.ext
        mtype = filerec.mimetype
        print 'mimetype is', mtype
        if myblob != None:
            f = myblob.open("r")
            filename = f.name
            f.close()
        else:
            return False

        if self.currplatform == 'Linux':
            #try using mailcaps on linux system
            import mailcap, os
            d = mailcap.getcaps()
            print mtype, filename
            f = mailcap.findmatch(d, mtype)[1]
            os.system(f['view'] % filename)
            return
        else:
            import os, tempfile, shutil
            tempname = os.path.normpath(
                os.path.join(tempfile.gettempdir(), filerec.name))
            if not os.path.exists(tempname):
                #os.remove(tempname)
                shutil.copy(filename, tempname)
            os.startfile(tempname)

        return True
Esempio n. 27
0
    def getUnixHandler(self, mime_types):

        ## in case the type has more than one mime-type, only use
        ## the first one for now...
        mime_type = mime_types[0]
    
        import mailcap
        caps = mailcap.getcaps()
        match = mailcap.findmatch(caps, mime_type)
       
        if match == (None, None):
            return "<None>"
        else:
            try:
                cmd = match[0]
                exec_path = cmd.split()
                exec_file = os.path.split(exec_path[0])[1]
            except:
                return "<None>"

            if len(exec_path) > 2:
                return exec_file + " " + ' '.join(exec_path[1:-1]) 
            else:
                return exec_file
Esempio n. 28
0
    def getUnixHandler(self, mime_types):

        ## in case the type has more than one mime-type, only use
        ## the first one for now...
        mime_type = mime_types[0]

        import mailcap
        caps = mailcap.getcaps()
        match = mailcap.findmatch(caps, mime_type)

        if match == (None, None):
            return "<None>"
        else:
            try:
                cmd = match[0]
                exec_path = cmd.split()
                exec_file = os.path.split(exec_path[0])[1]
            except:
                return "<None>"

            if len(exec_path) > 2:
                return exec_file + " " + ' '.join(exec_path[1:-1])
            else:
                return exec_file
Esempio n. 29
0
    def displayFile(self, filerec):
        """Uses a new method of file storage with blobs"""
        #now we just get the blob from the filerecord object...
        from PILView import PILViewer
        from PEATDB.Record import FileRecord
        #check class        
        if not type(filerec) is FileRecord:           
            return False
        myblob = filerec.blob
        ext = filerec.ext
        mtype = filerec.mimetype
        print 'mimetype is', mtype
        if myblob != None:
            f = myblob.open("r")
            filename = f.name
            f.close()
        else:
            return False

        if self.currplatform == 'Linux':
            #try using mailcaps on linux system
            import mailcap, os
            d=mailcap.getcaps()
            print mtype, filename
            f=mailcap.findmatch(d, mtype)[1]
            os.system(f['view'] %filename)
            return
        else:
            import os, tempfile, shutil
            tempname = os.path.normpath(os.path.join(tempfile.gettempdir(), filerec.name))
            if not os.path.exists(tempname):
                #os.remove(tempname)
                shutil.copy(filename, tempname)
            os.startfile(tempname)

        return True
Esempio n. 30
0
    def handle_meta(self, errcode, errmsg, headers):
        if not self.handle_meta_prelim(errcode, errmsg, headers):
            return

        # This updates the attributes in the bookmarks database.
        try:
            bkmks = self.last_context.app.bookmarks_controller
        except AttributeError:
            pass
        else:
            last_modified = None
            if headers.has_key("last-modified"):
                try: last_modified = ht_time.parse(headers["last-modified"])
                except ValueError: pass
            bkmks.record_visit(self.url, last_modified)

        content_encoding, transfer_encoding = get_encodings(headers)
        if headers.has_key('content-type'):
            content_type = headers['content-type']
            if ';' in content_type:
                content_type = string.strip(
                    content_type[:string.index(content_type, ';')])
        else:
            content_type, encoding = self.app.guess_type(self.url)
            if not content_encoding:
                content_encoding = encoding
        real_content_type = content_type or "unknown"
        real_content_encoding = content_encoding
        if (transfer_encoding
            and not transfer_decoding_wrappers.has_key(transfer_encoding)) \
            or (content_encoding
                and not content_decoding_wrappers.has_key(content_encoding)):
            # XXX provisional hack -- change content type to octet stream
            content_type = "application/octet-stream"
            transfer_encoding = None
            content_encoding = None
        if not content_type:
            content_type = "text/plain" # Last resort guess only

        istext = content_type and content_type[:5] == 'text/' \
                 and not (content_encoding or transfer_encoding)
        if self.show_source and istext:
            content_type = 'text/plain'
        parserclass = self.find_parser_extension(content_type)
        if not parserclass and istext:
            if content_type != 'text/plain':
                # still need to check for text/plain
                parserclass = self.find_parser_extension('text/plain')
            if not parserclass:
                parserclass = TextParser

        if not parserclass:
            # Don't know how to display this.
            # First consult mailcap.
            import mailcap
            global caps
            if not caps:
                caps = mailcap.getcaps()
            if caps:
                plist = [] # XXX Should be taken from Content-type header
                command, entry = mailcap.findmatch(
                    caps, content_type, 'view', "/dev/null", plist)
                if command:
                    # Retrieve to temporary file.
                    import tempfile
                    self.save_mailcap = command
                    self.save_filename = tempfile.mktemp()
                    self.save_content_type = content_type
                    self.save_plist = plist
                    self.save_file = open(self.save_filename, "wb")
                    # remember the original click location
                    self.app.global_history.remember_url(self.url)
                    self.viewer.remove_temp_tag(histify=1)
                    return
            # No relief from mailcap either.
            # Ask the user whether and where to save it.
            # Stop the transfer, and restart when we're ready.
            context = self.last_context
            # TBD: hack so that Context.rmreader() doesn't call
            # Viewer.remove_temp_tag().  We'll call that later
            # explicitly once we know whether the file has been saved
            # or not.
            context.source = None
            self.stop()
            context.message("Wait for save dialog...")
            encoding = ''
            if real_content_encoding:
                encoding = real_content_encoding + "ed "
                if encoding[:2] == "x-":
                    encoding = encoding[2:]
            encoding_label = "MIME type: %s%s" % (encoding, real_content_type)
            import FileDialog
            fd = FileDialog.SaveFileDialog(context.root)
            label = Label(fd.top, text=encoding_label)
            label.pack(before=fd.filter)
            # give it a default filename on which save within the
            # current directory
            urlasfile = string.splitfields(self.url, '/')
            fn = fd.go(default=urlasfile[-1], key="save")
            if not fn:
                # User canceled.  Stop the transfer.
                self.viewer.remove_temp_tag()
                return
            self.viewer.remove_temp_tag(histify=1)
            self.app.global_history.remember_url(self.url)
            # Prepare to save.
            # Always save in binary mode.
            try:
                self.save_file = open(fn, "wb")
            except IOError, msg:
                context.error_dialog(IOError, msg)
                return
            TransferDisplay(context, fn, self)
            return
Esempio n. 31
0
# https://docs.python.org/zh-cn/3/library/mailcap.html
"""
Mailcap 文件可用来配置支持 MIME 的应用例如邮件阅读器和 Web 浏览器如何响应具有不同 MIME 类型的文件。
("mailcap" 这个名称源自短语"mail capability"。) 例如,一个 mailcap 文件可能包含 video/mpeg; xmpeg %s 这样的行。
然后,如果用户遇到 MIME 类型为 video/mpeg 的邮件消息或 Web 文档时,%s 将被替换为一个文件名(通常是一个临时文件)并且将自动启动 xmpeg 程序来查看该文件。

mailcap 格式的文档见 RFC 1524, "A User Agent Configuration Mechanism For Multimedia Mail Format Information",但它并不是一个因特网标准。
不过,mailcap 文件在大多数 Unix 系统上都受到支持。
"""

import mailcap
d = mailcap.getcaps()
print(mailcap.findmatch(d, 'video/mpeg', filename='tmp1223'))
Esempio n. 32
0
 def _run_cases(self, cases):
     for c in cases:
         self.assertEqual(mailcap.findmatch(*c[0], **c[1]), c[2])
Esempio n. 33
0
 def mailcap_find_match(self, *args, **kwargs):
     """
     Propagates :func:`mailcap.find_match` but caches the mailcap (first
     argument)
     """
     return mailcap.findmatch(self._mailcaps, *args, **kwargs)
'''
mailcap 模块

mailcap 模块用于处理  mailcap 文件, 该文件指定了不同的文档格式的处理方法( Unix 系统下). 
'''
# 使用 mailcap 模块获得 Capability 字典
import mailcap

caps = mailcap.getcaps()
print(caps)

for k, v in caps.items():
    print(k, '=', v)

# 使用 mailcap 模块获得打开
import mailcap
caps = mailcap.getcaps()
command, info = mailcap.findmatch(caps, "image/jpeg", "view",
                                  "samples/sample.jpg")
print(command)
Esempio n. 35
0
def open_mimetype(tag, keywords, val=None):
    """Simulate double-clicking on the filename in a file manager.  Order of
    preference is:

        1) @string mime_open_cmd setting
        2) _mime_open_cmd, defined per sys.platform detection
        3) open_func(fpath), defined per sys.platform detection
        4) mailcap file for mimetype handling
    """

    global open_func

    c = keywords.get("c")
    p = keywords.get("p")
    if not c or not p:
        return

    if p.h.startswith("@mime"):
        fname = p.h[6:]

        # honor @path
        d = c.scanAllDirectives(p)
        path = d.get("path")
        fpath = g.os_path_finalize_join(path, fname)

        # stop here if the file doesn't exist
        if not g.os_path_exists(fpath):
            g.error("@mime: file does not exist, %s" % fpath)
            return True

        # user-specified command string, or sys.platform-determined string
        mime_cmd = c.config.getString("mime_open_cmd") or _mime_open_cmd
        if mime_cmd:
            if "%s" not in mime_cmd:
                mime_cmd += " %s"
            open_func = exec_string_cmd(mime_cmd)

        # no special handler function specified (unknown platform),
        # try mailcap/mimetype entries explicitly
        if open_func is None:
            (ftype, encoding) = mimetypes.guess_type(fname)
            if ftype:
                caps = mailcap.getcaps()
                (fullcmd, entry) = mailcap.findmatch(caps, ftype, filename=fpath, key="view")
                if fullcmd:
                    # create a function which merely executes the fullcmd in
                    # a shell for e.g. PATH access
                    open_func = exec_full_cmd(fullcmd)
                else:
                    g.error("@mime: no mailcap entry for %s: %s" % (ftype, fname))
                g.trace("mailcap command:", fullcmd)
            else:
                g.error("@mime: unknown file type: %s" % fname)

        # use the custom open_func to open external file viewer
        if open_func:
            open_func(fpath)
        else:
            g.error("@mime: no known way to open %s" % fname)

        # block execution of e.g. vim plugin
        return True

    # not an @mime node
    return val
Esempio n. 36
0
def extract_body(mail, types=None, field_key='copiousoutput'):
    """Returns a string view of a Message.
    If the `types` argument is set then any encoding types there will be used
    as the prefered encoding to extract. If `types` is None then
    :ref:`prefer_plaintext <prefer-plaintext>` will be consulted; if it is True
    then text/plain parts will be returned, if it is false then text/html will
    be returned if present or text/plain if there are no text/html parts.
    :param mail: the mail to use
    :type mail: :class:`email.Message`
    :param types: mime content types to use for body string
    :type types: list[str]
    :returns: The combined text of any parts to be used
    :rtype: str
    """

    # preferred = 'text/plain' if settings.get(
    #     'prefer_plaintext') else 'text/html'
    preferred = 'text/plain'
    has_preferred = False

    # see if the mail has our preferred type
    if types is None:
        has_preferred = list(
            typed_subpart_iterator(mail, *preferred.split('/')))

    body_parts = []
    for part in mail.walk():
        ctype = part.get_content_type()

        if types is not None:
            if ctype not in types:
                continue
        cd = part.get('Content-Disposition', '')
        if cd.startswith('attachment'):
            continue
        # if the mail has our preferred type, we only keep this type
        # note that if types != None, has_preferred always stays False
        if has_preferred and ctype != preferred:
            continue

        enc = part.get_content_charset() or 'ascii'
        raw_payload = part.get_payload(decode=True)
        if ctype == 'text/plain':
            raw_payload = string_decode(raw_payload, enc)
            body_parts.append(string_sanitize(raw_payload))
        else:
            # get mime handler
            # _, entry = settings.mailcap_find_match(ctype, key=field_key)
            _mailcaps = mailcap.getcaps()
            _, entry = mailcap.findmatch(_mailcaps, ctype, key=field_key)
            tempfile_name = None
            stdin = None

            if entry:
                handler_raw_commandstring = entry['view']
                # in case the mailcap defined command contains no '%s',
                # we pipe the files content to the handling command via stdin
                if '%s' in handler_raw_commandstring:
                    # open tempfile, respect mailcaps nametemplate
                    nametemplate = entry.get('nametemplate', '%s')
                    prefix, suffix = parse_mailcap_nametemplate(nametemplate)
                    with tempfile.NamedTemporaryFile(
                            delete=False, prefix=prefix, suffix=suffix) \
                            as tmpfile:
                        tmpfile.write(raw_payload)
                        tempfile_name = tmpfile.name
                else:
                    stdin = raw_payload

                body_parts.append(string_sanitize(str(raw_payload, 'utf-8')))
                continue

                # read parameter, create handler command
                # parms = tuple('='.join(p) for p in part.get_params())

                # create and call external command
                # cmd = mailcap.subst(entry['view'], ctype,
                #                     filename=tempfile_name, plist=parms)
                # logging.debug('command: %s', cmd)
                # logging.debug('parms: %s', str(parms))

                # cmdlist = split_commandstring(cmd)
                # # call handler
                # rendered_payload, _, _ = helper.call_cmd(cmdlist, stdin=stdin)

                # # remove tempfile
                # if tempfile_name:
                #     os.unlink(tempfile_name)

                # if rendered_payload:  # handler had output
                #     body_parts.append(string_sanitize(rendered_payload))
    return u'\n\n'.join(body_parts)
Esempio n. 37
0
 def update_event(self, inp=-1):
     self.set_output_val(
         0,
         mailcap.findmatch(self.input(0), self.input(1), self.input(2),
                           self.input(3), self.input(4)))
Esempio n. 38
0
import mailcap

caps = mailcap.getcaps()

command, info = mailcap.findmatch(
    caps, "image/jpeg", "view", "samples/sample.jpg"
    )

print command

## pilview samples/sample.jpg
Esempio n. 39
0
    def handle_meta(self, errcode, errmsg, headers):
        if not self.handle_meta_prelim(errcode, errmsg, headers):
            return

        # This updates the attributes in the bookmarks database.
        try:
            bkmks = self.last_context.app.bookmarks_controller
        except AttributeError:
            pass
        else:
            last_modified = None
            if headers.has_key("last-modified"):
                try: last_modified = ht_time.parse(headers["last-modified"])
                except ValueError: pass
            bkmks.record_visit(self.url, last_modified)

        content_encoding, transfer_encoding = get_encodings(headers)
        if headers.has_key('content-type'):
            content_type = headers['content-type']
            if ';' in content_type:
                content_type = string.strip(
                    content_type[:string.index(content_type, ';')])
        else:
            content_type, encoding = self.app.guess_type(self.url)
            if not content_encoding:
                content_encoding = encoding
        real_content_type = content_type or "unknown"
        real_content_encoding = content_encoding
        if (transfer_encoding
            and not transfer_decoding_wrappers.has_key(transfer_encoding)) \
            or (content_encoding
                and not content_decoding_wrappers.has_key(content_encoding)):
            # XXX provisional hack -- change content type to octet stream
            content_type = "application/octet-stream"
            transfer_encoding = None
            content_encoding = None
        if not content_type:
            content_type = "text/plain" # Last resort guess only

        istext = content_type and content_type[:5] == 'text/' \
                 and not (content_encoding or transfer_encoding)
        if self.show_source and istext:
            content_type = 'text/plain'
        parserclass = self.find_parser_extension(content_type)
        if not parserclass and istext:
            if content_type != 'text/plain':
                # still need to check for text/plain
                parserclass = self.find_parser_extension('text/plain')
            if not parserclass:
                parserclass = TextParser

        if not parserclass:
            # Don't know how to display this.
            # First consult mailcap.
            import mailcap
            global caps
            if not caps:
                caps = mailcap.getcaps()
            if caps:
                plist = [] # XXX Should be taken from Content-type header
                command, entry = mailcap.findmatch(
                    caps, content_type, 'view', "/dev/null", plist)
                if command:
                    # Retrieve to temporary file.
                    import tempfile
                    self.save_mailcap = command
                    self.save_filename = tempfile.mktemp()
                    self.save_content_type = content_type
                    self.save_plist = plist
                    self.save_file = open(self.save_filename, "wb")
                    # remember the original click location
                    self.app.global_history.remember_url(self.url)
                    self.viewer.remove_temp_tag(histify=1)
                    return
            # No relief from mailcap either.
            # Ask the user whether and where to save it.
            # Stop the transfer, and restart when we're ready.
            context = self.last_context
            # TBD: hack so that Context.rmreader() doesn't call
            # Viewer.remove_temp_tag().  We'll call that later
            # explicitly once we know whether the file has been saved
            # or not.
            context.source = None
            self.stop()
            context.message("Wait for save dialog...")
            encoding = ''
            if real_content_encoding:
                encoding = real_content_encoding + "ed "
                if encoding[:2] == "x-":
                    encoding = encoding[2:]
            encoding_label = "MIME type: %s%s" % (encoding, real_content_type)
            import FileDialog
            fd = FileDialog.SaveFileDialog(context.root)
            label = Label(fd.top, text=encoding_label)
            label.pack(before=fd.filter)
            # give it a default filename on which save within the
            # current directory
            urlasfile = string.splitfields(self.url, '/')
            fn = fd.go(default=urlasfile[-1], key="save")
            if not fn:
                # User canceled.  Stop the transfer.
                self.viewer.remove_temp_tag()
                return
            self.viewer.remove_temp_tag(histify=1)
            self.app.global_history.remember_url(self.url)
            # Prepare to save.
            # Always save in binary mode.
            try:
                self.save_file = open(fn, "wb")
            except IOError, msg:
                context.error_dialog(IOError, msg)
                return
            TransferDisplay(context, fn, self)
            return
Esempio n. 40
0
 def _run_cases(self, cases):
     for c in cases:
         self.assertEqual(mailcap.findmatch(*c[0], **c[1]), c[2])
Esempio n. 41
0
def open_mimetype(tag, keywords, val=None):
    """Simulate double-clicking on the filename in a file manager.  Order of
    preference is:

        1) @string mime_open_cmd setting
        2) _mime_open_cmd, defined per sys.platform detection
        3) open_func(fpath), defined per sys.platform detection
        4) mailcap file for mimetype handling
    """

    global open_func

    c = keywords.get('c')
    p = keywords.get('p')
    if not c or not p:
        return None

    if p.h.startswith('@mime'):
        fname = p.h[6:]

        # honor @path
        d = c.scanAllDirectives(p)
        path = d.get('path')
        fpath = g.os_path_finalize_join(path, fname)

        # stop here if the file doesn't exist
        if not g.os_path_exists(fpath):
            g.error('@mime: file does not exist, %s' % fpath)
            return True

        # user-specified command string, or sys.platform-determined string
        mime_cmd = c.config.getString('mime-open-cmd') or _mime_open_cmd
        if mime_cmd:
            if '%s' not in mime_cmd:
                mime_cmd += ' %s'
            open_func = exec_string_cmd(mime_cmd)

        #no special handler function specified (unknown platform),
        #try mailcap/mimetype entries explicitly
        if open_func is None:
            (ftype, encoding) = mimetypes.guess_type(fname)
            if ftype:
                caps = mailcap.getcaps()
                (fullcmd, entry) = mailcap.findmatch(caps,
                                                     ftype,
                                                     filename=fpath,
                                                     key='view')
                if fullcmd:
                    # create a function which merely executes the fullcmd in
                    # a shell for e.g. PATH access
                    open_func = exec_full_cmd(fullcmd)
                else:
                    g.error('@mime: no mailcap entry for %s: %s' %
                            (ftype, fname))
                g.trace('mailcap command:', fullcmd)
            else:
                g.error('@mime: unknown file type: %s' % fname)

        # use the custom open_func to open external file viewer
        if open_func:
            open_func(fpath)
        else:
            g.error('@mime: no known way to open %s' % fname)

        # block execution of e.g. vim plugin
        return True

    # not an @mime node
    return val
Esempio n. 42
0
    def keypress(self, size, key):
        if key == "tab":
            if self.viewing == self.REQ:
                self.view_response()
            else:
                self.view_request()
        elif key in ("up", "down", "page up", "page down"):
            # Why doesn't this just work??
            self.w.body.keypress(size, key)
        elif key == "a":
            self.flow.accept_intercept()
            self.master.view_connection(self.flow)
        elif key == "A":
            self.master.accept_all()
            self.master.view_connection(self.flow)
        elif key == "b":
            self.binary = not self.binary
            self.master.refresh_connection(self.flow)
        elif key == "e":
            if self.viewing == self.REQ:
                self.master.prompt_onekey(
                    "Edit request ",
                    (
                        ("header", "h"),
                        ("body", "b"),
                        ("url", "u"),
                        ("method", "m")
                    ),
                    self.edit
                )
            else:
                self.master.prompt_onekey(
                    "Edit response ",
                    (
                        ("header", "h"),
                        ("body", "b"),
                    ),
                    self.edit
                )
            key = None
        elif key == "r":
            r = self.state.replay(self.flow, self.master.masterq)
            if r:
                self.master.statusbar.message(r)
            self.master.refresh_connection(self.flow)
        elif key == "R":
            self.state.revert(self.flow)
            self.master.refresh_connection(self.flow)
        elif key == "S":
            if self.viewing == self.REQ:
                self.master.prompt("Save request: ", self.save_connection)
            else:
                self.master.prompt("Save response: ", self.save_connection)
        elif key == "v":
            if self.viewing == self.REQ:
                conn = self.flow.request
            else:
                conn = self.flow.response
            if conn.content:
                t = conn.headers.get("content-type", [None])
                t = t[0]
                if t:
                    ext = mimetypes.guess_extension(t) or ""
                else:
                    ext = ""
                fd, name = tempfile.mkstemp(ext, "mproxy")
                os.write(fd, conn.content)
                os.close(fd)
                t = conn.headers.get("content-type", [None])
                t = t[0]

                cmd = None
                shell = False

                if t:
                    c = mailcap.getcaps()
                    cmd, _ = mailcap.findmatch(c, t, filename=name)
                    if cmd:
                        shell = True
                if not cmd:
                    c = os.environ.get("PAGER") or os.environ.get("EDITOR")
                    cmd = [c, name]
                ret = subprocess.call(cmd, shell=shell)
                # Not sure why, unless we do this we get a visible cursor after
                # spawning 'less'.
                self.master.ui._curs_set(1)
                self.master.ui.clear()
                os.unlink(name)
        return key
Esempio n. 43
0
 def mailcap_find_match(self, *args, **kwargs):
     """
     Propagates :func:`mailcap.find_match` but caches the mailcap (first
     argument)
     """
     return mailcap.findmatch(self._mailcaps, *args, **kwargs)
Esempio n. 44
0
def run():
    args = parse_args()

    caps = mailcap.getcaps()

    if len(args.file) == 0:
        args.file.append('')

    err = False
    for fname in args.file:
        if args.verbose:
            print('file:', fname)

        typ = args.type
        enc = args.encoding

        if not typ:
            import mimetypes
            typ, enc = mimetypes.guess_type(fname, strict=False)

        if not typ:
            print('error: no MIME type found:', fname, file=sys.stderr)
            err = True
            continue

        if args.verbose:
            print('type:', typ)
            print('encoding:', enc)

        if enc:
            tmp = decode(fname, enc)
            if not tmp:
                print('error: encoding not supported:', enc, file=sys.stderr)
                err = True
                continue
            fname = tmp.name

        cmd, ent = mailcap.findmatch(
            caps,
            typ,
            key=args.action,
            filename=quote(fname),
            plist=args.parameter)

        if args.verbose:
            print('command:', cmd)

        if args.verbose:
            print('entry:', ent)

        if not cmd:
            print('error: no', args.action, 'command found:', fname, file=sys.stderr)
            err = True
            continue

        ret = subprocess.call(cmd, shell=True, stdin=sys.stdin)

        if ret != 0:
            print('error: command returned non-zero exit code:', ret, file=sys.stderr)
            err = True
            continue

    if err:
        sys.exit(1)