Example #1
0
	def chunk_position_to_path(self, chunk_position):
		x, y, z = chunk_position

		chunk_path = '/'.join((self.path,
			base36.dumps(x % 64), base36.dumps(z % 64),
			f"c.{base36.dumps(x)}.{base36.dumps(z)}.dat"))
		
		return chunk_path
Example #2
0
def wait(watch_mode, target_id, reddit):
    subreddit = reddit.subreddit('all')
    rootLogger.info('Entering wait mode...')
    target_id_decoded = base36.loads(target_id) if not watch_mode else None
    min_distance = 270

    if has_libs:
        ids, times = np.array([]), np.array([])
        to_predict = np.array(target_id_decoded).reshape(1, -1)
    else:
        ids, times, to_predict = [None] * 3  # fix assignment warning

    while True:
        max_id, time_id = None, None
        while not max_id:
            max_id = max([base36.loads(s.id) for s in subreddit.new(limit=2)],
                         default=0)
            time_id = time.time()

        if watch_mode:
            rootLogger.info('Last ID: {lastid}'.format(
                lastid=base36.dumps(max_id), ))
            hint = max_id + 1500
            rootLogger.info('Try to capture {}'.format(base36.dumps(hint)))
            quit(0)

        if has_libs:
            ids = np.append(ids, max_id)
            times = np.append(times, time_id)
            # rootLogger.info('id {di} found'.format(di=base36.dumps(max_id)))

        if has_libs and len(ids) > 1:
            X, y = ids.reshape(-1, 1), times.reshape(-1, 1)
            reg = LinearRegression().fit(X, y)
            pred = reg.predict(to_predict)  # ndarray
            pred = datetime.datetime.fromtimestamp(pred[0][0])  # datetime
        elif has_libs:
            pred = 'Cannot calculate (need two or more ids)'
        else:
            pred = 'Cannot calculate (need missing libraries)'

        distance = target_id_decoded - max_id

        rootLogger.info(
            'Last ID: {lastid} - Distance: {d} - ETA: {eta}'.format(
                lastid=base36.dumps(max_id), d=distance, eta=pred))

        if distance <= 0:
            rootLogger.info('ID "{}" passed.'.format(target_id))
            quit(1)
        elif distance <= min_distance:
            rootLogger.info('Exiting wait mode...')
            return
        else:
            tts = round(min(10, distance / 200), 2)
            rootLogger.info('Sleep for {} seconds...'.format(tts))
            time.sleep(tts)
Example #3
0
    def open(self, service, name):
        '''
        open(service: str, name: str)
        Opens a channel. Returns a _Channel object.
        '''
        cmd = api_pb2.Command()  # Create the command
        cmd.channel = 0  # Use channel 0
        cmd.session = 0
        cmd.openChan.service = service  # Set the service and name
        cmd.openChan.name = name
        cmd.openChan.action = 0  # 0 is CREATE
        cmd.ref = base36.dumps(int(str(random.uniform(
            0, 1)).split('.')[1]))  # Generate a ref
        # I don't know why this is necessary, but Crosis has it, so yeah

        data = cmd.SerializeToString()
        self.ws.send(data)  # Serialize and send the command

        got = False
        while not got:
            res = api_pb2.OpenChannelRes()  # Wait to get an OpenChannelRes
            data = self.ws.recv()
            res.ParseFromString(data)
            got = bool(res.id)  # If we got one, then exit
        self.channels.append(res.id)

        return _Channel(res.id, service, name, self.ws)  # Create the channel
Example #4
0
    def get(self, *args, **kwargs):
        keyword = kwargs['keyword']

        url = 'https://www.plurk.com/Search/search2'

        title = 'Plurk Search - {}'.format(keyword)

        feed = feedgen.feed.FeedGenerator()
        feed.author({'name': 'Feed Generator'})
        feed.id(url)
        feed.link(href=url, rel='alternate')
        feed.title(title)

        s = services.RequestsService().process()

        r = s.post(url, data={'query': keyword})
        body = json.loads(r.text)

        for p in body['plurks']:
            url = 'https://www.plurk.com/p/' + base36.dumps(p['id'])

            content = self.str_clean(p['content'])

            entry = feed.add_entry()
            entry.content(content, type='CDATA')
            entry.id(url)
            entry.link(href=url)
            entry.published(dateutil.parser.parse(p['posted']))
            entry.title(self.str_clean(p['content_raw']))

        res = HttpResponse(feed.atom_str(), content_type='application/atom+xml; charset=utf-8')
        res['Cache-Control'] = 'max-age=300,public'

        return res
