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