Example #1
0
def get_transaction(card_number: int, date_format: str):
    transaction = {
        "user_card_number": card_number,
        "bonus_miles": randint(300, 3000),
        "departure_location": generate_code(),
        "arrival_location": generate_code(),
        "departure_date": datetime.utcfromtimestamp(randint(1446372000, 1535365267)).strftime(date_format),
    }

    return transaction
Example #2
0
    def testGetCode(self):
        c = generate_code(alphabet, '^^^^')

        self.assertEqual(len(c), 4)

        for ch in c:
            self.assert_(ch in alphabet)
Example #3
0
 def testGetCode(self):
     c = generate_code(alphabet, '^^^^')
     
     self.assertEqual(len(c), 4)
     
     for ch in c:
         self.assert_(ch in alphabet)
Example #4
0
def password_reset():
    """Password reset request
    """
    if 'username' in session:
        return redirect('/')

    if request.method == 'POST':
        username = request.form['username']
        u = User.query.filter_by(username=username).first()
        if u == None:
            u = User.query.filter_by(email=username).first()
            if u == None:
                # No user found
                flash('No user found under that username/email.', 'error')
                return render_template('password_reset_request.html')

        # Generate and set code for user
        code = generate_code()
        u.code = code
        db.session.commit()

        # Send email with reset link
        callback_url = f'{request.base_url}/callback?code={code}&email={u.email}'
        send(
            to=u.email,
            subject='Password Reset was Requested',
            body=f'Password request link: {callback_url}',
        )

        flash('Email requesting password reset successfully sent!', 'info')
        return render_template('password_reset_request.html')

    else:
        return render_template('password_reset_request.html')
Example #5
0
 def on_post(self, req, resp):
     if 'request' not in req.context.keys():
         raise RError(16)
     request = req.context['request']
     if 'username' not in request.keys():
         raise RError(20)
     if 'password' not in request.keys():
         raise RError(20)
     user = RAdminUser()
     token = utils.generate_code(16)
     user.login_by_password(request['username'], request['password'], token)
     req.context['result'] = {'token': token, 'username': user.info.username, 'level': user.info.level}
Example #6
0
    def create(self, sid):
        print('Create game room called:', sid)
        code = generate_code(5)
        nRoom = {
            'code': code,
            'admin': sid,
            'state': 'WAITING_FOR_PLAYERS',
            'players': []
        }
        self.rooms.insert_one(nRoom)

        return nRoom
Example #7
0
def get_classroom_user_code(classroom_id, user_id, short_code=None):
    if short_code is None:
        short_code = utils.generate_code()

    classroom_user_code_id = insert(
        "INSERT INTO classroom_user_code (classroom_id, user_id, short_code, update_time) VALUES(%s, %s, %s, NOW()) ON DUPLICATE KEY UPDATE update_time = NOW()",
        [classroom_id, user_id, short_code],
    )

    return fetchrow(
        "SELECT classroom_id, user_id, short_code, update_time FROM classroom_user_code WHERE id = %s",
        classroom_user_code_id,
    )
Example #8
0
def generate_point(room):
    print('Generated point thread init.')
    while room in active_rooms:
        nPoint = generate_code(10)
        active_hits.append(nPoint)
        cords = {
            'x' : random.randint(1,100),
            'y' : random.randint(1,100),
        }
        point = {'hitCode':nPoint, 'cords':cords}
        
        print(f'Generated point', room, '@', point)
        socketio.emit('point', dumps(point), room=room, namespace='/game')
        socketio.sleep(1)
def main():
    logging.info('starting up')
    pid = os.fork()
    if pid == 0:
        signal.signal(signal.SIGTERM, on_term)
        pidfile.acquire()
        while True:
            try:
                s = socket.socket(
                    socket.AF_INET, socket.SOCK_STREAM)
                s.connect((config.host, config.port))
                s.send(generate_code(config.secret))
                s.close()
                time.sleep(3)
            except socket.error as e:
                logging.error(e)
    else:
        signal.signal(signal.SIGTERM, on_term)
