Пример #1
0
def tick_city(city):
    """ Process city resource consumption and growth. """

    city_volume = city.population // 100

    city_resources = {
        resource_slot.resource.name: resource_slot for resource_slot in city.resources
    }

    critical = False
    growth_triggers = []
    for resource, slot in city_resources.items():
        demand = CONSUMPTION_RATIOS[resource] * city_volume

        LOGGER.debug(f"{slot}")
        need = demand - slot.amount
        if need <= 0:
            LOGGER.debug(
                f"{city} has enough {resource} to consume {demand} with {-need} left over"
            )
            slot.amount -= demand
            growth_triggers.append(
                partial(process_surplus, -need, resource, city, slot)
            )
        else:
            LOGGER.debug(f"{city} does not have enough to consume {demand}")
            process_deficit(need, resource, city, slot)
            critical = True

    if not critical:
        for trigger in growth_triggers:
            trigger()

    LOGGER.info(f"{city} population {city.population} updated")
    socketio.emit("city_updated", city)
Пример #2
0
def get_all_citations(data):
    email = session.get("user")
    project_name = data["project_name"]
    citation_list = []
    with app.app_context():
        user_info = db.session.query(Users).filter(Users.email == email).one()
        project_info = (db.session.query(Projects).filter(
            Projects.owner_id == user_info.user_id,
            Projects.project_name == project_name,
        ).first())
    if project_info:
        log.info("Getting citations for <%s> owned by <%s>", project_name,
                 email)
        project_id = project_info.project_id
        with app.app_context():
            citations = (db.session.query(Citations).filter(
                Citations.project_id == project_id).order_by(
                    Citations.author.asc()).all())
            for citation in citations:
                citation_list.append({
                    "mla": citation.mla_citation,
                    "apa": citation.apa_citation,
                    "source_id": citation.source_id,
                    "is_cited": citation.is_cited,
                })
            socketio.emit(
                "all_citations",
                {
                    "citation_list": citation_list,
                },
                room=request.sid,
            )
    else:
        log.warning("No project named <%s> is owned by <%s>", project_name,
                    email)
Пример #3
0
    def progress_listener(self, value):
        time = default_timer()
        if self.last_time is not None:
            self.progress_diffs.append(value - self.last_progress)
            self.time_diffs.append(time - self.last_time)

        if self.last_progress > 0.1:  # The first few updates tend to be unstable
            # Estimate average time per progress value
            current_average = np.average(
                self.time_diffs, weights=self.progress_diffs) / np.mean(
                    self.progress_diffs)
            self.average_times.append(current_average)

            remaining_time = round(
                np.median(self.average_times) *
                (1 - value))  # The median should be relatively stable
        else:
            remaining_time = None

        self.last_progress = value
        self.last_time = time

        data = {'progress': value, 'remaining_time': remaining_time}
        socketio.emit('update_progress', data, room=session_mapper[self.sid])

        # When using eventlet as webserver instead of the default development server, emits get stalled and only passed to the client at the end. This is most likely because the eventlet thread gets no CPU time (https://github.com/miguelgrinberg/Flask-SocketIO/issues/394#issuecomment-273842453).
        # The following call flushes the emits and ensures that the client gets the status updates faster (https://stackoverflow.com/a/36204786)
        # Note: at least currently, monkeypatching (https://stackoverflow.com/questions/34581255/python-flask-socketio-send-message-from-thread-not-always-working) seems not to be required which is another common cause of problems
        socketio.sleep(0)
Пример #4
0
 def __ping(self):
     log.debug("{}: ping request".format(self.__sid))
     self.__ping_token = random.randint(1, 10000000)
     self.__ping_ts = time.time()
     socketio.emit('latency_ping', {"token": self.__ping_token},
                   namespace='/publish', room=self.__sid)
     self.__heartbeat = eventlet.greenthread.spawn_after(self.PING_DELAY,
                                                         self.__ping)
