Exemple #1
0
    def add_format(self, codec):
        transcode_dir = transcode.transcode(self.flac_dir, codec, output_dir=self.browser.data_dir)
        # create torrent in a temporary directory, then move it to the watch dir.
        # some clients (i.e. deluge) delete torrents after adding them from the watch dir.
        # it's difficult to upload a non-existent torrent, so we do it this way instead. 
        torrent = transcode.make_torrent(transcode_dir, tempfile.mkdtemp(), self.browser.tracker, self.browser.passkey)

        self.browser.goto(self.upload_url)
        # select the last form on the page
        self.browser.select_form(nr=len(list(self.browser.forms()))-1) 

        # add the torrent
        self.browser.find_control('file_input').add_file(open(torrent), 'text/plain', os.path.basename(torrent))

        # specify edition information
        if len(self.editions) > 0:
            if len(self.editions) > 1:
                #TODO select edition
                raise NotImplementedError('Releases with more than one edition are currently unsupported.')
            try:
                edition = self.torrent.edition
            except:
                edition = self.editions[0]
            self.browser.find_control('remaster').set_single('1')
    
            if edition['year']:
                self.browser['remaster_year'] = edition['year']
            if edition['title']:
                self.browser['remaster_title'] = edition['title']
            if edition['catalog_number']:
                self.browser['remaster_catalogue_number'] = edition['catalog_number']
            if edition['record_label']:
                self.browser['remaster_record_label'] = edition['record_label']

        # specify format
        self.browser.find_control('format').set('1', encoders[codec]['format'])

        # specify bitrate
        self.browser.find_control('bitrate').set('1', encoders[codec]['bitrate'])

        # specify media
        self.browser.find_control('media').set('1', self.media)

        # specify release description
        self.browser['release_desc'] = 'Created with [url=http://github.com/zacharydenton/whatbetter/]whatbetter[/url].'

        # submit the form
        response = self.browser.submit()

        # copy torrent to watch dir
        shutil.copy(torrent, self.browser.torrent_dir)
        
        return response
Exemple #2
0
    def create_formats(self):
        self.formats = defaultdict(list)
        self.zips = []
        for encoding in encodings:
            transcode_dir = os.path.join(self.path, slugify(encoding))
            zip_file = os.path.join(
                self.path,
                slugify("{title} - {encoding}".format(
                    title=self.title, encoding=encoding)) + ".zip")
            if not os.path.isdir(transcode_dir):
                if encoding == "FLAC":
                    shutil.copytree(self.original_path, transcode_dir)
                else:
                    os.makedirs(transcode_dir)
                    transcode.transcode(self.original_path,
                                        encoding,
                                        output_dir=transcode_dir)

                # build the zip
                subprocess.call('zip -r "{0}" "{1}"'.format(
                    zip_file, transcode_dir),
                                shell=True)

                # slugify filenames
                for filename in os.listdir(transcode_dir):
                    name, extension = os.path.splitext(filename)
                    shutil.move(
                        os.path.join(transcode_dir, filename),
                        os.path.join(transcode_dir,
                                     slugify(name) + extension))

            for filename in glob.glob(os.path.join(transcode_dir, "*")):
                try:
                    self.formats[slugify(encoding)].append(
                        Song(filename, encoding=encoding))
                except:
                    pass
            self.zips.append((os.path.basename(zip_file), encoding))
Exemple #3
0
   print("Project = {p}".format(p = pj))
   # Get an overview for all open issues
   issues = []
   issues = Retrieve.search_open_issue(url, user, pj, loginToken)

   ws = write_ws.create_ws(wb, pj, keys)

   #Get more detail for each issue
   row = 2  #start with 2 as 1st row has been filled
   for i in issues:
      id = i.get('id')
      #print("ID = {id}".format(id = id))
      xsync = "false"
      #detail = Retrieve.issue_detail(url, user, project, loginToken, issues[0].get('id'), xsync)
      detail = Retrieve.issue_detail(url, user, pj, loginToken, id, xsync)
      coded_detail = transcode.transcode(detail)
      #print('type = {t}'.format(t = type(coded_detail.keys())))

      #convert the coded detail in dict type to a list in str
      d_list = list(coded_detail.values())
      write_ws.write2ws(d_list, ws, row)
      row = row + 1