def populate_usi(apps, schema_editor):
    Subscribe = apps.get_model("courses", "Subscribe")
    for s in Subscribe.objects.all():
        checksum = hashlib.md5()
        checksum.update(str(s.id))
        s.usi = (base36.dumps(s.id).zfill(4)[:4] + checksum.hexdigest()[:2]).lower()
        s.save()
Example #6
0
def gen_dog_id():
    """
    生成10位时间戳(伪)
    """
    tdog = int(1000 * time.time()) - SDOG
    strdog = base36.dumps(tdog)
    return str(strdog)
Example #7
0
    async def post_challenge(self, request):
        if request.content_type != 'application/jose+json':
            return web.HTTPBadRequest()

        req_body = await request.text()
        req_obj = json.loads(req_body)
        #try:
        if True:
            # TODO(supersat): Is there a less brain-dead way of doing this?
            jws = jwcrypto.jws.JWS()
            jws.deserialize(req_body)
            protected = json.loads(
                str(base64.urlsafe_b64decode(req_obj['protected'] + '=='),
                    'utf-8'))
            chal = json.loads(
                str(base64.urlsafe_b64decode(req_obj['payload'] + '=='),
                    'utf-8'))
            pub_key = jwcrypto.jwk.JWK.from_json(json.dumps(protected['jwk']))
            jws.verify(pub_key)
            thumbprint_bytes = base64.urlsafe_b64decode(pub_key.thumbprint() +
                                                        '==')
            thumbprint = base36.dumps(
                int.from_bytes(thumbprint_bytes, byteorder='big'))
            if chal['type'] == 'dns-01':
                await self._redis_pool.set(
                    'acme-dns-01-chal:{}'.format(thumbprint),
                    chal['token'],
                    expire=300)
                return web.HTTPNoContent()
        #except:
        #    pass
        return web.HTTPBadRequest()
Example #8
0
    def xhm_uri(self):
        """Generates the X-HM:// uri (Setup Code URI)

        :rtype: str
        """
        payload = 0
        payload |= 0 & 0x7  # version

        payload <<= 4
        payload |= 0 & 0xF  # reserved bits

        payload <<= 8
        payload |= self.category & 0xFF  # category

        payload <<= 4
        payload |= 2 & 0xF  # flags

        payload <<= 27
        payload |= (int(self.driver.state.pincode.replace(b"-", b""), 10)
                    & 0x7FFFFFFF)  # pincode

        encoded_payload = base36.dumps(payload).upper()
        encoded_payload = encoded_payload.rjust(9, "0")

        return "X-HM://" + encoded_payload + self.driver.state.setup_id
def test_populate_all_posts_and_comments(mocker, settings, mocked_celery):
    """
    populate_all_posts_and_comments should create batched subtasks to populate the Posts and Comments
    """
    mock_api = mocker.patch("channels.api.Api", autospec=True)
    mock_api.return_value.reddit.front.new.return_value = iter(
        [mocker.Mock(id=base36.dumps(23))])

    mock_populate_posts_and_comments = mocker.patch(
        "channels.tasks.populate_posts_and_comments")
    mock_populate_posts_and_comments_merge_results = mocker.patch(
        "channels.tasks.populate_posts_and_comments_merge_results")

    # ensure group consumers the generator passed to it so the other assertions work
    mocked_celery.group.side_effect = list

    settings.ELASTICSEARCH_INDEXING_CHUNK_SIZE = 10

    with pytest.raises(mocked_celery.replace_exception_class):
        tasks.populate_all_posts_and_comments.delay()

    assert mocked_celery.group.call_count == 1
    assert mock_populate_posts_and_comments.si.call_count == 3
    mock_populate_posts_and_comments.si.assert_any_call(list(range(0, 10)))
    mock_populate_posts_and_comments.si.assert_any_call(list(range(10, 20)))
    mock_populate_posts_and_comments.si.assert_any_call(list(range(20, 24)))
    mock_populate_posts_and_comments_merge_results.s.assert_called_once_with()
    assert mocked_celery.replace.call_count == 1
