Esempio n. 1
0
    def doGet(self, handler, path):
        splitted_path = path.split('/')
        if len(splitted_path) == 2:
            names = filter(lambda x: conf.supybot.plugins.get(x).public(),
                    map(lambda cb:cb.name(), self._irc.callbacks))
            plugins = ''.join(map(lambda x:'<li><a href="%s/">%s</a></li>'%(x,x),
                sorted(names)))
            response = 200
            output = httpserver.get_template('webdoc/index.html') % {
                    'plugins': plugins,
                    }
        elif len(splitted_path) == 3:
            name = splitted_path[1]
            cbs = dict(map(lambda cb:(cb.name(), cb),
                self._irc.callbacks))
            if name not in cbs or \
                    not conf.supybot.plugins.get(name).public():
                response = 404
                output = httpserver.get_template('generic/error.html') % \
                    {'title': 'PluginsDoc',
                     'error': 'Requested plugin is not found. Sorry.'}
            else:
                response = 200
                callback = cbs[name]
                commands = callback.listCommands()
                description = callback.__doc__
                if not description or description.startswith('Add the help for'):
                    description = ''
                if commands:
                    commands.sort()
                def formatter(command):
                    command = list(map(callbacks.canonicalName,
                        command.split(' ')))
                    doc = callback.getCommandMethod(command).__doc__
                    if not doc:
                        return '<tr><td>%s</td><td> </td></tr>' % \
                                ' '.join(command)
                    doclines = doc.splitlines()
                    s = cgi.escape('%s %s' % (name, doclines.pop(0)))
                    if doclines:
                        help_ = cgi.escape('\n'.join(doclines))
                        s = '<strong>%s</strong><br />%s' % \
                                (ircutils.bold(s), help_)
                    return '<tr><td>%s</td><td>%s</td></tr>' % \
                            (' '.join(command), s)

                table = ''.join(map(formatter, commands))
                output = httpserver.get_template('webdoc/plugin.html') % {
                        'plugin': name,
                        'table': table,
                        'description': description
                        }
                
        self.send_response(response)
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.end_headers()
        if sys.version_info[0] >= 3:
            output = output.encode()
        self.wfile.write(output)
Esempio n. 2
0
 def doGetOrHead(self, handler, path, write_content):
     parts = path.split('/')[1:]
     if path == '/':
         self.send_response(200)
         self.send_header('Content-type', 'text/html; charset=utf-8')
         self.end_headers()
         self.write(httpserver.get_template('factoids/index.html'))
     elif len(parts) == 2:
         channel = utils.web.urlunquote(parts[0])
         if not irc.isChannel(channel):
             self.send_response(404)
             self.send_header('Content-type', 'text/html; charset=utf-8')
             self.end_headers()
             if write_content:
                 self.write(httpserver.get_template('generic/error.html')%
                     {'title': 'Factoids - not a channel',
                      'error': 'This is not a channel'})
             return
         if not self._plugin.registryValue('web.channel',
                                           channel, irc.network):
             self.send_response(403)
             self.send_header('Content-type', 'text/html; charset=utf-8')
             self.end_headers()
             if write_content:
                 self.write(httpserver.get_template('generic/error.html')%
                     {'title': 'Factoids - unavailable',
                      'error': 'This channel does not exist or its factoids '
                               'are not available here.'})
             return
         db = self._plugin.getDb(channel)
         cursor = db.cursor()
         cursor.execute("""SELECT keys.key, factoids.id, factoids.fact
                           FROM factoids, keys, relations
                           WHERE relations.key_id=keys.id AND relations.fact_id=factoids.id
                           """)
         factoids = {}
         for (key, id_, fact) in cursor.fetchall():
             if key not in factoids:
                 factoids[key] = {}
             factoids[key][id_] = fact
         content = ''
         keys = sorted(factoids.keys())
         for key in keys:
             facts = factoids[key]
             content += '<tr>'
             content += ('<td rowspan="%i" class="key">'
                             '<a name="%s" href="#%s">%s</a>'
                        '</td>') % (len(facts), key, key, key)
             for id_, fact in facts.items():
                 content += '<td class="id">%i</td>' % id_
                 content += '<td class="fact">%s</td>' % fact
                 content += '</tr><tr>'
             content = content[:-len('<tr>')]
         self.send_response(200)
         self.send_header('Content-type', 'text/html; charset=utf-8')
         self.end_headers()
         if write_content:
             self.write(httpserver.get_template('factoids/channel.html')%
                     {'channel': channel, 'rows': content})