wb.save(configuration.name_report) #save it

#history = detail.get('history')

#print('History = {c}'.format(c = history))
#print('type = {t}'.format(t= type(history)))
#print('type = {t}'.format(t= type(history[0])))
Exemple #4
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
Exemple #5
0
    def send_file(self, handler, path, query):
        mime = 'video/x-tivo-mpeg'
        tsn = handler.headers.getheader('tsn', '')
        tivo_name = config.tivo_names.get(tsn, tsn)

        is_tivo_file = (path[-5:].lower() == '.tivo')

        if 'Format' in query:
            mime = query['Format'][0]

        needs_tivodecode = (is_tivo_file and mime == 'video/mpeg')
        compatible = (not needs_tivodecode and
                      transcode.tivo_compatible(path, tsn, mime)[0])

        try:  # "bytes=XXX-"
            offset = int(handler.headers.getheader('Range')[6:-1])
        except:
            offset = 0

        if needs_tivodecode:
            valid = bool(config.get_bin('tivodecode') and
                         config.get_server('tivo_mak'))
        else:
            valid = True

        if valid and offset:
            valid = ((compatible and offset < os.stat(path).st_size) or
                     (not compatible and transcode.is_resumable(path, offset)))

        #faking = (mime in ['video/x-tivo-mpeg-ts', 'video/x-tivo-mpeg'] and
        faking = (mime == 'video/x-tivo-mpeg' and
                  not (is_tivo_file and compatible))
        fname = unicode(path, 'utf-8')
        thead = ''
        if faking:
            thead = self.tivo_header(tsn, path, mime)
        if compatible:
            size = os.stat(fname).st_size + len(thead)
            handler.send_response(200)
            handler.send_header('Content-Length', size - offset)
            handler.send_header('Content-Range', 'bytes %d-%d/%d' % 
                                (offset, size - offset - 1, size))
        else:
            handler.send_response(206)
            handler.send_header('Transfer-Encoding', 'chunked')
        handler.send_header('Content-Type', mime)
        handler.end_headers()

        logger.info('[%s] Start sending "%s" to %s' %
                    (time.strftime('%d/%b/%Y %H:%M:%S'), fname, tivo_name))
        start = time.time()
        count = 0

        if valid:
            if compatible:
                if faking and not offset:
                    handler.wfile.write(thead)
                logger.debug('"%s" is tivo compatible' % fname)
                f = open(fname, 'rb')
                try:
                    if mime == 'video/mp4':
                        count = qtfaststart.process(f, handler.wfile, offset)
                    else:
                        if offset:
                            offset -= len(thead)
                            f.seek(offset)
                        while True:
                            block = f.read(512 * 1024)
                            if not block:
                                break
                            handler.wfile.write(block)
                            count += len(block)
                except Exception, msg:
                    logger.info(msg)
                f.close()
            else:
                logger.debug('"%s" is not tivo compatible' % fname)
                if offset:
                    count = transcode.resume_transfer(path, handler.wfile, 
                                                      offset)
                else:
                    count = transcode.transcode(False, path, handler.wfile,
                                                tsn, mime, thead)
