import os
import re
import datetime
from werkzeug.utils import secure_filename
from flask import Flask, jsonify, request, abort, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_mysqldb import MySQL
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_jwt_extended import (
    JWTManager, jwt_required, create_access_token,
    jwt_refresh_token_required, create_refresh_token,
    get_jwt_identity, set_access_cookies,
    set_refresh_cookies, unset_jwt_cookies
)
from flask_wtf.csrf import CSRFProtect
from model import user_model
from model import student_model
from model import lecturer_model
from model import mentor_model

from controller import user_controller, news_controller, blogger_controller
import json
from model import base
from functools import wraps
from flask import g, request, redirect, url_for
import MySQLdb
from inittables import InitTables
from sqlalchemy.orm import relationship, backref
from sqlalchemy.orm import sessionmaker
from model.school_model import School, Faculty, Department, Program, Level
from platform_model import class_mem, class_message, class_model, course_model, course_mem, course_lecturer, course_message

from message_model import group_conv_init, group_conv_mem, personal_conv_init, personal_conv_mem, personal_message_model, group_message_model 
from entertainment_model import news_model, blogger_model, featured_image_model, like, comment, news_category
from personal_model import course_reg, calender
from model.user_type import UserType


# Retrieves database configuration from environment variables
mysql_host = os.environ.get('MYSQL_HOST')
mysql_user = os.environ.get('MYSQL_USER')
mysql_password = os.environ.get('MYSQL_PASSWORD')
db_name = 'testing'  # os.environ.get('DB_NAME')

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'mp3', 'mp4', 'pdf', 'doc', 'docx'}    # Feel free to add more file types to be accepted
MAX_CONTENT_LENGTH = 1024*1024*10  # Maximum file upload sixe is 50 MB

# App flask Configuration
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://' + mysql_user + ':' + mysql_password + '@' + mysql_host + '/' + db_name
app.config['JWT_TOKEN_LOCATION'] = ['cookies']
app.config['JWT_COOKIE_SECURE'] = False
app.config['JWT_ACCESS_COOKIE_PATH'] = '/api/'
app.config['JWT_REFRESH_COOKIE_PATH'] = '/token/refresh'
app.config['JWT_COOKIE_CSRF_PROTECT'] = True
app.config['JWT_SECRET_KEY'] = os.environ.get('JWT_SECRET_KEY')  #The Jwt_secret_key is obtained from environment variables
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH
app.config['UPLOAD_EXTENSIONS'] = ALLOWED_EXTENSIONS
app.config['UPLOAD_PATH'] = UPLOAD_FOLDER


db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
jwt = JWTManager(app)
base.Base.metadata.create_all(db.engine, checkfirst=True)

 # This part of the code is to check if the important tables (School, Faculty, Department, Program, Level) have been initialized
Session = sessionmaker(db.engine) 
Session.configure()
session = Session()
if session.query(School).count() == 0 or session.query(Faculty).count() == 0 or session.query(Department).count() == 0 or session.query(Program).count() == 0 or session.query(Level).count() == 0 :
    InitTables(session)

controller = user_controller.UserController(db)     #Create instance of controller to perform some operations
n_controller = news_controller.NewsController(db)   # Create instance of news controller to perform some operations
b_controller = blogger_controller.BloggerController(db)     #Create instance of blogger controller to perform some operations

CORS(app)

# Sets up the funtion for checking if a user is logged in
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'csrf_access_token' not in request.cookies:
            return {'Error': 'You have to login first'}
        return f(*args, **kwargs)
    return decorated_function


# Register a user - either a student, lecturer or mentor
@app.route('/users/register', methods = ['POST'])
def register ():
    try:
        # Gets all input data from the user
        user_name = request.form.get('user_name')
        surname = request.form.get('surname')
        first_name = request.form.get('first_name')
        email = request.form.get('email')
        password = bcrypt.generate_password_hash(request.form.get('password')).decode('utf-8')
        user_type = request.form.get('user_type')

        getemail = controller.get_email(email)  # Checks to see if the entry email is in the database. If not, it returns None

    except:
        return {'Error': 'Unable to retrieve user details'}


    if str(user_type) == 'Student':
        try:  
            # Gets additional input for a student
            program_id = request.form.get('program_id')
            matric_no = request.form.get('matric_no')
            level_id = request.form.get('level_id')

            if getemail == None:   # If email is not already registered, input the data into the database
                controller.add_data(student_model.Student(
                    user_name, surname, first_name, email, password, user_type, program_id, matric_no, level_id))

                class_id = controller.get_class_id(program_id, level_id)
                user_id = controller.get_user_id(email)
                controller.add_data(class_mem.ClassMem(class_id, user_id))

                return {'success': 'succesfully updated in the database'}         

            elif email == getemail[0]: # If email is already used, notify the user
                return {'Error': 'This email has already been used to register'}
        
        except:  # To notify if a student hasn't conformed to an acceptable input format.
            return {'Error': 'Unable to retrieve student details. Ensure the inputs are valid'}


    elif str(user_type) == 'Lecturer':
        try: 
            # Get additional inpuuts for lecturers
            department_id = request.form.get('department_id')
            title = request.form.get('title')
            position = request.form.get('position')

            if getemail == None:  # If email is not already registered, input the data into the database
                controller.add_data(lecturer_model.Lecturer(
                    user_name, surname, first_name, email, password, user_type, department_id, title, position))

                return {'success': 'succesfully updated in the database'}

            elif email == getemail[0]:   # If email is already used, notify the user
                return {'Error':'This email has already been used to register'}

        except:  # To notify if a lecturer hasn't conformed to an acceptable input format.
            return {'Error': "Unable to save lecturer details. Ensure that the inputs are correct"}
        
  

    elif str(user_type) == 'Mentor':
        try:
            # Gets addional input data for a mentor
            profession = request.form.get('profession')
            company = request.form.get('company')
            title = request.form.get('title')

            if getemail == None:   # If email is not already registered, input the data into the database
                controller.add_data(mentor_model.Mentor(
                    user_name, surname, first_name, email, password, user_type, profession, company, title))

                return {'success': 'succesfully updated in the database'}

            elif email == getemail[0]:    # If email is already used, notify the user
                return {'Error': 'This email has already been used to register'}
 
        except:   # To notify if a mentor hasn't conformed to an acceptable input format.
            return {'Error': 'Unable to get mentor details. Ensure that the inputs are correct'}


    else:        # To notify if a user hasn't conformed to an acceptable input format.
        return {'Error': 'Unable to get user details. Ensure that the inputs are correct'}


# Function to retrieve a user details based on id
@app.route('/users/<id>', methods=['GET'])
@login_required
def get_user(id):
    try:
        resp = controller.get_user(id)   #Gets the details of a user given the user id.
        return resp.to_dict()
    except:
        return {'Error': 'User not found'}



# Function to login
@app.route('/token/auth', methods=['POST'])
def login():
    # Gets email and password inputed by the user
    email = request.form.get('email')
    pass_word = request.form.get('password')
    
    
    try:
        password = controller.get_password(email) # Checks if email has been registered. If this line fails, it runs the except block
        if bcrypt.check_password_hash(password[0], pass_word):    # Checks if password is correct
            user_name = controller.get_user_name(email)
            user_id = controller.get_user_id(email)
            print(user_name)

            access_token = create_access_token(identity={'User name': user_name[0],'id': user_id[0]}, expires_delta=datetime.timedelta(days=1))
            refresh_token = create_refresh_token(identity = {'User name': user_name[0], 'id': user_id[0]}, expires_delta=datetime.timedelta(days=1))
        
            resp = jsonify({'login': True, 'user name': user_name[0]})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)

            return resp, 200
        else:
            return jsonify({'login': False}), 401
    except:
        return jsonify({'login': False}), 401


@app.route('/token/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
    # Create the new access token
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)

    # Set the access JWT and CSRF double submit protection cookies
    # in this response
    resp = jsonify({'refresh': True})
    set_access_cookies(resp, access_token)
    return resp, 200


@app.route('/token/remove', methods=['POST'])
def logout():
    resp = jsonify({'logout': True})
    unset_jwt_cookies(resp)
    return resp, 200



#This route is to return the image from the local storage.
@app.route('/uploads/<fc>/<yr>/<mn>/<dy>/<filename>', methods=['GET'])
def get_file(fc, yr, mn, dy, filename):
    return send_from_directory((os.path.join(app.config['UPLOAD_PATH'], fc, str(yr), str(mn), str(dy))), filename)

#checks file category


def get_file_category(uploaded_file):
    file_mime = uploaded_file.content_type
    # extracts the file format e.g application, media, etc
    file_category = re.findall('(.*)\/', file_mime)[0]
    return file_category


