def __init__(self, opts, name, root, vidlist, harvesters):
        self.name = name
        self.title = name
        self.opts = opts.copy()
        self.count = 0
        self.root = root
        self.videoDir = VideoDir(opts, "", "", root, name)

        tree = myWalk(root)

        sharedirs = {"": self.videoDir}
        shareopts = {"": self.opts}

        for path, dirs, files in tree:
            rpath = path[len(root) :]
            if rpath.startswith(os.path.sep):
                rpath = rpath[1:]
            if rpath not in sharedirs:
                continue
            vl = sharedirs[rpath]
            lopts = shareopts[rpath]
            Config.addLocalOpts(lopts, root, rpath)
            vl.setOpts(lopts)

            for name in dirs:
                if name.startswith("."):
                    continue
                meta = metadata.from_text(
                    os.path.join(path, name, "folder"),
                    lopts["metamergefiles"],
                    lopts["metamergelines"],
                    lopts["metamergeparent"],
                )
                d = VideoDir(lopts, name, rpath, path, self.name)
                d.setMeta(meta)
                vl.addDir(d)
                sharedirs[os.path.join(rpath, name)] = d
                shareopts[os.path.join(rpath, name)] = lopts.copy()

            for name in files:
                if name.startswith("."):
                    continue
                if os.path.splitext(name)[1].lower() in lopts["goodexts"]:
                    fid = fileId(os.path.join(path, name))
                    if fid != None:
                        vf = vidlist.findVideo(fid)
                    else:
                        vf = None

                    if vf == None:
                        vf = VideoFile(lopts, path, name, fid)
                        vidlist.addVideo(vf)

                        meta = metadata.from_text(
                            os.path.join(path, name),
                            lopts["metamergefiles"],
                            lopts["metamergelines"],
                            lopts["metamergeparent"],
                        )
                        if not "title" in meta:
                            meta = metadata.basic(os.path.join(path, name))
                        vf.setMeta(meta)

                        vl.addVideo(vf)
                        self.count += 1

                        for h in harvesters:
                            h.harvest(vf)

                    else:
                        vl.addVideo(vf, path=path, fn=name)
                        self.count += 1

            vl.sort()
Example #2
0
    def metadata_full(self, full_path, tsn='', mime=''):
        data = {}
        vInfo = transcode.video_info(full_path)

        if ((int(vInfo['vHeight']) >= 720 and
             config.getTivoHeight >= 720) or
            (int(vInfo['vWidth']) >= 1280 and
             config.getTivoWidth >= 1280)):
            data['showingBits'] = '4096'

        data.update(metadata.basic(full_path))
        if full_path[-5:].lower() == '.tivo':
            data.update(metadata.from_tivo(full_path))
        if full_path[-4:].lower() == '.wtv':
            data.update(metadata.from_mscore(vInfo['rawmeta']))

        if 'episodeNumber' in data:
            try:
                ep = int(data['episodeNumber'])
            except:
                ep = 0
            data['episodeNumber'] = str(ep)

        if config.getDebug() and 'vHost' not in data:
            compatible, reason = transcode.tivo_compatible(full_path, tsn, mime)
            if compatible:
                transcode_options = {}
            else:
                transcode_options = transcode.transcode(True, full_path,
                                                        '', tsn, mime)
            data['vHost'] = (
                ['TRANSCODE=%s, %s' % (['YES', 'NO'][compatible], reason)] +
                ['SOURCE INFO: '] +
                ["%s=%s" % (k, v)
                 for k, v in sorted(vInfo.items(), reverse=True)] +
                ['TRANSCODE OPTIONS: '] +
                ["%s" % (v) for k, v in transcode_options.items()] +
                ['SOURCE FILE: ', os.path.basename(full_path)]
            )

        now = datetime.utcnow()
        if 'time' in data:
            if data['time'].lower() == 'file':
                mtime = os.stat(unicode(full_path, 'utf-8')).st_mtime
                if (mtime < 0):
                    mtime = 0
                try:
                    now = datetime.utcfromtimestamp(mtime)
                except:
                    logger.warning('Bad file time on ' + full_path)
            elif data['time'].lower() == 'oad':
                    now = isodt(data['originalAirDate'])
            else:
                try:
                    now = isodt(data['time'])
                except:
                    logger.warning('Bad time format: ' + data['time'] +
                                   ' , using current time')

        duration = self.__duration(full_path)
        duration_delta = timedelta(milliseconds = duration)
        min = duration_delta.seconds / 60
        sec = duration_delta.seconds % 60
        hours = min / 60
        min = min % 60

        data.update({'time': now.isoformat(),
                     'startTime': now.isoformat(),
                     'stopTime': (now + duration_delta).isoformat(),
                     'size': self.__est_size(full_path, tsn, mime),
                     'duration': duration,
                     'iso_duration': ('P%sDT%sH%sM%sS' % 
                          (duration_delta.days, hours, min, sec))})

        return data