Exemple #6
0
    def add_format(self, codec):
        transcode_dir = transcode.transcode(self.flac_dir,
                                            codec,
                                            output_dir=self.browser.data_dir)
        # create torrent in a temporary directory, then move it to the watch dir.
        # some clients (i.e. deluge) delete torrents after adding them from the watch dir.
        # it's difficult to upload a non-existent torrent, so we do it this way instead.
        torrent = transcode.make_torrent(transcode_dir, tempfile.mkdtemp(),
                                         self.browser.tracker,
                                         self.browser.passkey)

        self.browser.goto(self.upload_url)
        # select the last form on the page
        self.browser.select_form(nr=len(list(self.browser.forms())) - 1)

        # add the torrent
        self.browser.find_control('file_input').add_file(
            open(torrent), 'text/plain', os.path.basename(torrent))

        # specify edition information
        if len(self.editions) > 0:
            if len(self.editions) > 1:
                #TODO select edition
                raise NotImplementedError(
                    'Releases with more than one edition are currently unsupported.'
                )
            try:
                edition = self.torrent.edition
            except:
                edition = self.editions[0]
            self.browser.find_control('remaster').set_single('1')

            if edition['year']:
                self.browser['remaster_year'] = edition['year']
            if edition['title']:
                self.browser['remaster_title'] = edition['title']
            if edition['catalog_number']:
                self.browser['remaster_catalogue_number'] = edition[
                    'catalog_number']
            if edition['record_label']:
                self.browser['remaster_record_label'] = edition['record_label']

        # specify format
        self.browser.find_control('format').set('1', encoders[codec]['format'])

        # specify bitrate
        self.browser.find_control('bitrate').set('1',
                                                 encoders[codec]['bitrate'])

        # specify media
        self.browser.find_control('media').set('1', self.media)

        # specify release description
        self.browser[
            'release_desc'] = 'Created with [url=http://github.com/zacharydenton/whatbetter/]whatbetter[/url].'

        # submit the form
        response = self.browser.submit()

        # copy torrent to watch dir
        shutil.copy(torrent, self.browser.torrent_dir)

        return response
Exemple #7
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
Exemple #8
0
                        tivolibre.kill()
                        tivolibre.wait()

                    logger.info(msg)

                f.close()
            else:
                status[tivo_name][path]['transcoding'] = True
                logger.debug('"%s" is not tivo compatible' % fname)
                if offset:
                    count = transcode.resume_transfer(path, handler.wfile,
                                                      offset,
                                                      status[tivo_name][path])
                else:
                    count = transcode.transcode(False, path, handler.wfile,
                                                status[tivo_name][path],
                                                is_tivo_file, tsn, mime, thead)

            end_time = time.time()
            elapsed = end_time - status[tivo_name][path]['start']
            rate = count * 8.0 / elapsed

            status[tivo_name][path]['active'] = False
            status[tivo_name][path]['end'] = end_time
            status[tivo_name][path]['rate'] = rate

            logger.info('[%s] Done sending "%s" to %s, %d bytes, %.2f Mb/s' %
                        (time.strftime('%d/%b/%Y %H:%M:%S'), fname, tivo_name,
                         count, rate * 1024 * 1024))

        else:
