コード例 #1
0
ファイル: media.py プロジェクト: vmware-archive/weasel
    def mount(self):
        if self.isMounted:
            return
        
        if not self.isoPath:
            # The disk itself is the install media.
            self._mountMediaAsTheDepot()
            return
        
        # The disk contains an ISO that is the media.
        if self.partPath and util.mount(self.partPath,
                                        MEDIA_PATH,
                                        fsTypeName=self.partFsName) != 0:
            raise Exception("could not mount partition containing ISO -- %s" %
                            self.partPath)
        
        if os.path.isabs(self.isoPath):
            absIsoPath = self.isoPath
        else:
            absIsoPath = os.path.join(MEDIA_PATH, self.isoPath)
        if util.mount(absIsoPath,
                      MEDIA_DEVICE_MOUNT_POINT,
                      loopMount=self.isoPath.endswith(".iso"),
                      # Be explicit with the mount type in case the file name
                      # has a colon in it, which might make mount think it is an
                      # nfs mount.  See bug 249366.
                      fsTypeName="iso9660") != 0:
            raise Exception("could not mount ISO -- %s" % self.isoPath)

        self.isMounted = True
コード例 #2
0
 def mountNew(self):
     "mount the new media"
     util.mount(CDROM_DEVICE_PATH, self.toMedia['mount'])
     # We've mounted something, lets save the path so we can eject it later.
     self.mountedPath = self.toMedia['mount']
     # After mounting, check that correct media is in the drive.
     self.setSubstepEnv({'next': self.checkMedia})
コード例 #3
0
    def test_modify_origin(self):
        testfile = "{}/testfile".format(self.mount)
        snapfile = "{}/testfile".format(self.snap_mount)

        with open(testfile, "w") as f:
            f.write("The quick brown fox")

        self.addCleanup(os.remove, testfile)
        os.sync()
        md5_orig = util.md5sum(testfile)

        self.assertEqual(
            elastio_snap.setup(self.minor, self.device, self.cow_full_path), 0)
        self.addCleanup(elastio_snap.destroy, self.minor)

        with open(testfile, "w") as f:
            f.write("jumps over the lazy dog")

        os.sync()

        util.mount(self.snap_device, self.snap_mount, opts="ro")
        self.addCleanup(util.unmount, self.snap_mount)

        md5_snap = util.md5sum(snapfile)
        self.assertEqual(md5_orig, md5_snap)
コード例 #4
0
ファイル: rom_drives.py プロジェクト: 1147279/SoftwareProject
 def mount(self):
     """
     Mount the media
     """
     _debug_('Mounting disc in drive %s' % self.drivename, 2)
     util.mount(self.mountdir, force=True)
     return
コード例 #5
0
ファイル: stage.py プロジェクト: jsbronder/inhibitor
    def install_sources(self):
        for src in self.sources:
            src.install(root=self.target_root)

        for m in ("proc", "sys", "dev", "devpts"):
            util.mount(self.aux_mounts[m], self.istate.mount_points)
        for m in ("resolv.conf", "hosts"):
            self.aux_sources[m].install(root=self.target_root)
コード例 #6
0
ファイル: test_setup.py プロジェクト: ihavec/dattobd_snap
    def test_setup_readonly_volume(self):
        util.mount(self.device, self.mount, opts="remount,ro")
        self.addCleanup(util.mount, self.device, self.mount, opts="remount,rw")

        self.assertEqual(
            dattobd.setup(self.minor, self.device, self.cow_full_path),
            errno.EINVAL)
        self.assertFalse(os.path.exists(self.snap_device))
        self.assertIsNone(dattobd.info(self.minor))
コード例 #7
0
ファイル: chroot.py プロジェクト: BackupTheBerlios/paella-svn
 def mount_backup(self, mtpnt, fstype='hostfs', export=None):
     self.check_guest()
     mounts = parse_proc_mounts()
     mounted = False
     for m in mounts:
         if m['mtpnt'] == mtpnt:
             mounted = True
     if fstype == 'nfs':
         export = self.cfg.get('umlmachines', 'nfs_backup_export')
     if not mounted:
         print mtpnt, fstype, export
         mount(mtpnt, fstype=fstype, export=export)
         print '%s mounted' % mtpnt
コード例 #8
0
 def mount_backup(self, mtpnt, fstype='hostfs', export=None):
     self.check_guest()
     mounts = parse_proc_mounts()
     mounted = False
     for m in mounts:
         if m['mtpnt'] == mtpnt:
             mounted = True
     if fstype == 'nfs':
         export = self.cfg.get('umlmachines', 'nfs_backup_export')
     if not mounted:
         print mtpnt, fstype, export
         mount(mtpnt, fstype=fstype, export=export)
         print '%s mounted' % mtpnt
コード例 #9
0
ファイル: devicetestcase.py プロジェクト: ihavec/dattobd_snap
    def setUpClass(cls):
        cls.backing_store = "/tmp/disk.img"
        cls.device = "/dev/loop0"
        cls.mount = "/tmp/dattobd"

        cls.kmod = kmod.Module("../src/dattobd.ko")
        cls.kmod.load(debug=1)

        util.dd("/dev/zero", cls.backing_store, 256, bs="1M")
        util.loop_create(cls.device, cls.backing_store)
        util.mkfs(cls.device)
        os.makedirs(cls.mount, exist_ok=True)
        util.mount(cls.device, cls.mount)
コード例 #10
0
ファイル: remote_files.py プロジェクト: vmware/weasel
    def mount(self, host, root, options="nolock"):
        self._checkNFSAvailable()
        self.unmount()

        nfsMountPoint = self.mountpoint
        nfsRoot = root
        
        isoName = None
        if root.endswith('.iso'):
            nfsRoot, isoName = os.path.split(root)
            nfsMountPoint = "%s-isosrc" % self.mountpoint
            if not os.path.exists(nfsMountPoint):
                os.makedirs(nfsMountPoint)
                
        command = '/sbin/mount.nfs'
        argv = [command, '%s:%s' % (host, nfsRoot), nfsMountPoint,
                '-v', '-o', options]
        rc = execWithLog(command, argv)
        
        if rc == 0:
            self.mountedServer = host
            self.mountedRoot = root
            if isoName:
                if util.mount(os.path.join(nfsMountPoint, isoName),
                              self.mountpoint,
                              loopMount=True,
                              fsTypeName='iso9660') != 0:
                    self.unmount()
                    return False
            return True
        else:
            return False
コード例 #11
0
    def mount(self, host, root, options="nolock"):
        self._checkNFSAvailable()
        self.unmount()

        nfsMountPoint = self.mountpoint
        nfsRoot = root

        isoName = None
        if root.endswith('.iso'):
            nfsRoot, isoName = os.path.split(root)
            nfsMountPoint = "%s-isosrc" % self.mountpoint
            if not os.path.exists(nfsMountPoint):
                os.makedirs(nfsMountPoint)

        command = '/sbin/mount.nfs'
        argv = [
            command,
            '%s:%s' % (host, nfsRoot), nfsMountPoint, '-v', '-o', options
        ]
        rc = execWithLog(command, argv)

        if rc == 0:
            self.mountedServer = host
            self.mountedRoot = root
            if isoName:
                if util.mount(os.path.join(nfsMountPoint, isoName),
                              self.mountpoint,
                              loopMount=True,
                              fsTypeName='iso9660') != 0:
                    self.unmount()
                    return False
            return True
        else:
            return False
コード例 #12
0
ファイル: usbmedia.py プロジェクト: vmware/weasel
def _tryDevice(disk, part):
    devicePath = part.consoleDevicePath
    
    log.info("looking for installation data on %s" % devicePath)

    # Either the USB storage is the media itself or it might contain an ISO file
    # that is the installation media.
    usbDesc = media.MediaDescriptor(disk.name, devicePath, part.getFsTypeName())
    if usbDesc.probeForPackages():
        log.info("  found installation media...")
        return [usbDesc]
    
    # Be explicit about fsTypeName since long file names work if we mount it as
    # "vfat", but not when the auto-detection thinks it's "msdos".
    if util.mount(devicePath,
                  USB_MEDIA_PATH,
                  fsTypeName=part.getFsTypeName()) != 0:
        return []

    retval = []
    for iso in glob.glob(os.path.join(USB_MEDIA_PATH, "*.iso")):
        isoDesc = media.MediaDescriptor(
            disk.name,
            devicePath, part.getFsTypeName(),
            os.path.basename(iso))
        if isoDesc.probeForPackages():
            log.info("  found iso, %s, with installation media..." % iso)
            retval.append(isoDesc)

    util.umount(USB_MEDIA_PATH)
    
    return retval
コード例 #13
0
ファイル: usbmedia.py プロジェクト: vmware-archive/weasel
def _tryDevice(disk, part):
    devicePath = part.consoleDevicePath

    log.info("looking for installation data on %s" % devicePath)

    # Either the USB storage is the media itself or it might contain an ISO file
    # that is the installation media.
    usbDesc = media.MediaDescriptor(disk.name, devicePath,
                                    part.getFsTypeName())
    if usbDesc.probeForPackages():
        log.info("  found installation media...")
        return [usbDesc]

    # Be explicit about fsTypeName since long file names work if we mount it as
    # "vfat", but not when the auto-detection thinks it's "msdos".
    if util.mount(devicePath, USB_MEDIA_PATH,
                  fsTypeName=part.getFsTypeName()) != 0:
        return []

    retval = []
    for iso in glob.glob(os.path.join(USB_MEDIA_PATH, "*.iso")):
        isoDesc = media.MediaDescriptor(disk.name, devicePath,
                                        part.getFsTypeName(),
                                        os.path.basename(iso))
        if isoDesc.probeForPackages():
            log.info("  found iso, %s, with installation media..." % iso)
            retval.append(isoDesc)

    util.umount(USB_MEDIA_PATH)

    return retval
コード例 #14
0
ファイル: media.py プロジェクト: vmware-archive/weasel
 def _mountMediaAsTheDepot(self):
     if util.mount(self.partPath,
                   MEDIA_DEVICE_MOUNT_POINT,
                   loopMount=self.partPath.endswith(".iso"),
                   fsTypeName=self.partFsName) != 0:
         raise Exception("Could not mount media device -- %s" %
                         self.partPath)
     self.isMounted = True
コード例 #15
0
def _usbOption(match):
    '''Handle the "ks=usb" and "ks=usb:<path>" option.'''

    try:
        ksFile = match.group(1)
    except IndexError:
        ksFile = "ks.cfg"

    firstTime = True
    while True:
        if not firstTime:
            # XXX Maybe we should just stop retrying after awhile?
            log.info("Insert a USB storage device that contains '%s' "
                     "file to perform a scripted install..." % ksFile)
            util.rawInputCountdown("\rrescanning in %2d second(s), "
                                   "press <enter> to rescan immediately", 10)
        firstTime = False

        diskSet = devices.DiskSet(forceReprobe=True)

        usbDisks = [disk for disk in diskSet.values()
                    if disk.driverName == devices.DiskDev.DRIVER_USB_STORAGE]

        if not usbDisks:
            log.info("") # XXX just for spacing
            log.warn("No USB storage found.")
            continue

        kickstartPath = os.path.join(USB_MOUNT_PATH, ksFile.lstrip('/'))

        if not os.path.exists(USB_MOUNT_PATH):
            os.makedirs(USB_MOUNT_PATH)

        for disk in usbDisks:
            for part in disk.partitions:
                if part.partitionId == -1:
                    continue

                if (part.getFsTypeName() not in ("ext2", "ext3", "vfat")):
                    # Don't try mounting partitions with filesystems that aren't
                    # likely to be on a usb key.
                    continue

                if util.mount(part.consoleDevicePath,
                              USB_MOUNT_PATH,
                              fsTypeName=part.getFsTypeName()):
                    log.warn("Unable to mount '%s'" % part.consoleDevicePath)
                    continue

                if os.path.exists(kickstartPath):
                    userchoices.addDriveUse(disk.name, 'kickstart')
                    return [('-s', kickstartPath)]

                if util.umount(USB_MOUNT_PATH):
                    failWithLog("Unable to umount '%s'" % USB_MOUNT_PATH)

        log.info("")
        log.warn("%s was not found on any attached USB storage." % ksFile)