Example #3
0
    def QueryContainer(self, handler, query):
        tsn = handler.headers.getheader('tsn', '')
        subcname = query['Container'][0]
        useragent = handler.headers.getheader('User-Agent', '')

        if not self.get_local_path(handler, query):
            handler.send_error(404)
            return

        container = handler.container
        force_alpha = container.getboolean('force_alpha')
        use_html = query.get('Format', [''])[0].lower() == 'text/html'

        files, total, start = self.get_files(handler, query,
                                             self.video_file_filter,
                                             force_alpha)

        videos = []
        local_base_path = self.get_local_base_path(handler, query)
        for f in files:
            video = VideoDetails()
            mtime = f.mdate
            try:
                ltime = time.localtime(mtime)
            except:
                logger.warning('Bad file time on ' + unicode(f.name, 'utf-8'))
                mtime = int(time.time())
                ltime = time.localtime(mtime)
            video['captureDate'] = hex(mtime)
            video['textDate'] = time.strftime('%b %d, %Y', ltime)
            video['name'] = os.path.basename(f.name)
            video['path'] = f.name
            video['part_path'] = f.name.replace(local_base_path, '', 1)
            if not video['part_path'].startswith(os.path.sep):
                video['part_path'] = os.path.sep + video['part_path']
            video['title'] = os.path.basename(f.name)
            video['is_dir'] = f.isdir
            if video['is_dir']:
                video['small_path'] = subcname + '/' + video['name']
                video['total_items'] = self.__total_items(f.name)
            else:
                if len(files) == 1 or f.name in transcode.info_cache:
                    video['valid'] = transcode.supported_format(f.name)
                    if video['valid']:
                        video.update(self.metadata_full(f.name, tsn))
                        if len(files) == 1:
                            video['captureDate'] = hex(isogm(video['time']))
                else:
                    video['valid'] = True
                    video.update(metadata.basic(f.name))

                if self.use_ts(tsn, f.name):
                    video['mime'] = 'video/x-tivo-mpeg-ts'
                else:
                    video['mime'] = 'video/x-tivo-mpeg'

                video['textSize'] = metadata.human_size(f.size)

            videos.append(video)

        logger.debug('mobileagent: %d useragent: %s' % (useragent.lower().find('mobile'), useragent.lower()))
        use_mobile = useragent.lower().find('mobile') > 0
        if use_html:
            if use_mobile:
                t = Template(HTML_CONTAINER_TEMPLATE_MOBILE, filter=EncodeUnicode)
            else:
                t = Template(HTML_CONTAINER_TEMPLATE, filter=EncodeUnicode)
        else:
            t = Template(XML_CONTAINER_TEMPLATE, filter=EncodeUnicode)

        t.container = handler.cname
        t.name = subcname
        t.total = total
        t.start = start
        t.videos = videos
        t.quote = quote
        t.escape = escape
        t.crc = zlib.crc32
        t.guid = config.getGUID()
        t.tivos = config.tivos
        t.tivo_names = config.tivo_names
        if use_html:
            handler.send_html(str(t))
        else:
            handler.send_xml(str(t))