Example #10
0
def plurktop(lang):
    url = "https://www.plurk.com/Stats/topReplurks?period=day&lang={}&limit=50".format(
        urllib.parse.quote_plus(lang))

    title = "Plurk Top ({})".format(lang)

    feed = feedgen.feed.FeedGenerator()
    feed.author({"name": "Feed Generator"})
    feed.id(url)
    feed.link(href=url, rel="alternate")
    feed.title(title)

    r = requests.get(url, headers={"User-agent": user_agent}, timeout=5)
    body = json.loads(r.text)

    for (x, stat) in body["stats"]:
        url = "https://www.plurk.com/p/" + base36.dumps(stat["id"])

        content = stat["content"]
        content = re.sub(r' height="\d+(px)?"', " ", content)
        content = re.sub(r' width="\d+(px)?"', " ", content)

        entry = feed.add_entry()
        entry.author({"name": stat["owner"]["full_name"]})
        entry.content(content, type="CDATA")
        entry.id(url)
        entry.link(href=url)
        entry.published(stat["posted"])
        entry.title(stat["content_raw"])

    bottle.response.set_header("Cache-Control", "max-age=300,public")
    bottle.response.set_header("Content-Type", "application/atom+xml")

    return feed.atom_str()
Example #11
0
    def flatten(reducible: {}, prefix: str = ""):
        """
        The recursive call to flatten the dictionary, which accepts a Python dictionary as input and deeply flattens it
        by converting it to a composed string with the properties separated by a string separator.

        :param reducible: a dictionary to add the flatten objects
        :param prefix: a prefix to prepend to properties

        :return: the flatten Python dictionary
        """
        fixed_key: str = prefix[:-len(flatten_separator)]
        printable_fixed_key: str = fixed_key.replace(flatten_separator,
                                                     print_separator)
        if type(reducible) is dict:
            for key in reducible:
                flatten(reducible[key], f"{prefix}{key}{flatten_separator}")
        elif type(reducible) is list:
            indexes_mapping: {} = {}
            for value in reducible:
                if type(value) is FileMarkedValue:
                    value = value.contents
                else:
                    if isinstance(value, YamlInclude):
                        raise AssertionError(
                            "Found include tags outside of the include sequence.\n\t"
                            f"Offending key path: '{printable_fixed_key}'")
                    raise AssertionError(
                        "Internal: Invalid encapsulation inside the YAML sequence."
                    )
                if type(value) is dict:
                    computed_prefix = f"{prefix}{flatten_separator}{next(iter(value))}"
                else:
                    computed_prefix = prefix
                index = indexes_mapping.pop(computed_prefix, 0)
                max_36 = "3W5E11264SGSF"
                max_index = int(max_36, 36)
                if index > max_index:
                    raise AssertionError(
                        f"Maximum elements for table reached: {max_index + 1}.\n\t"
                        f"Offending key path: '{printable_fixed_key}'")
                printable_index = base36.dumps(index).upper().rjust(
                    len(max_36), "0")
                flatten(value, prefix + printable_index + flatten_separator)
                indexes_mapping[computed_prefix] = index + 1
        else:
            try:
                fixed_key.encode("ASCII")
            except UnicodeEncodeError as e:
                raise AssertionError(
                    f"Can not interpret key '{printable_fixed_key}' as an ASCII string."
                ) from e
            if fixed_key not in result_dictionary:
                result_dictionary[fixed_key] = reducible
            else:
                raise AssertionError(
                    "Unrecoverable collision detected while building the key-value mappings.\n\t"
                    f"Offending key path: '{printable_fixed_key}'.")
