fix streaming playback (webradio)
[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                 self.cd = ""
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                         else:
305                                 self.cd = blockdev
306                 except IOError:
307                         error = True
308                 return error, blacklisted, removable, is_cdrom, partitions
309
310         def enumerateBlockDevices(self):
311                 print "enumerating block devices..."
312                 for blockdev in listdir("/sys/block"):
313                         error, blacklisted, removable, is_cdrom, partitions = self.getBlockDevInfo(blockdev)
314                         print "found block device '%s':" % blockdev, 
315                         if error:
316                                 print "error querying properties"
317                         elif blacklisted:
318                                 print "blacklisted"
319                         else:
320                                 print "ok, removable=%s, cdrom=%s, partitions=%s, device=%s" % (removable, is_cdrom, partitions, blockdev)
321                                 self.addHotplugPartition(blockdev, blockdev)
322                                 for part in partitions:
323                                         self.addHotplugPartition(part, part)
324
325         def getAutofsMountpoint(self, device):
326                 return "/autofs/%s/" % (device)
327
328         def addHotplugPartition(self, device, description):
329                 p = Partition(mountpoint = self.getAutofsMountpoint(device), description = description, force_mounted = True)
330                 self.partitions.append(p)
331                 self.on_partition_list_change("add", p)
332                 l = len(device)
333                 if l and device[l-1] not in ('0','1','2','3','4','5','6','7','8','9'):
334                         error, blacklisted, removable, is_cdrom, partitions = self.getBlockDevInfo(device)
335                         if not blacklisted and not removable and not is_cdrom:
336                                 self.hdd.append(Harddisk(device))
337                                 self.hdd.sort()
338                                 SystemInfo["Harddisc"] = len(self.hdd) > 0
339
340         def removeHotplugPartition(self, device):
341                 mountpoint = self.getAutofsMountpoint(device)
342                 for x in self.partitions[:]:
343                         if x.mountpoint == mountpoint:
344                                 self.partitions.remove(x)
345                                 self.on_partition_list_change("remove", x)
346                 l = len(device)
347                 if l and device[l-1] not in ('0','1','2','3','4','5','6','7','8','9'):
348                         idx = 0
349                         for hdd in self.hdd:
350                                 if hdd.device == device:
351                                         del self.hdd[idx]
352                                         break
353                         SystemInfo["Harddisc"] = len(self.hdd) > 0
354
355         def HDDCount(self):
356                 return len(self.hdd)
357
358         def HDDList(self):
359                 list = [ ]
360                 for hd in self.hdd:
361                         hdd = hd.model() + " - " + hd.bus()
362                         cap = hd.capacity()
363                         if cap != "":
364                                 hdd += " (" + cap + ")"
365                         list.append((hdd, hd))
366                 return list
367
368         def getCD(self):
369                 return self.cd
370
371         def getMountedPartitions(self, onlyhotplug = False):
372                 return [x for x in self.partitions if (x.is_hotplug or not onlyhotplug) and x.mounted()]
373
374 harddiskmanager = HarddiskManager()