<commit_before>###
# Copyright (c) 2002-2004, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

import re
import cgi
import time
import socket
import urllib
import xml.sax

import SOAP
import google

import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
from supybot.commands import *
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
import supybot.structures as structures

def search(log, queries, **kwargs):
    # We have to keep stats here, rather than in formatData or elsewhere,
    # because not all searching functions use formatData -- fight, lucky, etc.
    assert not isinstance(queries, basestring), 'Old code: queries is a list.'
    try:
        for (i, query) in enumerate(queries):
            if len(query.split(None, 1)) > 1:
                queries[i] = repr(query)
        proxy = conf.supybot.protocols.http.proxy()
        if proxy:
            kwargs['http_proxy'] = proxy
        query = ' '.join(queries).decode('utf-8')
        data = google.doGoogleSearch(query, **kwargs)
        searches = conf.supybot.plugins.Google.state.searches() + 1
        conf.supybot.plugins.Google.state.searches.setValue(searches)
        time = conf.supybot.plugins.Google.state.time() + data.meta.searchTime
        conf.supybot.plugins.Google.state.time.setValue(time)
        last24hours.enqueue(None)
        return data
    except socket.error, e:
        if e.args[0] == 110:
            raise callbacks.Error, 'Connection timed out to Google.com.'
        else:
            raise callbacks.Error, 'Error connecting to Google.com.'
    except SOAP.HTTPError, e:
        log.info('HTTP Error accessing Google: %s', e)
        raise callbacks.Error, 'Error connecting to Google.com.'
    except SOAP.faultType, e:
        if 'Invalid authorization key' in e.faultstring:
            raise callbacks.Error, 'Invalid Google license key.'
        elif 'Problem looking up user record' in e.faultstring:
            raise callbacks.Error, \
                  'Google seems to be having trouble looking up the user for '\
                  'your license key.  This probably isn\'t a problem on your '\
                  'side; it\'s probably a bug on Google\'s side.  It seems '\
                  'to happen intermittently.'
        else:
            log.exception('Unexpected SOAPpy error:')
            raise callbacks.Error, \
                  'Unexpected error from Google; please report this to the ' \
                  'Supybot developers.'
    except xml.sax.SAXException, e:
        log.exception('Uncaught SAX error:')
        raise callbacks.Error, 'Google returned an unparsable response.  ' \
                               'The full traceback has been logged.'
    except SOAPpy.Error, e:
        log.exception('Uncaught SOAP exception in Google.search:')
        raise callbacks.Error, 'Error connecting to Google.com.'

last24hours = structures.TimeoutQueue(86400)
totalTime = conf.supybot.plugins.Google.state.time()
searches = conf.supybot.plugins.Google.state.searches()

class Google(callbacks.PluginRegexp):
    threaded = True
    callBefore = ['URL']
    regexps = ['googleSnarfer', 'googleGroups']
    def __init__(self, irc):
        self.__parent = super(Google, self)
        self.__parent.__init__(irc)
        google.setLicense(self.registryValue('licenseKey'))

    def callCommand(self, command, irc, msg, *args, **kwargs):
        try:
            self.__parent.callCommand(command, irc, msg, *args, **kwargs)
        except xml.sax.SAXReaderNotAvailable, e:
            irc.error('No XML parser available.')

    _colorGoogles = {}
    def _getColorGoogle(self, m):
        s = m.group(1)
        ret = self._colorGoogles.get(s)
        if not ret:
            L = list(s)
            L[0] = ircutils.mircColor(L[0], 'blue')[:-1]
            L[1] = ircutils.mircColor(L[1], 'red')[:-1]
            L[2] = ircutils.mircColor(L[2], 'yellow')[:-1]
            L[3] = ircutils.mircColor(L[3], 'blue')[:-1]<commit_msg>Moved the titleSnarfer to Web, so we need to insist that we're called before that instead.<commit_after>###
# Copyright (c) 2002-2004, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

import re
import cgi
import time
import socket
import urllib
import xml.sax

