Ejemplo n.º 1
0
Archivo: up.py Proyecto: pdool/free-hls
def main():

    title = argv[2] if argv[2] else os.path.splitext(os.path.basename(
        argv[1]))[0]
    tmpdir = os.path.dirname(os.path.abspath(__file__)) + '/tmp'
    command = command_generator(os.path.abspath(argv[1]))

    if sameparams(tmpdir, command):
        os.chdir(tmpdir)
    else:
        os.mkdir(tmpdir)
        os.chdir(tmpdir)
        os.system(command)
        open('command.sh', 'w').write(command)

    failures, completions = 0, 0
    lines = encrypt(open('out.m3u8', 'r').read())

    #TODO
    for file in tsfiles(lines):
        if os.path.getsize(file) >= upload_limit[_('UPLOAD_DRIVE')]:
            print('file too large: %s' % file)
            exit(1)

    executor = ThreadPoolExecutor(max_workers=10)
    futures = {
        executor.submit(uploader(), chunk): chunk
        for chunk in tsfiles(lines)
    }

    for future in as_completed(futures):
        completions += 1
        result = future.result()

        if not result:
            failures += 1
            print('[%s/%s] Uploaded failed: %s' %
                  (completions, len(futures), futures[future]))
            continue

        lines = lines.replace(futures[future], result)
        print('[%s/%s] Uploaded %s to %s' %
              (completions, len(futures), futures[future], result))

    print('\n')

    #Write to file
    open('out.m3u8', 'w').write(lines)

    if not failures:
        publish(lines, title)
    else:
        print('Partially successful: %d/%d' %
              (completions, completions - failures))
        print('You can re-execute this program with the same parameters')
Ejemplo n.º 2
0
Archivo: up.py Proyecto: pdool/free-hls
def encrypt(code):
    if not _('ENCRYPTION') == 'YES':
        return code

    for file in tsfiles(code):
        if file.startswith('enc.'):
            continue

        print('Encrypting %s to enc.%s ... ' % (file, file), end='')
        key = exec(['openssl', 'rand', '16']).hex()
        iv = execstr(['openssl', 'rand', '-hex', '16'])
        exec([
            'openssl', 'aes-128-cbc', '-e', '-in', file, '-out',
            'enc.%s' % file, '-p', '-nosalt', '-iv', iv, '-K', key
        ])

        key_id = api('POST', 'key', {'iv': iv, 'key': key})
        if not key_id:
            print('failed')
            open('out.m3u8', 'w').write(code)
            exit()

        print('done')
        code = re.sub(
            '(#EXTINF:.+$[\\r\\n]+^%s$)' % file,
            '#EXT-X-KEY:METHOD=AES-128,URI="%s/play/%s.key",IV=0x%s\n\\1' %
            (_('APIURL'), key_id, iv), code, 1, re.M)
        code = code.replace(file, 'enc.%s' % file)

    open('out.m3u8', 'w').write(code)
    return code
Ejemplo n.º 3
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('file', type=str, help='video file')
    parser.add_argument('title', type=str, nargs='?', help='post title')
    parser.add_argument('time',
                        type=int,
                        nargs='?',
                        help='time for pre segment',
                        default=0)
    parser.add_argument('-c, --config',
                        type=str,
                        dest='config',
                        help='change the configuration file path')
    args = parser.parse_args()

    load_dotenv(args.config)
    tmpdir = path.dirname(path.abspath(__file__)) + '/tmp'
    command = genslice(path.abspath(args.file), args.time)

    if sameparams(tmpdir, command):
        os.chdir(tmpdir)
    else:
        os.mkdir(tmpdir)
        os.chdir(tmpdir)
        os.system(command)
        open('command.sh', 'w').write(command)

    failures, completions = 0, 0
    lines = encrypt(repairer(open('out.m3u8', 'r').read()))
    executor = ThreadPoolExecutor(max_workers=15)
    futures = {
        executor.submit(uploader().handle, chunk): chunk
        for chunk in tsfiles(lines)
    }

    for future in as_completed(futures):
        completions += 1
        result = future.result()

        if not result:
            failures += 1
            print('[%s/%s] Uploaded failed: %s' %
                  (completions, len(futures), futures[future]))
            continue

        lines = lines.replace(futures[future], result)
        print('[%s/%s] Uploaded %s to %s' %
              (completions, len(futures), futures[future], result))

    #Write to file
    open('out.m3u8', 'w').write(lines)
    open('params.json', 'w').write(json.dumps(uploader().params()))

    if failures:
        print('Partially successful: %d/%d' %
              (completions - failures, completions))
        print('You can re-execute this program with the same parameters')
        exit(2)

    publish(lines, args.title or path.splitext(path.basename(args.file))[0])