Example #4
0
    def QueryContainer(self, handler, query):
        tsn = handler.headers.getheader('tsn', '')
        subcname = query['Container'][0]
        cname = subcname.split('/')[0]

        if (not cname in handler.server.containers or
            not self.get_local_path(handler, query)):
            handler.send_error(404)
            return

        container = handler.server.containers[cname]
        precache = container.get('precache', 'False').lower() == 'true'
        force_alpha = container.get('force_alpha', 'False').lower() == 'true'

        files, total, start = self.get_files(handler, query,
                                             self.video_file_filter,
                                             force_alpha)

        videos = []
        local_base_path = self.get_local_base_path(handler, query)
        for f in files:
            video = VideoDetails()
            mtime = f.mdate
            try:
                ltime = time.localtime(mtime)
            except:
                logger.warning('Bad file time on ' + unicode(f.name, 'utf-8'))
                mtime = int(time.time())
                ltime = time.localtime(mtime)
            video['captureDate'] = hex(mtime)
            video['textDate'] = time.strftime('%b %d, %Y', ltime)
            video['name'] = os.path.split(f.name)[1]
            video['path'] = f.name
            video['part_path'] = f.name.replace(local_base_path, '', 1)
            if not video['part_path'].startswith(os.path.sep):
                video['part_path'] = os.path.sep + video['part_path']
            video['title'] = os.path.split(f.name)[1]
            video['is_dir'] = f.isdir
            if video['is_dir']:
                video['small_path'] = subcname + '/' + video['name']
                video['total_items'] = self.__total_items(f.name)
            else:
                if precache or len(files) == 1 or f.name in transcode.info_cache:
                    video['valid'] = transcode.supported_format(f.name)
                    if video['valid']:
                        video.update(self.metadata_full(f.name, tsn))
                else:
                    video['valid'] = True
                    video.update(metadata.basic(f.name))

                video['textSize'] = ( '%.3f GB' %
                    (float(f.size) / (1024 ** 3)) )

            videos.append(video)

        t = Template(CONTAINER_TEMPLATE, filter=EncodeUnicode)
        t.container = cname
        t.name = subcname
        t.total = total
        t.start = start
        t.videos = videos
        t.quote = quote
        t.escape = escape
        t.crc = zlib.crc32
        t.guid = config.getGUID()
        t.tivos = config.tivos
        t.tivo_names = config.tivo_names
        handler.send_response(200)
        handler.send_header('Content-Type', 'text/xml')
        handler.send_header('Expires', '0')
        handler.end_headers()
        handler.wfile.write(t)
Example #5
0
    def QueryContainer(self, handler, query):
        tsn = handler.headers.getheader('tsn', '')
        subcname = query['Container'][0]

        if not self.get_local_path(handler, query):
            handler.send_error(404)
            return

        container = handler.container
        force_alpha = container.getboolean('force_alpha')
        ar = container.get('allow_recurse', 'auto').lower()
        if ar == 'auto':
            allow_recurse = not tsn or tsn[0] < '7'
        else:
            allow_recurse = ar in ('1', 'yes', 'true', 'on')

        files, total, start = self.get_files(handler, query,
                                             self.video_file_filter,
                                             force_alpha, allow_recurse)

        videos = []
        local_base_path = self.get_local_base_path(handler, query)
        for f in files:
            video = VideoDetails()
            mtime = f.mdate
            try:
                ltime = time.localtime(mtime)
            except:
                logger.warning('Bad file time on ' + unicode(f.name, 'utf-8'))
                mtime = time.time()
                ltime = time.localtime(mtime)
            video['captureDate'] = hex(int(mtime))
            video['textDate'] = time.strftime('%b %d, %Y', ltime)
            video['name'] = os.path.basename(f.name)
            video['path'] = f.name
            video['part_path'] = f.name.replace(local_base_path, '', 1)
            if not video['part_path'].startswith(os.path.sep):
                video['part_path'] = os.path.sep + video['part_path']
            video['title'] = os.path.basename(f.name)
            video['is_dir'] = f.isdir
            if video['is_dir']:
                video['small_path'] = subcname + '/' + video['name']
                video['total_items'] = self.__total_items(f.name)
            else:
                if len(files) == 1 or f.name in transcode.info_cache:
                    video['valid'] = transcode.supported_format(f.name)
                    if video['valid']:
                        video.update(self.metadata_full(f.name, tsn,
                                     mtime=mtime))
                        if len(files) == 1:
                            video['captureDate'] = hex(isogm(video['time']))
                else:
                    video['valid'] = True
                    video.update(metadata.basic(f.name, mtime))

                if self.use_ts(tsn, f.name):
                    video['mime'] = 'video/x-tivo-mpeg-ts'
                else:
                    video['mime'] = 'video/x-tivo-mpeg'

                video['textSize'] = metadata.human_size(f.size)

            videos.append(video)

        t = Template(XML_CONTAINER_TEMPLATE, filter=EncodeUnicode)
        t.container = handler.cname
        t.name = subcname
        t.total = total
        t.start = start
        t.videos = videos
        t.quote = quote
        t.escape = escape
        t.crc = zlib.crc32
        t.guid = config.getGUID()
        t.tivos = config.tivos
        handler.send_xml(str(t))