import SOAP
import google

import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
from supybot.commands import *
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
import supybot.structures as structures

def search(log, queries, **kwargs):
    # We have to keep stats here, rather than in formatData or elsewhere,
    # because not all searching functions use formatData -- fight, lucky, etc.
    assert not isinstance(queries, basestring), 'Old code: queries is a list.'
    try:
        for (i, query) in enumerate(queries):
            if len(query.split(None, 1)) > 1:
                queries[i] = repr(query)
        proxy = conf.supybot.protocols.http.proxy()
        if proxy:
            kwargs['http_proxy'] = proxy
        query = ' '.join(queries).decode('utf-8')
        data = google.doGoogleSearch(query, **kwargs)
        searches = conf.supybot.plugins.Google.state.searches() + 1
        conf.supybot.plugins.Google.state.searches.setValue(searches)
        time = conf.supybot.plugins.Google.state.time() + data.meta.searchTime
        conf.supybot.plugins.Google.state.time.setValue(time)
        last24hours.enqueue(None)
        return data
    except socket.error, e:
        if e.args[0] == 110:
            raise callbacks.Error, 'Connection timed out to Google.com.'
        else:
            raise callbacks.Error, 'Error connecting to Google.com.'
    except SOAP.HTTPError, e:
        log.info('HTTP Error accessing Google: %s', e)
        raise callbacks.Error, 'Error connecting to Google.com.'
    except SOAP.faultType, e:
        if 'Invalid authorization key' in e.faultstring:
            raise callbacks.Error, 'Invalid Google license key.'
        elif 'Problem looking up user record' in e.faultstring:
            raise callbacks.Error, \
                  'Google seems to be having trouble looking up the user for '\
                  'your license key.  This probably isn\'t a problem on your '\
                  'side; it\'s probably a bug on Google\'s side.  It seems '\
                  'to happen intermittently.'
        else:
            log.exception('Unexpected SOAPpy error:')
            raise callbacks.Error, \
                  'Unexpected error from Google; please report this to the ' \
                  'Supybot developers.'
    except xml.sax.SAXException, e:
        log.exception('Uncaught SAX error:')
        raise callbacks.Error, 'Google returned an unparsable response.  ' \
                               'The full traceback has been logged.'
    except SOAPpy.Error, e:
        log.exception('Uncaught SOAP exception in Google.search:')
        raise callbacks.Error, 'Error connecting to Google.com.'

last24hours = structures.TimeoutQueue(86400)
totalTime = conf.supybot.plugins.Google.state.time()
searches = conf.supybot.plugins.Google.state.searches()

class Google(callbacks.PluginRegexp):
    threaded = True
    callBefore = ['Web']
    regexps = ['googleSnarfer', 'googleGroups']
    def __init__(self, irc):
        self.__parent = super(Google, self)
        self.__parent.__init__(irc)
        google.setLicense(self.registryValue('licenseKey'))

    def callCommand(self, command, irc, msg, *args, **kwargs):
        try:
            self.__parent.callCommand(command, irc, msg, *args, **kwargs)
        except xml.sax.SAXReaderNotAvailable, e:
            irc.error('No XML parser available.')

    _colorGoogles = {}
    def _getColorGoogle(self, m):
        s = m.group(1)
        ret = self._colorGoogles.get(s)
        if not ret:
            L = list(s)
            L[0] = ircutils.mircColor(L[0], 'blue')[:-1]
            L[1] = ircutils.mircColor(L[1], 'red')[:-1]
            L[2] = ircutils.mircColor(L[2], 'yellow')[:-1]
            L[3] = ircutils.mircColor(L[3], 'blue')[:-1]
{'fraction_non_alphanumeric': 0.09159280150416331, 'fraction_numerical': 0.0068045483033396005, 'mean_word_length': 2.8637149775164303, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 6}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3361389', 'n_tokens_mistral': 3256, 'n_tokens_neox': 3082, 'n_words': 1122}