def delete(request, body, *args, **kwargs):
    """
    Delete Account
    Method: Post
    Request: accountId
    """
    account_id = body.get('id')

    try:
        account = Account.objects.get(account_id=account_id,
                                      status=Status.valid.key)
        user = User.objects.get(account_id=account_id, status=Status.valid.key)
    except ObjectDoesNotExist:
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    timestamp = mills_timestamp()

    try:
        with transaction.atomic():
            account.status = Status.invalid.key
            account.update_date = timestamp
            account.save()
            user.status = Status.invalid.key
            user.update_date = timestamp
            user.save()
    except Exception as e:
        print(e)
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    resp = init_http_response_my_enum(RespCode.success)
    return make_json_response(resp=resp)
def get_supervisor(request, supervisor_id, *args, **kwargs):
    """

    :param request:
    :param supervisor_id:
    :param args:
    :param kwargs:
    :return:
    """

    try:
        supervisor = User.objects.get(
            user_id=supervisor_id,
            role__in=[Roles.supervisor.key, Roles.coordinator.key],
            status=Status.valid.key)
    except ObjectDoesNotExist as e:
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    data = dict(
        id=supervisor.user_id,
        name=supervisor.get_name(),
        email=supervisor.email,
    )
    resp = init_http_response_my_enum(RespCode.success, data)
    return make_json_response(resp=resp)
def atl_login(request, body, *args, **kwargs):
    """
    Update atlassian login info
    Method: Post
    Request: first_name,last_name,old_password,password
    """
    try:
        user = request.session.get('user', {})
        # if user['atl_login']:
        #     resp = init_http_response_my_enum(RespCode.success)
        #     return make_json_response(resp=resp)

        user['atl_username'] = body['atl_username']
        user['atl_password'] = body['atl_password']
        # user['atl_login'] = True
        request.session['user'] = user

        confluence = Confluence(
            url='https://confluence.cis.unimelb.edu.au:8443/',
            username=request.session['user']['atl_username'],
            password=request.session['user']['atl_password'])

        conf_resp = confluence.get_all_groups()

        # print("~~")
        # print(request.session['user']['atl_username'])
        resp = init_http_response_my_enum(RespCode.success)
        return make_json_response(resp=resp)
    except requests.exceptions.HTTPError as e:
        resp = init_http_response_my_enum(RespCode.server_error)
        return make_json_response(resp=resp)
示例#4
0
def get_git_individual_commits(request, space_key):
    data = []
    if StudentCommitCounts.objects.filter(space_key=space_key).exists():
        for item in StudentCommitCounts.objects.filter(space_key=space_key):
            temp = {
                "student": str(item.student_name),
                "commit_count": int(item.commit_counts)
            }
            data.append(temp)
    else:
        if ProjectCoordinatorRelation.objects.filter(space_key=space_key).exists():
            update_individual_commits()
            temp = {}
            for item in StudentCommitCounts.objects.filter(space_key=space_key):
                temp = {
                    "student": str(item.student_name),
                    "commit_count": int(item.commit_counts)
                }
                data.append(temp)
        else:
            resp = init_http_response_my_enum(RespCode.invalid_parameter)
            return make_json_response(resp=resp)

    resp = init_http_response_my_enum(RespCode.success, data)
    return make_json_response(resp=resp)
def get_account(request):
    """
    Get Account
    Method: Get
    Request: accountId
    """
    user = request.session.get('user')
    user_id = user['id']

    try:
        user = User.objects.get(user_id=user_id, status=Status.valid.key)
    except ObjectDoesNotExist:
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    account_id = int(request.GET.get('id', user.account_id))
    if not account_id:
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    try:
        account = Account.objects.get(account_id=account_id,
                                      status=Status.valid.key)
    except ObjectDoesNotExist:
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    data = dict(
        username=account.username,
        email=account.email,
        first_name=user.first_name,
        last_name=user.last_name,
    )
    resp = init_http_response_my_enum(RespCode.success, data)
    return make_json_response(resp=resp)
def delete_subject(request, *args, **kwargs):
    """

    :param request:
    :param args:
    :param kwargs:
    :return:
    """
    subject_id = kwargs.get('id')

    if not subject_id:
        print("f**k")
        resp = init_http_response(RespCode.invalid_parameter.value.key,
                                  RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponse, resp)

    try:
        subject = Subject.objects.get(subject_id=subject_id)
    except ObjectDoesNotExist as e:
        print("f**k two")
        resp = init_http_response(RespCode.invalid_parameter.value.key,
                                  RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponse, resp)

    subject.status = Status.invalid.value.key
    subject.save()

    resp = init_http_response(RespCode.success.value.key,
                              RespCode.success.value.msg)
    return make_json_response(HttpResponse, resp)
