Ejemplo n.º 1
0
 def post(self):
     reqparser = reqparse.RequestParser()
     reqparser.add_argument('feed_id',
                            type=unicode,
                            location='json',
                            required=False)
     args = reqparser.parse_args()
     feed_id = int(decode_id(args.get('feed_id')))
     feed = Feed.find(feed_id)
     if not feed:
         st_raise_error(ErrorCode.FEED_NOT_FOUND)
     feed_like = FeedLike.find_by_uid(current_user.user.id, feed_id)
     if not feed_like:
         feed_like = FeedLike(uid=current_user.user.id,
                              feed_id=feed_id,
                              status=FeedLikeStatus.Liked)
         FeedLike.add(feed_like)
     else:
         feed_like.status = FeedLikeStatus.reverse(feed_like.status)
     if feed_like.status == FeedLikeStatus.Liked:
         feed.like_count += 1
     else:
         feed.like_count -= 1
     if feed.like_count < 0:
         # Ensure the count is >= 0
         feed.like_count = 0
     feed_like.update()
     new_feed = feed_service.get_feed(current_user.user.id, feed_id)
     return compose_response(result=new_feed)
Ejemplo n.º 2
0
    def get(self):
        reqparser = reqparse.RequestParser()
        reqparser.add_argument('mobile',
                               type=str,
                               location='args',
                               required=True)
        args = reqparser.parse_args()

        mobile = args["mobile"]

        verification_code = VerificationCode(mobile)
        if verification_code.request_count(
        ) >= settings["MAX_VERIFICATION_CODE_REQUEST_COUNT"]:
            raise st_raise_error(ErrorCode.VERIFICATION_CODE_MAX_REQUEST)

        code = verification_code.get_code()
        if not code:
            # get and send sms code
            if os.getenv("API_ENV") == "dev" and mobile.startswith('190'):
                code = mobile[-6:]
            else:
                code = generate_random_verification_code()
                result = send_sms_code(mobile, code)
                if not result:
                    st_raise_error(ErrorCode.VERIFICATION_CODE_SEND_FAILED)
            verification_code.set_code(code)
        return compose_response(message="验证码已发送")
Ejemplo n.º 3
0
    def add(uid, uidA, uidB, comment):
        result = False
        contact = Contact.find_by_uid(uidA, uidB)
        if contact and contact.status == ContactStatus.Connected:
            st_raise_error(ErrorCode.RELATIONSHIP_ALREADY_CONNECTED)

        type = ContactRequestType.Added if uid == uidA else ContactRequestType.Recommended
        if type == ContactRequestType.Added:
            # the two user must have been in at least one same company if add directly.
            work_experiences_A = set(WorkExperience.get_company_ids(uidA))
            work_experiences_B = set(WorkExperience.get_company_ids(uidB))
            if len(work_experiences_A & work_experiences_B) == 0:
                st_raise_error(ErrorCode.ADD_RELATIONSHIP_NOT_COMMON_COMPANY)

        # TODO: 过期时间
        request = ContactRequest.query.filter(
            ContactRequest.uid == uid,
            ContactRequest.uidA == uidA,
            ContactRequest.uidB == uidB,
        ).one_or_none()

        if request is None:
            request = ContactRequest(uid=uid,
                                     uidA=uidA,
                                     uidB=uidB,
                                     type=type,
                                     comment=comment,
                                     status=ContactRequestStatus.Pending)
            db.session.add(request)
            result = True
        db.session.commit()
        return result
Ejemplo n.º 4
0
 def post(self):
     text = request.json.get('text')
     encoded_image_ids = request.json.get('images')
     if not text and not encoded_image_ids:
         st_raise_error(ErrorCode.FEED_CONTENT_INCOMPLETE)
     image_ids = None
     if encoded_image_ids:
         image_ids = [Image.decode_id(id) for id in encoded_image_ids]
     feed = Feed(uid=current_user.user.id, images=image_ids, text=text)
     Feed.add(feed)
     new_feed = Feed.find(feed.id)
     return compose_response(result=new_feed.to_dict(), message="发布成功")
