Ejemplo n.º 1
0
async def requestToken(pin,client):
    options = {
        "headers": {
            "User-Agent": UserAgent(),
            "Origin": "kahoot.it",
            "Referer": "https://kahoot.it",
            "Accept-Language": "en-US,en;q=0.8",
            "Accept": "*/*"
        },
        "host": "kahoot.it",
        "protocol": "https:",
        "path": f"/reserve/session/{pin}/?{int(time.time() * 1000)}"
    }
    url = (options.get("protocol") or "https:") + "//" + (options.get("host") or "kahoot.it") + (options.get("port") or "") + options.get("path")
    r = requests.request(options.get("method") or "GET",url,headers=options.get("headers"))
    if not r.headers.get("x-kahoot-session-token"):
        raise Exception("Invalid PIN")
    try:
        data = r.json()
        token = r.headers.get("x-kahoot-session-token")
        token = decodeBase64(token)
        return {
            "token": token,
            "data": data
        }
    except Exception as e:
        raise e
Ejemplo n.º 2
0
async def requestChallenge(pin, client):
    options = {
        "headers": {
            "User-Agent": UserAgent(),
            "Origin": "kahoot.it",
            "Referer": "https://kahoot.it",
            "Accept-Language": "en-US,en;q=0.8",
            "Accept": "*/*"
        },
        "host": "kahoot.it",
        "protocol": "https:",
        "path": f"/rest/challenges/pin/{pin}"
    }
    proxyOptions = await client.defaults["proxy"](options)
    # proxy options either returns the options listed above
    # or returns an object with:
    # - headers (list of headers)
    # - text (text response)
    r = None
    try:
        if proxyOptions.get("headers") and proxyOptions.get("text"):
            # Proxied request
            r = proxyOptions

            def json():
                return JSON.loads(r["text"])

            r.json = json
        else:
            if proxyOptions:
                options.update(proxyOptions)
            url = (options.get("protocol") or
                   "https:") + "//" + (options.get("host") or "kahoot.it") + (
                       options.get("port") or "") + options.get("path")
            r = requests.request(options.get("method") or "GET",
                                 url,
                                 headers=options.get("headers"))
    except Exception:
        if proxyOptions:
            options.update(proxyOptions)
        url = (options.get("protocol") or "https:") + "//" + (
            options.get("host") or "kahoot.it") + (options.get("port")
                                                   or "") + options.get("path")
        r = requests.request(options.get("method") or "GET",
                             url,
                             headers=options.get("headers"))
    try:
        data = r.json()
        out = {
            "data": {
                "isChallenge": True,
                "twoFactorAuth": False,
                "kahootData": data.get("kahoot"),
                "rawChallengeData": data["challenge"]
            }
        }
        out["data"].update(data["challenge"]["game_options"])
        return out
    except Exception as e:
        raise e
Ejemplo n.º 3
0
async def requestChallenge(pin,client):
    options = {
        "headers": {
            "User-Agent": UserAgent(),
            "Origin": "kahoot.it",
            "Referer": "https://kahoot.it",
            "Accept-Language": "en-US,en;q=0.8",
            "Accept": "*/*"
        },
        "host": "kahoot.it",
        "protocol": "https:",
        "path": f"/rest/challenges/pin/{pin}"
    }
    url = (options.get("protocol") or "https:") + "//" + (options.get("host") or "kahoot.it") + (options.get("port") or "") + options.get("path")
    r = requests.request(options.get("method") or "GET",url,headers=options.get("headers"))
    try:
        data = r.json()
        out = {
            "data": {
                "isChallenge": True,
                "twoFactorAuth": False,
                "kahootData": data.get("kahoot"),
                "rawChallengeData": data["challenge"]
            }
        }
        out["data"].update(data["challenge"]["game_options"])
        return out
    except Exception as e:
        raise e
Ejemplo n.º 4
0
 def relog(self, cid):
     if not self.ready:
         time.sleep(0.5)
         self.relog(cid)
         return
     self.msgID += 1
     packet = {
         "channel": "/service/controller",
         "clientId": self.clientID,
         "data": {
             "cid":
             cid,
             "content":
             JSON.dumps({
                 "device": {
                     "userAgent": UserAgent(),
                     "screen": {
                         "width": 2000,
                         "height": 1000
                     }
                 }
             }),
             "gameid":
             self.gameID,
             "host":
             "kahoot.it",
             "type":
             "relogin"
         },
         "ext": {},
         "id": str(self.msgID)
     }
     self.send([packet])
