Example #1
0
	def get(self):
		queryUsers, error = User.queryByAll()
		if error:
			return res.internalServiceError(error)
		onlineStudents = Api42.onlineUsers()
		onlineSenseiUsers = [u for u in queryUsers for o in onlineStudents if u['id_user42'] == o['id']]
		return res.getSuccess(data=onlineSenseiUsers)
Example #2
0
	def post(self):
		
		data = request.get_json()
		print(data.get('code'))

		if not data or not data.get("code"):
			return res.badRequestError(message="No authorizen token provided.")

		accessReq = requests.post('https://api.intra.42.fr/oauth/token', data= {
			'grant_type' : 'authorization_code',
			'client_id' : app.config['CLIENT_ID'],
			'client_secret' : app.config['CLIENT_SECRET'],
			'code' : data.get('code'),
			'redirect_uri' : "http://localhost:8080/auth"
		}).json()
		if not accessReq or 'error' in accessReq:
			return res.badRequestError(message=accessReq['error_description'])
		LoggedUser = requests.get('https://api.intra.42.fr/v2/me', headers= { 'Authorization' : 'Bearer {}'.format(accessReq['access_token'])}).json()
		
		queryUser = User.query.filter_by(id_user42=LoggedUser['id']).first()
		err = None
		#	Registers user if record doesn't exist in Sensei database
		if not queryUser:
			data, err = registerUser(LoggedUser)
			if err:
				return res.internalServiceError(err)
		else:
			queryUser.last_seen = datetime.datetime.now()
			db.session.commit()
			
		#print(LoggedUser)
		return res.postSuccess(data={'access': accessReq, 'user': LoggedUser, 'error': err})
Example #3
0
    def post(self):
        #	Check if any projects exist
        existingProjects, error = Project.queryAll()
        if error:
            return res.internalServiceError(error)

        #	get existing projects from 42 API
        data = Api42.allProjects()
        if not data:
            return res.internalServiceError("unable to query the 42 API")

        #	only add new projects that are not in the projects table
        newProjects = []
        existingProjects = []
        for d in data:
            #	check if project exists
            projectCheck = Project.query.filter_by(
                id_project42=d['id_project42']).first()

            #	only add the new projects that don't exist in the database
            if not projectCheck:
                newProject, err = project_schema.load(d)
                if err:
                    db.session.rollback()
                    return res.internalServiceError('bad data')
                db.session.add(newProject)
                newProjects.append(project_schema.dump(newProject).data)
            else:
                projectCheck.name = d['name']
                projectCheck.slug = d['slug']
                projectCheck.tier = d['tier']
                existingProjects.append(project_schema.dump(projectCheck).data)

        print("COMMITTING NEW PROJECTS")
        db.session.commit()

        #   change return message if projects were updated
        retMessage = 'created new project' if newProjects else 'no new projects needed to be updated'
        retData = {
            'newProjects': newProjects,
            'existingProjects': existingProjects
        }
        return res.postSuccess(retMessage, retData)


#	LOAD takes a python DICTIONARY of data and will return a new CLASS object (the 'record')
#	DUMP takes a CLASS object (the 'record') and returns a tuple of data and something else
Example #4
0
 def get(self):
     queryAppointments = Appointment.query.filter_by(
         status=Status['Pending']).all()
     if not queryAppointments:
         return res.getSuccess("No appointments found.")
     appointments = appointments_schema.dump(queryAppointments).data
     if not appointments:
         return res.internalServiceError(
             "Failed to create appointment schema.")
     return res.getSuccess(data=appointments)
Example #5
0
def registerUser(LoggedUser):
    userDetails = {'id_user42': LoggedUser['id'], 'login': LoggedUser['login']}
    newUser, err = user_schema.load(userDetails)
    if err:
        return res.internalServiceError("Error saving user")
    db.session.add(newUser)
    db.session.commit()
    data, err = userUpdater.loadUserProjects(newUser.id_user42)
    if err:
        return None, err
    return data, None
