Created Rate My Lit Review
[ipdf/sam.git] / rate-my-litreview.py
1 #!/usr/bin/python
2
3 import sys
4 import os
5 import sqlite3
6 import cgi
7 import smtplib
8 from email.mime.text import MIMEText
9 import datetime
10 import subprocess
11 import random
12
13 # Setup a sqlite3 database before deploying:
14 # sqlite3 ratings.db
15 # sqlite> CREATE TABLE ratings(formalness, citeyness, reviewyness, accurateness, boringness, pointyness, overallness, version, time, message, page);
16 # Get rid of database by DROP TABLE or deleting the file
17
18 target_email = "matches@ucc.asn.au"
19 secret_answers = ["No", "no"]
20 dbfile = "ratings.db"
21
22 def print_form(name):
23         """ Print the form """
24         f = open(name,"r")
25         for line in f.readlines():
26                 print(line)
27         f.close()
28
29 def git_stamp():
30         # Python is nice but sometimes you just need to bash it over the head
31         p = subprocess.Popen("git show | head --lines=1 | awk '{print $NF}'", stdout=subprocess.PIPE, shell=True)
32         return p.stdout.readline().strip(" \r\n")
33
34 def main(argv):
35         """ Do the shit """
36         con = sqlite3.connect(dbfile)
37         c = con.cursor()
38
39         # Values we expect
40         values = {
41                 "formalness" : "",
42                 "citeyness" : "",
43                 "reviewyness" : "",
44                 "accurateness" : "",
45                 "boringness" : "",
46                 "pointyness" : "",
47                 "overallness" : "",
48                 "page" : 0,
49                 "secret" : "No"
50         }
51
52         sanity = True
53
54         # Max pages
55         p = subprocess.Popen("pdfinfo thesis.pdf | grep Pages | sed 's/[^0-9]*//'", stdout=subprocess.PIPE, shell=True)
56         max_pages = int(p.stdout.read().strip(" \r\bn"))
57                 
58
59
60         form = cgi.FieldStorage()
61
62         # Check we have all the values
63         for k in values.keys():
64                 if k in form:
65                         values[k] = form[k].value
66
67
68         # No values? Print the form
69         if len(form.keys()) <= 0 or "page" not in form:
70                 values["page"] = random.randint(1, max_pages)
71
72         print("Content-type: text/html\n")
73         print("<!DOCTYPE html>")
74         print("<html>")
75         print("<head><title>Rate My LitReview(TM) (Patent Pending)</title>")
76         print("<style>body {font-size: 0;}")
77         print("body * {font-size: 16px;}")
78         print("</style>")
79         print("</head>")
80         print("<body style=\"font-size: 0;\">")
81
82         # Check page number
83         try:
84                 values["page"] = int(values["page"])
85         except:
86                 print("<p> Invalid Page %s!</p>" % values["page"])
87                 values["page"] = random.randint(1, max_pages)
88                 sanity = False
89
90         print("<form id=\"rating\" action=\"rate-my-litreview.py\" method=\"POST\">")
91
92         
93         print("<h1>Rate My Lit Review</h1>")
94         print("<p>Read a page, then rate it with the hammer of judgement!</p>")
95         print("<p> Page: <input type=\"text\" name=\"page\" value=\"%d\" disabled> of %d" % (values["page"], max_pages))
96         if values["page"] > 1:
97                 print("<a href=\"rate-my-litreview.py?page=%d\">Prev</a>" % (values["page"]-1))
98         if values["page"] < max_pages:
99                 print("<a href=\"rate-my-litreview.py?page=%d\">Next</a>" % (values["page"]+1))
100         print("</p>")
101
102
103
104
105
106         # Check secret question
107         if values["secret"] not in secret_answers: 
108                 print("<p><b>You failed the turing test!</b> Hint: The answer is \"No\"</p>")
109                 sanity = False
110         del values["secret"]
111
112
113         print("<div style=\"float: left; border:0px solid black;\">")
114         print("<img src=\"read-my-litreview.py?page=%d\" border=\"1\";>" % values["page"])
115         print("</div>")
116
117
118         print("<div style=\"float: right; border:0px solid black; width:43%;\">")
119         print_form("rate-my-litreview.html")
120         print("</div>")
121
122
123         if not sanity:
124                 return 1        
125
126         if len(form.keys()) <= 1:
127                 print("</body></html>")
128                 return 0
129
130         # Sanity checks complete; set other values
131         values.update({"time" : int(datetime.datetime.now().strftime("%s"))})
132         values.update({"version" : git_stamp()})
133
134         # Produce emails
135         
136         # Send emails
137         emails = ["matches@ucc.asn.au"]
138         userMsg = "Someone Rated Your LitReview!\n"
139         userMsg += "Your ratings\n-----------------\n"
140         for k in values:
141                 userMsg += str(k) + ":\t" + str(values[k])
142
143         userMsg += "Happy LitReviewing!\n"
144         userMsg += "\n\nNOTE: This Message Automatically Sent By Rate My LitReview(TM) (Patent Pending)\n"
145         userMsg = MIMEText(userMsg)
146         for i,msg in enumerate([userMsg]):
147                 msg["Subject"] = "Rate My LitReview"
148                 msg["From"] = "matches@ucc.asn.au"
149                 msg["To"] = emails[i]
150                 s = smtplib.SMTP("localhost")
151                 s.sendmail(msg["From"], [msg["To"]], msg.as_string())
152                 s.quit()
153
154         # Tell them what happened.
155         # Do the thing
156         c.execute("INSERT INTO ratings("+",".join(values.keys())+") VALUES("+",".join(["?" for _ in xrange(len(values.keys()))])+")", [values[k] for k in values.keys()])
157         con.commit()
158         con.close()
159
160         print("<script>alert(\"Thank you for rating Page %d.\");</script><noscript>Thanks for rating Page %d</noscript>" % (values["page"], values["page"]))
161         print("</body></html>")
162         return 0
163         
164         
165 if __name__ == "__main__":
166         #try:
167         sys.exit(main(sys.argv))
168         #except:
169         #       print "Content-type: text/plain\r\n\r\n"
170         #       print "Something went wrong! You were unable to Rate Sam's LitReview(TM)!\nPlease send him an abusive email instead <matches at ucc.asn.au>\n"
171

UCC git Repository :: git.ucc.asn.au