Example #6
0
    def metadata_full(self, full_path, tsn='', mime='', mtime=None):
        data = {}
        vInfo = transcode.video_info(full_path)

        if ((int(vInfo['vHeight']) >= 720 and config.getTivoHeight >= 720) or
            (int(vInfo['vWidth']) >= 1280 and config.getTivoWidth >= 1280)):
            data['showingBits'] = '4096'

        data.update(metadata.basic(full_path, mtime))
        if full_path[-5:].lower() == '.tivo':
            data.update(metadata.from_tivo(full_path))
        if full_path[-4:].lower() == '.wtv':
            data.update(metadata.from_mscore(vInfo['rawmeta']))

        if 'episodeNumber' in data:
            try:
                ep = int(data['episodeNumber'])
            except:
                ep = 0
            data['episodeNumber'] = str(ep)

        if config.getDebug() and 'vHost' not in data:
            compatible, reason = transcode.tivo_compatible(
                full_path, tsn, mime)
            if compatible:
                transcode_options = []
            else:
                transcode_options = transcode.transcode(
                    True, full_path, '', None, False, tsn, mime)
            data['vHost'] = (
                ['TRANSCODE=%s, %s' %
                 (['YES', 'NO'][compatible], reason)] + ['SOURCE INFO: '] + [
                     "%s=%s" % (k, v)
                     for k, v in sorted(vInfo.items(), reverse=True)
                 ] + ['TRANSCODE OPTIONS: '] + transcode_options +
                ['SOURCE FILE: ', os.path.basename(full_path)])

        now = datetime.utcnow()
        if 'time' in data:
            if data['time'].lower() == 'file':
                if not mtime:
                    mtime = os.path.getmtime(unicode(full_path, 'utf-8'))
                try:
                    now = datetime.utcfromtimestamp(mtime)
                except:
                    logger.warning('Bad file time on ' + full_path)
            elif data['time'].lower() == 'oad':
                now = isodt(data['originalAirDate'])
            else:
                try:
                    now = isodt(data['time'])
                except:
                    logger.warning('Bad time format: ' + data['time'] +
                                   ' , using current time')

        duration = self.__duration(full_path)
        duration_delta = timedelta(milliseconds=duration)
        min = duration_delta.seconds / 60
        sec = duration_delta.seconds % 60
        hours = min / 60
        min = min % 60

        data.update({
            'time':
            now.isoformat(),
            'startTime':
            now.isoformat(),
            'stopTime': (now + duration_delta).isoformat(),
            'size':
            self.__est_size(full_path, tsn, mime),
            'duration':
            duration,
            'iso_duration':
            ('P%sDT%sH%sM%sS' % (duration_delta.days, hours, min, sec))
        })

        return data