示例#7
0
def invite_accept(request, body, *args, **kwargs):
    """
    Accept Invitation and Create Account (WIP)
    Method: Post
    Request: key, username, password
    """
    invite_accept_dto = InviteAcceptDTO()
    body_extract(body, invite_accept_dto)

    if not invite_accept_dto.not_empty():
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    if Account.objects.filter(username=invite_accept_dto.username).exists():
        resp = init_http_response_my_enum(RespCode.account_existed)
        return make_json_response(resp=resp)

    try:
        invitation = Invitation.objects.get(key=invite_accept_dto.key,
                                            status=InvitationStatus.sent.key)
    except Exception as e:
        print(e)
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    timestamp = mills_timestamp()
    data = dict()
    try:
        with transaction.atomic():
            invite_accept_dto.encrypt()
            account = Account(username=invite_accept_dto.username,
                              password=invite_accept_dto.md5,
                              email=invitation.email,
                              status=Status.valid.key,
                              create_date=timestamp,
                              update_date=timestamp)
            account.save()

            data['account_id'] = account.account_id
            user = User(account_id=account.account_id,
                        username=invite_accept_dto.username,
                        first_name=invite_accept_dto.first_name,
                        last_name=invite_accept_dto.last_name,
                        role=Roles.supervisor.key,
                        status=Status.valid.key,
                        create_date=timestamp,
                        update_date=timestamp,
                        email=invitation.email)
            user.save()

            invitation.status = InvitationStatus.accepted.key
            invitation.accept_reject_date = timestamp
            invitation.save()
    except Exception as e:
        print(e)
        resp = init_http_response_my_enum(RespCode.server_error)
        return make_json_response(resp=resp)

    resp = init_http_response_my_enum(RespCode.success, data)
    return make_json_response(resp=resp)
示例#8
0
def delete_subject(request, *args, **kwargs):
    """

    :param request:
    :param args:
    :param kwargs:
    :return:
    """
    subject_id = None
    for arg in args:
        if isinstance(arg, dict):
            subject_id = arg.get('id', None)

    if not subject_id:
        resp = init_http_response(RespCode.invalid_parameter.value.key, RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponseBadRequest, resp)

    try:
        subject = Subject.objects.get(subject_id=subject_id)
    except ObjectDoesNotExist as e:
        resp = init_http_response(RespCode.invalid_parameter.value.key, RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponseBadRequest, resp)

    subject.status = Status.invalid
    subject.save()

    resp = init_http_response(RespCode.success.value.key, RespCode.success.value.msg)
    return make_json_response(HttpResponse, resp)
示例#9
0
def update_subject(request, *args, **kwargs):
    """

    :param request:
    :param args:
    :param kwargs:
    :return:
    """
    subject_id = None
    for arg in args:
        if isinstance(arg, dict):
            subject_id = arg.get('id', None)

    if not subject_id:
        resp = init_http_response(RespCode.invalid_parameter.value.key, RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponseBadRequest, resp)

    subject_code = request.POST.get('code', '')
    subject_name = request.POST.get('name', '')
    coordinator_id = int(request.POST.get('coordinator_id', 0))

    try:
        subject = Subject.objects.get(subject_id=subject_id)
    except ObjectDoesNotExist as e:
        resp = init_http_response(RespCode.invalid_parameter.value.key, RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponseBadRequest, resp)

    subject.subject_code = subject_code
    subject.subject_name = subject_name
    subject.coordinator_id = coordinator_id
    subject.save()

    resp = init_http_response(RespCode.success.value.key, RespCode.success.value.msg)
    return make_json_response(HttpResponse, resp)