#This route is to upload a file
@app.route('/api/file', methods=['POST'])
@jwt_required
def uploadfeaturedimage_file():
    uploaded_file = request.files['file']

    ts = int(datetime.datetime.now().timestamp())
    date = datetime.datetime.fromtimestamp(ts)

    yr = date.year
    mn = date.month
    dy = date.day

    filename = secure_filename(uploaded_file.filename)

    if filename != '':
        name = filename.split('.')[0]
        file_ext = filename.split('.')[1].lower()
       
        file_category = get_file_category(uploaded_file)

        if file_ext not in app.config['UPLOAD_EXTENSIONS']: 
            abort(400, description="File format not supported")

        filename = name + str(ts) + '.' + file_ext

        try:
            if os.path.isdir('./uploads/' + file_category + '/' + str(yr) + '/' + str(mn) + '/' + str(dy)) is True:
                uploaded_file.save(os.path.join(
                    app.config['UPLOAD_PATH'], file_category, str(yr), str(mn), str(dy), filename))

            else:
                directory = './uploads/' + file_category + '/' + str(yr) + '/' + str(mn) + '/' + str(dy)
                print(directory)
                os.makedirs(directory)
                uploaded_file.save(os.path.join(
                    app.config['UPLOAD_PATH'], file_category, str(yr), str(mn), str(dy), filename))

            stat = 'upload successful'  # Default status if file upload is successful
            link = 'http://127.0.0.1:5000/uploads/' + file_category + '/' + str(yr) + '/' + str(mn) + '/' + str(dy) + '/' + str(filename)

        except:
            stat = 'upload not succesful'
            link = 'no link returned because upload was unsuccessful'

        return {'status': stat, 'link': link}


# Create a Course by a lecturer
@app.route('/course/create', methods=['POST'])
@login_required
def course_create():
    try:
        # Gets all input data from the user
        code = request.form.get('code')
        title = request.form.get('title')
        unit = request.form.get('unit')

    except:
        return {'Error': 'Unable to retrieve course details'}


    try:
        code = code.replace(" ", "")
        code = code.upper()

        # Check to see if course code is already in the DB
        controller.add_data(course_model.Course(code, title, unit))
        return {'Status': 'Course registered successfully'}

    except: # Exception as e:
       # raise
       return {'Status': 'registration not successfully'}

# Join a course created
@app.route ('/course/join', methods=['POST'])
@login_required
def course_join():
    try:
        # Get all inputs from the user
        course_id = request.form.get('course_id')
        user_id = request.form.get('user_id')
        
    except:
        return {'Error': 'Unable to retreive details'}

    # add data in the course_memmber table
    try:
        controller.add_data(course_mem.CourseMem(course_id, user_id))

        if controller.get_user_type(user_id) == UserType.Lecturer:
            controller.add_data(course_lecturer.CourseLecturer(course_id, user_id))
        
        return {'Status': 'Successfully joined the course'}
    
    except:
        return {'Error': 'Unable to join course'}


#Get list of active courses a student or lecturer is part of.
@app.route('/courses/<id>', methods=['GET'])
@login_required
def courses(id):
    try:
        courses = controller.get_courses(id)
        return courses

    except:
        return {'Error': 'failed to get courses'}
     

# Register a Course by a Student
@app.route('/course/register', methods=['POST'])
@login_required
def course_register():
    try:
    # Gets all input data from the student
        student_id = request.form.get('student_id')
        course_id = request.form.get('course_id')
        grade_id = request.form.get('grade_id')
        semester = request.form.get('semester')
        session_id = request.form.get('session_id')

    except:
        return {'Error': 'Unable to retreive details'}

    try:
        # add the data to the database
        controller.add_data(course_reg.CourseRegistration(student_id, course_id, grade_id, semester, session_id))
        return {'Status': 'Successfully registered the course'}

    except:
        return {'Error': 'Unable to register the course'}


#Get list of  courses a student has registered.
@app.route('/courses/registered/<id>', methods=['GET'])
@login_required
def registered_courses(id):
    courses = controller.get_registered_courses(id)
    return courses


# Route to update the event for a user. 
@app.route('/calendar/update', methods=['POST'])
@login_required
def update_calendar():   #where id is the user_id
    try:
        user_id = request.form.get('user_id')
        data = request.form.get('data')
        updated_at = request.form.get('updated_at')

    except:
        return {'Error': 'Unable to retreive data sent'}

    try: 
        ts = datetime.datetime.now()
        controller.update_event(user_id, data, ts)
        return{'success': 'event successfully inserted or updated'}
   
   
    except:
        return{'Error': 'error updating event'}


#This route is to like a news
@app.route('/api/news/like', methods=['POST'])
@jwt_required
def like_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    ts = datetime.datetime.now()
    ts = str(ts)
    try:
        # Gets all input data from the user
        # Get the news user wants to like
        news_id = request.form.get('news_id')

    except:
        return {'Error': 'Invalid news_id'}

    try:
        n_controller.like_news(news_controller.Like(user_id, news_id, ts))
        
    except:
        return {'Error': 'unable to like news'}
        
    return{'status': 'liked'}


#This route is to unlike a news
@app.route('/api/news/unlike', methods=['POST'])
@jwt_required
def unlike_news():
    user = get_jwt_identity()
    user_id = int(user['id'])

    try:
        # Gets all input data from the user
        # Get the news user wants to like
        news_id = request.form.get('news_id')

    except:
        return {'Error': 'Invalid news_id'}

    try:
        n_controller.unlike_news(user_id, news_id)

    except:
        return {'Error': 'unable to unlike news'}

    return{'status': 'unliked'}


#This route is to comment on a news
@app.route('/api/news/comment', methods=['POST'])
@jwt_required
def comment_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    ts = datetime.datetime.now()
    ts = str(ts)
    try:
        # Gets all input data from the user
        # Get the news user wants to like
        news_id = request.form.get('news_id')
        comment = request.form.get('comment')  # This is the user's comment

    except:
        return {'Error': 'Invalid news_id'}

    try:
        n_controller.comment_news(
            news_controller.Comment(user_id, news_id, comment, ts))

    except:
        return {'Error': 'unable to comment on news'}

    return{'status': 'commented'}


#This route if to retrieve likes
@app.route('/api/likes/<news_id>', methods=['GET'])
@jwt_required
def get_likes(news_id):

    likes = n_controller.get_likes(news_id)

    return likes


#This route if to retrieve comments
@app.route('/api/comments/<news_id>', methods=['GET'])
@jwt_required
def get_comments(news_id):

    comments = n_controller.get_comments(news_id)

    return comments


#This route is to get the info in a specific news based on the news_id
@app.route('/api/news/<int:news_id>', methods=['GET'])  
@jwt_required
def get_news(news_id): 
    user = get_jwt_identity()
    user_id = int(user['id'])  

    try:  
        news_object = n_controller.get_news(news_id)
        blogger_id = news_object.blogger_id
        blogger_name = b_controller.blogger_name(blogger_id)
        content = news_object.content
        title = news_object.title
        category_id = news_object.category_id
        category = n_controller.get_category(category_id)
        ts = news_object.timestamp
        featured_image_object = n_controller.get_featuredimage(news_id)
        featured_image = featured_image_object.image
        no_of_likes = n_controller.get_no_likes(news_id)
        no_of_comments = n_controller.get_no_comments(news_id)
        user_like = n_controller.user_like(user_id, news_id)

        status = 'success'

        news = {'blogger_name': blogger_name, 'title': title, 'content': content, 'category': category,'featured image': featured_image, 'no of likes':no_of_likes, 'no of comments': no_of_comments, 'user like ?': user_like, 'time': ts}

    except:
        news = 'Record not found'
        status = 'failed'

    return {'status': status, str(news_id):news}

#This route is to get news in a news page


# per means the number per page and page_num means the page number
@app.route('/api/newslist/<int:per>/<int:page_num>', methods=['GET'])
@jwt_required
def get_news_list(per, page_num):

    if page_num == 0:
        page_num = 1

    if per == 0:
        per = 20

    threads = db.session.query(news_model.News).paginate(per_page=per, page=page_num, error_out=False)
    no_of_items = len(threads.items)

    news = {}
    status = 'failed'

    if no_of_items > 0:
        for a in range(no_of_items):
            blogger_id = threads.items[a].blogger_id
            blogger_name = b_controller.blogger_name(blogger_id)
            news.update({threads.items[a].id: {'news_id': threads.items[a].id,
                                               'blogger_name': blogger_name, 'title': threads.items[a].title}})

        status = 'success'

    news_list = {'news_list': news, 'status': status}

    print("i'm here")

    return news_list



if __name__ == '__main__':
    app.run(debug=True)

a3bcc610d94d2704057b75bd778d5737764803a3
<mask token>


def login_required(f):

    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'csrf_access_token' not in request.cookies:
            return {'Error': 'You have to login first'}
        return f(*args, **kwargs)
    return decorated_function


@app.route('/users/register', methods=['POST'])
def register():
    try:
        user_name = request.form.get('user_name')
        surname = request.form.get('surname')
        first_name = request.form.get('first_name')
        email = request.form.get('email')
        password = bcrypt.generate_password_hash(request.form.get('password')
            ).decode('utf-8')
        user_type = request.form.get('user_type')
        getemail = controller.get_email(email)
    except:
        return {'Error': 'Unable to retrieve user details'}
    if str(user_type) == 'Student':
        try:
            program_id = request.form.get('program_id')
            matric_no = request.form.get('matric_no')
            level_id = request.form.get('level_id')
            if getemail == None:
                controller.add_data(student_model.Student(user_name,
                    surname, first_name, email, password, user_type,
                    program_id, matric_no, level_id))
                class_id = controller.get_class_id(program_id, level_id)
                user_id = controller.get_user_id(email)
                controller.add_data(class_mem.ClassMem(class_id, user_id))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to retrieve student details. Ensure the inputs are valid'
                }
    elif str(user_type) == 'Lecturer':
        try:
            department_id = request.form.get('department_id')
            title = request.form.get('title')
            position = request.form.get('position')
            if getemail == None:
                controller.add_data(lecturer_model.Lecturer(user_name,
                    surname, first_name, email, password, user_type,
                    department_id, title, position))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to save lecturer details. Ensure that the inputs are correct'
                }
    elif str(user_type) == 'Mentor':
        try:
            profession = request.form.get('profession')
            company = request.form.get('company')
            title = request.form.get('title')
            if getemail == None:
                controller.add_data(mentor_model.Mentor(user_name, surname,
                    first_name, email, password, user_type, profession,
                    company, title))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to get mentor details. Ensure that the inputs are correct'
                }
    else:
        return {'Error':
            'Unable to get user details. Ensure that the inputs are correct'}


