⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 proxyui.py

📁 用python实现的邮件过滤器
💻 PY
📖 第 1 页 / 共 3 页
字号:
"""POP3Proxy and SMTPProxy Web InterfaceClasses:    ProxyUserInterface - Interface class for pop3proxy and smtpproxyAbstract:This module implements a browser based Spambayes user interface for thePOP3, IMAP4 SMTP proxies.  Users may use it to interface with theproxies.The following functions are currently included:[From the base class UserInterface]  onClassify - classify a given message  onWordquery - query a word from the database  onTrain - train a message or mbox  onSave - save the database and possibly shutdown[Here]  onHome - a home page with various options  onUpload - upload a message for later training (used by proxytee.py)  onReview - show messages in corpii  onView - view a message from one of the corpii  onShowclues - show clues for a messageTo do:Web training interface: o Review already-trained messages, and purge them. o Add a Today button on the Review page.User interface improvements: o Can it cleanly dynamically update its status display while having a POP3   conversation?  Hammering reload sucks. o Suggestions?"""# This module is part of the spambayes project, which is Copyright 2002-3# The Python Software Foundation and is covered by the Python Software# Foundation license.# This module was once part of pop3proxy.py; if you are looking through# the history of the file, you may need to go back there.__author__ = "Richie Hindle <richie@entrian.com>"__credits__ = "Tim Peters, Neale Pickett, Tim Stone, all the Spambayes folk."try:    True, Falseexcept NameError:    # Maintain compatibility with Python 2.2    True, False = 1, 0import reimport cgiimport timeimport typesimport bisecttry:    # We have three possibilities for Set:    #  (a) With Python 2.2 and earlier, we use our compatsets class    #  (b) With Python 2.3, we use the sets.Set class    #  (c) With Python 2.4 and later, we use the builtin set class    Set = setexcept NameError:    try:        from sets import Set    except ImportError:        from spambayes.compatsets import Setimport tokenizerimport UserInterfacefrom spambayes.Options import options, _from email.Iterators import typed_subpart_iteratorglobal state# These are the options that will be offered on the configuration page.# If the option is None, then the entry is a header and the following# options will appear in a new box on the configuration page.# These are also used to generate http request parameters and template# fields/variables.parm_ini_map = (    ('POP3 Proxy Options',  None),    ('pop3proxy',           'remote_servers'),    ('pop3proxy',           'listen_ports'),#    ('IMAP4 Proxy Options',  None),#    ('imap4proxy',          'remote_servers'),#    ('imap4proxy',          'listen_ports'),    ('SMTP Proxy Options',  None),    ('smtpproxy',           'remote_servers'),    ('smtpproxy',           'listen_ports'),    ('smtpproxy',           'ham_address'),    ('smtpproxy',           'spam_address'),    ('smtpproxy',           'use_cached_message'),    ('Header Options',      None),    ('Headers',             'notate_to'),    ('Headers',             'notate_subject'),    ('Storage Options',     None),    ('Storage',             'persistent_storage_file'),    ('Storage',             'messageinfo_storage_file'),    ('Storage',             'cache_messages'),    ('Storage',             'no_cache_bulk_ham'),    ('Storage',             'no_cache_large_messages'),    ('Statistics Options',  None),    ('Categorization',      'ham_cutoff'),    ('Categorization',      'spam_cutoff'),)# Like the above, but hese are the options that will be offered on the# advanced configuration page.adv_map = (    (_('Statistics Options'), None),    ('Classifier',            'max_discriminators'),    ('Classifier',            'minimum_prob_strength'),    ('Classifier',            'unknown_word_prob'),    ('Classifier',            'unknown_word_strength'),    ('Classifier',            'use_bigrams'),    (_('Header Options'),     None),    ('Headers',               'include_score'),    ('Headers',               'header_score_digits'),    ('Headers',               'header_score_logarithm'),    ('Headers',               'include_thermostat'),    ('Headers',               'include_evidence'),    ('Headers',               'clue_mailheader_cutoff'),    (_('Storage Options'),    None),    ('Storage',               'persistent_use_database'),    ('Storage',               'cache_expiry_days'),    ('Storage',               'cache_use_gzip'),    ('Storage',               'ham_cache'),    ('Storage',               'spam_cache'),    ('Storage',               'unknown_cache'),    (_('Tokenising Options'), None),    ('Tokenizer',             'mine_received_headers'),    ('Tokenizer',             'replace_nonascii_chars'),    ('Tokenizer',             'summarize_email_prefixes'),    ('Tokenizer',             'summarize_email_suffixes'),    (_('Training Options'),   None),    ('Hammie',                'train_on_filter'),    (_('Interface Options'),  None),    ('html_ui',               'display_headers'),    ('html_ui',               'display_received_time'),    ('html_ui',               'display_score'),    ('html_ui',               'display_adv_find'),    ('html_ui',               'default_ham_action'),    ('html_ui',               'default_spam_action'),    ('html_ui',               'default_unsure_action'),    ('html_ui',               'ham_discard_level'),    ('html_ui',               'spam_discard_level'),    ('html_ui',               'allow_remote_connections'),    ('html_ui',               'http_authentication'),    ('html_ui',               'http_user_name'),    ('html_ui',               'http_password'),    ('pop3proxy',             'allow_remote_connections'),    ('smtpproxy',             'allow_remote_connections'),    ('globals',               'language'),    (_('POP3 Proxy Options'), None),    ('pop3proxy',             'retrieval_timeout'),)class ProxyUserInterface(UserInterface.UserInterface):    """Serves the HTML user interface for the proxies."""    def __init__(self, proxy_state, state_recreator):        global state        UserInterface.UserInterface.__init__(self, proxy_state.bayes,                                             parm_ini_map, adv_map,                                             proxy_state.lang_manager,                                             proxy_state.stats)        state = proxy_state        self.state_recreator = state_recreator # ugly        self.app_for_version = "SpamBayes Proxy"        self.previous_sort = None        if not proxy_state.can_stop:            self.html._readonly = False            self.html.shutdownTableCell = "&nbsp;"            self.html._readonly = True    def onHome(self):        """Serve up the homepage."""        state.buildStatusStrings()        stateDict = state.__dict__.copy()        stateDict.update(state.bayes.__dict__)        statusTable = self.html.statusTable.clone()        if not state.servers:            statusTable.proxyDetails = _("No POP3 proxies running.<br/>")        findBox = self._buildBox(_('Word query'), 'query.gif',                                 self.html.wordQuery)        if not options["html_ui", "display_adv_find"]:            del findBox.advanced        content = (self._buildBox(_('Status and Configuration'),                                  'status.gif', statusTable % stateDict)+                   self._buildBox(_('Train on proxied messages'),                                  'train.gif', self.html.reviewText) +                   self._buildTrainBox() +                   self._buildClassifyBox() +                   findBox +                   self._buildBox(_('Find message'), 'query.gif',                                  self.html.findMessage)                   )        self._writePreamble(_("Home"))        self.write(content)        self._writePostamble(help_topic="home_proxy")    def onUpload(self, file):        """Save a message for later training - used by Skip's proxytee.py."""        # Convert platform-specific line endings into unix-style.        file = file.replace('\r\n', '\n').replace('\r', '\n')        # Get a message list from the upload and write it into the cache.        messages = self._convertUploadToMessageList(file)        for m in messages:            messageName = state.getNewMessageName()            message = state.unknownCorpus.makeMessage(messageName, m)            state.unknownCorpus.addMessage(message)        # Return a link Home.        self.write(_("<p>OK. Return <a href='home'>Home</a>.</p>"))    def _keyToTimestamp(self, key):        """Given a message key (as seen in a Corpus), returns the timestamp        for that message.  This is the time that the message was received,        not the Date header."""        return long(key[:10])    def _getTimeRange(self, timestamp):        """Given a unix timestamp, returns a 3-tuple: the start timestamp        of the given day, the end timestamp of the given day, and the        formatted date of the given day."""        this = time.localtime(timestamp)        start = (this[0], this[1], this[2], 0, 0, 0, this[6], this[7], this[8])        end = time.localtime(time.mktime(start) + 36*60*60)        end = (end[0], end[1], end[2], 0, 0, 0, end[6], end[7], end[8])        date = time.strftime("%A, %B %d, %Y", start)        return time.mktime(start), time.mktime(end), date    def _buildReviewKeys(self, timestamp):        """Builds an ordered list of untrained message keys, ready for output        in the Review list.  Returns a 5-tuple: the keys, the formatted date        for the list (eg. "Friday, November 15, 2002"), the start of the prior        page or zero if there isn't one, likewise the start of the given page,        and likewise the start of the next page."""        # Fetch all the message keys        allKeys = state.unknownCorpus.keys()        # We have to sort here to split into days.        # Later on, we also sort the messages that will be on the page        # (by whatever column we wish).        allKeys.sort()        # The default start timestamp is derived from the most recent message,        # or the system time if there are no messages (not that it gets used).        if not timestamp:            if allKeys:                timestamp = self._keyToTimestamp(allKeys[-1])            else:                timestamp = time.time()        start, end, date = self._getTimeRange(timestamp)        # Find the subset of the keys within this range.        startKeyIndex = bisect.bisect(allKeys, "%d" % long(start))        endKeyIndex = bisect.bisect(allKeys, "%d" % long(end))        keys = allKeys[startKeyIndex:endKeyIndex]        keys.reverse()        # What timestamps to use for the prior and next days?  If there any        # messages before/after this day's range, use the timestamps of those        # messages - this will skip empty days.        prior = end = 0        if startKeyIndex != 0:            prior = self._keyToTimestamp(allKeys[startKeyIndex-1])        if endKeyIndex != len(allKeys):            end = self._keyToTimestamp(allKeys[endKeyIndex])        # Return the keys and their date.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -