Exemplo n.º 1
0
    def get_context_data(self, **kwargs):
        """
        Include non-sensitive stream api key and a current user feed token
        for specified feed type.
        """
        kwargs = super(FeedActivityContextMixin,
                       self).get_context_data(**kwargs)

        try:
            user = attrgetter(self.user_field)(self)
        except AttributeError:
            user = None

        try:
            activity = attrgetter(self.activity_field)(self)
        except AttributeError:
            activity = None

        if user and not user.is_anonymous:
            feed = feed_manager.get_feed(self.feed_type, user.id)
            kwargs.update({
                'stream_api_key': settings.STREAM_API_KEY,
                'stream_feed_id': user.id,
                'stream_feed_type': self.feed_type,
                'stream_feed_token': feed.get_readonly_token(),
            })
        elif activity:
            feed = feed_manager.get_feed(self.feed_type, activity.id)
            kwargs.update({
                'stream_api_key': settings.STREAM_API_KEY,
                'stream_feed_id': activity.id,
                'stream_feed_type': self.feed_type,
                'stream_feed_token': feed.get_readonly_token(),
            })
        return kwargs
Exemplo n.º 2
0
 def activity_notify(self):
     targets = [feed_manager.get_news_feeds(self.user_id)["flat"]]
     for hashtag in self.parse_hashtags():
         targets.append(feed_manager.get_feed("user", "hash_%s" % hashtag))
     for user in self.parse_mentions():
         targets.append(feed_manager.get_news_feeds(user.id)["flat"])
     return targets
Exemplo n.º 3
0
 def activity_notify(self):
     targets = []
     for hashtag in self.parse_hashtags():
         targets.append(feed_manager.get_feed('hashtag', hashtag))
     for user in self.parse_mentions():
         targets.append(feed_manager.get_news_feeds(user.id)['flat'])
     return targets
Exemplo n.º 4
0
 def activity_notify(self):
     targets = [feed_manager.get_news_feeds(self.user_id)['flat']]
     for hashtag in self.parse_hashtags():
         targets.append(feed_manager.get_feed('user', 'hash_%s' % hashtag))
     for user in self.parse_mentions():
         targets.append(feed_manager.get_news_feeds(user.id)['flat'])
     return targets
Exemplo n.º 5
0
def hashtag(request, hashtag_name):
    hashtag_name = hashtag_name.lower()
    feed = feed_manager.get_feed("user", "hash_%s" % hashtag_name)
    activities = feed.get(limit=25)["results"]

    activities = enricher.enrich_activities(activities)
    context = {"hashtag_name": hashtag_name, "activities": activities}
    return render(request, "stream_twitter/hashtag.html", context)
Exemplo n.º 6
0
def hashtag(request, hashtag_name):
    hashtag_name = hashtag_name.lower()
    feed = feed_manager.get_feed('user', 'hash_%s' % hashtag_name)
    activities = feed.get(limit=25)['results']

    activities = enricher.enrich_activities(activities)
    context = {'hashtag_name': hashtag_name, 'activities': activities}
    return render(request, 'stream_twitter/hashtag.html', context)
Exemplo n.º 7
0
def hashtag(request, hashtag):
	feed = feed_manager.get_feed('hashtag', hashtag)
	activities = feed.get(limit=25)['results']
	enricher.enrich_activities(activities)
	context = {
		'activities': activities
	}
	return render(request, 'hashtag.html', context)
Exemplo n.º 8
0
 def get_context_data(self, object):
     user = self.object
     feed = feed_manager.get_feed('timeline', 'shell')
     activities = feed.get()['results']
     activities = enricher.enrich_activities(activities)
     return {
         'activities': activities,
         'user': user,
         'login_user': self.request.user
     }
Exemplo n.º 9
0
def hashtag(request, hashtag_name):
    hashtag_name = hashtag_name.lower()
    feed = feed_manager.get_feed('user', 'hash_%s' % hashtag_name)
    activities = feed.get(limit=25)['results']

    activities = enricher.enrich_activities(activities)
    context = {
        'hashtag_name': hashtag_name,
        'activities': activities
    }
    return render(request, 'stream_twitter/hashtag.html', context)