Example #10
0
def request_code_service(email: str):
    user = mongo.db.users.find_one({'email': email})

    if user:
        code = generate_code()
        cache.set(code, str(user.get('_id')), timeout=1800)

        # TODO I would do it would celery, but I don't see the point of doing it in a test task
        sent_email_thread = Thread(target=send_email,
                                   args=[
                                       current_app._get_current_object(),
                                       user.get('email'), '*****@*****.**',
                                       'Auth code', code
                                   ])
        sent_email_thread.start()

        return {'status': True, 'message': 'Email sent'}

    return None
Example #11
0
 def testFormat(self):
     c = generate_code(alphabet, '^-^-^-^')
     for i in (0,2,4,6):
         self.assert_(c[i] in alphabet)
     for i in (1,3,5):
         self.assertEqual(c[i], '-')
Example #12
0
def main(screen=None):
    if screen is None:
        try:
            token = curses.wrapper(
                main
            )  # Use curses to handle user input, screen clearing and simplify other display management tools

            if token is not None:  # If the game has been interrupted and a token to resume was generated, show a message to inform the user
                print(
                    "This game has been interrupted. To resume, copy paste this token:",
                    token)
        except KeyboardInterrupt:
            pass
        except Exception as e:
            if utils.DEBUG:
                traceback.print_exc()
            else:
                print("Oops! An error occured:", e)
        return

    curses.start_color()  # Enable curses' colors
    curses.use_default_colors()
    curses.curs_set(
        0
    )  # Hide the cursor as we will use a custom way to show the selected color

    if len(sys.argv) > 1 and re.match(
            "^[A-Za-z0-9+/]*=*$", sys.argv[1]
    ):  # If a (seemingly) valid token was provided, resume this game rather than starting a new one
        token = sys.argv[1]
        if len(token) % 4 > 0:
            token += "=" * (
                4 - len(token) % 4
            )  # Fix Base64 padding by adding equal signs at the end of the token

        gamemode, score, games, color_count, max_attempts, code, attempts = utils.decode_token(
            token
        )  # Get all the required information about the pending game from the token
        code_length = len(code)
    else:
        gamemode, code_length, color_count, max_attempts = select_gamemode(
            screen)
        score, games = 0, 0
        code, attempts = None, None

    if gamemode == 0:
        if code is None:
            code = utils.generate_code(
                code_length, color_count
            )  # Generate a random code to "play against the computer"

        return singleplayer.main(screen, color_count, max_attempts, score,
                                 games, code, attempts)
    elif gamemode == 1:
        return online_ranked.main(screen, color_count, max_attempts,
                                  code_length)
    elif gamemode == 2:
        if code is None:
            code = utils.generate_code(
                code_length, color_count
            )  # Generate a random code for the computer to guess

        return computer_vs_computer.main(screen, color_count, max_attempts,
                                         score, games, code, attempts)
    else:
        raise Exception("Unknown gamemode selected: {}".format(gamemode))
Example #13
0
 def testGetCode2(self):
     c = generate_code(alphabet, '^^^^-^^^^')
     c2 = generate_code(alphabet, '^^^^-^^^^')
     self.assertNotEqual(c,c2)
Example #14
0
 def testFormat(self):
     c = generate_code(alphabet, '^-^-^-^')
     for i in (0, 2, 4, 6):
         self.assert_(c[i] in alphabet)
     for i in (1, 3, 5):
         self.assertEqual(c[i], '-')
Example #15
0
 def add_company(self, **values):
     names = self.get_names()
     name = generate_code(names, "c%06d")
     return self.make_resource(name, Company, **values)
