e13370b592d2e24a535e5f5b2e45a5bac6740d93
[enigma2.git] / lib / python / Components / Scanner.py
1 from Plugins.Plugin import PluginDescriptor
2 from Components.PluginComponent import plugins
3
4 from os import path as os_path, walk as os_walk
5 from string import lower
6 from mimetypes import guess_type
7
8 def getExtension(file):
9         p = file.rfind('.')
10         if p == -1:
11                 ext = ""
12         else:   
13                 ext = file[p+1:]
14
15         return lower(ext)
16
17 def getType(file):
18         (type, _) = guess_type(file)
19         if type is None:
20                 # Detect some mimetypes unknown to dm7025
21                 # TODO: do mimetypes.add_type once should be better
22                 ext = getExtension(file)
23                 if ext == "ipk":
24                         return "application/x-debian-package"
25                 elif ext == "ogg":
26                         return "application/ogg"
27                 elif ext == "dmpkg":
28                         return "application/x-dream-package"
29                 elif ext == "ts":
30                         return "video/MP2T"
31                 elif ext == "iso":
32                         return "video/x-dvd-iso"
33                 elif file[-12:].lower() == "video_ts.ifo":
34                         return "video/x-dvd"
35                 elif ext == "dat" and file[-11:-6].lower() == "avseq":
36                         return "video/x-vcd"
37         return type
38
39 class Scanner:
40         def __init__(self, name, mimetypes= [], paths_to_scan = [], description = "", openfnc = None):
41                 self.mimetypes = mimetypes
42                 self.name = name
43                 self.paths_to_scan = paths_to_scan
44                 self.description = description
45                 self.openfnc = openfnc
46
47         def checkFile(self, file):
48                 return True
49
50         def handleFile(self, res, file):
51                 if (self.mimetypes is None or file.mimetype in self.mimetypes) and self.checkFile(file):
52                         res.setdefault(self, []).append(file)
53
54         def __repr__(self):
55                 return "<Scanner " + self.name + ">"
56
57         def open(self, list, *args, **kwargs):
58                 if self.openfnc is not None:
59                         self.openfnc(list, *args, **kwargs)
60
61 class ScanPath:
62         def __init__(self, path, with_subdirs = False):
63                 self.path = path
64                 self.with_subdirs = with_subdirs
65
66         def __repr__(self):
67                 return self.path + "(" + str(self.with_subdirs) + ")"
68
69         # we will use this in a set(), so we need to implement __hash__ and __cmp__
70         def __hash__(self):
71                 return self.path.__hash__() ^ self.with_subdirs.__hash__()
72
73         def __cmp__(self, other):
74                 if self.path < other.path:
75                         return -1
76                 elif self.path > other.path:
77                         return +1
78                 else:
79                         return self.with_subdirs.__cmp__(other.with_subdirs)
80
81 class ScanFile:
82         def __init__(self, path, mimetype = None, size = None, autodetect = True):
83                 self.path = path
84                 if mimetype is None and autodetect:
85                         self.mimetype = getType(path)
86                 else:
87                         self.mimetype = mimetype
88                 self.size = size
89
90         def __repr__(self):
91                 return "<ScanFile " + self.path + " (" + str(self.mimetype) + ", " + str(self.size) + " MB)>"
92
93 def execute(option):
94         print "execute", option
95         if option is None:
96                 return
97
98         (_, scanner, files, session) = option
99         scanner.open(files, session)
100
101 def scanDevice(mountpoint):
102         scanner = [ ]
103
104         for p in plugins.getPlugins(PluginDescriptor.WHERE_FILESCAN):
105                 l = p()
106                 if not isinstance(l, list):
107                         l = [l]
108                 scanner += l
109
110         print "scanner:", scanner
111
112         res = { }
113
114         # merge all to-be-scanned paths, with priority to 
115         # with_subdirs.
116
117         paths_to_scan = set()
118
119         # first merge them all...
120         for s in scanner:
121                 paths_to_scan.update(set(s.paths_to_scan))
122
123         # ...then remove with_subdir=False when same path exists
124         # with with_subdirs=True
125         for p in set(paths_to_scan):
126                 if p.with_subdirs == True and ScanPath(path=p.path) in paths_to_scan:
127                         paths_to_scan.remove(ScanPath(path=p.path))
128
129         # convert to list
130         paths_to_scan = list(paths_to_scan)
131         
132         from Components.Harddisk import harddiskmanager 
133         blockdev = mountpoint.split('/')[2]
134         error, blacklisted, removable, is_cdrom, partitions = harddiskmanager.getBlockDevInfo(blockdev)
135
136         # now scan the paths
137         for p in paths_to_scan:
138                 path = os_path.join(mountpoint, p.path)
139
140                 for root, dirs, files in os_walk(path):
141                         for f in files:
142                                 path = os_path.join(root, f)
143                                 if is_cdrom and path.endswith(".wav") and path[-13:-6] == ("/track-"):
144                                         sfile = ScanFile(path,"audio/x-cda")
145                                 else:
146                                         sfile = ScanFile(path)
147                                 for s in scanner:
148                                         s.handleFile(res, sfile)
149
150                         # if we really don't want to scan subdirs, stop here.
151                         if not p.with_subdirs:
152                                 del dirs[:]
153
154         # res is a dict with scanner -> [ScanFiles]
155         return res
156
157 def openList(session, files):
158         if not isinstance(files, list):
159                 files = [ files ]
160
161         scanner = [ ]
162
163         for p in plugins.getPlugins(PluginDescriptor.WHERE_FILESCAN):
164                 l = p()
165                 if not isinstance(l, list):
166                         l = [l]
167                 scanner += l
168
169         print "scanner:", scanner
170
171         res = { }
172
173         for file in files:
174                 for s in scanner:
175                         s.handleFile(res, file)
176
177         choices = [ (r.description, r, res[r], session) for r in res ]
178         Len = len(choices)
179         if Len > 1:
180                 from Screens.ChoiceBox import ChoiceBox
181
182                 session.openWithCallback(
183                         execute,
184                         ChoiceBox,
185                         title = "The following viewers were found...",
186                         list = choices
187                 )
188                 return True
189         elif Len:
190                 execute(choices[0])
191                 return True
192
193         return False
194
195 def openFile(session, mimetype, file):
196         return openList(session, [ScanFile(file, mimetype)])