Ejemplo n.º 1
0
def game(request,id):
	game_exists = Game.objects.filter(id=id).count()
	if game_exists:
		game = Game.objects.get(id=id)
		print action_object_stream(game)

		comment_form = CommentForm(initial={'user_id': request.user.id, 'game_id':game.id})
	
		# Check whether the game has already happened
		if game.timeStart.replace(tzinfo=None) < datetime.datetime.now():
			passed_game = True
		else:
			passed_game = False

		# Check if the game player has maxed
		maxed = False
		if game.cap:
			if game.users.count() >= game.cap:
				maxed = True


		# Check if user is the creator of the game
		is_creator = False
		if request.user == game.creator:
			is_creator = True

		# Check if user has joined the game
		joined = False
		if request.user in game.users.all() or is_creator:
			joined = True

		connected_to_instagram = False
		if InstagramInfo.objects.filter(user=request.user).count():
			connected_to_instagram = True

		return render(request, 'game.html', {
			'game':game, 
			'joined':joined, 
			'is_creator':is_creator, 
			'user':request.user, 
			'game_exists':game_exists, 
			'passed_game':passed_game, 
			'maxed':maxed, 
			'comment_form':comment_form, 
			'connected_to_instagram':connected_to_instagram,
			'instagramID' : INSTAGRAM_ID,
			'instagramSecret' : INSTAGRAM_SECRET,
			'redirectURL' : REDIRECT_URL,
		})
	else:
		return render(request, 'game.html', {'game_exists':game_exists})
Ejemplo n.º 2
0
def taskDetail(request: HttpRequest, projectid, taskGroupId, taskid):
    if not request.user.is_authenticated:
        return redirect('projectMgr:homepage')

    '''

    :param request:
    :return:
    '''
    thisProject = models.Project.objects.get(id=projectid)
    thisTaskGroup = models.TaskGroup.objects.get(id=taskGroupId)
    thisTask = models.Task.objects.get(id=taskid)
    thisUser = request.user

    commentForm = forms.createComment
    commentSet = thisTask.comment.all()
    stream = action_object_stream(thisTask)

    '''
    need multiple forms to fill in the details of the task.
    1.description
    2.attachment
    3.comment
    '''

    return render(request, 'projectMgr/taskDetail.html',
                  {'project': thisProject, 'taskGroup': thisTaskGroup, 'task': thisTask, 'commentForm': commentForm,
                   'commentSet': commentSet, 'thisUser': thisUser, 'stream':stream})

    pass
Ejemplo n.º 3
0
def get_history(nh):
    """
    :param nh: NodeHandle
    :return: List of ActStream actions
    """
    history = list(action_object_stream(nh)) + list(target_stream(nh))
    return sorted(history, key=lambda action: action.timestamp, reverse=True)
Ejemplo n.º 4
0
 def get_context_data(self, **kwargs):
     # Call the base implementation first to get a context
     context = super(PostDetailView, self).get_context_data(**kwargs)
     post = self.noun
     context['post'] = post
     context['project'] = post.project
     context['medias'] = post.get_medias()
     if self.noun.submitted != True:
         context['publish_url'] = cm.PostSubmitVerb(self.noun).get_url()
     context['available_verbs'] = post.get_available_verbs(self.request.user)
     stream = []
     for a in action_object_stream(post):
         stream.append(a)
     for m in post.media.all():
         for a in action_object_stream(m):
             stream.append(a)
     context['stream'] = stream
     return context
Ejemplo n.º 5
0
def new_books(request, delta=1):
    delta = int(delta)
    days_ago = date.today() - timedelta(days=delta)
    ctype = ContentType.objects.get_for_model(User)
    actor = request.user
    created_streams = User.objects.get(username="******")
    action_list = action_object_stream(created_streams, timestamp__gte=days_ago)

    variables = {"ctype": ctype, "actor": actor, "action_list": action_list, "delta": delta}

    return render(request, "activity/new_actions.html", variables)