示例#10
0
def team_configure(request, body, *args, **kwargs):
    team_id = None
    if isinstance(kwargs, dict):
        team_id = kwargs.get('team_id', None)
    if team_id:
        try:
            team_configuration = TeamConfiguration.objects.get(team_id=team_id)
        except ObjectDoesNotExist as e:
            logger.info(e)
            resp = init_http_response_my_enum(RespCode.invalid_parameter)
            return make_json_response(resp=resp)
    else:
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)
    if request.method == 'POST':
        team_configuration_dto = TeamConfigurationDTO()
        body_extract(body, team_configuration_dto)
        team_configuration.slack_workspace = team_configuration_dto.slack_workspace
        team_configuration.confluence_workspace = team_configuration_dto.confluence_workspace
        team_configuration.jira_workspace = team_configuration_dto.jira_workspace
        team_configuration.git_repository = team_configuration_dto.git_repository
        team_configuration.save()
        resp = init_http_response_my_enum(RespCode.success)
        return make_json_response(HttpResponse, resp)
    elif request.method == 'GET':
        data = dict()
        data['slack_workspace'] = team_configuration.slack_workspace
        data['confluence_workspace'] = team_configuration.confluence_workspace
        data['jira_workspace'] = team_configuration.jira_workspace
        data['git_repository'] = team_configuration.git_repository
        resp = init_http_response_my_enum(RespCode.success, data)
        return make_json_response(HttpResponse, resp)
    return HttpResponseNotAllowed(['POST', 'GET'])
示例#11
0
def get_subject(request, subject_id: int):
    """
    Get certain subject

    :param request:
    :param subject_id:
    :return:
    """

    try:
        subject = Subject.objects.get(subject_id=subject_id)
        coordinator = User.objects.get(user_id=subject.coordinator_id) if subject.coordinator_id else None
    except ObjectDoesNotExist as e:
        resp = init_http_response(RespCode.invalid_parameter.value.key, RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponseBadRequest, resp)

    data = dict(
        id=subject.subject_id,
        code=subject.subject_code,
        name=subject.name,
        coordinator=dict(
            id=coordinator.user_id,
            name=coordinator.get_name(),
            email=coordinator.email,
            join_date=coordinator.create_date,
            status=coordinator.status,
        ),
        supervisors=[],
        teams=[],
        status=subject.status,
    )

    resp = init_http_response(RespCode.success.value.key, RespCode.success.value.msg)
    resp['data'] = data
    return make_json_response(HttpResponse, resp)
示例#12
0
def add_subject(request):
    """

    :param request:
    :return:
    """
    subject_code = request.POST.get('code', '')
    subject_name = request.POST.get('name', '')
    coordinator_id = int(request.POST.get('coordinator_id', 0))

    # if the parameter is not sufficient
    if not subject_code or not subject_name or coordinator_id == 0:
        resp = init_http_response(RespCode.invalid_parameter.value.key, RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponseBadRequest, resp)

    # if the subject code existed
    if Subject.objects.filter(subject_code=subject_code).exists():
        resp = init_http_response(RespCode.subject_existed.value.key, RespCode.subject_existed.value.msg)
        return make_json_response(HttpResponseBadRequest, resp)

    # if user is not coordinator
    try:
        user = User.objects.get(user_id=coordinator_id, role=Roles.coordinator.value.key, status=Status.valid.value.key)
    except ObjectDoesNotExist:
        resp = init_http_response(RespCode.invalid_op.value.key, RespCode.invalid_op.value.msg)
        return make_json_response(HttpResponseBadRequest, resp)

    subject = Subject(subject_code=subject_code, name=subject_name, coordinator_id=coordinator_id,
                      create_date=int(now().timestamp()), status=Status.valid.value.key)
    subject.save()

    resp = init_http_response(RespCode.success.value.key, RespCode.success.value.msg)
    return make_json_response(HttpResponse, resp)
示例#13
0
def get_git_commits(request, body, *args, **kwargs):

    git_dto = GitDTO()
    body_extract(body, git_dto)

    if not git_dto.valid_url:
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)
    git_dto.url = git_dto.url.lstrip('$')

    commits = get_commits(git_dto.url, git_dto.author, git_dto.branch,
                          git_dto.second_after, git_dto.second_before)
    total = len(commits)
    author = set()
    file_changed = 0
    insertion = 0
    deletion = 0
    for commit in commits:
        file_changed += commit['file_changed']
        insertion += commit['insertion']
        deletion += commit['deletion']
        author.add(commit['author'])

    data = dict(
        total=total,
        author=list(author),
        file_changed=file_changed,
        insertion=insertion,
        deletion=deletion,
        commits=commits,
    )
    resp = init_http_response_my_enum(RespCode.success, data)
    return make_json_response(resp=resp)