コード例 #16
0
 def start(self):
     if self.start_count == 0:
         self.location = tempfile.mkdtemp(prefix="media-", dir="/tmp")
         # try each filesystem in turn:
         success = False
         for fs in self.mount_types:
             try:
                 util.mount(self.mount_source,
                            self.location,
                            options=self.mount_options,
                            fstype=fs)
             except util.MountFailureException, e:
                 continue
             else:
                 success = True
                 break
         if not success:
             os.rmdir(self.location)
             raise util.MountFailureException
コード例 #17
0
ファイル: source.py プロジェクト: jsbronder/inhibitor
    def install(self, root):
        src = self.src
        if self.cachedir:
            src = self.cachedir
        full_dest = root.pjoin(self.dest)

        if not self.keep and self.mountable:
            util.dbg("Bind mounting %s at %s" % (src, full_dest))
            self.mount = util.Mount(src, self.dest, root)
            util.mount(self.mount, self.istate.mount_points)
        else:
            util.path_sync(
                src,
                full_dest,
                root = root,
                ignore = self.ignore,
                file_copy_callback = self.file_copy_callback
            )
        return
コード例 #18
0
ファイル: fsset.py プロジェクト: vmware/weasel
    def mount(self, device, mountPoint, readOnly=False, bindMount=False,
              loopMount=False):

        #if not self.isMountable():
        #    print "Couldn't mount %s" % (device)
        #    return
        
        status = util.mount(device, mountPoint, readOnly, bindMount, loopMount)
        if status:
            raise InstallationError("Could not mount '%s' onto '%s'." % (
                    device, mountPoint))
コード例 #19
0
def hostActionMountFileSystems(context):
    # XXX - we only use one virtual device for now
    virtualDevs = userchoices.getVirtualDevices()
    assert len(virtualDevs) == 1 or len(virtualDevs) == 0

    requests = allUserPartitionRequests()
    requests.sort(sortByMountPoint=True)

    for request in requests:
        # skip vmfs partitions since they can't be mounted
        if not request.mountPoint:
            continue

        mountPoint = os.path.normpath(consts.HOST_ROOT + request.mountPoint)

        if not os.path.exists(mountPoint):
            os.makedirs(mountPoint)

        log.debug("Mounting %s -> %s" % \
                  (request.consoleDevicePath, mountPoint))
        request.fsType.mount(request.consoleDevicePath, mountPoint)

        if request.clearContents:
            # Clear out the contents of the drive.  Removing the files might be
            # preferable to a reformat since we preserve the UUID.
            for name in os.listdir(mountPoint):
                path = os.path.join(mountPoint, name)
                if os.path.isdir(path):
                    shutil.rmtree(path)
                else:
                    os.remove(path)

    if userchoices.getUpgrade():
        upgradeMounts = [(consts.ESX3_INSTALLATION,
                          userchoices.getRootUUID()['uuid'])]

        if userchoices.isCombinedBootAndRootForUpgrade():
            log.debug("Linking boot")
            # No /boot partition, need to create a link to the old one.
            os.symlink(
                os.path.join(consts.ESX3_INSTALLATION.lstrip('/'), "boot"),
                os.path.join(consts.HOST_ROOT, "boot"))
        else:
            upgradeMounts.append(("/boot", userchoices.getBootUUID()['uuid']))

        for partMountPoint, uuid in upgradeMounts:
            mountPoint = os.path.normpath(consts.HOST_ROOT + partMountPoint)
            if not os.path.exists(mountPoint):
                os.makedirs(mountPoint)

            log.debug("Mounting %s -> %s" % (uuid, mountPoint))
            rc = util.mount(uuid, mountPoint, isUUID=True)
            assert rc == 0  # TODO: handle errors
コード例 #20
0
    def setUpClass(cls):
        cls.minor = randint(0, 23)
        r = randint(0, 999)
        cls.mount = "/tmp/elastio-snap_{0:03d}".format(r)

        cls.kmod = kmod.Module("../src/elastio-snap.ko")
        cls.kmod.load(debug=1)
        if os.getenv('TEST_DEVICE'):
            cls.device = os.getenv('TEST_DEVICE')
            dev_size = int(
                subprocess.check_output("blockdev --getsize64 %s" % cls.device,
                                        shell=True,
                                        text=True)) // 1024**2
            util.dd("/dev/zero", cls.device, dev_size, bs="1M")
        else:
            cls.backing_store = "/tmp/disk_{0:03d}.img".format(r)
            util.dd("/dev/zero", cls.backing_store, 256, bs="1M")
            cls.device = util.loop_create(cls.backing_store)

        util.mkfs(cls.device)
        os.makedirs(cls.mount, exist_ok=True)
        util.mount(cls.device, cls.mount)
コード例 #21
0
    def check_password_and_build(self, arg=None, menuw=None):
        """
        password checker
        """
        if not self.menuw:
            self.menuw = menuw

        # are we on a ROM_DRIVE and have to mount it first?
        for media in config.REMOVABLE_MEDIA:
            if self.dir.find(media.mountdir) == 0:
                util.mount(self.dir)
                self.media = media

        if vfs.isfile(self.dir + '/.password'):
            print 'password protected dir'
            self.arg = arg
            self.menuw = menuw
            pb = InputBox(text=_('Enter Password'),
                          handler=self.pass_cmp_cb,
                          type='password')
            pb.show()
        else:
            self.build(arg=arg, menuw=menuw)
コード例 #22
0
ファイル: fsset.py プロジェクト: vmware-archive/weasel
    def mount(self,
              device,
              mountPoint,
              readOnly=False,
              bindMount=False,
              loopMount=False):

        #if not self.isMountable():
        #    print "Couldn't mount %s" % (device)
        #    return

        status = util.mount(device, mountPoint, readOnly, bindMount, loopMount)
        if status:
            raise InstallationError("Could not mount '%s' onto '%s'." %
                                    (device, mountPoint))
コード例 #23
0
    def scanForDriverDisk(self):
        '''Mount the CD-ROM and check to see if it is a driver CD.'''

        self.foundDriverList = []
        driverDict = {}

        xmlFileName = os.path.join(MEDIA_DEVICE_MOUNT_POINT, "drivers.xml")

        util.umount(MEDIA_DEVICE_MOUNT_POINT)
        cdutil.ejectCdrom()
        window = MessageWindow(None, "Insert CD", INSERT_DRIVER_CD_STRING,
                               type="okcancel")

        if window.affirmativeResponse:
            util.mount(CDROM_DEVICE_PATH, MEDIA_DEVICE_MOUNT_POINT)
            if not os.path.exists(xmlFileName):
                raise InvalidDriverCDException(INVALID_DRIVER_CD_STRING)
        else:
            return

        try:
            driverXml = customdrivers.CustomDriversXML(xmlFileName)
        except customdrivers.InvalidVersion, msg:
            raise InvalidDriverCDException(INVALID_VERSION_STRING)
コード例 #24
0
def _ksFileCdromOption(match):
    path = match.group(1)

    if not os.path.exists(CDROM_MOUNT_PATH):
        os.makedirs(CDROM_MOUNT_PATH)

    for cdPath in cdutil.cdromDevicePaths():
        if util.mount(cdPath, CDROM_MOUNT_PATH):
            log.warn("cannot mount cd-rom in %s" % cdPath)
            continue

        ksPath = os.path.join(CDROM_MOUNT_PATH, path.lstrip('/'))
        if os.path.exists(ksPath):
            return [('-s', ksPath)]

        util.umount(CDROM_MOUNT_PATH)

    failWithLog("cannot find kickstart file on cd-rom with path -- %s" % path)
コード例 #25
0
def _ksFileUUIDOption(match):
    uuid = match.group(1)
    path = match.group(2)

    diskSet = devices.DiskSet(forceReprobe=True)
    diskPartTuple = diskSet.findFirstPartitionMatching(uuid=uuid)
    if diskPartTuple:
        disk, _part = diskPartTuple
        userchoices.addDriveUse(disk.name, 'kickstart')
        
    mountPath = os.path.join(UUID_MOUNT_PATH, uuid)
    if not os.path.exists(mountPath):
        os.makedirs(mountPath)
        if util.mount(uuid, mountPath, isUUID=True):
            os.rmdir(mountPath)
            failWithLog("error: cannot mount partition with UUID: %s\n" % uuid)

    ksPath = os.path.join(mountPath, path[1:])
    return [('-s', ksPath)]
コード例 #26
0
ファイル: jail.py プロジェクト: wagnerrp/pyjail
    def _mount(self):
        if self.devfs:
            Devfs.loadrules()
            if self.devfs_rules:
                Devfs.loadrules(self.devfs_rules)
            Devfs.mount(self.rootdir+'/dev', self.devfs)

        if self.procfs:
            mount('proc', self.rootdir+'/proc', 'procfs')

        if self.ports:
            mount('/usr/ports', self.rootdir+'/usr/ports', 'nullfs')
            mount('/usr/ports/distfiles', self.rootdir+'/usr/ports/distfiles', 'nullfs')

        if self.mount:
            # check if exists
            call(['/sbin/mount','-a','-F',self.mount])