Ejemplo n.º 6
0
def lireSuffrage(request, slug):
    suffrage = get_object_or_404(Suffrage, slug=slug)
    if not suffrage.est_autorise(request.user):
        return render(
            request,
            'notMembre.html',
        )

    try:
        voteCourant = Vote.objects.get(auteur=request.user, suffrage=suffrage)
    except:
        voteCourant = None

    questions_b, questions_m = suffrage.questions

    commentaires = Commentaire.objects.filter(
        suffrage=suffrage).order_by("date_creation")
    actions = action_object_stream(suffrage)

    form = CommentaireSuffrageForm(request.POST or None)
    if form.is_valid():
        comment = form.save(commit=False)
        if comment:
            comment.suffrage = suffrage
            comment.auteur_comm = request.user
            suffrage.date_dernierMessage = comment.date_creation
            suffrage.dernierMessage = (
                "(" + str(comment.auteur_comm) + ") " +
                str(strip_tags(comment.commentaire).replace('&nspb',
                                                            ' ')))[:96] + "..."
            suffrage.save()
            comment.save()
            url = suffrage.get_absolute_url() + "#idConversation"
            suffix = "_" + suffrage.asso.abreviation
            #action.send(request.user, verb='suffrage_message' + suffix, action_object=suffrage, url=url,
            #           description="a réagi au suffrage: '%s'" % suffrage.question)

        return redirect(request.path)

    return render(
        request,
        'vote/lireSuffrage.html',
        {
            'suffrage': suffrage,
            'form': form,
            'commentaires': commentaires,
            'actions': actions,
            'questions_b': questions_b,
            'questions_m': questions_m,
            'vote': voteCourant
        },
    )
Ejemplo n.º 7
0
def get_actions_following(request, content_type_id, object_id):
    activity_queryset = None
    ctype 			  = get_object_or_404(ContentType, pk=content_type_id)
    actor 			  = get_object_or_404(ctype.model_class(), pk=object_id)

    if activity_queryset is None:    	
        activity_queryset = actor.actor_actions.public()

        for followedObject in Follow.objects.following(user=actor):
            if followedObject:
                obj_content_type 	  = ContentType.objects.get_for_model(followedObject)
                followObject     	  = Follow.objects.get(user=actor, content_type=obj_content_type, object_id=followedObject.pk )
                if followObject:
                    stream 		 	  = followedObject.actor_actions.public()#timestamp__gte=followObject.started)
                    activity_queryset = activity_queryset | stream

                if not isinstance(followedObject, User) and not isinstance(followedObject, BlogPost):           
                    _follow    = _Follow.objects.get_follows(followedObject)
                    if _follow:
                        follow = None     
                        try:
                            follow = _follow.get(user=actor)
                        except (MultipleObjectsReturned, _Follow.DoesNotExist) as e:
                            if isinstance(e, MultipleObjectsReturned):
                                follow = _follow.filter(user=actor)[0]
                                pass
                            else:
                                follow = None
                                pass

                        if follow:        
                            stream 			  = models.action_object_stream(followedObject)#, timestamp__gte = follow.datetime )
                            activity_queryset = activity_queryset | stream 
                            stream 			  = models.target_stream(followedObject)#, timestamp__gte = follow.datetime )
                            activity_queryset = activity_queryset | stream
        
        allowed_verbs_for_user_in_common_feed = [settings.SAID_VERB, settings.SHARE_VERB, settings.DEAL_POST_VERB, settings.WISH_POST_VERB]# settings.REVIEW_POST_VERB, ]
        user_ctype = ContentType.objects.get_for_model(request.user)
        activity_queryset = activity_queryset.exclude(~Q(verb__in=allowed_verbs_for_user_in_common_feed) & Q(actor_content_type=user_ctype, actor_object_id=request.user.id) )

        followed_blog_posts = utils.get_following_vendors_for_user(request.user)

        blogPostContentType = ContentType.objects.get_for_model(BlogPost)
        if followed_blog_posts:
            activity_queryset = activity_queryset.exclude(Q(verb=settings.REVIEW_POST_VERB) & Q(action_object_content_type=blogPostContentType) & Q(action_object_object_id__in=[blogpost.id for blogpost in followed_blog_posts]))

        activity_queryset = activity_queryset.order_by('-timestamp')

    return activity_queryset
