Exemplo n.º 1
0
def yt_new_video(user, id, reaction, job_id):
    """
	Description\n
		Action function for yt service : triggers when new video from a chosen channel comes out
	Parameters
		user : user dict\t
		id : trigger id
		reaction : reaction function\t
		job_id : id of apscheduler job
	"""
    channel = user["triggers"][id]["action"]["data"]["channel"]
    url = "https://www.googleapis.com/youtube/v3/channels?part=statistics,status&forUsername="******"tokens"]["googleToken"]}
    response = requests.request("GET", url, headers=headers)
    data = response.json()
    value = data["items"][0]["statistics"]["videoCount"]
    current_user = (get_user(user["tokens"]["area"],
                             db.child("Users").get())).val()
    trigger, trigger_id = get_trigger_by_jobid(current_user, job_id)
    try:
        video_count = trigger["action"]["data"]["video_count"]
        if (int(video_count) < int(value)):
            trigger["action"]["data"]["video_count"] = value
            current_user["triggers"][trigger_id] = trigger
            db.child("Users").child(user["tokens"]["area"]).set(current_user)
            reaction(current_user, id)
    except Exception as e:
        print(e)
        trigger["action"]["data"].update(video_count=value)
        current_user["triggers"][trigger_id] = trigger
        db.child("Users").child(user["tokens"]["area"]).set(current_user)
Exemplo n.º 2
0
def th_get_status(user, id, reaction, job_id):
    """
	Description\n
		Action function for th service : triggers when a chosen streamer goes online
	Parameters
		user : user dict\t
		id : trigger id
		reaction : reaction function\t
		job_id : id of apscheduler job
	Return
		True or error message
	"""
    channel_name = user["triggers"][id]["action"]["data"]["channel"]
    current_user = (get_user(user["tokens"]["area"],
                             db.child("Users").get())).val()
    trigger, trigger_id = get_trigger_by_jobid(current_user, job_id)
    headers = {"Client-ID": client_id}
    try:
        channel_id = trigger["action"]["data"]["channel_id"]
    except:
        url = "https://api.twitch.tv/kraken/channels/" + channel_name
        r = requests.get(url, headers=headers)
        data = r.json()
        channel_id = data["_id"]
        trigger["action"]["data"]["channel_id"] = channel_id
        current_user["triggers"][trigger_id] = trigger
        db.child("Users").child(user["tokens"]["area"]).set(current_user)
    headers["Accept"] = "application/vnd.twitchtv.v5+json"
    url = "https://api.twitch.tv/kraken/streams/" + str(channel_id)
    r = requests.get(url, headers=headers)
    data = r.json()
    if data["stream"] != None:
        reaction(user, id)
Exemplo n.º 3
0
def lol_levelup(user, id, reaction, job_id):
	"""
	Description\n
		Action function for LoL service : triggers when a player levels up
	Parameters
		user : user dict\t
		id : trigger id
		reaction : reaction function
		job_id : id of apscheduler job
	Return
		True or error message
	"""
	summoner_name = user["triggers"][id]["action"]["data"]["summoner"]
	region_name = user["triggers"][id]["action"]["data"]["region"]
	url = "https://lolprofile.net/fr/summoner/" + region_name + "/" + summoner_name
	response = requests.request("GET", url)
	page_content = BeautifulSoup(response.content, "html.parser")
	div_tag = page_content.find("div", {"class" : "s-icon mhide"})
	current_level = div_tag.find("div")
	current_level = str(current_level).replace("<div>Niveau ", "").replace("</div>", "")
	current_user = (get_user(user["tokens"]["area"], db.child("Users").get())).val()
	trigger, trigger_id = get_trigger_by_jobid(current_user, job_id)
	try:
		level = trigger["action"]["data"]["level"]
		if (level != current_level):
			trigger["action"]["data"]["level"] = current_level
			current_user["triggers"][trigger_id] = trigger
			db.child("Users").child(user["tokens"]["area"]).set(current_user)
			reaction(current_user, id)
	except Exception as e:
		print(e)
		trigger["action"]["data"].update(level = current_level)
		current_user["triggers"][trigger_id] = trigger
		db.child("Users").child(user["tokens"]["area"]).set(current_user)