Esempio n. 3
0
 def doGetOrHead(self, handler, path, write_content):
     parts = path.split('/')[1:]
     if path == '/':
         self.send_response(200)
         self.send_header('Content-type', 'text/html; charset=utf-8')
         self.end_headers()
         self.write(httpserver.get_template('factoids/index.html'))
     elif len(parts) == 2:
         channel = utils.web.urlunquote(parts[0])
         if not ircutils.isChannel(channel):
             self.send_response(404)
             self.send_header('Content-type', 'text/html; charset=utf-8')
             self.end_headers()
             if write_content:
                 self.write(httpserver.get_template('generic/error.html')%
                     {'title': 'Factoids - not a channel',
                      'error': 'This is not a channel'})
             return
         if not self._plugin.registryValue('web.channel', channel):
             self.send_response(403)
             self.send_header('Content-type', 'text/html; charset=utf-8')
             self.end_headers()
             if write_content:
                 self.write(httpserver.get_template('generic/error.html')%
                     {'title': 'Factoids - unavailable',
                      'error': 'This channel does not exist or its factoids '
                               'are not available here.'})
             return
         db = self._plugin.getDb(channel)
         cursor = db.cursor()
         cursor.execute("""SELECT keys.key, factoids.id, factoids.fact
                           FROM factoids, keys, relations
                           WHERE relations.key_id=keys.id AND relations.fact_id=factoids.id
                           """)
         factoids = {}
         for (key, id_, fact) in cursor.fetchall():
             if key not in factoids:
                 factoids[key] = {}
             factoids[key][id_] = fact
         content = ''
         keys = sorted(factoids.keys())
         for key in keys:
             facts = factoids[key]
             content += '<tr>'
             content += ('<td rowspan="%i" class="key">'
                             '<a name="%s" href="#%s">%s</a>'
                        '</td>') % (len(facts), key, key, key)
             for id_, fact in facts.items():
                 content += '<td class="id">%i</td>' % id_
                 content += '<td class="fact">%s</td>' % fact
                 content += '</tr><tr>'
             content = content[:-len('<tr>')]
         self.send_response(200)
         self.send_header('Content-type', 'text/html; charset=utf-8')
         self.end_headers()
         if write_content:
             self.write(httpserver.get_template('factoids/channel.html')%
                     {'channel': channel, 'rows': content})