@app.route('/users/<id>', methods=['GET'])
@login_required
def get_user(id):
    try:
        resp = controller.get_user(id)
        return resp.to_dict()
    except:
        return {'Error': 'User not found'}


@app.route('/token/auth', methods=['POST'])
def login():
    email = request.form.get('email')
    pass_word = request.form.get('password')
    try:
        password = controller.get_password(email)
        if bcrypt.check_password_hash(password[0], pass_word):
            user_name = controller.get_user_name(email)
            user_id = controller.get_user_id(email)
            print(user_name)
            access_token = create_access_token(identity={'User name':
                user_name[0], 'id': user_id[0]}, expires_delta=datetime.
                timedelta(days=1))
            refresh_token = create_refresh_token(identity={'User name':
                user_name[0], 'id': user_id[0]}, expires_delta=datetime.
                timedelta(days=1))
            resp = jsonify({'login': True, 'user name': user_name[0]})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp, 200
        else:
            return jsonify({'login': False}), 401
    except:
        return jsonify({'login': False}), 401


@app.route('/token/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)
    resp = jsonify({'refresh': True})
    set_access_cookies(resp, access_token)
    return resp, 200


<mask token>


@app.route('/uploads/<fc>/<yr>/<mn>/<dy>/<filename>', methods=['GET'])
def get_file(fc, yr, mn, dy, filename):
    return send_from_directory(os.path.join(app.config['UPLOAD_PATH'], fc,
        str(yr), str(mn), str(dy)), filename)


<mask token>


@app.route('/api/file', methods=['POST'])
@jwt_required
def uploadfeaturedimage_file():
    uploaded_file = request.files['file']
    ts = int(datetime.datetime.now().timestamp())
    date = datetime.datetime.fromtimestamp(ts)
    yr = date.year
    mn = date.month
    dy = date.day
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        name = filename.split('.')[0]
        file_ext = filename.split('.')[1].lower()
        file_category = get_file_category(uploaded_file)
        if file_ext not in app.config['UPLOAD_EXTENSIONS']:
            abort(400, description='File format not supported')
        filename = name + str(ts) + '.' + file_ext
        try:
            if os.path.isdir('./uploads/' + file_category + '/' + str(yr) +
                '/' + str(mn) + '/' + str(dy)) is True:
                uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'],
                    file_category, str(yr), str(mn), str(dy), filename))
            else:
                directory = './uploads/' + file_category + '/' + str(yr
                    ) + '/' + str(mn) + '/' + str(dy)
                print(directory)
                os.makedirs(directory)
                uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'],
                    file_category, str(yr), str(mn), str(dy), filename))
            stat = 'upload successful'
            link = ('http://127.0.0.1:5000/uploads/' + file_category + '/' +
                str(yr) + '/' + str(mn) + '/' + str(dy) + '/' + str(filename))
        except:
            stat = 'upload not succesful'
            link = 'no link returned because upload was unsuccessful'
        return {'status': stat, 'link': link}


@app.route('/course/create', methods=['POST'])
@login_required
def course_create():
    try:
        code = request.form.get('code')
        title = request.form.get('title')
        unit = request.form.get('unit')
    except:
        return {'Error': 'Unable to retrieve course details'}
    try:
        code = code.replace(' ', '')
        code = code.upper()
        controller.add_data(course_model.Course(code, title, unit))
        return {'Status': 'Course registered successfully'}
    except:
        return {'Status': 'registration not successfully'}


<mask token>


@app.route('/courses/<id>', methods=['GET'])
@login_required
def courses(id):
    try:
        courses = controller.get_courses(id)
        return courses
    except:
        return {'Error': 'failed to get courses'}


@app.route('/course/register', methods=['POST'])
@login_required
def course_register():
    try:
        student_id = request.form.get('student_id')
        course_id = request.form.get('course_id')
        grade_id = request.form.get('grade_id')
        semester = request.form.get('semester')
        session_id = request.form.get('session_id')
    except:
        return {'Error': 'Unable to retreive details'}
    try:
        controller.add_data(course_reg.CourseRegistration(student_id,
            course_id, grade_id, semester, session_id))
        return {'Status': 'Successfully registered the course'}
    except:
        return {'Error': 'Unable to register the course'}


<mask token>


@app.route('/calendar/update', methods=['POST'])
@login_required
def update_calendar():
    try:
        user_id = request.form.get('user_id')
        data = request.form.get('data')
        updated_at = request.form.get('updated_at')
    except:
        return {'Error': 'Unable to retreive data sent'}
    try:
        ts = datetime.datetime.now()
        controller.update_event(user_id, data, ts)
        return {'success': 'event successfully inserted or updated'}
    except:
        return {'Error': 'error updating event'}


<mask token>


@app.route('/api/news/unlike', methods=['POST'])
@jwt_required
def unlike_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    try:
        news_id = request.form.get('news_id')
    except:
        return {'Error': 'Invalid news_id'}
    try:
        n_controller.unlike_news(user_id, news_id)
    except:
        return {'Error': 'unable to unlike news'}
    return {'status': 'unliked'}


@app.route('/api/news/comment', methods=['POST'])
@jwt_required
def comment_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    ts = datetime.datetime.now()
    ts = str(ts)
    try:
        news_id = request.form.get('news_id')
        comment = request.form.get('comment')
    except:
        return {'Error': 'Invalid news_id'}
    try:
        n_controller.comment_news(news_controller.Comment(user_id, news_id,
            comment, ts))
    except:
        return {'Error': 'unable to comment on news'}
    return {'status': 'commented'}


@app.route('/api/likes/<news_id>', methods=['GET'])
@jwt_required
def get_likes(news_id):
    likes = n_controller.get_likes(news_id)
    return likes


<mask token>


@app.route('/api/newslist/<int:per>/<int:page_num>', methods=['GET'])
@jwt_required
def get_news_list(per, page_num):
    if page_num == 0:
        page_num = 1
    if per == 0:
        per = 20
    threads = db.session.query(news_model.News).paginate(per_page=per, page
        =page_num, error_out=False)
    no_of_items = len(threads.items)
    news = {}
    status = 'failed'
    if no_of_items > 0:
        for a in range(no_of_items):
            blogger_id = threads.items[a].blogger_id
            blogger_name = b_controller.blogger_name(blogger_id)
            news.update({threads.items[a].id: {'news_id': threads.items[a].
                id, 'blogger_name': blogger_name, 'title': threads.items[a]
                .title}})
        status = 'success'
    news_list = {'news_list': news, 'status': status}
    print("i'm here")
    return news_list


<mask token>

<mask token>


def login_required(f):

    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'csrf_access_token' not in request.cookies:
            return {'Error': 'You have to login first'}
        return f(*args, **kwargs)
    return decorated_function


@app.route('/users/register', methods=['POST'])
def register():
    try:
        user_name = request.form.get('user_name')
        surname = request.form.get('surname')
        first_name = request.form.get('first_name')
        email = request.form.get('email')
        password = bcrypt.generate_password_hash(request.form.get('password')
            ).decode('utf-8')
        user_type = request.form.get('user_type')
        getemail = controller.get_email(email)
    except:
        return {'Error': 'Unable to retrieve user details'}
    if str(user_type) == 'Student':
        try:
            program_id = request.form.get('program_id')
            matric_no = request.form.get('matric_no')
            level_id = request.form.get('level_id')
            if getemail == None:
                controller.add_data(student_model.Student(user_name,
                    surname, first_name, email, password, user_type,
                    program_id, matric_no, level_id))
                class_id = controller.get_class_id(program_id, level_id)
                user_id = controller.get_user_id(email)
                controller.add_data(class_mem.ClassMem(class_id, user_id))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to retrieve student details. Ensure the inputs are valid'
                }
    elif str(user_type) == 'Lecturer':
        try:
            department_id = request.form.get('department_id')
            title = request.form.get('title')
            position = request.form.get('position')
            if getemail == None:
                controller.add_data(lecturer_model.Lecturer(user_name,
                    surname, first_name, email, password, user_type,
                    department_id, title, position))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to save lecturer details. Ensure that the inputs are correct'
                }
    elif str(user_type) == 'Mentor':
        try:
            profession = request.form.get('profession')
            company = request.form.get('company')
            title = request.form.get('title')
            if getemail == None:
                controller.add_data(mentor_model.Mentor(user_name, surname,
                    first_name, email, password, user_type, profession,
                    company, title))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to get mentor details. Ensure that the inputs are correct'
                }
    else:
        return {'Error':
            'Unable to get user details. Ensure that the inputs are correct'}


@app.route('/users/<id>', methods=['GET'])
@login_required
def get_user(id):
    try:
        resp = controller.get_user(id)
        return resp.to_dict()
    except:
        return {'Error': 'User not found'}


@app.route('/token/auth', methods=['POST'])
def login():
    email = request.form.get('email')
    pass_word = request.form.get('password')
    try:
        password = controller.get_password(email)
        if bcrypt.check_password_hash(password[0], pass_word):
            user_name = controller.get_user_name(email)
            user_id = controller.get_user_id(email)
            print(user_name)
            access_token = create_access_token(identity={'User name':
                user_name[0], 'id': user_id[0]}, expires_delta=datetime.
                timedelta(days=1))
            refresh_token = create_refresh_token(identity={'User name':
                user_name[0], 'id': user_id[0]}, expires_delta=datetime.
                timedelta(days=1))
            resp = jsonify({'login': True, 'user name': user_name[0]})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp, 200
        else:
            return jsonify({'login': False}), 401
    except:
        return jsonify({'login': False}), 401


@app.route('/token/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)
    resp = jsonify({'refresh': True})
    set_access_cookies(resp, access_token)
    return resp, 200


<mask token>


@app.route('/uploads/<fc>/<yr>/<mn>/<dy>/<filename>', methods=['GET'])
def get_file(fc, yr, mn, dy, filename):
    return send_from_directory(os.path.join(app.config['UPLOAD_PATH'], fc,
        str(yr), str(mn), str(dy)), filename)


<mask token>


@app.route('/api/file', methods=['POST'])
@jwt_required
def uploadfeaturedimage_file():
    uploaded_file = request.files['file']
    ts = int(datetime.datetime.now().timestamp())
    date = datetime.datetime.fromtimestamp(ts)
    yr = date.year
    mn = date.month
    dy = date.day
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        name = filename.split('.')[0]
        file_ext = filename.split('.')[1].lower()
        file_category = get_file_category(uploaded_file)
        if file_ext not in app.config['UPLOAD_EXTENSIONS']:
            abort(400, description='File format not supported')
        filename = name + str(ts) + '.' + file_ext
        try:
            if os.path.isdir('./uploads/' + file_category + '/' + str(yr) +
                '/' + str(mn) + '/' + str(dy)) is True:
                uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'],
                    file_category, str(yr), str(mn), str(dy), filename))
            else:
                directory = './uploads/' + file_category + '/' + str(yr
                    ) + '/' + str(mn) + '/' + str(dy)
                print(directory)
                os.makedirs(directory)
                uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'],
                    file_category, str(yr), str(mn), str(dy), filename))
            stat = 'upload successful'
            link = ('http://127.0.0.1:5000/uploads/' + file_category + '/' +
                str(yr) + '/' + str(mn) + '/' + str(dy) + '/' + str(filename))
        except:
            stat = 'upload not succesful'
            link = 'no link returned because upload was unsuccessful'
        return {'status': stat, 'link': link}


@app.route('/course/create', methods=['POST'])
@login_required
def course_create():
    try:
        code = request.form.get('code')
        title = request.form.get('title')
        unit = request.form.get('unit')
    except:
        return {'Error': 'Unable to retrieve course details'}
    try:
        code = code.replace(' ', '')
        code = code.upper()
        controller.add_data(course_model.Course(code, title, unit))
        return {'Status': 'Course registered successfully'}
    except:
        return {'Status': 'registration not successfully'}


<mask token>


@app.route('/courses/<id>', methods=['GET'])
@login_required
def courses(id):
    try:
        courses = controller.get_courses(id)
        return courses
    except:
        return {'Error': 'failed to get courses'}


@app.route('/course/register', methods=['POST'])
@login_required
def course_register():
    try:
        student_id = request.form.get('student_id')
        course_id = request.form.get('course_id')
        grade_id = request.form.get('grade_id')
        semester = request.form.get('semester')
        session_id = request.form.get('session_id')
    except:
        return {'Error': 'Unable to retreive details'}
    try:
        controller.add_data(course_reg.CourseRegistration(student_id,
            course_id, grade_id, semester, session_id))
        return {'Status': 'Successfully registered the course'}
    except:
        return {'Error': 'Unable to register the course'}


@app.route('/courses/registered/<id>', methods=['GET'])
@login_required
def registered_courses(id):
    courses = controller.get_registered_courses(id)
    return courses


@app.route('/calendar/update', methods=['POST'])
@login_required
def update_calendar():
    try:
        user_id = request.form.get('user_id')
        data = request.form.get('data')
        updated_at = request.form.get('updated_at')
    except:
        return {'Error': 'Unable to retreive data sent'}
    try:
        ts = datetime.datetime.now()
        controller.update_event(user_id, data, ts)
        return {'success': 'event successfully inserted or updated'}
    except:
        return {'Error': 'error updating event'}


@app.route('/api/news/like', methods=['POST'])
@jwt_required
def like_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    ts = datetime.datetime.now()
    ts = str(ts)
    try:
        news_id = request.form.get('news_id')
    except:
        return {'Error': 'Invalid news_id'}
    try:
        n_controller.like_news(news_controller.Like(user_id, news_id, ts))
    except:
        return {'Error': 'unable to like news'}
    return {'status': 'liked'}


@app.route('/api/news/unlike', methods=['POST'])
@jwt_required
def unlike_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    try:
        news_id = request.form.get('news_id')
    except:
        return {'Error': 'Invalid news_id'}
    try:
        n_controller.unlike_news(user_id, news_id)
    except:
        return {'Error': 'unable to unlike news'}
    return {'status': 'unliked'}


@app.route('/api/news/comment', methods=['POST'])
@jwt_required
def comment_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    ts = datetime.datetime.now()
    ts = str(ts)
    try:
        news_id = request.form.get('news_id')
        comment = request.form.get('comment')
    except:
        return {'Error': 'Invalid news_id'}
    try:
        n_controller.comment_news(news_controller.Comment(user_id, news_id,
            comment, ts))
    except:
        return {'Error': 'unable to comment on news'}
    return {'status': 'commented'}


@app.route('/api/likes/<news_id>', methods=['GET'])
@jwt_required
def get_likes(news_id):
    likes = n_controller.get_likes(news_id)
    return likes


<mask token>


@app.route('/api/newslist/<int:per>/<int:page_num>', methods=['GET'])
@jwt_required
def get_news_list(per, page_num):
    if page_num == 0:
        page_num = 1
    if per == 0:
        per = 20
    threads = db.session.query(news_model.News).paginate(per_page=per, page
        =page_num, error_out=False)
    no_of_items = len(threads.items)
    news = {}
    status = 'failed'
    if no_of_items > 0:
        for a in range(no_of_items):
            blogger_id = threads.items[a].blogger_id
            blogger_name = b_controller.blogger_name(blogger_id)
            news.update({threads.items[a].id: {'news_id': threads.items[a].
                id, 'blogger_name': blogger_name, 'title': threads.items[a]
                .title}})
        status = 'success'
    news_list = {'news_list': news, 'status': status}
    print("i'm here")
    return news_list


<mask token>

<mask token>


def login_required(f):

    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'csrf_access_token' not in request.cookies:
            return {'Error': 'You have to login first'}
        return f(*args, **kwargs)
    return decorated_function


@app.route('/users/register', methods=['POST'])
def register():
    try:
        user_name = request.form.get('user_name')
        surname = request.form.get('surname')
        first_name = request.form.get('first_name')
        email = request.form.get('email')
        password = bcrypt.generate_password_hash(request.form.get('password')
            ).decode('utf-8')
        user_type = request.form.get('user_type')
        getemail = controller.get_email(email)
    except:
        return {'Error': 'Unable to retrieve user details'}
    if str(user_type) == 'Student':
        try:
            program_id = request.form.get('program_id')
            matric_no = request.form.get('matric_no')
            level_id = request.form.get('level_id')
            if getemail == None:
                controller.add_data(student_model.Student(user_name,
                    surname, first_name, email, password, user_type,
                    program_id, matric_no, level_id))
                class_id = controller.get_class_id(program_id, level_id)
                user_id = controller.get_user_id(email)
                controller.add_data(class_mem.ClassMem(class_id, user_id))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to retrieve student details. Ensure the inputs are valid'
                }
    elif str(user_type) == 'Lecturer':
        try:
            department_id = request.form.get('department_id')
            title = request.form.get('title')
            position = request.form.get('position')
            if getemail == None:
                controller.add_data(lecturer_model.Lecturer(user_name,
                    surname, first_name, email, password, user_type,
                    department_id, title, position))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to save lecturer details. Ensure that the inputs are correct'
                }
    elif str(user_type) == 'Mentor':
        try:
            profession = request.form.get('profession')
            company = request.form.get('company')
            title = request.form.get('title')
            if getemail == None:
                controller.add_data(mentor_model.Mentor(user_name, surname,
                    first_name, email, password, user_type, profession,
                    company, title))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to get mentor details. Ensure that the inputs are correct'
                }
    else:
        return {'Error':
            'Unable to get user details. Ensure that the inputs are correct'}


@app.route('/users/<id>', methods=['GET'])
@login_required
def get_user(id):
    try:
        resp = controller.get_user(id)
        return resp.to_dict()
    except:
        return {'Error': 'User not found'}


@app.route('/token/auth', methods=['POST'])
def login():
    email = request.form.get('email')
    pass_word = request.form.get('password')
    try:
        password = controller.get_password(email)
        if bcrypt.check_password_hash(password[0], pass_word):
            user_name = controller.get_user_name(email)
            user_id = controller.get_user_id(email)
            print(user_name)
            access_token = create_access_token(identity={'User name':
                user_name[0], 'id': user_id[0]}, expires_delta=datetime.
                timedelta(days=1))
            refresh_token = create_refresh_token(identity={'User name':
                user_name[0], 'id': user_id[0]}, expires_delta=datetime.
                timedelta(days=1))
            resp = jsonify({'login': True, 'user name': user_name[0]})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp, 200
        else:
            return jsonify({'login': False}), 401
    except:
        return jsonify({'login': False}), 401


@app.route('/token/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)
    resp = jsonify({'refresh': True})
    set_access_cookies(resp, access_token)
    return resp, 200


@app.route('/token/remove', methods=['POST'])
def logout():
    resp = jsonify({'logout': True})
    unset_jwt_cookies(resp)
    return resp, 200


@app.route('/uploads/<fc>/<yr>/<mn>/<dy>/<filename>', methods=['GET'])
def get_file(fc, yr, mn, dy, filename):
    return send_from_directory(os.path.join(app.config['UPLOAD_PATH'], fc,
        str(yr), str(mn), str(dy)), filename)


def get_file_category(uploaded_file):
    file_mime = uploaded_file.content_type
    file_category = re.findall('(.*)\\/', file_mime)[0]
    return file_category


@app.route('/api/file', methods=['POST'])
@jwt_required
def uploadfeaturedimage_file():
    uploaded_file = request.files['file']
    ts = int(datetime.datetime.now().timestamp())
    date = datetime.datetime.fromtimestamp(ts)
    yr = date.year
    mn = date.month
    dy = date.day
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        name = filename.split('.')[0]
        file_ext = filename.split('.')[1].lower()
        file_category = get_file_category(uploaded_file)
        if file_ext not in app.config['UPLOAD_EXTENSIONS']:
            abort(400, description='File format not supported')
        filename = name + str(ts) + '.' + file_ext
        try:
            if os.path.isdir('./uploads/' + file_category + '/' + str(yr) +
                '/' + str(mn) + '/' + str(dy)) is True:
                uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'],
                    file_category, str(yr), str(mn), str(dy), filename))
            else:
                directory = './uploads/' + file_category + '/' + str(yr
                    ) + '/' + str(mn) + '/' + str(dy)
                print(directory)
                os.makedirs(directory)
                uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'],
                    file_category, str(yr), str(mn), str(dy), filename))
            stat = 'upload successful'
            link = ('http://127.0.0.1:5000/uploads/' + file_category + '/' +
                str(yr) + '/' + str(mn) + '/' + str(dy) + '/' + str(filename))
        except:
            stat = 'upload not succesful'
            link = 'no link returned because upload was unsuccessful'
        return {'status': stat, 'link': link}


@app.route('/course/create', methods=['POST'])
@login_required
def course_create():
    try:
        code = request.form.get('code')
        title = request.form.get('title')
        unit = request.form.get('unit')
    except:
        return {'Error': 'Unable to retrieve course details'}
    try:
        code = code.replace(' ', '')
        code = code.upper()
        controller.add_data(course_model.Course(code, title, unit))
        return {'Status': 'Course registered successfully'}
    except:
        return {'Status': 'registration not successfully'}


<mask token>


@app.route('/courses/<id>', methods=['GET'])
@login_required
def courses(id):
    try:
        courses = controller.get_courses(id)
        return courses
    except:
        return {'Error': 'failed to get courses'}


@app.route('/course/register', methods=['POST'])
@login_required
def course_register():
    try:
        student_id = request.form.get('student_id')
        course_id = request.form.get('course_id')
        grade_id = request.form.get('grade_id')
        semester = request.form.get('semester')
        session_id = request.form.get('session_id')
    except:
        return {'Error': 'Unable to retreive details'}
    try:
        controller.add_data(course_reg.CourseRegistration(student_id,
            course_id, grade_id, semester, session_id))
        return {'Status': 'Successfully registered the course'}
    except:
        return {'Error': 'Unable to register the course'}


@app.route('/courses/registered/<id>', methods=['GET'])
@login_required
def registered_courses(id):
    courses = controller.get_registered_courses(id)
    return courses


@app.route('/calendar/update', methods=['POST'])
@login_required
def update_calendar():
    try:
        user_id = request.form.get('user_id')
        data = request.form.get('data')
        updated_at = request.form.get('updated_at')
    except:
        return {'Error': 'Unable to retreive data sent'}
    try:
        ts = datetime.datetime.now()
        controller.update_event(user_id, data, ts)
        return {'success': 'event successfully inserted or updated'}
    except:
        return {'Error': 'error updating event'}


@app.route('/api/news/like', methods=['POST'])
@jwt_required
def like_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    ts = datetime.datetime.now()
    ts = str(ts)
    try:
        news_id = request.form.get('news_id')
    except:
        return {'Error': 'Invalid news_id'}
    try:
        n_controller.like_news(news_controller.Like(user_id, news_id, ts))
    except:
        return {'Error': 'unable to like news'}
    return {'status': 'liked'}


@app.route('/api/news/unlike', methods=['POST'])
@jwt_required
def unlike_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    try:
        news_id = request.form.get('news_id')
    except:
        return {'Error': 'Invalid news_id'}
    try:
        n_controller.unlike_news(user_id, news_id)
    except:
        return {'Error': 'unable to unlike news'}
    return {'status': 'unliked'}


@app.route('/api/news/comment', methods=['POST'])
@jwt_required
def comment_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    ts = datetime.datetime.now()
    ts = str(ts)
    try:
        news_id = request.form.get('news_id')
        comment = request.form.get('comment')
    except:
        return {'Error': 'Invalid news_id'}
    try:
        n_controller.comment_news(news_controller.Comment(user_id, news_id,
            comment, ts))
    except:
        return {'Error': 'unable to comment on news'}
    return {'status': 'commented'}


@app.route('/api/likes/<news_id>', methods=['GET'])
@jwt_required
def get_likes(news_id):
    likes = n_controller.get_likes(news_id)
    return likes


<mask token>


@app.route('/api/news/<int:news_id>', methods=['GET'])
@jwt_required
def get_news(news_id):
    user = get_jwt_identity()
    user_id = int(user['id'])
    try:
        news_object = n_controller.get_news(news_id)
        blogger_id = news_object.blogger_id
        blogger_name = b_controller.blogger_name(blogger_id)
        content = news_object.content
        title = news_object.title
        category_id = news_object.category_id
        category = n_controller.get_category(category_id)
        ts = news_object.timestamp
        featured_image_object = n_controller.get_featuredimage(news_id)
        featured_image = featured_image_object.image
        no_of_likes = n_controller.get_no_likes(news_id)
        no_of_comments = n_controller.get_no_comments(news_id)
        user_like = n_controller.user_like(user_id, news_id)
        status = 'success'
        news = {'blogger_name': blogger_name, 'title': title, 'content':
            content, 'category': category, 'featured image': featured_image,
            'no of likes': no_of_likes, 'no of comments': no_of_comments,
            'user like ?': user_like, 'time': ts}
    except:
        news = 'Record not found'
        status = 'failed'
    return {'status': status, str(news_id): news}


@app.route('/api/newslist/<int:per>/<int:page_num>', methods=['GET'])
@jwt_required
def get_news_list(per, page_num):
    if page_num == 0:
        page_num = 1
    if per == 0:
        per = 20
    threads = db.session.query(news_model.News).paginate(per_page=per, page
        =page_num, error_out=False)
    no_of_items = len(threads.items)
    news = {}
    status = 'failed'
    if no_of_items > 0:
        for a in range(no_of_items):
            blogger_id = threads.items[a].blogger_id
            blogger_name = b_controller.blogger_name(blogger_id)
            news.update({threads.items[a].id: {'news_id': threads.items[a].
                id, 'blogger_name': blogger_name, 'title': threads.items[a]
                .title}})
        status = 'success'
    news_list = {'news_list': news, 'status': status}
    print("i'm here")
    return news_list


<mask token>

<mask token>


def login_required(f):

    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'csrf_access_token' not in request.cookies:
            return {'Error': 'You have to login first'}
        return f(*args, **kwargs)
    return decorated_function