Example #12
0
def create_short_url(full_url: str) -> ShortUrl:
    print(f'Creating new short url for {full_url}')
    short_url = ShortUrl()
    short_url.full_url = full_url
    short_url.short_url = base36.dumps(randrange(36 ** 8))

    session.add(short_url)
    session.commit()

    return short_url
Example #13
0
def gen_room_code(replace_chars=3):
    base36_timestamp = base36.dumps(int(datetime.utcnow().timestamp() * 1000))
    # Replace the first 3 chars with random chars (0-9a-z), to prevent other users "guessing" other room codes
    # Since the room codes get periodically deleted, the first 2 chars are therefore not important as they will likely
    # be the same
    random_chars = ''.join(
        random.choice(string.ascii_lowercase + string.digits)
        for _ in range(replace_chars))
    room_code = random_chars + base36_timestamp[replace_chars:]
    return room_code
Example #14
0
def f(l, *a):
    for x in range(*z[l]):
        if l + 1 == len(z):
            try:
                x = base36.dumps(int(datetime.datetime(*a, x).timestamp()))
                if term in x: print(2024,*a, x)
            except:
                pass
            return
        f(l+1, *a, x)
Example #15
0
    def _seqMessageSetToSeqDict(self, messageSet, uid):
        if not uid and not messageSet.last:
            messageSet.last = self.getMessageCount()

        seqMap = {}
        for index, messageNum in enumerate(messageSet):
            if uid or messageNum >= 0 and messageNum <= self.getMessageCount():
                seqMap[index + 1] = base36.dumps(
                    messageNum) if uid else self.messages[index]['id']
        return seqMap
Example #16
0
def get_domain(key, domain, cname):
    priv_key = jwcrypto.jwk.JWK.from_json(open(key, 'rt').read())
    thumbprint_bytes = base64.urlsafe_b64decode(priv_key.thumbprint() + '==')
    thumbprint = base36.dumps(int.from_bytes(thumbprint_bytes,
                                             byteorder='big'))
    if cname is None:
        return '*.{}.{}'.format(thumbprint, domain)
    else:
        return '_acme-challenge.{} IN CNAME _acme-challenge.{}.{}'.format(
            cname, thumbprint, domain)
Example #17
0
    def start(self):
        """
        In a background thread, we wait for incoming channel data. Upon
        reciept, we pass it along to the subscribing callback and then push it
        into a ring history buffer for easy access of previous data in
        subsequent calls.
        """
        def run(subscriber):
            """
            Thread target function
            """
            self._is_active = True

            while self._is_active:
                # import ipdb; ipdb.set_trace()
                # enforce finite history capacity
                if len(self.history) > self._history_capacity:
                    self.history.popleft()

                channel = self.hub[subscriber.name]
                data = channel.receive()

                if data is not None:
                    # trigger callback with received data
                    self.callback(self, data)
                    # append the new data item to subscription history
                    self.history.append(data)
                else:
                    self._is_active = False
                    channel.remove()

            self.log.info(f'{self.channel.name} subscription ended')

        # already active?
        if self._thread is not None:
            self.log.debug(
                f'{b36_thread_id} already subscribed to {self.channel.name}')
            return

        # create the Subscriber
        b36_thread_id = base36.dumps(get_ident())
        subscriber_name = f'{self.channel.name}:{b36_thread_id}'
        subscriber = Subscriber(self.hub, subscriber_name)

        self._subscriber = subscriber

        # tell the publisher we want to subscribe
        channel = self.hub[f'{self.channel.name}:subscribe']
        channel.send(subscriber.to_dict())

        # start the background thread
        self._thread = Thread(target=run, args=(subscriber, ), daemon=True)
        self._thread.start()