Esempio n. 4
0
    def doGet(self, handler, path):
        splitted_path = path.split("/")
        if len(splitted_path) == 2:
            names = filter(
                lambda x: conf.supybot.plugins.get(x).public(), map(lambda cb: cb.name(), self._irc.callbacks)
            )
            plugins = "".join(map(lambda x: '<li><a href="%s/">%s</a></li>' % (x, x), sorted(names)))
            response = 200
            output = httpserver.get_template("webdoc/index.html") % {"plugins": plugins}
        elif len(splitted_path) == 3:
            name = splitted_path[1]
            cbs = dict(map(lambda cb: (cb.name(), cb), self._irc.callbacks))
            if name not in cbs or not conf.supybot.plugins.get(name).public():
                response = 404
                output = httpserver.get_template("generic/error.html") % {
                    "title": "PluginsDoc",
                    "error": "Requested plugin is not found. Sorry.",
                }
            else:
                response = 200
                callback = cbs[name]
                commands = callback.listCommands()
                description = callback.__doc__
                if not description or description.startswith("Add the help for"):
                    description = ""
                if commands:
                    commands.sort()

                def formatter(command):
                    command = list(map(callbacks.canonicalName, command.split(" ")))
                    doc = callback.getCommandMethod(command).__doc__
                    if not doc:
                        return "<tr><td>%s</td><td> </td></tr>" % " ".join(command)
                    doclines = doc.splitlines()
                    if self._plugin.registryValue("withFullName"):
                        s = "%s %s %s" % (name, " ".join(command), doclines.pop(0))
                    else:
                        s = doclines.pop(0)
                    s = cgi.escape(s)
                    if doclines:
                        help_ = cgi.escape("\n".join(doclines))
                        s = "<strong>%s</strong><br />%s" % (ircutils.bold(s), help_)
                    return "<tr><td>%s</td><td>%s</td></tr>" % (" ".join(command), s)

                table = "".join(map(formatter, commands))
                output = httpserver.get_template("webdoc/plugin.html") % {
                    "plugin": name,
                    "table": table,
                    "description": description,
                }

        self.send_response(response)
        self.send_header("Content-type", "text/html; charset=utf-8")
        self.end_headers()
        if sys.version_info[0] >= 3:
            output = output.encode()
        self.wfile.write(output)
Esempio n. 5
0
 def get_global(self, urlLevel, channel, page, orderby=None):
     template = httpserver.get_template('webstats/global.html')
     channel = '#' + channel
     items = self.db.getChanGlobalData(channel)
     bound = self.db.getChanRecordingTimeBoundaries(channel)
     hourly_items = self.db.getChanXXlyData(channel, 'hour')
     replacement = {
         'channel':
         channel,
         'escaped_channel':
         channel[1:].replace('#', ' '),
         'quick_stats':
         utils.str.format('%n, %n, %n, %n, %n, %n, %n, and %n.',
                          (items[0], _('line')), (items[1], _('word')),
                          (items[2], _('char')), (items[3], _('join')),
                          (items[4], _('part')), (items[5], _('quit')),
                          (items[6], _('nick change')),
                          (items[8], _('kick'))),
         'table':
         getTable(_('Hour'), hourly_items, channel, urlLevel, page,
                  orderby)[0],
         'date':
         time.strftime('%Y-%m-%d %H:%M:%S%z'),
     }
     return template % replacement
Esempio n. 6
0
 def _invalidChannel(self):
     self.send_response(404)
     self.send_header('Content-type', 'text/html; charset=utf-8')
     self.end_headers()
     self.wfile.write(httpserver.get_template('generic/error.html')%
         {'title': 'ChannelStatus - not a channel',
          'error': 'This is not a channel'})
Esempio n. 7
0
 def doGet(self, handler, path):
     parts = path.split('/')[1:]
     if path == '/':
         self.send_response(200)
         self.send_header('Content-type', 'text/html; charset=utf-8')
         self.end_headers()
         template = httpserver.get_template('channelstatus/index.html')
         channels = set()
         for irc in world.ircs:
             channels |= set(['<li><a href="./%s/">%s@%s</a></li>' %
                 (quote('%s@%s' % (x, irc.network)), x, irc.network)
                 for x in irc.state.channels.keys()
                 if self._plugin.registryValue('listed', x)])
         channels = list(channels)
         channels.sort()
         self._write(template % {'channels': ('\n'.join(channels))})
     elif len(parts) == 2:
         (channel, network) = unquote(parts[0]).split('@')
         if not ircutils.isChannel(channel):
             self._invalidChannel()
             return
         for irc in world.ircs:
             if irc.network == network:
                 break
         if irc.network != network or channel not in irc.state.channels:
             self._invalidChannel()
             return
         self.send_response(200)
         self.send_header('Content-type', 'text/html; charset=utf-8')
         self.end_headers()
         state = irc.state.channels[channel]
         replacements = {'channel': channel, 'network': network,
                 'nicks': _('Private'), 'topic': _('Private')}
         if self._plugin.registryValue('topic', channel):
             replacements['topic'] = state.topic
         if self._plugin.registryValue('nicks', channel):
             replacements['nicks'] = '<ul>' + \
                     '\n'.join(sorted(['<li>%s</li>' % x
                         for x in state.users])) + \
                     '</ul>'
         template = httpserver.get_template('channelstatus/channel.html')
         self._write(template % replacements)
