Exemplo n.º 1
0
def cache(g_username):
    """
    Caches GitHub data for a user in the local DB

    Args:
    g_username (str):  GitHub username

    Returns:
    git_data: cached GitHub data
    """

    conn = create_connection('test.db')
    git_data = getGitData(g_username)

    # cache profile details
    stars = git_data['stars']
    repos = git_data['public_repos']
    followers = git_data['followers']
    values = (g_username, repos, followers, stars)
    query = f"INSERT INTO GitHub (g_username, repos, followers, stars) \
            VALUES {values};"

    execute_query(conn, query)

    # store language list explicitly in text format
    language_lst = str(git_data['languages'])
    values = (g_username, language_lst)
    query = f"INSERT INTO Language (g_username, language) VALUES {values}"
    execute_query(conn, query)
    return git_data
Exemplo n.º 2
0
def checkContribution(username):
    """
    Checks commits highlighted by a user

    Args:
    username: GitHub username of the user

    Returns:
    response: Contributions of the user (empty if nothing added)
    """

    # fetch all highlighted commits
    conn = create_connection('test.db')
    query = f"SELECT * FROM Commits WHERE g_username='******';"
    result = execute_read_query(conn, query)

    # condition for creating 3 entries for first time
    condition = True
    for item in result:
        condition = condition and (item[2] != "None")
        break

    response = {}

    # if commits exist, send it in list
    if len(result) > 0 and condition:
        lst = [item[1:] for item in result]
        response['contributions'] = lst

    # if commits doesn't exist, send empty list
    elif len(result) > 0:
        response['contributions'] = []

    # first time user, make 3 entries in the table
    # return empty list for this case
    else:
        for i in range(1, 4):
            values = (username, i, "None", "None", "None", "None")
            query = f"INSERT INTO Commits \
                    (g_username, rank, repo, message, sha, description) \
                    VALUES {values};"

            execute_query(conn, query)
        response['contributions'] = []
    return response
Exemplo n.º 3
0
def getIssues(username):
    """
    Fetches highlighted for given user

    Args:
    username (str): GitHub username
    
    Returns:
    response: highlighted issues
    """

    # fetch all highlighted issue for given username
    conn = create_connection('test.db')
    query = f"SELECT * FROM Issue WHERE g_username='******';"
    result = execute_read_query(conn, query)

    # condition for first time users
    condition = True
    for item in result:
        condition = condition and (item[2] != "None")
        break

    response = {}

    # check for appropriate conditions and return issues
    if len(result) > 0 and condition:
        response['issues'] = result
    elif len(result) > 0:
        response['issues'] = []
    else:
        for i in range(1, 4):
            values = (username, i, "None", "None", "None", "None", "None")
            query = f"INSERT INTO Issue \
                    (g_username, rank, repo_fullname, issue_number,\
                    description, title, body) \
                    VALUES {values};"

            execute_query(conn, query)
        response['issues'] = []
    return response
Exemplo n.º 4
0
def getPr(username):
    """
    Fetches highlighted pull requests for the user

    Args:
    username (str): GitHub username

    Returns:
    response: List of highlighted Pull requests
    """

    # fetch highlighted PRs from the DB
    conn = create_connection('test.db')
    query = f"SELECT * FROM PR WHERE g_username='******';"
    result = execute_read_query(conn, query)
    response = {}

    # condition for the first time user
    condition = True
    for item in result:
        condition = condition and (item[2] != "None")
        break

    # check appropriate condition and return list of PRs
    if len(result) > 0 and condition:
        response['pr'] = result
    elif len(result) > 0:
        response['pr'] = []
    else:
        for i in range(1, 4):
            values = (username, i, "None", "None", "None", "None", "None")
            query = f"INSERT INTO PR \
                    (g_username, rank, repo_fullname,\
                    pull_number, description, title, body) \
                    VALUES {values};"

            execute_query(conn, query)
        response['pr'] = []
    return response