Ejemplo n.º 5
0
async def requestToken(pin, client):
    options = {
        "headers": {
            "User-Agent": UserAgent(),
            "Origin": "kahoot.it",
            "Referer": "https://kahoot.it",
            "Accept-Language": "en-US,en;q=0.8",
            "Accept": "*/*"
        },
        "host": "kahoot.it",
        "protocol": "https:",
        "path": f"/reserve/session/{pin}/?{int(time.time() * 1000)}"
    }
    proxyOptions = await client.defaults["proxy"](options)
    # proxy options either returns the options listed above
    # or returns an object with:
    # - headers (list of headers)
    # - text (text response)
    r = None
    try:
        if proxyOptions.get("headers") and proxyOptions.get("text"):
            # Proxied request
            r = proxyOptions

            def json():
                return JSON.loads(r["text"])

            r.json = json
        else:
            if proxyOptions:
                options.update(proxyOptions)
            url = (options.get("protocol") or
                   "https:") + "//" + (options.get("host") or "kahoot.it") + (
                       options.get("port") or "") + options.get("path")
            r = requests.request(options.get("method") or "GET",
                                 url,
                                 headers=options.get("headers"))
    except Exception:
        if proxyOptions:
            options.update(proxyOptions)
        url = (options.get("protocol") or "https:") + "//" + (
            options.get("host") or "kahoot.it") + (options.get("port")
                                                   or "") + options.get("path")
        r = requests.request(options.get("method") or "GET",
                             url,
                             headers=options.get("headers"))
    if not r.headers.get("x-kahoot-session-token"):
        raise "Invalid PIN"
    try:
        data = r.json()
        token = r.headers.get("x-kahoot-session-token")
        token = decodeBase64(token)
        return {"token": token, "data": data}
    except Exception as e:
        raise e
Ejemplo n.º 6
0
    def __init__(self, options={}):
        super().__init__()
        self.defaults = {}
        # Assign the default values
        for i in client._defaults:
            if callable(client._defaults[i]):
                # TODO: Check if this is needed.
                self.defaults[i] = copy_func(client._defaults[i])
                continue
            self.defaults[i] = copy.deepcopy(client._defaults[i])
        # Assign values from options
        self.defaults["options"].update(options.get("options") or {})
        self.defaults["modules"].update(options.get("modules") or {})
        self.defaults["proxy"] = options.get("proxy") or self.defaults["proxy"]
        self.defaults["wsproxy"] = options.get(
            "wsproxy") or self.defaults["wsproxy"]
        # Set up some data
        self.classes = {}
        self.handlers = {}
        self.waiting = {}
        self.data = {}
        self.cid = None
        self.gameid = None
        self.socket = None
        self.settings = None
        self.questionStartTime = None
        self.reconnectRecovery = None
        self.feedbackTime = None
        self.connected = False
        self.name = None
        self.quiz = None
        self.clientId = None
        self.loggingMode = False
        self.lastEvent = (None, None)
        self._timesync = {}
        self.twoFactorResetTime = None
        self.disconnectReason = None
        # Import modules
        for mod in self.defaults["modules"]:
            if self.defaults["modules"].get(
                    mod) or self.defaults["modules"].get(mod) == None:
                try:
                    f = getattr(
                        importlib.import_module(".src.modules." + mod,
                                                "kahootpy"), "main")
                    f(self)
                except Exception:
                    pass
        m = getattr(importlib.import_module(".src.modules.main", "kahootpy"),
                    "main")
        m(self)

        self.userAgent = UserAgent()
        self.messageId = 0
Ejemplo n.º 7
0
 def add_new_users(self):
     num_agents = random.choice([i for i in range(MAX_NUMBER_OF_NEW_USERS)])
     # Create users
     for i in range(num_agents):
         user = UserAgent(
             self.increment_curr_user_id(), define_user_interests(),
             define_user_actions_probabilities(self.exp_normalized),
             self.define_user_influence(), self)
         self.schedule.add(user)
         self.users.append(user)
         user.add_random_friends(10)
         user.expand_influence()
