Пример #1
0
def vote(user_token: bytes):

    users = memcache.get("voting.users")

    if user_token not in users:
        users.add(user_token)
        memcache.set("voting.users", users)
        memcache.incr("voting.count")

    if memcache.get("voting.count") >= memcache.get("voting.required"):
        pub("vote_passed")
        memcache.set("voting.count", 0)
        memcache.set("voting.users", set({}))
Пример #2
0
def user_authenticated(user_token: str, username: str, privilege_level: int,
                       ttl: int) -> None:
    """
    » Subscribed to user_authenticated
    Populates the cache with info about the user.
    :param user_token: The user token of the user who just authenticated themselves
    :param username: The username token of the user who just authenticated themselves
    :param privilege_level: The privilege level of the user who just authenticated themselves
    :param ttl: The ttl of the record
    :return: None
    """
    # print(username, "authenticated.")  # TODO: log event

    active_users = memcache.get("user_cache.active_users")
    active_users[user_token] = {
        'last_seen': time.time(),
        'username': username,
        'privilege_level': privilege_level,
        'ttl': ttl
    }

    old_sessions = []

    for token, record in active_users.items():
        if record['username'] == username and token != user_token:
            old_sessions.append(token)

    for token in old_sessions:
        del active_users[token]

    memcache.set("user_cache.active_users", active_users)
Пример #3
0
def get(key: str) -> Any:
    """
    Gets a value from the config by it's key.
    :param key: The key of the value
    :return: The value or None
    """
    return memcache.get("config").get(key)
Пример #4
0
def track_from_upload(name, **kwargs) -> Optional[Track]:
    plugin_description = memcache.get("upload.plugins").get(name)

    if plugin_description is None:
        return Response.INVALID_PLUGIN

    plugin = __load_plugin(name, plugin_description["path"])
    track_record = plugin.handle(**kwargs)  # type: TrackRecord

    if track_record.backend is None or track_record.mrl is None:
        return Response.PLUGIN_ERROR

    if tracks.exists(track_record.title, track_record.artist,
                     track_record.album):
        __cleanup(track_record.mrl)
        return Response.TRACK_EXISTS

    track = None
    with persistance():

        track = tracks.get_or_create(track_record.title, track_record.artist,
                                     track_record.album)

        track.backend = track_record.backend
        track.mrl = track_record.mrl

        # TODO: tag info
        db_session.add(track)

    return track
Пример #5
0
def whois(user_token: str) -> str:
    """
    :param user_token: A user token
    :return: The username of the user with the given token
    """
    record = memcache.get("user_cache.active_users").get(user_token)

    if record is None:
        return ""

    return record['username']
Пример #6
0
def authorize(user_token: str, required_privilege: int) -> bool:
    """
    Used to check whether a user is permitted to perform a certain action.
    :param user_token: The user token of the user who wants to perform the action
    :param required_privilege: The required privilege level to perform the action
    :return: Whether the user is permitted to perform the action
    """

    if required_privilege < 1:
        return True

    record = memcache.get("user_cache.active_users").get(user_token)

    if record is None:
        return False

    if time.time() - record['last_seen'] > record['ttl']:
        active_users = memcache.get("user_cache.active_users")
        del active_users[user_token]
        memcache.set("user_cache.active_users", active_users)
        return False

    return record['privilege_level'] >= required_privilege
Пример #7
0
def sub(topic: str, subscriber: Callable) -> None:
    """
    Subscribes a listener method to a certain topic.
    :param topic: The topic ti subscribe to
    :param subscriber: The subscriber method
    :return: None
    """

    topics = memcache.get("pubsub.topics")

    if topics.get(topic) is not None:
        topics[topic].append(subscriber)
    else:
        topics[topic] = [subscriber]

    memcache.set("pubsub.topics", topics)
Пример #8
0
def activity(user_token: str) -> None:
    """
    » Subscribed to user_activity
    Refreshes the last_seen attribute of the user with the given user_token.
    Also invalidates the user's session if the ttl has expired.
    :param user_token: The user token of the active user
    :return: None
    """

    active_users = memcache.get("user_cache.active_users")
    record = active_users.get(user_token)

    if record is None:
        return

    if time.time() - record['last_seen'] > record['ttl']:
        del active_users[user_token]
        memcache.set("user_cache.active_users", active_users)
        return

    active_users[user_token]['last_seen'] = time.time()
    memcache.set("user_cache.active_users", active_users)
Пример #9
0
def pub(topic: str, *args, **kwargs) -> None:
    """
    Publishes data to a certain topic.
    When data is published, all subscribed methods will be called and the
    published data is handed over. Make sure that all subscribers can handle
    the published data in their method definition.
    Use keyword args when published data is heterogeneous.
    :param topic: The topic to publish to
    :param args: All non positional args
    :param kwargs: All keyword args
    :return: None
    """

    subscribers = memcache.get("pubsub.topics").get(topic)

    if subscribers is not None:
        for s in subscribers:
            try:
                s(*args, **kwargs)
            except Exception as e:
                # TODO: log error
                print("Pubsub: Data on {} could not be published to {}, because {}".format(topic, s, e))
Пример #10
0
def exists(user_token: str) -> bool:
    """
    :param user_token: A user token
    :return: Whether the user token exists in the cache
    """
    return memcache.get("user_cache.active_users").get(user_token) is not None
Пример #11
0
def get_plugins():
    return memcache.get("upload.plugins")
Пример #12
0
def get_plugin_description(name: str) -> Dict[str, Any]:
    return memcache.get("upload.plugins").get(name)
Пример #13
0
from Pynitus.io.config import init_config
from Pynitus.io.storage import init_storage
from Pynitus.model.db.database import db_session, init_db
from Pynitus.player.contributor_queue import init_contributor_queue
from Pynitus.player.player import init_player
from Pynitus.player.queue import init_queue
from Pynitus.player.voting import init_voting
from Pynitus.upload import init_upload

app = Flask(__name__)

if app.debug:
    CORS(app)

with app.app_context():
    if memcache.get("pynitus.initialized") is None:
        init_config()
        init_pubsub()
        init_db()
        init_user_cache()
        init_player()
        init_queue()
        init_contributor_queue()
        init_voting()
        init_storage()
        init_upload()
        memcache.set("pynitus.initialized", True)


@app.teardown_appcontext
def shutdown_session(exception=None):