Esempio n. 8
0
 def get_index(self):
     template = httpserver.get_template('webstats/index.html')
     channels = self.db.getChannels()
     if len(channels) == 0:
         title = _('Stats available for no channels')
     elif len(channels) == 1:
         title = _('Stats available for a channel:')
     else:
         title = _('Stats available for channels:')
     channels_html = ''
     for channel in channels:
         channels_html += ('<li><a href="/webstats/global/%s/" title="%s">'
                      '%s</a></li>') % \
                   (channel[1:].replace('#', ' '), # Strip the leading #
                   _('View the stats for the %s channel') % channel,
                   channel)
     return template % {'title': title, 'channels': channels_html}
Esempio n. 9
0
 def get_index(self):
     template = httpserver.get_template("webstats/index.html")
     channels = self.db.getChannels()
     if len(channels) == 0:
         title = _("Stats available for no channels")
     elif len(channels) == 1:
         title = _("Stats available for a channel:")
     else:
         title = _("Stats available for channels:")
     channels_html = ""
     for channel in channels:
         channels_html += ('<li><a href="/webstats/global/%s/" title="%s">' "%s</a></li>") % (
             channel[1:].replace("#", " "),  # Strip the leading #
             _("View the stats for the %s channel") % channel,
             channel,
         )
     return template % {"title": title, "channels": channels_html, "date": time.strftime("%Y-%m-%d %H:%M:%S%z")}
Esempio n. 10
0
 def get_global(self, urlLevel, channel, page, orderby=None):
     template = httpserver.get_template('webstats/global.html')
     channel = '#' + channel
     items = self.db.getChanGlobalData(channel)
     bound = self.db.getChanRecordingTimeBoundaries(channel)
     hourly_items = self.db.getChanXXlyData(channel, 'hour')
     replacement = {'channel': channel,
             'escaped_channel': channel[1:].replace('#', ' '),
             'quick_stats': utils.str.format(
                 '%n, %n, %n, %n, %n, %n, %n, and %n.',
                 (items[0], _('line')), (items[1], _('word')),
                 (items[2], _('char')), (items[3], _('join')),
                 (items[4], _('part')), (items[5], _('quit')),
                 (items[6], _('nick change')),
                 (items[8], _('kick'))),
             'table': getTable(_('Hour'), hourly_items, channel, urlLevel,
                 page, orderby)[0]
             }
     return template % replacement
Esempio n. 11
0
    def get_nicks(self, urlLevel, channel, page, orderby=None):
        channel = '#' + channel
        template = httpserver.get_template('webstats/nicks.html')
        items = self.db.getChanGlobalData(channel)
        bound = self.db.getChanRecordingTimeBoundaries(channel)
        nickly_items = self.db.getChanNickGlobalData(channel, 20)
        table, nbItems = getTable(_('Nick'), nickly_items, channel, urlLevel,
                                  page, orderby)

        page = int(page)
        pagination = ''
        if nbItems >= 25:
            if page == 0:
                pagination += '1 '
            else:
                pagination += '<a href="0.htm">1</a> '
            if page > 100:
                pagination += '... '
            for i in range(int(max(1, page / 25 - 3)),
                           int(min(nbItems / 25 - 1, page / 25 + 3))):
                if page != i * 25 - 1:
                    pagination += '<a href="%i.htm">%i</a> ' % (i * 25 - 1,
                                                                i * 25)
                else:
                    pagination += '%i ' % (i * 25)
            if nbItems - page > 100:
                pagination += '... '
            if page == nbItems - 24 - 1:
                pagination += '%i' % (nbItems - 24)
            else:
                pagination += '<a href="%i.htm">%i</a>' % (nbItems - 24 - 1,
                                                           nbItems - 24)
        replacement = {
            'channel': channel,
            'escaped_channel': channel[1:].replace('#', ' '),
            'table': table,
            'pagination': pagination,
            'date': time.strftime('%Y-%m-%d %H:%M:%S%z'),
        }
        return template % replacement
