Example #1
0
    def mutate(self, info, isApproved, entryID, position=None):
        try:
            entry = ListEntry.objects.get(id=entryID)
            if entry.position is None:
                if isApproved:
                    # if position is none, add item at the end
                    if position is None:
                        count = Position.objects.filter(
                            list=entry.list).count()
                        position = count + 1

                    # Insert item at position
                    pObj = insert_at_position(entry.item, position)

                    # update ListEntry Obj
                    entry.approver = info.context.user
                    entry.position = pObj
                    entry.save()
                    return True
                # if rejected (i.e. isApproved=False), delete the entry
                else:
                    entry.item.delete()
                    return True
            else:
                raise APIException('Entry already approved',
                                   code='ALREADY_APPROVED')
        except ListEntry.DoesNotExist:
            raise APIException('Entry not found', code='ENTRY_NOT_FOUND')
Example #2
0
 def mutate(self, info, username):
     if username == info.context.user.username:
         raise APIException('User cannot follow self.',
                            code='CANNOT_FOLLOW_SELF')
     if UserSubscription.objects.filter(
             user__username=username,
             subscriber=info.context.user).exists():
         raise APIException('Already following User',
                            code='ALREADY_FOLLOWING_USER')
     else:
         try:
             user = User.objects.get(username=username)
             if not User.isProfilePrivate:
                 raise APIException(
                     'Respondent profile is public, directly follow the user.',
                     code='PUBLIC_PROFILE')
             if FollowUserRequest.objects.get(requester=info.context.user,
                                              respondent=user).exists():
                 raise APIException('Request already sent to the user.',
                                    code='ALREADY_REQUESTED')
             FollowUserRequest.objects.create(requester=info.context.user,
                                              respondent=user)
             return True
         except User.DoesNotExist:
             raise APIException('User does not exist.',
                                code='USER_DOES_NOT_EXIST')
Example #3
0
    def resolve_list(self, info, slug, username=None, **kwargs):
        try:
            if username is not None:
                listObj = List.objects.get(slug=slug, curator__username=username)
            else:
                listObj = List.objects.get(slug=slug)
            if listObj.isActive:
                if not listObj.isPrivate:
                    return listObj
                else:
                    user = info.context.user
                    if user is None:
                        raise APIException("The list is private. Login required to view the list", code='LOGIN_REQUIRED')
                    # @todo check if user is following owner, and owner allowed user
                    try:
                        UserSubscription.objects.get(user=listObj.curator, subscriber=user)
                        return listObj
                    except UserSubscription.DoesNotExist:
                        raise APIException("The list is private, you need to subscription required to view this list", code='NO_SUBSCRIPTION')
            else:
                # @todo find reason and return exact reason for being inactive
                raise APIException("The list has been taken down or removed.", code='LIST_INACTIVE')

        except List.DoesNotExist:
            raise APIException("The list queried does not exit", code='LIST_NOT_FOUND')
 def mutate(self, info, input):
     try:
         user = User.objects.get(
             Q(username=input.username) | Q(email=input.email))
         if user.username == input.username:
             raise APIException('Username already taken.',
                                code='USERNAME_TAKEN')
         raise APIException('An account with this email already exist.',
                            code='EMAIL_IN_USE')
     except User.DoesNotExist:
         username = input.username if input.username is not None else generate_username_from_email(
             input.email)
         password = input.password if input.password is not None else generate_password(
         )
         user = User.objects.create(
             first_name=input.firstName
             if input.firstName is not None else username,
             last_name=input.lastName if input.lastName is not None else '',
             email=input.email,
             username=username,
         )
         user.set_password(password)
         user.save()
         return AccountCreationResponse(
             returning=user,
             generatedPassword=password if input.password is None else None,
         )
Example #5
0
 def mutate(self, info, list):
     try:
         listObj = List.objects.get(slug=list.slug)
         if listObj.cover:
             listObj.cover = None
             listObj.save()
         else:
             raise APIException('List does not have a cover',
                                code="COVER_DOES_NOT_EXITS")
         return True
     except List.DoesNotExist:
         raise APIException('List not found.', code="LIST_DOES_NOT_EXIST")
Example #6
0
 def resolve_itemPoll(self, info, itemID):
     try:
         item = Item.objects.get(id=itemID)
         if item.pollOptions:
             return Poll(hasAnswer=item.correctOption is not None,
                         totalEntries=UserPollChoice.objects.filter(
                             item=item).count(),
                         options=item.pollOptions.all())
         else:
             raise APIException("Item does not have a poll",
                                code="ITEM_HAS_NO_POLL")
     except Item.DoesNotExist:
         raise APIException("Item does not exist", code="INVALID_ITEM")