@app.route('/users/register', methods=['POST'])
def register():
    try:
        user_name = request.form.get('user_name')
        surname = request.form.get('surname')
        first_name = request.form.get('first_name')
        email = request.form.get('email')
        password = bcrypt.generate_password_hash(request.form.get('password')
            ).decode('utf-8')
        user_type = request.form.get('user_type')
        getemail = controller.get_email(email)
    except:
        return {'Error': 'Unable to retrieve user details'}
    if str(user_type) == 'Student':
        try:
            program_id = request.form.get('program_id')
            matric_no = request.form.get('matric_no')
            level_id = request.form.get('level_id')
            if getemail == None:
                controller.add_data(student_model.Student(user_name,
                    surname, first_name, email, password, user_type,
                    program_id, matric_no, level_id))
                class_id = controller.get_class_id(program_id, level_id)
                user_id = controller.get_user_id(email)
                controller.add_data(class_mem.ClassMem(class_id, user_id))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to retrieve student details. Ensure the inputs are valid'
                }
    elif str(user_type) == 'Lecturer':
        try:
            department_id = request.form.get('department_id')
            title = request.form.get('title')
            position = request.form.get('position')
            if getemail == None:
                controller.add_data(lecturer_model.Lecturer(user_name,
                    surname, first_name, email, password, user_type,
                    department_id, title, position))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to save lecturer details. Ensure that the inputs are correct'
                }
    elif str(user_type) == 'Mentor':
        try:
            profession = request.form.get('profession')
            company = request.form.get('company')
            title = request.form.get('title')
            if getemail == None:
                controller.add_data(mentor_model.Mentor(user_name, surname,
                    first_name, email, password, user_type, profession,
                    company, title))
                return {'success': 'succesfully updated in the database'}
            elif email == getemail[0]:
                return {'Error': 'This email has already been used to register'
                    }
        except:
            return {'Error':
                'Unable to get mentor details. Ensure that the inputs are correct'
                }
    else:
        return {'Error':
            'Unable to get user details. Ensure that the inputs are correct'}


@app.route('/users/<id>', methods=['GET'])
@login_required
def get_user(id):
    try:
        resp = controller.get_user(id)
        return resp.to_dict()
    except:
        return {'Error': 'User not found'}


@app.route('/token/auth', methods=['POST'])
def login():
    email = request.form.get('email')
    pass_word = request.form.get('password')
    try:
        password = controller.get_password(email)
        if bcrypt.check_password_hash(password[0], pass_word):
            user_name = controller.get_user_name(email)
            user_id = controller.get_user_id(email)
            print(user_name)
            access_token = create_access_token(identity={'User name':
                user_name[0], 'id': user_id[0]}, expires_delta=datetime.
                timedelta(days=1))
            refresh_token = create_refresh_token(identity={'User name':
                user_name[0], 'id': user_id[0]}, expires_delta=datetime.
                timedelta(days=1))
            resp = jsonify({'login': True, 'user name': user_name[0]})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)
            return resp, 200
        else:
            return jsonify({'login': False}), 401
    except:
        return jsonify({'login': False}), 401


@app.route('/token/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)
    resp = jsonify({'refresh': True})
    set_access_cookies(resp, access_token)
    return resp, 200


@app.route('/token/remove', methods=['POST'])
def logout():
    resp = jsonify({'logout': True})
    unset_jwt_cookies(resp)
    return resp, 200


@app.route('/uploads/<fc>/<yr>/<mn>/<dy>/<filename>', methods=['GET'])
def get_file(fc, yr, mn, dy, filename):
    return send_from_directory(os.path.join(app.config['UPLOAD_PATH'], fc,
        str(yr), str(mn), str(dy)), filename)


def get_file_category(uploaded_file):
    file_mime = uploaded_file.content_type
    file_category = re.findall('(.*)\\/', file_mime)[0]
    return file_category


@app.route('/api/file', methods=['POST'])
@jwt_required
def uploadfeaturedimage_file():
    uploaded_file = request.files['file']
    ts = int(datetime.datetime.now().timestamp())
    date = datetime.datetime.fromtimestamp(ts)
    yr = date.year
    mn = date.month
    dy = date.day
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        name = filename.split('.')[0]
        file_ext = filename.split('.')[1].lower()
        file_category = get_file_category(uploaded_file)
        if file_ext not in app.config['UPLOAD_EXTENSIONS']:
            abort(400, description='File format not supported')
        filename = name + str(ts) + '.' + file_ext
        try:
            if os.path.isdir('./uploads/' + file_category + '/' + str(yr) +
                '/' + str(mn) + '/' + str(dy)) is True:
                uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'],
                    file_category, str(yr), str(mn), str(dy), filename))
            else:
                directory = './uploads/' + file_category + '/' + str(yr
                    ) + '/' + str(mn) + '/' + str(dy)
                print(directory)
                os.makedirs(directory)
                uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'],
                    file_category, str(yr), str(mn), str(dy), filename))
            stat = 'upload successful'
            link = ('http://127.0.0.1:5000/uploads/' + file_category + '/' +
                str(yr) + '/' + str(mn) + '/' + str(dy) + '/' + str(filename))
        except:
            stat = 'upload not succesful'
            link = 'no link returned because upload was unsuccessful'
        return {'status': stat, 'link': link}


@app.route('/course/create', methods=['POST'])
@login_required
def course_create():
    try:
        code = request.form.get('code')
        title = request.form.get('title')
        unit = request.form.get('unit')
    except:
        return {'Error': 'Unable to retrieve course details'}
    try:
        code = code.replace(' ', '')
        code = code.upper()
        controller.add_data(course_model.Course(code, title, unit))
        return {'Status': 'Course registered successfully'}
    except:
        return {'Status': 'registration not successfully'}


@app.route('/course/join', methods=['POST'])
@login_required
def course_join():
    try:
        course_id = request.form.get('course_id')
        user_id = request.form.get('user_id')
    except:
        return {'Error': 'Unable to retreive details'}
    try:
        controller.add_data(course_mem.CourseMem(course_id, user_id))
        if controller.get_user_type(user_id) == UserType.Lecturer:
            controller.add_data(course_lecturer.CourseLecturer(course_id,
                user_id))
        return {'Status': 'Successfully joined the course'}
    except:
        return {'Error': 'Unable to join course'}


@app.route('/courses/<id>', methods=['GET'])
@login_required
def courses(id):
    try:
        courses = controller.get_courses(id)
        return courses
    except:
        return {'Error': 'failed to get courses'}


@app.route('/course/register', methods=['POST'])
@login_required
def course_register():
    try:
        student_id = request.form.get('student_id')
        course_id = request.form.get('course_id')
        grade_id = request.form.get('grade_id')
        semester = request.form.get('semester')
        session_id = request.form.get('session_id')
    except:
        return {'Error': 'Unable to retreive details'}
    try:
        controller.add_data(course_reg.CourseRegistration(student_id,
            course_id, grade_id, semester, session_id))
        return {'Status': 'Successfully registered the course'}
    except:
        return {'Error': 'Unable to register the course'}


@app.route('/courses/registered/<id>', methods=['GET'])
@login_required
def registered_courses(id):
    courses = controller.get_registered_courses(id)
    return courses


@app.route('/calendar/update', methods=['POST'])
@login_required
def update_calendar():
    try:
        user_id = request.form.get('user_id')
        data = request.form.get('data')
        updated_at = request.form.get('updated_at')
    except:
        return {'Error': 'Unable to retreive data sent'}
    try:
        ts = datetime.datetime.now()
        controller.update_event(user_id, data, ts)
        return {'success': 'event successfully inserted or updated'}
    except:
        return {'Error': 'error updating event'}


@app.route('/api/news/like', methods=['POST'])
@jwt_required
def like_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    ts = datetime.datetime.now()
    ts = str(ts)
    try:
        news_id = request.form.get('news_id')
    except:
        return {'Error': 'Invalid news_id'}
    try:
        n_controller.like_news(news_controller.Like(user_id, news_id, ts))
    except:
        return {'Error': 'unable to like news'}
    return {'status': 'liked'}


@app.route('/api/news/unlike', methods=['POST'])
@jwt_required
def unlike_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    try:
        news_id = request.form.get('news_id')
    except:
        return {'Error': 'Invalid news_id'}
    try:
        n_controller.unlike_news(user_id, news_id)
    except:
        return {'Error': 'unable to unlike news'}
    return {'status': 'unliked'}


@app.route('/api/news/comment', methods=['POST'])
@jwt_required
def comment_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    ts = datetime.datetime.now()
    ts = str(ts)
    try:
        news_id = request.form.get('news_id')
        comment = request.form.get('comment')
    except:
        return {'Error': 'Invalid news_id'}
    try:
        n_controller.comment_news(news_controller.Comment(user_id, news_id,
            comment, ts))
    except:
        return {'Error': 'unable to comment on news'}
    return {'status': 'commented'}


@app.route('/api/likes/<news_id>', methods=['GET'])
@jwt_required
def get_likes(news_id):
    likes = n_controller.get_likes(news_id)
    return likes


<mask token>


@app.route('/api/news/<int:news_id>', methods=['GET'])
@jwt_required
def get_news(news_id):
    user = get_jwt_identity()
    user_id = int(user['id'])
    try:
        news_object = n_controller.get_news(news_id)
        blogger_id = news_object.blogger_id
        blogger_name = b_controller.blogger_name(blogger_id)
        content = news_object.content
        title = news_object.title
        category_id = news_object.category_id
        category = n_controller.get_category(category_id)
        ts = news_object.timestamp
        featured_image_object = n_controller.get_featuredimage(news_id)
        featured_image = featured_image_object.image
        no_of_likes = n_controller.get_no_likes(news_id)
        no_of_comments = n_controller.get_no_comments(news_id)
        user_like = n_controller.user_like(user_id, news_id)
        status = 'success'
        news = {'blogger_name': blogger_name, 'title': title, 'content':
            content, 'category': category, 'featured image': featured_image,
            'no of likes': no_of_likes, 'no of comments': no_of_comments,
            'user like ?': user_like, 'time': ts}
    except:
        news = 'Record not found'
        status = 'failed'
    return {'status': status, str(news_id): news}