Esempio n. 12
0
    def get_nicks(self, urlLevel, channel, page, orderby=None):
        channel = '#' + channel
        template = httpserver.get_template('webstats/nicks.html')
        items = self.db.getChanGlobalData(channel)
        bound = self.db.getChanRecordingTimeBoundaries(channel)
        nickly_items = self.db.getChanNickGlobalData(channel, 20)
        table, nbItems = getTable(_('Nick'), nickly_items, channel,
                urlLevel, page, orderby)

        page = int(page)
        pagination = ''
        if nbItems >= 25:
            if page == 0:
                pagination += '1 '
            else:
                pagination += '<a href="0.htm">1</a> '
            if page > 100:
                pagination += '... '
            for i in range(int(max(1,page/25-3)),int(min(nbItems/25-1,page/25+3))):
                if page != i*25-1:
                    pagination += '<a href="%i.htm">%i</a> ' % (i*25-1, i*25)
                else:
                    pagination += '%i ' % (i*25)
            if nbItems - page > 100:
                pagination += '... '
            if page == nbItems-24-1:
                pagination += '%i' % (nbItems-24)
            else:
                pagination += '<a href="%i.htm">%i</a>' % (nbItems-24-1, nbItems-24)
        replacement = {
                'channel': channel,
                'escaped_channel': channel[1:].replace('#', ' '),
                'table': table,
                'pagination': pagination,
                'date': time.strftime('%Y-%m-%d %H:%M:%S%z'),
                }
        return template % replacement
Esempio n. 13
0
    def get_nicks(self, urlLevel, channel, page, orderby=None):
        channel = "#" + channel
        template = httpserver.get_template("webstats/nicks.html")
        items = self.db.getChanGlobalData(channel)
        bound = self.db.getChanRecordingTimeBoundaries(channel)
        nickly_items = self.db.getChanNickGlobalData(channel, 20)
        table, nbItems = getTable(_("Nick"), nickly_items, channel, urlLevel, page, orderby)

        page = int(page)
        pagination = ""
        if nbItems >= 25:
            if page == 0:
                pagination += "1 "
            else:
                pagination += '<a href="0.htm">1</a> '
            if page > 100:
                pagination += "... "
            for i in range(int(max(1, page / 25 - 3)), int(min(nbItems / 25 - 1, page / 25 + 3))):
                if page != i * 25 - 1:
                    pagination += '<a href="%i.htm">%i</a> ' % (i * 25 - 1, i * 25)
                else:
                    pagination += "%i " % (i * 25)
            if nbItems - page > 100:
                pagination += "... "
            if page == nbItems - 24 - 1:
                pagination += "%i" % (nbItems - 24)
            else:
                pagination += '<a href="%i.htm">%i</a>' % (nbItems - 24 - 1, nbItems - 24)
        replacement = {
            "channel": channel,
            "escaped_channel": channel[1:].replace("#", " "),
            "table": table,
            "pagination": pagination,
            "date": time.strftime("%Y-%m-%d %H:%M:%S%z"),
        }
        return template % replacement
Esempio n. 14
0
 def get_global(self, urlLevel, channel, page, orderby=None):
     template = httpserver.get_template("webstats/global.html")
     channel = "#" + channel
     items = self.db.getChanGlobalData(channel)
     bound = self.db.getChanRecordingTimeBoundaries(channel)
     hourly_items = self.db.getChanXXlyData(channel, "hour")
     replacement = {
         "channel": channel,
         "escaped_channel": channel[1:].replace("#", " "),
         "quick_stats": utils.str.format(
             "%n, %n, %n, %n, %n, %n, %n, and %n.",
             (items[0], _("line")),
             (items[1], _("word")),
             (items[2], _("char")),
             (items[3], _("join")),
             (items[4], _("part")),
             (items[5], _("quit")),
             (items[6], _("nick change")),
             (items[8], _("kick")),
         ),
         "table": getTable(_("Hour"), hourly_items, channel, urlLevel, page, orderby)[0],
         "date": time.strftime("%Y-%m-%d %H:%M:%S%z"),
     }
     return template % replacement