def update_account(request, body, *args, **kwargs):
    """
    Update account
    Method: Post
    Request: first_name,last_name,old_password,password
    """
    user = request.session.get('user')
    user_id = user['id']

    update_account_dto = UpdateAccountDTO()
    body_extract(body, update_account_dto)
    update_account_dto.encrypt()

    try:
        user = User.objects.get(user_id=user_id, status=Status.valid.key)
        account = Account.objects.get(account_id=user.account_id,
                                      status=Status.valid.key)
    except ObjectDoesNotExist:
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    if (update_account_dto.old_password and update_account_dto.old_md5 != account.password) \
            or not update_account_dto.validate():
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    timestamp = mills_timestamp()
    if update_account_dto.first_name:
        user.first_name = update_account_dto.first_name
        user.update_date = timestamp
    if update_account_dto.role:
        user.role = update_account_dto.role
        user.update_date = timestamp
    if update_account_dto.last_name:
        user.last_name = update_account_dto.last_name
        user.update_date = timestamp
    if update_account_dto.atl_username:
        user.atl_username = update_account_dto.atl_username
        user.update_date = timestamp
    if update_account_dto.atl_password:
        update_account_dto.encrypt_aes()
        user.atl_password = update_account_dto.aes
        user.update_date = timestamp
    if update_account_dto.old_password and update_account_dto.password \
            and update_account_dto.old_md5 == account.password:
        account.password = update_account_dto.md5
        account.update_date = timestamp

    try:
        with transaction.atomic():
            user.save()
            account.save()
    except Exception as e:
        print(e)
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    resp = init_http_response_my_enum(RespCode.success)
    return make_json_response(resp=resp)
示例#15
0
def import_team(request, body, *args, **kwargs):
    """
    Import team from confluence with supervisor_id
    :param request:
    :param body:
    :param args:
    :param kwargs:
    :return:
    """

    add_team_dto = AddTeamDTO()
    body_extract(body, add_team_dto)

    # Check parameters
    if not add_team_dto.not_empty():
        resp = init_http_response(RespCode.invalid_parameter.value.key,
                                  RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponse, resp)

    team_members = get_members(request, add_team_dto.team)
    if not team_members:
        logger.info('Empty team member: %s', add_team_dto.team)
        resp = init_http_response(RespCode.invalid_parameter.value.key,
                                  RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponse, resp)

    # If the team existed
    if Team.objects.filter(name=add_team_dto.team).exists():
        resp = init_http_response(RespCode.team_existed.value.key,
                                  RespCode.team_existed.value.msg)
        return make_json_response(HttpResponse, resp)

    try:
        with transaction.atomic():
            team = Team(name=add_team_dto.team,
                        subject_code=add_team_dto.subject,
                        year=add_team_dto.year,
                        project_name=add_team_dto.project,
                        create_date=mills_timestamp())
            team.save()

            for member in team_members:
                try:
                    student = Student.objects.get(email=member['email'])
                except ObjectDoesNotExist as e:
                    student = Student(fullname=member['name'],
                                      email=member['email'])
                    student.save()
                import_team_member(team.team_id, student.student_id)

    except Exception as e:
        logger.error(e)
        resp = init_http_response(RespCode.server_error.value.key,
                                  RespCode.server_error.value.msg)
        return make_json_response(HttpResponse, resp)

    resp = init_http_response(RespCode.success.value.key,
                              RespCode.success.value.msg)
    return make_json_response(HttpResponse, resp)
示例#16
0
def get_team_members(request, *args, **kwargs):
    """
        Get certain team members
        :param request:
        :param team_id:
        :return:
        """

    team_id = int(kwargs['id'])
    members = []
    data = dict()
    try:
        team = Team.objects.get(team_id=team_id)
        team_members = TeamMember.objects.filter(team_id=team_id)
    except ObjectDoesNotExist as e:
        logger.info(e)
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    try:
        supervisor = User.objects.get(account_id=team.supervisor_id)
        if supervisor:
            data['supervisor'] = supervisor_data = {
                'supervisor_id': supervisor.account_id,
                'supervisor_first_name': supervisor.first_name,
                'supervisor_last_name': supervisor.last_name,
                'email': supervisor.email
            }
    except ObjectDoesNotExist:
        data['supervisor'] = "supervisor not exist"

    try:
        secondary_supervisor = User.objects.get(
            account_id=team.secondary_supervisor_id)
        if secondary_supervisor:
            data['secondary_supervisor'] = secondary_supervisor_data = {
                'secondary_supervisor_id': secondary_supervisor.account_id,
                'secondary_supervisor_first_name':
                secondary_supervisor.first_name,
                'secondary_supervisor_last_name':
                secondary_supervisor.last_name,
                'email': secondary_supervisor.email,
            }
    except ObjectDoesNotExist:
        data['secondary_supervisor'] = "secondary_supervisor not exist"

    for member in team_members:
        student = Student.objects.get(student_id=member.student_id)
        member_data = {
            'student_id': student.student_id,
            'fullname': student.fullname,
            'email': student.email
        }
        members.append(member_data)

    data['team_members'] = members
    resp = init_http_response_my_enum(RespCode.success, data)
    return make_json_response(HttpResponse, resp)