Ejemplo n.º 8
0
 def login(self, name, team):
     if not self.ready:
         time.sleep(0.5)
         self.login(name, team)
         return
     self.name = name
     self.msgID += 1
     joinPacket = [{
         "channel": "/service/controller",
         "clientId": self.clientID,
         "data": {
             "content": '{"device":{"userAgent":"' + UserAgent() +
             '","screen":{"width":1280,"height":800}}}',
             "gameid": self.gameID,
             "host": consts.ENDPOINT_URI,
             "name": self.name,
             "type": "login"
         },
         "ext": {},
         "participantUserId": None,
         "id": str(self.msgID)
     }]
     time.sleep(0.5)
     self.send(joinPacket)
     if self.kahoot.gamemode == "team":
         joinPacket2 = [{
             "channel": "/service/controller",
             "clientId": self.clientID,
             "data": {
                 "content":
                 JSON.dumps(
                     team if type(team) ==
                     type(list()) else team if len(team) else
                     ["Player 1", "Player 2", "Player 3", "Player 4"]),
                 "gameid":
                 self.gameID,
                 "host":
                 consts.ENDPOINT_URI,
                 "id":
                 18,
                 "type":
                 "message"
             },
             "ext": {},
             "participantUserId": None,
             "id": str(self.msgID)
         }]
         self.msgID += 1
         time.sleep(0.5)
         self.send(joinPacket2)
Ejemplo n.º 9
0
    def __init__(self, num_agents):
        super().__init__()

        self.running = True
        self.num_agents = num_agents
        self.schedule = RandomActivation(self)
        self.schedule_groups = RandomActivation(self)
        self.schedule_roles = RandomActivation(self)
        self.exp = np.random.exponential(1, num_agents * 2)
        self.exp_normalized = [
            float(value) / max(self.exp) for value in self.exp
        ]
        self.influence_values = deepcopy(self.exp_normalized)
        self.users = []
        self.role_agents = []
        self.groups = []
        self.curr_user_id = 0
        self.negotiations = {}
        self.roles_count = defaultdict(list)
        self.curr_iteration = 0
        self.role_changes_from = {}

        for role in roles:
            self.roles_count[role] = []

        # Create users
        for i in range(num_agents):
            user = UserAgent(
                self.increment_curr_user_id(), define_user_interests(),
                define_user_actions_probabilities(self.exp_normalized),
                self.define_user_influence(), self)
            self.schedule.add(user)
            self.users.append(user)
        for user in self.users:
            user.add_random_friends(
                round(
                    math.ceil(
                        random.choice(self.exp_normalized) * num_agents / 3)) +
                1)
            user.expand_influence()

        self.data_collector = DataCollector(
            agent_reporters={"Post_written": get_number_of_post_written})

        self.data_group_collector = DataCollector(
            model_reporters={
                "biggestGroup": biggest_group,
                "groupSizeDistribution": group_size_dist,
                "number_of_groups": get_number_of_groups
            })
Ejemplo n.º 10
0
async def main():
    bus = AIORedisSignalBus('redis://localhost/7')
    broker = AIORedisBroker('redis://localhost/7')
    await bus.started.send('user_agent')

    user_agent = UserAgent(bus=bus, broker=broker)
    comment_agent = CommentAgent(bus=bus, broker=broker)
    email_agent = EmailAgent(broker=broker)

    await user_agent.start()
    await comment_agent.start()
    await email_agent.start()

    while True:
        await asyncio.sleep(60)