Esempio n. 15
0
 def doGet(self, handler, path):
     parts = path.split("/")[1:]
     if path == "/":
         self.send_response(200)
         self.send_header("Content-type", "text/html; charset=utf-8")
         self.end_headers()
         self.wfile.write(httpserver.get_template("factoids/index.html"))
     elif len(parts) == 2:
         channel = urllib.unquote(parts[0])
         if not ircutils.isChannel(channel):
             self.send_response(404)
             self.send_header("Content-type", "text/html; charset=utf-8")
             self.end_headers()
             self.wfile.write(
                 httpserver.get_template("generic/error.html")
                 % {"title": "Factoids - not a channel", "error": "This is not a channel"}
             )
             return
         if not self._plugin.registryValue("web.channel", channel):
             self.send_response(403)
             self.send_header("Content-type", "text/html; charset=utf-8")
             self.end_headers()
             self.wfile.write(
                 httpserver.get_template("generic/error.html")
                 % {
                     "title": "Factoids - unavailable",
                     "error": "This channel does not exist or its factoids " "are not available here.",
                 }
             )
             return
         db = self._plugin.getDb(channel)
         cursor = db.cursor()
         cursor.execute(
             """SELECT keys.key, factoids.id, factoids.fact
                           FROM factoids, keys, relations
                           WHERE relations.key_id=keys.id AND relations.fact_id=factoids.id
                           """
         )
         factoids = {}
         for (key, id_, fact) in cursor.fetchall():
             if key not in factoids:
                 factoids[key] = {}
             factoids[key][id_] = fact
         content = ""
         keys = factoids.keys()
         keys.sort()
         for key in keys:
             facts = factoids[key]
             content += "<tr>"
             content += ('<td rowspan="%i" class="key">' '<a name="%s" href="#%s">%s</a>' "</td>") % (
                 len(facts),
                 key,
                 key,
                 key,
             )
             for id_, fact in facts.items():
                 content += '<td class="id">%i</td>' % id_
                 content += '<td class="fact">%s</td>' % fact
                 content += "</tr><tr>"
             content = content[: -len("<tr>")]
         self.send_response(200)
         self.send_header("Content-type", "text/html; charset=utf-8")
         self.end_headers()
         self.wfile.write(httpserver.get_template("factoids/channel.html") % {"channel": channel, "rows": content})
