Exemplo n.º 1
0
    def test_request(self):

        response = api('get_status', STATUS_ID)
        self.assertEqual(response.text, '@mrshoranweyhey Thanks for the love! How about a follow for a follow? :) ^LF')
        self.assertEqual(response.source_url, 'http://www.exacttarget.com/social')

        response = api('get_user', USER_SCREEN_NAME)
        self.assertEqual(response.id, USER_ID)
        self.assertEqual(response.name, 'Barack Obama')
Exemplo n.º 2
0
    def test_request(self):

        response = api('get_status', STATUS_ID)
        self.assertEqual(
            response.text,
            '@mrshoranweyhey Thanks for the love! How about a follow for a follow? :) ^LF'
        )
        self.assertEqual(response.source_url,
                         'http://www.exacttarget.com/social')

        response = api('get_user', USER_SCREEN_NAME)
        self.assertEqual(response.id, USER_ID)
        self.assertEqual(response.name, 'Barack Obama')
Exemplo n.º 3
0
Arquivo: up.py Projeto: 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
Exemplo n.º 4
0
def login_handler(request, backend=None):
    """
    Google+ OAuth2 login handler.
    """

    if request.user.is_authenticated() and request.user.get_profile().googleplus_id != "":
        return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)

    if "error" in request.GET:
        messages.add_message(request, messages.ERROR, request.GET["error"])
        return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
    elif "code" in request.GET:
        params = {
            "client_id": settings.GOOGLEPLUS_CLIENT_ID,
            "redirect_uri": REDIRECT_URI,
            "client_secret": settings.GOOGLEPLUS_CLIENT_SECRET,
            "code": request.GET["code"],
            "grant_type": "authorization_code",
        }
        req = urllib.urlopen("https://accounts.google.com/o/oauth2/token", urllib.urlencode(params))
        if req.getcode() != 200:
            response = render_to_response("500.html", {}, context_instance=RequestContext(request))
            response.status_code = 500
            return response

        response = req.read()
        response_query_dict = json.loads(response)
        access_token = response_query_dict["access_token"]
        expires_in = response_query_dict["expires_in"]

        profile = utils.api("people/me", {"access_token": access_token})

        if profile.has_key("error"):
            print "profile with error", profile

        print "profile ", profile

        googleplus_user = _create_or_update_googleplus_user(request, profile, access_token, expires_in, backend)

        user = authenticate(googleplus_user=googleplus_user)
        if user is not None:
            if user.is_active:
                login(request, user)
                request.session.set_expiry(googleplus_user.googleplus_expiry_at)
                if "next" in request.GET:
                    return HttpResponseRedirect(request.GET["next"])
                return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
            else:
                messages.add_message(request, messages.ERROR, "Account disabled.")
        else:
            messages.add_message(request, messages.ERROR, "Login failed.")
    else:
        params = {
            "client_id": settings.GOOGLEPLUS_CLIENT_ID,
            "redirect_uri": REDIRECT_URI,
            "scope": "https://www.googleapis.com/auth/plus.me",
            "response_type": "code",
        }
        return HttpResponseRedirect("https://accounts.google.com/o/oauth2/auth?" + urllib.urlencode(params))
Exemplo n.º 5
0
Arquivo: up.py Projeto: 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)
Exemplo n.º 6
0
def kraken_status(data_set):
    response, _ = utils.api("coverage/{r}".format(r=data_set.name))
    assert 'error' not in response, "problem with the region: {error}".format(error=response['error'])

    current_region = response.get('regions', [None])[0]
    #the region should be the one asked for
    assert current_region and current_region['id'] == data_set.name

    return current_region['status']
Exemplo n.º 7
0
def kraken_status(data_set):
    response, _ = utils.api("coverage/{r}".format(r=data_set.name))
    assert 'error' not in response, "problem with the region: {error}".format(error=response['error'])

    current_region = response.get('regions', [None])[0]
    #the region should be the one asked for
    assert current_region and current_region['id'] == data_set.name

    return current_region['status']
Exemplo n.º 8
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)
Exemplo n.º 9
0
  def handle(cls, file):
    file = file.read()
    r = api('POST', 'upload', files={
      'file': (f'{md5(file)}.ts', file, 'video/mp2t')
    })

    if not r:
      return None

    return f'{_("APIURL")}/uploads/{r}'
Exemplo n.º 10
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

    return '%s/%s' % (_('APIURL'), r)