コード例 #27
0
ファイル: rom_drives.py プロジェクト: spartrekus/freevo1
class Identify_Thread(threading.Thread):
    """
    Thread to watch the rom drives for changes
    """
    def identify(self, media, force_rebuild=False):
        """
        Try to find out as much as possible about the disc in the rom drive: title,
        image, play options, ...
        """
        cds = media.get_drive_status()
        #media.log_drive_status(cds)

        # Same as last time? If so we're done
        if media.drive_status == cds:
            #_debug_('status not changed for drive %r' % (media.devicename))
            return

        logger.debug('drive_status changed %s -> %s', media.drive_status, cds)
        media.drive_status = cds
        media.id = ''
        media.label = ''
        media.type = 'empty_cdrom'
        media.item = None
        media.videoitem = None
        media.cached = False

        # Is there a disc information?
        if media.drive_status == CDS_NO_INFO:
            logger.debug('cannot get the drive status for drive %r',
                         media.devicename)
            return

        # Is there a disc present?
        if media.drive_status != CDS_DISC_OK:
            logger.debug('disc not ready for drive %r', media.devicename)
            return

        # try to set the speed
        try:
            fd = os.open(media.devicename, os.O_RDONLY | os.O_NONBLOCK)
            try:
                if media.can_select_speed and config.ROM_SPEED:
                    try:
                        ioctl(fd, CDROM_SELECT_SPEED, config.ROM_SPEED)
                    except Exception, e:
                        logger.debug('setting rom speed for %r failed: %s',
                                     media.devicename, e)

            finally:
                #_debug_('closing %r drive %r' % (fd, media.devicename))
                try:
                    os.close(fd)
                except Exception, e:
                    logger.debug('closing %r failed: %s', media.devicename, e)
        except Exception, e:
            logger.debug('opening %r failed: %s', media.devicename, e)
            return

        # if there is a disc, the tray can't be open
        media.tray_open = False
        disc_info = util.mediainfo.disc_info(media, force_rebuild)
        if not disc_info:
            logger.debug('no disc information for drive %r', media.devicename)
            return

        info = disc_info.discinfo
        if not info:
            logger.debug('no info for drive %r', media.devicename)
            return

        if info['mime'] == 'audio/cd':
            media.id = disc_id = info['id']
            media.item = AudioDiskItem(disc_id,
                                       parent=None,
                                       devicename=media.devicename,
                                       display_type='audio')
            media.type = 'audio'
            media.item.media = media
            if info['title']:
                media.item.name = info['title']
            media.item.info = disc_info
            logger.debug('playing audio in drive %r', media.devicename)
            return

        image = title = movie_info = more_info = fxd_file = None

        media.id = info['id']
        media.label = info['label']
        media.type = 'cdrom'

        label = info['label']

        # is the id in the database?
        if media.id in video.fxd_database['id']:
            movie_info = video.fxd_database['id'][media.id]
            if movie_info:
                title = movie_info.name
        else:  # no? Maybe we can find a label regexp match
            for (re_label, movie_info_t) in video.fxd_database['label']:
                if re_label.match(media.label):
                    movie_info = movie_info_t
                    if movie_info_t.name:
                        title = movie_info.name
                        m = re_label.match(media.label).groups()
                        re_count = 1

                        # found, now change the title with the regexp. E.g.:
                        # label is "bla_2", the label regexp "bla_[0-9]" and the title
                        # is "Something \1", the \1 will be replaced with the first item
                        # in the regexp group, here 2. The title is now "Something 2"
                        for g in m:
                            title = string.replace(title, '\\%s' % re_count, g)
                            re_count += 1
                        break

        if movie_info:
            image = movie_info.image

        # DVD/VCD/SVCD:
        if info['mime'] in ('video/vcd', 'video/dvd'):
            if not title:
                title = media.label.replace('_', ' ').lstrip().rstrip()
                title = '%s [%s]' % (info['mime'][6:].upper(), title)

            if movie_info:
                media.item = copy.copy(movie_info)
            else:
                media.item = VideoItem('', None)
                media.item.image = util.getimage(
                    os.path.join(config.OVERLAY_DIR, 'disc-set', media.id))
            variables = media.item.info.variables
            media.item.info = disc_info
            media.item.info.set_variables(variables)

            media.item.name = title
            media.item.url = info['mime'][6:] + '://'
            media.item.media = media

            media.type = info['mime'][6:]

            media.item.info.mmdata = info
            logger.debug('playing video in drive %r', media.devicename)
            return

        # Disc is data of some sort. Mount it to get the file info
        util.mount(media.mountdir, force=True)
        try:
            if os.path.isdir(os.path.join(media.mountdir, 'VIDEO_TS')) or \
                   os.path.isdir(os.path.join(media.mountdir, 'video_ts')):
                if force_rebuild:
                    logger.debug('Double check without success')
                else:
                    logger.debug('Undetected DVD, checking again')
                    media.drive_status = CDS_NO_DISC
                    return self.identify(media, True)

            # Check for movies/audio/images on the disc
            num_video = disc_info['disc_num_video']
            num_audio = disc_info['disc_num_audio']
            num_image = disc_info['disc_num_image']

            video_files = util.match_files(media.mountdir, config.VIDEO_SUFFIX)

            logger.debug('video_files=%r', video_files)

            media.item = DirItem(media.mountdir, None, create_metainfo=False)
            media.item.info = disc_info
        finally:
            util.umount(media.mountdir)

        # if there is a video file on the root dir of the disc, we guess
        # it's a video disc. There may also be audio files and images, but
        # they only belong to the movie
        if video_files:
            media.type = 'video'

            # try to find out if it is a series cd
            if not title:
                show_name = ""
                the_same = 1
                volumes = ''
                start_ep = 0
                end_ep = 0

                video_files.sort(lambda l, o: cmp(l.upper(), o.upper()))

                for movie in video_files:
                    if config.VIDEO_SHOW_REGEXP_MATCH(movie):
                        show = config.VIDEO_SHOW_REGEXP_SPLIT(
                            os.path.basename(movie))

                        if show_name and show_name != show[0]:
                            the_same = 0
                        if not show_name:
                            show_name = show[0]
                        if volumes:
                            volumes += ', '
                        current_ep = int(show[1]) * 100 + int(show[2])
                        if end_ep and current_ep == end_ep + 1:
                            end_ep = current_ep
                        elif not end_ep:
                            end_ep = current_ep
                        else:
                            end_ep = -1
                        if not start_ep:
                            start_ep = end_ep
                        volumes += show[1] + "x" + show[2]

                if show_name and the_same and config.VIDEO_SHOW_DATA_DIR:
                    if end_ep > 0:
                        volumes = '%dx%02d - %dx%02d' % (
                            start_ep / 100, start_ep % 100, end_ep / 100,
                            end_ep % 100)
                    k = config.VIDEO_SHOW_DATA_DIR + show_name
                    if os.path.isfile((k + ".png").lower()):
                        image = (k + ".png").lower()
                    elif os.path.isfile((k + ".jpg").lower()):
                        image = (k + ".jpg").lower()
                    title = show_name + ' (' + volumes + ')'
                    if video.tv_show_information.has_key(show_name.lower()):
                        tvinfo = video.tv_show_information[show_name.lower()]
                        more_info = tvinfo[1]
                        if not image:
                            image = tvinfo[0]
                        if not fxd_file:
                            fxd_file = tvinfo[3]

                elif (not show_name) and len(video_files) == 1:
                    movie = video_files[0]
                    title = os.path.splitext(os.path.basename(movie))[0]

            # nothing found, give up: return the label
            if not title:
                title = label

        # If there are no videos and only audio files (and maybe images)
        # it is an audio disc (autostart will auto play everything)
        elif not num_video and num_audio:
            media.type = 'audio'
            title = '%s [%s]' % (media.drivename, label)

        # Only images? OK than, make it an image disc
        elif not num_video and not num_audio and num_image:
            media.type = 'image'
            title = '%s [%s]' % (media.drivename, label)

        # Mixed media?
        elif num_video or num_audio or num_image:
            media.type = None
            title = '%s [%s]' % (media.drivename, label)

        # Strange, no useable files
        else:
            media.type = None
            title = '%s [%s]' % (media.drivename, label)

        # set the info we have now
        if title:
            media.item.name = title

        if image:
            media.item.image = image

        if more_info:
            media.item.info.set_variables(more_info)

        if fxd_file and not media.item.fxd_file:
            media.item.set_fxd_file(fxd_file)

        # One video in the root dir. This sounds like a disc with one
        # movie on it. Save the information about it and autostart will
        # play this.
        if len(video_files) == 1 and media.item['num_dir_items'] == 0:
            util.mount(media.mountdir)
            try:
                if movie_info:
                    media.videoitem = copy.deepcopy(movie_info)
                else:
                    media.videoitem = VideoItem(video_files[0], None)
            finally:
                util.umount(media.mountdir)
            media.videoitem.media = media
            media.videoitem.media_id = media.id

            # set the info we have
            if title:
                media.videoitem.name = title

            if image:
                media.videoitem.image = image

            if more_info:
                media.videoitem.set_variables(more_info)

            if fxd_file:
                media.videoitem.fxd_file = fxd_file

        media.item.media = media
コード例 #28
0
ファイル: rom_drives.py プロジェクト: spartrekus/freevo1
 def mount(self):
     """ Mount the media """
     logger.log(9, 'Mounting disc in drive %s', self.drivename)
     if self.mount_ref_count == 0:
         util.mount(self.mountdir, force=True)
     self.mount_ref_count += 1
コード例 #29
0
ファイル: rom_drives.py プロジェクト: adozenlines/freevo1
 def mount(self):
     """ Mount the media """
     logger.log( 9, 'Mounting disc in drive %s', self.drivename)
     if self.mount_ref_count == 0:
         util.mount(self.mountdir, force=True)
     self.mount_ref_count += 1
コード例 #30
0
ファイル: videoitem.py プロジェクト: spartrekus/freevo1
    def __play(self, arg=None, menuw=None):
        # execute commands if defined
        if config.VIDEO_PRE_PLAY:
            os.system(config.VIDEO_PRE_PLAY)

        if self.parent:
            self.parent.current_item = self

        if not self.menuw:
            self.menuw = menuw

        # if we have variants, play the first one as default
        if self.variants:
            self.variants[0].play(arg, menuw)
            return

        # if we have subitems (a movie with more than one file),
        # we start playing the first that is physically available
        if self.subitems:
            self.error_in_subitem = 0
            self.last_error_msg = ''
            self.current_subitem = None

            result = self.set_next_available_subitem()
            if self.current_subitem:  # 'result' is always 1 in this case
                # The media is available now for playing
                # Pass along the options, without loosing the subitem's own
                # options
                if self.current_subitem.mplayer_options:
                    if self.mplayer_options:
                        # With this set the player options are incorrect when there is more than 1 item
                        #self.current_subitem.mplayer_options += ' ' + self.mplayer_options
                        pass
                else:
                    self.current_subitem.mplayer_options = self.mplayer_options
                # When playing a subitem, the menu must be hidden. If it is not,
                # the playing will stop after the first subitem, since the
                # PLAY_END/USER_END event is not forwarded to the parent
                # videoitem.
                # And besides, we don't need the menu between two subitems.
                self.menuw.hide()
                self.last_error_msg = self.current_subitem.play(
                    arg, self.menuw)
                if self.last_error_msg:
                    self.error_in_subitem = 1
                    # Go to the next playable subitem, using the loop in
                    # eventhandler()
                    self.eventhandler(PLAY_END)

            elif not result:
                # No media at all was found: error
                ConfirmBox(text=(_(
                    'No media found for "%(name)s".\nPlease insert the media "%(media_id)s".'
                )) % ({
                    'name': self.name,
                    'media_id': self.media_id
                }),
                           handler=self.play).show()
            return

        # normal plackback of one file
        if self.url.startswith('file://'):
            file = self.filename
            if self.media_id:
                mountdir, file = util.resolve_media_mountdir(
                    self.media_id, file)
                if mountdir:
                    util.mount(mountdir)
                else:
                    self.menuw.show()
                    ConfirmBox(text=(_('No media found for "%(file)s".\nPlease insert the media "%(media_id)s".')) % \
                        ({'file': file, 'media_id': self.media_id}), handler=self.play).show()
                    return

            elif self.media:
                util.mount(os.path.dirname(self.filename))

        # dvd and vcd
        elif self.mode in ('dvd',
                           'vcd') and not self.filename and not self.media:
            media = util.check_media(self.media_id)
            if media:
                self.media = media
            else:
                self.menuw.show()
                ConfirmBox(text=(_(
                    'No media found for "%(media_id)s".\nPlease insert the media "%(url)s".'
                )) % ({
                    'media_id': self.media_id,
                    'url': self.url
                }),
                           handler=self.play).show()
                return

        mplayer_options = self.mplayer_options.split(' ')
        if not mplayer_options:
            mplayer_options = []

        if arg:
            mplayer_options += arg.split(' ')

        if self.menuw.visible:
            self.menuw.hide()

        self.plugin_eventhandler(PLAY, menuw)

        self.menuw.delete_submenu()

        error = self.player.play(mplayer_options, self)

        # Clear any resume settings
        self['resume'] = ''

        if error:
            # If we are a subitem we don't show any error message before
            # having tried all the subitems
            if hasattr(self.parent, 'subitems') and self.parent.subitems:
                return error
            else:
                AlertBox(text=error, handler=self.error_handler).show()