Ejemplo n.º 11
0
def requestChallenge(sessionID, callback, proxy):
    proxyOptions = None
    nopath = None
    if type(proxy) == type(str()):
        proxy = proxy or ""
    elif proxy and proxy.get("proxy"):
        proxyOptions = proxy.get("options") or {}
        nopath = proxy.get("nopath")
        proxy = proxy.get("proxy")
    else:
        proxy = ""
    uri = None
    if not nopath:
        if proxy[-1] == "/":
            uri = proxy + "https://" + consts.ENDPOINT_URI + consts.CHALLENGE_ENDPOINT + "/pin/" + sessionID
        else:
            uri = proxy + "/https://" + consts.ENDPOINT_URI + consts.CHALLENGE_ENDPOINT + "/pin/" + sessionID
    _uri = urllib.parse.urlparse(uri)
    options = {
        "port": consts.ENDPOINT_PORT,
        "headers": {
            "user-agent": UserAgent(),
            "host": (proxy and uri.hostname) or "kahoot.it",
            "referer": "https://kahoot.it/",
            "accept-language": "en-US,en;q=0.8",
            "accept": "*/*"
        }
    }
    if proxyOptions:
        options.update(proxyOptions)
    r = requests.get(uri)
    try:
        data = r.json()
    except Exception as e:
        return callback(None, e, None)
    try:
        inf = {
            "twoFactorAuth": False,
            "gameMode": data["challenge"]["type"],
            "kahootData": data["kahoot"],
            "rawChallengeData": data["challenge"]
        }.update(data["challenge"]["game_options"])
        return callback(True, inf)
    except Exception as e:
        return callback(None, e, None)
Ejemplo n.º 12
0
def requestToken(sessionID, callback, proxy):
    proxyOptions = None
    nopath = None
    if type(proxy) == type(str()):
        proxy = proxy or ""
    elif proxy and proxy.get("proxy"):
        proxyOptions = proxy.get("options") or {}
        nopath = proxy.get("nopath")
        proxy = proxy.get("proxy")
    else:
        proxy = ""
    uri = None
    if not nopath:
        if proxy and proxy[-1] == "/":
            uri = proxy + "https://" + consts.ENDPOINT_URI + consts.TOKEN_ENDPOINT + str(
                sessionID) + "/?" + str(math.floor(time.time() * 1000))
        elif proxy:
            uri = proxy + "/https://" + consts.ENDPOINT_URI + consts.TOKEN_ENDPOINT + str(
                sessionID) + "/?" + str(math.floor(time.time() * 1000))
        else:
            uri = "https://" + consts.ENDPOINT_URI + consts.TOKEN_ENDPOINT + str(
                sessionID) + "/?" + str(math.floor(time.time() * 1000))
    _uri = urllib.parse.urlparse(uri)
    options = {
        "port": consts.ENDPOINT_PORT,
        "headers": {
            "user-agent": UserAgent(),
            "host": (proxy and uri.hostname) or "kahoot.it",
            "referer": "https://kahoot.it/",
            "accept-language": "en-US,en;q=0.8",
            "accept": "*/*"
        }
    }
    if proxyOptions:
        options.update(proxyOptions)
    r = requests.get(uri)
    if not r.headers.get("x-kahoot-session-token"):
        return callback(None, None, None)
    try:
        data = r.json()
    except Exception as e:
        return callback(None, e, None)
    callback(r.headers.get("x-kahoot-session-token"), data["challenge"], data)
Ejemplo n.º 13
0
def main():
    key = os.environ.get('API_KEY', None)
    if key is None:
        sys.exit('Please provide an API key provided for lookup [env=API_KEY]')

    args = parse_args(sys.argv[1:])

    print 'Looking for the closest store near the provided address...'
    client = GoogleClient(UserAgent(), key)
    current_location = client.get_coords(args.address)

    closest_store = get_closest_store(current_location)

    output = client.get_distance(args.address, closest_store, units=args.units)

    print '...Done!'

    print '=============================================================='
    print format_output(output, args.output)
    print '=============================================================='
Ejemplo n.º 14
0
 def __init__(self):
     super().__init__()
     self.classes = {}
     self.connected = False
     self.data = {}
     self.gameid = None
     self.handlers = {}
     self.loggingMode = False
     self.name = None
     self.reconnectRecovery = None
     self.settings = {}
     self.socket = None
     self.twoFactorResetTime = None
     self.userAgent = UserAgent()
     self.quiz = {}
     for module in ("answer", "backup", "extraData", "feedback",
                    "gameReset", "main", "nameAccept", "podium",
                    "questionEnd", "questionReady", "questionStart",
                    "quizEnd", "quizStart", "teamAccept", "teamTalk",
                    "timeOver"):
         f = getattr(
             importlib.import_module(f".src.modules.{module}", "KahootPY"),
             "main")
         f(self)