Example #7
0
 def mutate(self, info, id):
     try:
         itemObj = Item.objects.get(id=id)
         try:
             Vote.objects.get(item=itemObj,
                              voter=info.context.user).delete()
             return True
         except Vote.DoesNotExist:
             raise APIException('Vote does not exist',
                                code='VOTE_DOES_NOT_EXIST')
     except Item.DoesNotExist:
         raise APIException('Item does not exist',
                            code='ITEM_DOES_NOT_EXIST')
Example #8
0
 def mutate(self, info, list):
     if info.context.FILES is not None:
         if 'cover' in info.context.FILES:
             try:
                 listObj = List.objects.get(slug=list.slug)
                 listObj.cover = info.context.FILES['cover']
                 listObj.save()
                 return True
             except List.DoesNotExist:
                 raise APIException('List not found.',
                                    code="LIST_DOES_NOT_EXIST")
         return False
     else:
         raise APIException("File not attached", code="FILE_NOT_ATTACHED")
Example #9
0
 def mutate(self, info, list, itemID):
     try:
         listObj = List.objects.get(slug=list.slug)
         if listObj.isVotable:
             try:
                 ListVote.objects.get(list=listObj,
                                      voter=info.context.user,
                                      item_id=itemID).delete()
             except ListVote.DoesNotExist:
                 raise APIException("User has not voted", code="NOT_VOTED")
         else:
             raise APIException("List cannot be voted upon",
                                code="NOT_VOTABLE")
     except List.DoesNotExist:
         raise APIException('List not found.', code="LIST_DOES_NOT_EXIST")
Example #10
0
def insert_at_position(i, pos):
    listObj = i.list
    if pos == 1:
        position = Position.objects.create(
            item=i,
            list=i.list,
            next=listObj.firstItem,
        )
        listObj.firstItem = i
        listObj.save()
    else:
        counter = 1
        try:
            itemPos = Position.objects.get(list=listObj,
                                           item=listObj.firstItem)
            while counter + 1 != pos:
                itemPos = Position.objects.get(list=listObj, item=itemPos.next)
                counter += 1
            prevPos = itemPos
            nextItem = itemPos.next
            position = Position.objects.create(
                item=i,
                list=i.list,
                next=nextItem,
            )
            prevPos.next = i
            prevPos.save()

        except Position.DoesNotExist:
            raise APIException(
                "Position of items of this list cannot be determined.",
                code='LIST_CORRUPTED')
    return position
Example #11
0
 def wrap(*args, **kwargs):
     slug = kwargs.get('list').get('slug')
     listObj = List.objects.get(slug=slug)
     if listObj.acceptEntries:
         return func(*args, **kwargs)
     raise APIException('You cannot make contributions to this list',
                        code='ENTRIES_NOT_ACCEPTED')
Example #12
0
 def resolve_items(self, info, count=10, starting="-1"):
     from list.models import Position
     try:
         items = []
         counter = 0
         ItemPos = None
         while (ItemPos is None
                or ItemPos.next is not None) and counter < count:
             if ItemPos is None:
                 if starting != "-1":
                     ItemPos = Position.objects.get(list=self,
                                                    item_id=int(starting))
                 else:
                     listObj = ListModel.objects.get(slug=self.slug)
                     ItemPos = Position.objects.get(list=self,
                                                    item=listObj.firstItem)
             else:
                 ItemPos = Position.objects.get(list=self,
                                                item=ItemPos.next)
             counter += 1
             items.append({
                 "position":
                 counter if starting == "-1" else None,
                 "id":
                 ItemPos.item.id,
                 "item":
                 ItemPos.item,
                 "nextItem":
                 ItemPos.next.id if ItemPos.next else None,
             })
         return items
     except Position.DoesNotExist:
         raise APIException('List item positions cannot be determined.',
                            code='POSITION_CORRUPTED')
Example #13
0
 def mutate(self, info, list):
     try:
         listObj = List.objects.get(slug=list.slug)
         listObj.delete()
     except List.DoesNotExist:
         raise APIException('List not found.', code="LIST_DOES_NOT_EXIST")
     return False
Example #14
0
 def resolve_user(self, info, username, **kwargs):
     try:
         user = User.objects.get(username=username)
         # @todo check if user is active
         return user
     except User.DoesNotExist:
         raise APIException("The user queried does not exit",
                            code='LIST_NOT_FOUND')