Ejemplo n.º 8
0
    def test_lawyer_patch(self):
        self.client.login(username=self.lawyer.username, password=self.password)

        data = {
            'email': '*****@*****.**',
            'first_name': 'Bob',
            'last_name': 'Da hoon',
            'message': 'Bob you are being added here please provide me with a monkey!',
        }

        resp = self.client.patch(self.endpoint, json.dumps(data), content_type='application/json')

        self.assertEqual(resp.status_code, 200)  # ok patch accepted
        json_data = json.loads(resp.content)

        new_item = Item.objects.requested(matter=self.matter, slug=json_data['slug']).first()

        self.assertEqual(json_data['name'], new_item.name)

        # we should have this new item in the standard item objects
        self.assertTrue(new_item in Item.objects.filter(matter=self.matter))

        outbox = mail.outbox
        self.assertEqual(len(outbox), 1)

        email = outbox[0]
        self.assertEqual(email.subject, u'[ACTION REQUIRED] Request to provide a document')
        self.assertEqual(email.recipients(), [u'*****@*****.**'])
        # test the custom message is present
        self.assertTrue(data.get('message') in email.body)

        # this should have created a new revision upload invite
        stream = action_object_stream(self.item)
        self.assertEqual(stream[0].data['override_message'],
                         u'Lawyër Tëst requested a file from Bob Da hoon for Test Item No. 1')

        # now we patch again to remove the revision_request and see if the activity is created
        data = {
            'is_requested': False,
            'responsible_party': None
        }
        self.client.patch(self.endpoint, json.dumps(data), content_type='application/json')
        stream = target_stream(self.matter)
        self.assertEqual(stream[0].data['override_message'],
                         u'Lawyër Tëst canceled their request for Bob Da hoon to provide a document on Test Item No. 1')
Ejemplo n.º 9
0
 def get_context_data(self, **kwargs):
     print self.object
     actionstream = action_object_stream(self.object)
     form_class = self.get_form_class()
     form = self.get_form(form_class)
     formpart = PartForm()
     formvenue = VenueForm()
     formrecipe = RecipeForm()
     print actionstream
     context = {
         'form': form,
         'formh': formpart,
         'formn': formpart,
         'formw': formpart,
         'formv': formvenue,
         'actstream': actionstream,
         'formr': formrecipe
     }
     context.update(kwargs)
     return super(MealDetailView, self).get_context_data(**context)
Ejemplo n.º 10
0
def actstream_following(request, content_type_id, object_id):
    from itertools import chain
    import operator
    ctype = get_object_or_404(ContentType, pk=content_type_id)
    actor = get_object_or_404(ctype.model_class(), pk=object_id)
    activity = actor.actor_actions.public()
    
    for followedActor in Follow.objects.following(user=actor):
        target_content_type = ContentType.objects.get_for_model(followedActor)
        prevFollowActions = Action.objects.all().filter(actor_content_type=ctype, actor_object_id=object_id,verb=settings.FOLLOW_VERB, target_content_type=target_content_type, target_object_id = followedActor.pk ).order_by('-pk')
        followAction = None
        if prevFollowActions:
            followAction =  prevFollowActions[0]
        if followAction:
            stream = followedActor.actor_actions.public(timestamp__gte = followAction.timestamp)
            activity = activity | stream

        if not isinstance(followedActor, User):
            _follow = _Follow.objects.get_follows(followedActor)
            if _follow:
                try:     
                    follow = _follow.get(user=actor)
                except (MultipleObjectsReturned, _Follow.DoesNotExist) as e:
                    if isinstance(e, MultipleObjectsReturned):
                        follow = _follow.filter(user=actor)[0]
                        pass
                    else:
                        follow = None
                        pass
                        
                if follow:        
                    stream = models.action_object_stream(followedActor, timestamp__gte = follow.datetime )
                    activity = activity | stream 
                    stream = models.target_stream(followedActor, timestamp__gte = follow.datetime )
                    activity = activity | stream
    activity =  activity.order_by('-timestamp')

    return render_to_response(('actstream/actor_feed.html', 'activity/actor_feed.html'), {
       'action_list': activity, 'actor': actor,
       'ctype': ctype, 'sIndex':0
    }, context_instance=RequestContext(request))
Ejemplo n.º 11
0
 def items(self, obj):
     i = action_object_stream(obj)
     if i:
         return i[:30]
     return []
Ejemplo n.º 12
0
    def test_object_activity(self):
        """Ensure that there is an activity stream for a certain post."""
        from actstream.models import action_object_stream

        # Verify there is activity for 'posting' and 'following' the post
        self.assertEqual(2, len(action_object_stream(self.post)))