@app.route('/api/newslist/<int:per>/<int:page_num>', methods=['GET'])
@jwt_required
def get_news_list(per, page_num):
    if page_num == 0:
        page_num = 1
    if per == 0:
        per = 20
    threads = db.session.query(news_model.News).paginate(per_page=per, page
        =page_num, error_out=False)
    no_of_items = len(threads.items)
    news = {}
    status = 'failed'
    if no_of_items > 0:
        for a in range(no_of_items):
            blogger_id = threads.items[a].blogger_id
            blogger_name = b_controller.blogger_name(blogger_id)
            news.update({threads.items[a].id: {'news_id': threads.items[a].
                id, 'blogger_name': blogger_name, 'title': threads.items[a]
                .title}})
        status = 'success'
    news_list = {'news_list': news, 'status': status}
    print("i'm here")
    return news_list


<mask token>

import os
import re
import datetime
from werkzeug.utils import secure_filename
from flask import Flask, jsonify, request, abort, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_mysqldb import MySQL
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from flask_jwt_extended import (
    JWTManager, jwt_required, create_access_token,
    jwt_refresh_token_required, create_refresh_token,
    get_jwt_identity, set_access_cookies,
    set_refresh_cookies, unset_jwt_cookies
)
from flask_wtf.csrf import CSRFProtect
from model import user_model
from model import student_model
from model import lecturer_model
from model import mentor_model

from controller import user_controller, news_controller, blogger_controller
import json
from model import base
from functools import wraps
from flask import g, request, redirect, url_for
import MySQLdb
from inittables import InitTables
from sqlalchemy.orm import relationship, backref
from sqlalchemy.orm import sessionmaker
from model.school_model import School, Faculty, Department, Program, Level
from platform_model import class_mem, class_message, class_model, course_model, course_mem, course_lecturer, course_message

from message_model import group_conv_init, group_conv_mem, personal_conv_init, personal_conv_mem, personal_message_model, group_message_model 
from entertainment_model import news_model, blogger_model, featured_image_model, like, comment, news_category
from personal_model import course_reg, calender
from model.user_type import UserType


# Retrieves database configuration from environment variables
mysql_host = os.environ.get('MYSQL_HOST')
mysql_user = os.environ.get('MYSQL_USER')
mysql_password = os.environ.get('MYSQL_PASSWORD')
db_name = 'testing'  # os.environ.get('DB_NAME')

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'mp3', 'mp4', 'pdf', 'doc', 'docx'}    # Feel free to add more file types to be accepted
MAX_CONTENT_LENGTH = 1024*1024*10  # Maximum file upload sixe is 50 MB

# App flask Configuration
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://' + mysql_user + ':' + mysql_password + '@' + mysql_host + '/' + db_name
app.config['JWT_TOKEN_LOCATION'] = ['cookies']
app.config['JWT_COOKIE_SECURE'] = False
app.config['JWT_ACCESS_COOKIE_PATH'] = '/api/'
app.config['JWT_REFRESH_COOKIE_PATH'] = '/token/refresh'
app.config['JWT_COOKIE_CSRF_PROTECT'] = True
app.config['JWT_SECRET_KEY'] = os.environ.get('JWT_SECRET_KEY')  #The Jwt_secret_key is obtained from environment variables
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH
app.config['UPLOAD_EXTENSIONS'] = ALLOWED_EXTENSIONS
app.config['UPLOAD_PATH'] = UPLOAD_FOLDER


db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
jwt = JWTManager(app)
base.Base.metadata.create_all(db.engine, checkfirst=True)

 # This part of the code is to check if the important tables (School, Faculty, Department, Program, Level) have been initialized
Session = sessionmaker(db.engine) 
Session.configure()
session = Session()
if session.query(School).count() == 0 or session.query(Faculty).count() == 0 or session.query(Department).count() == 0 or session.query(Program).count() == 0 or session.query(Level).count() == 0 :
    InitTables(session)

controller = user_controller.UserController(db)     #Create instance of controller to perform some operations
n_controller = news_controller.NewsController(db)   # Create instance of news controller to perform some operations
b_controller = blogger_controller.BloggerController(db)     #Create instance of blogger controller to perform some operations

CORS(app)

# Sets up the funtion for checking if a user is logged in
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'csrf_access_token' not in request.cookies:
            return {'Error': 'You have to login first'}
        return f(*args, **kwargs)
    return decorated_function


# Register a user - either a student, lecturer or mentor
@app.route('/users/register', methods = ['POST'])
def register ():
    try:
        # Gets all input data from the user
        user_name = request.form.get('user_name')
        surname = request.form.get('surname')
        first_name = request.form.get('first_name')
        email = request.form.get('email')
        password = bcrypt.generate_password_hash(request.form.get('password')).decode('utf-8')
        user_type = request.form.get('user_type')

        getemail = controller.get_email(email)  # Checks to see if the entry email is in the database. If not, it returns None

    except:
        return {'Error': 'Unable to retrieve user details'}


    if str(user_type) == 'Student':
        try:  
            # Gets additional input for a student
            program_id = request.form.get('program_id')
            matric_no = request.form.get('matric_no')
            level_id = request.form.get('level_id')

            if getemail == None:   # If email is not already registered, input the data into the database
                controller.add_data(student_model.Student(
                    user_name, surname, first_name, email, password, user_type, program_id, matric_no, level_id))

                class_id = controller.get_class_id(program_id, level_id)
                user_id = controller.get_user_id(email)
                controller.add_data(class_mem.ClassMem(class_id, user_id))

                return {'success': 'succesfully updated in the database'}         

            elif email == getemail[0]: # If email is already used, notify the user
                return {'Error': 'This email has already been used to register'}
        
        except:  # To notify if a student hasn't conformed to an acceptable input format.
            return {'Error': 'Unable to retrieve student details. Ensure the inputs are valid'}


    elif str(user_type) == 'Lecturer':
        try: 
            # Get additional inpuuts for lecturers
            department_id = request.form.get('department_id')
            title = request.form.get('title')
            position = request.form.get('position')

            if getemail == None:  # If email is not already registered, input the data into the database
                controller.add_data(lecturer_model.Lecturer(
                    user_name, surname, first_name, email, password, user_type, department_id, title, position))

                return {'success': 'succesfully updated in the database'}

            elif email == getemail[0]:   # If email is already used, notify the user
                return {'Error':'This email has already been used to register'}

        except:  # To notify if a lecturer hasn't conformed to an acceptable input format.
            return {'Error': "Unable to save lecturer details. Ensure that the inputs are correct"}
        
  

    elif str(user_type) == 'Mentor':
        try:
            # Gets addional input data for a mentor
            profession = request.form.get('profession')
            company = request.form.get('company')
            title = request.form.get('title')

            if getemail == None:   # If email is not already registered, input the data into the database
                controller.add_data(mentor_model.Mentor(
                    user_name, surname, first_name, email, password, user_type, profession, company, title))

                return {'success': 'succesfully updated in the database'}

            elif email == getemail[0]:    # If email is already used, notify the user
                return {'Error': 'This email has already been used to register'}
 
        except:   # To notify if a mentor hasn't conformed to an acceptable input format.
            return {'Error': 'Unable to get mentor details. Ensure that the inputs are correct'}


    else:        # To notify if a user hasn't conformed to an acceptable input format.
        return {'Error': 'Unable to get user details. Ensure that the inputs are correct'}


# Function to retrieve a user details based on id
@app.route('/users/<id>', methods=['GET'])
@login_required
def get_user(id):
    try:
        resp = controller.get_user(id)   #Gets the details of a user given the user id.
        return resp.to_dict()
    except:
        return {'Error': 'User not found'}



# Function to login
@app.route('/token/auth', methods=['POST'])
def login():
    # Gets email and password inputed by the user
    email = request.form.get('email')
    pass_word = request.form.get('password')
    
    
    try:
        password = controller.get_password(email) # Checks if email has been registered. If this line fails, it runs the except block
        if bcrypt.check_password_hash(password[0], pass_word):    # Checks if password is correct
            user_name = controller.get_user_name(email)
            user_id = controller.get_user_id(email)
            print(user_name)

            access_token = create_access_token(identity={'User name': user_name[0],'id': user_id[0]}, expires_delta=datetime.timedelta(days=1))
            refresh_token = create_refresh_token(identity = {'User name': user_name[0], 'id': user_id[0]}, expires_delta=datetime.timedelta(days=1))
        
            resp = jsonify({'login': True, 'user name': user_name[0]})
            set_access_cookies(resp, access_token)
            set_refresh_cookies(resp, refresh_token)

            return resp, 200
        else:
            return jsonify({'login': False}), 401
    except:
        return jsonify({'login': False}), 401


@app.route('/token/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
    # Create the new access token
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)

    # Set the access JWT and CSRF double submit protection cookies
    # in this response
    resp = jsonify({'refresh': True})
    set_access_cookies(resp, access_token)
    return resp, 200


@app.route('/token/remove', methods=['POST'])
def logout():
    resp = jsonify({'logout': True})
    unset_jwt_cookies(resp)
    return resp, 200



