Example #1
0
    def add_friend(self, domain):
        # Validate user_id should be exists
        user_principal = UserPrincipal.query.filter_by(
            id=domain['user_id']).first()
        if user_principal is None:
            raise ValidationException(ErrorCode.USER_NOT_FOUND)
        # Validate friend_id should be exists
        user_principal = UserPrincipal.query.filter_by(
            id=domain['friend_id']).first()
        if user_principal is None:
            raise ValidationException(ErrorCode.FRIEND_NOT_FOUND)
        # Validate friend exists
        friend_count = Friend.query.filter_by(
            user_id=domain['user_id'], friend_id=domain['friend_id']).count()
        if friend_count:
            raise ValidationException(ErrorCode.FRIEND_ALREADY_EXIST)

        friend = Friend(domain)
        friend.save()
        friend_dict = friend.to_dict()
        activity_domain = {
            'user_id':
            friend.user_id,
            'message':
            ActivityMessage.START_FOLLOW,
            'raw':
            json.dumps(friend_dict,
                       indent=4,
                       sort_keys=True,
                       cls=TeachmeJsonEncoder),
            'doc_type':
            ActivityType.FOLLOW
        }
        activity_service.add_activity(activity_domain)
        return {'payload': friend.to_dict()}
Example #2
0
    def find_user_principal_by_id(self, domain):
        user_principal = UserPrincipal.query.with_entities(
         UserPrincipal.id,
         UserPrincipal.phone_number,
         UserPrincipal.username,
         UserPrincipal.fullname,
         UserPrincipal.gender,
         SchoolLevel.name.label('level'),
         SchoolClass.name.label('class_name'),
         UserPrincipal.level_id,
         UserPrincipal.class_id
        ).join(SchoolLevel, UserPrincipal.level_id == SchoolLevel.id) \
         .outerjoin(SchoolClass, UserPrincipal.class_id == SchoolClass.id) \
         .filter(UserPrincipal.id == domain['user_id']).first()
        if user_principal is None:
            raise ValidationException(ErrorCode.USER_NOT_FOUND)
        user_dict = user_principal._asdict()

        if int(domain['friend_id']) > 0:
            count_follower = Friend.query.filter_by(
                user_id=user_dict['id'],
                friend_id=domain['friend_id']).count()
            count_following = Friend.query.filter_by(
                user_id=domain['friend_id'],
                friend_id=user_dict['id']).count()
            user_dict['is_following'] = (count_following > 0)
            user_dict['is_follower'] = (count_follower > 0)

        return {'payload': user_dict}
Example #3
0
def add_document():
	if 'file' not in request.files:
		raise ValidationException('file.not.found')
	file = request.files['file']
	log.info("filename : %s", file.filename)
	if file.filename == '':
		raise ValidationException('file.cannot.be.empty')
	
	upload_folder = app.config['UPLOAD_FOLDER']
	data = request.form.to_dict()
	user_dir = '' if 'directory' not in data else data['directory']
	log.info('user_dir : %s', user_dir)
	
	directory = os.path.join(os.path.dirname(upload_folder), user_dir)
	if not os.path.exists(directory):
		os.makedirs(directory)
	
	if file and allowed_file(file.filename):
		# setting file upload
		mimetype = str(file.content_type)
		file_time = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
		original_filename = secure_filename(file.filename)
		filename = file_time + '_' + original_filename
		domain = {'filename': filename, 'folder': directory, 'mimetype': mimetype,
		          'original_filename': original_filename}
		# Check if data has secure key
		if 'secure' in data:
			domain['secure'] = data['secure']
		final_file_path = os.path.join(directory, filename)
		file.save(final_file_path)
		extension = str(os.path.splitext(filename)[1][1:]).strip().lower()
		# video/mp4
		if extension.endswith('mp4'):
			domain['thumbnails'] = video_thumbnails(final_file_path)
			return document_service.add_document(domain)
		# application/pdf
		elif extension.endswith('pdf'):
			domain['thumbnails'] = save_pdf_image(final_file_path, directory)
			return document_service.add_document(domain)
		elif extension.endswith('jpg') or extension.endswith('jpeg'):
			img = cv2.imread(final_file_path, cv2.IMREAD_UNCHANGED) 
			cv2.imwrite(final_file_path, img,   [int(cv2.IMWRITE_JPEG_QUALITY), 50])
			return document_service.add_document(domain)
		else:
			return document_service.add_document(domain)
	raise CoreException(ErrorCode.UPLOAD_FAIL)
Example #4
0
	def add_lesson_viewer(self, domain):
		lesson = Lesson.query.get(domain['lesson_id'])
		if lesson is None:
			raise ValidationException(ErrorCode.LESSON_NOT_FOUND)
		if lesson.active != 'A':
			raise ValidationException(ErrorCode.LESSON_IS_NOT_ACTIVE)
		viewer = LessonViewer.query.filter_by(user_id=domain['user_id']).filter_by(lesson_id=domain['lesson_id']).first()
		if viewer is not None:
			raise ValidationException(ErrorCode.LESSON_VIEWER_EXIST)
		if lesson.user_id == domain['user_id']:
			raise ValidationException(ErrorCode.LESSON_VIEWER_MUST_NOT_CREATOR)
		lesson_viewer = LessonViewer(domain)
		lesson_viewer.save()
		activity_domain = {'user_id': domain["user_id"],
		                   'message': ActivityMessage.READ_LESSON,
		                   'raw': json.dumps(lesson.to_dict(), indent=4, sort_keys=True, cls=TeachmeJsonEncoder),
		                   'doc_type': ActivityType.LESSON_VIEWER}
		activity_service.add_activity(activity_domain)
		return {'payload': lesson_viewer.to_dict()}