def test_populate_posts_and_comments(mocker):
    """
    populate_posts_and_comments should call the backpopulate API for each post
    """

    post_ids = [1, 2, 3]

    ChannelFactory.create(name="exists")

    submission_mock = mocker.Mock(id="1",
                                  subreddit=mocker.Mock(display_name="exists"))

    mock_submissions = [
        submission_mock,
        mocker.Mock(id="2", subreddit=mocker.Mock(display_name="missing")),
    ]

    mock_api = mocker.patch("channels.api.Api", autospec=True)
    mock_api.return_value.get_submission.side_effect = mock_submissions

    mock_backpopulate_api = mocker.patch("channels.tasks.backpopulate_api")
    mock_backpopulate_api.backpopulate_comments.return_value = 15

    result = tasks.populate_posts_and_comments.delay(post_ids).get()

    assert mock_api.return_value.get_submission.call_count == len(post_ids)
    for post_id in post_ids:
        mock_api.return_value.get_submission.assert_any_call(
            base36.dumps(post_id))

    assert Post.objects.filter(post_id="1").exists()

    post = Post.objects.get(post_id="1")

    mock_backpopulate_api.backpopulate_post.assert_called_once_with(
        post=post, submission=submission_mock)
    mock_backpopulate_api.backpopulate_comments.assert_called_once_with(
        post=post, submission=submission_mock)

    for mock in mock_submissions:
        mock._fetch.assert_called_once_with()  # pylint: disable=protected-access

    assert result == {
        "posts":
        1,
        "comments":
        15,
        "failures": [{
            "thing_type": "post",
            "thing_id": "2",
            "reason": "unknown channel 'missing'",
        }],
    }
def test_maybe_repair_post_in_host_listing(mocker, settings, is_in_new_posts,
                                           is_missing, will_fail_repair):
    """Tests that maybe_repair_post_in_host_listing correctly repairs if the post is missing"""

    get_admin_api_mock = mocker.patch("channels.tasks.get_admin_api")
    log_mock = mocker.patch("channels.tasks.log")
    will_attempt_repair = is_in_new_posts and is_missing

    channel_name = "channel"
    post_id = base36.dumps(23)

    missing_post = mocker.Mock(id=post_id)
    posts = list(mocker.Mock(id=str(x)) for x in range(5))

    admin_api_mock = get_admin_api_mock.return_value
    admin_api_mock.list_posts.side_effect = [
        ([missing_post] if is_in_new_posts else []) + posts,
        ([] if is_missing else [missing_post]) + posts,
        ([missing_post] if is_in_new_posts else []) + posts,
        ([] if will_fail_repair else [missing_post]) + posts,
    ]

    settings.OPEN_DISCUSSIONS_HOT_POST_REPAIR_LIMIT = 4

    tasks.maybe_repair_post_in_host_listing.delay(channel_name, post_id)

    get_admin_api_mock.assert_called_once_with()

    assert admin_api_mock.list_posts.call_count == (4 if will_attempt_repair
                                                    else 2)

    if will_attempt_repair:
        missing_post.upvote.assert_called_once_with()
        missing_post.clear_vote.assert_called_once_with()
    else:
        missing_post.upvote.assert_not_called()
        missing_post.clear_vote.assert_not_called()

    if will_attempt_repair:
        if will_fail_repair:
            log_mock.error.assert_called_once_with(
                "Failed to repair submission %s missing from hot posts in channel %s",
                post_id,
                channel_name,
            )
        else:
            log_mock.info.assert_called_once_with(
                "Successfully repaired submission %s missing from hot posts in channel %s",
                post_id,
                channel_name,
            )
def encode(txt):
    print("[+]input is ", end="")
    print(txt)

    print(
        "=============================================================================="
    )
    #base16
    print("[成功]base16 encode: ", end="")
    print(base64.b16encode(txt))

    #base32
    print("[成功]base32 encode: ", end="")
    print(base64.b32encode(txt))

    #base36
    try:
        base36_m_str = bytes.decode(txt)
        base36_m_int = int(base36_m_str)

        base36_cipher = base36.dumps(base36_m_int)
        print("[成功]base36 encode: ", end="")
        print(base36_cipher)
    except Exception as e:
        print("[失败]base36 encode: ", end="")
        print("base36加密只支持整数数字")

    #base58
    print("[成功]base58 encode: ", end="")
    print(base58.b58encode(txt))

    #base62
    print("[成功]base62 encode: ", end="")
    print(base62.encodebytes(txt))

    #base64
    print("[成功]base64 encode: ", end="")
    print(base64.b64encode(txt))

    #base85
    print("[成功]base85 encode: ", end="")
    print(base64.b85encode(txt))

    #base91
    print("[成功]base91 encode: ", end="")
    print(base91.encode(txt))

    #base92
    print("[成功]base92 encode: ", end="")
    print(py3base92.encode(txt))
