Ejemplo n.º 1
0
class INFO:
    # 校历 http://www.dean.swust.edu.cn/type/2c9fd0b8655589e50165558a19a9000e/page/2c9fd0b8655589e50165558a19a9000f
    semester_name = _("c2i_semester_name")
    semester_start_day = _("c2i_semester_start_day")
    load_exp = False if _("c2i_load_exp", "").upper() == "FALSE" else True
    if not semester_name or not semester_start_day:
        raise ValueError("请配置环境变量:c2i_semester_name 和 c2i_semester_start_day")
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():
  tmpdir = os.path.dirname(os.path.abspath(__file__)) + '/tmp'
  os.chdir(tmpdir)

  lines    = open('outtiny.m3u8', 'r').read()

  llen = len(lines)+64
  wh = math.ceil(llen/3)
  print('文本大小:%s,图片尺寸:%s' % (llen, wh))

  new_img_file_name = new_image(wh, wh, 'out', show_image=False)
  print('生成图片:%s' % (new_img_file_name))

  in_img = cv2.imread(new_img_file_name)
  steg = LSBSteg(in_img)
  done = base64.b64encode(lines.encode('utf-8'))
  done = zlib.compress(done)
  res = steg.encode_binary(done)
  cv2.imwrite('outtiny.png', res)

  m3u8url = uploader().handle('outtiny.png')
  if _('PROXY') == 'YES':
    m3u8url = str(base64.b64encode(m3u8url.encode('utf-8')),'utf8')
    print('This video\'s m3u8 has been published to: %s/p/%s' % (_('APIURL'),m3u8url))
  else:
    print('This video\'s m3u8 has been published to: %s/p/%s' % (_('APIURL'),m3u8url))
Ejemplo n.º 4
0
def upload(lines, uploadList):
  failures, completions = 0, 0
  executor = ThreadPoolExecutor(max_workers=15)
  futures = {executor.submit(uploader().handle, chunk): chunk for chunk in uploadList}
  uploadList = []

  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]))
      uploadList.append(futures[future])
      continue
    if _('PROXY') == 'YES':
      result = str(base64.b64encode(result.encode('utf-8')), 'utf8')
      lines = lines.replace(futures[future], _('APIURL')+'/p/'+result)
    else:
      lines = lines.replace(futures[future], result)
    print('[%s/%s] Uploaded %s to %s' % (completions, len(futures), futures[future], result))

  if(len(uploadList)>0):
    print('retry upload')
    lines = upload(lines, uploadList)
  return lines
Ejemplo n.º 5
0
def publish(code, title=None):
  r = requests.post('%s/publish' % _('APIURL'), data={'code': code, 'title': title}).json()

  if r['code'] == 0:
    return '%s/play/%s' % (_('APIURL'), r['data'])
  else:
    return None
Ejemplo n.º 6
0
Archivo: up.py Proyecto: pdool/free-hls
def publish(code, title=None):
    if _('NOSERVER') == 'YES':
        return print('The m3u8 file has been dumped to tmp/out.m3u8')

    r = api('POST', 'publish', {'code': code, 'title': title})
    if r:
        url = '%s/play/%s' % (_('APIURL'), r)
        print('This video has been published to: %s' % url)
        print('You can also download it directly: %s.m3u8' % url)
Ejemplo n.º 7
0
 def test_auth_success(self):
     u = _("testusername")
     p = _("testpassword")
     if not (u and p):
         pytest.skip(
             msg="requires testusername and testpassword to test success")
     login = Login(u, p)
     res, info = login.try_login()
     print(res)
     assert res is True
Ejemplo n.º 8
0
def upload_yuque(file):

  r = requests.post('https://www.yuque.com/api/upload/attach?ctoken=%s' % _('YUQUE_CTOKEN'), files={
    'file': ('image.png', open(file, 'rb'), 'image/png')
  }, headers={
    'Referer': 'https://www.yuque.com/yuque/topics/new',
    'Cookie': 'ctoken=%s; _yuque_session=%s' % (_('YUQUE_CTOKEN'), _('YUQUE_SESSION'))
  }).json()

  if 'data' in r and 'url' in r['data']:
    return r['data']['url']
  else:
    return None
Ejemplo n.º 9
0
    def handle(cls, file):
        file = file.read()
        r = api('POST',
                'upload',
                files={'file': ('%s.png' % md5(file), file, 'image/png')})

        if not r:
            return None

        if len(_('DOMAIN')) > 0:
            return '%s/%s' % (_('DOMAIN'), r)
        else:
            return '%s/%s' % (_('APIURL'), r)
Ejemplo n.º 10
0
def video_codec(file):
    codecs = execstr([
        'ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries',
        'stream=codec_name', '-of', 'default=noprint_wrappers=1:nokey=1', file
    ])
    return _('VCODEC') if set(codecs.split('\n')).difference({'h264'
                                                              }) else 'copy'
