def consume(self): task = self.pool.get(block=True, timeout=None) logger.info(u'[SMTP] Send Email: %d %s' % (self.count, str(task))) invite = Invitation.objects.get(invitation_id=task['id'], status=InvitationStatus.waiting.value.key) if invite is None or invite.expired <= mills_timestamp(): return if send_email(task['coordinator'], task['email'], task['text']): invite.status = InvitationStatus.sent.value.key invite.send_date = mills_timestamp() invite.save() else: self.pool.put(task)
def createSubject(subject_code, subject_name, coordinator_id): subject = Subject(subject_code=subject_code, name=subject_name, coordinator_id=coordinator_id, create_date=mills_timestamp(), status=Status.valid.value.key) subject.save()
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 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)
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)
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)
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 createUser(role, user_details): """ user_details: - first_name - last_name - email """ # create account timestamp = mills_timestamp() username = user_details['first_name'] password = user_details['first_name'] email = user_details['email'] status = Status.valid.value.key create_date = timestamp update_date = timestamp first_name = user_details['first_name'] last_name = user_details['last_name'] role = role.value.key md5 = login_helpers.encrypt(password) account = Account(username=username, email=email, password=md5, status=status, create_date=create_date, update_date=update_date) account.save() # create user user = User(account_id=account.account_id, username=username, first_name=first_name, last_name=last_name, role=role, status=status, create_date=create_date, update_date=update_date, email=email) user.save()
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)
def get_team_data(request, *args, **kwargs): team_id = kwargs['id'] 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) # call Slack api to get all Slack channels before the end of the sprint client = check_oauth(team_id) if not client: resp = init_http_response_my_enum(RespCode.invalid_op) return make_json_response(resp=resp) elif isinstance(client, HttpResponse): return client channels = get_all_channels(client) logger.info('channel: {}'.format(channels)) # get sprint number from request sprint_num = request.GET.get("sprint_num", None) sprint_num = int(sprint_num) if sprint_num is not None else -1 logger.info('sprint_num: {}'.format(sprint_num)) sprint_start = None sprint_end = None if sprint_num >= 0: parameter_start = 'sprint_start_{}'.format(sprint_num) parameter_end = 'sprint_end_{}'.format(sprint_num) sprint_start = team.__getattribute__(parameter_start) sprint_end = team.__getattribute__(parameter_end) logger.info('sprint start {} end {}'.format(sprint_start, sprint_end)) result = dict() temp_result = dict() total_number = 0 if SlackTeam.objects.filter(team_id=team_id, sprint_num=sprint_num).exists(): records = SlackTeam.objects.filter( team_id=team_id, sprint_num=sprint_num).order_by('time') start_time = records[0].time / 1000 if sprint_end and start_time > sprint_end: for record in records: result[record.channel_name] = record.message_num total_number += record.message_num result['total_number'] = total_number if sprint_start: result['sprint_start'] = sprint_start * 1000 if sprint_end: result['sprint_end'] = sprint_end * 1000 logger.info('result: {}'.format(result)) resp = init_http_response_my_enum(RespCode.success, data=result) return make_json_response(resp=resp) else: # call Slack api to get all channel messages in a specific sprint for channel in channels: messages = get_channel_messages(client, channel['id'], start_time, sprint_end) temp_result[channel['name']] = len(messages) for record in records: record.message_num += temp_result[record.channel_name] temp_result.pop(record.channel_name) result[record.channel_name] = record.message_num total_number += result[record.channel_name] record.time = mills_timestamp() record.save() # save new created channels logger.info('temp result: {}'.format(temp_result)) for (channel, num) in temp_result.items(): print(channel, num) result[channel] = num total_number += num slack_team = SlackTeam(team_id=team_id, channel_name=channel, message_num=num, sprint_num=sprint_num, time=mills_timestamp()) slack_team.save() result["total_number"] = total_number if sprint_start: result['sprint_start'] = sprint_start * 1000 if sprint_end: result['sprint_end'] = sprint_end * 1000 logger.info('result: {}'.format(result)) resp = init_http_response_my_enum(RespCode.success, data=result) return make_json_response(resp=resp) else: # call Slack api to get all channel messages in a specific sprint for channel in channels: messages = get_channel_messages(client, channel['id'], sprint_start, sprint_end) logger.info("{}: {}".format(channel['name'], len(messages))) result[channel['name']] = len(messages) total_number += len(messages) slack_team = SlackTeam(team_id=team_id, channel_name=channel['name'], message_num=result[channel['name']], sprint_num=sprint_num, time=mills_timestamp()) slack_team.save() result['total_number'] = total_number if sprint_start: result['sprint_start'] = sprint_start * 1000 if sprint_end: result['sprint_end'] = sprint_end * 1000 logger.info('result: {}'.format(result)) resp = init_http_response_my_enum(RespCode.success, data=result) return make_json_response(resp=resp)
def get_member_data(request, *args, **kwargs): team_id = kwargs['team_id'] student_id = int(kwargs['student_id']) 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) client = check_oauth(team_id) if not client: resp = init_http_response_my_enum(RespCode.invalid_op) return make_json_response(resp=resp) elif isinstance(client, HttpResponse): return client channels = get_all_channels(client) users, user_email = get_all_users(client) email_id = dict() for uid in user_email: email_id[user_email[uid]] = uid student = Student.objects.get(student_id=student_id) student_uid = email_id[student.email] student_info = dict( email=student.email, id=student_uid, name=users[email_id[student.email]], ) print(student_info) # get sprint number from request sprint_num = request.GET.get("sprint_num", None) sprint_num = int(sprint_num) if sprint_num is not None else -1 logger.info('sprint_num: {}'.format(sprint_num)) sprint_start = None sprint_end = None if sprint_num >= 0: parameter_start = 'sprint_start_{}'.format(sprint_num) parameter_end = 'sprint_end_{}'.format(sprint_num) sprint_start = team.__getattribute__(parameter_start) sprint_end = team.__getattribute__(parameter_end) logger.info('sprint start {} end {}'.format(sprint_start, sprint_end)) result = dict(total_number=0, name=student_info['name'], channel=dict()) for channel in channels: result['channel'][channel['name']] = 0 temp_result = deepcopy(result) if SlackMember.objects.filter(team_id=team_id, student_id=student_id, sprint_num=sprint_num).exists(): records = SlackMember.objects.filter( team_id=team_id, student_id=student_id, sprint_num=sprint_num).order_by('time') start_time = records[0].time / 1000 if sprint_end and start_time > sprint_end: for record in records: result['total_number'] += record.message_num result['channel'][record.channel_name] = record.message_num logger.info('result: {}'.format(result)) if sprint_start: result['sprint_start'] = sprint_start * 1000 if sprint_end: result['sprint_end'] = sprint_end * 1000 resp = init_http_response_my_enum(RespCode.success, data=result) return make_json_response(resp=resp) else: for channel in channels: messages = get_channel_messages(client, channel['id'], start_time, sprint_end) for message in messages: if message['user'] != student_info['id']: continue temp_result['total_number'] += 1 temp_result['channel'][channel['name']] += 1 for record in records: record.message_num += temp_result['channel'][ record.channel_name] temp_result['channel'].pop(record.channel_name) result['channel'][record.channel_name] = record.message_num result['total_number'] += record.message_num record.time = mills_timestamp() record.save() # save new created channels logger.info('temp result: {}'.format(temp_result)) for k, v in temp_result['channel'].items(): result['channel'][k] = v result['total_number'] += v slack_member = SlackMember(team_id=team_id, student_id=student_id, channel_name=k, message_num=v, sprint_num=sprint_num, time=mills_timestamp()) slack_member.save() logger.info('result: {}'.format(result)) if sprint_start: result['sprint_start'] = sprint_start * 1000 if sprint_end: result['sprint_end'] = sprint_end * 1000 resp = init_http_response_my_enum(RespCode.success, data=result) return make_json_response(resp=resp) else: for channel in channels: messages = get_channel_messages(client, channel['id'], sprint_start, sprint_end) for message in messages: if message['user'] != student_info['id']: continue result['total_number'] += 1 result['channel'][channel['name']] += 1 for c in result['channel']: slack_member = SlackMember(team_id=team_id, student_id=student_id, channel_name=c, message_num=result['channel'][c], sprint_num=sprint_num, time=mills_timestamp()) slack_member.save() logger.info('result: {}'.format(result)) if sprint_start: result['sprint_start'] = sprint_start * 1000 if sprint_end: result['sprint_end'] = sprint_end * 1000 resp = init_http_response_my_enum(RespCode.success, data=result) return make_json_response(resp=resp)
def add_invitation(request, body, *args, **kwargs): """ TODO: check email in account TODO: send email :param body: :param request: :return: """ print(body) user = request.session.get('user') user_id = user['id'] timestamp = mills_timestamp() expired = timestamp + 1000 * 60 * 60 * 24 * 1 invite_emails = body['emails'] template = body['template'] failed_list = list() invitations = list() if PATTERN_COORDINATOR not in template or PATTERN_URL not in template: resp = init_http_response_my_enum(RespCode.invalid_parameter) return make_json_response(resp=resp) for email in invite_emails: if Invitation.objects.filter(email=email, status__lte=InvitationStatus.accepted.key).exists() or \ Account.objects.filter(email=email, status=Status.valid.key).exists(): failed_list.append( dict( email=email, status=InvitationRespCode.existed.key, message=InvitationRespCode.existed.msg, )) continue key = ''.join([ ''.join(random.sample(string.ascii_letters + string.digits, 8)) for i in range(4) ]) content = str(template).replace(PATTERN_COORDINATOR, user['name']).replace( PATTERN_URL, get_invitation_link(key)) invitation = Invitation(key=key, email=email, operator=user_id, create_date=timestamp, expired=expired, template=content, status=InvitationStatus.waiting.key) invitations.append(invitation) try: with transaction.atomic(): for invite in invitations: invite.save() for invite in invitations: smtp_thread.put_task(invite.invitation_id, user['name'], invite.email, invite.template) except Exception as e: print(e) resp = init_http_response_my_enum(RespCode.server_error) return make_json_response(resp=resp) data = dict( invitation=[ dict( email=invite.email, status=invite.status, template=invite.template, message=get_message(InvitationStatus.__members__, invite.status), expired=invite.expired, ) for invite in invitations ], failed=failed_list, ) resp = init_http_response_my_enum(RespCode.success, data) return make_json_response(resp=resp)
def get_invitation(request): """ TODO: update expired status :param request: :param subject_id: :return: """ user = request.session.get('user') user_id = user['id'] finished = request.GET.get('finished', None) offset = int(request.GET.get('offset', 0)) has_more = 0 kwargs = dict(operator=user_id, ) if finished is not None: if int(finished) == 0: kwargs['status__lt'] = InvitationStatus.accepted.key else: kwargs['status__gte'] = InvitationStatus.accepted.key kwargs_update = dict( expired=mills_timestamp(), status=InvitationStatus.waiting.key, ) Invitation.objects.filter(**kwargs_update).update( status=InvitationStatus.expired.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_my_enum(RespCode.success, data) return make_json_response(resp=resp) data = dict(invitation=[ dict( id=invitation.invitation_id, email=invitation.email, expired=invitation.expired, status=get_message(InvitationStatus.__members__, invitation.status), ) for invitation in invitations ], offset=offset, has_more=has_more) resp = init_http_response_my_enum(RespCode.success, data) return make_json_response(resp=resp)