Пример #5
0
def on_login_request(data):
    email = data["email"]
    log.info("Logging in <%s>", email)
    with app.app_context():
        user_info = db.session.query(Users).filter(
            Users.email == email).one().json()
    session["user"] = email
    socketio.emit("login_response", user_info, room=request.sid)
Пример #6
0
 def robberRequest(name, *args):
     if not request.sid == robber.sid:
         raise Exception("Authorization Error")
     oldrole = users[users.startrole == "robber"].iloc[0].currentrole
     newrole = users[users.username == name].iloc[0].currentrole
     users.loc[users.startrole == "robber", "currentrole"] = newrole
     users.loc[users.username == name, "currentrole"] = oldrole
     socketio.emit("robberResponse", newrole, room=robber.sid)
Пример #7
0
def handle_software_updates_check():
    result = software_updates.compare_local_remote_tags()
    if result:
        if result["behind_remote"]:
            toast = """A new update is available ({0})\n
            Your version is {1}\n
            Check the github page to update to the latest version.
            """.format(result["remote_latest"], result["local"])
            socketio.emit("software_updates_response", toast)
Пример #8
0
 def __ping(self):
     log.debug(f"{self.__sid}: ping request")
     self.__ping_token = random.randint(1, 10000000)
     self.__ping_ts = time.time()
     socketio.emit('latency_ping', {"token": self.__ping_token},
                   namespace='/publish',
                   room=self.__sid)
     self.__heartbeat = eventlet.greenthread.spawn_after(
         self.PING_DELAY, self.__ping)
Пример #9
0
def messageJSON(JSONMessage):
    now = datetime.datetime.now()
    timeNow = "(" + str(now.hour) + ":" + str(now.minute) + ") "
    m = Message(JSONMessage['message'], JSONMessage['room'], \
        current_user.id, now)
    message = timeNow + current_user.username + ": " + JSONMessage['message']
    db.session.add(m)
    db.session.commit()
    socketio.emit("receivedMessage", message, \
        room=JSONMessage['room'])
Пример #10
0
 def __process_timeout(self):
     log.info(
         "{}: no ping reply in {} seconds, setting latency to -1".format(
             self.__sid, self.TIMEOUT_THRESHOLD))
     self.latency = -1
     self.__timeout = eventlet.greenthread.spawn_after(
         self.TIMEOUT_THRESHOLD, self.__process_timeout)
     socketio.emit('update publishers',
                   {'data': clean_publishers(), 'update': self.nick,
                    'show': False}, namespace='/subscribe', broadcast=True)
Пример #11
0
def on_request_project():
    if "user" in session:
        email = session.get("user")
        selected_project = session.get("selected_project")
        socketio.emit("give_project_name", {"project_name": selected_project},
                      room=request.sid)
        log.info("Returning project name <%s> for <%s>", selected_project,
                 email)
    else:
        log.warning("No login found")
Пример #12
0
 def seerRequest(names, *args):
     if not request.sid == seer.sid:
         raise Exception("Authorization Error")
     response = {}
     for name in names:
         if name in ["1", "2", "3"]:
             response[name] = config["centerRoles"][int(name) - 1]
         else:
             u = users[users.username == name].iloc[0]
             response[name] = u.currentrole
     socketio.emit("seerResponse", response, room=seer.sid)
def processor():
    client = base.Client(('localhost', 11211))

    while True:
        message = client.get('can')

        if message:
            socketio.emit('can', pickle.loads(message))
            client.delete('can')

        time.sleep(1)
Пример #14
0
def on_request_user_info():
    email = session.get("user")
    if email:
        log.info("Sending user info of <%s>", email)
        with app.app_context():
            user_info = (db.session.query(Users).filter(
                Users.email == email).one().json())
        socketio.emit("user_info", user_info, room=request.sid)
        emit_projects(user_info["user_id"])
    else:
        socketio.emit("redirect_to_login")
        log.warning("No login found")
Пример #15
0
def finish_judge(submission_id, judge_status):
    """ジャッジ終了時に呼ぶ!

    Args:
        submission_id (str) : 提出ID
        judge_status (str) : ジャッジステータス

    Returns:
        None
    """

    socketio.emit("update_judge_status", (submission_id, judge_status))