Example #15
0
 def resolve_isFollower(self, info, username):
     try:
         user = User.objects.get(username=username, is_active=True)
         return UserSubscription.objects.filter(
             user=user, subscriber=info.context.user).exists()
     except User.DoesNotExist:
         raise APIException("Invalid username provided",
                            code='INVALID_USERNAME')
Example #16
0
 def mutate(self, info, list, direction, id):
     try:
         item = Item.objects.get(id=id)
         if direction == 1:
             return move_item_up(item)
         elif direction == 0:
             return move_item_down(item)
         else:
             raise APIException('Direction should be either up or down',
                                code='INVALID_DIRECTION')
     except Item.DoesNotExist:
         raise APIException('Item with the provided key does not exist.',
                            code='ITEM_DOES_NOT_EXIST')
     except Item.MultipleObjectsReturned:
         # @todo report incident
         raise APIException(
             'Database Integrity Error, multiple items with same key found.',
             code='DATABASE_ERROR')
 def mutate(self, info, oldPassword, newPassword):
     user = info.context.user
     if user.check_password(raw_password=oldPassword):
         user.set_password(raw_password=newPassword)
         user.save()
         return True
     else:
         raise APIException('Invalid old password',
                            code='INVALID_OLD_PASSWORD')
Example #18
0
 def resolve_isUsernameAvailable(self, info, username, **kwargs):
     if username is not None and len(username) > 0:
         try:
             User.objects.get(username=username)
             return False
         except User.DoesNotExist:
             return True
     else:
         raise APIException("Invalid username provided",
                            code='INVALID_USERNAME')
Example #19
0
 def mutate(self, info, username, subject=''):
     if username == info.context.user.username:
         raise APIException('User cannot request self.',
                            code='CANNOT_REQUEST_SELF')
     else:
         try:
             user = User.objects.get(username=username)
             if not UserSubscription.objects.filter(
                     user=user, subscriber=info.context.user).exists():
                 raise APIException(
                     'User can only request lists from people following.',
                     code='NOT_FOLLOWING')
             ListRequest.objects.create(requester=info.context.user,
                                        respondent=user,
                                        subject=subject)
             return True
         except User.DoesNotExist:
             raise APIException('User does not exist.',
                                code='USER_DOES_NOT_EXIST')
Example #20
0
 def mutate(self, info):
     user = info.context.user
     if info.context.FILES is not None:
         if 'userAvatar' in info.context.FILES:
             user.avatar = info.context.FILES['userAvatar']
         if 'userCover' in info.context.FILES:
             user.cover = info.context.FILES['userCover']
         user.save()
     else:
         raise APIException("File not attached", code="FILE_NOT_ATTACHED")
Example #21
0
 def mutate(self, info, properties):
     if info.context.FILES is not None and 'media' in info.context.FILES:
         user = info.context.user
         return Media.objects.create(
             type=properties.type,
             aspect=decimal.Decimal(properties.aspect),
             uploader=user,
             asset=info.context.FILES['media']
         )
     else:
         raise APIException('No file attached', code='FILE_NOT_ATTACHED')
Example #22
0
 def mutate(self, info, optionID, itemID):
     try:
         item = Item.objects.get(id=itemID)
         try:
             optionSelected = PollOption.objects.get(id=optionID)
             if item.correctOption is not None:
                 if item.correctOption == optionSelected:
                     return PollQuestionResult(
                         isCorrect=True, correctOption=item.correctOption)
                 else:
                     return PollQuestionResult(
                         isCorrect=False, correctOption=item.correctOption)
             else:
                 raise APIException('Poll does not have right answer.',
                                    code='NO_ANSWER')
         except PollOption.DoesNotExist:
             raise APIException('Option does not exist.',
                                code='INVALID_OPTION')
     except Item.DoesNotExist:
         raise APIException('Item does not exist.', code='INVALID_ITEM')
Example #23
0
 def mutate(self, info, username):
     if UserSubscription.objects.filter(
             user__username=username,
             subscriber=info.context.user).exists():
         UserSubscription.objects.get(
             user__username=username,
             subscriber=info.context.user).delete()
         return True
     else:
         raise APIException('User is not being followed.',
                            code='NOT_FOLLOWING_USER')
Example #24
0
 def wrap(*args, **kwargs):
     info = next(arg for arg in args if isinstance(arg, ResolveInfo))
     user = info.context.user
     slug = kwargs.get('list').get('slug')
     listObj = List.objects.get(slug=slug)
     if listObj.curator == user:
         return func(*args, **kwargs)
     elif Collaborator.objects.filter(list=listObj, user=user).exists():
         return func(*args, **kwargs)
     raise APIException(
         'You dont have permission to make changes to this list',
         code='PERMISSION_DENIED')