Example #6
0
    def get(self, mentorId):
        query = Mentor.query.filter_by(id=mentorId).first()
        if not query:
            return res.badRequestError(
                'no mentor record with id {} exists'.format(mentorId))

        data = mentor_schema.dump(query).data
        if not data:
            return res.internalServiceError('failed to build mentor data')

        return res.getSuccess(
            'mentor data retrieved for user {} on project {}'.format(
                query.user.login, query.project.name), data)
Example #7
0
    def get(self, login):
        user, error = User.queryByLogin(login)
        if error:
            return res.resourceMissing(error)

        #   get the mentor records for that user on which projects they can mentor
        query = Mentor.query.filter_by(id_user42=user['id_user42'],
                                       active=True)
        if not query:
            return res.internalServiceError(
                'no mentor records for user {}'.format(login))

        #   return the mentor data
        mentors = mentors_schema.dump(query).data
        return res.getSuccess(data=mentors)
Example #8
0
 def get(self):
     data, error = Project.queryAll()
     if error:
         return res.internalServiceError(error)
     return res.getSuccess('found projects', data)
Example #9
0
    def post(self):

        data = request.get_json()

        #   Checks if required data to create an appointment was provided in request
        if not data:
            return res.badRequestError("Missing data to process request.")
        if not data.get("topic") and not data.get("project"):
            return res.badRequestError(
                "Missing data to process request. No topic or project provided to search for mentors"
            )
        if not data.get("login"):
            return res.badRequestError(
                "Missing data to process request. No user login provided")

        #   Checks if project name exists in database
        queryProject = Project.query.filter_by(
            name=data.get("project")).first()
        if not queryProject:
            return res.resourceMissing("No project {} found.".format(
                data.get("project")))
        project, error = project_schema.dump(queryProject)
        if error:
            return res.internalServiceError(error)

        #   Checks if user with provided login exists in database
        user, error = User.queryByLogin(data.get("login"))
        if error:
            return res.resourceMissing(error)

        #	Check if the user already has an appointment pending
        queryUserAppointment = Appointment.query.filter_by(
            id_user=user['id'], status=Status['Pending']).first()
        if queryUserAppointment:
            return res.badRequestError(
                "You have already an appointment pending")

        #   Limits appointments made by user for a specific project
        projectAppointmentsCount = Appointment.queryCountProjectAppointmentsbyUser(
            project["id_project42"], user["id"])
        if projectAppointmentsCount > _maxAppointmentsPerDay:
            return res.badRequestError(
                "User reached limit appointments for project {}".format(
                    data.get("project")))

        # jmeier id 23677, mentor id 48 project rec 847

        #	Filters out any mentors who have an appointment pending
        goodMentors = []
        queryMentor = Mentor.query \
         .filter(Mentor.id_project42==project['id_project42'], Mentor.active==True, Mentor.id_user42!=user['id_user42']) \
         .all()

        #	Check that the mentor does not have an existing pending appointment
        for q in queryMentor:
            appointment = Appointment.query.filter(
                Appointment.id_mentor == q.id,
                Appointment.status == Status['Pending']).first()
            if not appointment:
                goodMentors.append(q)
        if not goodMentors:
            return res.resourceMissing(
                'No mentors without pending appointments found')

        onlineUsers = Api42.onlineUsers()

        #	Checks online students is not empty
        if len(onlineUsers) == 0:
            return res.resourceMissing("No mentors found on campus.")

        #	Filtering out the available mentors with the online students
        availablementors = [
            mentor for mentor in goodMentors for o in onlineUsers
            if mentor.id_user42 == o['id']
        ]

        #   Checks if there is avaliable online mentors for the project/topic
        if not availablementors:
            return res.resourceMissing(
                "No mentors online found for {}.".format(data.get("project")))

        #   Calls 'mentor algorithm' to select a mentor from availablementors.
        chosenMentor = mentorAlgorithm(availablementors)

        #   Creates and returns appointment if valid
        if not chosenMentor:
            return res.internalServiceError("Error: mentor selection.")

        mentorLogin = [
            i['login'] for i in onlineUsers
            if i['id'] == chosenMentor.id_user42
        ][0]

        #	Gets the mentor's 'login'
        if not mentorLogin:
            return res.internalServiceError('Something strange happened')

        #	FINALLY, create the appointment
        newappointment, error = Appointment.createAppointment(
            chosenMentor.id, user['id'])
        if error:
            return res.internalServiceError(error)

        return res.postSuccess("Appointment created successfully",
                               newappointment)
