summaryrefslogtreecommitdiff
path: root/patchtracker/ReqHandler.py
blob: ca81be7cdfbb561dd1b9ccafd4e92b497e9f4353 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# -*- coding: utf-8 -*-

import cgi
import os
import sys

import patchtracker.Conf as Conf
from patchtracker.Templates import ErrorTemplate, LetterTocTemplate, FrontPageTemplate, SearchResultsTemplate
from patchtracker.CacheObject import CacheObject, CacheMissException
import patchtracker.DB as DB
from patchtracker.DB import PatchTrackerDB
import pygments
from pygments.lexers import DiffLexer
from pygments.formatters import HtmlFormatter
import patchtracker.SourceArchive as SourceArchive

class ReqHandlerException(Exception):
  def __init__(self, msg, code="500 Oh noes"):
    Exception.__init__(self, msg)
    self.status=code

class Cmd:
  def __init__(self):
    self.content_type = 'text/html'
    self.status = "200 OK"

class ErrorCmd(Cmd):
  def __init__(self, msg, code="500 Oh noes"):
    Cmd.__init__(self)
    self.status = code
    self.msg = msg

  def output(self):
    return str(ErrorTemplate(self.msg))

class PackageCmd(Cmd):
  def __init__(self, args):
    Cmd.__init__(self)
    db = PatchTrackerDB()
    self.name = args[0]
    if len(args) > 1:
      version = args[1]
    else:
      version = None
    self.toc = db.findCollection(package=self.name, version=version)

    # if there's no match, try with a wildcard match
    if not self.toc.size():
      # ... but don't allow pathologically short names
      if len(self.name) < 3:
        raise ReqHandlerException("search terms must be 3 or more letters...")
      else:
        self.toc = db.findCollection(package="%"+self.name+"%", version=version)

    plist = self.toc.getletter(self.name)
    if not plist or len(plist) == 0:
      raise ReqHandlerException("can't find any package named or containing '%s'"%self.name, code="404 ENOPKG kthxbye")

  def output(self):
    p = self.toc.getpackage(self.name)
    # if there is no match, or if multiple versions were returned
    if not p or len(set(map(lambda x: x.version, p.values()))) > 1:
      querydesc = "package name contains"
      return str(SearchResultsTemplate(self.name, querydesc, self.toc))

class IndexCmd(Cmd):
  def __init__(self, args):
    Cmd.__init__(self)
    if len(args) < 1 or not len(args[0]):
      raise ReqHandlerException("please provide a letter on which to index")
    else:
      self.db = PatchTrackerDB()
      self.letter = args[0]
      self.toc = self.db.findLetterToc(self.letter)

  def output(self):
    return str(LetterTocTemplate(self.letter, self.toc))

class MaintCmd(Cmd):
  def __init__(self, args):
    Cmd.__init__(self)
    if len(args) < 1 or not len(args[0]):
      raise ReqHandlerException("please provide a email address on which to index")
    else:
      self.db = PatchTrackerDB()
      self.email = args[0]
      self.toc = self.db.findCollection(email=self.email)

  def output(self):
    return str(SearchResultsTemplate(self.email, "maintainer email", self.toc))

class JumpCmd(Cmd):
  def __init__(self, env):
    Cmd.__init__(self)
    form = cgi.FieldStorage(fp=env['wsgi.input'],environ=env)
    self.name = form.getfirst("package")
    self.uri = "%s/package/%s"%(Conf.root_url, self.name)
    self.status = "302 Try this other place kthx"

  def output(self):
    return ""

class FrontPageCmd(Cmd):
  def __init__(self):
    Cmd.__init__(self)
    self.db = PatchTrackerDB()
    self.index = self.db.findIndices()

  def output(self):
    return str(FrontPageTemplate(self.index))

class CmdHandler:
  def __init__(self, env):
    self.headers = []
    uri = Conf.root_url+env['PATH_INFO']
    self.cacheobj = None
    #print "Accept:",env['HTTP_ACCEPT']

    args = uri[len(Conf.root_url)+1:].split("/")
    cmdarg = args[0]
    cacheable = False
    if cmdarg == "package":
      self.cmd = PackageCmd(args[1:]) 
      if len(args[1:]) > 1:
        cacheable = True
    elif cmdarg == "index":
      self.cmd = IndexCmd(args[1:]) 
    elif cmdarg == "jump":
      self.cmd = JumpCmd(env) 
      self.headers.append( ('Location', self.cmd.uri) )
    elif cmdarg == "email":
      self.cmd = MaintCmd(args[1:]) 
    elif not len(cmdarg):
      self.cmd = FrontPageCmd()
    else:
      self.cmd = ErrorCmd("invalid command/location '%s'"%(cmdarg), "404 Not found")

    if Conf.caching and cacheable:
      self.cacheobj = CacheObject(key=uri)

    self.headers.append( ('Content-type', self.cmd.content_type) )
    self.status = self.cmd.status

  def output(self):
    result = None
    try:
      if self.cacheobj:
        result = self.cacheobj.get()
      else:
        result = self.cmd.output()
    except CacheMissException:
      result = self.cmd.output()
      self.cacheobj.put(result)

    return result

if __name__ == '__main__':
  fake_env = { 'PATH_INFO': sys.argv[1] }
  cmdh = CmdHandler(fake_env)
  print "Status: %s\nHeaders: %s"%(cmdh.status, cmdh.headers)
  print cmdh.output()