Esempio n. 1
0
def create_note(app, noteId, ticketId, userId, text):
    note = Note()
    note.id = noteId
    note.ticket_id = ticketId
    note.user_id = userId
    note.text = text
    database.addItemSafelyToDB(note)
    return note
Esempio n. 2
0
def create_user(app, id):
    new_user = User()
    psw = b'$2b$12$1Y21IaNbwu357bI4ipaZO.GVvzouAEvnrAy80TGCBRtX5q8OUlIr2'
    new_user.id = id
    new_user.name = "test"
    new_user.email = str(id) + "@mail.com"
    new_user.password = psw
    database.addItemSafelyToDB(new_user)
    return new_user
Esempio n. 3
0
def create_ticket(app, ticketId, userId, courseId, status=1):
    ticket = Ticket()
    ticket.id = ticketId
    ticket.user_id = userId
    ticket.course_id = courseId
    ticket.status_id = status
    ticket.email = "*****@*****.**"
    ticket.title = "title"
    ticket.timestamp = datetime.now()
    database.addItemSafelyToDB(ticket)
    return ticket
Esempio n. 4
0
def create_course(app, courseId, tas=[], students=[], supervisors=[]):
    course = Course()
    course.id = courseId
    course.course_email = "*****@*****.**"
    course.title = "test_title"
    course.description = "desc"
    course.ta_courses = tas
    course.student_courses = students
    course.supervisors = supervisors
    database.addItemSafelyToDB(course)
    return course
Esempio n. 5
0
def create_labels(course_id):
    """
    Adds a label to a course.
    """
    data = request.get_json()
    if data is None:
        return Iresponse.create_response("", 404)
    name = data["name"]
    labelid = uuid.uuid4()
    exist_label = Label.query.filter_by(label_name=name).all()

    if exist_label:
        return Iresponse.create_response("", 200)

    course = Course.query.get(course_id)
    if course is None:
        return Iresponse.create_response("", 404)

    new_label = Label()
    new_label.label_name = name
    new_label.label_id = labelid
    new_label.course = course

    if not database.addItemSafelyToDB(new_label):
        return Iresponse.internal_server_error()

    database.db.session.commit()
    return Iresponse.create_response("", 200)
Esempio n. 6
0
def read_students_csv(filename, course_id):
    """
    Reads in a csv file and creates a user
    if the there is no user yet with the gived id.
    Adds the user to the specified course if its not
    yet active.
    This will probably be removed when
    the integration with lti works.
    If not, add some better error handeling
    and exiting.
    """
    f = open(filename, 'r')
    reader = csv.reader(f, delimiter=',')
    course = Course.query.get(course_id)
    if course is None:
        f.close()
        return False
    for row in reader:
        if len(row) != 3:
            continue
        stud_id = int(row[0])
        user = User.query.get(stud_id)
        if user is None:
            user = User(id=int(row[0]), name=row[1], email=row[2])
            if not database.addItemSafelyToDB(user):
                continue

        if user not in course.student_courses:
            print("APPENDING USER")
            course.student_courses.append(user)
            database.get_db().session.commit()
    f.close()
    return True
Esempio n. 7
0
def read_tas_csv(filename, course_id):
    """
    Add teaching assistants from uploaded file.
    """
    f = open(filename, 'r')
    reader = csv.reader(f, delimiter=',')
    course = Course.query.get(course_id)
    if course is None:
        f.close()
        return False
    for row in reader:
        if len(row) != 3:
            continue
        stud_id = int(row[0])
        user = User.query.get(stud_id)
        if user is None:
            user = User(id=int(row[0]), name=row[1], email=row[2])
            if not database.addItemSafelyToDB(user):
                continue

        if user not in course.ta_courses:
            print("ADDING TA")
            course.ta_courses.append(user)
            database.get_db().session.commit()
    f.close()
    return True