Example #16
0
def tick_client(conn, address, data, user_list, scoreboard):
    try:
        buff = data["inputs"].pop(
            0) if data["inputs"] else utils.receive_packet(conn)

        if buff:
            if data["status"] == 200:
                game = user_list[address[0]]["game"]

                guess = [0xFFFF] * len(game["code"])
                for i in range(len(game["code"])):
                    guess[i] = int.from_bytes(buff[2 * i:2 * (i + 1)], "big")

                perfect, partial = utils.compare_codes(guess, game["code"])

                if game["color_count"] == 6 and len(
                        game["code"]) == 4 and guess == [0, 1, 0, 0]:
                    utils.send_packet(conn, (418).to_bytes(2, "big"))

                utils.send_packet(
                    conn,
                    perfect.to_bytes(2, "big") + partial.to_bytes(2, "big"))

                if perfect == len(game["code"]):
                    game["score"] += game["max_attempts"] - len(
                        game["attempts"])
                    game["games"] += 1
                    game["code"] = utils.generate_code(len(game["code"]),
                                                       game["color_count"])
                    game["attempts"] = []

                    if utils.DEBUG:
                        print("Client {}:{} won a game on thread #{}.".format(
                            *address, thread.ident))
                else:
                    game["attempts"].append(guess)
                    if len(game["attempts"]) >= game["max_attempts"]:
                        token = utils.encode_token(
                            game["gamemode"], game["score"], game["games"],
                            game["color_count"], game["max_attempts"],
                            game["code"], game["attempts"])
                        utils.send_packet(conn, token.encode("utf8"))

                        total_attempts = (game["max_attempts"] +
                                          1) * game["games"] - game["score"]
                        normalized_score = game["score"]
                        normalized_score *= game["color_count"]**len(
                            game["code"]) / 1000
                        normalized_score /= 1.2**game["max_attempts"] / 10
                        normalized_score = int(normalized_score)

                        entry = (address[0], user_list[address[0]]["username"],
                                 game["score"], game["games"], total_attempts,
                                 normalized_score, game["color_count"],
                                 len(game["code"]), game["max_attempts"],
                                 time.time())
                        for i, other in enumerate(scoreboard):
                            if other[5] < entry[5] or (
                                    other[5] == entry[5]
                                    and other[3] < entry[3] or
                                (other[3] == entry[3]
                                 and other[4] > entry[4])):
                                scoreboard.insert(i, entry)
                                break
                        else:
                            scoreboard.append(entry)

                        del user_list[address[0]]["game"]
                        user_list[address[0]]["connected"] = False
                        data["status"] = 204
                        utils.send_packet(conn,
                                          data["status"].to_bytes(2, "big"))

                        if utils.DEBUG:
                            print("Client {}:{} lost a game on thread #{}.".
                                  format(*address, thread.ident))

            elif address[0] in user_list and "connected" in user_list[
                    address[0]] and user_list[address[0]]["connected"]:
                data["status"] = 409
                utils.send_packet(conn, data["status"].to_bytes(2, "big"))
                conn.close()

                if utils.DEBUG:
                    print(
                        "Client {}:{} forcefully disconnected from thread #{}."
                        .format(*address, thread.ident))

                return False

            elif data["status"] == 204:
                token = buff.decode("utf8")
                if re.match(r"^SB:\d+ \d+$", token):
                    page_size, offset = map(int, token[3:].split())
                    answer_bytes = bytes()

                    if len(scoreboard) >= offset:
                        for entry in scoreboard[
                                offset:min(offset +
                                           page_size, len(scoreboard))]:
                            username = entry[1].encode("utf8")

                            if 6 + len(answer_bytes) + len(
                                    username) + 6 > 65535:
                                break

                            answer_bytes += (min(len(username), 0xFFFF)
                                             & 0xFFFF).to_bytes(2, "big")
                            answer_bytes += username

                            answer_bytes += (min(entry[5], 0xFFFF)
                                             & 0xFFFF).to_bytes(2, "big")
                            answer_bytes += (min(entry[3], 0xFFFF)
                                             & 0xFFFF).to_bytes(2, "big")
                            answer_bytes += (min(entry[4], 0xFFFF)
                                             & 0xFFFF).to_bytes(2, "big")

                            answer_bytes += (min(entry[4], 0xFFFF)
                                             & 0xFFFF).to_bytes(2, "big")
                            answer_bytes += (min(entry[5], 0xFFFF)
                                             & 0xFFFF).to_bytes(2, "big")
                            answer_bytes += (min(entry[6], 0xFFFF)
                                             & 0xFFFF).to_bytes(2, "big")

                            answer_bytes += (
                                min(int(entry[8] * 1000), 2**64 - 1)
                                & 2**64 - 1).to_bytes(8, "big")

                    utils.send_packet(conn, answer_bytes)
                else:
                    gamemode, score, games, color_count, max_attempts, code, attempts = utils.decode_token(
                        token)

                    score, games = 0, 0
                    code = utils.generate_code(len(code), color_count)

                    user_list[address[0]]["connected"] = True
                    game = {
                        "gamemode": gamemode,
                        "score": score,
                        "games": games,
                        "color_count": color_count,
                        "max_attempts": max_attempts,
                        "code": code,
                        "attempts": []
                    }
                    user_list[address[0]]["game"] = game

                    if len(attempts) > max_attempts:
                        attempts = attempts[:max_attempts]

                    for attempt in attempts:
                        attempt_bytes = bytes()

                        if len(attempt) > len(code):
                            attempt = attempt[:len(code)]
                        elif len(attempt) < len(code):
                            attempt += [0] * (len(code) - len(attempt))

                        for color in attempt:
                            attempt_bytes += (min(color, 0xFFFF)
                                              & 0xFFFF).to_bytes(2, "big")

                        data["inputs"].append(attempt_bytes)

                        if attempt == code:
                            break

                    data["status"] = 200
                    utils.send_packet(conn, data["status"].to_bytes(2, "big"))

                    fake_code = [0xFFFF] * len(game["code"])
                    fake_token = utils.encode_token(game["gamemode"],
                                                    game["score"],
                                                    game["games"],
                                                    game["color_count"],
                                                    game["max_attempts"],
                                                    fake_code, attempts)
                    utils.send_packet(conn, fake_token.encode("utf8"))

                    if utils.DEBUG:
                        print("Client {}:{} started a new game on thread #{}.".
                              format(*address, thread.ident))

            elif data["status"] == 401 or data["status"] == 403:
                username = buff.decode("utf8")

                if buff == b"\x36\x39":
                    for chars in itertools.product(*[
                        [
                            b"\x4e", b"\x6e", b"\xc3\xb1", b"\xc5\x84",
                            b"\xc3\x91", b"\xc5\x83"
                        ],
                        [
                            b"\x69", b"\x49", b"\xc3\xae", b"\xc3\xaf",
                            b"\xc3\xac", b"\xc3\xad", b"\xc4\xaf", b"\xc4\xab",
                            b"\xc3\x8e", b"\xc3\x8f", b"\xc3\x8c", b"\xc3\x8d",
                            b"\xc4\xae", b"\xc4\xaa"
                        ],
                        [
                            b"\x63", b"\x43", b"\xc3\xa7", b"\xc4\x87",
                            b"\xc4\x8d", b"\xc3\x87", b"\xc4\x86", b"\xc4\x8c"
                        ],
                        [
                            b"\x65", b"\x45", b"\xc3\xa9", b"\xc3\xa8",
                            b"\xc3\xaa", b"\xc3\xab", b"\xc4\x99", b"\xc4\x97",
                            b"\xc4\x93", b"\xc3\x89", b"\xc3\x88", b"\xc3\x8a",
                            b"\xc3\x8b", b"\xc4\x98", b"\xc4\x96", b"\xc4\x92"
                        ]
                    ]):
                        username = "".join(
                            map(lambda x: x.decode("utf8"), chars))
                        for other_address in user_list:
                            if username == user_list[other_address][
                                    "username"]:
                                data["status"] = 403
                                utils.send_packet(
                                    conn, data["status"].to_bytes(2, "big"))
                                break
                        else:
                            break
                    else:
                        username = ""

                if 3 <= len(username) <= 32 and set(
                        username) <= USERNAME_CHARACTERS:
                    for other_address in user_list:
                        if username == user_list[other_address]["username"]:
                            data["status"] = 403
                            utils.send_packet(
                                conn, data["status"].to_bytes(2, "big"))
                            break
                    else:
                        user_list[address[0]] = {"username": username}
                        data["status"] = 204
                        utils.send_packet(conn,
                                          data["status"].to_bytes(2, "big"))
                else:
                    data["status"] = 403
                    utils.send_packet(conn, data["status"].to_bytes(2, "big"))

            elif data["status"] == 300:
                if buff.decode("utf8") == "OK":
                    if address[0] in user_list:
                        if not "connected" in user_list[address[
                                0]] or not user_list[address[0]]["connected"]:
                            if "game" in user_list[address[0]] and user_list[
                                    address[0]]["game"] is not None:
                                game = user_list[address[0]]["game"]
                                user_list[address[0]]["connected"] = True

                                attempts = game["attempts"]
                                game["attempts"] = []

                                if len(attempts) > game["max_attempts"]:
                                    attempts = attempts[:game["max_attempts"]]

                                for attempt in attempts:
                                    attempt_bytes = bytes()

                                    if len(attempt) > len(game["code"]):
                                        attempt = attempt[:len(game["code"])]
                                    elif len(attempt) < len(game["code"]):
                                        attempt += [0] * (len(game["code"]) -
                                                          len(attempt))

                                    for color in attempt:
                                        attempt_bytes += (min(color, 0xFFFF)
                                                          & 0xFFFF).to_bytes(
                                                              2, "big")

                                    data["inputs"].append(attempt_bytes)

                                    if attempt == game["code"]:
                                        break

                                data["status"] = 200
                                utils.send_packet(
                                    conn, data["status"].to_bytes(2, "big"))
                                utils.send_packet(
                                    conn, user_list[address[0]]
                                    ["username"].encode("utf8"))

                                fake_code = [0xFFFF] * len(game["code"])
                                fake_token = utils.encode_token(
                                    game["gamemode"], game["score"],
                                    game["games"], game["color_count"],
                                    game["max_attempts"], fake_code, attempts)
                                utils.send_packet(conn,
                                                  fake_token.encode("utf8"))

                                if utils.DEBUG:
                                    print(
                                        "Client {}:{} resumed a game on thread #{}."
                                        .format(*address, thread.ident))
                            else:
                                data["status"] = 204
                                utils.send_packet(
                                    conn, data["status"].to_bytes(2, "big"))
                                utils.send_packet(
                                    conn, user_list[address[0]]
                                    ["username"].encode("utf8"))
                        else:
                            data["status"] = 409
                            utils.send_packet(
                                conn, data["status"].to_bytes(2, "big"))
                            conn.close()

                            if utils.DEBUG:
                                print(
                                    "Client {}:{} forcefully disconnected from thread #{}."
                                    .format(*address, thread.ident))

                            return False
                    else:
                        data["status"] = 401
                        utils.send_packet(conn,
                                          data["status"].to_bytes(2, "big"))

            return True
    except socket.error as e:
        if hasattr(e, "skipped_data"):
            data = e.skipped_data
            if data.decode("utf8").startswith("GET "):
                data += conn.recv(65536 - len(e.skipped_data))
                if re.match(r"^GET .*? HTTP/\d+(?:\.\d+)*\r\n",
                            data.decode("utf8")):
                    conn.send(
                        base64.b64decode(
                            "SFRUUC8xLjEgMjAwIE9LDQpDb250ZW50LVR5cGU6aW1hZ2UvZ2lmDQpDb25uZWN0aW9uOmNsb3NlZA0KDQpHSUY4OWEQAA4A8gAA/wEqFf5J4esIoOc5K+7IycenAAAAAAAAIfkECQQAAAAh/hlPcHRpbWl6ZWQgdXNpbmcgZXpnaWYuY29tACH/C05FVFNDQVBFMi4wAwEAAAAh/wt4bXAgZGF0YXhtcP8/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG10YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS4zLWMwMTEgNjYuMTQ1NjYxLCAyMDEyLzAyLzA2LTE0OjU2OjI3ICAgICAgICAiPjxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53Lm9yZy8xOTk5LzAyLzIyLXJ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0JgJZpMwJnjErKtAoaik87s4MlEr1cDygUgCPR6s9nQeGyCHkVQ8ygFJAAAIfkECQQAAAAsAAABABAADQCCAAAA/SgnN/4K190Gu+EazqatAAAAAAAAAzsIugxTjREBByEwDlummJGzeRTYjML3TdliXWRKNMEbX/T2ysTADIEa7ML5BYM6XQt4bCIVOqdUJJ0CEgAh+QQFBAAAACwAAAAAEAAOAIIAAAD+QwQm/hsI/l3D2R1G7r8AAAAAAAADPwi63K5lifHULFjgSrT4Q+gQHTiAEUN+aDE1pRZmAhyH4WfH7KuSvE5KQQoEgEjComhsIlPIphFJJBylThIgAQA7"
                        ))
                    conn.close()

                    if utils.DEBUG:
                        print("Client {}:{} disconnected from thread #{}.".
                              format(*address, thread.ident))

                    return False

        if e.errno == errno.EWOULDBLOCK:
            return True
        elif utils.DEBUG:
            traceback.print_exc()
        else:
            print(e)
    except Exception as e:
        if utils.DEBUG:
            traceback.print_exc()
        else:
            print(e)
        pass

    conn.close()

    if address[0] in user_list and "connected" in user_list[
            address[0]] and user_list[address[0]]["connected"]:
        user_list[address[0]]["connected"] = False

    if utils.DEBUG:
        print("Client {}:{} disconnected from thread #{}.".format(
            *address, thread.ident))

    return False