Example #7
0
    def QueryContainer(self, handler, query):
        tsn = handler.headers.getheader('tsn', '')
        subcname = query['Container'][0]

        if not self.get_local_path(handler, query):
            handler.send_error(404)
            return

        container = handler.container
        force_alpha = container.getboolean('force_alpha')
        ar = container.get('allow_recurse', 'auto').lower()
        if ar == 'auto':
            allow_recurse = not tsn or tsn[0] < '7'
        else:
            allow_recurse = ar in ('1', 'yes', 'true', 'on')

        files, total, start = self.get_files(handler, query,
                                             self.video_file_filter,
                                             force_alpha, allow_recurse)

        videos = []
        local_base_path = self.get_local_base_path(handler, query)
        for f in files:
            video = VideoDetails()
            mtime = f.mdate
            try:
                ltime = time.localtime(mtime)
            except:
                logger.warning('Bad file time on ' + unicode(f.name, 'utf-8'))
                mtime = time.time()
                ltime = time.localtime(mtime)
            video['captureDate'] = hex(int(mtime))
            video['textDate'] = time.strftime('%b %d, %Y', ltime)
            video['name'] = os.path.basename(f.name)
            video['path'] = f.name
            video['part_path'] = f.name.replace(local_base_path, '', 1)
            if not video['part_path'].startswith(os.path.sep):
                video['part_path'] = os.path.sep + video['part_path']
            video['title'] = os.path.basename(f.name)
            video['is_dir'] = f.isdir
            if video['is_dir']:
                video['small_path'] = subcname + '/' + video['name']
                video['total_items'] = self.__total_items(f.name)
            else:
                if len(files) == 1 or f.name in transcode.info_cache:
                    video['valid'] = transcode.supported_format(f.name)
                    if video['valid']:
                        video.update(
                            self.metadata_full(f.name, tsn, mtime=mtime))
                        if len(files) == 1:
                            video['captureDate'] = hex(isogm(video['time']))
                else:
                    video['valid'] = True
                    video.update(metadata.basic(f.name, mtime))

                if self.use_ts(tsn, f.name):
                    video['mime'] = 'video/x-tivo-mpeg-ts'
                else:
                    video['mime'] = 'video/x-tivo-mpeg'

                video['textSize'] = metadata.human_size(f.size)

            videos.append(video)

        t = Template(XML_CONTAINER_TEMPLATE, filter=EncodeUnicode)
        t.container = handler.cname
        t.name = subcname
        t.total = total
        t.start = start
        t.videos = videos
        t.quote = quote
        t.escape = escape
        t.crc = zlib.crc32
        t.guid = config.getGUID()
        t.tivos = config.tivos
        handler.send_xml(str(t))
Example #8
0
    def QueryContainer(self, handler, query):
        tsn = handler.headers.getheader('tsn', '')
        subcname = query['Container'][0]

        if not self.get_local_path(handler, query):
            handler.send_error(404)
            return

        container = handler.container
        precache = container.get('precache', 'False').lower() == 'true'
        force_alpha = container.get('force_alpha', 'False').lower() == 'true'
        use_html = query.get('Format', [''])[0].lower() == 'text/html'

        files, total, start = self.get_files(handler, query,
                                             self.video_file_filter,
                                             force_alpha)

        videos = []
        local_base_path = self.get_local_base_path(handler, query)
        for f in files:
            video = VideoDetails()
            mtime = f.mdate
            try:
                ltime = time.localtime(mtime)
            except:
                logger.warning('Bad file time on ' + unicode(f.name, 'utf-8'))
                mtime = int(time.time())
                ltime = time.localtime(mtime)
            video['captureDate'] = hex(mtime)
            video['textDate'] = time.strftime('%b %d, %Y', ltime)
            video['name'] = os.path.basename(f.name)
            video['path'] = f.name
            video['part_path'] = f.name.replace(local_base_path, '', 1)
            if not video['part_path'].startswith(os.path.sep):
                video['part_path'] = os.path.sep + video['part_path']
            video['title'] = os.path.basename(f.name)
            video['is_dir'] = f.isdir
            if video['is_dir']:
                video['small_path'] = subcname + '/' + video['name']
                video['total_items'] = self.__total_items(f.name)
            else:
                if precache or len(
                        files) == 1 or f.name in transcode.info_cache:
                    video['valid'] = transcode.supported_format(f.name)
                    if video['valid']:
                        video.update(self.metadata_full(f.name, tsn))
                        if len(files) == 1:
                            video['captureDate'] = hex(isogm(video['time']))
                else:
                    video['valid'] = True
                    video.update(metadata.basic(f.name))

                if config.hasTStivo(tsn):
                    video['mime'] = 'video/x-tivo-mpeg-ts'
                else:
                    video['mime'] = 'video/x-tivo-mpeg'

                video['textSize'] = ('%.3f GB' % (float(f.size) / (1024**3)))

            videos.append(video)

        if use_html:
            t = Template(HTML_CONTAINER_TEMPLATE, filter=EncodeUnicode)
        else:
            t = Template(XML_CONTAINER_TEMPLATE, filter=EncodeUnicode)
        t.container = handler.cname
        t.name = subcname
        t.total = total
        t.start = start
        t.videos = videos
        t.quote = quote
        t.escape = escape
        t.crc = zlib.crc32
        t.guid = config.getGUID()
        t.tivos = config.tivos
        t.tivo_names = config.tivo_names
        if use_html:
            handler.send_html(str(t))
        else:
            handler.send_xml(str(t))