Esempio n. 8
0
def create_request(json_data):
    """
    Function that handles the create request for a ticket.
    """
    name = escape(json_data["name"])
    name = name  # flake8
    studentid = escape(json_data["studentid"])
    email = escape(json_data["email"])
    subject = escape(json_data["subject"])
    message = escape(json_data["message"])
    courseid = escape(json_data["courseid"])
    labelid = escape(json_data["labelid"])
    files = json_data['files']

    response_body = {}

    bound_tas = list()
    label = None

    if labelid != "":
        label = Label.query.get(uuid.UUID(labelid))
        bound_tas = get_label_tas(label, studentid)

    if len(bound_tas) < 1:
        status_id = TicketStatus.unassigned
    else:
        status_id = TicketStatus.waiting_for_help

    ticket = Ticket(id=uuid.uuid4(),
                    user_id=studentid,
                    course_id=courseid,
                    status_id=status_id,
                    title=subject,
                    email=email,
                    label=label,
                    files=files,
                    timestamp=datetime.now())

    for ta in bound_tas:
        ticket.bound_tas.append(ta)
        level_up = levels.add_experience(levels.EXP_FOR_ASSING, ta.id)
        levels.notify_level_change(ta.id, ticket, level_up)

    if not database.addItemSafelyToDB(ticket):
        return Iresponse.internal_server_error()

    try:
        msg = notifications.notify(studentid, ticket, message,
                                   Message.NTFY_TYPE_MESSAGE)
        msg = msg
    except Exception as e:
        raise e
        return Iresponse.create_response(str(e), 400)

    response_body['ticketid'] = ticket.id
    response = Iresponse.create_response(response_body, 201)
    response.headers.add('Location', 'api/ticket/{0}'.format(ticket.id))
    return response
Esempio n. 9
0
    def setup_mail(data):
        emit('setup-email', {'result': 'update', 'data': "recieved data"})
        email = data['email']
        password = data['password']
        port = data['port']
        server = data['pop']
        course_id = data['course_id']
        sleeptime = app.config['MAIL_WAIT_TIME_BEFORE_FETCH']

        thread = MailThread.existThreadCourseID(course_id)
        if (MailThread.existThreadEmail(email)):
            if thread is None:
                emit('setup-email',
                     {'result': 'fail', 'data': 'Email already exists'})
                return

        try:
            test_connection = poplib.POP3_SSL(server, port)
            test_connection.user(email)
            test_connection.pass_(password)
            test_connection.quit()
        except (poplib.error_proto) as msg:
            message = msg.args[0].decode('ascii')
            emit('setup-email', {'result': 'fail', 'data': message})
            return
        except OSError as msg:
            message = str(msg)
            emit('setup-email', {'result': 'fail', 'data': message})
            return

        if (thread is None):
            new_thread = MailThread(sleeptime, server, port, email, password,
                                    course_id)
            new_thread.setName(course_id)
            new_thread.start()
        else:
            thread.update(sleep_time=sleeptime, server=server, port=port,
                          email=email, password=password)

        course = Course.Course.query.get(course_id)
        course.course_email = email
        course.mail_password = password
        course.mail_port = port
        course.mail_server_url = server
        if not database.addItemSafelyToDB(course):
            emit('setup-email', {'result': 'fail', 'data': 'database error'})
            return

        emit('setup-email', {'result': 'succes'})
        return
Esempio n. 10
0
 def ensure_user_exists(self):
     """
     Function that ensures the user exists.
     """
     user_id = int(self.lti_instance.user_id)
     print(user_id)
     user = User.query.get(user_id)
     if user is None:
         user = User()
         user.create(id=user_id,
                     name=self.lti_instance.user_full_name,
                     email=self.lti_instance.user_primary_email,
                     password="******")
         if not database.addItemSafelyToDB(user):
             user = None
     self.cache['user'] = user