Пример #16
0
def day(users, config, roomid):
    print("Day phase")
    socketio.emit("startDay", room=roomid)

    # TODO: time limit for voting

    votes = {u: False for u in users.userid.tolist()}
    for uid in users.userid.tolist():

        def voteRecieved(u, vote, *args):
            if not "userid" in session: raise Exception("Authorization Error")
            if not u == session["userid"]:
                raise Exception("Authorization Error")
            votes[u] = vote

        socketio.on_event("vote",
                          partial(voteRecieved, uid),
                          namespace=f"/{uid}")
    while not all(votes.values()):
        time.sleep(0.1)

    votes = list(votes.values())
    print("votes:", votes)
    maxNumVotes = max([votes.count(v) for v in votes])
    killed = [v for v in votes if votes.count(v) == maxNumVotes]

    werewolvesWin = True
    for name in killed:
        u = users[users.username == name].iloc[0]
        if u.currentrole == "werewolf":
            werewolvesWin = False

    startRoles = {
        user.username: user.startrole
        for _, user in users.iterrows()
    }
    for i, r in enumerate(config["startCenterRoles"]):
        startRoles[str(i + 1)] = r

    finalRoles = {
        user.username: user.currentrole
        for _, user in users.iterrows()
    }
    for i, r in enumerate(config["centerRoles"]):
        finalRoles[str(i + 1)] = r

    gameOverInfo = {
        "startRoles": startRoles,
        "finalRoles": finalRoles,
        "winningTeam": "werewolf" if werewolvesWin else "villager",
    }
    socketio.emit("gameover", gameOverInfo, room=roomid)
Пример #17
0
def change_grid_dims(message):
    log.info("Changing grid dims: [{}, {}]".format(message['width'],
                                                   message['height']))

    width = int(message['width'])
    height = int(message['height'])

    redisc.set('grid_width', width)
    redisc.set('grid_height', height)

    # GLOBAL EMIT to all connected clients with the new dimensions
    socketio.emit("create_grid", {'width': width, 'height': height})
    reset_grid(width, height)
Пример #18
0
    def pong(self, token):
        log.debug("{}: pong received".format(self.__sid))
        if not self.__ping_token == token:
            log.warning("{}: Invalid token, ignoring...".format(self.__sid))
            return
        self.latency = round(time.time() - self.__ping_ts, 3)
        socketio.emit('update publishers',
                      {'data': clean_publishers(), 'update': self.nick,
                       'show': False}, namespace='/subscribe', broadcast=True)

        # reset timeout
        self.__timeout.cancel()
        self.__timeout = eventlet.greenthread.spawn_after(
            self.TIMEOUT_THRESHOLD, self.__process_timeout)
Пример #19
0
 def __process_timeout(self):
     log.info(
         "{}: no ping reply in {} seconds, setting latency to -1".format(
             self.__sid, self.TIMEOUT_THRESHOLD))
     self.latency = -1
     self.__timeout = eventlet.greenthread.spawn_after(
         self.TIMEOUT_THRESHOLD, self.__process_timeout)
     socketio.emit('update publishers', {
         'data': clean_publishers(),
         'update': self.nick,
         'show': False
     },
                   namespace='/subscribe',
                   broadcast=True)
Пример #20
0
    def check_players():
        for user in list(ACTIVE_PLAYERS):
            deadline = datetime.today() - timedelta(seconds=INACTIVE_TIMEOUT)
            inactive = user.last_seen < deadline
            LOGGER.debug(f"Checking {user} for inactivity: "
                         f"{user.last_seen.strftime('%H:%M:%S')} "
                         f"< {deadline.strftime('%H:%M:%S')} "
                         f"== {inactive}")
            if inactive:
                ACTIVE_PLAYERS.remove(user)

                LOGGER.info(f"Logging out {user} due to inactivity")

                socketio.emit("player_logout", user.id)