Example #9
0
    def QueryContainer(self, handler, query):
        tsn = handler.headers.getheader('tsn', '')
        subcname = query['Container'][0]

        if not self.get_local_path(handler, query):
            handler.send_error(404)
            return

        container = handler.container
        force_alpha = container.getboolean('force_alpha')
        ar = container.get('allow_recurse', 'auto').lower()
        if ar == 'auto':
            allow_recurse = not tsn or tsn[0] < '7'
        else:
            allow_recurse = ar in ('1', 'yes', 'true', 'on')
        use_html = query.get('Format', [''])[0].lower() == 'text/html'

        files, total, start = self.get_files(handler, query,
                                             self.video_file_filter,
                                             force_alpha, allow_recurse)

        videos = []
        local_base_path = self.get_local_base_path(handler, query)
        resort = False
        for f in files:
            video = VideoDetails()
            mtime = f.mdate
            try:
                ltime = time.localtime(mtime)
            except:
                logger.warning('Bad file time on ' + unicode(f.name, 'utf-8'))
                mtime = time.time()
                ltime = time.localtime(mtime)
            video['captureDate'] = hex(int(mtime))
            video['textDate'] = time.strftime('%b %d, %Y', ltime)
            video['name'] = os.path.basename(f.name)
            video['path'] = f.name
            video['part_path'] = f.name.replace(local_base_path, '', 1)
            if not video['part_path'].startswith(os.path.sep):
                video['part_path'] = os.path.sep + video['part_path']
            video['title'] = os.path.basename(f.name)
            video['is_dir'] = f.isdir
            if video['is_dir']:
                video['small_path'] = subcname + '/' + video['name']
                video['total_items'] = self.__total_items(f.name)
            else:
                if len(files) == 1 or f.name in transcode.info_cache:
                    video['valid'] = transcode.supported_format(f.name)
                    if video['valid']:
                        video.update(self.metadata_full(f.name, tsn,
                                     mtime=mtime))
                        if len(files) == 1:
                            video['captureDate'] = hex(isogm(video['time']))
                else:
                    video['valid'] = True
                    video.update(metadata.basic(f.name, mtime))

                if 'time' in video and video['time'] != '':
                    if video['time'].lower() == 'oad':
                        video['time'] = video['originalAirDate']
                        resort = True
                    try:
                        video['captureDate'] = hex(isogm(video['time']))
                        video['textDate'] = time.strftime('%b %d, %Y', time.localtime(isogm(video['time'])))
                        resort = True
                    except:
                        logger.warning('Bad time format: "' + video['time'] +
                                       '", using current time')

                if self.use_ts(tsn, f.name):
                    video['mime'] = 'video/x-tivo-mpeg-ts'
                else:
                    video['mime'] = 'video/x-tivo-mpeg'

                video['textSize'] = metadata.human_size(f.size)

            videos.append(video)

        if use_html:
            t = Template(HTML_CONTAINER_TEMPLATE, filter=EncodeUnicode)
        else:
            t = Template(XML_CONTAINER_TEMPLATE, filter=EncodeUnicode)

        sortby = query.get('SortOrder', ['Normal'])[0].lower()
        t.sortby = sortby
        if use_html and resort:
            if sortby == 'capturedate':
                logger.info('re-sorting by captureDate, reverse=True')
                videos.sort(key=itemgetter('captureDate'), reverse=True)
            elif sortby == '!capturedate':
                logger.info('re-sorting by captureDate, reverse=False')
                videos.sort(key=itemgetter('captureDate'), reverse=False)

        t.container = handler.cname
        t.name = subcname
        t.total = total
        t.start = start
        t.videos = videos
        t.quote = quote
        t.escape = escape
        t.crc = zlib.crc32
        t.guid = config.getGUID()
        t.tivos = config.tivos
        if use_html:
            handler.send_html(str(t))
        else:
            handler.send_xml(str(t))
