Beispiel #1
0
 def startConversation(self, request):
     try:
         user = request.user
         profileSender = utils.getProfile(user)
         idNotice = request.data.get('notice', None)
         notice = None if idNotice is None else Notice.getNotice(idNotice)
         idUserReceiver = request.data.get('user', None)
         profileReceiver = utils.getProfile(utils.getUser(idUserReceiver)) if notice is None else notice.profile
         profiles = []
         profiles.append(profileReceiver)
         profiles.append(profileSender)
         text = request.data.get('text', None)
         image = request.data.get('image', None)
         if profiles[0] == profiles[1]:
             return Response({'success': False, 'err': 'Message to myself not allowed'}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
         if (text or image) and len(profiles) > 0:
             conversation = Conversation.create(profiles, notice)[0][0]
             Message.create(text, image, profileSender, conversation)
             utils.sendEmail(profiles[0].user.email, 'notifications/new_message.html')
             return Response({'success': True, 'msg': 'conversation-created'}, status=status.HTTP_201_CREATED)
         else:
             return Response({'success': False, 'err': 'Incomplete data'}, status=status.HTTP_400_BAD_REQUEST)
     except Exception as e:
         if hasattr(e, 'message'):
             err = e.message
         else:
             err = e
         return Response({'success': False, 'err': str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
Beispiel #2
0
    def checkFollowing(self, request):
        try:
            following = utils.getProfile(utils.getUser(request.data.get('user', None)))
            follower = utils.getProfile(request.user)
            if following is None:
                return Response({'success': False, 'err': 'field-undefined'}, status=status.HTTP_400_BAD_REQUEST)
            return Response({'success': True, 'following': Follow.checkFollowing(follower, following)})

        except Exception as e:
            if hasattr(e, 'message'):
                err = e.message
            else:
                err = e
            return Response({'success': False, 'err': str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
Beispiel #3
0
 def getData(self, request, pk=None):
     try:
         user = utils.getUser(pk)
         context = {}
         context['user'] = json.loads(serializers.serialize('json', [user], fields=('username', 'first_name', 'last_name', 'email', 'is_active', 'last_login', 'date_joined')))
         profile = utils.getProfile(user)
         context['profile'] = json.loads(serializers.serialize('json', [profile]))
         context['profile'][0]['fields']['location'] = utils.getDataCities([profile.location])
         context['profile'][0]['fields']['avatar'] = S3 + MEDIA_URL + str(profile.avatar)
         context['duration'] = utils.getDurationUser(user)
         context['numberFollowers'] = utils.getNumberFollowersUser(user)
         haveCategories = utils.getHaveCategoriesUser(user)
         context['haveCategories'] = json.loads(serializers.serialize('json', haveCategories))
         for i, category in enumerate(context['haveCategories']):
             context['haveCategories'][i]['fields']['name'] = str(haveCategories[i])
         searchCategories = utils.getSearchCategoriesUser(user)
         context['searchCategories'] = json.loads(serializers.serialize('json', searchCategories))
         for i, category in enumerate(context['searchCategories']):
             context['searchCategories'][i]['fields']['name'] = str(searchCategories[i])
         context['tags'] = json.loads(serializers.serialize('json', utils.getTagsUser(user)))
         return Response({'success': True, 'data': context})
     except Exception as e:
         if hasattr(e, 'message'):
             err = e.message
         else:
             err = e
         return Response({'success': False, 'err': str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
Beispiel #4
0
 def create(self, request, *args, **kwargs):
     profile = utils.getProfile(request.user)
     request.data['profile'] = profile.id
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     self.perform_create(serializer)
     headers = self.get_success_headers(serializer.data)
     return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
Beispiel #5
0
    def unfollow(self, request):
        try:
            follower = utils.getProfile(request.user)

            user = request.data.get('user', None)
            if user is None:
                return Response({'success': False, 'err': 'field-undefined'}, status=status.HTTP_400_BAD_REQUEST)

            following = utils.getProfile(utils.getUser(user))

            instance = Follow.getFollowing(follower, following)
            instance.delete()
            return Response({'success': True})
        except Exception as e:
            if hasattr(e, 'message'):
                err = e.message
            else:
                err = e
            return Response({'success': False, 'err': str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
Beispiel #6
0
    def create(self, request, *args, **kwargs):
        follower = utils.getProfile(request.user)
        user = request.data.get('user', None)

        if user is None:
            return Response({'success': False, 'err': 'field-undefined'}, status=status.HTTP_400_BAD_REQUEST)

        following = utils.getProfile(utils.getUser(user))
        if Follow.checkFollowing(follower.id, following.id):
            return Response({'success': False, 'err': 'already following'}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)

        request.data['following'] = following.id
        request.data['follower'] = follower.id
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        utils.sendEmail(following.user.email, 'notifications/new_follower.html')
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
Beispiel #7
0
 def getCountNotifications(self, request):
     try:
         user = request.user
         profile = utils.getProfile(user)
         count = Conversation.countNotifications(profile)
         return Response({'success': True, 'count': count})
     except Exception as e:
         if hasattr(e, 'message'):
             err = e.message
         else:
             err = e
         return Response({'success': False, 'err': str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
Beispiel #8
0
 def reviewConversation(self, request):
     try:
         user = request.user
         idProfile = utils.getProfile(user).id
         idConversation = request.data.get('conversation', None)
         Conversation.addReview(idProfile, idConversation)
         return Response({'success': True, 'msg': 'conversation-review'})
     except Exception as e:
         if hasattr(e, 'message'):
             err = e.message
         else:
             err = e
         return Response({'success': False, 'err': str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
Beispiel #9
0
    def update(self, request, *args, **kwargs):
        profile = utils.getProfile(request.user)
        request.data['profile'] = profile.id
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        if request.user != instance.profile.user:
            return Response({'success': False, 'err': 'user-unauthorized'}, status=status.HTTP_401_UNAUTHORIZED)
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)
Beispiel #10
0
    def addMessage(self, request):
        # try:
        user = request.user
        profileSender = utils.getProfile(user)
        idConversation = request.data.get('conversation', None)
        conversation = Conversation.getConversation(idConversation)
        text = request.data.get('text', None)
        image = request.data.get('image', None)

        if (text or image) and conversation and profileSender:
            Message.create(text, image, profileSender, conversation)
            contestants = conversation.contestant.all()
            for profile in contestants:
                if profile != profileSender:
                    utils.sendEmail(profile.user.email, 'notifications/new_message.html')
            return Response({'success': True, 'msg': 'message-created'}, status=status.HTTP_201_CREATED)
        else:
            return Response({'success': False, 'err': 'Incomplete data'}, status=status.HTTP_400_BAD_REQUEST)
Beispiel #11
0
 def getInbox(self, request):
     try:
         user = request.user
         profile = utils.getProfile(user)
         context = []
         conversations = Conversation.search(profile)
         for conversation in conversations:
             listContestants = utils.getProfileSimple(conversation.contestant.all())
             listReviews = utils.getProfileSimple(conversation.review.all())
             listNotices = utils.getDataNotice(conversation.notice.all(), fullData=False)
             listMessages = utils.getDataMessages(Message.search(conversation))
             context.append({'id': conversation.id, 'modified': conversation.modified, 'contestants': listContestants, 'notices': listNotices, 'reviews': listReviews, 'messages': listMessages})
         return Response({'success': True, 'data': context})
     except Exception as e:
         if hasattr(e, 'message'):
             err = e.message
         else:
             err = e
         return Response({'success': False, 'err': str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
Beispiel #12
0
 def retrieve(self, request, pk=None):
     try:
         conversation = Conversation.getConversation(pk)
         if utils.getProfile(request.user) not in conversation.contestant.all():
             return Response({'success': False, 'err': 'user-unauthorized'}, status=status.HTTP_401_UNAUTHORIZED)
         conversations = [conversation]
         context = []
         for conversation in conversations:
             listContestants = utils.getProfileSimple(conversation.contestant.all())
             listReviews = utils.getProfileSimple(conversation.review.all())
             listNotices = utils.getDataNotice(conversation.notice.all(), fullData=False)
             listMessages = utils.getDataMessages(Message.search(conversation))
             context.append({'id': conversation.id, 'modified': conversation.modified, 'contestants': listContestants, 'notices': listNotices, 'reviews': listReviews, 'messages': listMessages})
         return Response({'success': True, 'data': context})
     except Exception as e:
         if hasattr(e, 'message'):
             err = e.message
         else:
             err = e
         return Response({'success': False, 'err': str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
Beispiel #13
0
    def getHome(self, request):
        try:
            user = request.user
            profile = utils.getProfile(user)
            context = cache.get('home_%s' % profile.id)
            if context is None:
                queries = utils.Notice.searchHome(profile.id)
                notices = utils.noticesQuery(queries)
                context = utils.getDataNotice(notices)
                cache.set('home_%s' % profile.id, context)

            page = utils.getPagination(context, request, 20)
            if isinstance(page, str):
                return Response({'success': False, 'err': page}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
            elif page.has_next():
                return Response({'success': True, 'data': page.object_list, 'next': page.next_page_number()})
            else:
                return Response({'success': True, 'data': page.object_list})
        except Exception as e:
            if hasattr(e, 'message'):
                err = e.message
            else:
                err = e
            return Response({'success': False, 'err': str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
Beispiel #14
0
    def updateUser(self, request):
        try:
            user = request.user
            profile = utils.getProfile(user)
            username = request.data.get('username', None)
            first_name = request.data.get('first_name', None)
            last_name = request.data.get('last_name', None)
            email = request.data.get('email', None)
            avatar = request.data.get('avatar', None)
            icono = request.data.get('icono', None)
            birth_date = request.data.get('birth_date', None)
            gender = request.data.get('gender', None)
            phone = request.data.get('phone', None)
            biography = request.data.get('biography', None)
            location = request.data.get('location', None)
            company = request.data.get('company', None)
            profession = request.data.get('profession', None)
            address = request.data.get('address', None)
            avialability = request.data.get('avialability', None)
            i_search = request.data.get('i_search', None)
            tags = request.data.get('tags', None)

            response = {'success': False, 'err': 'field-undefined'}

            if username:
                if Profile.searchUsername(username) is False:
                    user.username = username
                    user.save()
                    response = {'success': True, 'msg': 'username-update'}
                else:
                    response = {'success': False, 'err': 'username-exists'}
            if first_name:
                user.first_name = first_name
                user.save()
                response = {'success': True, 'msg': 'first_name-update'}
            if last_name:
                user.last_name = last_name
                user.save()
                response = {'success': True, 'msg': 'last_name-update'}
            if email:
                if Profile.searchEmail(email) is False:
                    if utils.validateStructureEmail(email) is True:
                        EmailAddress.change(EmailAddress.objects.get(user=user), request, email)
                        response = {'success': True, 'msg': 'email-update'}
                    else:
                        response = {'success': False, 'err': 'email-invalid'}
                else:
                    response = {'success': False, 'err': 'email-exists'}
            if avatar:
                Profile.updateAvatar(profile, avatar)
                response = {'success': True, 'msg': 'avatar-update'}
            if icono:
                Profile.updateIcono(profile, icono)
                response = {'success': True, 'msg': 'icono-update'}
            if birth_date:
                Profile.updateBirthdate(profile, birth_date)
                response = {'success': True, 'msg': 'birth_date-update'}
            if gender:
                Profile.updateGender(profile, gender)
                response = {'success': True, 'msg': 'gender-update'}
            if phone:
                Profile.updatePhone(profile, phone)
                response = {'success': True, 'msg': 'phone-update'}
            if biography:
                Profile.updateBiography(profile, biography)
                response = {'success': True, 'msg': 'biography-update'}
            if location:
                Profile.updateLocation(profile, location)
                response = {'success': True, 'msg': 'location-update'}
            if company:
                Profile.updateCompany(profile, company)
                response = {'success': True, 'msg': 'company-update'}
            if profession:
                Profile.updateProfession(profile, profession)
                response = {'success': True, 'msg': 'profession-update'}
            if address:
                Profile.updateAddress(profile, address)
                response = {'success': True, 'msg': 'address-update'}
            if avialability:
                Profile.updateAvialability(profile, avialability)
                response = {'success': True, 'msg': 'avialability-update'}
            if i_search:
                WantedCategory.deleteAll(profile)
                for element in i_search:
                    WantedCategory.create(element['pk'], profile)
                response = {'success': True, 'msg': 'i_search-update'}
            if tags:
                TagProfile.deleteAll(profile)
                for element in tags:
                    TagProfile.create(element['pk'], profile)
                response = {'success': True, 'msg': 'tags-update'}

            if response["success"]:
                return Response(response)
            return Response(response, status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            if hasattr(e, 'message'):
                err = e.message
            else:
                err = e
            return Response({'success': False, 'err': str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
Beispiel #15
0
    def newNotice(self, request):
        try:
            user = request.user
            profile = utils.getProfile(user)
            # KIND: 1 --> have; 2 --> search
            kind = request.data.get('kind', None)
            # THING P --> producto, S --> servicio
            thing = request.data.get('thing', None)
            title = request.data.get('title', None)
            category = request.data.get('category', None)
            place = request.data.get('place', None)
            description = request.data.get('description', None)
            locations = request.data.get('locations', None)
            urgency = request.data.get('urgency', None)
            # busco
            offer = request.data.get('offer', None)
            # producto
            state = request.data.get('state', None)
            quantity = request.data.get('quantity', None)
            colors = request.data.get('colors', None)
            # servicio
            time = request.data.get('time', None)

            if kind is None or thing is None or title is None or category is None or place is None or description is None:
                return Response({'success': False, 'err': 'Incomplete data'}, status=status.HTTP_400_BAD_REQUEST)

            if thing == 'P' and (state is None or state == 'null'):
                return Response({'success': False, 'err': 'state undin'}, status=status.HTTP_400_BAD_REQUEST)

            if thing == 'S' and (time is None or time == 'null'):
                return Response({'success': False, 'err': 'Incomplete data'}, status=status.HTTP_400_BAD_REQUEST)

            notice = Notice.create(profile, category, title, description, kind, urgency, place)
            if locations:
                for location in locations:
                    CityNotice.create(location, notice)
            else:
                CityNotice.create(place, notice)
            noticeSerialized = json.loads(serializers.serialize('json', [notice]))
            if offer and kind == 2:
                try:
                    Notice.updateOffer(notice, offer)
                except Exception:
                    # "Non-existent offer"
                    pass
            if thing == 'P':
                product = Product.create(notice, state)
                if quantity:
                    Product.updateQuantity(product, quantity)
                if colors:
                    for color in colors:
                        Color.create(color, product)
                return Response({'success': True, 'msg': 'product-posted', 'notice': noticeSerialized})
            elif thing == 'S':
                Service.create(notice, time)
                return Response({'success': True, 'msg': 'service-posted', 'notice': noticeSerialized})
            else:
                return Response({'success': False, 'err': 'Thing not defined'}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        except Exception as e:
            if hasattr(e, 'message'):
                err = e.message
            else:
                err = e
            return Response({'success': False, 'err': str(err)}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)