Пример #21
0
def reset_grid(width, height):
    for i in range(width*height):
        # TODO need to set up a callback with this 
        # mqtt.unsubscribe_all()

        # subscribe to appropriate mqtt topic
        topic = get_topic_from_index(i, width, height)
        log.info("Subscribing to Topic: {}".format(topic))
        mqtt.subscribe(topic)

        # populate the board with white tiles
        message = {"id": topic, "color": "#ffffff"}
        redisc.set(topic, "#ffffff")
        socketio.emit("server_update_light", message)
Пример #22
0
def emit_projects(owner_id: str) -> None:
    log.debug("Sending all projects created by user with ID <%s>", owner_id)
    with app.app_context():
        user_projects = (db.session.query(Projects).filter(
            Projects.owner_id == owner_id).all())
    response = {
        project.project_id: {
            "project_id": project.project_id,
            "owner_id": project.owner_id,
            "project_name": project.project_name,
            "sources": project.sources,
            "citation_type": project.citation_type,
        }
        for project in user_projects
    }
    log.debug("Sending these IDs via all_projects: %s", list(response.keys()))
    socketio.emit("all_projects", response, room=request.sid)
Пример #23
0
def broadcast_sync_suggestion(suggest_sync: bool, status: PlayerState,
                              position: int):
    requester_nick = publishers[request.sid].nick

    if suggest_sync == SyncSuggestion.STATE.value:
        global current_state
        request_str = "Pause"  # default/catch-all
        emit_str = "pause"

        if status == PlayerState.PLAYING:
            current_state = PlayerState.PLAYING
            request_str = "Resume"
            emit_str = "resume"
        if status == PlayerState.PAUSED:
            current_state = PlayerState.PAUSED
            request_str = "Pause"
            emit_str = "pause"

        socketio.emit("log_message", {
            "data": f'{request_str} requested by "{requester_nick}"',
            "state": current_state.value
        },
                      namespace="/subscribe")
        emit(emit_str, {'explicit': False},
             namespace="/publish",
             broadcast=True,
             include_self=False)

    elif suggest_sync == SyncSuggestion.SEEK.value:
        socketio.emit("log_message", {
            "data": f'Seek requested by "{requester_nick}"',
        },
                      namespace="/subscribe")
        emit("seek", {
            "seek": position,
            "explicit": False
        },
             namespace="/publish",
             broadcast=True,
             include_self=False)

    else:
        msg = f"Received bad suggest_sync: {suggest_sync}"
        log.error(msg)
        emit('log_message', {'data': msg})
        return False
Пример #24
0
    def pong(self, token):
        log.debug(f"{self.__sid}: pong received")
        if not self.__ping_token == token:
            log.warning(f"{self.__sid}: Invalid token, ignoring...")
            return
        self.latency = round(time.time() - self.__ping_ts, 3)
        socketio.emit('update publishers', {
            'data': clean_publishers(),
            'update': self.nick,
            'show': False
        },
                      namespace='/subscribe',
                      broadcast=True)

        # reset timeout
        self.__timeout.cancel()
        self.__timeout = eventlet.greenthread.spawn_after(
            self.TIMEOUT_THRESHOLD, self.__process_timeout)
Пример #25
0
def start_judge(submission_id):
    """ジャッジ開始時に呼ぶ!

    Args:
        submission_id (str) : 提出ID

    Returns:
        None
    """

    # ステータス変更
    connect = sqlite3.connect("./server/DB/problem.db")
    cur = connect.cursor()
    cur.execute("UPDATE submission SET status = -1 WHERE id = ?",
                (submission_id, ))
    connect.commit()
    cur.close()
    connect.close()

    socketio.emit("update_judge_status", (submission_id, "SJ"))
Пример #26
0
def add_judge_job(submission_id):
    """ジャッジジョブ追加

    Args:
        submission_id (str) : 提出ID

    Returns:
        None
    """
    # ステータス変更
    connect = sqlite3.connect("./server/DB/problem.db")
    cur = connect.cursor()
    cur.execute("UPDATE submission SET status = 0 WHERE id = ?",
                (submission_id, ))
    connect.commit()
    cur.close()
    connect.close()

    socketio.emit("update_judge_status", (submission_id, "WJ"))
    executor.submit(judge_code, submission_id)