Ejemplo n.º 13
0
def _all_related(obj):

    # TODO move somewhere else
    registry.register(User)

    return actor_stream(obj) | action_object_stream(obj) | target_stream(obj)
Ejemplo n.º 14
0
def activity_register(_user, _action_object):
    """
    Registers and activity when an object is saved. Takes a diff with a
    previous version of edited objects, put it as message content in a
    timeline, uses the verbs 'created' or 'edited' for actions on actstream.
    """
    from lxml.html.diff import htmldiff

    from django.db.models.loading import get_model
    from django.forms import ValidationError
    from django.forms.models import model_to_dict
    from django.template.loader import render_to_string

    from actstream import action
    from actstream.actions import follow, is_following
    from actstream.models import action_object_stream

    klass = _action_object.__class__.__name__.lower()
    if klass not in ['problem', 'criteria', 'idea', 'alternative', 'comment']:
        raise forms.ValidationError(_('Wrong object type'))

    # Last activity
    last = (action_object_stream(_action_object)[:1] or [None])[0]
    _content_old = render_to_string('diffbase_' + klass +
                                    '.html', {klass: last}) if last else ''
    _content = render_to_string('diffbase_' + klass + '.html',
                                {klass: _action_object})
    _emsg = _action_object.edit_message if hasattr(_action_object,
                                                   'edit_message') else ''
    _diff = htmldiff(_content_old, _content)

    # Set target problem
    if klass in ['comment']:
        if getattr(_action_object, 'problem'):
            _target = getattr(_action_object, 'problem')
        else:
            for attr in ['criteria', 'idea', 'alternative']:
                if getattr(_action_object, attr):
                    _target = getattr(_action_object, attr)
                    break
            _target = getattr(_target, 'problem')
    elif klass in ['criteria', 'idea', 'alternative']:
        _target = getattr(_action_object, 'problem')
    elif klass in ['problem']:
        _target = _action_object

    # Don't do anything if the problem or the action object is a draft
    if hasattr(_action_object,
               'published') and not getattr(_action_object, 'published'):
        return None

    # Set verb
    _verb = 'edited'
    if klass == 'comment':
        _verb = 'commented'
        _notification = True
    elif not last:
        _verb = 'created'
        _notification = True

    # Add user as collaborator
    _target.collaborator.add(_user)
    _follow = _target

    # Action
    a = action.send(_user,
                    verb=_verb,
                    action_object=_action_object,
                    target=_target)
    a[0][1].data = {
        'diff': _diff,
        'content': _content,
        'edit_message': _emsg,
        'object': model_to_dict(_action_object)
    }
    a[0][1].save()
    activity_count(_target)
    follow(_user, _follow,
           actor_only=False) if not is_following(_user, _follow) else None
Ejemplo n.º 15
0
 def items(self, obj):
     i = action_object_stream(obj)
     if i:
         return i[:30]
     return []
Ejemplo n.º 16
0
def activity_register(_user, _action_object):
    """
    Registers and activity when an object is saved. Takes a diff with a
    previous version of edited objects, put it as message content in a
    timeline, uses the verbs 'created' or 'edited' for actions on actstream.
    """
    from lxml.html.diff import htmldiff

    from django.db.models.loading import get_model
    from django.forms import ValidationError
    from django.forms.models import model_to_dict
    from django.template.loader import render_to_string

    from actstream import action
    from actstream.actions import follow, is_following
    from actstream.models import action_object_stream

    klass = _action_object.__class__.__name__.lower()
    if klass not in ['problem', 'criteria', 'idea', 'alternative', 'comment']:
        raise forms.ValidationError(_('Wrong object type'))

    # Last activity
    last = (action_object_stream(_action_object)[:1] or [None])[0]
    _content_old = render_to_string('diffbase_' + klass + '.html', {klass: last}) if last else ''
    _content = render_to_string('diffbase_' + klass + '.html', {klass: _action_object})
    _emsg = _action_object.edit_message if hasattr(_action_object, 'edit_message') else ''
    _diff = htmldiff(_content_old, _content)

    # Set target problem
    if klass in ['comment']:
        if getattr(_action_object, 'problem'):
            _target = getattr(_action_object, 'problem')
        else:
            for attr in ['criteria', 'idea', 'alternative']:
                if getattr(_action_object, attr):
                    _target = getattr(_action_object, attr)
                    break
            _target = getattr(_target, 'problem')
    elif klass in ['criteria', 'idea', 'alternative']:
        _target = getattr(_action_object, 'problem')
    elif klass in ['problem']:
        _target = _action_object

    # Don't do anything if the problem or the action object is a draft
    if hasattr(_action_object, 'published') and not getattr(_action_object, 'published'):
        return None

    # Set verb
    _verb = 'edited'
    if klass == 'comment':
        _verb = 'commented'
        _notification = True
    elif not last:
        _verb = 'created'
        _notification = True

    # Add user as collaborator
    _target.collaborator.add(_user)
    _follow = _target

    # Action
    a = action.send(_user, verb=_verb, action_object=_action_object, target=_target)
    a[0][1].data = { 'diff': _diff, 'content': _content,
        'edit_message': _emsg, 'object': model_to_dict(_action_object)}
    a[0][1].save()
    activity_count(_target)
    follow(_user, _follow, actor_only=False) if not is_following(_user, _follow) else None