Esempio n. 11
0
def create_request(jsonData):
    """
    Function that handles the create request for a course.
    """
    mail = escape(jsonData['mail'])
    title = escape(jsonData['title'])
    description = escape(jsonData['description'])

    course = Course()
    course.id = uuid.uuid4()
    course.course_email = mail
    course.title = title
    course.description = description

    if not database.addItemSafelyToDB(course):
        return Iresponse.internal_server_error()

    return Iresponse.create_response("", 200)
Esempio n. 12
0
def activate_plugin(label_id):
    """
    Create a record in the database to activate this plugin.
    """
    label = Label.query.get_or_404(label_id)
    plugin_id = request.get_json()['plugin_id']
    if plugin_id not in plugins.plugin_list():
        return Iresponse.create_response({"error": "Plugin does not exist"},
                                         404)
    lp = LabelPlugin()
    lp.id = uuid.uuid4()
    lp.plugin = plugin_id
    lp.label = label
    lp.assignment_id = ''
    if database.addItemSafelyToDB(lp):
        return Iresponse.create_response({"status": "success"}, 200)
    else:
        return Iresponse.create_response({"error": "Something went wrong"},
                                         500)
Esempio n. 13
0
def create_request(jsonData):
    """
    Process the request to create a node.
    """
    ticket_id = escape(jsonData["ticket_id"])
    user_id = escape(jsonData["user_id"])
    message = escape(jsonData["text"])

    response_body = {}

    if message == '':
        response_body['message'] = "empty message"

    if ticket_id == '':
        response_body['ticket_id'] = "No ticket id has been supplied"

    if user_id == '':
        response_body['user_id'] = "No user id has been supplieds"

    ticket = Ticket.query.get(ticket_id)
    if ticket is None:
        response_body['ticket'] = "No ticket exists with this id"

    if len(response_body) != 0:
        return Iresponse.create_response(response_body, 400)

    note = Note()
    note.id = uuid.uuid4()
    note.user_id = user_id
    note.ticket_id = ticket_id
    note.text = message
    note.timestamp = datetime.now()

    if not database.addItemSafelyToDB(note):
        return Iresponse.internal_server_error()

    parse_note(message, ticket)
    levels.add_experience(levels.EXP_FOR_NOTE, note.user_id)
    # add header location.
    return Iresponse.create_response(note.serialize, 201)
Esempio n. 14
0
def fill_new_course_with_canvas_data(headers, course_id):
    """
    A function that fills a new course with data from canvas.
    This function is only called if a new course is created.
    It then fills the course with students, tas and teachers.
    When using the api canvas has different names for roles,
    so we use a different function for filling a course
    with canvas data.
    """
    request_url = lti_base_route + lti_api_route
    request_url += '/courses/{}/users?'.format(course_id)
    request_url += 'include[]=enrollments&include[]=email'
    user_req = requests.get(request_url, headers=headers)

    users = user_req.json()
    if user_req.status_code != 200:
        return

    for user in users:
        user_id = user.get('sis_user_id')
        if user_id is None:
            return

        existing_user = User.query.get(user_id)
        if existing_user is None:
            name = user.get('name')
            email = user.get('email')
            existing_user = User()
            existing_user.create(id=user_id,
                                 name=name,
                                 email=email,
                                 password="******")
            if not database.addItemSafelyToDB(
                    existing_user, fill_new_course_with_canvas_data):
                continue

        course = Course.query.filter_by(canvas_unique_id=course_id).first()
        if course is None:
            return
        ensure_user_couples_to_course(existing_user, course, user)
Esempio n. 15
0
 def ensure_course_exists(self):
     """
     Function that ensures the course in the lti instance
     exists.
     """
     print(self.lti_instance.params)
     canvas_course_id = self.lti_instance.params['custom_canvas_course_id']
     course = Course.query.filter_by(
         canvas_unique_id=canvas_course_id).first()
     course_name = self.lti_instance.course_name
     if course is None:
         self.lti_instance.params['new_tiktech_course'] = True
         course = Course(id=uuid.uuid4(),
                         title=course_name,
                         description=self.lti_instance.course_description,
                         canvas_unique_id=canvas_course_id)
         if not database.addItemSafelyToDB(course,
                                           self.ensure_course_exists):
             self.cache['course'] = None
             return
     self.lti_instance.params['tiktech_course_id'] = course.id
     self.cache['course'] = course