Exemple #9
0
    def send_file(self, handler, path, query):
        mime = 'video/x-tivo-mpeg'
        tsn = handler.headers.getheader('tsn', '')
        try:
            assert (tsn)
            tivo_name = config.tivos[tsn].get('name', tsn)
        except:
            tivo_name = handler.address_string()

        is_tivo_file = (path[-5:].lower() == '.tivo')

        if 'Format' in query:
            mime = query['Format'][0]

        needs_tivodecode = (is_tivo_file and mime == 'video/mpeg')
        compatible = (not needs_tivodecode
                      and transcode.tivo_compatible(path, tsn, mime)[0])

        try:  # "bytes=XXX-"
            offset = int(handler.headers.getheader('Range')[6:-1])
        except:
            offset = 0

        if needs_tivodecode:
            valid = bool(
                config.get_bin('tivodecode') and config.get_server('tivo_mak'))
        else:
            valid = True

        if valid and offset:
            valid = ((compatible and offset < os.path.getsize(path)) or
                     (not compatible and transcode.is_resumable(path, offset)))

        #faking = (mime in ['video/x-tivo-mpeg-ts', 'video/x-tivo-mpeg'] and
        faking = (mime == 'video/x-tivo-mpeg'
                  and not (is_tivo_file and compatible))
        fname = unicode(path, 'utf-8')
        thead = ''
        if faking:
            thead = self.tivo_header(tsn, path, mime)
        if compatible:
            size = os.path.getsize(fname) + len(thead)
            handler.send_response(200)
            handler.send_header('Content-Length', size - offset)
            handler.send_header(
                'Content-Range',
                'bytes %d-%d/%d' % (offset, size - offset - 1, size))
        else:
            handler.send_response(206)
            handler.send_header('Transfer-Encoding', 'chunked')
        handler.send_header('Content-Type', mime)
        handler.end_headers()

        logger.info('[%s] Start sending "%s" to %s' %
                    (time.strftime('%d/%b/%Y %H:%M:%S'), fname, tivo_name))
        start = time.time()
        count = 0

        if valid:
            if compatible:
                if faking and not offset:
                    handler.wfile.write(thead)
                logger.debug('"%s" is tivo compatible' % fname)
                f = open(fname, 'rb')
                try:
                    if mime == 'video/mp4':
                        count = qtfaststart.process(f, handler.wfile, offset)
                    else:
                        if offset:
                            offset -= len(thead)
                            f.seek(offset)
                        while True:
                            block = f.read(512 * 1024)
                            if not block:
                                break
                            handler.wfile.write(block)
                            count += len(block)
                except Exception, msg:
                    logger.info(msg)
                f.close()
            else:
                logger.debug('"%s" is not tivo compatible' % fname)
                if offset:
                    count = transcode.resume_transfer(path, handler.wfile,
                                                      offset)
                else:
                    count = transcode.transcode(False, path, handler.wfile,
                                                tsn, mime, thead)
Exemple #10
0
    def process_format(self, torrent, path, oformat):
        """
        Transcode and upload a single format.

        :param torrent: A `dict` as returned by `api.get_torrent`.
        :param path: A `Path` to the directory containing the source flac files.
        :param oformat: The output format.

        :returns: `True` on success, `False` otherwise.
        """
        print("\tProcessing Format {}:".format(oformat.NAME))

        transcode_dir = util.generate_transcode_name(torrent, oformat)
        dst_path = self.output_dir / transcode_dir
        tfile = Path(self.tmp.name) / (transcode_dir + ".torrent")

        tfile_new = self.torrent_dir / tfile.name
        if tfile_new.exists():
            msg = "\t\tError, {} allready exists.".format(tfile_new)
            if self.continue_on_error:
                print(msg)
                return False
            else:
                raise ApolloBetterError(msg)

        print("\t\tTranscoding...")
        try:
            transcode(path, dst_path, oformat)
        except TranscodeError as e:
            if self.continue_on_error:
                print("\t\tError: ", e)
                return False
            else:
                raise e

        print("\t\tCreating torrent file...")
        util.create_torrent_file(tfile,
                                 dst_path,
                                 ANNOUNCE_URL,
                                 self.api.passkey,
                                 "APL",
                                 overwrite=True)

        print("\t\tUploading torrent...")
        description = util.generate_description(
            torrent["torrent"]["id"],
            sorted(path.glob("**/*" + formats.FormatFlac.SUFFIX))[0], oformat)
        try:
            self.api.add_format(torrent, oformat, tfile, description)
        except ApiError as e:
            shutil.rmtree(dst_path)
            os.remove(tfile)
            if self.continue_on_error:
                print("Error on upload:{}")
                return False
            else:
                raise e

        print("\t\tMoving torrent file...")
        shutil.copyfile(tfile, tfile_new)

        print("\t\tDone.")
        return True
exercise = inquirer.prompt(menu)['menu']

if '1)' in exercise:
    getData()

elif '2)' in exercise:
    print('Enter the path of the file you want to rename:')
    input_file = str(input())
    print('\nEnter the new name:')
    new_name = str(input())
    rename(input_file, new_name)

elif '3)' in exercise:
    print('Enter the path of the input you want to resize:')
    input_file = str(input())
    print(
        '\nDefine the width and height as (360x240) or the resolution as (720p):'
    )
    while 1:
        size = str(input())
        if 'p' in size or 'x' in size:
            print('\nSize: ', size)
            resize(size, input_file)
            break
        else:
            print('Invalid option, choose another size')