コード例 #31
0
ファイル: restore.py プロジェクト: xcp-ng/host-installer
def restoreFromBackup(backup, progress=lambda x: ()):
    """ Restore files from backup_partition to the root partition on disk.
    Call progress with a value between 0 and 100.  Re-install bootloader.  Fails if
    backup is not same version as the CD in use."""

    label = None
    bootlabel = None
    disk = backup.root_disk
    tool = PartitionTool(disk)
    _, _, _, storage, _ = diskutil.probeDisk(disk)
    create_sr_part = storage[0] is not None
    _, boot_partnum, primary_partnum, backup_partnum, logs_partnum, swap_partnum, _ = backend.inspectTargetDisk(
        disk, None, [], constants.PRESERVE_IF_UTILITY, create_sr_part, True)

    backup_fs = util.TempMount(backup.partition, 'backup-', options=['ro'])
    inventory = util.readKeyValueFile(os.path.join(backup_fs.mount_point,
                                                   constants.INVENTORY_FILE),
                                      strip_quotes=True)
    backup_partition_layout = inventory['PARTITION_LAYOUT'].split(',')
    backup_fs.unmount()

    logger.log("BACKUP DISK PARTITION LAYOUT: %s" % backup_partition_layout)

    backup_partition = backup.partition

    assert backup_partition.startswith('/dev/')
    assert disk.startswith('/dev/')

    restore_partition = partitionDevice(disk, primary_partnum)
    logger.log("Restoring to partition %s." % restore_partition)

    boot_part = tool.getPartition(boot_partnum)
    boot_device = partitionDevice(disk, boot_partnum) if boot_part else None
    efi_boot = boot_part and boot_part['id'] == GPTPartitionTool.ID_EFI_BOOT

    # determine current location of bootloader
    current_location = 'unknown'
    try:
        root_fs = util.TempMount(restore_partition,
                                 'root-',
                                 options=['ro'],
                                 boot_device=boot_device)
        try:
            boot_config = bootloader.Bootloader.loadExisting(
                root_fs.mount_point)
            current_location = boot_config.location
            logger.log("Bootloader currently in %s" % current_location)
        finally:
            root_fs.unmount()
    except:
        pass

    # mount the backup fs
    backup_fs = util.TempMount(backup_partition,
                               'restore-backup-',
                               options=['ro'])
    try:
        # extract the bootloader config
        boot_config = bootloader.Bootloader.loadExisting(backup_fs.mount_point)
        if boot_config.src_fmt == 'grub':
            raise RuntimeError("Backup uses grub bootloader which is no longer supported - " + \
                "to restore please use a version of the installer that matches the backup partition")

        # format the restore partition(s):
        try:
            util.mkfs(constants.rootfs_type, restore_partition)
        except Exception as e:
            raise RuntimeError("Failed to create root filesystem: %s" % e)

        if efi_boot:
            try:
                util.mkfs('vfat', boot_device)
            except Exception as e:
                raise RuntimeError("Failed to create boot filesystem: %s" % e)

        # mount restore partition:
        dest_fs = util.TempMount(restore_partition, 'restore-dest-')
        efi_mounted = False
        try:
            if efi_boot:
                esp = os.path.join(dest_fs.mount_point, 'boot', 'efi')
                os.makedirs(esp)
                util.mount(boot_device, esp)
                efi_mounted = True

            # copy files from the backup partition to the restore partition:
            objs = filter(
                lambda x: x not in
                ['lost+found', '.xen-backup-partition', '.xen-gpt.bin'],
                os.listdir(backup_fs.mount_point))
            for i in range(len(objs)):
                obj = objs[i]
                logger.log("Restoring subtree %s..." % obj)
                progress((i * 100) / len(objs))

                # Use 'cp' here because Python's copying tools are useless and
                # get stuck in an infinite loop when copying e.g. /dev/null.
                if util.runCmd2([
                        'cp', '-a',
                        os.path.join(backup_fs.mount_point, obj),
                        dest_fs.mount_point
                ]) != 0:
                    raise RuntimeError("Failed to restore %s directory" % obj)

            logger.log(
                "Data restoration complete.  About to re-install bootloader.")

            location = boot_config.location
            m = re.search(r'root=LABEL=(\S+)',
                          boot_config.menu[boot_config.default].kernel_args)
            if m:
                label = m.group(1)
            if location == constants.BOOT_LOCATION_PARTITION and current_location == constants.BOOT_LOCATION_MBR:
                # if bootloader in the MBR it's probably not safe to restore with it
                # on the partition
                logger.log(
                    "Bootloader is currently installed to MBR, restoring to MBR instead of partition"
                )
                location = constants.BOOT_LOCATION_MBR

            with open(os.path.join(backup_fs.mount_point, 'etc', 'fstab'),
                      'r') as fstab:
                for line in fstab:
                    m = re.match(r'LABEL=(\S+)\s+/boot/efi\s', line)
                    if m:
                        bootlabel = m.group(1)

            mounts = {
                'root': dest_fs.mount_point,
                'boot': os.path.join(dest_fs.mount_point, 'boot')
            }

            # prepare extra mounts for installing bootloader:
            util.bindMount("/dev", "%s/dev" % dest_fs.mount_point)
            util.bindMount("/sys", "%s/sys" % dest_fs.mount_point)
            util.bindMount("/proc", "%s/proc" % dest_fs.mount_point)
            if boot_config.src_fmt == 'grub2':
                if efi_boot:
                    branding = util.readKeyValueFile(
                        os.path.join(backup_fs.mount_point,
                                     constants.INVENTORY_FILE))
                    branding['product-brand'] = branding['PRODUCT_BRAND']
                    backend.setEfiBootEntry(mounts, disk, boot_partnum,
                                            constants.INSTALL_TYPE_RESTORE,
                                            branding)
                else:
                    if location == constants.BOOT_LOCATION_MBR:
                        if diskutil.is_raid(disk):
                            for member in diskutil.getDeviceSlaves(disk):
                                backend.installGrub2(mounts, member, False)
                        else:
                            backend.installGrub2(mounts, disk, False)
                    else:
                        backend.installGrub2(mounts, restore_partition, True)
            else:
                backend.installExtLinux(mounts, disk,
                                        probePartitioningScheme(disk),
                                        location)

            # restore bootloader configuration
            dst_file = boot_config.src_file.replace(backup_fs.mount_point,
                                                    dest_fs.mount_point, 1)
            util.assertDir(os.path.dirname(dst_file))
            boot_config.commit(dst_file)
        finally:
            util.umount("%s/proc" % dest_fs.mount_point)
            util.umount("%s/sys" % dest_fs.mount_point)
            util.umount("%s/dev" % dest_fs.mount_point)
            if efi_mounted:
                util.umount(esp)
            dest_fs.unmount()
    finally:
        backup_fs.unmount()

    if not label:
        raise RuntimeError(
            "Failed to find label required for root filesystem.")
    if efi_boot and not bootlabel:
        raise RuntimeError(
            "Failed to find label required for boot filesystem.")

    if util.runCmd2(['e2label', restore_partition, label]) != 0:
        raise RuntimeError("Failed to label root partition")

    if bootlabel:
        if util.runCmd2(['fatlabel', boot_device, bootlabel]) != 0:
            raise RuntimeError("Failed to label boot partition")

    if 'LOG' in backup_partition_layout:  # From 7.x (new layout) to 7.x (new layout)
        tool.commitActivePartitiontoDisk(boot_partnum)
        rdm_label = label.split("-")[1]
        logs_part = partitionDevice(disk, logs_partnum)
        swap_part = partitionDevice(disk, swap_partnum)
        if util.runCmd2(
            ['e2label', logs_part, constants.logsfs_label % rdm_label]) != 0:
            raise RuntimeError("Failed to label logs partition")
        if util.runCmd2([
                'swaplabel', '-L', constants.swap_label % rdm_label, swap_part
        ]) != 0:
            raise RuntimeError("Failed to label swap partition")
コード例 #32
0
ファイル: mplayer.py プロジェクト: 1147279/SoftwareProject
    def play(self, options, item):
        """
        play a videoitem with mplayer
        """
        self.options = options
        self.item = item

        mode = item.mode
        url = item.url

        self.item_info = None
        self.item_length = -1
        self.item.elapsed = 0

        VODEV = config.MPLAYER_VO_DEV
        VODEVOPTS = config.MPLAYER_VO_DEV_OPTS

        if mode == 'file':
            url = item.url[6:]
            self.item_info = mmpython.parse(url)
            if hasattr(self.item_info, 'get_length'):
                self.item_length = self.item_info.get_endpos()
                self.dynamic_seek_control = True

        if url.startswith('dvd://') and url[-1] == '/':
            url += '1'

        if url == 'vcd://':
            c_len = 0
            for i in range(len(item.info.tracks)):
                if item.info.tracks[i].length > c_len:
                    c_len = item.info.tracks[i].length
                    url = item.url + str(i + 1)

        try:
            _debug_('MPlayer.play(): mode=%s, url=%s' % (mode, url))
        except UnicodeError:
            _debug_('MPlayer.play(): [non-ASCII data]')

        if mode == 'file' and not os.path.isfile(url):
            # This event allows the videoitem which contains subitems to
            # try to play the next subitem
            return '%s\nnot found' % os.path.basename(url)

        # Build the MPlayer command
        command = [ '--prio=%s' % config.MPLAYER_NICE, config.MPLAYER_CMD ] + \
                  config.MPLAYER_ARGS_DEF.split(' ') + \
                  [ '-slave', '-ao'] + config.MPLAYER_AO_DEV.split(' ')

        additional_args = []

        if mode == 'dvd':
            if config.DVD_LANG_PREF:
                # There are some bad mastered DVDs out there. E.g. the specials on
                # the German Babylon 5 Season 2 disc claim they have more than one
                # audio track, even more then on en. But only the second en works,
                # mplayer needs to be started without -alang to find the track
                if hasattr(
                        item,
                        'mplayer_audio_broken') and item.mplayer_audio_broken:
                    print '*** dvd audio broken, try without alang ***'
                else:
                    additional_args += ['-alang', config.DVD_LANG_PREF]

            if config.DVD_SUBTITLE_PREF:
                # Only use if defined since it will always turn on subtitles
                # if defined
                additional_args += ['-slang', config.DVD_SUBTITLE_PREF]

        if hasattr(item.media, 'devicename') and mode != 'file':
            additional_args += ['-dvd-device', item.media.devicename]
        elif mode == 'dvd':
            # dvd on harddisc
            additional_args += ['-dvd-device', item.filename]
            url = url[:6] + url[url.rfind('/') + 1:]

        if item.media and hasattr(item.media, 'devicename'):
            additional_args += ['-cdrom-device', item.media.devicename]

        if item.selected_subtitle == -1:
            additional_args += ['-noautosub']

        elif item.selected_subtitle and mode == 'file':
            if os.path.isfile(os.path.splitext(item.filename)[0] + '.idx'):
                additional_args += ['-vobsubid', str(item.selected_subtitle)]
            else:
                additional_args += ['-sid', str(item.selected_subtitle)]

        elif item.selected_subtitle:
            additional_args += ['-sid', str(item.selected_subtitle)]

        if item.selected_audio:
            if item.mimetype == 'mkv':
                additional_args += ['-aid', str(item.selected_audio - 1)]
            else:
                additional_args += ['-aid', str(item.selected_audio)]

        # This comes from the bilingual language selection menu
        if hasattr(item, 'selected_language') and item.selected_language:
            if item.selected_language == 'left':
                additional_args += ['-af', 'pan=2:1:1:0:0']
            elif item.selected_language == 'right':
                additional_args += ['-af', 'pan=2:0:0:1:1']

        if item['deinterlace'] and config.MPLAYER_VF_INTERLACED:
            additional_args += ['-vf', config.MPLAYER_VF_INTERLACED]
        elif config.MPLAYER_VF_PROGRESSIVE:
            additional_args += ['-vf', config.MPLAYER_VF_PROGRESSIVE]

        if os.path.isfile(os.path.splitext(item.filename)[0] + '.edl'):
            additional_args += [
                '-edl',
                str(os.path.splitext(item.filename)[0] + '.edl')
            ]

        mode = item.mimetype
        if not config.MPLAYER_ARGS.has_key(mode):
            mode = 'default'

        # Mplayer command and standard arguments
        command += ['-v', '-vo', VODEV]
        command += VODEVOPTS.split(' ')

        # mode specific args
        command += config.MPLAYER_ARGS[mode].split(' ')

        # make the options a list
        command += additional_args

        if hasattr(item, 'is_playlist') and item.is_playlist:
            command.append('-playlist')

        # add the file to play
        command.append(url)

        if options:
            command += options

        # use software scaler?
        if '-nosws' in command:
            command.remove('-nosws')

        elif not '-framedrop' in command:
            command += config.MPLAYER_SOFTWARE_SCALER.split(' ')

        # correct avi delay based on kaa.metadata settings
        if config.MPLAYER_SET_AUDIO_DELAY and item.info.has_key('delay') and \
               item.info['delay'] > 0:
            command += [
                '-mc',
                str(int(item.info['delay']) + 1), '-delay',
                '-' + str(item.info['delay'])
            ]

        while '' in command:
            command.remove('')

        # autocrop
        if config.MPLAYER_AUTOCROP and not item.network_play and str(' ').join(
                command).find('crop=') == -1:
            _debug_('starting autocrop')
            (x1, y1, x2, y2) = (1000, 1000, 0, 0)
            crop_cmd = [
                config.MPLAYER_CMD, '-ao', 'null', '-vo', 'null', '-slave',
                '-nolirc', '-ss',
                '%s' % config.MPLAYER_AUTOCROP_START, '-frames', '20', '-vf',
                'cropdetect'
            ]
            crop_cmd.append(url)
            child = popen2.Popen3(self.sort_filter(crop_cmd), 1, 100)
            exp = re.compile(
                '^.*-vf crop=([0-9]*):([0-9]*):([0-9]*):([0-9]*).*')
            while (1):
                data = child.fromchild.readline()
                if not data:
                    break
                m = exp.match(data)
                if m:
                    x1 = min(x1, int(m.group(3)))
                    y1 = min(y1, int(m.group(4)))
                    x2 = max(x2, int(m.group(1)) + int(m.group(3)))
                    y2 = max(y2, int(m.group(2)) + int(m.group(4)))
                    _debug_('x1=%s x2=%s y1=%s y2=%s' % (x1, x2, y1, y2))

            if x1 < 1000 and x2 < 1000:
                command = command + [
                    '-vf',
                    'crop=%s:%s:%s:%s' % (x2 - x1, y2 - y1, x1, y1)
                ]
                _debug_('crop=%s:%s:%s:%s' % (x2 - x1, y2 - y1, x1, y1))

            child.wait()

        if item.subtitle_file:
            d, f = util.resolve_media_mountdir(item.subtitle_file)
            util.mount(d)
            command += ['-sub', f]

        if item.audio_file:
            d, f = util.resolve_media_mountdir(item.audio_file)
            util.mount(d)
            command += ['-audiofile', f]

        self.plugins = plugin.get('mplayer_video')

        for p in self.plugins:
            command = p.play(command, self)

        command = self.sort_filter(command)

        if plugin.getbyname('MIXER'):
            plugin.getbyname('MIXER').reset()

        rc.app(self)

        self.app = MPlayerApp(command, self)
        return None