Esempio n. 16
0
def register_user(json_data):
    email = escape(json_data["email"])
    name = escape(json_data["name"])
    studentid = int(escape(json_data["studentid"]))
    password = escape(json_data["password"])
    repassword = escape(json_data["password_confirmation"])

    validated = validate_userdata(email, name, studentid, password, repassword)
    if validated != '':
        return Iresponse.create_response({"status": validated}, 200)

    # Backend check if email/studentid already exists
    user = User.query.filter_by(email=email).first()
    if user:
        return Iresponse.create_response({"status": "Email is taken"}, 200)

    studentid = json_data["studentid"]
    user = User.query.filter_by(id=studentid).first()

    if user:
        return Iresponse.create_response({"status": "Studentid taken"}, 200)

    new_user = User()
    salt = bcrypt.gensalt()
    hashedpsw = bcrypt.hashpw(password.encode('utf-8'), salt)
    new_user.password = hashedpsw
    new_user.id = studentid
    new_user.name = name
    new_user.email = email
    new_user.level = 1
    new_user.experience = 1

    if not database.addItemSafelyToDB(new_user):
        return Iresponse.internal_server_error()

    return Iresponse.create_response({"status": "OK"}, 201)
Esempio n. 17
0
def notify(sender_id, ticket, text, n_type, initial=False):
    """
    Notify everyone in a ticket.
    """
    verbose = False  # Set to True for debugging

    user = User.query.get(sender_id)
    message = Message()
    message.ticket_id = ticket.id
    message.text = text
    message.n_type = n_type
    message.user_id = sender_id

    # We have to remove te owner from the related users in order to
    # notify everyone this message is targeted at.
    us = ticket.related_users
    if verbose:
        print("Users related to ticket:")
        for u in us:
            print(" - {}".format(u.name))
        print("----------------\n\n")

    if user in us:
        us.remove(user)

    if verbose:
        print("Users to notify: {}".format(len(us)))
        for u in us:
            print(" - {}".format(u.name))
        print("----------------\n\n")

    if len(us):
        if verbose:
            print("Adding recipients to unread table... ", end="")
        try:
            message.recipients.extend(list(us))
        except Exception as e:
            if verbose:
                print("Failed..")
                print(e)
            raise Exception("Could not add recipients")

        if verbose:
            print("Done!")
    else:
        if verbose:
            print("No recipients, skip adding")

    if verbose:
        print("Inserting into database")
    if not database.addItemSafelyToDB(message):
        if verbose:
            print("Failed to insert into database.")
        raise Exception("Could not create message")
    if verbose:
        print("Successfully inserted into database")

    # Place the notification in the ticket overview for everyone
    # present in that room.
    socketio.emit('messageAdded',
                  {'text': message.text,
                   'user_id':  user.id,
                   'user_name': user.name,
                   'type': message.n_type},
                  room='ticket-messages-{}'
                  .format(message.ticket_id))

    notification = {'text': "{}{}"
                    .format(message.text[:40],
                            '...' if len(message.text) > 40 else ''),
                    'ticket': str(ticket.id),
                    'ticket_owner': str(ticket.owner.id),
                    'sender': user.serialize,
                    'initial': initial,
                    'ticket_title': "{}{}"
                    .format(ticket.title[:40],
                            '...' if len(ticket.title) > 40 else ''),
                    'type': n_type}

    # We need to notify everyone related to the course. For this,
    # we use the user set we made earlier.
    for u in us:
        u.notify(notification)

    return message