Exemplo n.º 5
0
def registerUser():
    """
    Registers new user on the website,
    POST request is used for getting user's details

    Returns:
    res: response whether signup successful or failed
    """

    conn = create_connection('test.db')
    rqst_data = request.data
    user_data = json.loads(rqst_data.decode('utf-8'))

    # check whether user exists before
    username = str(user_data['username'])
    query = f"SELECT username FROM User WHERE username='******';"
    result = execute_read_query(conn, query)

    res = None

    # If User already exists
    if (len(result) > 0):
        res = "User already exists"

    # If user doesn't exist signup
    else:
        # save details of user in DB
        values = (user_data['username'], user_data['password'], 0)
        query = f"INSERT INTO User (username, password, hasLinked) \
                VALUES {values};"

        execute_query(conn, query)
        res = "User added successfully"

    res = json.dumps(res)
    return res
Exemplo n.º 6
0
def getData():
    """
    Updates cache data after notification from webhooks
    """

    # fetch header to identify event type
    conn = create_connection('test.db')
    rqst_data = request.get_json(force=True)
    headers = request.headers
    event_type = headers['X-GitHub-Event']

    # if event type is star, update stars
    if event_type == 'star':
        g_username = rqst_data['repository']['owner']['login']

        # if starred, increase value else decrease
        if rqst_data['starred_at'] is not None:
            query = f"UPDATE GitHub SET stars = stars + 1 \
                    WHERE g_username='******';"

            execute_query(conn, query)
        else:
            query = f"UPDATE GitHub SET stars = stars - 1 \
                    WHERE g_username='******';"

            execute_query(conn, query)

    # if event type is repository, update repo data
    elif event_type == 'repository':
        g_username = rqst_data['repository']['owner']['login']
        action = action = rqst_data['action']
        if action == 'created':
            query = f"UPDATE GitHub SET repos = repos + 1 \
                    WHERE g_username='******';"

            execute_query(conn, query)
        else:
            query = f"UPDATE GitHub SET repos = repos - 1 \
                    WHERE g_username='******';"

            execute_query(conn, query)

    # updating language cache on each push
    elif event_type == 'push':
        g_username = rqst_data['repository']['owner']['login']
        language = rqst_data['language']
        query = f"SELECT language FROM Language \
                WHERE g_username = '******';"

        usr_lang = execute_read_query(conn, query)
        lang_lst = usr_lang[0][0][1:-1]
        lang_lst = (lang_lst).split(', ')
        lang_lst = [i[1:-1] for i in lang_lst]

        if language not in lang_lst:
            lang_lst.append(language)
            lang_lst = str(lang_lst)
            query = f"UPDATE Language SET language = {lang_lst} \
                    WHERE g_username='******';"

            execute_query(conn, query)

    return "received"
Exemplo n.º 7
0
def link():
    """
    Links GitHub account using OAuth 2.0

    Returns:
    res: Link text with Javascript to close browser window
         (if linking successful)
         fail message
         (if linking fails)
    """

    # Get authorization code and state from request URL
    code = request.args.get('code')
    state = request.args.get('state')
    client_id = 'Iv1.6a23a85edae7274a'
    url = 'https://github.com/login/oauth/access_token'

    # prepare data for access token POST request
    # client secret should be set up as environment variable
    # using client secret directly for ease
    data = {
        'client_id': client_id,
        'code': code,
        'state': state,
        'client_secret': '26b6d03d65baf64c4ce8b8de5c95fbab3f749b8b'
    }

    # include headers as written in API documentation
    headers = {'Accept': 'application/json'}

    # make POST request and get token
    res = requests.post(url=url, data=data, headers=headers)
    token = (res.json())['access_token']

    # If valid token is returned, Update it corresponding to user in DB
    if token is not None:
        conn = create_connection('test.db')
        query = f"UPDATE User SET hasLinked=1 WHERE username='******';"
        execute_query(conn, query)
        headers = {'Authorization': 'token ' + token}
        url = 'https://api.github.com/user'
        res = requests.get(url=url, headers=headers)
        g_username = (res.json())['login']

        # Save GitHub username corresponding to LinkedIn username
        values = (state, g_username)
        query = f"INSERT INTO Link (l_username, g_username) VALUES {values};"
        execute_query(conn, query)

        # Save user's access token in DB
        values = (g_username, token)
        query = f"INSERT INTO Token (g_username, token) VALUES {values};"
        execute_query(conn, query)

        # cache data while Linking to support filtering
        cache(g_username)

        return '<a href="#" onclick="window.close();">ID Linked, Click to close, Please Login again</a>'

    # return response message if linking fails
    return "Linking failed"