コード例 #33
0
ファイル: fstab.py プロジェクト: vmware/weasel
def hostActionMigrateFstab(_context):
    oldFile = FstabFile.fromFile(HOST_ROOT + ESX3_INSTALLATION + "/etc/fstab")
    newFile = open(os.path.join(HOST_ROOT, "etc/fstab"), 'a')

    try:
        # Write out any entries that should need be cleaned out by the upgrade
        # cleanup script.
        for entry in oldFile:
            if entry.isDoubleMounted(
                userchoices.isCombinedBootAndRootForUpgrade()):
                # Write out the entry for "/boot" or "/" if there is no "/boot"
                # in the old install.
                if userchoices.isCombinedBootAndRootForUpgrade():
                    entry.mntpoint = ESX3_INSTALLATION + entry.mntpoint
                newFile.write("%s\n" % " ".join(entry))

        # Write out a header to demarcate the start of the entries that should
        # be removed by the upgrade cleanup script.
        newFile.write(
            "\n"
            "# BEGIN migrated entries\n"
            "#   Note: Any entries in this section will be removed\n"
            "#   when cleaning out the ESX v3 installation.\n")
        for entry in oldFile:
            if not entry.isMigratable():
                log.warning("not migrating fstab entry: %s" % " ".join(entry))
                continue

            if entry.mntpoint.startswith(ESX3_INSTALLATION):
                # Skip entries that have already been migrated by the first
                # loop above.
                continue
            
            # We have to mount /boot in the old and new cos, so it'll be rw
            # and show up twice in the file.
            if not entry.isDoubleMounted(
                userchoices.isCombinedBootAndRootForUpgrade()):
                entry.flags += ",ro"
            
            oldMntpoint = entry.mntpoint
            entry.mntpoint = ESX3_INSTALLATION + entry.mntpoint
            newFile.write("%s\n" % " ".join(entry))
            
            if oldMntpoint in ["/",]:
                # We've already mounted the old root by this point since we
                # need to be able to read the old fstab.
                continue

            # Mount the rest of entries in case they're needed by the %post.
            mntpoint = os.path.normpath(HOST_ROOT + entry.mntpoint)
            if os.path.islink(mntpoint):
                # XXX The user's configuration needs to be corrected...
                log.warn("mount point refers to a link, ignoring...")
                rc = 1
            elif entry.fstype in ["swap"]:
                # ignore
                rc = 0
            elif entry.fstype in ["nfs"]:
                # Don't use the cos infrastructure to do the mount since
                # resolv.conf/hosts is not transferred over yet.
                mounter = NFSMounter(mntpoint)
                host, root = entry.device.split(':', 1)
                if mounter.mount(host, root, entry.flags + ",bg,soft,nolock"):
                    rc = 0
                else:
                    rc = 1
            else:
                rc = util.mount(entry.device, mntpoint)
                
            if rc:
                log.warn("unable to mount -- %s" % " ".join(entry))
        newFile.write("# END migrated entries\n")
    finally:
        newFile.close()
コード例 #34
0
ファイル: rom_drives.py プロジェクト: 1147279/SoftwareProject
    def identify(self, media, force_rebuild=False):
        """
        magic!
        Try to find out as much as possible about the disc in the
        rom drive: title, image, play options, ...
        """
        # Check drive status (tray pos, disc ready)
        try:
            CDSL_CURRENT = ((int)(~0 >> 1))
            fd = os.open(media.devicename, os.O_RDONLY | os.O_NONBLOCK)
            if os.uname()[0] == 'FreeBSD':
                try:
                    data = array.array('c', '\000' * 4096)
                    (address, length) = data.buffer_info()
                    buf = pack('BBHP', CD_MSF_FORMAT, 0, length, address)
                    s = ioctl(fd, CDIOREADTOCENTRYS, buf)
                    s = CDS_DISC_OK
                except:
                    s = CDS_NO_DISC
            else:
                s = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT)
        except:
            # maybe we need to close the fd if ioctl fails, maybe
            # open fails and there is no fd
            try:
                os.close(fd)
            except:
                pass
            media.drive_status = None
            return

        # Same as last time? If so we're done
        if s == media.drive_status:
            os.close(fd)
            return

        media.drive_status = s

        media.id = ''
        media.label = ''
        media.type = 'empty_cdrom'
        media.item = None
        media.videoitem = None
        media.cached = False

        # Is there a disc present?
        if s != CDS_DISC_OK:
            os.close(fd)
            return

        # if there is a disc, the tray can't be open
        media.tray_open = False
        disc_info = util.mediainfo.disc_info(media, force_rebuild)
        if not disc_info:
            # bad disc, e.g. blank disc.
            os.close(fd)
            return

        data = disc_info.mmdata

        # try to set the speed
        if config.ROM_SPEED and data and not data['mime'] == 'video/dvd':
            try:
                ioctl(fd, CDROM_SELECT_SPEED, config.ROM_SPEED)
            except:
                pass

        if data and data['mime'] == 'audio/cd':
            os.close(fd)
            disc_id = data['id']
            media.item = AudioDiskItem(disc_id,
                                       parent=None,
                                       devicename=media.devicename,
                                       display_type='audio')
            media.type = media.item.type
            media.item.media = media
            if data['title']:
                media.item.name = data['title']
            media.item.info = disc_info
            return

        os.close(fd)
        image = title = movie_info = more_info = fxd_file = None

        media.id = data['id']
        media.label = data['label']
        media.type = 'cdrom'

        label = data['label']

        # is the id in the database?
        if media.id in video.fxd_database['id']:
            movie_info = video.fxd_database['id'][media.id]
            if movie_info:
                title = movie_info.name

        # no? Maybe we can find a label regexp match
        else:
            for (re_label, movie_info_t) in video.fxd_database['label']:
                if re_label.match(media.label):
                    movie_info = movie_info_t
                    if movie_info_t.name:
                        title = movie_info.name
                        m = re_label.match(media.label).groups()
                        re_count = 1

                        # found, now change the title with the regexp. E.g.:
                        # label is "bla_2", the label regexp "bla_[0-9]" and the title
                        # is "Something \1", the \1 will be replaced with the first item
                        # in the regexp group, here 2. The title is now "Something 2"
                        for g in m:
                            title = string.replace(title, '\\%s' % re_count, g)
                            re_count += 1
                        break

        if movie_info:
            image = movie_info.image

        # DVD/VCD/SVCD:
        # There is data from mmpython for these three types
        if data['mime'] in ('video/vcd', 'video/dvd'):
            if not title:
                title = media.label.replace('_', ' ').lstrip().rstrip()
                title = '%s [%s]' % (data['mime'][6:].upper(), title)

            if movie_info:
                media.item = copy.copy(movie_info)
            else:
                media.item = VideoItem('', None)
                media.item.image = util.getimage(
                    os.path.join(config.OVERLAY_DIR, 'disc-set', media.id))
            variables = media.item.info.variables
            media.item.info = disc_info
            media.item.info.set_variables(variables)

            media.item.name = title
            media.item.set_url(data['mime'][6:] + '://')
            media.item.media = media

            media.type = data['mime'][6:]

            media.item.info.mmdata = data
            return

        # Disc is data of some sort. Mount it to get the file info
        util.mount(media.mountdir, force=True)
        if os.path.isdir(os.path.join(media.mountdir, 'VIDEO_TS')) or \
               os.path.isdir(os.path.join(media.mountdir, 'video_ts')):
            if force_rebuild:
                _debug_('Double check without success')
            else:
                _debug_('Undetected DVD, checking again')
                media.drive_status = CDS_NO_DISC
                util.umount(media.mountdir)
                return self.identify(media, True)

        # Check for movies/audio/images on the disc
        num_video = disc_info['disc_num_video']
        num_audio = disc_info['disc_num_audio']
        num_image = disc_info['disc_num_image']

        video_files = util.match_files(media.mountdir, config.VIDEO_SUFFIX)

        _debug_('identifymedia: mplayer = "%s"' % video_files, level=2)

        media.item = DirItem(media.mountdir, None, create_metainfo=False)
        media.item.info = disc_info
        util.umount(media.mountdir)

        # if there is a video file on the root dir of the disc, we guess
        # it's a video disc. There may also be audio files and images, but
        # they only belong to the movie
        if video_files:
            media.type = 'video'

            # try to find out if it is a series cd
            if not title:
                show_name = ""
                the_same = 1
                volumes = ''
                start_ep = 0
                end_ep = 0

                video_files.sort(lambda l, o: cmp(l.upper(), o.upper()))

                for movie in video_files:
                    if config.VIDEO_SHOW_REGEXP_MATCH(movie):
                        show = config.VIDEO_SHOW_REGEXP_SPLIT(
                            os.path.basename(movie))

                        if show_name and show_name != show[0]:
                            the_same = 0
                        if not show_name:
                            show_name = show[0]
                        if volumes:
                            volumes += ', '
                        current_ep = int(show[1]) * 100 + int(show[2])
                        if end_ep and current_ep == end_ep + 1:
                            end_ep = current_ep
                        elif not end_ep:
                            end_ep = current_ep
                        else:
                            end_ep = -1
                        if not start_ep:
                            start_ep = end_ep
                        volumes += show[1] + "x" + show[2]

                if show_name and the_same and config.VIDEO_SHOW_DATA_DIR:
                    if end_ep > 0:
                        volumes = '%dx%02d - %dx%02d' % (
                            start_ep / 100, start_ep % 100, end_ep / 100,
                            end_ep % 100)
                    k = config.VIDEO_SHOW_DATA_DIR + show_name
                    if os.path.isfile((k + ".png").lower()):
                        image = (k + ".png").lower()
                    elif os.path.isfile((k + ".jpg").lower()):
                        image = (k + ".jpg").lower()
                    title = show_name + ' (' + volumes + ')'
                    if video.tv_show_informations.has_key(show_name.lower()):
                        tvinfo = video.tv_show_informations[show_name.lower()]
                        more_info = tvinfo[1]
                        if not image:
                            image = tvinfo[0]
                        if not fxd_file:
                            fxd_file = tvinfo[3]

                elif (not show_name) and len(video_files) == 1:
                    movie = video_files[0]
                    title = os.path.splitext(os.path.basename(movie))[0]

            # nothing found, give up: return the label
            if not title:
                title = label

        # If there are no videos and only audio files (and maybe images)
        # it is an audio disc (autostart will auto play everything)
        elif not num_video and num_audio:
            media.type = 'audio'
            title = '%s [%s]' % (media.drivename, label)

        # Only images? OK than, make it an image disc
        elif not num_video and not num_audio and num_image:
            media.type = 'image'
            title = '%s [%s]' % (media.drivename, label)

        # Mixed media?
        elif num_video or num_audio or num_image:
            media.type = None
            title = '%s [%s]' % (media.drivename, label)

        # Strange, no useable files
        else:
            media.type = None
            title = '%s [%s]' % (media.drivename, label)

        # set the infos we have now
        if title:
            media.item.name = title

        if image:
            media.item.image = image

        if more_info:
            media.item.info.set_variables(more_info)

        if fxd_file and not media.item.fxd_file:
            media.item.set_fxd_file(fxd_file)

        # One video in the root dir. This sounds like a disc with one
        # movie on it. Save the information about it and autostart will
        # play this.
        if len(video_files) == 1 and media.item['num_dir_items'] == 0:
            util.mount(media.mountdir)
            if movie_info:
                media.videoitem = copy.deepcopy(movie_info)
            else:
                media.videoitem = VideoItem(video_files[0], None)
            util.umount(media.mountdir)
            media.videoitem.media = media
            media.videoitem.media_id = media.id

            # set the infos we have
            if title:
                media.videoitem.name = title

            if image:
                media.videoitem.image = image

            if more_info:
                media.videoitem.set_variables(more_info)

            if fxd_file:
                media.videoitem.fxd_file = fxd_file

        media.item.media = media
        return