Ejemplo n.º 5
0
def add_work_experience(uid, company_id, company_name, title, start_year,
                        start_month, end_year, end_month):
    company = _get_or_add_company(company_id, company_name)
    if company is None:
        st_raise_error(ErrorCode.COMPANY_INFO_MISSED)
    work_experience = WorkExperience(uid=uid,
                                     company_id=company.id,
                                     title=title,
                                     start_year=start_year,
                                     start_month=start_month,
                                     end_year=end_year,
                                     end_month=end_month)
    WorkExperience.add(work_experience)
    _update_user_title(uid)
Ejemplo n.º 6
0
 def delete(self):
     reqparser = reqparse.RequestParser()
     reqparser.add_argument('id',
                            type=unicode,
                            location='json',
                            required=True)
     args = reqparser.parse_args()
     id = decode_id(args.get('id'))
     wks = work_service.get_work_experiences(current_user.user.id)
     if len(wks) <= 1:
         st_raise_error(ErrorCode.WORK_EXPERIENCE_CAN_NOT_BE_EXTINCT)
     work_service.delete_work_experience(current_user.user.id, id)
     return compose_response(
         result=user_service.get_login_user_profile(current_user.user.id))
Ejemplo n.º 7
0
def update_work_experience(uid, id, company_id, company_name, title,
                           start_year, start_month, end_year, end_month):
    company = _get_or_add_company(company_id, company_name)
    if company is None:
        st_raise_error(ErrorCode.COMPANY_INFO_MISSED)
    work_experience = WorkExperience.find_by_uid_id(uid, id)
    if not work_experience:
        st_raise_error(ErrorCode.WORK_EXPERIENCE_NOT_EXIST)
    work_experience.start_year = start_year
    work_experience.start_month = start_month
    work_experience.end_year = end_year
    work_experience.end_month = end_month
    work_experience.company_id = company.id
    work_experience.title = title
    work_experience.update()
    _update_user_title(uid)
Ejemplo n.º 8
0
 def post(self):
     args = self.reqparser.parse_args()
     device_id = args['device_id']
     mobile = args['mobile']
     password = args['password']
     user = User.find_by_mobile(mobile)
     if user is None:
         st_raise_error(ErrorCode.NOT_REGISTERED)
     elif not user.verify_password(password):
         raise st_raise_error(ErrorCode.USER_PASSWORD_WRONG)
     elif not user.is_available():
         raise st_raise_error(ErrorCode.USER_UNAVAILABLE)
     token = user.login_on(device_id)
     json_user = user_service.get_login_user_profile(user.id)
     json_user.update(token)
     return compose_response(result=json_user, message="登录成功")
Ejemplo n.º 9
0
    def post(self):
        reqparser = reqparse.RequestParser()
        reqparser.add_argument('device-id',
                               type=str,
                               location='headers',
                               required=True)
        reqparser.add_argument('mobile',
                               type=str,
                               location='json',
                               required=True)
        reqparser.add_argument('password',
                               type=str,
                               location='json',
                               required=True)
        reqparser.add_argument('verification_code',
                               type=str,
                               location='json',
                               required=True)
        args = reqparser.parse_args()

        mobile = args["mobile"]
        password = args["password"]

        verification_code = redis_conn.get(
            "verification_code:{}".format(mobile))
        if verification_code is None:
            raise st_raise_error(ErrorCode.VERIFICATION_CODE_EXPIRE)
        if verification_code != args["verification_code"]:
            raise st_raise_error(ErrorCode.VERIFICATION_CODE_NOT_MATCH)

        user = User.find_by_mobile(mobile)
        message = ""
        if user is None:
            user = User.add(mobile, password)
            Endorsement.add(user.id)
            message = "注册成功"
        else:
            user.hash_password(password)
            db.session.commit()
            message = "密码已重置"
        token = user.login_on(args["device-id"])
        json_user = user_service.get_login_user_profile(user.id)
        json_user.update(token)
        return compose_response(result=json_user, message=message)
Ejemplo n.º 10
0
    def update_user(self, **kwargs):
        if not kwargs:
            return

        for key, value in kwargs.iteritems():
            if key in ["password", "user_name", "gender", "colleague_id", "avatar"] and value:
                if key == 'password':
                    self.hash_password(value)
                if key == 'colleague_id':
                    if self.colleague_id:
                        st_raise_error(ErrorCode.COLLEAGUE_ID_ALREADY_SET)
                    exist_colleague_id = User.query.filter(User.colleague_id == value).one_or_none()
                    if exist_colleague_id:
                        st_raise_error(ErrorCode.ALREADY_EXIST_COLLEAGUE_ID)
                    self.colleague_id = value
                else:
                    setattr(self, key, value)

        db.session.commit()
        return self.to_dict()