示例#17
0
def get_invitation(request, subject_id: int):
    """
    TODO: update expired status

    :param request:
    :param subject_id:
    :return:
    """

    finished = request.GET.get('finished', None)
    offset = int(request.POST.get('offset', 0))
    has_more = 0

    kwargs = dict(subject_id=subject_id, )
    if finished is not None:
        if int(finished) == 0:
            kwargs['status__lt'] = InvitationStatus.accepted.value.key
        else:
            kwargs['status__gte'] = InvitationStatus.accepted.value.key

    invitations = Invitation.objects.filter(
        **kwargs).order_by('invitation_id')[offset:offset + SINGLE_PAGE_LIMIT +
                                            1]
    if len(invitations) > SINGLE_PAGE_LIMIT:
        invitations = invitations[:SINGLE_PAGE_LIMIT]
        has_more = 1
    offset += len(invitations)

    if len(invitations) == 0:
        data = dict(
            invitations=[],
            has_more=has_more,
            offset=offset,
        )
        resp = init_http_response(RespCode.success.value.key,
                                  RespCode.success.value.msg)
        resp['data'] = data
        return make_json_response(HttpResponse, resp)

    data = dict(invitation=[
        dict(id=invitation.invitation_id,
             name=invitation.get_name(),
             email=invitation.email,
             expired=invitation.expired,
             status=invitation.status) for invitation in invitations
    ],
                offset=offset,
                has_more=has_more)

    resp = init_http_response(RespCode.success.value.key,
                              RespCode.success.value.msg)
    resp['data'] = data
    return make_json_response(HttpResponse, resp)
def add_account(request, body, *args, **kwargs):
    """
    Create account and user
    Method: Post
    Request: username, email, password, role, first_name, last_name
    """

    add_account_dto = AddAccountDTO()
    body_extract(body, add_account_dto)

    if not add_account_dto.not_empty() or not add_account_dto.validate():
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    if Account.objects.filter(
            Q(username=add_account_dto.username)
            | Q(email=add_account_dto.email)).exists():
        resp = init_http_response_my_enum(RespCode.account_existed)
        return make_json_response(resp=resp)

    add_account_dto.encrypt()
    timestamp = mills_timestamp()

    try:
        with transaction.atomic():
            account = Account(username=add_account_dto.username,
                              email=add_account_dto.email,
                              password=add_account_dto.md5,
                              status=Status.valid.key,
                              create_date=timestamp,
                              update_date=timestamp)
            account.save()

            user = User(account_id=account.account_id,
                        username=add_account_dto.username,
                        first_name=add_account_dto.first_name,
                        last_name=add_account_dto.last_name,
                        role=add_account_dto.role,
                        status=Status.valid.key,
                        create_date=timestamp,
                        update_date=timestamp,
                        email=add_account_dto.email)
            user.save()
    except Exception as e:
        print(e)
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    resp = init_http_response_my_enum(RespCode.success)
    return make_json_response(resp=resp)
def get_all_page_contributions(request, space_key):
    """
    Get all the page contributions made by each team member
    Method: GET
    Request: space_key
    Return: a dictionary of {"username": [list of contributed page_ids]}
    """
    user = request.session.get('user')
    username = user['atl_username']
    password = user['atl_password']
    conf = confluence.log_into_confluence(username, password)

    # Read confluence config yaml file
    config_dict = read_confluence_config()
    if config_dict == -1:
        resp = init_http_response(
            RespCode.config_not_found.value.key, RespCode.config_not_found.value.msg)
        return make_json_response(HttpResponse, resp)

    # Build query url
    host = config_dict["common"]["host"]
    port = config_dict["common"]["port"]
    base_path = config_dict["common"]["path"]
    api_path = config_dict["api"]["get-all-page-contributors"]["path"]
    query_expand = config_dict["api"]["get-all-page-contributors"]["query"]["expand"]
    query_limit = config_dict["api"]["get-all-page-contributors"]["query"]["limit"]

    base_url = f"{host}:{port}{base_path}{api_path}?expand={query_expand}&limit={query_limit}"

    # Get list of contributors to a page
    url = base_url.replace("{space_key}", space_key, 1)
    conf_resp = requests.get(
        url, auth=HTTPBasicAuth(username, password)).json()

    # Create a dictionary of team members and the number of contributions made to a confluence space
    member_contributions = {}

    # Loop through every page and store in a dictionary {"page": set of members}
    for page in conf_resp["results"]:
        page_contributors = page["history"]["contributors"]["publishers"]["users"]
        for user in page_contributors:
            if not user["username"] in member_contributions:
                member_contributions[user["username"]] = 0
            member_contributions[user["username"]] += 1

    resp = init_http_response(
        RespCode.success.value.key, RespCode.success.value.msg)
    resp['data'] = member_contributions
    return make_json_response(HttpResponse, resp)
