-
Notifications
You must be signed in to change notification settings - Fork 2
/
controller.py
executable file
·260 lines (229 loc) · 8.63 KB
/
controller.py
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#!/usr/bin/env python
# Import required modules
import cherrypy
import os, sys
from genshi.template import TemplateLoader
import MySQLdb
# This is just a little utility function
# that queries the DB for specific
# fields and then returns the result
# in a dictionary
def fetch(k, table, root, add=""):
cursor = root.cursor()
fields = []
names = []
for name in k:
if type(name)==tuple:
fields.append(name[0])
names.append(name[1])
else:
fields.append(name)
names.append(name)
cmd = "SELECT %s FROM %s %s" % (",".join(fields), table, add)
cursor.execute(cmd)
entries = []
for row in cursor.fetchall():
entries.append(stitch(row, names))
cursor.close()
return entries
# This is just a utility routine used by the
# fetch function
def stitch(t, k):
ret = {}
for e in zip(t,k):
ret[e[1]] = e[0]
return ret
# This is a class to represent the web site.
class Root(object):
def __init__(self):
import ConfigParser
import urllib
# Open configuration file
conf_file = os.path.join(os.path.dirname(__file__), 'mythpch.cfg')
options = ConfigParser.ConfigParser()
options.readfp(open(conf_file))
# Extract out select options
host = options.get("mysql", "host")
user = options.get("mysql", "user")
password = options.get("mysql", "password")
self.share = options.get("samba", "share")
# Connect to the SQL database
self.conn = MySQLdb.connect(host,
user=user,
passwd=password,
db='mythconverg',
use_unicode=True)
# Create the template loader
self.loader = TemplateLoader(
os.path.join(os.path.dirname(__file__), 'templates'),
auto_reload=True)
def cursor(self):
try:
# These are all here to make sure the
# connection is still alive. Is there
# a better way?
self.conn.get_server_info()
self.conn.ping()
self.conn.stat()
cursor = self.conn.cursor()
except OperationalError:
self.conn = MySQLdb.connect(host,
user=user,
passwd=password,
db='mythconverg',
use_unicode=True)
cursor = self.conn.cursor()
return cursor
@cherrypy.expose
def rss(self, recgroup, title):
import urllib
import os
cursor = self.cursor()
data = fetch(['recgroup','title','subtitle',
'description','basename', 'chanid',
'starttime',
("DATE_FORMAT(endtime, '%m/%e')",'endtime')],
'recorded', self, "ORDER BY starttime")
results = []
for d in data:
if d['recgroup']==recgroup and d['title']==title:
if d['subtitle']==None or len(d['subtitle'])==0:
d['subtitle'] = "<No Sub-Title Given>"
fname = "/data/video/library/"+d['basename']
d['length'] = os.stat(fname).st_size
results.append(d)
media_url = "file:///data/video/library/"+\
self.share
context = {'name': "name",
'recgroup': recgroup,
'title': title,
'media': media_url,
'results': results }
tmpl = self.loader.load('subgroup_rss.xml')
gen = tmpl.generate(**context)
return gen.render('xml', doctype='xhtml')
@cherrypy.expose
def bytitle(self, recgroup, title):
import urllib
cursor = self.cursor()
data = fetch(['recgroup','title','subtitle',
'description','basename', 'chanid',
'starttime',
("DATE_FORMAT(endtime, '%m/%e')",'endtime')],
'recorded', self, "ORDER BY starttime")
results = []
for d in data:
if d['recgroup']==recgroup and d['title']==title:
if d['subtitle']==None or len(d['subtitle'])==0:
d['subtitle'] = "<No Sub-Title Given>"
results.append(d)
media_url = "file:///opt/sybhttpd/localhost.drives/NETWORK_SHARE/"+\
self.share
context = {'name': "name",
'recgroup': recgroup,
'title': title,
'media': media_url,
'results': results }
tmpl = self.loader.load('subgroup_contents.html')
gen = tmpl.generate(**context)
return gen.render('html', doctype='html')
@cherrypy.expose
def recgroup(self, name):
import urllib
cursor = self.cursor()
data = fetch(['recgroup','title'], 'recorded', self)
results = {}
counts = {}
for d in data:
if d['recgroup']==name:
results[d['title']] = urllib.quote(d['title'])
if not d['title'] in counts:
counts[d['title']] = 0
counts[d['title']] = counts[d['title']] + 1
context = {'name': name,
'recgroup': urllib.quote(name),
'counts': counts,
'results': results }
tmpl = self.loader.load('group_contents.html')
gen = tmpl.generate(**context)
return gen.render('html', doctype='html')
def _findshow(self, chanid, year, month, day, hour, minute):
import MythTV
import sys
sys.argv = ["fake", "--host", "localhost"]
con = MythTV.MythTV()
rs = con.getRecordings()
for r in rs:
st = r.starttime
if r.chanid==int(chanid) and st.year==int(year) and \
st.month==int(month) and st.day==int(day) and \
st.hour==int(hour) and st.minute==int(minute):
return (con, r)
return (None, None)
@cherrypy.expose
def prompt(self, chanid, year, month, day, hour, minute):
(con, r) = self._findshow(chanid, year, month, day, hour, minute)
tmpl = self.loader.load('delete_show.html')
context = {'year': year, 'month': month, 'day': day,
'hour': hour, 'minute': minute,
'chanid': chanid, 'title': r.title}
gen = tmpl.generate(**context)
return gen.render('html', doctype='html')
@cherrypy.expose
def delete(self, chanid, year, month, day, hour, minute):
(con, r) = self._findshow(chanid, year, month, day, hour, minute)
con.deleteRecording(r)
raise cherrypy.HTTPRedirect( "/" )
@cherrypy.expose
def index(self):
import urllib
tmpl = self.loader.load('index.html')
cursor = self.cursor()
data = fetch(['recgroup'], 'recorded', self)
namemap = {}
for d in data:
namemap[d['recgroup']] = urllib.quote(d['recgroup'])
context = {'title': "MythTV Groups",
'namemap': namemap }
gen = tmpl.generate(**context)
return gen.render('html', doctype='html')
def config_server():
data = {}
# This is all to configure the CherryPy server
static_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), 'static'))
print "static dir = ", static_dir
base_config = {
'tools.encode.on': True,
'cherrypy.engine.SIGHUP': None,
'cherrypy.engine.SIGTERM': None,
'tools.decode.on': True,
'tools.trailing_slash.on': True,
'log.screen': True,
'log.error_file': 'server.log',
'tools.staticdir.root': static_dir,
'/media': { 'tools.staticdir.on': True,
'tools.staticdir.dir': 'media' },
'global': { 'server.socket_host': '0.0.0.0',
'server.socket_port': 8080 }
}
conf = {'/': { 'tools.staticdir.root': static_dir},
'/media': { 'tools.staticdir.on': True,
'tools.staticdir.dir': 'media' }}
cherrypy.config.update(base_config)
return conf
# This function gets called from Apache
def setup_server():
config_server()
cherrypy.engine.SIGHUP = None
cherrypy.engine.SIGTERM = None
cherrypy.tree.mount(Root())
# This function gets invoked if you run this from the command line
# and CherryPy supplies the server handling
def main():
conf = config_server()
# Create the root application object
root = Root()
cherrypy.quickstart(root, '/', config=conf)
if __name__ == '__main__':
main()