Exemplo n.º 4
0
def addTwitterToken():
    """
    Description\n
        POST route to add a twitter token to an authenticated user
    Json-data
        twitterToken : twitter token from oauth\t
        twitterSecret : twitter secret from oauth
    Headers
        Authorization : Bearer token
    Return
        200 code for succes and 400 for failure
    """
    users = db.child('Users').get()
    authorization = request.headers.get("Authorization")
    token = check_token(authorization, users)
    if token == False:
        return serialize_response('Unkown user', {}, 400)
    user = token
    data = request.json
    try:
        twitter_token = data["twitterToken"]
        twitter_secret = data["twitterSecret"]
    except:
        return serialize_response('Missing parameters', {}, 400)
    user["tokens"]["twitterToken"] = twitter_token
    user["tokens"]["twitterSecret"] = twitter_secret
    db.child("Users").child(user["tokens"]["area"]).set(user)
    return serialize_response('Tokens added', {}, 200)
Exemplo n.º 5
0
def addGoogleToken():
    """
    Description\n
        POST route to add a google token to an authenticated user
    Json-data
        googleToken : google token from oauth\t
        googleId : google id of user
    Headers
        Authorization : Bearer token
    Return
        200 code for succes and 400 for failure
    """
    users = db.child('Users').get()
    authorization = request.headers.get("Authorization")
    token = check_token(authorization, users)
    if token == False:
        return serialize_response('Unknown user', {}, 400)
    user = token
    data = request.json
    try:
        google_token = data["googleToken"]
        google_id = data["googleId"]
    except:
        return serialize_response('Missing parameters', {}, 400)
    user["tokens"]["googleToken"] = google_token
    user["tokens"]["googleId"] = google_id
    db.child("Users").child(user["tokens"]["area"]).set(user)
    return serialize_response('Tokens added', {}, 200)
Exemplo n.º 6
0
def rmv_triggers():
    """
    Description\n
        POST route to remove a trigger from a user list of triggers
    Json-data
        triggerId : trigger id of authenticated user\t
    Headers
        Authorization : Bearer token
    Return
        200 code for succes and 400 for failure
    """
    users = db.child('Users').get()
    authorization = request.headers.get("Authorization")
    token = check_token(authorization, users)
    if token == False:
        return serialize_response('Unkown user', {}, 400)
    user = get_user(authorization.split(' ')[1], users)
    val = user.val()
    data = request.json
    trigger_id = int(data["triggerId"])
    job_id = val["triggers"][trigger_id]["job_id"]
    try:
        if len(val["triggers"]) == 1:
            val["triggers"] = [-1]
        else:
            val["triggers"].pop(trigger_id)
    except:
        return serialize_response('Invalid trigger id', {}, 400)
    try:
        scheduler.remove_job(job_id)
        db.child("Users").child(user.key()).set(val)
    except:
        return serialize_response('Invalid trigger id', {}, 400)
    return serialize_response('Trigger deleted', {}, 200)
Exemplo n.º 7
0
def add_trigger_to_db(job_id, user, key, action_id, reaction_id, action_data,
                      reaction_data):
    """
    Description\n
        Add new trigger to database
    Parameters
        job_id : apscheduler jobid\t
        user : authenticated user\t
        key : \t
        action_id : index of array action
        reaction_id : index of reaction id
        action_data : json data linked to action
        reaction_data : json data linked to reaction
    Return
        trigger id
    """
    trigger = {
        "job_id": job_id,
        "action": {
            "id": action_id,
            "data": action_data
        },
        "reaction": {
            "id": reaction_id,
            "data": reaction_data
        }
    }
    triggers = user["triggers"]
    if (triggers[0] == -1):
        triggers[0] = trigger
    else:
        user["triggers"].append(trigger)
    db.child("Users").child(key).set(user)
    return len(user["triggers"]) - 1
Exemplo n.º 8
0
def github_commit(user, id, reaction, job_id):
    """
	Description\n
		Action function for GH service : triggers when a commit is made on a chosen repository from a chosen owner
	Parameters
		user : user dict\t
		id : trigger id
		reaction : reaction function\t
		job_id : id of apscheduler job
	"""
    repo = user["triggers"][id]["action"]["data"]["repo"]
    owner = user["triggers"][id]["action"]["data"]["owner"]
    params = [('client_id', client_id), ('client_secret', client_secret)]
    url = "https://api.github.com/repos/" + owner + "/" + repo + "/commits"
    response = requests.request("GET", url, params=params)
    data = response.json()
    request_commit = data[0]["sha"]
    current_user = (get_user(user["tokens"]["area"],
                             db.child("Users").get())).val()
    trigger, trigger_id = get_trigger_by_jobid(current_user, job_id)
    try:
        last_commit = trigger["action"]["data"]["last_commit"]
        print("the sha is " + str(request_commit) + " , last commit is " +
              str(last_commit))
        if (last_commit != request_commit):
            trigger["action"]["data"]["last_commit"] = request_commit
            current_user["triggers"][trigger_id] = trigger
            db.child("Users").child(user["tokens"]["area"]).set(current_user)
            reaction(current_user, id)
    except Exception as e:
        print(e)
        trigger["action"]["data"].update(last_commit=request_commit)
        current_user["triggers"][trigger_id] = trigger
        db.child("Users").child(user["tokens"]["area"]).set(current_user)
