~and471/harvest/pretty-harvest

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
162
163
164
165
166
167
168
169
#!/usr/bin/python
#
#    Copyright (C) 2008 Canonical Ltd.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import re
import sys
from cgi import escape

if __name__ != "__main__":
    # run this script by a web server
    from mod_python import apache
    xhtml = apache.import_module("./scripts/xhtml.py", autoreload=1)
else:
    from scripts import xhtml


def safe_convert(number):
    try:
        op = int(number)
    except:
        raise ValueError("Not an int: %s" % number)
    return op


def find_package(pkg):
    if not pkg:
        return ""
    if pkg.startswith("lib"):
        dirname = os.path.join(os.path.dirname(__file__), 
                               "data/packages/%s" % pkg[0:4])
    else:
        dirname = os.path.join(os.path.dirname(__file__),
                               "data/packages/%s" % pkg[0])
    fname = os.path.join(dirname, pkg)
    if not os.path.exists(fname):
        return ""

    return fname


def verify_args(args):
    # returns [pkgnames, filenames, reviewed arg, unreviewed arg]
    if not args or not args.has_key("pkg") or not args["pkg"]:
        return [None, None, None, None]
    
    reviewed = unreviewed = None
    if args.has_key("not_apply") and args["not_apply"]:
        reviewed = safe_convert(args["not_apply"])

    if args.has_key("apply_again") and args["apply_again"]:
        unreviewed = safe_convert(args["apply_again"])

    pkgs = []
    fnames = []
    for p in args["pkg"]:
        pkgs.append(p)
        fnames.append(find_package(p))

    return [pkgs, fnames, reviewed, unreviewed]


def parse_args(args_str):
    # unescape string
    unescape = [("%2C", ","),
                ("%2B", "+")]
    for item in unescape:
        args_str = item[1].join(args_str.split(item[0]))

    args = dict()
    for part in args_str.split("&"):
        if not part or not part.count("="):
            raise ValueError("args: %s" % args_str)
        else:
            s = part.split("=")
            if len(s)>2:
                raise ValueError("multiple '=' in one argument: %s" % args_str)
            (key, value) = part.split("=")
            if not key or not value:
                raise ValueError("empty key or empty value: %s" % args_str)
            args[key] = value

    if not args.has_key("pkg") or not args["pkg"]:
        raise ValueError("No packages: %s" % args_str)

    if filter(lambda a: (a not in ["pkg", "apply_again", "not_apply"]) or \
                        (not args[a]),
              args.keys()):
        raise ValueError("empty argument or unknown argument: %s" % args_str)

    # Validate package names
    args["pkg"] = args["pkg"].split(",")
    for pkg in args["pkg"]:
        if not pkg:
            raise ValueError("args: %s" % args_str)
        elif '..' in pkg:
            raise ValueError("Found '..': %s" % pkg)
        elif not re.match(r'^[a-z0-9][a-z0-9+\.\-]+$', pkg):
            # verify package name
            raise ValueError("Invalid package name: %s" % pkg)
    return args


def fill_placeholders(pkgs, html):
    pkg_list = ','.join(pkgs)
    print "<p>" + pkg_list.join(html.split("%s")) + "</p>"
    return pkg_list.join(html.split("%s"))

def main(args, output):
    # output is a function used to output the resulting HTML file

    args = verify_args(args)
    if not args[0]:
        return

    if not args[2] is None or not args[3] is None:
        if not args[2] is None:
            os.system(os.path.join(os.path.dirname(__file__), "scripts/deactivate_opportunity %s" % str(args[2])))
        if not args[3] is None:
            os.system(os.path.join(os.path.dirname(__file__), "scripts/activate_opportunity %s" % str(args[3])))
        # TODO: run generate_html in scripts/sourcepackage_content directly
        os.system(os.path.join(os.path.dirname(__file__), 
                               "scripts/sourcepackage_content %s" % ' '.join(args[0])))

    output(xhtml.header("Harvest"))
    output('<p>Go back to <a href="sourcepackages.html#' + xhtml.htmlify_anchors(args[0][0]) + '">Sourcepackage list</a> <a href="age.html">New incoming items</a></p>\n')

    for p in range(0, len(args[0])):
        if args[1][p]:
            html = open(args[1][p]).read()
            html = fill_placeholders(args[0], html)
            output(html)
        else:
            output("""<p style="font-weight: bold">There are no opportunities for '%s' or the package does not exist.</p>""" % escape(args[0][p]))

    output(xhtml.footer())


def handler(req):
    req.content_type = "text/html"
    if req.args:
        request = req.args
    else:
        request = req.read()
        if not request:
            return apache.OK

    main(parse_args(request), req.write)
    return apache.OK


if __name__ == "__main__":
    args = dict()
    args["pkg"] = sys.argv[1:]
    main(args, sys.stdout.write)