Example #21
0
    def __init__(self,
                 subreddit_name,
                 author_name,
                 title,
                 body=None,
                 url=None):
        self.id = base36.dumps(FakeSubmission.crt_id)
        self.shortlink = "https://redd.it/" + self.id
        self.permalink = self.shortlink
        self.created_utc = utils.utcnow()
        self.body = body
        self.url = url
        self.deleted = False

        self.selftext = ""
        if body:
            self.selftext = body

        self.domain = "self"
        if self.url:
            self.domain = self.url.split("//")[1].split("/")[0].replace(
                "www.", "")

        self.author = get_user(author_name)
        self.title = title

        self.is_crosspostable = True
        self.link_flair_text = None

        # Add submission to subreddit
        self.subreddit = get_subreddit(subreddit_name)
        self.subreddit.add_submission(self)

        # Add to global cache and increment submission id
        cache_submissions[self.id] = self
        FakeSubmission.crt_id += 1
        cache_info["t3_%s" % self.id] = self

        self.reports = []
        self.comments = []

        self.flairs = None
        # Create a flair instance for each submission
        if self.subreddit.sub_flairs:
            self.flairs = self.FakeFlair(self.subreddit.sub_flairs, self)

        self.mod = FakeSubmission.mod(self)

        # Announce the bot that there is a new submission
        new_all_sub(self)
Example #22
0
def run(s):
    mm = s.strip().encode("utf8")
    output = ""
    try:
        output += "base16:" + base64.b16decode(mm).decode("utf8")
    except:
        output += "base16:失败"
    try:
        output += "\r\nbase24:" + pybase24.decode24(mm)
    except:
        output += "\r\nbase24:失败,pybase24解密貌似代码有问题"
    try:
        output += "\r\nbase32:" + base64.b32decode(mm).decode("utf8")
    except:
        output += "\r\nbase32:失败"
    try:
        output += "\r\nbase36" + str(base36.dumps(int(mm, 10)))
    except:
        output += "\r\nbase36:失败"
    try:
        output += "\r\nbase58:" + base58.b58decode(mm).decode("utf8")
    except:
        output += "\r\nbase58:失败"
    try:
        output += "\r\nbase62:" + base62.decodebytes(
            mm.decode("utf8")).decode("utf8")
    except:
        output += "\r\nbase62:失败"
    try:
        output += "\r\nbase64:" + base64.b64decode(mm).decode("utf8")
    except:
        output += "\r\nbase64:失败"
    try:
        output += "\r\nbase85:" + base64.b85decode(mm).decode("utf8")
    except:
        output += "\r\nbase85:失败"
    try:
        output += "\r\nbase91:" + base91.decode(mm)
    except:
        output += "\r\nbase91:失败"
    try:
        output += "\r\nbase92:" + base92.b92decode(mm).decode("utf8")
    except:
        output += "\r\nbase92:失败"
    try:
        output += "\r\nbase128:" + base128.decode(mm).decode("utf8")
    except:
        output += "\r\nbase128:失败"
    return output
Example #23
0
    def __init__(self, author, body, submission):
        self.author = get_user(author)
        self.body = body
        self.id = base36.dumps(FakeComment.id)
        self.submission = submission
        self.subreddit = submission.subreddit

        self.permalink = "testbot.com/%s/%s" \
            % (self.submission.id, self.id)

        cache_info["t1_%s" % self.id] = self

        FakeComment.id += 1

        new_all_com(self)