コード例 #35
0
ファイル: videoitem.py プロジェクト: golaizola/freevo1
    def __play(self, arg=None, menuw=None):
        # execute commands if defined
        if config.VIDEO_PRE_PLAY:
            os.system(config.VIDEO_PRE_PLAY)

        if self.parent:
            self.parent.current_item = self

        if not self.menuw:
            self.menuw = menuw

        # if we have variants, play the first one as default
        if self.variants:
            self.variants[0].play(arg, menuw)
            return

        # if we have subitems (a movie with more than one file),
        # we start playing the first that is physically available
        if self.subitems:
            self.error_in_subitem = 0
            self.last_error_msg   = ''
            self.current_subitem  = None

            result = self.set_next_available_subitem()
            if self.current_subitem: # 'result' is always 1 in this case
                # The media is available now for playing
                # Pass along the options, without loosing the subitem's own
                # options
                if self.current_subitem.mplayer_options:
                    if self.mplayer_options:
                        # With this set the player options are incorrect when there is more than 1 item
                        #self.current_subitem.mplayer_options += ' ' + self.mplayer_options
                        pass
                else:
                    self.current_subitem.mplayer_options = self.mplayer_options
                # When playing a subitem, the menu must be hidden. If it is not,
                # the playing will stop after the first subitem, since the
                # PLAY_END/USER_END event is not forwarded to the parent
                # videoitem.
                # And besides, we don't need the menu between two subitems.
                self.menuw.hide()
                self.last_error_msg = self.current_subitem.play(arg, self.menuw)
                if self.last_error_msg:
                    self.error_in_subitem = 1
                    # Go to the next playable subitem, using the loop in
                    # eventhandler()
                    self.eventhandler(PLAY_END)

            elif not result:
                # No media at all was found: error
                ConfirmBox(text=(_('No media found for "%(name)s".\nPlease insert the media "%(media_id)s".')) %
                     ({'name': self.name, 'media_id': self.media_id}), handler=self.play).show()
            return

        # normal plackback of one file
        if self.url.startswith('file://'):
            file = self.filename
            if self.media_id:
                mountdir, file = util.resolve_media_mountdir(self.media_id,file)
                if mountdir:
                    util.mount(mountdir)
                else:
                    self.menuw.show()
                    ConfirmBox(text=(_('No media found for "%(file)s".\nPlease insert the media "%(media_id)s".')) % \
                        ({'file': file, 'media_id': self.media_id}), handler=self.play).show()
                    return

            elif self.media:
                util.mount(os.path.dirname(self.filename))

        # dvd and vcd
        elif self.mode in ('dvd', 'vcd') and not self.filename and not self.media:
            media = util.check_media(self.media_id)
            if media:
                self.media = media
            else:
                self.menuw.show()
                ConfirmBox(text=(_('No media found for "%(media_id)s".\nPlease insert the media "%(url)s".')) % ({
                    'media_id': self.media_id, 'url': self.url}), handler=self.play).show()
                return

        mplayer_options = self.mplayer_options.split(' ')
        if not mplayer_options:
            mplayer_options = []

        if arg:
            mplayer_options += arg.split(' ')

        if self.menuw.visible:
            self.menuw.hide()

        self.plugin_eventhandler(PLAY, menuw)

        self.menuw.delete_submenu()

        error = self.player.play(mplayer_options, self)

        # Clear any resume settings
        self['resume'] = ''

        if error:
            # If we are a subitem we don't show any error message before
            # having tried all the subitems
            if hasattr(self.parent, 'subitems') and self.parent.subitems:
                return error
            else:
                AlertBox(text=error, handler=self.error_handler).show()
コード例 #36
0
def hostActionMigrateFstab(_context):
    oldFile = FstabFile.fromFile(HOST_ROOT + ESX3_INSTALLATION + "/etc/fstab")
    newFile = open(os.path.join(HOST_ROOT, "etc/fstab"), 'a')

    try:
        # Write out any entries that should need be cleaned out by the upgrade
        # cleanup script.
        for entry in oldFile:
            if entry.isDoubleMounted(
                    userchoices.isCombinedBootAndRootForUpgrade()):
                # Write out the entry for "/boot" or "/" if there is no "/boot"
                # in the old install.
                if userchoices.isCombinedBootAndRootForUpgrade():
                    entry.mntpoint = ESX3_INSTALLATION + entry.mntpoint
                newFile.write("%s\n" % " ".join(entry))

        # Write out a header to demarcate the start of the entries that should
        # be removed by the upgrade cleanup script.
        newFile.write("\n"
                      "# BEGIN migrated entries\n"
                      "#   Note: Any entries in this section will be removed\n"
                      "#   when cleaning out the ESX v3 installation.\n")
        for entry in oldFile:
            if not entry.isMigratable():
                log.warning("not migrating fstab entry: %s" % " ".join(entry))
                continue

            if entry.mntpoint.startswith(ESX3_INSTALLATION):
                # Skip entries that have already been migrated by the first
                # loop above.
                continue

            # We have to mount /boot in the old and new cos, so it'll be rw
            # and show up twice in the file.
            if not entry.isDoubleMounted(
                    userchoices.isCombinedBootAndRootForUpgrade()):
                entry.flags += ",ro"

            oldMntpoint = entry.mntpoint
            entry.mntpoint = ESX3_INSTALLATION + entry.mntpoint
            newFile.write("%s\n" % " ".join(entry))

            if oldMntpoint in [
                    "/",
            ]:
                # We've already mounted the old root by this point since we
                # need to be able to read the old fstab.
                continue

            # Mount the rest of entries in case they're needed by the %post.
            mntpoint = os.path.normpath(HOST_ROOT + entry.mntpoint)
            if os.path.islink(mntpoint):
                # XXX The user's configuration needs to be corrected...
                log.warn("mount point refers to a link, ignoring...")
                rc = 1
            elif entry.fstype in ["swap"]:
                # ignore
                rc = 0
            elif entry.fstype in ["nfs"]:
                # Don't use the cos infrastructure to do the mount since
                # resolv.conf/hosts is not transferred over yet.
                mounter = NFSMounter(mntpoint)
                host, root = entry.device.split(':', 1)
                if mounter.mount(host, root, entry.flags + ",bg,soft,nolock"):
                    rc = 0
                else:
                    rc = 1
            else:
                rc = util.mount(entry.device, mntpoint)

            if rc:
                log.warn("unable to mount -- %s" % " ".join(entry))
        newFile.write("# END migrated entries\n")
    finally:
        newFile.close()
コード例 #37
0
    def play(self, arg=None, menuw=None, alternateplayer=False):
        """
        execute commands if defined
        """
        if config.VIDEO_PRE_PLAY:
            os.system(config.VIDEO_PRE_PLAY)
        """
        play the item.
        """
        if not self.possible_player:
            for p in plugin.getbyname(plugin.VIDEO_PLAYER, True):
                rating = p.rate(self) * 10
                if config.VIDEO_PREFERED_PLAYER == p.name:
                    rating += 1
                if hasattr(self,
                           'force_player') and p.name == self.force_player:
                    rating += 100
                self.possible_player.append((rating, p))

            self.possible_player.sort(lambda l, o: -cmp(l[0], o[0]))

        if alternateplayer:
            self.possible_player.reverse()

        if not self.possible_player:
            return

        self.player_rating, self.player = self.possible_player[0]
        if self.parent:
            self.parent.current_item = self

        if not self.menuw:
            self.menuw = menuw

        # if we have variants, play the first one as default
        if self.variants:
            self.variants[0].play(arg, menuw)
            return

        # if we have subitems (a movie with more than one file),
        # we start playing the first that is physically available
        if self.subitems:
            self.error_in_subitem = 0
            self.last_error_msg = ''
            self.current_subitem = None

            result = self.set_next_available_subitem()
            if self.current_subitem:  # 'result' is always 1 in this case
                # The media is available now for playing
                # Pass along the options, without loosing the subitem's own
                # options
                if self.current_subitem.mplayer_options:
                    if self.mplayer_options:
                        self.current_subitem.mplayer_options += ' ' + self.mplayer_options
                else:
                    self.current_subitem.mplayer_options = self.mplayer_options
                # When playing a subitem, the menu must be hidden. If it is not,
                # the playing will stop after the first subitem, since the
                # PLAY_END/USER_END event is not forwarded to the parent
                # videoitem.
                # And besides, we don't need the menu between two subitems.
                self.menuw.hide()
                self.last_error_msg = self.current_subitem.play(
                    arg, self.menuw)
                if self.last_error_msg:
                    self.error_in_subitem = 1
                    # Go to the next playable subitem, using the loop in
                    # eventhandler()
                    self.eventhandler(PLAY_END)

            elif not result:
                # No media at all was found: error
                ConfirmBox(text=(_('No media found for "%s".\n') +
                                 _('Please insert the media.')) % self.name,
                           handler=self.play).show()
            return

        # normal plackback of one file
        if self.url.startswith('file://'):
            file = self.filename
            if self.media_id:
                mountdir, file = util.resolve_media_mountdir(
                    self.media_id, file)
                if mountdir:
                    util.mount(mountdir)
                else:
                    self.menuw.show()
                    ConfirmBox(text=(_('No media found for "%s".\n') +
                                     _('Please insert the media.')) % file,
                               handler=self.play).show()
                    return

            elif self.media:
                util.mount(os.path.dirname(self.filename))

        elif self.mode in ('dvd',
                           'vcd') and not self.filename and not self.media:
            media = util.check_media(self.media_id)
            if media:
                self.media = media
            else:
                self.menuw.show()
                ConfirmBox(text=(_('No media found for "%s".\n') +
                                 _('Please insert the media.')) % self.url,
                           handler=self.play).show()
                return

        if self.player_rating < 10:
            AlertBox(text=_('No player for this item found')).show()
            return

        mplayer_options = self.mplayer_options.split(' ')
        if not mplayer_options:
            mplayer_options = []

        if arg:
            mplayer_options += arg.split(' ')

        if self.menuw.visible:
            self.menuw.hide()

        self.plugin_eventhandler(PLAY, menuw)

        error = self.player.play(mplayer_options, self)

        if error:
            # If we are a subitem we don't show any error message before
            # having tried all the subitems
            if hasattr(self.parent, 'subitems') and self.parent.subitems:
                return error
            else:
                AlertBox(text=error, handler=self.error_handler).show()
