Spelling
[pyTivo.git] / plugin.py
blob36dcb0ddbe8292a196ecfa48e467699f0d4581a3
1 import os, shutil, re, random, threading, urllib
2 from urlparse import urlparse
4 if os.path.sep == '/':
5 quote = urllib.quote
6 unquote = urllib.unquote_plus
7 else:
8 quote = lambda x: urllib.quote(x.replace(os.path.sep, '/'))
9 unquote = lambda x: urllib.unquote_plus(x).replace('/', os.path.sep)
11 def GetPlugin(name):
12 module_name = '.'.join(['plugins', name, name])
13 module = __import__(module_name, globals(), locals(), name)
14 plugin = getattr(module, module.CLASS_NAME)()
15 return plugin
17 class Plugin(object):
19 random_lock = threading.Lock()
21 CONTENT_TYPE = ''
23 def __new__(cls, *args, **kwds):
24 it = cls.__dict__.get('__it__')
25 if it is not None:
26 return it
27 cls.__it__ = it = object.__new__(cls)
28 it.init(*args, **kwds)
29 return it
31 def init(self):
32 pass
34 def send_file(self, handler, container, name):
35 o = urlparse("http://fake.host" + handler.path)
36 path = unquote(o[2])
37 handler.send_response(200)
38 handler.end_headers()
39 f = file(container['path'] + path[len(name)+1:], 'rb')
40 shutil.copyfileobj(f, handler.wfile)
42 def get_local_base_path(self, handler, query):
44 subcname = query['Container'][0]
45 container = handler.server.containers[subcname.split('/')[0]]
47 return container['path']
49 def get_local_path(self, handler, query):
51 subcname = query['Container'][0]
52 container = handler.server.containers[subcname.split('/')[0]]
54 path = container['path']
55 for folder in subcname.split('/')[1:]:
56 if folder == '..':
57 return False
58 path = os.path.join(path, folder)
59 return path
61 def item_count(self, handler, query, cname, files):
62 """Return only the desired portion of the list, as specified by
63 ItemCount, AnchorItem and AnchorOffset
64 """
65 totalFiles = len(files)
66 index = 0
68 if query.has_key('ItemCount'):
69 count = int(query['ItemCount'][0])
71 if query.has_key('AnchorItem'):
72 bs = '/TiVoConnect?Command=QueryContainer&Container='
73 local_base_path = self.get_local_base_path(handler, query)
75 anchor = query['AnchorItem'][0]
76 if anchor.startswith(bs):
77 anchor = anchor.replace(bs, '/')
78 anchor = unquote(anchor)
79 anchor = anchor.replace(os.path.sep + cname, local_base_path)
80 anchor = os.path.normpath(anchor)
82 try:
83 index = files.index(anchor)
84 except ValueError:
85 print 'Anchor not found:', anchor # just use index = 0
87 if count > 0:
88 index += 1
90 if query.has_key('AnchorOffset'):
91 index += int(query['AnchorOffset'][0])
93 #foward count
94 if count > 0:
95 files = files[index:index + count]
96 #backwards count
97 elif count < 0:
98 if index + count < 0:
99 count = -index
100 files = files[index + count:index]
101 index += count
103 else: # No AnchorItem
105 if count >= 0:
106 files = files[:count]
107 else:
108 index = count % len(files)
109 files = files[count:]
111 return files, totalFiles, index
113 def get_files(self, handler, query, filterFunction=None):
114 subcname = query['Container'][0]
115 cname = subcname.split('/')[0]
116 path = self.get_local_path(handler, query)
118 files = [ os.path.join(path, file) for file in os.listdir(path)]
119 if query.get('Recurse',['No'])[0] == 'Yes':
120 for file in files:
121 if os.path.isdir(file):
122 for new_file in os.listdir(file):
123 files.append( os.path.join(file, new_file) )
125 file_type = query.get('Filter', [''])[0]
126 if filterFunction:
127 files = [file for file in files if filterFunction(file, file_type)]
129 totalFiles = len(files)
131 def dir_sort(x, y):
132 xdir = os.path.isdir(os.path.join(path, x))
133 ydir = os.path.isdir(os.path.join(path, y))
135 if xdir == ydir:
136 return name_sort(x, y)
137 else:
138 return ydir - xdir
140 def name_sort(x, y):
141 numbername = re.compile(r'(\d*)(.*)')
142 m = numbername.match(x)
143 xNumber = m.group(1)
144 xStr = m.group(2)
145 m = numbername.match(y)
146 yNumber = m.group(1)
147 yStr = m.group(2)
149 if xNumber and yNumber:
150 xNumber, yNumber = int(xNumber), int(yNumber)
151 if xNumber == yNumber:
152 return cmp(xStr, yStr)
153 else:
154 return cmp(xNumber, yNumber)
155 elif xNumber:
156 return -1
157 elif yNumber:
158 return 1
159 else:
160 return cmp(xStr, yStr)
162 if query.get('SortOrder',['Normal'])[0] == 'Random':
163 seed = query.get('RandomSeed', ['1'])[0]
164 self.random_lock.acquire()
165 random.seed(seed)
166 random.shuffle(files)
167 self.random_lock.release()
168 else:
169 files.sort(dir_sort)
171 # Trim the list
172 return self.item_count(handler, query, cname, files)