Ejemplo n.º 11
0
def home():
    if _('CLOSEUI') == 'YES':
        return 'Hello Free-HLS!'

    total_tags = Tag.select().count()
    total_videos = Video.select().count()
    latest_tags = {
        vtag.tag.id: vtag.tag
        for vtag in VideoTag.select().join(Tag).order_by(
            VideoTag.id.desc()).group_by(VideoTag.tag).limit(10)
    }
    video_tags = VideoTag.select().join(Tag).switch(VideoTag).join(
        Video).where(VideoTag.tag << list(latest_tags)).order_by(
            VideoTag.id.desc()).limit(50)

    tags_videos = {}
    for vt in video_tags:
        if vt.tag.id not in tags_videos:
            tags_videos[vt.tag.id] = []
        tags_videos[vt.tag.id].append(vt.video)

    return render_template('home.html',
                           total_tags=total_tags,
                           total_videos=total_videos,
                           latest_tags=latest_tags,
                           tags_videos=tags_videos)
Ejemplo n.º 12
0
def api(method, url, **kwargs):
  if method == 'POST':
    fn = requests.post
  else:
    fn = requests.get
  try:
    r = fn('%s/%s' % (_('APIURL'), url), **kwargs, headers={
      'API-Token': _('SECRET'),
      'API-Version': VERSION}).json()

    if not r['err']:
      return r['data']
    print('Request failed: %s' % r['message'])

  except:
    print('Request failed: connection error')
Ejemplo n.º 13
0
def uploader():
    handle = importlib.import_module('uploader.' + _('UPLOAD_DRIVE')).handle

    def wrapper(file):
        with open(file, 'rb') as f:
            return handle(f)

    return wrapper
Ejemplo n.º 14
0
def handle(file):
    try:
        r = session.post('https://www.yuque.com/api/upload/attach?ctoken=%s' %
                         _('YUQUE_CTOKEN'),
                         files={
                             'file': ('image.png', file, 'image/png')
                         },
                         headers={
                             'Referer':
                             'https://www.yuque.com/yuque/topics/new',
                             'Cookie':
                             'ctoken=%s; _yuque_session=%s' %
                             (_('YUQUE_CTOKEN'), _('YUQUE_SESSION'))
                         }).json()

        return r['data']['url']
    except:
        return None
Ejemplo n.º 15
0
def publish(code, title=None):
    if _('NOSERVER') == 'YES':
        return print('The m3u8 file has been dumped to tmp/out.m3u8')

    try:
        r = requests.post('%s/publish' % _('APIURL'),
                          data={
                              'code': code,
                              'title': title
                          }).json()
        if r['err']:
            print('Publish failed: %s' % r['message'])

        url = '%s/play/%s' % (_('APIURL'), r['data'])
        print('This video has been published to: %s' % url)
        print('You can also download it directly: %s.m3u8' % url)
    except:
        print('Publish failed: network connection error')
Ejemplo n.º 16
0
def publish(code, title=None):
    if _('NOSERVER') == 'YES':
        return print('The m3u8 file has been dumped to tmp/out.m3u8')

    r = api('POST',
            'publish',
            data={
                'code': code,
                'title': title,
                'params': json.dumps(uploader().params())
            })
    if r:
        url = '%s/play/%s' % (_('APIURL'), r['slug'])
        print(f'This video has been published to: {url}')
        print(f'You can also download it directly: {url}.m3u8')
        print('---')
        print('Click here to edit the information for this video:\n%s' %
              manageurl(f'video/{r["id"]}'))
Ejemplo n.º 17
0
    def handle(cls, file):
        file = file.read()
        r = api('POST',
                'upload',
                files={'file': ('%s.ts' % md5(file), file, 'video/mp2t')})

        if not r:
            return None

        return '%s/uploads/%s' % (_('APIURL'), r)
Ejemplo n.º 18
0
def api(method, url, **kwargs):
    if method == 'POST':
        fn = requests.post
    else:
        fn = requests.get
    try:
        ok, data = fn('%s/%s' % (_('APIURL'), url),
                      **kwargs,
                      timeout=10,
                      headers={
                          'API-Token': _('SECRET'),
                          'API-Version': VERSION
                      }).json()

        if ok: return data
        print('Request failed: %s' % data)

    except:
        print('Request failed: connection error')
Ejemplo n.º 19
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.º 20
0
def publish(code, title=None):
    r = requests.post('%s/publish.php' % _('APIURL'),
                      data={
                          'code': code,
                          'title': title
                      }).json()

    if r['code'] == 0:
        return r['data']['url']
    else:
        return None
Ejemplo n.º 21
0
def login():
  if 'auth' in request.args:
    if request.args['auth'] != md5(_('SECRET')):
      return 0, '无效的 Token'

    resp = make_response(redirect(request.args.get('goto')))
    resp.set_cookie('secret', _('SECRET'))
    return resp

  if 'secret' in request.form:
    secret = request.form['secret']
    if not _('SECRET') == secret:
      return 0, '登录失败'

    resp = make_response('[1, "OK"]')
    resp.set_cookie('secret', secret)
    return resp

  resp = make_response(render_template('login.html'))
  resp.delete_cookie('secret')
  return resp