コード例 #38
0
ファイル: mplayer.py プロジェクト: murbaniak/freevo1
    def play(self, options, item):
        """
        play a videoitem with mplayer
        """
        logger.log( 9, 'options=%r', options)
        for k, v in item.__dict__.items():
            logger.log( 9, 'item[%s]=%r', k, v)

        mode         = item.mode
        url          = item.url

        self.options = options
        self.item    = item
        self.item_info    = None
        self.item_length  = -1
        self.item.elapsed = 0

        if mode == 'file':
            url = item.url[6:]
            self.item_info = mmpython.parse(url)
            if hasattr(self.item_info, 'get_length'):
                self.item_length = self.item_info.get_endpos()
                self.dynamic_seek_control = True

        if url.startswith('dvd://') and url[-1] == '/':
            url += '1'

        if url == 'vcd://':
            c_len = 0
            for i in range(len(item.info.tracks)):
                if item.info.tracks[i].length > c_len:
                    c_len = item.info.tracks[i].length
                    url = item.url + str(i+1)

        url=Unicode(url)
        try:
            logger.debug('MPlayer.play(): mode=%s, url=%s', mode, url)
        except UnicodeError:
            logger.debug('MPlayer.play(): [non-ASCII data]')

        if mode == 'file' and not os.path.isfile(url):
            # This event allows the videoitem which contains subitems to
            # try to play the next subitem
            return '%s\nnot found' % os.path.basename(url)

        set_vcodec = False
        if item['xvmc'] and item['type'][:6] in ['MPEG-1', 'MPEG-2', 'MPEG-T']:
            set_vcodec = True

        mode = item.mimetype
        if not config.MPLAYER_ARGS.has_key(mode):
            logger.info('MPLAYER_ARGS not defined for %r, using default', mode)
            mode = 'default'

        logger.debug('mode=%s args=%s', mode, config.MPLAYER_ARGS[mode])
        # Build the MPlayer command
        args = {
            'nice': config.MPLAYER_NICE,
            'cmd': config.MPLAYER_CMD,
            'vo': '-vo %s' % config.MPLAYER_VO_DEV,
            'vo_opts': config.MPLAYER_VO_DEV_OPTS,
            'vc': '',
            'ao': '-ao %s' % config.MPLAYER_AO_DEV,
            'ao_opts': config.MPLAYER_AO_DEV_OPTS,
            'default_args': config.MPLAYER_ARGS_DEF,
            'mode_args': config.MPLAYER_ARGS[mode],
            'fxd_args': ' '.join(options),
            'geometry': '',
            'verbose': '',
            'dvd-device': '',
            'cdrom-device': '',
            'alang': '',
            'aid': '',
            'slang': '',
            'sid': '',
            'playlist': '',
            'field-dominance': '',
            'edl': '',
            'mc': '',
            'delay': '',
            'sub': '',
            'audiofile': '',
            'af': [],
            'vf': [],
            'url': url,
            'disable_osd': False,
            'start_position': [],
        }

        if item['resume']:
            t = int(item['resume'])
            info = mmpython.parse(item.filename)
            if hasattr(info, 'seek') and t:
                args['start_position']=['-sb' , str(info.seek(t))]
            else:
                args['start_position']=['-ss', str(t)]

        if config.CONF.x or config.CONF.y:
            args['geometry'] = '-geometry %d:%d' % (config.CONF.x, config.CONF.y)

        if config.DEBUG_CHILDAPP:
            args['verbose'] = '-v'

        if mode == 'dvd':
            if config.DVD_LANG_PREF:
                # There are some bad mastered DVDs out there. E.g. the specials on
                # the German Babylon 5 Season 2 disc claim they have more than one
                # audio track, even more then on en. But only the second en works,
                # mplayer needs to be started without -alang to find the track
                if hasattr(item, 'mplayer_audio_broken') and item.mplayer_audio_broken:
                    print '*** dvd audio broken, try without alang ***'
                else:
                    args['alang'] = '-alang %s' % config.DVD_LANG_PREF

            if config.DVD_SUBTITLE_PREF:
                # Only use if defined since it will always turn on subtitles when defined
                args['slang'] = '-slang %s' % config.DVD_SUBTITLE_PREF

        if mode == 'dvd':
            # dvd on harddisc
            args['dvd-device'] = '%s' % item.filename
            args['url'] = url[:6] + url[url.rfind('/')+1:]
        elif mode != 'file' and hasattr(item.media, 'devicename'):
            args['dvd-device'] = '%s' % item.media.devicename

        if item.media and hasattr(item.media, 'devicename'):
            args['cdrom-device'] = '%s' % item.media.devicename

        if item.selected_subtitle == -1:
            args['sid'] = '-noautosub'
        elif item.selected_subtitle is not None:
            if mode == 'file':
                if os.path.isfile(os.path.splitext(item.filename)[0]+'.idx'):
                    args['sid'] = '-vobsubid %s' % str(item.selected_subtitle)
                else:
                    args['sid'] = '-sid %s' % str(item.selected_subtitle)
            else:
                args['sid'] = '-sid %s' % str(item.selected_subtitle)

        if item.selected_audio is not None:
            args['aid'] = '-aid %s' % str(item.selected_audio)

        # This comes from the bilingual language selection menu
        if hasattr(item, 'selected_language') and item.selected_language:
            if item.selected_language == 'left':
                args['af'].append('pan=2:1:1:0:0')
            elif item.selected_language == 'right':
                args['af'].append('pan=2:0:0:1:1')

        if not set_vcodec:
            if item['deinterlace'] and config.MPLAYER_VF_INTERLACED:
                args['vf'].append(config.MPLAYER_VF_INTERLACED)
            elif config.MPLAYER_VF_PROGRESSIVE:
                args['vf'].append(config.MPLAYER_VF_PROGRESSIVE)

        if config.VIDEO_FIELD_DOMINANCE is not None:
            args['field-dominance'] = '-field-dominance %d' % int(item['field-dominance'])

        if os.path.isfile(os.path.splitext(item.filename)[0]+'.edl'):
            args['edl'] = '-edl %s' % str(os.path.splitext(item.filename)[0]+'.edl')

        if dialog.overlay_display_supports_dialogs:
            # Disable the mplayer OSD if we have a better option.
            args['disable_osd'] = True

        # Mplayer command and standard arguments
        if set_vcodec:
            if item['deinterlace']:
                bobdeint='bobdeint'
            else:
                bobdeint='nobobdeint'
            args['vo'] = '-vo xvmc:%s' % bobdeint
            args['vc'] = '-vc ffmpeg12mc'

        if hasattr(item, 'is_playlist') and item.is_playlist:
            args['playlist'] = '-playlist'

        if args['fxd_args'].find('-playlist') > 0:
            args['fxd_args'] = args['fxd_args'].replace('-playlist', '')
            args['playlist'] = '-playlist'
       
        # correct avi delay based on kaa.metadata settings
        if config.MPLAYER_SET_AUDIO_DELAY and item.info.has_key('delay') and item.info['delay'] > 0:
            args['mc'] = '-mc %s' % str(int(item.info['delay'])+1)
            args['delay'] = '-delay -%s' % str(item.info['delay'])

        # mplayer A/V is screwed up when setrting screen refresh rate to the same value as the movies FPS
        # this does happen almost exclusively at 23.976 FPS. Let's try to fix it. 
        if config.MPLAYER_RATE_SET_FROM_VIDEO and item.getattr('fps') in ['23.976', '24.000' ]:
            args['mc'] = '-mc %s' % str(int(config.MPLAYER_AUDIO_DELAY)+1)
            args['delay'] = '-delay %s' % str(config.MPLAYER_AUDIO_DELAY)

        # autocrop
        if config.MPLAYER_AUTOCROP and not item.network_play and args['fxd_args'].find('crop=') == -1:
            logger.debug('starting autocrop')
            (x1, y1, x2, y2) = (1000, 1000, 0, 0)
            crop_points = config.MPLAYER_AUTOCROP_START
            if not isinstance(crop_points, list):
                crop_points = [crop_points]

            for crop_point in crop_points:
                (x1, y1, x2, y2) = self.get_crop(crop_point, x1, y1, x2, y2)

            if x1 < 1000 and x2 < 1000:
                args['vf'].append('crop=%s:%s:%s:%s' % (x2-x1, y2-y1, x1, y1))
                logger.debug('crop=%s:%s:%s:%s', x2 - x1, y2 - y1, x1, y1)

        if item.subtitle_file:
            d, f = util.resolve_media_mountdir(item.subtitle_file)
            util.mount(d)
            args['sub'] = '-sub %s' % f

        if item.audio_file:
            d, f = util.resolve_media_mountdir(item.audio_file)
            util.mount(d)
            args['audiofile'] = '-audiofile %s' % f

        self.plugins = plugin.get('mplayer_video')
        for p in self.plugins:
            command = p.play(command, self)

        vo = ['%(vo)s' % args, '%(vo_opts)s' % args]
        vo = filter(len, vo)
        vo = ':'.join(vo)

        ao = ['%(ao)s' % args, '%(ao_opts)s' % args]
        ao = filter(len, ao)
        ao = ':'.join(ao)

        # process the mplayer options extracting video and audio filters
        args['default_args'], args = self.find_filters(args['default_args'], args)
        args['mode_args'], args = self.find_filters(args['mode_args'], args)
        args['fxd_args'], args = self.find_filters(args['fxd_args'], args)

        command = ['--prio=%(nice)s' % args]
        command += ['%(cmd)s' % args]
        command += ['-slave']
        command += str('%(verbose)s' % args).split()
        command += str('%(geometry)s' % args).split()
        command += vo.split()
        command += str('%(vc)s' % args).split()
        command += ao.split()
        command += args['dvd-device'] and ['-dvd-device', '%(dvd-device)s' % args] or []
        command += args['cdrom-device'] and ['-cdrom-device', '%(cdrom-device)s' % args] or []
        command += str('%(alang)s' % args).split()
        command += str('%(aid)s' % args).split()
        command += str('%(audiofile)s' % args).split()
        command += str('%(slang)s' % args).split()
        command += str('%(sid)s' % args).split()
        command += str('%(sub)s' % args).split()
        command += str('%(field-dominance)s' % args).split()
        command += str('%(edl)s' % args).split()
        command += str('%(mc)s' % args).split()
        command += str('%(delay)s' % args).split()
        command += args['default_args'].split()
        command += args['mode_args'].split()
        command += args['fxd_args'].split()
        command += args['af'] and ['-af', '%s' % ','.join(args['af'])] or []
        command += args['vf'] and ['-vf', '%s' % ','.join(args['vf'])] or []
        command += args['disable_osd'] and ['-osdlevel', '0'] or []
        command += args['start_position']

        if config.OSD_SINGLE_WINDOW:
            command += ['-wid', str(osd.video_window.id)]
            
        # This ensures constant subtitle size, disable if you do not like this
        # and want to have the size as designed by the sutitle creator.
        # Unfortunately, subtitle size is heavilly dependant on the size of 
        # the video, i.e. width/height so the size varies so much that is unusable
        if config.MPLAYER_ASS_FONT_SCALE and mode not in ['dvd', 'default']:
            v_height = float(item.getattr('height'))
            v_width  = float(item.getattr('width'))
            f_scale = (v_width / v_height) * config.MPLAYER_ASS_FONT_SCALE

            command += ['-ass-font-scale', str(f_scale)]

        # use software scaler?
        #XXX these need to be in the arg list as the scaler will add vf args
        if '-nosws' in command:
            command.remove('-nosws')
        elif '-framedrop' not in command:
            command += config.MPLAYER_SOFTWARE_SCALER.split()

        command = filter(len, command)

        command += str('%(playlist)s' % args).split()
        command += ['%(url)s' % args]

        logger.debug(' '.join(command[1:]))

        #if plugin.getbyname('MIXER'):
            #plugin.getbyname('MIXER').reset()

        self.paused = False

        rc.add_app(self)
        self.app = MPlayerApp(command, self)
        dialog.enable_overlay_display(AppTextDisplay(self.show_message))
        self.play_state_dialog = None
        return None
コード例 #39
0
ファイル: devfs.py プロジェクト: wagnerrp/pyjail
 def mount(cls, mountpoint, ruleset):
     mount('devfs', mountpoint, 'devfs')
     if ruleset in cls._byid:
         cls._byid[ruleset].apply(mountpoint)
     elif ruleset in cls._byname:
         cls._byname[ruleset].apply(mountpoint)