Example #17
0
 def testGetCode2(self):
     c = generate_code(alphabet, '^^^^-^^^^')
     c2 = generate_code(alphabet, '^^^^-^^^^')
     self.assertNotEqual(c, c2)
Example #18
0
 def add_mission(self, **kw):
     names = self.get_names()
     name = generate_code(names, 'm%06d')
     return self.make_resource(name, Mission, **kw)
Example #19
0
def withdraw(bot_username):
    if logged_in():
        steam_id = request.form.get("steam_id")
        trade_token = request.form.get("trade_token")
        report_url = request.form.get("report_url")

        assets = json.loads(request.form.get("assets"))
        additional = json.loads(request.form.get("data"))

        current_bot = db_bots.get_username(bot_username)
        if not current_bot.get("active", False):
            report(service_url="http://%s/trade/withdrawals/%s/report" %
                   (CONFIG["SERVICE_HOST"], steam_id),
                   report_url=report_url,
                   status=6,
                   error="The bot you are trying to withdraw is offline",
                   token=CONFIG["ACCESS_TOKEN"],
                   data={
                       "bot": bot_username,
                       "points": additional["points"]
                   })
            return abort(500)

        if len(assets) == 0:
            report(service_url="http://%s/trade/withdrawals/%s/report" %
                   (CONFIG["SERVICE_HOST"], steam_id),
                   report_url=report_url,
                   status=6,
                   error="0 Items to withdraw",
                   token=CONFIG["ACCESS_TOKEN"],
                   data={
                       "bot": bot_username,
                       "points": additional["points"]
                   })
            return abort(500)

        if len(assets) > 50:
            report(service_url="http://%s/trade/withdrawals/%s/report" %
                   (CONFIG["SERVICE_HOST"], steam_id),
                   report_url=report_url,
                   status=6,
                   error="50 Items max to withdraw",
                   token=CONFIG["ACCESS_TOKEN"],
                   data={
                       "bot": bot_username,
                       "points": additional["points"]
                   })
            return abort(500)

        current_bot["password"] = simple_decode(CONFIG["CRYPTO_SALT"],
                                                current_bot["password"])
        current_bot["shared_secret"] = simple_decode(
            CONFIG["CRYPTO_SALT"], current_bot["shared_secret"])
        current_bot["identity_secret"] = simple_decode(
            CONFIG["CRYPTO_SALT"], current_bot["identity_secret"])
        bot_json = {
            "username": str(current_bot["username"]),
            "password": str(current_bot["password"]),
            "shared_secret": str(current_bot["shared_secret"]),
            "identity_secret": str(current_bot["identity_secret"]),
            "device_id": str(current_bot["device_id"])
        }
        security_code = generate_code()
        additional["security_code"] = security_code
        task = withdraw_task.apply_async(args=[
            bot_json, steam_id, trade_token, assets, report_url, additional
        ],
                                         queue="withdraw_task")
        return jsonify({
            "security_code": security_code,
            "bot": current_bot["nickname"],
            "task_id": task.id
        }), 200
    return abort(401)