def login(request, body, *args, **kwargs):
    """
    Login
    Method: Post
    Request: username(can input username or email to this), password
    """

    login_dto = LoginDTO()
    body_extract(body, login_dto)

    if not login_dto.validate():
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    login_dto.encrypt()
    account = None
    try:
        if login_dto.username:
            account = Account.objects.get(username=login_dto.username,
                                          password=login_dto.md5,
                                          status=Status.valid.key)
        elif login_dto.email:
            account = Account.objects.get(email=login_dto.email,
                                          password=login_dto.md5,
                                          status=Status.valid.key)
    except ObjectDoesNotExist:
        resp = init_http_response_my_enum(RespCode.login_fail)
        return make_json_response(resp=resp)

    user = User.objects.get(account_id=account.account_id)

    session_data = dict(
        id=user.user_id,
        name=user.get_name(),
        role=user.role,
        is_login=True,
        atl_login=False,
        atl_username=None,
        atl_password=None,
    )
    request.session['user'] = session_data

    data = dict(user_id=user.user_id,
                account_id=account.account_id,
                role=user.role,
                name=user.get_name())
    resp = init_http_response_my_enum(RespCode.success, data)
    return make_json_response(resp=resp)
def multi_get_supervisor(request, *args, **kwargs):
    """

    :param request:
    :param args:
    :param kwargs:
    :return:
    """

    offset = int(request.GET.get('offset', 0))
    has_more = 0

    supervisors = User.objects.filter(role__in=[Roles.supervisor.key, Roles.coordinator.key], status=Status.valid.key)\
        .only('user_id')[offset: offset + SINGLE_PAGE_LIMIT + 1]
    if len(supervisors) > SINGLE_PAGE_LIMIT:
        supervisors = supervisors[:SINGLE_PAGE_LIMIT]
        has_more = 1
    offset += len(supervisors)

    data = dict(
        supervisors=[supervisor.user_id for supervisor in supervisors],
        offset=offset,
        has_more=has_more,
    )
    resp = init_http_response_my_enum(RespCode.success, data)
    return make_json_response(resp=resp)
def logout(request, *args, **kwargs):
    """

    :param request:
    :param args:
    :param kwargs:
    :return:
    """
    user = request.session.get('user')
    if user is None:
        resp = init_http_response_my_enum(RespCode.not_logged)
        return make_json_response(resp=resp)

    request.session.flush()
    resp = init_http_response_my_enum(RespCode.success)
    return make_json_response(resp=resp)
def get_metrics(relation):
    data = {"url": relation.git_url}
    # create GitDTO object
    git_dto = GitDTO()
    # extract body information and store them in GitDTO.
    body_extract(data, git_dto)
    if not git_dto.valid_url:
        resp = init_http_response_my_enum(RespCode.no_repository)
        return make_json_response(resp=resp)
    git_dto.url = git_dto.url.lstrip('$')

    metrics = get_und_metrics(git_dto.url, relation.space_key)
    if metrics is None:
        resp = init_http_response_my_enum(RespCode.invalid_authentication)
        return make_json_response(resp=resp)
    elif metrics == -1:
        resp = init_http_response_my_enum(RespCode.user_not_found)
        return make_json_response(resp=resp)
    elif metrics == -2:
        resp = init_http_response_my_enum(RespCode.git_config_not_found)
        return make_json_response(resp=resp)

    if GitMetrics.objects.filter(space_key=relation.space_key).exists():
        GitMetrics.objects.filter(space_key=relation.space_key).update(
            file_count=metrics['CountDeclFile'],
            class_count=metrics['CountDeclClass'],
            function_count=metrics['CountDeclFunction'],
            code_lines_count=metrics['CountLineCode'],
            declarative_lines_count=metrics['CountLineCodeDecl'],
            executable_lines_count=metrics['CountLineCodeExe'],
            comment_lines_count=metrics['CountLineComment'],
            comment_to_code_ratio=metrics['RatioCommentToCode'],
        )
    else:
        metrics_dto = GitMetrics(
            space_key=relation.space_key,
            file_count=metrics['CountDeclFile'],
            class_count=metrics['CountDeclClass'],
            function_count=metrics['CountDeclFunction'],
            code_lines_count=metrics['CountLineCode'],
            declarative_lines_count=metrics['CountLineCodeDecl'],
            executable_lines_count=metrics['CountLineCodeExe'],
            comment_lines_count=metrics['CountLineComment'],
            comment_to_code_ratio=metrics['RatioCommentToCode'],
        )
        metrics_dto.save()
