Completed
Push — master ( 6b05c7...3c8f2c )
by
unknown
8s
created

unfollow()   B

Complexity

Conditions 4

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
c 0
b 0
f 0
dl 0
loc 29
rs 8.5806
1
import datetime
2
3
from django.utils.translation import ugettext_lazy as _
4
from django.utils.six import text_type
5
from django.contrib.contenttypes.models import ContentType
6
7
from actstream import settings
8
from actstream.signals import action
9
from actstream.registry import check
10
from actstream.compat import get_model
11
12
try:
13
    from django.utils import timezone
14
15
    now = timezone.now
16
except ImportError:
17
    now = datetime.datetime.now
18
19
20
def follow(user, obj, send_action=True, actor_only=True, flag='', **kwargs):
21
    """
22
    Creates a relationship allowing the object's activities to appear in the
23
    user's stream.
24
25
    Returns the created ``Follow`` instance.
26
27
    If ``send_action`` is ``True`` (the default) then a
28
    ``<user> started following <object>`` action signal is sent.
29
    Extra keyword arguments are passed to the action.send call.
30
31
    If ``actor_only`` is ``True`` (the default) then only actions where the
32
    object is the actor will appear in the user's activity stream. Set to
33
    ``False`` to also include actions where this object is the action_object or
34
    the target.
35
36
    If ``flag`` not an empty string then the relationship would marked by this flag.
37
38
    Example::
39
40
        follow(request.user, group, actor_only=False)
41
        follow(request.user, group, actor_only=False, flag='liking')
42
    """
43
    check(obj)
44
    instance, created = get_model('actstream', 'follow').objects.get_or_create(
45
        user=user, object_id=obj.pk, flag=flag,
46
        content_type=ContentType.objects.get_for_model(obj),
47
        actor_only=actor_only)
48
    if send_action and created:
49
        if not flag:
50
            action.send(user, verb=_('started following'), target=obj, **kwargs)
51
        else:
52
            action.send(user, verb=_('started %s' % flag), target=obj, **kwargs)
53
    return instance
54
55
56
def unfollow(user, obj, send_action=False, flag=''):
57
    """
58
    Removes a "follow" relationship.
59
60
    Set ``send_action`` to ``True`` (``False is default) to also send a
61
    ``<user> stopped following <object>`` action signal.
62
63
    Pass a string value to ``flag`` to determine which type of "follow" relationship you want to remove.
64
65
    Example::
66
67
        unfollow(request.user, other_user)
68
        unfollow(request.user, other_user, flag='watching')
69
    """
70
    check(obj)
71
    qs = get_model('actstream', 'follow').objects.filter(
72
        user=user, object_id=obj.pk,
73
        content_type=ContentType.objects.get_for_model(obj)
74
    )
75
76
    if flag:
77
        qs = qs.filter(flag=flag)
78
    qs.delete()
79
80
    if send_action:
81
        if not flag:
82
            action.send(user, verb=_('stopped following'), target=obj)
83
        else:
84
            action.send(user, verb=_('stopped %s' % flag), target=obj)
85
86
87
def is_following(user, obj, flag=''):
88
    """
89
    Checks if a "follow" relationship exists.
90
91
    Returns True if exists, False otherwise.
92
93
    Pass a string value to ``flag`` to determine which type of "follow" relationship you want to check.
94
95
    Example::
96
97
        is_following(request.user, group)
98
        is_following(request.user, group, flag='liking')
99
    """
100
    check(obj)
101
    qs = get_model('actstream', 'follow').objects.filter(
102
        user=user, object_id=obj.pk,
103
        content_type=ContentType.objects.get_for_model(obj)
104
    )
105
106
    if flag:
107
        qs = qs.filter(flag=flag)
108
109
    return qs.exists()
110
111
112
def action_handler(verb, **kwargs):
113
    """
114
    Handler function to create Action instance upon action signal call.
115
    """
116
    kwargs.pop('signal', None)
117
    actor = kwargs.pop('sender')
118
119
    # We must store the unstranslated string
120
    # If verb is an ugettext_lazyed string, fetch the original string
121
    if hasattr(verb, '_proxy____args'):
122
        verb = verb._proxy____args[0]
123
124
    newaction = get_model('actstream', 'action')(
125
        actor_content_type=ContentType.objects.get_for_model(actor),
126
        actor_object_id=actor.pk,
127
        verb=text_type(verb),
128
        public=bool(kwargs.pop('public', True)),
129
        description=kwargs.pop('description', None),
130
        timestamp=kwargs.pop('timestamp', now())
131
    )
132
133
    for opt in ('target', 'action_object'):
134
        obj = kwargs.pop(opt, None)
135
        if obj is not None:
136
            check(obj)
137
            setattr(newaction, '%s_object_id' % opt, obj.pk)
138
            setattr(newaction, '%s_content_type' % opt,
139
                    ContentType.objects.get_for_model(obj))
140
    if settings.USE_JSONFIELD and len(kwargs):
141
        newaction.data = kwargs
142
    newaction.save(force_insert=True)
143
    return newaction
144