Example #20
0
def main(screen=None,
         color_count=None,
         max_attempts=None,
         score=0,
         games=0,
         code=None,
         attempts=None):
    if screen is None:
        try:
            token = curses.wrapper(
                main
            )  # Use curses to handle user input, screen clearing and simplify other display management tools

            if token is not None:  # If the game has been interrupted and a token to resume was generated, show a message to inform the user
                print(
                    "This game has been interrupted. To resume, copy paste this token:",
                    token)
        except KeyboardInterrupt:
            pass
        except Exception as e:
            if utils.DEBUG:
                traceback.print_exc()
            else:
                print("Oops! An error occured:", e)
        return

    curses.start_color()  # Enable curses' colors
    curses.use_default_colors()
    curses.curs_set(
        0
    )  # Hide the cursor as we will use a custom way to show the selected color

    code_length = len(code) if code is not None else utils.DEFAULT_CODE_LENGTH

    if color_count is None or color_count <= 0:
        color_count = utils.DEFAULT_COLOR_COUNT

    if max_attempts is None or max_attempts <= 0:
        max_attempts = utils.DEFAULT_MAX_ATTEMPTS

    curses.init_pair(0, -1, utils.find_nearest_color(0, 0, 0))
    curses.init_pair(1, -1, utils.find_nearest_color(1, 1, 1))
    for color in range(
            2, color_count + 2
    ):  # Initialize all the colors we will need, generating them around the color wheel
        # Each color is uniformly spread around the color spectrum, keeping its saturation and value to the max (excludes black and white)
        h, s, v = (color - 2) / color_count, 1.0, 1.0
        r, g, b = colorsys.hsv_to_rgb(
            h, s, v
        )  # Convert the color from HSV (easier to generate) to RGB (easier to manipulate)

        # Because we can't use custom colors in most terminals, we find the closest available one and pair it to the color's id with a white foreground
        curses.init_pair(color, -1, utils.find_nearest_color(r, g, b))

    global line

    while True:  # Play an infinite number of games until the user quits the program (with Ctrl+C)
        screen.clear()
        line = 0

        try:
            if code is None:
                code = utils.generate_code(
                    code_length, color_count
                )  # Generate a random code to "play against the computer"
            if attempts is None:
                attempts = []

            game_score = play_game(screen, color_count, max_attempts, code,
                                   attempts)
            code, attempts = None, None  # Reset the code and the attempts to make the next game independent
        except KeyboardInterrupt:
            screen.move(line, 0)
            screen.clrtoeol(
            )  # Clear the current line, just in case some text was there

            if games > 0:
                screen.addstr("Average score: {}\n\r".format(score / games))
                screen.refresh()
                curses.napms(3000)

            token = utils.encode_token(2, score, games, color_count,
                                       max_attempts, code, attempts)
            return token

        if game_score > 0:
            score += game_score  # If the computer won this game, we increment his score and the number of (consecutive) games he played
            games += 1

        if game_score <= 0:
            score, games = 0, 0  # If he lost, we reset his score and the number of (consecutive) games