Ejemplo n.º 22
0
def main():
    try:
        skip = int(argv[1])
    except:
        skip = 0

    for video in api('GET', 'videos/%d' % skip):
        link = '%s/play/%s' % (_('APIURL'), video['key'])
        date = time.strftime("%Y-%m-%d %H:%M:%S",
                             time.localtime(video['created_at']))

        print('%s\t%s\t%s' % (video['title'], date, link))
Ejemplo n.º 23
0
def playlist(tag_id):
    if _('CLOSEUI') == 'YES':
        return redirect('/')

    tag = Tag.get_by_id(tag_id)
    videos = VideoTag.blend(tag)
    watch = request.args.get('watch') or videos[0]['slug']

    return render_template('playlist.html',
                           tag=tag,
                           watch=watch,
                           videos=videos)
Ejemplo n.º 24
0
def upload():
    if not _('ENABLE_UPLOAD') == 'YES':
        return jsonify({'err': 1, 'message': 'Upload is not enabled'})

    if 'file' not in request.files:
        return jsonify({'err': 1, 'message': 'No file part'})

    file = request.files['file']
    if not file or file.filename == '':
        return jsonify({'err': 1, 'message': 'No selected file'})

    name = secure_filename(file.filename)
    file.save(os.path.join('uploads', name))
    return jsonify({'err': 0, 'data': name})
Ejemplo n.º 25
0
def upload():
  if not _('ENABLE_UPLOAD') == 'YES':
    return jsonify({'err': 1, 'message': 'Upload is not enabled'})

  if 'file' not in request.files:
    return jsonify({'err': 1, 'message': 'No file part'})

  file = request.files['file']
  if not file or file.filename == '':
    return jsonify({'err': 1, 'message': 'No selected file'})

  name = secure_filename(file.filename)
  path = os.path.join('uploads',time.strftime("%Y%m%d", time.localtime()))
  if not os.path.exists(path):
    os.mkdir(path)
  file.save(os.path.join(path, name))
  return jsonify({'err': 0, 'data': os.path.join(path, name)})
Ejemplo n.º 26
0
def test(curr, step):
  maps = {}
  reve = False
  reve_inc = None
  print('Starting test %s:' % _('UPLOAD_DRIVE'))

  while True:
    if curr in maps:
      result = maps[curr]
    else:
      result = maps[curr] = upload(curr)
      print('%dM\t%s\t%s' % (curr, 'OK' if result else 'FAIL', result))

    if not result:
      reve = True
    if not reve and curr > 20:
      step = 20
    if not reve and curr > 50:
      step = 30

    if not result and not reve_inc == None:
      print('\n---\nFinally ... %dM' % reve_inc)
      exit(0)

    if reve and result:
      reve_inc = curr
      curr += 1
    elif reve and not result:
      if (curr - 1) % 5 == 0:
        curr -= 1
      else:
        step //= 2
        curr -= max(1, step)
      if curr < 1:
        curr = 1
        reve_inc = 0
    elif not reve:
      curr += step
Ejemplo n.º 27
0
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]))
  print('commend:%s'%command)


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


  lines    = checker(encrypt(open('out.m3u8', 'r').read()))
  #return

  # failures, completions = 0, 0
  # executor = ThreadPoolExecutor(max_workers=15)
  # futures  = {executor.submit(uploader().handle, chunk): chunk for chunk in pngfiles(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))

  # 上传
  lines = upload(lines, pngfiles(lines))

  """
  head = read_bytes(os.path.dirname(os.path.abspath(__file__)) + '/dangdai-32x32.png')
  head1 = head[0:-12]
  head2 = head[-12:]
  done = base64.b64encode(lines.encode('utf-8'))
  done = zlib.compress(done)
  open('out.png', 'wb').write(head1 + done+head2)
  """
  llen = len(lines)+64
  wh = math.ceil(llen/3)
  print('文本大小:%s,图片尺寸:%s' % (llen, wh))

  new_img_file_name = new_image(wh, wh, 'out', show_image=False)
  print('生成图片:%s' % (new_img_file_name))

  in_img = cv2.imread(new_img_file_name)
  steg = LSBSteg(in_img)
  done = base64.b64encode(lines.encode('utf-8'))
  done = zlib.compress(done)
  res = steg.encode_binary(done)
  cv2.imwrite('out.png', res)

  m3u8url = uploader().handle('out.png')
  if _('PROXY') == 'YES':
    m3u8url = str(base64.b64encode(m3u8url.encode('utf-8')), 'utf8')
    print('This video\'s m3u8 has been published to: %s/p/%s' % (_('APIURL'),m3u8url))
  else:
    print('This video\'s m3u8 has been published to: %s/p/%s' % (_('APIURL'),m3u8url))
  publish(lines, title)
Ejemplo n.º 28
0
def uploader():
    return importlib.import_module('uploader.' + _('UPLOAD_DRIVE')).Uploader
Ejemplo n.º 29
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.º 30
0
def upload():
    if not _('ENABLE_UPLOAD') == 'YES':
        return 0, 'Upload is not enabled'
    return saveupload('uploads')