allow MediaPlayer AudioCD playback only for what appear to be AudioCDs
[enigma2.git] / lib / python / Components / Harddisk.py
1 from os import system, listdir, statvfs, popen, makedirs, readlink, stat, major, minor
2 from Tools.Directories import SCOPE_HDD, resolveFilename
3 from Tools.CList import CList
4 from SystemInfo import SystemInfo
5
6 def tryOpen(filename):
7         try:
8                 procFile = open(filename)
9         except IOError:
10                 return ""
11         return procFile
12
13 class Harddisk:
14         def __init__(self, device):
15                 self.device = device
16                 procfile = tryOpen("/sys/block/"+self.device+"/dev")
17                 tmp = procfile.readline().split(':')
18                 s_major = int(tmp[0])
19                 s_minor = int(tmp[1])
20                 for disc in listdir("/dev/discs"):
21                         path = readlink('/dev/discs/'+disc)
22                         devidex = '/dev'+path[2:]+'/'
23                         disc = devidex+'disc'
24                         ret = stat(disc).st_rdev
25                         if s_major == major(ret) and s_minor == minor(ret):
26                                 self.devidex = devidex
27                                 print "new Harddisk",  device, self.devidex
28                                 break
29
30         def __lt__(self, ob):
31                 return self.device < ob.device
32
33         def bus(self):
34                 ide_cf = self.device.find("hd") == 0 and self.devidex.find("host0") == -1 # 7025 specific
35                 internal = self.device.find("hd") == 0 and self.devidex
36                 if ide_cf:
37                         ret = "External (CF)"
38                 elif internal:
39                         ret = "Internal"
40                 else:
41                         ret = "External"
42                 return ret
43
44         def diskSize(self):
45                 procfile = tryOpen("/sys/block/"+self.device+"/size")
46                 if procfile == "":
47                         return 0
48                 line = procfile.readline()
49                 procfile.close()
50                 try:
51                         cap = int(line)
52                 except:
53                         return 0;
54                 return cap / 1000 * 512 / 1000
55
56         def capacity(self):
57                 cap = self.diskSize()
58                 if cap == 0:
59                         return ""
60                 return "%d.%03d GB" % (cap/1024, cap%1024)
61
62         def model(self):
63                 if self.device.find("hd") == 0:
64                         procfile = tryOpen("/proc/ide/"+self.device+"/model")
65                         if procfile == "":
66                                 return ""
67                         line = procfile.readline()
68                         procfile.close()
69                         return line.strip()
70                 elif self.device.find("sd") == 0:
71                         procfile = tryOpen("/sys/block/"+self.device+"/device/vendor")
72                         if procfile == "":
73                                 return ""
74                         vendor = procfile.readline().strip()
75                         procfile.close()
76                         procfile = tryOpen("/sys/block/"+self.device+"/device/model")
77                         model = procfile.readline().strip()
78                         return vendor+'('+model+')'
79                 else:
80                         assert False, "no hdX or sdX"
81
82         def free(self):
83                 procfile = tryOpen("/proc/mounts")
84                 
85                 if procfile == "":
86                         return -1
87
88                 free = -1
89                 while 1:
90                         line = procfile.readline()
91                         if line == "":
92                                 break
93                         if line.startswith(self.devidex):
94                                 parts = line.strip().split(" ")
95                                 try:
96                                         stat = statvfs(parts[1])
97                                 except OSError:
98                                         continue
99                                 free = stat.f_bfree/1000 * stat.f_bsize/1000
100                                 break
101                 procfile.close()
102                 return free
103
104         def numPartitions(self):
105                 try:
106                         idedir = listdir(self.devidex)
107                 except OSError:
108                         return -1
109                 numPart = -1
110                 for filename in idedir:
111                         if filename.startswith("disc"):
112                                 numPart += 1
113                         if filename.startswith("part"):
114                                 numPart += 1
115                 return numPart
116
117         def unmount(self):
118                 procfile = tryOpen("/proc/mounts")
119
120                 if procfile == "":
121                         return -1
122
123                 cmd = "/bin/umount"
124
125                 for line in procfile:
126                         if line.startswith(self.devidex):
127                                 parts = line.split()
128                                 cmd = ' '.join([cmd, parts[1]])
129
130                 procfile.close()
131
132                 res = system(cmd)
133                 return (res >> 8)
134
135         def createPartition(self):
136                 cmd = "/sbin/sfdisk -f " + self.devidex + "disc"
137                 sfdisk = popen(cmd, "w")
138                 sfdisk.write("0,\n;\n;\n;\ny\n")
139                 sfdisk.close()
140                 return 0
141
142         def mkfs(self):
143                 cmd = "/sbin/mkfs.ext3 "
144                 if self.diskSize() > 4 * 1024:
145                         cmd += "-T largefile "
146                 cmd += "-m0 " + self.devidex + "part1"
147                 res = system(cmd)
148                 return (res >> 8)
149
150         def mount(self):
151                 cmd = "/bin/mount -t ext3 " + self.devidex + "part1"
152                 res = system(cmd)
153                 return (res >> 8)
154
155         def createMovieFolder(self):
156                 try:
157                         makedirs(resolveFilename(SCOPE_HDD))
158                 except OSError:
159                         return -1
160                 return 0
161
162         def fsck(self):
163                 # We autocorrect any failures
164                 # TODO: we could check if the fs is actually ext3
165                 cmd = "/sbin/fsck.ext3 -f -p " + self.devidex + "part1"
166                 res = system(cmd)
167                 return (res >> 8)
168
169         errorList = [ _("Everything is fine"), _("Creating partition failed"), _("Mkfs failed"), _("Mount failed"), _("Create movie folder failed"), _("Fsck failed"), _("Please Reboot"), _("Filesystem contains uncorrectable errors"), _("Unmount failed")]
170
171         def initialize(self):
172                 self.unmount()
173
174                 if self.createPartition() != 0:
175                         return -1
176
177                 if self.mkfs() != 0:
178                         return -2
179
180                 if self.mount() != 0:
181                         return -3
182
183                 if self.createMovieFolder() != 0:
184                         return -4
185
186                 return 0
187
188         def check(self):
189                 self.unmount()
190
191                 res = self.fsck()
192                 if res & 2 == 2:
193                         return -6
194
195                 if res & 4 == 4:
196                         return -7
197
198                 if res != 0 and res != 1:
199                         # A sum containing 1 will also include a failure
200                         return -5
201
202                 if self.mount() != 0:
203                         return -3
204
205                 return 0
206         
207         def getDeviceDir(self):
208                 return self.devidex
209         
210         def getDeviceName(self):
211                 return self.getDeviceDir() + "disc"
212
213 class Partition:
214         def __init__(self, mountpoint, description = "", force_mounted = False):
215                 self.mountpoint = mountpoint
216                 self.description = description
217                 self.force_mounted = force_mounted
218                 self.is_hotplug = force_mounted # so far; this might change.
219
220         def stat(self):
221                 return statvfs(self.mountpoint)
222
223         def free(self):
224                 try:
225                         s = self.stat()
226                         return s.f_bavail * s.f_bsize
227                 except OSError:
228                         return None
229         
230         def total(self):
231                 try:
232                         s = self.stat()
233                         return s.f_blocks * s.f_bsize
234                 except OSError:
235                         return None
236
237         def mounted(self):
238                 # THANK YOU PYTHON FOR STRIPPING AWAY f_fsid.
239                 # TODO: can os.path.ismount be used?
240                 if self.force_mounted:
241                         return True
242                 procfile = tryOpen("/proc/mounts")
243                 for n in procfile.readlines():
244                         if n.split(' ')[1] == self.mountpoint:
245                                 return True
246                 return False
247
248 class HarddiskManager:
249         def __init__(self):
250                 self.hdd = [ ]
251                 
252                 self.partitions = [ ]
253                 
254                 self.on_partition_list_change = CList()
255                 
256                 self.enumerateBlockDevices()
257                 
258                 # currently, this is just an enumeration of what's possible,
259                 # this probably has to be changed to support automount stuff.
260                 # still, if stuff is mounted into the correct mountpoints by
261                 # external tools, everything is fine (until somebody inserts 
262                 # a second usb stick.)
263                 p = [
264                                         ("/media/hdd", _("Harddisk")), 
265                                         ("/media/card", _("Card")), 
266                                         ("/media/cf", _("Compact Flash")),
267                                         ("/media/mmc1", _("MMC Card")),
268                                         ("/media/net", _("Network Mount")),
269                                         ("/media/ram", _("Ram Disk")),
270                                         ("/media/usb", _("USB Stick")),
271                                         ("/", _("Internal Flash"))
272                                 ]
273                 
274                 for x in p:
275                         self.partitions.append(Partition(mountpoint = x[0], description = x[1]))
276
277         def getBlockDevInfo(self, blockdev):
278                 devpath = "/sys/block/" + blockdev
279                 error = False
280                 removable = False
281                 blacklisted = False
282                 is_cdrom = False
283                 partitions = []
284                 try:
285                         removable = bool(int(open(devpath + "/removable").read()))
286                         dev = int(open(devpath + "/dev").read().split(':')[0])
287                         if dev in [7, 31]: # loop, mtdblock
288                                 blacklisted = True
289                         if blockdev[0:2] == 'sr':
290                                 is_cdrom = True
291                         if blockdev[0:2] == 'hd':
292                                 try:
293                                         media = open("/proc/ide/%s/media" % blockdev).read()
294                                         if media.find("cdrom") != -1:
295                                                 is_cdrom = True
296                                 except IOError:
297                                         error = True
298                         # check for partitions
299                         if not is_cdrom:
300                                 for partition in listdir(devpath):
301                                         if partition[0:len(blockdev)] != blockdev:
302                                                 continue
303                                         partitions.append(partition)
304                 except IOError:
305                         error = True
306                 return error, blacklisted, removable, is_cdrom, partitions
307
308         def enumerateBlockDevices(self):
309                 print "enumerating block devices..."
310                 for blockdev in listdir("/sys/block"):
311                         error, blacklisted, removable, is_cdrom, partitions = self.getBlockDevInfo(blockdev)
312                         print "found block device '%s':" % blockdev, 
313                         if error:
314                                 print "error querying properties"
315                         elif blacklisted:
316                                 print "blacklisted"
317                         else:
318                                 print "ok, removable=%s, cdrom=%s, partitions=%s, device=%s" % (removable, is_cdrom, partitions, blockdev)
319                                 self.addHotplugPartition(blockdev, blockdev)
320                                 for part in partitions:
321                                         self.addHotplugPartition(part, part)
322
323         def getAutofsMountpoint(self, device):
324                 return "/autofs/%s/" % (device)
325
326         def addHotplugPartition(self, device, description):
327                 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True)
328                 self.partitions.append(p)
329                 self.on_partition_list_change("add", p)
330                 l = len(device)
331                 if l and device[l-1] not in ('0','1','2','3','4','5','6','7','8','9'):
332                         error, blacklisted, removable, is_cdrom, partitions = self.getBlockDevInfo(device)
333                         if not blacklisted and not removable and not is_cdrom:
334                                 self.hdd.append(Harddisk(device))
335                                 self.hdd.sort()
336                                 SystemInfo["Harddisc"] = len(self.hdd) > 0
337
338         def removeHotplugPartition(self, device):
339                 mountpoint = self.getAutofsMountpoint(device)
340                 for x in self.partitions[:]:
341                         if x.mountpoint == mountpoint:
342                                 self.partitions.remove(x)
343                                 self.on_partition_list_change("remove", x)
344                 l = len(device)
345                 if l and device[l-1] not in ('0','1','2','3','4','5','6','7','8','9'):
346                         idx = 0
347                         for hdd in self.hdd:
348                                 if hdd.device == device:
349                                         del self.hdd[idx]
350                                         break
351                         SystemInfo["Harddisc"] = len(self.hdd) > 0
352
353         def HDDCount(self):
354                 return len(self.hdd)
355
356         def HDDList(self):
357                 list = [ ]
358                 for hd in self.hdd:
359                         hdd = hd.model() + " - " + hd.bus()
360                         cap = hd.capacity()
361                         if cap != "":
362                                 hdd += " (" + cap + ")"
363                         list.append((hdd, hd))
364                 return list
365
366         def getMountedPartitions(self, onlyhotplug = False):
367                 return [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
368
369 harddiskmanager = HarddiskManager()