elif '4)' in exercise:
    print('Video codec MPEG2, audio codec ACC')
    transcode()
Exemple #12
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
Exemple #13
0
    def send_file(self, handler, path, query):
        mime = "video/x-tivo-mpeg"
        tsn = handler.headers.getheader("tsn", "")
        tivo_name = config.tivo_names.get(tsn, tsn)

        is_tivo_file = path[-5:].lower() == ".tivo"

        if "Format" in query:
            mime = query["Format"][0]

        needs_tivodecode = is_tivo_file and mime == "video/mpeg"
        compatible = not needs_tivodecode and transcode.tivo_compatible(path, tsn, mime)[0]

        try:  # "bytes=XXX-"
            offset = int(handler.headers.getheader("Range")[6:-1])
        except:
            offset = 0

        if needs_tivodecode:
            valid = bool(config.get_bin("tivodecode") and config.get_server("tivo_mak"))
        else:
            valid = True

        if valid and offset:
            valid = (compatible and offset < os.stat(path).st_size) or (
                not compatible and transcode.is_resumable(path, offset)
            )

        # faking = (mime in ['video/x-tivo-mpeg-ts', 'video/x-tivo-mpeg'] and
        faking = mime == "video/x-tivo-mpeg" and not (is_tivo_file and compatible)
        fname = unicode(path, "utf-8")
        thead = ""
        if faking:
            thead = self.tivo_header(tsn, path, mime)
        if compatible:
            size = os.stat(fname).st_size + len(thead)
            handler.send_response(200)
            handler.send_header("Content-Length", size - offset)
            handler.send_header("Content-Range", "bytes %d-%d/%d" % (offset, size - offset - 1, size))
        else:
            handler.send_response(206)
            handler.send_header("Transfer-Encoding", "chunked")
        handler.send_header("Content-Type", mime)
        handler.send_header("Connection", "close")
        handler.end_headers()

        logger.info('[%s] Start sending "%s" to %s' % (time.strftime("%d/%b/%Y %H:%M:%S"), fname, tivo_name))
        start = time.time()
        count = 0

        if valid:
            if compatible:
                if faking and not offset:
                    handler.wfile.write(thead)
                logger.debug('"%s" is tivo compatible' % fname)
                f = open(fname, "rb")
                try:
                    if mime == "video/mp4":
                        count = qtfaststart.process(f, handler.wfile, offset)
                    else:
                        if offset:
                            offset -= len(thead)
                            f.seek(offset)
                        while True:
                            block = f.read(512 * 1024)
                            if not block:
                                break
                            handler.wfile.write(block)
                            count += len(block)
                except Exception, msg:
                    logger.info(msg)
                f.close()
            else:
                logger.debug('"%s" is not tivo compatible' % fname)
                if offset:
                    count = transcode.resume_transfer(path, handler.wfile, offset)
                else:
                    count = transcode.transcode(False, path, handler.wfile, tsn, mime, thead)