Exemplo n.º 10
0
    def get_context_data(self, hashtag):
        context = super(TemplateView, self).get_context_data()

        hashtag = hashtag.lower()
        feed = feed_manager.get_feed('user', f'hash_{hashtag}')
        activities = feed.get(limit=25)['results']

        context['hashtag'] = hashtag
        context['activities'] = enricher.enrich_activities(activities)

        return context
Exemplo n.º 11
0
    def clean(self):
        """
        Override to obtain transaction details from given tx_hash.
        """
        # Call the super
        super(FeedActivityCreateForm, self).clean()

        # Obtain form input parameter
        tx_hash = self.cleaned_data.get("tx_hash")

        # Make calls to Horizon to get tx and all ops associated with given tx hash
        horizon = settings.STELLAR_HORIZON_INITIALIZATION_METHOD()
        tx_json = horizon.transaction(tx_hash=tx_hash)
        ops_json = horizon.transaction_operations(tx_hash=tx_hash)

        # Store the memo if there
        self.memo = tx_json['memo'] if 'memo' in tx_json and tx_json[
            'memo_type'] != "none" else ""

        # Store the ops for save method and verify source account
        self.ops = ops_json['_embedded'][
            'records'] if '_embedded' in ops_json and 'records' in ops_json[
                '_embedded'] else None

        # Store the time created and check current user has added account associated with tx
        # TODO: Sometimes the transaction_operations() call returns a 404
        # for some reason (tx not settling in time?) after POSTing. Eventually
        # create a listener for txs that POSTs to this endpoint after checking
        # if an associated account is a part of the tx. Instead of current way
        # of doing in request/response cycle.
        if self.ops:
            first_op = self.ops[0]
            self.time = dateutil.parser.parse(first_op['created_at'])
            self.tx_href = first_op['_links']['transaction'][
                'href'] if '_links' in first_op and 'transaction' in first_op[
                    '_links'] and 'href' in first_op['_links'][
                        'transaction'] else None

            try:
                self.account = self.request_user.accounts.get(
                    public_key=first_op['source_account'])
            except ObjectDoesNotExist:
                raise ValidationError(_(
                    'Invalid user id. Decoded account associated with Stellar transaction does not match your user id.'
                ),
                                      code='invalid_user')

        # Retrieve and store stream feed of current user
        self.feed = feed_manager.get_feed(settings.STREAM_USER_FEED,
                                          self.request_user.id)

        return self.cleaned_data
Exemplo n.º 12
0
def delete_discussions(sender, instance, **kwargs):
    request = ListRequestsChannels.objects.create(discussion=instance.id)
    feed = feed_manager.get_feed(
        'timeline', '{}_channels_events'.format(instance.account.id))
    t = feed.add_activity({
        'actor': instance.slug,
        'verb': 'delete',
        'object': request.id,
        'message': instance.__dict__,
        'member_ids': []
    })

    request.getstream_info = json.dumps(t, default=myconverter)
    request.save()
Exemplo n.º 13
0
def add_activity_to_feed(feed_type, feed_id, context):
    """
    Task to add activity to feed.
    """
    feed = feed_manager.get_feed(feed_type, feed_id)
    resp = feed.add_activity(context)
    inv_verb_choices = {
        v: k
        for k, v in dict(Activity.VERB_CHOICES).iteritems()
    }
    verb = inv_verb_choices.get(resp.get('verb', ''), -1)
    if verb != -1:
        model_cls = Activity if verb != Activity.COMMENT else Comment
        model_cls.objects.update_from_stream_response(resp)