Ejemplo n.º 4
0
def checker(code):
    flag = False
    limit = uploader().MAX_BYTES

    for file in tsfiles(code):
        if os.path.getsize(file) > limit:
            flag = True
            print('File too large: tmp/%s' % file)

    return exit(1) if flag else code
Ejemplo n.º 5
0
def repairer(code):
    limit = uploader().MAX_BYTES

    for file in tsfiles(code):
        if path.getsize(file) > limit:
            tmp = 'rep.%s' % file
            os.system(genrepair(file, tmp, limit * 8))
            os.rename(tmp, file)

            if path.getsize(file) > limit:
                open('out.m3u8', 'w').write(code)
                print(f'File too large: tmp/{file}')
                print(
                    'Adjust parameters or continue execution with the same parameters'
                )
                exit(2)

    open('out.m3u8', 'w').write(code)
    return code
Ejemplo n.º 6
0
def encrypt(code):
  if _('ENCRYPTION_VERSION') == 'V1':
    print('ENCRYPTION_VERSION:%s' % _('ENCRYPTION_VERSION'))
    head = read_bytes('../dangdai-32x32.png')
    head1 = head[0:-12]
    head2 = head[-12:]
    tmpdir = os.getcwd()+'/tmp'
    if not os.path.exists(tmpdir):
      os.mkdir(tmpdir)
    os.chdir(tmpdir)
    for file in tsfiles(code):
      portion = os.path.splitext(file)
      if portion[1] == ".ts":
        newName = portion[0] + ".png"
        if os.path.isfile(newName):
          code = code.replace(file, newName)
          continue
        segment = read_bytes('../' + file)
        segment = zlib.compress(segment)
        done_segments = head1 + segment + head2
        open(newName, 'wb').write(done_segments)
        code = code.replace(file, newName)
      #break
    #os.chdir('../')

  if _('ENCRYPTION_VERSION') == 'V2':
    print('ENCRYPTION_VERSION:%s' % _('ENCRYPTION_VERSION'))
    tmpdir = os.getcwd()+'/tmp'
    if not os.path.exists(tmpdir):
      os.mkdir(tmpdir)
    os.chdir(tmpdir)

    for file in tsfiles(code):
      # 1,获取切片大小
      filesize = os.path.getsize('../' +file)+64
      wh=math.ceil(math.sqrt(filesize/3))*4
      # wh=math.ceil(math.sqrt(filesize*3))
      print('切片大小:%s,图片尺寸:%s' % (filesize,wh))
      data = open('../' + file, "rb").read()
      data = zlib.compress(data)
      print('压缩后切片大小:%s' % (len(data)))

      portion = os.path.splitext(file)
      newName = portion[0] + ".png"

      if os.path.isfile(newName):
        code = code.replace(file, newName)
        continue
      # 2,生成图片
      new_img_file_name = new_image(wh, wh, portion[0], show_image=False)
      print('生成图片:%s' % (new_img_file_name))

      # 3,隐写
      in_img = cv2.imread(new_img_file_name)
      steg = LSBSteg(in_img)
      starttime = time.time()
      res = steg.encode_binary(data)
      duration = time.time()-starttime
      print('隐写完成时间:%s' % (duration))
      cv2.imwrite(newName, res)
      print('隐写完成:%s' % (newName))

      # embed(new_img_file_name, '../' + file)
      # 4,替换
      code = code.replace(file, newName)

      """
      # 1,获取切片大小
      filesize = os.path.getsize('../' + file) + 64
      wh = math.ceil(math.sqrt(filesize / 3))
      print('切片大小:%s,图片尺寸:%s' % (filesize, wh))
      data = open('../' + file, "rb").read()
      new_img_file_name = r'%s_%s_%s.png' % (wh, wh, md5(data))
      if os.path.isfile('out' + new_img_file_name):
        code = code.replace(file, 'out' + new_img_file_name)
        continue
      # 2,生成图片
      new_image(wh, wh, md5(data), show_image=False)
      print('生成图片:%s' % (new_img_file_name))

      # 3,隐写
      in_img = cv2.imread(new_img_file_name)
      steg = LSBSteg(in_img)
      starttime = time.time()
      res = steg.encode_binary(data)
      duration = time.time() - starttime
      print('隐写完成时间:%s' % (duration))
      cv2.imwrite('out' + new_img_file_name, res)
      print('隐写完成:%s' % ('out' + new_img_file_name))
      # embed(new_img_file_name, '../' + file)
      # 4,替换
      code = code.replace(file, 'out' + new_img_file_name)
      
      """


  if not _('ENCRYPTION') == 'YES':
    return code

  for file in tsfiles(code):
    if file.startswith('enc.'):
      continue

    print('Encrypting %s to enc.%s ... ' % (file, file), end='')
    key = exec(['openssl','rand','16']).hex()
    iv  = execstr(['openssl','rand','-hex','16'])
    exec(['openssl','aes-128-cbc','-e','-in',file,'-out','enc.%s' % file,'-p','-nosalt','-iv',iv,'-K',key])

    key_id = api('POST', 'key', data={'iv': iv, 'key': key})
    if not key_id:
      print('failed')
      open('out.m3u8', 'w').write(code)
      exit()

    print('done')
    code = re.sub('(#EXTINF:.+$[\\r\\n]+^%s$)' % file, '#EXT-X-KEY:METHOD=AES-128,URI="%s/play/%s.key",IV=0x%s\n\\1' % (_('APIURL'), key_id, iv), code, 1, re.M)
    code = code.replace(file, 'enc.%s' % file)

  open('out.m3u8', 'w').write(code)
  return code