Example #25
0
 def mutate(self, info, input):
     try:
         if input.username == info.context.user.username:
             user = info.context.user
             if hasattr(input, "firstName") and input.firstName is not None:
                 user.first_name = input.firstName
             if hasattr(input, "lastName") and input.lastName is not None:
                 user.last_name = input.lastName
             if hasattr(input, "bio") and input.bio is not None:
                 user.bio = input.bio
             if hasattr(input, "url") and input.url is not None:
                 user.url = input.url
             user.save()
             return AccountUpdationResponse(returning=user, )
         else:
             raise APIException(
                 'You can only update your own profile using this API',
                 code='USER_MISMATCH')
     except User.DoesNotExist:
         raise APIException('User matching email does not exist',
                            code='DOES_NOT_EXIST')
Example #26
0
 def mutate(self, info, optionID, itemID):
     try:
         item = Item.objects.get(id=itemID)
         try:
             poll = UserPollChoice.objects.get(
                 user=info.context.user,
                 item=item,
             )
             if poll.choice.id != optionID:
                 poll.choice = PollOption.objects.get(id=optionID)
                 poll.save()
                 return True
             else:
                 raise APIException('Already recorded',
                                    code="ALREADY_RECORDED")
         except UserPollChoice.DoesNotExist:
             UserPollChoice.objects.create(user=info.context.user,
                                           item=item,
                                           choice_id=optionID)
             return True
     except Item.DoesNotExist:
         raise APIException('Item does not exist.', code='INVALID_ITEM')
Example #27
0
 def mutate(self, info, username):
     if username == info.context.user.username:
         raise APIException('User cannot follow self.',
                            code='CANNOT_FOLLOW_SELF')
     if UserSubscription.objects.filter(
             user__username=username,
             subscriber=info.context.user).exists():
         raise APIException('Already following User',
                            code='ALREADY_FOLLOWING_USER')
     else:
         try:
             user = User.objects.get(username=username)
             if user.isProfilePrivate:
                 raise APIException(
                     'User profile is private, request for following.',
                     code='PRIVATE_PROFILE')
             UserSubscription.objects.create(user=user,
                                             subscriber=info.context.user)
             return True
         except User.DoesNotExist:
             raise APIException('User does not exist.',
                                code='USER_DOES_NOT_EXIST')
Example #28
0
 def wrap(*args, **kwargs):
     info = next(arg for arg in args if isinstance(arg, ResolveInfo))
     user = info.context.user
     mediaID = kwargs.get('id')
     itemMediaObj = ItemMedia.objects.get(media__id=mediaID)
     if itemMediaObj.media.uploader == user:
         return func(*args, **kwargs)
     elif itemMediaObj.item.list.curator == user:
         return func(*args, **kwargs)
     elif Collaborator.objects.filter(list=itemMediaObj.item.list,
                                      user=user).exists():
         return func(*args, **kwargs)
     raise APIException('You dont have permission to delete this media',
                        code='PERMISSION_DENIED')
Example #29
0
 def mutate(self, info, list, itemID):
     try:
         listObj = List.objects.get(slug=list.slug)
         if listObj.isVotable:
             try:
                 vote = ListVote.objects.get(list=listObj,
                                             voter=info.context.user)
                 if vote.item.id == itemID:
                     raise APIException("Already Voted",
                                        code='ALREADY_VOTED')
                 else:
                     vote.item_id = itemID
                     vote.save()
                     return True
             except ListVote.DoesNotExist:
                 ListVote.objects.create(list=listObj,
                                         voter=info.context.user,
                                         item_id=itemID)
                 return True
         else:
             raise APIException("List cannot be voted upon",
                                code="NOT_VOTABLE")
     except List.DoesNotExist:
         raise APIException('List not found.', code="LIST_DOES_NOT_EXIST")
Example #30
0
 def resolve_relatedLists(self, info, list):
     lists = List.objects.filter((Q(slug=list.slug) | Q(id=list.id)))
     if lists.count() == 1:
         l = lists.first()
         relatedListByUser = List.objects.filter(
             Q(curator=l.curator)
         ).exclude(id=l.id)
         relatedListByTopics = List.objects.filter(
             Q(topic=l.topic)
         ).exclude(id=l.id)
         qs = relatedListByUser.intersection(relatedListByTopics)
         if qs.count() < 5:
             qs = qs.union(relatedListByTopics)
         if qs.count() < 5:
             qs = qs.union(relatedListByUser)
         return qs[:5]
     else:
         raise APIException('Invalid list passed', code="INVALID_LIST")