#This route is to return the image from the local storage.
@app.route('/uploads/<fc>/<yr>/<mn>/<dy>/<filename>', methods=['GET'])
def get_file(fc, yr, mn, dy, filename):
    return send_from_directory((os.path.join(app.config['UPLOAD_PATH'], fc, str(yr), str(mn), str(dy))), filename)

#checks file category


def get_file_category(uploaded_file):
    file_mime = uploaded_file.content_type
    # extracts the file format e.g application, media, etc
    file_category = re.findall('(.*)\/', file_mime)[0]
    return file_category


#This route is to upload a file
@app.route('/api/file', methods=['POST'])
@jwt_required
def uploadfeaturedimage_file():
    uploaded_file = request.files['file']

    ts = int(datetime.datetime.now().timestamp())
    date = datetime.datetime.fromtimestamp(ts)

    yr = date.year
    mn = date.month
    dy = date.day

    filename = secure_filename(uploaded_file.filename)

    if filename != '':
        name = filename.split('.')[0]
        file_ext = filename.split('.')[1].lower()
       
        file_category = get_file_category(uploaded_file)

        if file_ext not in app.config['UPLOAD_EXTENSIONS']: 
            abort(400, description="File format not supported")

        filename = name + str(ts) + '.' + file_ext

        try:
            if os.path.isdir('./uploads/' + file_category + '/' + str(yr) + '/' + str(mn) + '/' + str(dy)) is True:
                uploaded_file.save(os.path.join(
                    app.config['UPLOAD_PATH'], file_category, str(yr), str(mn), str(dy), filename))

            else:
                directory = './uploads/' + file_category + '/' + str(yr) + '/' + str(mn) + '/' + str(dy)
                print(directory)
                os.makedirs(directory)
                uploaded_file.save(os.path.join(
                    app.config['UPLOAD_PATH'], file_category, str(yr), str(mn), str(dy), filename))

            stat = 'upload successful'  # Default status if file upload is successful
            link = 'http://127.0.0.1:5000/uploads/' + file_category + '/' + str(yr) + '/' + str(mn) + '/' + str(dy) + '/' + str(filename)

        except:
            stat = 'upload not succesful'
            link = 'no link returned because upload was unsuccessful'

        return {'status': stat, 'link': link}


# Create a Course by a lecturer
@app.route('/course/create', methods=['POST'])
@login_required
def course_create():
    try:
        # Gets all input data from the user
        code = request.form.get('code')
        title = request.form.get('title')
        unit = request.form.get('unit')

    except:
        return {'Error': 'Unable to retrieve course details'}


    try:
        code = code.replace(" ", "")
        code = code.upper()

        # Check to see if course code is already in the DB
        controller.add_data(course_model.Course(code, title, unit))
        return {'Status': 'Course registered successfully'}

    except: # Exception as e:
       # raise
       return {'Status': 'registration not successfully'}

# Join a course created
@app.route ('/course/join', methods=['POST'])
@login_required
def course_join():
    try:
        # Get all inputs from the user
        course_id = request.form.get('course_id')
        user_id = request.form.get('user_id')
        
    except:
        return {'Error': 'Unable to retreive details'}

    # add data in the course_memmber table
    try:
        controller.add_data(course_mem.CourseMem(course_id, user_id))

        if controller.get_user_type(user_id) == UserType.Lecturer:
            controller.add_data(course_lecturer.CourseLecturer(course_id, user_id))
        
        return {'Status': 'Successfully joined the course'}
    
    except:
        return {'Error': 'Unable to join course'}


#Get list of active courses a student or lecturer is part of.
@app.route('/courses/<id>', methods=['GET'])
@login_required
def courses(id):
    try:
        courses = controller.get_courses(id)
        return courses

    except:
        return {'Error': 'failed to get courses'}
     

# Register a Course by a Student
@app.route('/course/register', methods=['POST'])
@login_required
def course_register():
    try:
    # Gets all input data from the student
        student_id = request.form.get('student_id')
        course_id = request.form.get('course_id')
        grade_id = request.form.get('grade_id')
        semester = request.form.get('semester')
        session_id = request.form.get('session_id')

    except:
        return {'Error': 'Unable to retreive details'}

    try:
        # add the data to the database
        controller.add_data(course_reg.CourseRegistration(student_id, course_id, grade_id, semester, session_id))
        return {'Status': 'Successfully registered the course'}

    except:
        return {'Error': 'Unable to register the course'}


#Get list of  courses a student has registered.
@app.route('/courses/registered/<id>', methods=['GET'])
@login_required
def registered_courses(id):
    courses = controller.get_registered_courses(id)
    return courses


# Route to update the event for a user. 
@app.route('/calendar/update', methods=['POST'])
@login_required
def update_calendar():   #where id is the user_id
    try:
        user_id = request.form.get('user_id')
        data = request.form.get('data')
        updated_at = request.form.get('updated_at')

    except:
        return {'Error': 'Unable to retreive data sent'}

    try: 
        ts = datetime.datetime.now()
        controller.update_event(user_id, data, ts)
        return{'success': 'event successfully inserted or updated'}
   
   
    except:
        return{'Error': 'error updating event'}


#This route is to like a news
@app.route('/api/news/like', methods=['POST'])
@jwt_required
def like_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    ts = datetime.datetime.now()
    ts = str(ts)
    try:
        # Gets all input data from the user
        # Get the news user wants to like
        news_id = request.form.get('news_id')

    except:
        return {'Error': 'Invalid news_id'}

    try:
        n_controller.like_news(news_controller.Like(user_id, news_id, ts))
        
    except:
        return {'Error': 'unable to like news'}
        
    return{'status': 'liked'}


#This route is to unlike a news
@app.route('/api/news/unlike', methods=['POST'])
@jwt_required
def unlike_news():
    user = get_jwt_identity()
    user_id = int(user['id'])

    try:
        # Gets all input data from the user
        # Get the news user wants to like
        news_id = request.form.get('news_id')

    except:
        return {'Error': 'Invalid news_id'}

    try:
        n_controller.unlike_news(user_id, news_id)

    except:
        return {'Error': 'unable to unlike news'}

    return{'status': 'unliked'}


#This route is to comment on a news
@app.route('/api/news/comment', methods=['POST'])
@jwt_required
def comment_news():
    user = get_jwt_identity()
    user_id = int(user['id'])
    ts = datetime.datetime.now()
    ts = str(ts)
    try:
        # Gets all input data from the user
        # Get the news user wants to like
        news_id = request.form.get('news_id')
        comment = request.form.get('comment')  # This is the user's comment

    except:
        return {'Error': 'Invalid news_id'}

    try:
        n_controller.comment_news(
            news_controller.Comment(user_id, news_id, comment, ts))

    except:
        return {'Error': 'unable to comment on news'}

    return{'status': 'commented'}


#This route if to retrieve likes
@app.route('/api/likes/<news_id>', methods=['GET'])
@jwt_required
def get_likes(news_id):

    likes = n_controller.get_likes(news_id)

    return likes


#This route if to retrieve comments
@app.route('/api/comments/<news_id>', methods=['GET'])
@jwt_required
def get_comments(news_id):

    comments = n_controller.get_comments(news_id)

    return comments


#This route is to get the info in a specific news based on the news_id
@app.route('/api/news/<int:news_id>', methods=['GET'])  
@jwt_required
def get_news(news_id): 
    user = get_jwt_identity()
    user_id = int(user['id'])  

    try:  
        news_object = n_controller.get_news(news_id)
        blogger_id = news_object.blogger_id
        blogger_name = b_controller.blogger_name(blogger_id)
        content = news_object.content
        title = news_object.title
        category_id = news_object.category_id
        category = n_controller.get_category(category_id)
        ts = news_object.timestamp
        featured_image_object = n_controller.get_featuredimage(news_id)
        featured_image = featured_image_object.image
        no_of_likes = n_controller.get_no_likes(news_id)
        no_of_comments = n_controller.get_no_comments(news_id)
        user_like = n_controller.user_like(user_id, news_id)

        status = 'success'

        news = {'blogger_name': blogger_name, 'title': title, 'content': content, 'category': category,'featured image': featured_image, 'no of likes':no_of_likes, 'no of comments': no_of_comments, 'user like ?': user_like, 'time': ts}

    except:
        news = 'Record not found'
        status = 'failed'

    return {'status': status, str(news_id):news}

#This route is to get news in a news page


# per means the number per page and page_num means the page number
@app.route('/api/newslist/<int:per>/<int:page_num>', methods=['GET'])
@jwt_required
def get_news_list(per, page_num):

    if page_num == 0:
        page_num = 1

    if per == 0:
        per = 20

    threads = db.session.query(news_model.News).paginate(per_page=per, page=page_num, error_out=False)
    no_of_items = len(threads.items)

    news = {}
    status = 'failed'

    if no_of_items > 0:
        for a in range(no_of_items):
            blogger_id = threads.items[a].blogger_id
            blogger_name = b_controller.blogger_name(blogger_id)
            news.update({threads.items[a].id: {'news_id': threads.items[a].id,
                                               'blogger_name': blogger_name, 'title': threads.items[a].title}})

        status = 'success'

    news_list = {'news_list': news, 'status': status}

    print("i'm here")

    return news_list



if __name__ == '__main__':
    app.run(debug=True)