Exemplo n.º 14
0
    def get(self, request, *args, **kwargs):
        account = get_current_account(self.request)
        feed_name = request.GET['feed_name']

        check_discussion = Discussions.objects.get_or_create(slug=feed_name,
                                                             account=account)
        if not check_discussion:
            return HttpResponse(json.dumps({'error': 'Not found'}))
        if 'to_id' in request.GET:
            to_id = request.GET['to_id']
            messages = Messages.objects.filter(verb='reply',
                                               feed_name=feed_name,
                                               to=to_id,
                                               getstream_info__isnull=False)
        else:
            messages = Messages.objects.filter(verb='tweet',
                                               feed_name=feed_name,
                                               getstream_info__isnull=False)
        feed = feed_manager.get_feed('user', feed_name)
        messages_getstream = [{
            'data': json.loads(d.getstream_info),
            'count_reply': d.get_count_reply()
        } for d in messages]
        kwargs['content_type'] = 'application/json'

        return HttpResponse(
            json.dumps(
                {
                    'token':
                    feed.get_readonly_token(),
                    'items':
                    messages_getstream,
                    'feed_name':
                    feed_name,
                    'creator_id':
                    check_discussion[0].creator_id,
                    'auto':
                    check_discussion[0].auto,
                    'private':
                    check_discussion[0].private,
                    'discussion_details':
                    check_discussion[0].details,
                    'url_edit_channel':
                    reverse('discussion:edit_channel',
                            kwargs={
                                'pk': check_discussion[0].id,
                                'url': account.url
                            })
                },
                default=self.myconverter), kwargs)
Exemplo n.º 15
0
    def get_context_data(self, *args, **kwargs):
        context = super(DiscussionOrganizationView,
                        self).get_context_data(*args, **kwargs)
        account = get_current_account(self.request)
        membership = self.request.user.get_membership(account)
        discussion_slug = '{}_organization'.format(account.id)
        feed_discussion = Discussions.objects.get(slug=discussion_slug,
                                                  account=account)

        all_members_objects = Membership.objects.filter(
            account=account, is_active=True).order_by('last_name')
        all_members = {
            member.id: {
                'full_name':
                member.get_full_name(),
                'avatar_url':
                member.avatar_url(geometry='50x50')
                if member.avatar else '/static/images/default_avatar_sq.svg'
            }
            for member in all_members_objects
        }
        feed_channels = feed_manager.get_feed(
            'timeline', '{}_channels_events'.format(account.id))

        context[
            'not_auto_feed_discussion_public'] = Discussions.objects.filter(
                private=False, auto=False, account=account)
        context[
            'not_auto_feed_discussion_private'] = Discussions.objects.filter(
                private=True,
                auto=False,
                account=account,
                member_ids=membership)
        context['feed_discussion'] = feed_discussion.slug
        context['folder'] = Folder.objects.get_discussion_folder(account)
        context['folder_add_form'] = DocumentAddForm()
        context['channel_add_form'] = ChannelForm({'account': account})
        context['channel_edit_form'] = EditChannelForm({'account': account})
        context['message_edit_form'] = MessageEditForm()
        context['getstream_key'] = STREAM_API_KEY
        context['getstream_app_id'] = STREAM_APP_ID
        context['active_member'] = self.get_queryset().filter(is_active=True)
        context['all_members_objects'] = all_members_objects
        context['active_news_rooms'] = News.objects.filter(account=account)
        context['active_committee'] = Committee.objects.for_membership(
            membership=membership)
        context['all_members'] = json.dumps(all_members)
        context['feed_channels_token'] = feed_channels.get_readonly_token()
        return context
Exemplo n.º 16
0
    def activity_notify(self):
        target_feed = []
        # 해당 hashtag(#) 키워드의 피드(e.g. hashtag:패션)에 activity 추가
        for keyword in self.parse_hashtags():
            target_feed.append(feed_manager.get_feed('hashtag', keyword))
        for user in self.parse_mentions():
            # mention(@)한 유저의 타임라인 피드에 activity 추가
            # get_news_feeds는 기본으로 인자로 받은 user의 1) timeline, 2) timeline_aggregated
            # 피드를 가져옴
            target_feed.append(
                feed_manager.get_news_feeds(user.id)['timeline'])
            # mention(@)한 유저의 notification 피드에 activity 추가
            target_feed.append(feed_manager.get_notification_feed(user.id))

        return target_feed