Exemplo n.º 11
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))
Exemplo n.º 12
0
    def _api_call(self, url, response_checker):
        """
        call the api and check against previous results

        the query is writen in a file
        """
        response, url = utils.api(url)

        filtered_response = response_checker.filter(response)

        filename = self._save_response(url, response, filtered_response)

        utils.compare_with_ref(filtered_response, filename, response_checker)
Exemplo n.º 13
0
    def _api_call(self, url, response_checker):
        """
        call the api and check against previous results

        the query is writen in a file
        """
        response, url = utils.api(url)

        filtered_response = response_checker.filter(response)

        filename = self._save_response(url, response, filtered_response)

        utils.compare_with_ref(filtered_response, filename, response_checker)
Exemplo n.º 14
0
def main():
    try:
        page = int(argv[1])
    except:
        page = 1

    result = api('GET', f'paginate?page={page}')
    for video in result['data']:
        link = f'{_("APIURL")}/play/{video["slug"]}'
        date = datetime.strptime(video['created_at'],
                                 '%a, %d %b %Y %H:%M:%S GMT')

        print(f'{video["title"]}\t{date}\t{link}')
Exemplo n.º 15
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"]}'))
Exemplo n.º 16
0
    def _api_call(self, url, response_checker):
        """
        call the api and check against previous results

        the query is writen in a file
        """
        if self.check_ref:  # only check consistency
            filename = self._get_file_name()
            assert utils.check_reference_consistency(filename,
                                                     response_checker)
            return

        response, url = utils.api(url)

        filtered_response = response_checker.filter(response)

        filename = self._save_response(url, response, filtered_response)

        utils.compare_with_ref(filtered_response, filename, response_checker)
Exemplo n.º 17
0
 def api_call(self, *args, **kwargs):
     method = kwargs.pop('method')
     return api(self.methods[method], *args, **kwargs)
Exemplo n.º 18
0
def get_last_rt_loaded_time(cov):
    _response, _ = utils.api("coverage/{cov}/status".format(cov=cov))
    return _response['status']['last_rt_data_loaded']
Exemplo n.º 19
0
def get_last_rt_loaded_time(cov):
    _response, _ = utils.api("coverage/{cov}/status".format(cov=cov))
    return _response['status']['last_rt_data_loaded']
    ips = json.load(ipsfile)

utils.login(sys.argv[1], getpass.getpass(), utils.ZERO)
token = utils.edittoken(utils.ZERO)
confs = utils.getAllConfigs()

for id, conf in confs.items():

    try:
        if id in ips:
            conf['ips'] = ips[id]
        elif not id.startswith('-'):
            conf['ips'] = []

        if 'admins' in conf:
            del conf['admins']

        text = json.dumps(conf)

        res = utils.api(utils.ZERO,
            action='edit',
            title='Zero:' + id,
            summary='(bot) upload',
            text=text,
            token=token,
            contentmodel='JsonZeroConfig')
        print('Upload %s %s' % (id, res['result']))
    except:
        print('Failed upload %s' % (id))
        pprint(sys.exc_info())
Exemplo n.º 21
0
def post(host_name, post_id):
    response = api(TUMBLR, 'blog', host_name, 'posts', id=post_id, api_key=API_KEY)['response']
    blog = response['blog']
    post = response['posts'][0]
    return render_template('post.html', post=post, blog=blog)
Exemplo n.º 22
0
def get_last_rt_loaded_time(cov):
    _response, _ = utils.api("coverage/{cov}/status".format(cov=cov))
    return _response.get('status', {}).get('last_rt_data_loaded', object())
Exemplo n.º 23
0
def get_tumblr_tag(tag, offset=0):
    return api(TUMBLR, 'tagged', offset=offset, api_key=API_KEY, tag=tag)['response']
Exemplo n.º 24
0
 def api_call(self, *args, **kwargs):
     method = kwargs.pop('method')
     return api(self.methods[method], *args, **kwargs)
Exemplo n.º 25
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
Exemplo n.º 26
0
import utils, requests, json

API = utils.api()


class Stop:
    def __init__(self, address, coords, name, rating, reviews):
        self.address = address
        self.coords = coords
        self.name = name
        self.rating = float(rating)
        self.reviews = reviews

    def __eq__(self, o):
        return isinstance(
            o, Stop) and self.name == o.name and (self.x, self.y) == (o.x, o.y)

    def __hash__(self):
        return hash(self.name) ^ hash(self.x) ^ hash(self.y) ^ hash(
            (self.name, self.x, self.y))

    def __str__(self):
        return ' '.join([
            self.name,
            str(self.x),
            str(self.y),
            str(self.rating),
            str(self.reviews)
        ])