Exemple #14
0
def extract(vrec):
    start_dt = vrec.start_dt
    start_dt_str = start_dt.strftime('%Y-%m-%d_%H:%M:%S')
    out_dir = os.path.join(config['main']['output_dir'],
                           '{:04d}'.format(start_dt.year),
                           '{:02d}'.format(start_dt.month),
                           '{:02d}'.format(start_dt.day))
    try:
        os.makedirs(out_dir, mode=0o750)
    except FileExistsError:
        pass

    in_fpath = os.path.join(os.path.dirname(vrec._h_idx_file.name),
                            'hiv{:05d}.mp4'.format(vrec.section.idx))
    converter = config['main']['converter']
    out_fmt = config['main']['output_format'] if converter else 'mp4'
    out_fname = 'rec_{}.{}'.format(start_dt_str, out_fmt)
    out_fpath = os.path.join(out_dir, out_fname)
    out_fpath_skip = out_fpath + '.skip'

    # We want FileExistsError propagated.
    # open(fpath, 'x') leaves a 0-length file which should be deleted before
    # we start extraction.
    for fpath in (out_fpath, out_fpath_skip):
        open(fpath, 'x')
        os.remove(fpath)

    # Create a temp file with just the portion of the stream we need
    with NamedTemporaryFile() as temp:
        with open(in_fpath, 'rb') as inpt:
            inpt.seek(vrec.start_offset)
            left = vrec.length
            while left > 0:
                buf = inpt.read(max(16 * 1024, left))
                left -= len(buf)
                temp.write(buf)

        temp.flush()
        temp_fpath = temp.name

        if config.getboolean('main', 'analyze_motion'):
            from motion import has_motion
            if not has_motion(temp_fpath):
                logger.info('No motion detected in {}, skipping'
                            .format(temp_fpath))
                open(out_fpath_skip, 'x')
                return

        logger.info('Extracting video record from ' + start_dt_str)
        logger.debug('Reading from {}, start {}, end {}'
                     .format(in_fpath,
                             log_int(vrec.start_offset),
                             log_int(vrec.start_offset + vrec.length)))

        if converter:
            xcoder_args = config['advanced']['converter_args'].split()
            transcode(temp_fpath, out_fpath,
                      converter=converter,
                      additional_flags=xcoder_args)
        else:
            logger.debug('Saving original stream to {}'.format(out_fpath))
            copyfile(temp_fpath, out_fpath)

    # Create a snapshot
    snap_fmt = config['main']['snapshot_format']
    if snap_fmt:
        fname_snap = 'snap_{}.{}'.format(start_dt_str, snap_fmt)
        out_fpath_snap = os.path.join(out_dir, fname_snap)
        ss = vrec.duration * config.getfloat('advanced', 'snapshot_pos')

        logger.info('Extracting snapshot from {}'.format(out_fpath))

        xcoder_args = config['advanced']['converter_args_snap'].split()
        xcoder_args += ['-ss', str(ss)]
        transcode(out_fpath, out_fpath_snap,
                  converter=converter,
                  additional_flags=xcoder_args)
Exemple #15
0
import hashlib
import getpass
import transcode as tran

DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/-_@.:,;!"§$%&/()=?üöäÜÖÄ'


def hashSHA1(param):
    # hash parameter with sha1 to hex encoded sting
    return hashlib.sha1(param.encode('utf-8')).hexdigest()


def inp():
    keyw = str(input("Enter Keyword: "))
    while 1:
        print("Enter Master Password")
        master1 = str(getpass.getpass())
        print("Enter Master Password again")
        master2 = str(getpass.getpass())
        if master1 == master2:
            key_and_master = keyw + master1
            break
        else:
            print("Passwords did not match, try again")
    return key_and_master

passw = hashSHA1(inp())
passw = tran.transcode(passw, DIGITS, tran.BASE16_DIGITS)
print(passw)
Exemple #16
0
    files = [i for i in os.listdir(path)
             if i.endswith('.mp4')]  # avoid random files
    files = [(s + 1, i) for (s, i) in enumerate(files)
             ]  #Make a enumerated list of the files in the folder
    return iodir(str(file_path[0]), path, files)


def check_ext_name(name):
    split = name.split('.')
    #Check if there is extension
    if (len(split) > 1):
        file_extension = split.pop()
    else:
        file_extension = None
    return split[0], file_extension


if __name__ == "__main__":
    dyr = setDir()  #set directories
    x = int(input("[1]Transcode\n[2]Multiple Video\n[3]Stream\n"))
    while not x == EXIT:
        if x == TRANSCODE:
            dyr.chooseinput(var='file')
            transcode.transcode(dyr.outputFolder, dyr.inp)
        elif x == MULTIPLE:
            dyr.chooseinput(var='folder')
            multipleVideo(dyr.outputFolder, dyr.files)
        elif x == STREAM:
            stream(dyr.path / "cut_BBB.mp4")
        x = int(input("[1]Transcode\n[2]Multiple Video\n[3]Stream\n"))