Пример #27
0
def add_source(data):
    email = session.get("user")
    project_name = data["project_name"]
    source_link = data["source_link"]
    source_id = str(uuid.uuid4())
    source_found = get_source_info(source_id, source_link)

    with app.app_context():
        user_info = db.session.query(Users).filter(Users.email == email).one()
        project_info = (db.session.query(Projects).filter(
            Projects.owner_id == user_info.user_id,
            Projects.project_name == project_name,
        ).first())
        log.debug("Before adding new source: %s", project_info.sources)

        source_map = create_source_map(project_info.sources)
        if source_found:
            log.info("Added new source to project <%s>", project_name)
            create_citation(source_id, project_info.project_id, project_name)
            source_map[source_id] = source_link
            project_info.sources = list(project_info.sources)
            project_info.sources.append(source_id)
            db.session.merge(project_info)
            db.session.commit()
        else:
            log.warning("Failed to add source to project <%s>", project_name)
            socketio.emit(
                "invalid_url",
                {"source_link": source_link},
                room=request.sid,
            )
        log.debug("After adding new source: %s", project_info.sources)

    socketio.emit(
        "all_sources_server",
        {
            "source_list": list(project_info.sources),
            "source_map": source_map
        },
        room=request.sid,
    )
Пример #28
0
def on_delete_source(data):
    email = session.get("user")
    project_name = data["project_name"]
    source_id = data["source_id"]

    with app.app_context():
        user_info = db.session.query(Users).filter(Users.email == email).one()
        project_info = (db.session.query(Projects).filter(
            Projects.owner_id == user_info.user_id,
            Projects.project_name == project_name,
        ).one())

        log.debug("Source list before removing: <%s>", project_info.sources)
        project_info.sources = list(project_info.sources)
        project_info.sources.remove(source_id)
        db.session.merge(project_info)
        db.session.commit()
        log.debug("Source list after removing: <%s>", project_info.sources)

        Citations.query.filter(Citations.source_id == source_id).delete()
        log.debug("Deleting citation that matches the source ID <%s>",
                  source_id)
        db.session.commit()

    # This is placed here separately due to a notorious bug in pytest-flask-sqlalchemy
    with app.app_context():
        Sources.query.filter(Sources.source_id == source_id).delete()
        log.info("Deleting source that matches the ID <%s>", source_id)
        db.session.commit()

    source_map = create_source_map(project_info.sources)
    socketio.emit(
        "all_sources_server",
        {
            "source_list": list(project_info.sources),
            "source_map": source_map
        },
        room=request.sid,
    )
Пример #29
0
def get_all_sources(data):
    email = session.get("user")
    project_name = data["project_name"]
    with app.app_context():
        user_info = db.session.query(Users).filter(Users.email == email).one()
        project_info = (db.session.query(Projects).filter(
            Projects.owner_id == user_info.user_id,
            Projects.project_name == project_name,
        ).first())
    if project_info:
        log.info("Getting source information for <%s> owned by <%s>",
                 project_name, email)
        source_map = create_source_map(project_info.sources)
        socketio.emit(
            "all_sources",
            {
                "source_list": list(project_info.sources),
                "source_map": source_map
            },
            room=request.sid,
        )
    else:
        log.warning("No project named <%s> is owned by <%s>", project_name,
                    email)
Пример #30
0
 def get(self):
     print('hi from flask')
     socketio.emit('my response', 'cc', namespace='/chat')
Пример #31
0
    def update_clients(self):
        """Function updates clients/players on actions"""

        socketio.emit('game-data', self.serialize(), room=self.gameid)
Пример #32
0
def chat():
    message = request.json.get("message", 0)
    print(message)
    socketio.emit('chatting', {'message': message})
    return 'success'
Пример #33
0
 def send_message(self, data):
     self.last_message_json = json.dumps(data)
     db.session.commit()
     socketio.emit('game_update', self.as_json(), room=self.uuid)