Ejemplo n.º 7
0
def main(video_path, video_title, segment_specify, repair=False):
    global upload_drive
    cwd = os.getcwd()
    upload_drive = importlib.import_module('uploader.' + _('UPLOAD_DRIVE'))
    title = video_title if video_title else os.path.splitext(
        os.path.basename(video_path))[0]
    tmpdir = os.path.dirname(os.path.abspath(__file__)) + '/tmp'
    segment_time = get_segment_time(os.path.abspath(video_path),
                                    segment_specify)
    command = command_generator(os.path.abspath(video_path), segment_time)
    if not os.path.exists(tmpdir):
        os.mkdir(tmpdir)
    if sameparams(tmpdir, command):
        os.chdir(tmpdir)
    else:
        os.chdir(tmpdir)
        try:
            os.system(command)
        except KeyboardInterrupt:
            return 1
        with open('command.sh', 'w') as f:
            f.write(command)
    failures, completions = 0, 0
    with open('out.m3u8', 'r') as f:
        lines = f.read()
    for tsfile in tsfiles(lines):
        if os.path.getsize(tsfile) >= upload_drive.UPLOAD_LIMIT:
            if repair:
                tmp = 'rep.%s' % tsfile
                os.system(genrepair(tsfile, tmp,
                                    upload_drive.UPLOAD_LIMIT * 8))
                os.rename(tsfile, 'old.%s' % tsfile)
                os.rename(tmp, tsfile)
            else:
                os.chdir(cwd)
                return 1
    executor = ThreadPoolExecutor(max_workers=10)
    futures = {
        executor.submit(uploader(), chunk): chunk
        for chunk in tsfiles(lines)
    }
    for future in as_completed(futures):
        completions += 1
        result = future.result()
        if not result:
            failures += 1
            print('[%s/%s] Uploaded failed: %s' %
                  (completions, len(futures), futures[future]))
            continue
        lines = lines.replace(futures[future], result)
        print('[%s/%s] Uploaded %s to %s' %
              (completions, len(futures), futures[future], result))
    print('\n')
    # Write to file
    with open('out.m3u8', 'w') as f:
        f.write(lines)
    os.chdir(cwd)
    if not failures:
        shutil.copy2('./tmp/out.m3u8', f'./results/{int(time.time())}.m3u8')
        writefile(lines, title)
        shutil.rmtree(tmpdir)
        return 0
    else:
        print('Partially successful: %d/%d' %
              (completions, completions - failures))
        print('You can re-execute this program with the same parameters')
        return 2