Esempio n. 16
0
 def doGet(self, handler, path):
     output = ''
     splittedPath = path.split('/')
     try:
         if path == '/design.css':
             response = 200
             content_type = 'text/css; charset=utf-8'
             output = httpserver.get_template('webstats/design.css')
         elif path == '/':
             response = 200
             content_type = 'text/html; charset=utf-8'
             output = self.get_index()
         elif path == '/global/':
             response = 404
             content_type = 'text/html; charset=utf-8'
             output = """<p style="font-size: 20em">BAM!</p>
             <p>You played with the URL, you lost.</p>"""
         elif splittedPath[1] in ('nicks', 'global', 'links') \
                 and path[-1]=='/'\
                 or splittedPath[1] == 'nicks' and \
                 path.endswith('.htm'):
             response = 200
             content_type = 'text/html; charset=utf-8'
             if splittedPath[1] == 'links':
                 try:
                     import pygraphviz
                     content_type = 'image/png'
                 except ImportError:
                     content_type = 'text/plain; charset=utf-8'
                     response = 501
                     self.send_response(response)
                     self.send_header('Content-type', content_type)
                     self.end_headers()
                     self.wfile.write('Links cannot be displayed; ask '
                             'the bot owner to install python-pygraphviz.')
                     self.wfile.close()
                     return
             assert len(splittedPath) > 2
             chanName = splittedPath[2].replace('%20', '#')
             page = splittedPath[-1][0:-len('.htm')]
             if page == '':
                 page = '0'
             if splittedPath[1] == 'nicks':
                 formatter = self.get_nicks
             elif splittedPath[1] == 'global':
                 formatter = self.get_global
             elif splittedPath[1] == 'links':
                 formatter = self.get_links
             else:
                 raise AssertionError(splittedPath[1])
             
             if len(splittedPath) == 3:
                 _.loadLocale(self.plugin._getLanguage(chanName))
                 output = formatter(len(splittedPath), chanName, page)
             else:
                 assert len(splittedPath) > 3
                 _.loadLocale(self.plugin._getLanguage(chanName))
                 subdir = splittedPath[3].lower()
                 output = formatter(len(splittedPath), chanName, page,
                         subdir)
         else:
             response = 404
             content_type = 'text/html; charset=utf-8'
             output = httpserver.get_template('generic/error.html') % \
                 {'title': 'WebStats - not found',
                  'error': 'Requested page is not found. Sorry.'}
     except Exception as e:
         response = 500
         content_type = 'text/html; charset=utf-8'
         if output == '':
             error = '<h1>Internal server error</h1>'
             if DEBUG:
                 error = '<p>The server raised this exception: %s</p>' % \
                         repr(e)
             output = httpserver.get_template('generic/error.html') % \
                 {'title': 'Internal server error',
                  'error': error}
     finally:
         self.send_response(response)
         self.send_header('Content-type', content_type)
         self.end_headers()
         if sys.version_info[0] >= 3:
             output = output.encode()
         self.wfile.write(output)
Esempio n. 17
0
    def doGet(self, handler, path):
        output = ""
        splittedPath = path.split("/")
        try:
            if path == "/design.css":
                response = 200
                content_type = "text/css; charset=utf-8"
                output = httpserver.get_template("webstats/design.css")
            elif path == "/":
                response = 200
                content_type = "text/html; charset=utf-8"
                output = self.get_index()
            elif path == "/global/":
                response = 404
                content_type = "text/html; charset=utf-8"
                output = """<p style="font-size: 20em">BAM!</p>
                <p>You played with the URL, you lost.</p>"""
            elif (
                splittedPath[1] in ("nicks", "global", "links")
                and path[-1] == "/"
                or splittedPath[1] == "nicks"
                and path.endswith(".htm")
            ):
                response = 200
                content_type = "text/html; charset=utf-8"
                if splittedPath[1] == "links":
                    try:
                        import pygraphviz

                        content_type = "image/png"
                    except ImportError:
                        content_type = "text/plain; charset=utf-8"
                        response = 501
                        output = "Links cannot be displayed; ask " "the bot owner to install python-pygraphviz."
                        return
                assert len(splittedPath) > 2
                chanName = splittedPath[2].replace("%20", "#")
                page = splittedPath[-1][0 : -len(".htm")]
                if page == "":
                    page = "0"
                if splittedPath[1] == "nicks":
                    formatter = self.get_nicks
                elif splittedPath[1] == "global":
                    formatter = self.get_global
                elif splittedPath[1] == "links":
                    formatter = self.get_links
                else:
                    raise AssertionError(splittedPath[1])

                if len(splittedPath) == 3:
                    _.loadLocale(self.plugin._getLanguage(chanName))
                    output = formatter(len(splittedPath), chanName, page)
                else:
                    assert len(splittedPath) > 3
                    _.loadLocale(self.plugin._getLanguage(chanName))
                    subdir = splittedPath[3].lower()
                    output = formatter(len(splittedPath), chanName, page, subdir)
            else:
                response = 404
                content_type = "text/html; charset=utf-8"
                output = httpserver.get_template("generic/error.html") % {
                    "title": "WebStats - not found",
                    "error": "Requested page is not found. Sorry.",
                    "date": time.strftime("%Y-%m-%d %H:%M:%S%z"),
                }
        except Exception as e:
            response = 500
            content_type = "text/html; charset=utf-8"
            if output == "":
                error = "<h1>Internal server error</h1>"
                if DEBUG:
                    error = "<p>The server raised this exception: %s</p>" % repr(e)
                output = httpserver.get_template("generic/error.html") % {
                    "title": "Internal server error",
                    "error": error,
                    "date": time.strftime("%Y-%m-%d %H:%M:%S%z"),
                }
            import traceback

            traceback.print_exc()
        finally:
            self.send_response(response)
            self.send_header("Content-type", content_type)
            self.end_headers()
            if sys.version_info[0] >= 3:
                output = output.encode()
            self.wfile.write(output)