Example #24
0
def xhm_uri(category, pincode, setup_id):
    """Generates the X-HM:// uri (Setup Code URI)
	:rtype: str
	"""
    buffer = bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')

    value_low = int(pincode.replace(b'-', b''), 10)
    #print value_low

    value_low |= 1 << 28
    #print value_low

    struct.pack_into('>L', buffer, 4, value_low)

    #print "buffer low:"
    #print ''.join(format(x, '02x') for x in buffer)

    if category == 0:
        buffer[4] = buffer[4] | 1 << 7

    value_high = category >> 1
    #print "value_high"
    #print value_high

    struct.pack_into('>L', buffer, 0, value_high)
    #print "buffer high:"
    #print ''.join(format(x, '02x') for x in buffer)

    #print "unpack 1"
    #print struct.unpack_from('>L', buffer, 4)[0]

    #print "unpack 2"
    #print struct.unpack_from('>L', buffer, 0)[0] * (1 << 32)

    #print "unpack3"
    #print struct.unpack_from('>L', buffer, 4)[0] + (struct.unpack_from('>L', buffer, 0)[0] * (1 << 32))

    encoded_payload = base36.dumps(
        struct.unpack_from('>L', buffer, 4)[0] +
        (struct.unpack_from('>L', buffer, 0)[0] * (1 << 32))).upper()

    #print "encoded_payload"
    #print encoded_payload

    encoded_payload = encoded_payload.rjust(9, '0')
    #print encoded_payload

    return 'X-HM://' + encoded_payload + setup_id
Example #25
0
def cache_put(query_key):
    def new_id():
        ids = mongodb.queries.distinct("_id")
        ids.sort()
        _id = None

        for a, b in itertools.izip(ids, ids[1:]):
            if b - a > 1:
                _id = a + 1
                break
        if not _id:
            _id = b + 1

        return _id

    obj = {}
    if request.method == 'GET':
        obj = request.args.to_dict()

    if request.method == 'POST':
        obj = request.get_json(force=True)

    if not obj:
        return ""

    h = hash(obj)

    doc = mongodb.queries.find_one({"hash": h})

    # if a record exists with this hash already then return
    #  the id for that record
    if doc:
        _id = doc["_id"]

    else:
        _id = new_id(obj)
        obj.update({"_id": _id, "hash": h, "ts": datetime.utcnow()})

        try:
            mongodb.queries.update_one({"_id": _id}, {"$set": obj},
                                       upsert=True)

        except Exception as e:
            log.debug("error writing query {} to MongoDB: {}".format(_id, e))
            return

    return jsonify(base36.dumps(_id))
Example #26
0
def add_post():
    author = request.form.get('author', None)
    topic = request.form.get('topic', None)

    if author and topic:
        # If topic exceeds 255 characters, return with 400 Bad Request.
        if len(topic) > 255 :
            abort(400)
        new_post = Post(base36.dumps(len(posts)), author, topic)
        # Append the new post and sort the posts by upvotes.
        posts.append(new_post)
        posts.sort(reverse=True)

        flash("Post added with id %s" % new_post.post_id)
    else:
        flash("Post failed, please fill both user and topic field above.")

    return redirect(url_for('.index'))
Example #27
0
    def hash_image(self, o):
        img_hash = hashlib.sha1(o)
        img_hex = img_hash.hexdigest()
        img_int = int(img_hex, 16)
        img_36 = base36.dumps(img_int)
        img_dir = 'img/{}/{}'.format(
            img_36[0:2],
            img_36[2:4],
        )
        img_filename = "{}/{}.jpg".format(
            img_dir,
            img_36,
        )

        self.sha1 = img_36
        self.image_location = img_filename

        self.img_hash = img_36
        self.img_dir = img_dir
        self.img_filename = img_filename
Example #28
0
def Base36(mode, data):
    if mode == 0:
        print("[Info]Encryption is in progress......")
        try:
            data_result = base36.dumps(int(data))
            return "[Success]Your cipher_text is:" + data_result
        except:
            print(
                "[Fail]Encryption failed! Please check the information you gave!"
            )
    elif mode == 1:
        print("[Info]Decryption is in progress......")
        try:
            data_result = str(base36.loads(data))
            return "[Success]Your plain_text is:" + data_result
        except:
            print(
                "[Fail]Decryption failed! Please check the information you gave!"
            )
    else:
        print("[ERROR]Invalid Mode!(encode->0/decode->1)")