Example #10
0
    def QueryContainer(self, handler, query):
        tsn = handler.headers.getheader("tsn", "")
        subcname = query["Container"][0]

        if not self.get_local_path(handler, query):
            handler.send_error(404)
            return

        container = handler.container
        force_alpha = container.get("force_alpha", "False").lower() == "true"
        use_html = query.get("Format", [""])[0].lower() == "text/html"

        files, total, start = self.get_files(handler, query, self.video_file_filter, force_alpha)

        videos = []
        local_base_path = self.get_local_base_path(handler, query)
        for f in files:
            video = VideoDetails()
            mtime = f.mdate
            try:
                ltime = time.localtime(mtime)
            except:
                logger.warning("Bad file time on " + unicode(f.name, "utf-8"))
                mtime = int(time.time())
                ltime = time.localtime(mtime)
            video["captureDate"] = hex(mtime)
            video["textDate"] = time.strftime("%b %d, %Y", ltime)
            video["name"] = os.path.basename(f.name)
            video["path"] = f.name
            video["part_path"] = f.name.replace(local_base_path, "", 1)
            if not video["part_path"].startswith(os.path.sep):
                video["part_path"] = os.path.sep + video["part_path"]
            video["title"] = os.path.basename(f.name)
            video["is_dir"] = f.isdir
            if video["is_dir"]:
                video["small_path"] = subcname + "/" + video["name"]
                video["total_items"] = self.__total_items(f.name)
            else:
                if len(files) == 1 or f.name in transcode.info_cache:
                    video["valid"] = transcode.supported_format(f.name)
                    if video["valid"]:
                        video.update(self.metadata_full(f.name, tsn))
                        if len(files) == 1:
                            video["captureDate"] = hex(isogm(video["time"]))
                else:
                    video["valid"] = True
                    video.update(metadata.basic(f.name))

                if self.use_ts(tsn, f.name):
                    video["mime"] = "video/x-tivo-mpeg-ts"
                else:
                    video["mime"] = "video/x-tivo-mpeg"

                video["textSize"] = "%.3f GB" % (float(f.size) / (1024 ** 3))

            videos.append(video)

        if use_html:
            t = Template(HTML_CONTAINER_TEMPLATE, filter=EncodeUnicode)
        else:
            t = Template(XML_CONTAINER_TEMPLATE, filter=EncodeUnicode)
        t.container = handler.cname
        t.name = subcname
        t.total = total
        t.start = start
        t.videos = videos
        t.quote = quote
        t.escape = escape
        t.crc = zlib.crc32
        t.guid = config.getGUID()
        t.tivos = config.tivos
        t.tivo_names = config.tivo_names
        if use_html:
            handler.send_html(str(t))
        else:
            handler.send_xml(str(t))