Exemplo n.º 17
0
def create_discussions(sender, instance, created, **kwargs):
    if created:
        if instance.auto == False:
            instance.slug = "{}_{}".format(instance.slug, instance.id)
        instance.save()
    else:
        request = ListRequestsChannels.objects.create(discussion=instance.id)

        member_ids_data = []
        for member in instance.member_ids.all():
            member_ids_data.append(member.id)

        feed = feed_manager.get_feed(
            'timeline', '{}_channels_events'.format(instance.account.id))
        t = feed.add_activity({
            'actor': instance.slug,
            'verb': 'edit',
            'object': request.id,
            'message': instance.__dict__,
            'member_ids': member_ids_data
        })

        request.getstream_info = json.dumps(t, default=myconverter)
        request.save()
Exemplo n.º 18
0
 def test_get_feed(self):
     feed = feed_manager.get_feed('flat', 42)
     self.assertEqual(feed.feed_id, 'flat:42')
Exemplo n.º 19
0
 def test_get_feed(self):
     feed = feed_manager.get_feed('timeline', 42)
     self.assertEqual(feed.id, 'timeline:42')
Exemplo n.º 20
0
def delete_messege_profile(sender, instance, **kwargs):
    feed = feed_manager.get_feed('user', instance.feed_name)
    feed.remove_activity(instance.activity_id)
Exemplo n.º 21
0
 def test_get_feed(self):
     feed = feed_manager.get_feed('flat', 42)
     self.assertEqual(feed.id, 'flat:42')
Exemplo n.º 22
0
 def test_get_feed(self):
     feed = feed_manager.get_feed("timeline", 42)
     self.assertEqual(feed.id, "timeline:42")
Exemplo n.º 23
0
 def test_get_feed(self):
     feed = feed_manager.get_feed('timeline', 42)
     self.assertEqual(feed.id, 'timeline:42')
Exemplo n.º 24
0
 def activity_notify(self):
     targets = []
     for hashtag in self.parse_hashtags():
         targets.append(feed_manager.get_feed('hashtag', hashtag))
     return targets
Exemplo n.º 25
0
def create_messege_profile(sender, instance, created, **kwargs):
    if hasattr(instance, '_dirty'):
        return

    if created:
        feed = feed_manager.get_feed('user', instance.feed_name)

        data_files = {}
        for file_id in instance.get_files():
            data_files[file_id.id] = file_id.name

        if instance.to:
            instance.verb = 'reply'
            t = feed.add_activity({
                'actor': instance.member_send.id,
                'verb': 'reply',
                'object': instance.id,
                'message': instance.message,
                'foreign_id': 'tweet:{}'.format(instance.to),
                'file_ids': data_files
            })
        else:
            instance.verb = 'tweet'
            t = feed.add_activity({
                'actor': instance.member_send.id,
                'verb': 'tweet',
                'object': instance.id,
                'message': instance.message,
                'file_ids': data_files
            })
        # t = feed.add_activity(
        #     {'actor': instance.member_send.id, 'verb': 'tweet', 'object': instance.id, 'message': instance.message})
        instance.getstream_info = json.dumps(t, default=myconverter)
        instance.activity_id = t['id']

        for perm in (PERMISSIONS.view, PERMISSIONS.add, PERMISSIONS.edit,
                     PERMISSIONS.delete):
            ObjectPermission.objects.create(
                membership=instance.member_send,
                content_type=get_contenttype(instance),
                object_id=instance.id,
                permission=perm,
            )

        discussion = Discussions.objects.get(slug=instance.feed_name)
        try:
            if discussion:
                instance.discussions = discussion
            instance._dirty = True
            instance.save()
        finally:
            if hasattr(instance, '_dirty'):
                del instance._dirty
    else:
        feed = feed_manager.get_feed('user', instance.feed_name)
        json_getstream = json.loads(instance.getstream_info)
        old_foreign_id = json_getstream['foreign_id']

        if json_getstream['message'] == instance.message:
            return

        # json_getstream['foreign_id'] = 'tweet:{}'.format(instance.id)
        print 'instance.created_at', instance.created_at
        json_getstream["time"] = instance.created_at
        json_getstream["message"] = instance.message

        t = feed.add_activity(json_getstream)

        # json_getstream['foreign_id'] = old_foreign_id
        print 'json_getstream', json_getstream
        Messages.objects.filter(pk=instance.pk).update(
            getstream_info=json.dumps(t, default=myconverter),
            activity_id=t['id'])