Example #5
0
 def get_user_image(self, domain):
     document = Document.query .join(UserPrincipal, UserPrincipal.document_id == Document.id) \
      .filter(UserPrincipal.username == domain['username']).first()
     # User not found cause is load by username
     if document is None:
         raise ValidationException(ErrorCode.USER_NOT_FOUND)
     else:
         filename = os.path.join(
             document.folder, document.filename
             if 'thumbnails' not in domain else document.thumbnails)
         return send_file(filename,
                          mimetype=document.mimetype
                          if 'thumbnails' not in domain else 'image/png')
Example #6
0
    def validate_edit_user(domain, user):
        # Validation
        phone_number = domain['phone_number']
        username = domain['username']

        # Validate Username regex
        if not re.match(r'^[a-z0-9_-]{3,15}$', username):
            raise ValidationException(ErrorCode.INVALID_USERNAME)

        # Validate Phone Number exists
        log.info('phone number %s : %s', user.phone_number, phone_number)
        log.info('phone number %s', user.phone_number != phone_number)
        if user.phone_number != phone_number:
            val_phone_number = UserPrincipal.query.filter_by(
                phone_number=phone_number).first()
            if val_phone_number is not None:
                raise ValidationException(ErrorCode.PHONE_NUMBER_HAS_BEEN_USED)
        log.info('username %s', user.username != username)
        if user.username != username:
            val_username = UserPrincipal.query.filter_by(
                username=username).first()
            if val_username is not None:
                raise ValidationException(ErrorCode.USERNAME_HAS_BEEN_USED)
        pass
Example #7
0
    def validate_add_user(domain):
        # Validation
        if domain['phone_number'].startswith('0'):
            domain['phone_number'] = domain['phone_number'].replace(
                '0', '+62', 1)

        phone_number = domain['phone_number']
        username = domain['username']

        # Validate Username regex
        if not re.match(r'^[a-z0-9_-]{3,15}$', username):
            raise ValidationException(ErrorCode.INVALID_USERNAME)

        # Validate Phone Number exists
        val_phone_number = UserPrincipal.query.filter_by(
            phone_number=phone_number).first()
        if val_phone_number is not None:
            raise ValidationException(ErrorCode.PHONE_NUMBER_HAS_BEEN_USED)

        # Validate Username exists
        val_username = UserPrincipal.query.filter_by(username=username).first()
        if val_username is not None:
            raise ValidationException(ErrorCode.USERNAME_HAS_BEEN_USED)
        pass
Example #8
0
 def count_following_followers(self, domain):
     user_principal = UserPrincipal.query.filter_by(
         id=domain['user_id']).first()
     if user_principal is None:
         raise ValidationException(ErrorCode.USER_NOT_FOUND)
     following = Friend.query.filter_by(user_id=domain['user_id']).count()
     follower = Friend.query.filter_by(friend_id=domain['user_id']).count()
     activity = Activity.query.filter(
         Activity.user_id == domain['user_id']).count()
     return {
         'payload': {
             'total_following': following,
             'total_follower': follower,
             'total_activity': activity
         }
     }
Example #9
0
 def get_task_for_edit(self, domain):
     task = Task.query.filter_by(id=domain['task_id']).first()
     if task == None:
         raise ValidationException(ErrorCode.TASK_NOT_FOUND)
     task_data = {
         'task_id': task.id,
         'active': task.active,
         'user_id': task.user_id,
         'title': task.title,
         'time_limit': task.time_limit
     }
     question_q = TaskQuestion.query.with_entities(TaskQuestion.id, TaskQuestion.answer_key, TaskQuestion.question, TaskQuestion.question_type.label('type')) \
         .filter(TaskQuestion.task_id == task.id) \
         .order_by(TaskQuestion.id.asc())
     question_list = list(
         map(lambda x: self.handle_question(x._asdict()), question_q.all()))
     task_data['questions'] = question_list
     return {'payload': task_data}
Example #10
0
    def edit_user_principal_by_username(self, domain):
        log.info("Input %s", domain)
        user_principal = UserPrincipal.query.get(domain['id'])

        if user_principal is None:
            raise ValidationException(ErrorCode.USER_NOT_FOUND)

        if 'username' in domain and 'phone_number' in domain:
            self.validate_edit_user(domain, user_principal)
            if 'password' in domain:
                domain['hash_password'] = bcrypt.generate_password_hash(
                    domain['password'], 10).replace(b'$2b$', b'$2a$')

            if domain['phone_number'].startswith('0'):
                domain['phone_number'] = domain['phone_number'].replace(
                    '0', '+62', 1)

        user_principal.update(domain)
        user_dict = user_principal.to_dict()
        return {'payload': user_dict}
Example #11
0
    def find_user_principal_by_username(self, domain):
        user_principal = UserPrincipal.query.with_entities(
         UserPrincipal.id,
         UserPrincipal.phone_number,
         UserPrincipal.username,
         UserPrincipal.fullname,
         UserPrincipal.gender,
         SchoolLevel.name.label('level'),
         SchoolClass.name.label('class_name'),
         UserPrincipal.level_id,
         UserPrincipal.class_id,
         UserPrincipal.register_type
        ).join(SchoolLevel, UserPrincipal.level_id == SchoolLevel.id) \
         .outerjoin(SchoolClass, UserPrincipal.class_id == SchoolClass.id) \
         .filter(UserPrincipal.username == domain['username']).first()
        if user_principal is None:
            raise ValidationException(ErrorCode.USER_NOT_FOUND)
        user_dict = user_principal._asdict()

        return {'payload': user_dict}