Even more audio ids for AAC.
[pyTivo/wmcbrine.git] / plugin.py
blob8efbbc17a3ca4d9c3c23223231bec9b6027dea27
1 import os
2 import shutil
3 import random
4 import threading
5 import urllib
6 from urlparse import urlparse
8 if os.path.sep == '/':
9 quote = urllib.quote
10 unquote = urllib.unquote_plus
11 else:
12 quote = lambda x: urllib.quote(x.replace(os.path.sep, '/'))
13 unquote = lambda x: urllib.unquote_plus(x).replace('/', os.path.sep)
15 class Error:
16 CONTENT_TYPE = 'text/html'
18 def GetPlugin(name):
19 try:
20 module_name = '.'.join(['plugins', name, name])
21 module = __import__(module_name, globals(), locals(), name)
22 plugin = getattr(module, module.CLASS_NAME)()
23 return plugin
24 except ImportError:
25 print 'Error no', name, 'plugin exists. Check the type ' \
26 'setting for your share.'
27 return Error
29 class Plugin(object):
31 random_lock = threading.Lock()
33 CONTENT_TYPE = ''
35 def __new__(cls, *args, **kwds):
36 it = cls.__dict__.get('__it__')
37 if it is not None:
38 return it
39 cls.__it__ = it = object.__new__(cls)
40 it.init(*args, **kwds)
41 return it
43 def init(self):
44 pass
46 def send_file(self, handler, container, name):
47 o = urlparse("http://fake.host" + handler.path)
48 path = unquote(o[2])
49 handler.send_response(200)
50 handler.end_headers()
51 f = open(container['path'] + path[len(name) + 1:], 'rb')
52 shutil.copyfileobj(f, handler.wfile)
53 f.close()
55 def get_local_base_path(self, handler, query):
57 subcname = query['Container'][0]
58 container = handler.server.containers[subcname.split('/')[0]]
60 return os.path.normpath(container['path'])
62 def get_local_path(self, handler, query):
64 subcname = query['Container'][0]
65 container = handler.server.containers[subcname.split('/')[0]]
67 path = os.path.normpath(container['path'])
68 for folder in subcname.split('/')[1:]:
69 if folder == '..':
70 return False
71 path = os.path.join(path, folder)
72 return path
74 def item_count(self, handler, query, cname, files, last_start=0):
75 """Return only the desired portion of the list, as specified by
76 ItemCount, AnchorItem and AnchorOffset. 'files' is either a
77 list of strings, OR a list of objects with a 'name' attribute.
78 """
79 totalFiles = len(files)
80 index = 0
82 if totalFiles and 'ItemCount' in query:
83 count = int(query['ItemCount'][0])
85 if 'AnchorItem' in query:
86 bs = '/TiVoConnect?Command=QueryContainer&Container='
87 local_base_path = self.get_local_base_path(handler, query)
89 anchor = query['AnchorItem'][0]
90 if anchor.startswith(bs):
91 anchor = anchor.replace(bs, '/', 1)
92 anchor = unquote(anchor)
93 anchor = anchor.replace(os.path.sep + cname, local_base_path, 1)
94 if not '://' in anchor:
95 anchor = os.path.normpath(anchor)
97 if type(files[0]) == str:
98 filenames = files
99 else:
100 filenames = [x.name for x in files]
101 try:
102 index = filenames.index(anchor, last_start)
103 except ValueError:
104 if last_start:
105 try:
106 index = filenames.index(anchor, 0, last_start)
107 except ValueError:
108 print 'Anchor not found:', anchor
109 else:
110 print 'Anchor not found:', anchor # just use index = 0
112 if count > 0:
113 index += 1
115 if 'AnchorOffset' in query:
116 index += int(query['AnchorOffset'][0])
118 #foward count
119 if count >= 0:
120 files = files[index:index + count]
121 #backwards count
122 else:
123 if index + count < 0:
124 count = -index
125 files = files[index + count:index]
126 index += count
128 else: # No AnchorItem
130 if count >= 0:
131 files = files[:count]
132 else:
133 index = count % len(files)
134 files = files[count:]
136 return files, totalFiles, index
138 def get_files(self, handler, query, filterFunction=None):
140 def build_recursive_list(path, recurse=True):
141 files = []
142 try:
143 for f in os.listdir(path):
144 if f.startswith('.'):
145 continue
146 f = os.path.join(path, f)
147 if recurse and os.path.isdir(f):
148 files.extend(build_recursive_list(f))
149 else:
150 if not filterFunction or filterFunction(f, file_type):
151 files.append(f)
152 except:
153 pass
154 return files
156 subcname = query['Container'][0]
157 cname = subcname.split('/')[0]
158 path = self.get_local_path(handler, query)
160 file_type = query.get('Filter', [''])[0]
162 recurse = query.get('Recurse', ['No'])[0] == 'Yes'
163 files = build_recursive_list(path, recurse)
165 totalFiles = len(files)
167 def dir_sort(x, y):
168 xdir = os.path.isdir(os.path.join(path, x))
169 ydir = os.path.isdir(os.path.join(path, y))
171 if xdir == ydir:
172 return name_sort(x, y)
173 else:
174 return ydir - xdir
176 def name_sort(x, y):
177 return cmp(x, y)
179 def date_sort(x, y):
180 return cmp(os.stat(y).st_mtime, os.stat(x).st_mtime)
182 if query.get('SortOrder', ['Normal'])[0] == 'Random':
183 seed = query.get('RandomSeed', ['1'])[0]
184 self.random_lock.acquire()
185 random.seed(seed)
186 random.shuffle(files)
187 self.random_lock.release()
188 elif query.get('SortOrder', ['Normal'])[0] == '!CaptureDate':
189 files.sort(date_sort)
190 else:
191 files.sort(dir_sort)
193 # Trim the list
194 return self.item_count(handler, query, cname, files)