Example #10
0
    def post(self):

        data = request.get_json()

        #   Checks if required data to create an appointment was provided in request
        if not data:
            return res.badRequestError("Missing data to process request.")
        if not data.get("topic") and not data.get("project"):
            return res.badRequestError(
                "Missing data to process request. No topic or project provided to search for mentors"
            )
        if not data.get("login"):
            return res.badRequestError(
                "Missing data to process request. No user login provided")

        #   Checks if project name exists in database
        queryProject = Project.query.filter_by(
            name=data.get("project")).first()
        if not queryProject:
            return res.resourceMissing("No project {} found.".format(
                data.get("project")))
        project, error = project_schema.dump(queryProject)
        if error:
            return res.internalServiceError(error)
        print(project)
        #   Checks if user with provided login exists in database
        user, error = User.queryByLogin(data.get("login"))
        if error:
            return res.resourceMissing(error)

        print(user)
        queryUserAppointment = Appointment.query.filter_by(
            id_user=user['id'], status=Status['Pending']).first()
        if queryUserAppointment:
            return res.badRequestError(
                "You have already an appointment pending")

        #   Limits appointments made by user for a specific project
        projectAppointmentsCount = Appointment.queryCountProjectAppointmentsbyUser(
            project["id_project42"], user["id"])
        if projectAppointmentsCount > _maxAppointmentsPerDay:
            return res.badRequestError(
                "User reached limit appointments for project {}".format(
                    data.get("project")))

        #   Retrieves available mentors for the specified project
        queryMentor = Mentor.query \
         .filter(~Mentor.appointments.any(), Mentor.id_project42==project['id_project42'], Mentor.active==True, Mentor.id_user42!=user['id_user42']) \
         .all()

        queryMentor2 = Mentor.query \
         .join(Appointment) \
         .filter(Mentor.id_project42==project['id_project42'], Mentor.active==True, Mentor.id_user42!=user['id_user42']) \
         .filter(Appointment.status==2) \
         .all()

        for q in queryMentor2:
            queryMentor.append(q)

        if not queryMentor:
            print("hereee")
            return res.resourceMissing(
                'No mentors found for project {}'.format(data.get('project')))

        #mentors = [mentor for mentor in queryMentor if mentor.app]
        #mentors = mentors_schema.dump(queryMentor).data
        onlineUsers = Api42.onlineUsers()

        #	Checks online students is not empty
        if len(onlineUsers) == 0:
            return res.resourceMissing("No mentors found on campus.")

        availablementors = [
            mentor for mentor in queryMentor for x in onlineUsers
            if mentor.id_user42 == x['id']
        ]

        #   Checks if there is avaliable online mentors for the project/topic
        if not availablementors:
            return res.resourceMissing(
                "No mentors online found for {}.".format(data.get("project")))

        #   Calls 'mentor algorithm' to select a mentor from availablementors.
        chosenMentor = mentorAlgorithm(availablementors)

        print(chosenMentor)
        #   Creates and returns appointment if valid
        if not chosenMentor:
            return res.internalServiceError("Error: mentor selection.")

        newappointment, error = Appointment.createAppointment(
            chosenMentor.id, user['id'])
        if error:
            return res.internalServiceError(error)
        print(newappointment)

        return res.postSuccess("Appointment created successfully",
                               newappointment)