Example #29
0
def GetP():
    try:
        global JSUGP
        global JSGP
        global JSGPL
        JSUGP = json.dumps(GetPlurkss())
        JSGP = json.loads(JSUGP)
        JSGPL = list(JSGP['plurk_users'].keys())
        GetPlurks.PlurkQualifier = JSGP['plurks'][0]['qualifier']
        Plurkuserids = str(JSGP['plurks'][0]['owner_id'])
        GetPlurks.PlurkUserID = JSGP['plurk_users'][Plurkuserids]['id']
        GetPlurks.PlurkDisplay_Name = JSGP['plurk_users'][Plurkuserids][
            'display_name']
        GetPlurks.PlurkUserURL = 'https://www.plurk.com/' + JSGP[
            'plurk_users'][Plurkuserids]['nick_name']
        GetPlurks.PlurkContent = JSGP['plurks'][0]['content']
        GetPlurks.PlurkContent_raw = JSGP['plurks'][0]['content_raw']
        GetPlurks.PlurkURL = 'https://www.plurk.com/p/' + base36.dumps(
            JSGP['plurks'][0]['plurk_id'])
    except Exception as ex:
        print(ex)
Example #30
0
    def close(self):
        '''
        close()
        Closes the websocket connection and all open channels.
        '''
        for channel in self.channels:
            cmd = api_pb2.Command()  # Generate the command
            cmd.channel = 0
            cmd.closeChan.id = channel  # The channel to close
            cmd.closeChan.action = 1  # 1 is TRY_CLOSE
            cmd.ref = base36.dumps(int(
                str(random.uniform(0, 1)).split('.')[1]))  # Again, make a ref
            data = cmd.SerializeToString()
            self.ws.send(data)  # Serialize and send
            got = False
            while not got:
                res = api_pb2.Command()  # Wait to get a result
                data = self.ws.recv()
                res.ParseFromString(data)
                got = res.closeChanRes.id == channel  # If the channel closed has the right ID, we're good

        self.ws.close()  # Close the websocket
Example #31
0
    def xhm_uri(self):
        """Generates the X-HM:// uri (Setup Code URI)

        :rtype: str
        """
        buffer = bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')

        value_low = int(self.pincode.replace(b'-', b''), 10)
        value_low |= 1 << 28
        struct.pack_into('>L', buffer, 4, value_low)

        if self.category == Category.OTHER:
            buffer[4] = buffer[4] | 1 << 7

        value_high = self.category >> 1
        struct.pack_into('>L', buffer, 0, value_high)

        encoded_payload = base36.dumps(struct.unpack_from('>L', buffer, 4)[0]
                                       + (struct.unpack_from('>L', buffer, 0)[0] * (1 << 32))).upper()
        encoded_payload = encoded_payload.rjust(9, '0')

        return 'X-HM://' + encoded_payload + self.setup_id
Example #32
0
 def generate_usi(self):
     checksum = hashlib.md5()
     checksum.update(str(self.id).encode('utf-8'))
     return (base36.dumps(self.id).zfill(4)[:4] + checksum.hexdigest()[:2]).lower()
Example #33
0
 def next_token():
     token = base36.dumps(int(hashlib.sha256(urandom(32)).hexdigest(), 16))
     return token + '0' if len(token) == 49 else token
Example #34
0
def test_dumps_and_loads_zero():
    assert base36.dumps(0) == '0'
    assert base36.loads('0') == 0
Example #35
0
def test_failure():
    with pytest.raises(TypeError):
        base36.dumps('wrong type')
Example #36
0
def test_dumps_and_loads(number, value):
    assert base36.dumps(number) == value
    assert base36.dumps(-number) == '-' + value
    assert base36.loads(value) == number
    assert base36.loads('-' + value) == -number
Example #37
0
def generate_hash():
    return base36.dumps(random.getrandbits(32))