Ejemplo n.º 11
0
def get_user_endorse(uid, type, latest_id, size=20):
    """
    Get endorse records.
    #TODO the api name
    :param uid: Target user
    :param type: Endorse type @see EndorseType
    :param latest_id: The latest id for already fetched list.
    :param size: records count
    :return: [UserEndorse]
    """
    if not EndorseType.check(type):
        st_raise_error(ErrorCode.ENDORSE_TYPE_INVALID)
    endorsements = UserEndorse.find_by_cursor(uid, type, latest_id, size)
    has_more = False
    next_cursor = None
    if len(endorsements) == size:
        has_more = True
        next_cursor = encode_id(endorsements[-1].id)
    json_endorsements = [item.to_dict() for item in endorsements]
    return cursor_data(has_more, next_cursor, 'endorsements', json_endorsements)
Ejemplo n.º 12
0
 def post(self):
     img = request.files['image']
     date = datetime.now()
     saved_dir = "feed/{}/{}/{}".format(date.year, date.month, date.day)
     data = img.read()
     md5hash = hashlib.md5(data).hexdigest()
     saved_path = os.path.join(saved_dir, md5hash)
     db_image = Image.find_by_path(saved_path)
     if db_image:
         return compose_response(result=db_image.to_dict())
     img.seek(0)
     (result, request_id) = aliyun_oss_service.upload_file(saved_path, img)
     if result:
         height, width, channels = imageio.imread(data).shape
         db_image = Image(uid=current_user.user.id, path=saved_path,
                          width=width, height=height, size=len(data),
                          location=MediaLocation.AliyunOSS, info=request_id)
         Image.add(db_image)
         return compose_response(result=db_image.to_dict())
     else:
         st_raise_error(ErrorCode.UPLOAD_IMAGE_FAILED)
Ejemplo n.º 13
0
 def post(self):
     # 请求建立联系人关系
     reqparser = reqparse.RequestParser()
     reqparser.add_argument('uidA', type=unicode, location='json', required=True)
     reqparser.add_argument('uidB', type=unicode, location='json', required=True)
     reqparser.add_argument('comment', type=unicode, location='json', required=False)
     args = reqparser.parse_args()
     uidA = int(decode_id(args['uidA']))
     uidB = int(decode_id(args['uidB']))
     if uidB == current_user.user.id:
         st_raise_error(ErrorCode.NOT_ALLOWED_ADD_SELF)
     result = ContactRequest.add(current_user.user.id, uidA, uidB, args.get('comment'))
     if result:
         if current_user.user.id == uidA:
             message = "{}请求添加你为联系人".format(current_user.user.user_name)
         else:
             userA = User.find(uidA)
             message = "{}给你推荐了{}".format(current_user.user.user_name, userA.user_name)
         rc_service.send_system_notification(rc_service.RCSystemUser.T100001,
                                             args['uidB'], message)
     return compose_response(message="请求发送成功")
Ejemplo n.º 14
0
def get_user_profile(uid, viewer_uid):
    """
    Get a user's profile. A views B's profile.
    uid = B's id, viewer_uid = A's id
    :param uid: Target user id
    :param viewer_uid: The viewer's uid.
    :return: Profile
    """
    user = User.find(uid)
    if not user:
        st_raise_error(ErrorCode.USER_NOT_EXIST)
    work_experiences = work_service.get_work_experiences(uid)
    endorsement = get_user_endorsement(uid, current_user.user.id)
    latest_comment = EndorseComment.find_latest_by_uid(uid)
    profile = user.to_dict()
    profile['endorsement'] = endorsement
    profile['work_experiences'] = work_experiences
    if latest_comment:
        profile['latest_comment'] = latest_comment.to_dict()
    contact = Contact.find_by_uid(uid, viewer_uid)
    profile['is_contact'] = contact is not None \
                            and contact.status == ContactStatus.Connected
    return profile
Ejemplo n.º 15
0
 def get(self):
     token = rc_service.get_rc_token(current_user.user)
     if token is None:
         st_raise_error(ErrorCode.RCTOKEN_FETCH_ERROR)
     return compose_response(result={"token": token})