Example #21
0
 def add_contact(self, **values):
     names = self.get_names()
     name = generate_code(names, 'c%06d')
     return self.make_resource(name, Contact, **values)
Example #22
0
def deposit():
    if logged_in():
        steam_id = request.form.get("steam_id")
        trade_token = request.form.get("trade_token")
        report_url = request.form.get("report_url")

        assets = json.loads(request.form.get("assets"))
        additional = json.loads(request.form.get("data"))

        active_bots = db_bots.get_all_active()
        if len(active_bots) == 0:
            report(service_url="http://%s/trade/deposits/%s/report" %
                   (CONFIG["SERVICE_HOST"], steam_id),
                   report_url=report_url,
                   status=6,
                   error="All bots are offline",
                   token=CONFIG["ACCESS_TOKEN"],
                   data={"steam_id": steam_id})
            return abort(500)

        if len(assets) == 0:
            report(service_url="http://%s/trade/deposits/%s/report" %
                   (CONFIG["SERVICE_HOST"], steam_id),
                   report_url=report_url,
                   status=6,
                   error="0 Items offered",
                   token=CONFIG["ACCESS_TOKEN"],
                   data={"steam_id": steam_id})
            return abort(500)

        if len(assets) > 100:
            report(service_url="http://%s/trade/deposits/%s/report" %
                   (CONFIG["SERVICE_HOST"], steam_id),
                   report_url=report_url,
                   status=6,
                   error="100 Items max to deposit",
                   token=CONFIG["ACCESS_TOKEN"],
                   data={"steam_id": steam_id})
            return abort(500)

        selected_bot = None
        biggest_inventory = 0
        for bot in active_bots:
            try:
                inventory_len = int(
                    redis.get("bot_%s_invnetory_%s_length" %
                              (str(bot["username"]), 730)))
                if inventory_len + len(
                        assets) + 5 < 950 and inventory_len > biggest_inventory:
                    selected_bot = bot
                    biggest_inventory = inventory_len
            except:
                pass
        if not selected_bot:
            report(service_url="http://%s/trade/deposits/%s/report" %
                   (CONFIG["SERVICE_HOST"], steam_id),
                   report_url=report_url,
                   status=6,
                   error="Cannot find proper bot to handle request",
                   token=CONFIG["ACCESS_TOKEN"],
                   data={"steam_id": steam_id})
            return abort(500)

        selected_bot["password"] = simple_decode(CONFIG["CRYPTO_SALT"],
                                                 selected_bot["password"])
        selected_bot["shared_secret"] = simple_decode(
            CONFIG["CRYPTO_SALT"], selected_bot["shared_secret"])
        selected_bot["identity_secret"] = simple_decode(
            CONFIG["CRYPTO_SALT"], selected_bot["identity_secret"])
        bot_json = {
            "username": str(selected_bot["username"]),
            "password": str(selected_bot["password"]),
            "shared_secret": str(selected_bot["shared_secret"]),
            "identity_secret": str(selected_bot["identity_secret"]),
            "device_id": str(selected_bot["device_id"])
        }
        security_code = generate_code()
        additional["security_code"] = security_code
        task = deposit_task.apply_async(args=[
            bot_json, steam_id, trade_token, assets, report_url, additional
        ],
                                        queue="deposit_task")
        return jsonify({
            "security_code": security_code,
            "bot": selected_bot["nickname"],
            "task_id": task.id
        }), 200
    return abort(401)