Use a single save/load for the config, instead of having a separate
[pyTivo/wgw.git] / plugin.py
blobcbe2199b6a916d2f7108ae2965c916b990d9529d
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 = file(container['path'] + path[len(name) + 1:], 'rb')
52 shutil.copyfileobj(f, handler.wfile)
54 def get_local_base_path(self, handler, query):
56 subcname = query['Container'][0]
57 container = handler.server.containers[subcname.split('/')[0]]
59 return os.path.normpath(container['path'])
61 def get_local_path(self, handler, query):
63 subcname = query['Container'][0]
64 container = handler.server.containers[subcname.split('/')[0]]
66 path = os.path.normpath(container['path'])
67 for folder in subcname.split('/')[1:]:
68 if folder == '..':
69 return False
70 path = os.path.join(path, folder)
71 return path
73 def item_count(self, handler, query, cname, files, last_start=0):
74 """Return only the desired portion of the list, as specified by
75 ItemCount, AnchorItem and AnchorOffset. 'files' is either a
76 list of strings, OR a list of objects with a 'name' attribute.
77 """
78 totalFiles = len(files)
79 index = 0
81 if totalFiles and 'ItemCount' in query:
82 count = int(query['ItemCount'][0])
84 if 'AnchorItem' in query:
85 bs = '/TiVoConnect?Command=QueryContainer&Container='
86 local_base_path = self.get_local_base_path(handler, query)
88 anchor = query['AnchorItem'][0]
89 if anchor.startswith(bs):
90 anchor = anchor.replace(bs, '/', 1)
91 anchor = unquote(anchor)
92 anchor = anchor.replace(os.path.sep + cname, local_base_path, 1)
93 if not '://' in anchor:
94 anchor = os.path.normpath(anchor)
96 if type(files[0]) == str:
97 filenames = files
98 else:
99 filenames = [x.name for x in files]
100 try:
101 index = filenames.index(anchor, last_start)
102 except ValueError:
103 if last_start:
104 try:
105 index = filenames.index(anchor, 0, last_start)
106 except ValueError:
107 print 'Anchor not found:', anchor
108 else:
109 print 'Anchor not found:', anchor # just use index = 0
111 if count > 0:
112 index += 1
114 if 'AnchorOffset' in query:
115 index += int(query['AnchorOffset'][0])
117 #foward count
118 if count >= 0:
119 files = files[index:index + count]
120 #backwards count
121 else:
122 if index + count < 0:
123 count = -index
124 files = files[index + count:index]
125 index += count
127 else: # No AnchorItem
129 if count >= 0:
130 files = files[:count]
131 else:
132 index = count % len(files)
133 files = files[count:]
135 return files, totalFiles, index
137 def get_files(self, handler, query, filterFunction=None):
139 def build_recursive_list(path, recurse=True):
140 files = []
141 try:
142 for f in os.listdir(path):
143 if f.startswith('.'):
144 continue
145 f = os.path.join(path, f)
146 if recurse and os.path.isdir(f):
147 files.extend(build_recursive_list(f))
148 else:
149 if not filterFunction or filterFunction(f, file_type):
150 files.append(f)
151 except:
152 pass
153 return files
155 subcname = query['Container'][0]
156 cname = subcname.split('/')[0]
157 path = self.get_local_path(handler, query)
159 file_type = query.get('Filter', [''])[0]
161 recurse = query.get('Recurse',['No'])[0] == 'Yes'
162 files = build_recursive_list(path, recurse)
164 totalFiles = len(files)
166 def dir_sort(x, y):
167 xdir = os.path.isdir(os.path.join(path, x))
168 ydir = os.path.isdir(os.path.join(path, y))
170 if xdir == ydir:
171 return name_sort(x, y)
172 else:
173 return ydir - xdir
175 def name_sort(x, y):
176 return cmp(x, y)
178 if query.get('SortOrder',['Normal'])[0] == 'Random':
179 seed = query.get('RandomSeed', ['1'])[0]
180 self.random_lock.acquire()
181 random.seed(seed)
182 random.shuffle(files)
183 self.random_lock.release()
184 else:
185 files.sort(dir_sort)
187 # Trim the list
188 return self.item_count(handler, query, cname, files)