コード例 #40
0
    def play(self, options, item):
        """
        play a videoitem with mplayer
        """
        logger.log(9, 'options=%r', options)
        for k, v in item.__dict__.items():
            logger.log(9, 'item[%s]=%r', k, v)

        mode = item.mode
        url = item.url

        self.options = options
        self.item = item
        self.item_info = None
        self.item_length = -1
        self.item.elapsed = 0

        if mode == 'file':
            url = item.url[6:]
            self.item_info = mmpython.parse(url)
            if hasattr(self.item_info, 'get_length'):
                self.item_length = self.item_info.get_endpos()
                self.dynamic_seek_control = True

        if url.startswith('dvd://') and url[-1] == '/':
            url += '1'

        if url == 'vcd://':
            c_len = 0
            for i in range(len(item.info.tracks)):
                if item.info.tracks[i].length > c_len:
                    c_len = item.info.tracks[i].length
                    url = item.url + str(i + 1)

        url = Unicode(url)
        try:
            logger.debug('MPlayer.play(): mode=%s, url=%s', mode, url)
        except UnicodeError:
            logger.debug('MPlayer.play(): [non-ASCII data]')

        if mode == 'file' and not os.path.isfile(url):
            # This event allows the videoitem which contains subitems to
            # try to play the next subitem
            return '%s\nnot found' % os.path.basename(url)

        set_vcodec = False
        if item['xvmc'] and item['type'][:6] in ['MPEG-1', 'MPEG-2', 'MPEG-T']:
            set_vcodec = True

        mode = item.mimetype
        if not config.MPLAYER_ARGS.has_key(mode):
            logger.info('MPLAYER_ARGS not defined for %r, using default', mode)
            mode = 'default'

        logger.debug('mode=%s args=%s', mode, config.MPLAYER_ARGS[mode])
        # Build the MPlayer command
        args = {
            'nice': config.MPLAYER_NICE,
            'cmd': config.MPLAYER_CMD,
            'vo': '-vo %s' % config.MPLAYER_VO_DEV,
            'vo_opts': config.MPLAYER_VO_DEV_OPTS,
            'vc': '',
            'ao': '-ao %s' % config.MPLAYER_AO_DEV,
            'ao_opts': config.MPLAYER_AO_DEV_OPTS,
            'default_args': config.MPLAYER_ARGS_DEF,
            'mode_args': config.MPLAYER_ARGS[mode],
            'fxd_args': ' '.join(options),
            'geometry': '',
            'verbose': '',
            'dvd-device': '',
            'cdrom-device': '',
            'alang': '',
            'aid': '',
            'slang': '',
            'sid': '',
            'playlist': '',
            'field-dominance': '',
            'edl': '',
            'mc': '',
            'delay': '',
            'sub': '',
            'audiofile': '',
            'af': [],
            'vf': [],
            'url': url,
            'disable_osd': False,
            'start_position': [],
        }

        if item['resume']:
            t = int(item['resume'])
            info = mmpython.parse(item.filename)
            if hasattr(info, 'seek') and t:
                args['start_position'] = ['-sb', str(info.seek(t))]
            else:
                args['start_position'] = ['-ss', str(t)]

        if config.CONF.x or config.CONF.y:
            args['geometry'] = '-geometry %d:%d' % (config.CONF.x,
                                                    config.CONF.y)

        if config.DEBUG_CHILDAPP:
            args['verbose'] = '-v'

        if mode == 'dvd':
            if config.DVD_LANG_PREF:
                # There are some bad mastered DVDs out there. E.g. the specials on
                # the German Babylon 5 Season 2 disc claim they have more than one
                # audio track, even more then on en. But only the second en works,
                # mplayer needs to be started without -alang to find the track
                if hasattr(
                        item,
                        'mplayer_audio_broken') and item.mplayer_audio_broken:
                    print '*** dvd audio broken, try without alang ***'
                else:
                    args['alang'] = '-alang %s' % config.DVD_LANG_PREF

            if config.DVD_SUBTITLE_PREF:
                # Only use if defined since it will always turn on subtitles when defined
                args['slang'] = '-slang %s' % config.DVD_SUBTITLE_PREF

        if mode == 'dvd':
            # dvd on harddisc
            args['dvd-device'] = '%s' % item.filename
            args['url'] = url[:6] + url[url.rfind('/') + 1:]
        elif mode != 'file' and hasattr(item.media, 'devicename'):
            args['dvd-device'] = '%s' % item.media.devicename

        if item.media and hasattr(item.media, 'devicename'):
            args['cdrom-device'] = '%s' % item.media.devicename

        if item.selected_subtitle == -1:
            args['sid'] = '-noautosub'
        elif item.selected_subtitle is not None:
            if mode == 'file':
                if os.path.isfile(os.path.splitext(item.filename)[0] + '.idx'):
                    args['sid'] = '-vobsubid %s' % str(item.selected_subtitle)
                else:
                    args['sid'] = '-sid %s' % str(item.selected_subtitle)
            else:
                args['sid'] = '-sid %s' % str(item.selected_subtitle)

        if item.selected_audio is not None:
            args['aid'] = '-aid %s' % str(item.selected_audio)

        # This comes from the bilingual language selection menu
        if hasattr(item, 'selected_language') and item.selected_language:
            if item.selected_language == 'left':
                args['af'].append('pan=2:1:1:0:0')
            elif item.selected_language == 'right':
                args['af'].append('pan=2:0:0:1:1')

        if not set_vcodec:
            if item['deinterlace'] and config.MPLAYER_VF_INTERLACED:
                args['vf'].append(config.MPLAYER_VF_INTERLACED)
            elif config.MPLAYER_VF_PROGRESSIVE:
                args['vf'].append(config.MPLAYER_VF_PROGRESSIVE)

        if config.VIDEO_FIELD_DOMINANCE is not None:
            args['field-dominance'] = '-field-dominance %d' % int(
                item['field-dominance'])

        if os.path.isfile(os.path.splitext(item.filename)[0] + '.edl'):
            args['edl'] = '-edl %s' % str(
                os.path.splitext(item.filename)[0] + '.edl')

        if dialog.overlay_display_supports_dialogs:
            # Disable the mplayer OSD if we have a better option.
            args['disable_osd'] = True

        # Mplayer command and standard arguments
        if set_vcodec:
            if item['deinterlace']:
                bobdeint = 'bobdeint'
            else:
                bobdeint = 'nobobdeint'
            args['vo'] = '-vo xvmc:%s' % bobdeint
            args['vc'] = '-vc ffmpeg12mc'

        if hasattr(item, 'is_playlist') and item.is_playlist:
            args['playlist'] = '-playlist'

        if args['fxd_args'].find('-playlist') > 0:
            args['fxd_args'] = args['fxd_args'].replace('-playlist', '')
            args['playlist'] = '-playlist'

        # correct avi delay based on kaa.metadata settings
        if config.MPLAYER_SET_AUDIO_DELAY and item.info.has_key(
                'delay') and item.info['delay'] > 0:
            args['mc'] = '-mc %s' % str(int(item.info['delay']) + 1)
            args['delay'] = '-delay -%s' % str(item.info['delay'])

        # mplayer A/V is screwed up when setrting screen refresh rate to the same value as the movies FPS
        # this does happen almost exclusively at 23.976 FPS. Let's try to fix it.
        if config.MPLAYER_RATE_SET_FROM_VIDEO and item.getattr('fps') in [
                '23.976', '24.000'
        ]:
            args['mc'] = '-mc %s' % str(int(config.MPLAYER_AUDIO_DELAY) + 1)
            args['delay'] = '-delay %s' % str(config.MPLAYER_AUDIO_DELAY)

        # autocrop
        if config.MPLAYER_AUTOCROP and not item.network_play and args[
                'fxd_args'].find('crop=') == -1:
            logger.debug('starting autocrop')
            (x1, y1, x2, y2) = (1000, 1000, 0, 0)
            crop_points = config.MPLAYER_AUTOCROP_START
            if not isinstance(crop_points, list):
                crop_points = [crop_points]

            for crop_point in crop_points:
                (x1, y1, x2, y2) = self.get_crop(crop_point, x1, y1, x2, y2)

            if x1 < 1000 and x2 < 1000:
                args['vf'].append('crop=%s:%s:%s:%s' %
                                  (x2 - x1, y2 - y1, x1, y1))
                logger.debug('crop=%s:%s:%s:%s', x2 - x1, y2 - y1, x1, y1)

        if item.subtitle_file:
            d, f = util.resolve_media_mountdir(item.subtitle_file)
            util.mount(d)
            args['sub'] = '-sub %s' % f

        if item.audio_file:
            d, f = util.resolve_media_mountdir(item.audio_file)
            util.mount(d)
            args['audiofile'] = '-audiofile %s' % f

        self.plugins = plugin.get('mplayer_video')
        for p in self.plugins:
            command = p.play(command, self)

        vo = ['%(vo)s' % args, '%(vo_opts)s' % args]
        vo = filter(len, vo)
        vo = ':'.join(vo)

        ao = ['%(ao)s' % args, '%(ao_opts)s' % args]
        ao = filter(len, ao)
        ao = ':'.join(ao)

        # process the mplayer options extracting video and audio filters
        args['default_args'], args = self.find_filters(args['default_args'],
                                                       args)
        args['mode_args'], args = self.find_filters(args['mode_args'], args)
        args['fxd_args'], args = self.find_filters(args['fxd_args'], args)

        command = ['--prio=%(nice)s' % args]
        command += ['%(cmd)s' % args]
        command += ['-slave']
        command += str('%(verbose)s' % args).split()
        command += str('%(geometry)s' % args).split()
        command += vo.split()
        command += str('%(vc)s' % args).split()
        command += ao.split()
        command += args['dvd-device'] and [
            '-dvd-device', '%(dvd-device)s' % args
        ] or []
        command += args['cdrom-device'] and [
            '-cdrom-device', '%(cdrom-device)s' % args
        ] or []
        command += str('%(alang)s' % args).split()
        command += str('%(aid)s' % args).split()
        command += str('%(audiofile)s' % args).split()
        command += str('%(slang)s' % args).split()
        command += str('%(sid)s' % args).split()
        command += str('%(sub)s' % args).split()
        command += str('%(field-dominance)s' % args).split()
        command += str('%(edl)s' % args).split()
        command += str('%(mc)s' % args).split()
        command += str('%(delay)s' % args).split()
        command += args['default_args'].split()
        command += args['mode_args'].split()
        command += args['fxd_args'].split()
        command += args['af'] and ['-af', '%s' % ','.join(args['af'])] or []
        command += args['vf'] and ['-vf', '%s' % ','.join(args['vf'])] or []
        command += args['disable_osd'] and ['-osdlevel', '0'] or []
        command += args['start_position']

        if config.OSD_SINGLE_WINDOW:
            command += ['-wid', str(osd.video_window.id)]

        # This ensures constant subtitle size, disable if you do not like this
        # and want to have the size as designed by the sutitle creator.
        # Unfortunately, subtitle size is heavilly dependant on the size of
        # the video, i.e. width/height so the size varies so much that is unusable
        if config.MPLAYER_ASS_FONT_SCALE and mode not in ['dvd', 'default']:
            try:
                v_height = float(item.getattr('height'))
                v_width = float(item.getattr('width'))
                f_scale = (v_width / v_height) * config.MPLAYER_ASS_FONT_SCALE
                command += ['-ass-font-scale', str(f_scale)]
            except:
                pass

        # use software scaler?
        #XXX these need to be in the arg list as the scaler will add vf args
        if '-nosws' in command:
            command.remove('-nosws')
        elif '-framedrop' not in command:
            command += config.MPLAYER_SOFTWARE_SCALER.split()

        command = filter(len, command)

        command += str('%(playlist)s' % args).split()
        command += ['%(url)s' % args]

        logger.debug(' '.join(command[1:]))

        #if plugin.getbyname('MIXER'):
        #plugin.getbyname('MIXER').reset()

        self.paused = False

        rc.add_app(self)
        self.app = MPlayerApp(command, self)
        dialog.enable_overlay_display(AppTextDisplay(self.show_message))
        self.play_state_dialog = None
        return None