Other code tidy ups and alignment with wmcbrine's fork
[pyTivo/wmcbrine/lucasnz.git] / plugin.py
blob784bf62c6e692a8a18fb6ea78418e897f602e114
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(unicode(path, 'utf-8'), 'rb')
75 shutil.copyfileobj(f, handler.wfile)
76 f.close()
78 def get_local_base_path(self, handler, query):
79 return os.path.normpath(handler.container['path'])
81 def get_local_path(self, handler, query):
83 subcname = query['Container'][0]
85 path = self.get_local_base_path(handler, query)
86 for folder in subcname.split('/')[1:]:
87 if folder == '..':
88 return False
89 path = os.path.join(path, folder)
90 return path
92 def item_count(self, handler, query, cname, files, last_start=0):
93 """Return only the desired portion of the list, as specified by
94 ItemCount, AnchorItem and AnchorOffset. 'files' is either a
95 list of strings, OR a list of objects with a 'name' attribute.
96 """
97 def no_anchor(handler, anchor):
98 handler.server.logger.warning('Anchor not found: ' + anchor)
100 totalFiles = len(files)
101 index = 0
103 if totalFiles and 'ItemCount' in query:
104 count = int(query['ItemCount'][0])
106 if 'AnchorItem' in query:
107 bs = '/TiVoConnect?Command=QueryContainer&Container='
108 local_base_path = self.get_local_base_path(handler, query)
110 anchor = query['AnchorItem'][0]
111 if anchor.startswith(bs):
112 anchor = anchor.replace(bs, '/', 1)
113 anchor = unquote(anchor)
114 anchor = anchor.replace(os.path.sep + cname, local_base_path, 1)
115 if not '://' in anchor:
116 anchor = os.path.normpath(anchor)
118 if type(files[0]) == str:
119 filenames = files
120 else:
121 filenames = [x.name for x in files]
122 try:
123 index = filenames.index(anchor, last_start)
124 except ValueError:
125 if last_start:
126 try:
127 index = filenames.index(anchor, 0, last_start)
128 except ValueError:
129 no_anchor(handler, anchor)
130 else:
131 no_anchor(handler, anchor) # just use index = 0
133 if count > 0:
134 index += 1
136 if 'AnchorOffset' in query:
137 index += int(query['AnchorOffset'][0])
139 if count < 0:
140 index = (index + count) % len(files)
141 count = -count
142 files = files[index:index + count]
144 return files, totalFiles, index
146 def get_files(self, handler, query, filterFunction=None, force_alpha=False):
148 class FileData:
149 def __init__(self, name, isdir):
150 self.name = name
151 self.isdir = isdir
152 st = os.stat(unicode(name, 'utf-8'))
153 self.mdate = int(st.st_mtime)
154 self.size = st.st_size
156 class SortList:
157 def __init__(self, files):
158 self.files = files
159 self.unsorted = True
160 self.sortby = None
161 self.last_start = 0
163 def build_recursive_list(path, recurse=True):
164 files = []
165 path = unicode(path, 'utf-8')
166 try:
167 for f in os.listdir(path):
168 if f.startswith('.'):
169 continue
170 f = os.path.join(path, f)
171 isdir = os.path.isdir(f)
172 f = f.encode('utf-8')
173 if recurse and isdir:
174 files.extend(build_recursive_list(f))
175 else:
176 if not filterFunction or filterFunction(f, file_type):
177 files.append(FileData(f, isdir))
178 except:
179 pass
180 return files
182 subcname = query['Container'][0]
183 path = self.get_local_path(handler, query)
185 file_type = query.get('Filter', [''])[0]
187 recurse = query.get('Recurse', ['No'])[0] == 'Yes'
189 filelist = []
190 rc = self.recurse_cache
191 dc = self.dir_cache
192 if recurse:
193 if path in rc and rc.mtime(path) + 300 >= time.time():
194 filelist = rc[path]
195 else:
196 updated = os.stat(unicode(path, 'utf-8'))[8]
197 if path in dc and dc.mtime(path) >= updated:
198 filelist = dc[path]
199 for p in rc:
200 if path.startswith(p) and rc.mtime(p) < updated:
201 del rc[p]
203 if not filelist:
204 filelist = SortList(build_recursive_list(path, recurse))
206 if recurse:
207 rc[path] = filelist
208 else:
209 dc[path] = filelist
211 def dir_sort(x, y):
212 if x.isdir == y.isdir:
213 return name_sort(x, y)
214 else:
215 return y.isdir - x.isdir
217 def name_sort(x, y):
218 return cmp(x.name, y.name)
220 def date_sort(x, y):
221 return cmp(y.mdate, x.mdate)
223 sortby = query.get('SortOrder', ['Normal'])[0]
224 if filelist.unsorted or filelist.sortby != sortby:
225 if force_alpha:
226 filelist.files.sort(dir_sort)
227 elif sortby == '!CaptureDate':
228 filelist.files.sort(date_sort)
229 else:
230 filelist.files.sort(name_sort)
232 filelist.sortby = sortby
233 filelist.unsorted = False
235 files = filelist.files[:]
237 # Trim the list
238 files, total, start = self.item_count(handler, query, handler.cname,
239 files, filelist.last_start)
240 if len(files) > 1:
241 filelist.last_start = start
242 return files, total, start