Exemplo n.º 9
0
def register():
    data = request.json
    try:
        firstname = data['firstName']
        lastname = data['lastName']
        email = data['email']
        password = data['password']
    except:
        return serialize_response('Missing parameters', {}, 400)
    password = generate_password_hash(password)

    users = db.child('Users').get()
    for user in users.each():
        each_user = user.val()
        if each_user['email'] == email:
            return serialize_response('Email already in use', {}, 400)
    new_user = {
        "email": email,
        "password": password,
        "firstName": firstname,
        "lastName": lastname,
        "tokens": {
            "area": "t"
        },
        "triggers": [-1]
    }
    db.child("Users").push(new_user, fire_user['idToken'])
    users = db.child("Users").get()
    for user in users.each():
        each_user = user.val()
        if each_user['email'] == email:
            each_user['tokens']['area'] = user.key()
            db.child("Users").child(user.key()).set(each_user)
            return serialize_response('User added', {}, 200)
    return serialize_response('Error in request', {}, 400)
Exemplo n.º 10
0
def add_trigger():
    """
    Description\n
        POST route to add a new trigger
    Json-data
        action_id = array index of actions\t
        reaction_id = array index of reactions\t
        action_data = json data of action\t
        reaction_data = json data of reaction\t
    Headers
        Authorization : Bearer token
    Return
        200 code for succes and 400 for failure
    """
    users = db.child('Users').get()
    authorization = request.headers.get("Authorization")
    token = check_token(authorization, users)
    if token == False:
        return serialize_response('Unkown user', {}, 400)
    user = get_user(authorization.split(' ')[1], users)
    data = request.json
    try:
        action_id = int(data["action_id"])
        reaction_id = int(data["reaction_id"])
        action_data = data["action_data"]
        reaction_data = data["reaction_data"]
    except:
        return serialize_response('Missing parameters', {}, 400)
    action = action_array[action_id]
    reaction = reaction_array[reaction_id]
    action_res = action[2](user.val(), action_data)
    if action_res != True:
        return serialize_response(action_res, {}, 400)
    reaction_res = reaction[1](user.val(), reaction_data)
    if reaction_res != True:
        return serialize_response(reaction_res, {}, 400)
    job_id = user.key() + str(int(time.time() * 10000))
    trigger_id = add_trigger_to_db(job_id, user.val(), user.key(), action_id,
                                   reaction_id, action_data, reaction_data)
    val = user.val()
    args = [val, trigger_id, reaction[0], job_id]
    scheduler.add_job(func=action[0],
                      trigger="interval",
                      seconds=action[1],
                      args=args,
                      max_instances=100,
                      id=job_id)
    return serialize_response('Here you are', {}, 200)
Exemplo n.º 11
0
def login():
    data = request.json
    try:
        email = data['email']
        password = data['password']
    except:
        return serialize_response('Missing parameters', {}, 400)
    users = db.child('Users').get()
    for user in users.each():
        each_user = user.val()
        if each_user['email'] == email:
            if check_password_hash(each_user['password'], password):
                return serialize_response('Here is the key',
                                          {"key": user.key()}, 200)
            return serialize_response('Bad password', {}, 400)
    return serialize_response('Unknown user', {}, 400)
Exemplo n.º 12
0
def get_triggers():
    """
    Description\n
        GET route to get all user triggers
    Json-data
        twitterToken : twitter token from oauth\t
        twitterSecret : twitter secret from oauth
    Headers
        Authorization : Bearer token
    Return
        200 code for succes and 400 for failure
    """
    users = db.child('Users').get()
    authorization = request.headers.get("Authorization")
    user = check_token(authorization, users)
    if user == False:
        return serialize_response('Unkown user', {}, 400)
    return serialize_response('Here are the triggers',
                              {"triggers": user["triggers"]}, 200)