示例#24
0
def team_member_configure(request, *args, **kwargs):
    team_id = None
    team_member_id = None
    if isinstance(kwargs, dict):
        team_id = kwargs.get('team_id', None)
        team_member_id = kwargs.get('team_member_id', None)
        print(team_id, team_member_id)
    if team_id and team_member_id:
        try:
            team_member = TeamMember.objects.get(team_id=team_id,
                                                 member_id=team_member_id)
            print(team_member)
        except ObjectDoesNotExist as e:
            logger.info(e)
            resp = init_http_response_my_enum(RespCode.invalid_parameter)
            return make_json_response(resp=resp)
        try:
            student = Student.objects.get(student_id=team_member.student_id)
            print(student)
        except ObjectDoesNotExist as e:
            logger.info(e)
            resp = init_http_response_my_enum(RespCode.invalid_parameter)
            return make_json_response(resp=resp)
    else:
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)
    if request.method == 'POST':
        body = dict(ujson.loads(request.body))
        team_member_dto = TeamMemberDTO()
        body_extract(body, team_member_dto)
        student.git_name = team_member_dto.git_name
        student.slack_email = team_member_dto.slack_email
        student.atl_account = team_member_dto.atl_account
        student.save()
        resp = init_http_response_my_enum(RespCode.success)
        return make_json_response(HttpResponse, resp)
    elif request.method == 'GET':
        data = dict()
        data['git_name'] = student.git_name
        data['slack_email'] = student.slack_email
        data['atl_account'] = student.atl_account
        resp = init_http_response_my_enum(RespCode.success, data)
        return make_json_response(HttpResponse, resp)
    return HttpResponseNotAllowed(['POST', 'GET'])
def update_individual_commits():
    for relation in ProjectCoordinatorRelation.objects.all():
        data = {"url": relation.git_url}
        # create GitDTO object
        git_dto = GitDTO()
        # extract body information and store them in GitDTO.
        body_extract(data, git_dto)

        if not git_dto.valid_url:
            resp = init_http_response_my_enum(RespCode.invalid_parameter)
            return make_json_response(resp=resp)
        git_dto.url = git_dto.url.lstrip('$')

        # request commits from  github api
        commits = get_commits(git_dto.url, relation.space_key, git_dto.author,
                              git_dto.branch, git_dto.second_after,
                              git_dto.second_before)
        # commits = get_commits(git_dto.url, git_dto.author, git_dto.branch, git_dto.second_after, git_dto.second_before)
        if commits is None:
            resp = init_http_response_my_enum(RespCode.invalid_authentication)
            return make_json_response(resp=resp)
        if commits == -1:
            resp = init_http_response_my_enum(RespCode.user_not_found)
            return make_json_response(resp=resp)
        if commits == -2:
            resp = init_http_response_my_enum(RespCode.git_config_not_found)
            return make_json_response(resp=resp)
        CommitCount = defaultdict(lambda: 0)
        for commit in commits:
            CommitCount[commit['author']] += 1

        for key, value in CommitCount.items():

            if StudentCommitCounts.objects.filter(
                    student_name=str(key)).exists():
                user = StudentCommitCounts.objects.get(student_name=str(key))
                if str(value) != user.commit_counts:
                    StudentCommitCounts.objects.filter(
                        student_name=str(key)).update(commit_counts=str(value))
            else:
                user = StudentCommitCounts(student_name=str(key),
                                           commit_counts=str(value),
                                           space_key=relation.space_key)
                user.save()