Ejemplo n.º 17
0
def deleteObject(request, content_type_id, object_id ):
    error_codes = []
    #if not request.is_ajax():
    #   error_codes.append(settings.AJAX_ONLY_SUPPORT)
    #   return json_error_response(error_codes)

    try:
        ctype = ContentType.objects.get(pk=content_type_id)
        object = ctype.model_class().objects.get(pk=object_id)
    except:
        error_codes.append(settings.OBJECT_DOES_NOT_EXIST)
        return json_error_response(error_codes)

    owner = get_object_owner_helper(content_type_id, object_id)

    """
        Check whehter use is authorized to delete the object.
    """
    if request.user != owner:
        error_codes.append(settings.UNAUTHORIZED_OPERATION)
        return json_error_response(error_codes)

    if object:
        """
        Delete related activities and actstream follow objects.
        """            
        stream = models.action_object_stream(object)
        activity = stream 
        stream = models.target_stream(object)
        activity = activity | stream 
            
        if activity:
            activity.delete()

        _followList = _Follow.objects.filter(content_type=ctype, object_id=str(object_id))
        for _followObj in _followList:
            _followObj.delete()

        """
            Delete django-follow objects.
        """
        follow = None
        try:
            follow = Follow.objects.get_follows(object)
        except:
            pass

        if follow:
            follow.delete() 

        """
            Delete voting objects.
        """
        voteObjects = Vote.objects.filter(content_type=ctype,
                         object_id=object._get_pk_val() )
        if voteObjects:
            voteObjects.delete()

        """
           Delete comments associated with the object.
        """
        comments_queryset = object.comments.all()
        for comment in comments_queryset:
        	ctype_id = ContentType.objects.get_for_model(comment).pk
        	deleteObject(request, ctype_id, comment.pk)
            #comments_queryset.delete()

        """
            Delete related objects for Reviews.
        """

        if isinstance(object, Review):
            try:
                requiredReviewRatingObj = RequiredReviewRating.objects.get(commentid=object._get_pk_val())
            except:
                requiredReviewRatingObj = None
                pass

            if requiredReviewRatingObj:
                requiredReviewRatingCtype = ContentType.objects.get_for_model(requiredReviewRatingObj)
                requiredReviewRatingVoteObjects = Vote.objects.filter(content_type=requiredReviewRatingCtype,
                                                                      object_id=requiredReviewRatingObj._get_pk_val() )
        
                if requiredReviewRatingVoteObjects:
                    requiredReviewRatingVoteObjects.delete()
                requiredReviewRatingObj.delete()
            try:
                OptionalReviewRatingObj = OptionalReviewRating.objects.get(commentid=object._get_pk_val())
            except:
                OptionalReviewRatingObj = None
                pass

            if OptionalReviewRatingObj:
                OptionalReviewRatingObj.delete()

        elif isinstance(object, GenericWish):
            if object.wishimage:
                try:
                    deleteFile(object.wishimage.image)
                except:
                    pass
                object.wishimage.delete()

        """
            Finally nuke the actual object.
        """
        object.delete()           

        return json_success_response()