Esempio n. 18
0
    def doGet(self, handler, path):
        output = ''
        splittedPath = path.split('/')
        try:
            if path == '/design.css':
                response = 200
                content_type = 'text/css; charset=utf-8'
                output = httpserver.get_template('webstats/design.css')
            elif path == '/':
                response = 200
                content_type = 'text/html; charset=utf-8'
                output = self.get_index()
            elif path == '/global/':
                response = 404
                content_type = 'text/html; charset=utf-8'
                output = """<p style="font-size: 20em">BAM!</p>
                <p>You played with the URL, you lost.</p>"""
            elif splittedPath[1] in ('nicks', 'global', 'links') \
                    and path[-1]=='/'\
                    or splittedPath[1] == 'nicks' and \
                    path.endswith('.htm'):
                response = 200
                content_type = 'text/html; charset=utf-8'
                if splittedPath[1] == 'links':
                    try:
                        import pygraphviz
                        content_type = 'image/png'
                    except ImportError:
                        content_type = 'text/plain; charset=utf-8'
                        response = 501
                        output = 'Links cannot be displayed; ask ' \
                                'the bot owner to install python-pygraphviz.'
                        return
                assert len(splittedPath) > 2
                chanName = splittedPath[2].replace('%20', '#')
                page = splittedPath[-1][0:-len('.htm')]
                if page == '':
                    page = '0'
                if splittedPath[1] == 'nicks':
                    formatter = self.get_nicks
                elif splittedPath[1] == 'global':
                    formatter = self.get_global
                elif splittedPath[1] == 'links':
                    formatter = self.get_links
                else:
                    raise AssertionError(splittedPath[1])

                if len(splittedPath) == 3:
                    _.loadLocale(self.plugin._getLanguage(chanName))
                    output = formatter(len(splittedPath), chanName, page)
                else:
                    assert len(splittedPath) > 3
                    _.loadLocale(self.plugin._getLanguage(chanName))
                    subdir = splittedPath[3].lower()
                    output = formatter(len(splittedPath), chanName, page,
                                       subdir)
            else:
                response = 404
                content_type = 'text/html; charset=utf-8'
                output = httpserver.get_template('generic/error.html') % \
                    {'title': 'WebStats - not found',
                     'error': 'Requested page is not found. Sorry.',
                     'date': time.strftime('%Y-%m-%d %H:%M:%S%z')}
        except Exception as e:
            response = 500
            content_type = 'text/html; charset=utf-8'
            if output == '':
                error = '<h1>Internal server error</h1>'
                if DEBUG:
                    error = '<p>The server raised this exception: %s</p>' % \
                            repr(e)
                output = httpserver.get_template('generic/error.html') % \
                    {'title': 'Internal server error',
                     'error': error,
                     'date': time.strftime('%Y-%m-%d %H:%M:%S%z')}
            import traceback
            traceback.print_exc()
        finally:
            self.send_response(response)
            self.send_header('Content-type', content_type)
            self.end_headers()
            if sys.version_info[0] >= 3:
                output = output.encode()
            self.wfile.write(output)