Hmm.
[pyTivo/TheBayer.git] / plugin.py
blobd6cab46561d69368170e9ccc02fe3e9118b5d184
1 import os
2 import random
3 import shutil
4 import sys
5 import threading
6 import time
7 import urllib
9 from Cheetah.Filters import Filter
10 from lrucache import LRUCache
12 if os.path.sep == '/':
13 quote = urllib.quote
14 unquote = urllib.unquote_plus
15 else:
16 quote = lambda x: urllib.quote(x.replace(os.path.sep, '/'))
17 unquote = lambda x: os.path.normpath(urllib.unquote_plus(x))
19 class Error:
20 CONTENT_TYPE = 'text/html'
22 def GetPlugin(name):
23 try:
24 module_name = '.'.join(['plugins', name, name])
25 module = __import__(module_name, globals(), locals(), name)
26 plugin = getattr(module, module.CLASS_NAME)()
27 return plugin
28 except ImportError:
29 print 'Error no', name, 'plugin exists. Check the type ' \
30 'setting for your share.'
31 return Error
33 class EncodeUnicode(Filter):
34 def filter(self, val, **kw):
35 """Encode Unicode strings, by default in UTF-8"""
37 encoding = kw.get('encoding', 'utf8')
39 if type(val) == str:
40 try:
41 val = val.decode('utf8')
42 except:
43 if sys.platform == 'darwin':
44 val = val.decode('macroman')
45 else:
46 val = val.decode('iso8859-1')
47 elif type(val) != unicode:
48 val = str(val)
49 return val.encode(encoding)
51 class Plugin(object):
53 random_lock = threading.Lock()
55 CONTENT_TYPE = ''
57 recurse_cache = LRUCache(5)
58 dir_cache = LRUCache(10)
60 def __new__(cls, *args, **kwds):
61 it = cls.__dict__.get('__it__')
62 if it is not None:
63 return it
64 cls.__it__ = it = object.__new__(cls)
65 it.init(*args, **kwds)
66 return it
68 def init(self):
69 pass
71 def send_file(self, handler, path, query):
72 handler.send_response(200)
73 handler.end_headers()
74 f = open(path, 'rb')
75 shutil.copyfileobj(f, handler.wfile)
76 f.close()
78 def get_local_base_path(self, handler, query):
80 subcname = query['Container'][0]
81 container = handler.server.containers[subcname.split('/')[0]]
83 return os.path.normpath(container['path'])
85 def get_local_path(self, handler, query):
87 subcname = query['Container'][0]
88 container = handler.server.containers[subcname.split('/')[0]]
90 path = os.path.normpath(container['path'])
91 for folder in subcname.split('/')[1:]:
92 if folder == '..':
93 return False
94 path = os.path.join(path, folder)
95 return path
97 def item_count(self, handler, query, cname, files, last_start=0):
98 """Return only the desired portion of the list, as specified by
99 ItemCount, AnchorItem and AnchorOffset. 'files' is either a
100 list of strings, OR a list of objects with a 'name' attribute.
102 def no_anchor(handler, anchor):
103 handler.server.logger.warning('Anchor not found: ' + anchor)
105 totalFiles = len(files)
106 index = 0
108 if totalFiles and 'ItemCount' in query:
109 count = int(query['ItemCount'][0])
111 if 'AnchorItem' in query:
112 bs = '/TiVoConnect?Command=QueryContainer&Container='
113 local_base_path = self.get_local_base_path(handler, query)
115 anchor = query['AnchorItem'][0]
116 if anchor.startswith(bs):
117 anchor = anchor.replace(bs, '/', 1)
118 anchor = unquote(anchor)
119 anchor = anchor.replace(os.path.sep + cname, local_base_path, 1)
120 if not '://' in anchor:
121 anchor = os.path.normpath(anchor)
123 if type(files[0]) == str:
124 filenames = files
125 else:
126 filenames = [x.name for x in files]
127 try:
128 index = filenames.index(anchor, last_start)
129 except ValueError:
130 if last_start:
131 try:
132 index = filenames.index(anchor, 0, last_start)
133 except ValueError:
134 no_anchor(handler, anchor)
135 else:
136 no_anchor(handler, anchor) # just use index = 0
138 if count > 0:
139 index += 1
141 if 'AnchorOffset' in query:
142 index += int(query['AnchorOffset'][0])
144 #foward count
145 if count >= 0:
146 files = files[index:index + count]
147 #backwards count
148 else:
149 if index + count < 0:
150 count = -index
151 files = files[index + count:index]
152 index += count
154 else: # No AnchorItem
156 if count >= 0:
157 files = files[:count]
158 else:
159 index = count % len(files)
160 files = files[count:]
162 return files, totalFiles, index
164 def get_files(self, handler, query, filterFunction=None, force_alpha=False):
166 class FileData:
167 def __init__(self, name, isdir):
168 self.name = name
169 self.isdir = isdir
170 st = os.stat(name)
171 self.mdate = int(st.st_mtime)
173 class SortList:
174 def __init__(self, files):
175 self.files = files
176 self.unsorted = True
177 self.sortby = None
178 self.last_start = 0
180 def build_recursive_list(path, recurse=True):
181 files = []
182 try:
183 for f in os.listdir(path):
184 if f.startswith('.'):
185 continue
186 f = os.path.join(path, f)
187 isdir = os.path.isdir(f)
188 if recurse and isdir:
189 files.extend(build_recursive_list(f))
190 else:
191 if not filterFunction or filterFunction(f, file_type):
192 files.append(FileData(f, isdir))
193 except:
194 pass
195 return files
197 subcname = query['Container'][0]
198 cname = subcname.split('/')[0]
199 path = self.get_local_path(handler, query)
201 file_type = query.get('Filter', [''])[0]
203 recurse = query.get('Recurse', ['No'])[0] == 'Yes'
205 filelist = []
206 rc = self.recurse_cache
207 dc = self.dir_cache
208 if recurse:
209 if path in rc and rc.mtime(path) + 300 >= time.time():
210 filelist = rc[path]
211 else:
212 updated = os.stat(path)[8]
213 if path in dc and dc.mtime(path) >= updated:
214 filelist = dc[path]
215 for p in rc:
216 if path.startswith(p) and rc.mtime(p) < updated:
217 del rc[p]
219 if not filelist:
220 filelist = SortList(build_recursive_list(path, recurse))
222 if recurse:
223 rc[path] = filelist
224 else:
225 dc[path] = filelist
227 def dir_sort(x, y):
228 if x.isdir == y.isdir:
229 return name_sort(x, y)
230 else:
231 return y.isdir - x.isdir
233 def name_sort(x, y):
234 return cmp(x.name, y.name)
236 def date_sort(x, y):
237 return cmp(y.mdate, x.mdate)
239 sortby = query.get('SortOrder', ['Normal'])[0]
240 if filelist.unsorted or filelist.sortby != sortby:
241 if force_alpha:
242 filelist.files.sort(dir_sort)
243 elif sortby == '!CaptureDate':
244 filelist.files.sort(date_sort)
245 else:
246 filelist.files.sort(name_sort)
248 filelist.sortby = sortby
249 filelist.unsorted = False
251 files = filelist.files[:]
253 # Trim the list
254 files, total, start = self.item_count(handler, query, cname, files,
255 filelist.last_start)
256 filelist.last_start = start
257 return files, total, start