示例#26
0
def update_team(request, body, *args, **kwargs):
    team_id = kwargs.get('id')
    update_team_dto = UpdateTeamDTO()
    body_extract(body, update_team_dto)

    try:
        team = Team.objects.get(team_id=team_id)
    except ObjectDoesNotExist as e:
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)

    if update_team_dto.supervisor_id:
        team.supervisor_id = update_team_dto.supervisor_id
    if update_team_dto.secondary_supervisor_id:
        team.secondary_supervisor_id = update_team_dto.secondary_supervisor_id

    team.save()
    resp = init_http_response_my_enum(RespCode.success)
    return make_json_response(resp=resp)
示例#27
0
def get_git_pr(request, body, *args, **kwargs):
    git_dto = GitDTO()
    body_extract(body, git_dto)

    if not git_dto.valid_url:
        resp = init_http_response_my_enum(RespCode.invalid_parameter)
        return make_json_response(resp=resp)
    git_dto.url = git_dto.url.lstrip('$')

    commits = get_pull_request(git_dto.url, git_dto.author, git_dto.branch,
                               git_dto.second_after, git_dto.second_before)
    total = len(commits)
    author = set()
    for commit in commits:
        author.add(commit['author'])
    data = dict(
        total=total,
        author=list(author),
        commits=commits,
    )
    resp = init_http_response_my_enum(RespCode.success, data)
    return make_json_response(resp=resp)
def update_subject(request, body, *args, **kwargs):
    """

    :param body:
    :param request:
    :param args:
    :param kwargs:
    :return:
    """
    subject_id = kwargs.get('id')

    if not subject_id:
        resp = init_http_response(RespCode.invalid_parameter.value.key,
                                  RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponse, resp)

    add_subject_dto = AddSubjectDTO()
    body_extract(body, add_subject_dto)

    try:
        subject = Subject.objects.get(subject_id=subject_id,
                                      status=Status.valid.value.key)

        if add_subject_dto.code is not None:
            subject.subject_code = add_subject_dto.code
        if add_subject_dto.name is not None:
            subject.name = add_subject_dto.name
        if add_subject_dto.coordinator_id is not None:
            subject.coordinator_id = add_subject_dto.coordinator_id
        subject.save()
    except ObjectDoesNotExist as e:
        resp = init_http_response(RespCode.invalid_parameter.value.key,
                                  RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponse, resp)

    resp = init_http_response(RespCode.success.value.key,
                              RespCode.success.value.msg)
    return make_json_response(HttpResponse, resp)
示例#29
0
def check_oauth(team_id):

    # retrieve Slack configuration
    try:
        team_configuration = TeamConfiguration.objects.get(team_id=team_id)
    except ObjectDoesNotExist as e:
        resp = init_http_response_my_enum(RespCode.invalid_op)
        resp['message'] = "Invalid team configuration"
        return make_json_response(resp=resp)

    # retrieve token by team_id from team Slack configuration
    if team_configuration.slack_access:
        token = team_configuration.slack_token
        if token:
            slack_client = WebClient(token=token)
            return slack_client
    else:
        resp = init_http_response_my_enum(RespCode.invalid_op)
        resp['message'] = "Need access to Slack workspace"
        return make_json_response(resp=resp)

    # Todo: Oauth v2
    return None
def add_subject(request, body, *args, **kwargs):
    """

    :param request:
    :return:
    """
    add_subject_dto = AddSubjectDTO()
    body_extract(body, add_subject_dto)

    # if the parameter is not sufficient
    if not add_subject_dto.not_empty():
        resp = init_http_response(RespCode.invalid_parameter.value.key,
                                  RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponseBadRequest, resp)

    # if the subject code existed
    if Subject.objects.filter(subject_code=add_subject_dto.code).exists():
        resp = init_http_response(RespCode.subject_existed.value.key,
                                  RespCode.subject_existed.value.msg)
        return make_json_response(HttpResponseBadRequest, resp)

    if not User.objects.filter(
            user_id=add_subject_dto.coordinator_id).exists():
        resp = init_http_response(RespCode.invalid_parameter.value.key,
                                  RespCode.invalid_parameter.value.msg)
        return make_json_response(HttpResponseBadRequest, resp)

    subject = Subject(subject_code=add_subject_dto.code,
                      name=add_subject_dto.name,
                      coordinator_id=add_subject_dto.coordinator_id,
                      create_date=mills_timestamp(),
                      status=Status.valid.value.key)
    subject.save()

    resp = init_http_response(RespCode.success.value.key,
                              RespCode.success.value.msg)
    return make_json_response(HttpResponse, resp)