Example #11
0
    def metadata_full(self, full_path, tsn="", mime=""):
        data = {}
        vInfo = transcode.video_info(full_path)

        if (int(vInfo["vHeight"]) >= 720 and config.getTivoHeight >= 720) or (
            int(vInfo["vWidth"]) >= 1280 and config.getTivoWidth >= 1280
        ):
            data["showingBits"] = "4096"

        data.update(metadata.basic(full_path))
        if full_path[-5:].lower() == ".tivo":
            data.update(metadata.from_tivo(full_path))
        if full_path[-4:].lower() == ".wtv":
            data.update(metadata.from_mscore(vInfo["rawmeta"]))

        if "episodeNumber" in data:
            try:
                ep = int(data["episodeNumber"])
            except:
                ep = 0
            data["episodeNumber"] = str(ep)

        if config.getDebug() and "vHost" not in data:
            compatible, reason = transcode.tivo_compatible(full_path, tsn, mime)
            if compatible:
                transcode_options = {}
            else:
                transcode_options = transcode.transcode(True, full_path, "", tsn, mime)
            data["vHost"] = (
                ["TRANSCODE=%s, %s" % (["YES", "NO"][compatible], reason)]
                + ["SOURCE INFO: "]
                + ["%s=%s" % (k, v) for k, v in sorted(vInfo.items(), reverse=True)]
                + ["TRANSCODE OPTIONS: "]
                + ["%s" % (v) for k, v in transcode_options.items()]
                + ["SOURCE FILE: ", os.path.basename(full_path)]
            )

        now = datetime.utcnow()
        if "time" in data:
            if data["time"].lower() == "file":
                mtime = os.stat(unicode(full_path, "utf-8")).st_mtime
                if mtime < 0:
                    mtime = 0
                try:
                    now = datetime.utcfromtimestamp(mtime)
                except:
                    logger.warning("Bad file time on " + full_path)
            elif data["time"].lower() == "oad":
                now = isodt(data["originalAirDate"])
            else:
                try:
                    now = isodt(data["time"])
                except:
                    logger.warning("Bad time format: " + data["time"] + " , using current time")

        duration = self.__duration(full_path)
        duration_delta = timedelta(milliseconds=duration)
        min = duration_delta.seconds / 60
        sec = duration_delta.seconds % 60
        hours = min / 60
        min = min % 60

        data.update(
            {
                "time": now.isoformat(),
                "startTime": now.isoformat(),
                "stopTime": (now + duration_delta).isoformat(),
                "size": self.__est_size(full_path, tsn, mime),
                "duration": duration,
                "iso_duration": ("P%sDT%sH%sM%sS" % (duration_delta.days, hours, min, sec)),
            }
        )

        return data
Example #12
0
    def __init__(self, opts, name, root, vidlist, harvesters):
        self.name = name
        self.title = name
        self.opts = opts.copy()
        self.count = 0
        self.root = root
        self.videoDir = VideoDir(opts, "", "", root, name)

        tree = myWalk(root)

        sharedirs = {"": self.videoDir}
        shareopts = {"": self.opts}

        for path, dirs, files in tree:
            rpath = path[len(root):]
            if rpath.startswith(os.path.sep): rpath = rpath[1:]
            if rpath not in sharedirs: continue
            vl = sharedirs[rpath]
            lopts = shareopts[rpath]
            Config.addLocalOpts(lopts, root, rpath)
            vl.setOpts(lopts)

            for name in dirs:
                if name.startswith("."): continue
                meta = metadata.from_text(os.path.join(path, name, "folder"),
                                          lopts['metamergefiles'],
                                          lopts['metamergelines'])
                d = VideoDir(lopts, name, rpath, path, self.name)
                d.setMeta(meta)
                vl.addDir(d)
                sharedirs[os.path.join(rpath, name)] = d
                shareopts[os.path.join(rpath, name)] = lopts.copy()

            for name in files:
                if name.startswith("."): continue
                if os.path.splitext(name)[1].lower() in lopts['goodexts']:
                    fid = fileId(os.path.join(path, name))
                    if fid != None:
                        vf = vidlist.findVideo(fid)
                    else:
                        vf = None

                    if vf == None:
                        vf = VideoFile(lopts, path, name, fid)
                        vidlist.addVideo(vf)

                        meta = metadata.from_text(os.path.join(path, name),
                                                  lopts['metamergefiles'],
                                                  lopts['metamergelines'])
                        if not 'title' in meta:
                            meta = metadata.basic(os.path.join(path, name))
                        vf.setMeta(meta)

                        vl.addVideo(vf)
                        self.count += 1

                        for h in harvesters:
                            h.harvest(vf)

                    else:
                        vl.addVideo(vf, path=path, fn=name)
                        self.count += 1

            vl.sort()