Beispiel #1
0
def register(request):
    if request.method == 'POST':
        user_form = RegistrationForm(request.POST)
        if user_form.is_valid():
            username = user_form.cleaned_data.get('username')
            email = user_form.cleaned_data.get('email')
            password = user_form.cleaned_data.get('password')

            User.objects.create_user(
                username=username,
                email=email,
                password=password,
            )
            user = authenticate(username=username, password=password)
            login(request, user)
            _success_msg = 'User {0} added'.format(user.username)
            feed = Feed(user=user, posts=_success_msg)
            feed.save()
            return redirect('/feeds/')
        else:
            return render(request, 'authentication/register.html',
                          {'form': user_form})
    else:
        user_form = RegistrationForm()

    return render(request, 'authentication/register.html', {'form': user_form})
Beispiel #2
0
    def setUp(self):
        """
        Set up enivironment to test models
        """
        self.user = User.objects.create_user(
            self.username,
            '*****@*****.**',
            self.password
        )
        """Test user."""

        self.feed1 = Feed(
            feed_url=reverse('planet:rss1'),
            name="rss1",
            short_name="rss1"
        )
        self.feed1.save()
        """Feed 1."""

        self.feed2 = Feed(
            feed_url=reverse('planet:rss2'),
            name="rss2",
            short_name="rss2"
        )
        self.feed2.save()
        """Feed 2."""

        self.client = Client()
        """Test Client."""
Beispiel #3
0
def save(request):
    data = json.loads(request.POST['feedinfo'])
    if 'feed_id' in data and data['feed_id']:
        feed_id = data['feed_id']
    else:
        feed_id = str(uuid.uuid4())
        data['feed_id'] = feed_id
#     folder = os.path.join( settings.FEED_STORAGE_DIR + '/' + feed_id)
#     if not os.path.exists(folder):
#         os.makedirs(folder)
#     with open(folder + '/feed.json', 'w') as f:
#         print folder
#         f.write(json.dumps(data))
    try:
        new_feed = Feed.objects.get(guid=feed_id)
    except ObjectDoesNotExist:
        new_feed = Feed(guid = feed_id)
        new_feed.create_time = timezone.now()
        new_feed.owner_id = request.user.id
    
    new_feed.title = 'demo'
    new_feed.desc = 'demo'
    new_feed.conf = json.dumps(data)
    new_feed.version = new_feed.version + 1
    new_feed.update_time = timezone.now()
    new_feed.save()
    
    response = {'result':'ok', 'feed_id' : feed_id}
    return HttpResponse(json.dumps(response))
Beispiel #4
0
def profilefeeds_h_h(request):
    most_active_profile_talks_h_h = Feed.get_feeds().filter(Q(profile_pk__gt=0) & Q(user__profile__is_product=0)
                                                        & Q(to_user__profile__is_product=0)).order_by('likes').reverse()[:7]

    trending_people = Profile.objects.all().order_by('likes').reverse()[:10]
    
    human_human_profile_feeds = Feed.get_feeds().filter(Q(profile_pk__gt=0) & Q(user__profile__is_product=0)
                                                        & Q(to_user__profile__is_product=0))
    mostliked_talks = human_human_profile_feeds.order_by('likes').reverse()[:5]

    paginator = Paginator(human_human_profile_feeds, FEEDS_NUM_PAGES)
    human_human_profile_feeds = paginator.page(1) # still to be made 
    
    from_feed = -1

    if human_human_profile_feeds:        
        from_feed = human_human_profile_feeds[0].id 

    return render(request, 'profile_feeds/human_human.html', {
        'human_human_profile_feeds' : human_human_profile_feeds, # profile feeds list
        'most_active_profile_talks_h_h' : most_active_profile_talks_h_h,
        'trending_people' : trending_people,
        'from_feed' : from_feed,        
        'page': 1, 
        })
Beispiel #5
0
def specialfeeds(request,id):
    print('inside feeds, feeds.view')
    print('gonna send special style_feeds via feeds.views.feeds')
    #online_users = User.objects.all().exclude(is_active=True)
    recent_challenge_feeds = Feed.get_feeds().filter(Q(is_challenge=1)
                                              # & Q(date=datetime.date.today())
                                                ).order_by('-date')[:5]    
    response_for = id
    style_feeds = Feed.get_feeds().filter(response_for=response_for)# 2nd lookup excludes all challenge feeds as they have is_challenge set to 1

    paginator = Paginator(style_feeds, FEEDS_NUM_PAGES)
    style_feeds = paginator.page(1)

    from_feed = -1
    if style_feeds: 
        from_feed = style_feeds[0].id

    response_for_feed = get_object_or_404(Feed, id=response_for)
    return render(request, 'feeds/special_feeds.html', {
        'style_feeds': style_feeds, 
        #'online_users' : online_users,
        'from_feed': from_feed, 
        'response_for_feed' : response_for_feed,   
        'recent_challenge_feeds' : recent_challenge_feeds,
        'page': 1,
        })
Beispiel #6
0
def subscription(request):
    profile = request.user.get_profile()
    if request.method == "GET":
        subscriptions = Subscription.objects.filter(profile=profile)
        subscriptions_json = [{'id': s.feed.id,
                               'title': s.feed.title,
                               'unread_entries': profile.unread_entries(s.feed)}
                              for s in subscriptions]
        return HttpResponse(json.dumps(subscriptions_json),
                            content_type='application/json')
    if request.method == "POST":
        link = json.loads(request.body)['link']
        if not link.startswith('http://'):
            link = 'http://{}'.format(link)
        parser = feedparser.parse(link)
        feed = parser.feed
        try:
            title = feed.title
        except AttributeError:
            return HttpResponseBadRequest('Invalid feed')
        try:
            feed_obj = Feed.objects.get(link=link)
        except ObjectDoesNotExist:
            feed_obj = Feed(link=link, title=title)
            feed_obj.save()
        if Subscription.objects.filter(profile=profile, feed=feed_obj).exists():
            return HttpResponseBadRequest('You are already subscribed to this '
                                          'feed')
        Subscription.objects.get_or_create(profile=profile, feed=feed_obj)
        try:
            poll_feed(feed_obj)
        except AttributeError:
            return HttpResponseBadRequest('Invalid feed')
        return HttpResponse()
Beispiel #7
0
    def _update_feed(
        cls,
        feed_subscription: FeedSubscription,
        feed_data: FeedParserDict,
    ) -> Feed:
        """
        Create or update Feed based on parsed data.

        :param feed_subscription: FeedSubscription related instance.
        :param feed_data: Parsed RSS data.
        :return: Processed Feed instance.
        """
        cloud = feed_data.feed.get('cloud', {})
        image = feed_data.feed.get('image', {})
        text_input = feed_data.feed.get('textinput', {})
        # Create a filed_name:value dict out of fetched data for Feed
        data = {
            'cloud_domain': cloud.get('domain'),
            'cloud_path': cloud.get('path'),
            'cloud_port': cloud.get('port'),
            'cloud_protocol': cloud.get('protocol'),
            'cloud_register_procedure': cloud.get('registerProcedure'),
            'copyright': feed_data.feed.get('rights'),
            'description': feed_data.feed.get('subtitle'),
            'docs': feed_data.feed.get('docs'),
            'encoding': feed_data.get('encoding'),
            'generator': feed_data.feed.get('generator'),
            'image_description': image.get('description'),
            'image_height': image.get('height'),
            'image_link': image.get('width'),
            'image_title': image.get('title'),
            'image_url': image.get('href'),
            'image_width': image.get('width'),
            'language': feed_data.feed.get('language'),
            'link': feed_data.feed.get('link'),
            'managing_editor': feed_data.feed.get('author'),
            'pub_date': cls.get_pub_date(feed_data.feed),
            'subscription': feed_subscription,
            'text_input_description': text_input.get('description'),
            'text_input_link': text_input.get('link'),
            'text_input_name': text_input.get('name'),
            'text_input_title': text_input.get('title'),
            'title': feed_data.feed.get('title'),
            'ttl': feed_data.feed.get('ttl'),
            'version': feed_data.get('version'),
            'web_master': feed_data.feed.get('publisher')
        }

        try:
            feed = feed_subscription.feed

            # Update Feed with fetched values
            for name, value in data.items():
                setattr(feed, name, value)
        except FeedSubscription.feed.RelatedObjectDoesNotExist:
            # Make a new Feed instance with fetched values
            feed = Feed(**data)

        feed.save()
        return feed
    def test_deleting_a_subscription(self):
        """Users should be able to unsubscribe to a feed through the API."""
        feed = Feed(url="http://example.org/feed")
        feed.save()
        feed.subscribers.add(self.user)

        response = self.client.delete('/api/subscriptions/%d/' % (feed.id,))

        assert response.status_code == 204
        assert self.user not in feed.subscribers.all()
    def build_articles(self, subscriber, feed_count=2, article_count=2):
        """Create two feeds and several articles for a user."""
        for _ in range(feed_count):
            feed = Feed(url=fake.uri())
            feed.save()
            feed.subscribers.add(subscriber)

            for _ in range(article_count):
                feed.items.create(uid=fake.md5(),
                                  title=fake.sentence(),
                                  link=fake.uri(),
                                  published_at=timezone.now())
class FeedTestCase(TestCase):
    """This class defines the test suite for the Feed model."""
    def setUp(self) -> None:
        title = 'Simple is Better Than Complex'
        link = 'https://simpleisbetterthancomplex.com/'
        rss = 'https://simpleisbetterthancomplex.com/feed.xml/'
        self.feed = Feed(title=title, link=link, rss=rss)

    def test_model_can_create_a_feed(self):
        old_count = Feed.objects.count()
        self.feed.save()
        new_count = Feed.objects.count()
        return self.assertNotEqual(old_count, new_count)
Beispiel #11
0
def post(request):
    last_feed = request.POST.get('last_feed')
    user = request.user
    csrf_token = unicode(csrf(request)['csrf_token'])
    feed = Feed()
    feed.user = user
    post = request.POST['post']
    post = post.strip()
    if len(post) > 0:
        feed.post = post[:255]
        feed.save()
    html = _html_feeds(last_feed, user, csrf_token)
    return HttpResponse(html)
Beispiel #12
0
 def _save_feed(self):
     """
     Custom method to create and save a new feed to the DB.
     """
     feed = Feed()
     feed.plugin_inst = self
     feed.save()
     feed.name = self.plugin.name
     feed.owner = [self.owner]
     feed.save()
    def create(self, validated_data):
        try:
            feed = Feed.objects.get(url=validated_data['url'])
        except Feed.DoesNotExist:
            feed = Feed(url=validated_data['url'])
            feed.save()
            feed.sync()

        subscriber = validated_data['subscriber']
        if subscriber in feed.subscribers.all():
            raise serializers.ValidationError(
                "You are already subscribed to this feed.")
        feed.subscribers.add(subscriber)

        return feed
Beispiel #14
0
def check(request): 
    last_feed = request.GET.get('last_feed')
    feed_source = request.GET.get('feed_source')
    # is_product_feed = request.GET.get('is_product_feed')
    profile_pk = request.GET.get('profile_pk')
    response_for_feed_id = request.GET.get('response_for_feed_id')
    page_user_name = request.GET.get('page_user_name')
    if page_user_name:
        page_user = get_object_or_404(User, username=page_user_name) 

    feeds = Feed.get_feeds_after(last_feed)
    if feed_source == 'all_profile_feeds':
        feeds = feeds.filter(Q(profile_pk__gt=0)
                            &Q(user__profile__is_product=1)
                            )
    elif feed_source == 'all_product_profile_feeds':
        feeds = feeds.filter(Q(profile_pk__gt=0)
                                & Q(user__profile__is_product=0)
                                )
    elif feed_source == 'user_profile_feeds':
        feeds = feeds.filter(profile_pk=profile_pk)
    
    elif feed_source == 'special_feeds':
        feeds = feeds.filter(response_for=response_for_feed_id)
    
    elif feed_source == 'challenge_feeds':
        feeds = feeds.filter(is_challenge=1)
    
    elif feed_source == 'user_feeds':
        feeds = feeds.filter(user__id=page_user.id)

    count = feeds.count()
    return HttpResponse(count)
Beispiel #15
0
def feeds(request):
    user = request.user
    feed_data = Feed.get_feeds(user)
    result = []

    for datum in feed_data:
        comment_data = Comments.get_comments(datum.feeds_id)
        feed_list = [datum, comment_data]
        result.append(feed_list)

    if request.method == 'POST' and user.is_authenticated:
        feeds_form = FeedsForm(request.POST)

        if feeds_form.is_valid():
            feed = feeds_form.cleaned_data.get('posts')
            Feed.objects.create(posts=feed, user=user)
            return redirect('/feeds/')
        else:
            return render(request, 'feeds/feeds.html', {'forms': feeds_form})
    else:
        feeds_form = FeedsForm()
        comments_form = CommentForm()
    return render(
        request, 'feeds/feeds.html', {
            'user': user,
            'feeds': result,
            'forms': feeds_form,
            'comments_form': comments_form,
        })
Beispiel #16
0
def profile(request, username):
    page_user = get_object_or_404(User, username=username)
    # empty_fields = []
    # profile_fields = ['first_name','last_name','job','email','institute','status','birth_date','likes_most']
    # for field in profile_fields:
    #     if not page_user.profile.:
    #         empty_fields.append(field)

    profile_pk = page_user.profile.pk
    # making profile feeds pagewise
    profile_feeds = Feed.get_feeds().filter(profile_pk=profile_pk)
    paginator_profile = Paginator(profile_feeds, FEEDS_NUM_PAGES)
    profile_feeds = paginator_profile.page(1)
    from_feed = -1
    if profile_feeds:
        from_feed = profile_feeds[0].id
    return render(
        request,
        'core/profile.html',
        {
            'page_user': page_user,
            # 'user_feeds': user_feeds,
            # 'from_feed_user': from_feed_user, I'll make different view for user feeds
            # 'from_feed_profile':from_feed_profile, # no need to do that
            'from_feed':
            from_feed,  # just maintain same name from_feed this will make work of feeds.load view easy
            'profile_feeds': profile_feeds,
            # 'empty_fields' : empty_fields,
            'page': 1
        })
Beispiel #17
0
    def setUp(self):
        self.feed = Feed(link="http://link.to/rss.xml",
                         title="A Feed")
        self.feed.save()

        # Create an entry
        published = datetime.datetime(2013, 9, 25, 4, 0)
        published = published.timetuple()
        self.entry1 = FeedParserEntry(title="An Entry",
                                      link="http://entry",
                                      published_parsed=published)

        # Create another entry
        published = datetime.datetime(2013, 9, 28, 4, 0)
        published = published.timetuple()
        self.entry2 = FeedParserEntry(title="Another Entry",
                                      link="http://another/entry",
                                      published_parsed=published)

        # Create users
        user1 = User(username="******")
        user1.save()
        self.profile1 = UserProfile(user=user1)
        self.profile1.save()

        user2 = User(username="******")
        user2.save()
        self.profile2 = UserProfile(user=user2)
        self.profile2.save()
Beispiel #18
0
 def form_valid(self, form):
     user = self.request.user
     link = form.cleaned_data['link']
     if not link.startswith('http://'):
         link = 'http://{}'.format(link)
     parser = feedparser.parse(link)
     feed = parser.feed
     title = feed.title
     try:
         feed_obj = Feed.objects.get(link=link)
     except ObjectDoesNotExist:
         feed_obj = Feed(link=link, title=title)
         feed_obj.save()
     profile = user.get_profile()
     Subscription(profile=profile, feed=feed_obj).save()
     poll_feed(feed_obj)
     return super(DashboardView, self).form_valid(form)
Beispiel #19
0
def check(request):
    last_feed = request.GET.get('last_feed')
    feed_source = request.GET.get('feed_source')
    feeds = Feed.get_feeds_after(last_feed)
    if feed_source != 'all':
        feeds = feeds.filter(user__id=feed_source)
    count = feeds.count()
    return HttpResponse(count)
Beispiel #20
0
def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if not form.is_valid():
            return render(request, 'authentication/signup.html', {'form': form})
        else:
            username = form.cleaned_data.get('username')
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            User.objects.create_user(username=username, password=password, email=email)
            user = authenticate(username=username, password=password)
            login(request, user)
            welcome_post = u'{0} has joined the network.'.format(user.username)
            feed = Feed(user=user, post=welcome_post)
            feed.save()
            return redirect('/')
    else:
        return render(request, 'authentication/signup.html', {'form': SignUpForm()})
Beispiel #21
0
def challengefeeds(request):
    challenge_feeds = Feed.get_feeds().filter(is_challenge=1)
    paginator = Paginator(challenge_feeds, FEEDS_NUM_PAGES)
    challenge_feeds = paginator.page(1)

    from_feed = -1
    if challenge_feeds:
        from_feed = challenge_feeds[0].id
    most_liked_challenge_feeds = Feed.get_feeds().filter(Q(is_challenge=1)
                                              # & Q(date=datetime.date.today())
                                                ).order_by('likes').reverse()[:6]

    return render(request, 'feeds/challenge_feeds.html', {
        'challenge_feeds': challenge_feeds, 
        'from_feed': from_feed,
        'most_liked_challenge_feeds' : most_liked_challenge_feeds,
        'page': 1,
        })
Beispiel #22
0
def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None

    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.profile.email_confirmed = True
        user.save()
        login(request, user)
        welcome_post = '{0} has joined the network.'.format(user.username,
                                                            user.username)
        feed = Feed(user=user, post=welcome_post)
        feed.save()
        return redirect('/')
    else:
        return render(request, 'authentication/account_activation_invalid.html')
Beispiel #23
0
def _process_post_form_messages(form, logged_user, to_user):

    msg = Message(from_user=logged_user,
                  to_user=to_user,
                  post=form.post.data,
                  message_type=POST).save()
    Feed(user=logged_user, message=msg).save()
    MessageProcessor(message_obj=msg).post_message_to_all_friends_feeds()

    return msg
Beispiel #24
0
def load_new(request):
    user = request.user
    last_feed = request.GET.get('last_feed')
    feed_source = request.GET.get('feed_source')
    # is_product_feed = request.GET.get('is_product_feed')
    profile_pk = request.GET.get('profile_pk')
    response_for_feed_id = request.GET.get('response_for_feed_id')
    page_user_name = request.GET.get('page_user_name')
    if page_user_name:
        page_user = get_object_or_404(User, username=page_user_name) 

    feeds = Feed.get_feeds_after(last_feed)
    
    if feed_source == 'all_profile_feeds':
        partial_feed_page = 'feeds/partial_feed_profile.html'
        feeds = feeds.filter(Q(profile_pk__gt=0)
                            &Q(user__profile__is_product=1)
                            )
    elif feed_source == 'all_product_profile_feeds':
        partial_feed_page = 'feeds/partial_feed_profile.html'
        feeds = feeds.filter(Q(profile_pk__gt=0)
                            & Q(user__profile__is_product=0)
                            )
    elif feed_source == 'user_profile_feeds':
        partial_feed_page = 'feeds/partial_feed_profile.html'
        feeds = feeds.filter(profile_pk=profile_pk)
    
    elif feed_source == 'special_feeds':
        if response_for_feed_id:
            partial_feed_page = 'feeds/partial_feed.html'
            feeds = feeds.filter(response_for=response_for_feed_id)
        else:
            feeds = []

    elif feed_source == 'challenge_feeds':
        partial_feed_page = 'feeds/partial_challenge_feed.html'
        feeds = feeds.filter(is_challenge=1)
    
    elif feed_source == 'user_feeds':
        partial_feed_page = 'feeds/partial_feed.html'
        feeds = feeds.filter(user__id=page_user.id)


    html = ''    
    csrf_token = (csrf(request)['csrf_token'])
    for feed in feeds:
       html = '{0}{1}'.format(html,
                               render_to_string(partial_feed_page,
                                                {
                                                    'feed': feed,
                                                    'user': request.user,
                                                    'csrf_token': csrf_token,
                                                    }))

    return HttpResponse(html)
Beispiel #25
0
def profile(request, username):
    page_user = get_object_or_404(User, username=username)
    all_feeds = Feed.get_feeds().filter(user=page_user)
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    feeds = paginator.page(1)
    from_feed = -1
    if feeds:
        from_feed = feeds[0].id
    return render(
        request, "core/profile.html", {"page_user": page_user, "feeds": feeds, "from_feed": from_feed, "page": 1}
    )
Beispiel #26
0
    def handle(self, *args, **options):
        try:
            user = User.objects.get(username=args[0])
        except (IndexError,User.DoesNotExist):
            raise CommandError('No valid username given.')

        try:
            xml = et.parse(args[1])
        except (IndexError,IOError):
            raise CommandError('No valid inputfile given.')

        for categoryNode in xml.find('body').findall('outline'):
            categoryTitle = categoryNode.attrib['title']

            print '    category',categoryTitle

            try:
                category = Category.objects.get(title=categoryTitle,user=user)
            except Category.DoesNotExist:
                category = Category(title=categoryTitle,user=user)
                category.save()

            for subscriptionNode in categoryNode.findall('outline'):
                subscriptionTitle = subscriptionNode.attrib['title']
                subscriptionHtmlUrl = subscriptionNode.attrib['htmlUrl']
                subscriptionXmlUrl = subscriptionNode.attrib['xmlUrl']

                print '        subscription',subscriptionTitle

                try:
                    feed = Feed.objects.get(xmlUrl=subscriptionXmlUrl)
                except Feed.DoesNotExist:
                    feed = Feed(xmlUrl=subscriptionXmlUrl)
                    feed.fetchItems()
                    feed.save()

                try:
                    subscription = Subscription.objects.get(category=category,feed=feed)
                except Subscription.DoesNotExist:
                    subscription = Subscription(category=category,feed=feed)
                    subscription.save()
Beispiel #27
0
def feeds(request):
    all_feeds = Feed.get_feeds()
    paginator = Paginator(all_feeds,8)
    feeds = paginator.page(1)
    from_feed = -1
    if feeds:
        from_feed = feeds[0].id
    return render_to_response('feed2.html', {
        'feeds': feeds,
        'from_feed': from_feed, 
        'page': 1,
        })
Beispiel #28
0
def feeds(request):
    all_feeds = Feed.get_feeds()
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    feeds = paginator.page(1)
    from_feed = -1
    if feeds:
        from_feed = feeds[0].id
    return render(request, 'feeds/feeds.html', {
        'feeds': feeds, 
        'from_feed': from_feed, 
        'page': 1,
        })
Beispiel #29
0
def feeds(request):
    all_feeds = Feed.get_feeds()
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    feeds = paginator.page(1)
    from_feed = -1
    if feeds:
        from_feed = feeds[0].id
    return render(request, 'feeds/feeds.html', {
        'feeds': feeds,
        'from_feed': from_feed,
        'page': 1,
        })
    def post_message_to_all_friends_feeds(self):

        friends = self._get_all_my_friends_obj()

        for friend in friends:

            rel_status = Relationship.get_relationship(
                friend.to_user, self._message_obj.to_user)

            if rel_status != constants.BLOCKED:
                Feed(user=friend.to_user, message=self._message_obj).save()
        return True
Beispiel #31
0
def update(request):
    first_feed = request.GET.get('first_feed')
    last_feed = request.GET.get('last_feed')
    feed_source = request.GET.get('feed_source')
    feeds = Feed.get_feeds().filter(id__range=(last_feed, first_feed))
    if feed_source != 'all':
        feeds = feeds.filter(user__id=feed_source)
    dump = {}
    for feed in feeds:
        dump[feed.pk] = {'likes': feed.likes, 'comments': feed.comments}
    data = json.dumps(dump)
    return HttpResponse(data, content_type='application/json')
Beispiel #32
0
def post(request):
    feed = Feed()
    feed.user = request.user
    # data: $("#compose-form").serialize(),
    feed.post = request.POST['post']
    feed.save()
    return render(request, 'feeds/partial_feed.html', {'feed': feed})
Beispiel #33
0
def feeds(request): 
    print('inside feeds, feeds.view')
    print('gonna send style_feeds via feeds.views.feeds')
    #online_users =User.objects.all()
    recent_challenge_feeds = Feed.get_feeds().filter(Q(is_challenge=1)
                                              # & Q(date=datetime.date.today())
                                                ).order_by('-date')[:5]
    most_liked_challenge_feeds = Feed.get_feeds().filter(Q(is_challenge=1)
                                              # & Q(date=datetime.date.today())
                                                ).order_by('likes').reverse()
 
    if most_liked_challenge_feeds:
        randno =random.randint(1,20)
        response_for_id = most_liked_challenge_feeds[randno].id
        response_for_feed = get_object_or_404(Feed, id=response_for_id)
    else:
        response_for_feed = None 
        response_for_id = None 

    if response_for_id:
        style_feeds = Feed.get_feeds().filter(response_for=response_for_id)
    else:
        style_feeds = []

    paginator = Paginator(style_feeds, FEEDS_NUM_PAGES)
    style_feeds = paginator.page(1)

    from_feed = -1
    if style_feeds:
        from_feed = style_feeds[0].id

    return render(request, 'feeds/feeds.html', {
        'style_feeds': style_feeds,  #all feeds for response for feed
        #'online_users' : online_users,
        'from_feed': from_feed,
        'response_for_feed' : response_for_feed,
        'recent_challenge_feeds' : recent_challenge_feeds,
        'page': 1,

        })
Beispiel #34
0
def _html_feeds(last_feed, user, csrf_token, feed_source='all'):
    feeds = Feed.get_feeds_after(last_feed)
    if feed_source != 'all':
        feeds = feeds.filter(user__id=feed_source)
    html = u''
    for feed in feeds:
        html = u'{0}{1}'.format(html, render_to_string('feeds/partial_feed.html', {
            'feed': feed,
            'user': user,
            'csrf_token': csrf_token
            })
        )
    return html
Beispiel #35
0
def profile(request, username):
    page_user = get_object_or_404(User, username=username)
    all_feeds = Feed.get_feeds().filter(user=page_user)
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    feeds = paginator.page(1)
    from_feed = -1
    if feeds:
        from_feed = feeds[0].id
    return render(request, 'core/profile.html',{
        'page_user': page_user,
        'feeds': feeds,
        'from_feed': from_feed,
        'page': 1
    })
Beispiel #36
0
    def setUp(self):
        """
        Set up enivironment to test models
        """
        self.user = User.objects.create_user(self.username,
                                             '*****@*****.**',
                                             self.password)
        """Test user."""

        self.feed1 = Feed(feed_url=reverse('planet:rss1'),
                          name="rss1",
                          short_name="rss1")
        self.feed1.save()
        """Feed 1."""

        self.feed2 = Feed(feed_url=reverse('planet:rss2'),
                          name="rss2",
                          short_name="rss2")
        self.feed2.save()
        """Feed 2."""

        self.client = Client()
        """Test Client."""
Beispiel #37
0
def profile(request, username):
    page_user = get_object_or_404(User, username=username)
    all_feeds = Feed.get_feeds().filter(user=page_user)
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    feeds = paginator.page(1)
    from_feed = -1
    if feeds:
        from_feed = feeds[0].id
    return render(request, 'core/profile.html', {
        'page_user': page_user,
        'feeds': feeds,
        'from_feed': from_feed,
        'page': 1
    })
Beispiel #38
0
def challenges_for_page_user(request, username):
    page_user = get_object_or_404(User, username=username)
    challenges_for_page_user = Feed.get_feeds().filter(
        Q(is_challenge=1) & Q(challenge_to_user=page_user))

    from_feed = -1
    if challenges_for_page_user:
        from_feed = challenges_for_page_user[0].id
    return render(
        request, 'core/challenges_for_page_user.html', {
            'page_user': page_user,
            'challenges_for_page_user': challenges_for_page_user,
            'from_feed': from_feed,
            'page': 1,
        })
Beispiel #39
0
def profilefeeds_p_h(request):
    most_active_profile_talks_p_h = Feed.get_feeds().filter(Q(profile_pk__gt=0) & Q(user__profile__is_product=1)
                                                        & Q(to_user__profile__is_product=0)).order_by('likes').reverse()[:7]

    top_feeds_p_h = Feed.get_feeds().filter(Q(profile_pk__gt=0) & Q(user__profile__is_product=1)
                                                        & Q(to_user__profile__is_product=0)).order_by('likes').reverse()[:10]
    product_human_profile_feeds = Feed.get_feeds().filter(Q(profile_pk__gt=0) & Q(user__profile__is_product=1)
                                                        & Q(to_user__profile__is_product=0))
   
    paginator = Paginator(product_human_profile_feeds, FEEDS_NUM_PAGES)
    product_human_profile_feeds = paginator.page(1) # still to be made 
    
    from_feed = -1

    if product_human_profile_feeds:
        from_feed = product_human_profile_feeds[0].id 

    return render(request, 'profile_feeds/product_human.html', {
        'product_human_profile_feeds' : product_human_profile_feeds,
        'most_active_profile_talks_p_h' : most_active_profile_talks_p_h,             
        'top_feeds_p_h' : top_feeds_p_h,      
        'from_feed' : from_feed,  
        'page': 1, 
        })
Beispiel #40
0
 def _save_feed(self):
     """
     Custom method to create and save a new feed to the DB.
     """
     feed = Feed()
     feed.name = self.plugin.name
     feed.save()
     feed.owner.set([self.owner])
     feed.save()
     return feed
Beispiel #41
0
def load(request):
    from_feed = request.GET.get('from_feed')
    page = request.GET.get('page')
    feed_source = request.GET.get('feed_source')
    all_feeds = Feed.get_feeds(from_feed)
    if feed_source != 'all':
        all_feeds = all_feeds.filter(user__id=feed_source)
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    try:
        feeds = paginator.page(page)
    except PageNotAnInteger:
        return HttpResponseBadRequest()
    except EmptyPage:
        feeds = []
    html = u''
    csrf_token = unicode(csrf(request)['csrf_token'])
    for feed in feeds:
        html = u'{0}{1}'.format(html, render_to_string('feeds/partial_feed.html', {
            'feed': feed,
            'user': request.user,
            'csrf_token': csrf_token
            })
        )
    return HttpResponse(html)
Beispiel #42
0
class TestAllViewsLoggedIn(TestCase):
    """
    Test Feeds views for users that are authenticated.
    """

    fixtures = [
        'Feed_all.yaml',
    ]

    username = "******"
    password = "******"

    def setUp(self):
        """
        Set up enivironment to test models
        """
        self.user = User.objects.create_user(
            self.username,
            '*****@*****.**',
            self.password
        )
        """Test user."""

        self.feed1 = Feed(
            feed_url=reverse('planet:rss1'),
            name="rss1",
            short_name="rss1"
        )
        self.feed1.save()
        """Feed 1."""

        self.feed2 = Feed(
            feed_url=reverse('planet:rss2'),
            name="rss2",
            short_name="rss2"
        )
        self.feed2.save()
        """Feed 2."""

        self.client = Client()
        """Test Client."""

    def site_add(self):
        """.. todo:: todo"""
        pass

    def test_site(self):
        """
        test_site
        ---------

        Test all aspects of "Site" as a logged in user.

        - add
        - submit
        - view
        - update
        """
        self.site_add()

    def feed_home(self):
        """
        go to feed-home

        .. todo:: rename and restructure as in
        :py:mod:`feeds.tests.ViewsAnonymousTest`.

        .. todo::
        Requires login or credential.
        """
        result = self.client.get(reverse('planet:feed-home'))
        self.assertEqual(result.status_code, 302)

    def feed_subscribe(self):
        """
        test feed-subscribe
        ---------
            :url: url(
                r'^list/$',
                FeedSubscribeView.as_view(),
                name="feed-subscription"
                )

            Should return 302 for an authenticated user and redirect to the
            details-page for the just subscribed feed.
        """
        self.client.login(
            username=self.username,
            password=self.password
        )
        result = self.client.get(
            reverse('planet:feed-subscribe', kwargs={'pk': 1})
        )
        self.assertEqual(result.status_code, 302)
        self.assertRedirects(
            result,
            reverse('planet:feed-view', kwargs={'pk': 1})
        )

    def feed_subscription(self):
        """
        test feed-subscription
        ---------
            :url: url(
                r'^list/$',
                FeedSubscriptionView.as_view(),
                name="feed-subscription"
                )

            Should return 200 for an authenticated user.
        """
        self.client.login(
            username=self.username,
            password=self.password
        )
        result = self.client.get(reverse('planet:feed-subscriptions'))
        self.assertEqual(result.status_code, 200)

    def feed_update(self):
        """
        test FeedUpdateView
        """
        self.client.login(
            username=self.username,
            password=self.password
        )
        result = self.client.get(
            reverse('planet:feed-update', kwargs={'pk': 1})
        )
        self.assertEqual(result.status_code, 200)

    def feed_delete(self):
        """
        Test FeedDeleteView

        Probably better through Selenium
        """
        pass

    def test_feed(self):
        """
        Run tests for all views related to feeds.
        - self.feed_home
        """
        self.feed_home()
        self.feed_subscribe()
        self.feed_subscription()
        self.feed_update()
        self.feed_delete()

    def test_feed_add(self):
        """
        Go to feed-add.
        This should require the proper credentials.
        """
        result = self.client.get(reverse('planet:feed-add'), follow=False)
        self.assertEqual(result.status_code, 302)

    def test_feed_add_no_credentials(self):
        """
        go to feed-add
        """
        self.client.login(username=self.username, password=self.password)
        result = self.client.get(reverse('planet:feed-add'), follow=False)
        self.assertEqual(result.status_code, 302)
        # self.assertRedirects(result, '/accounts/login')

    def test_feed_add_logged_in_valid_credentials(self):
        """
        go to feed-add
        """
        self.user = User.objects.get(username=self.username)
        permission = Permission.objects.get(codename="add_feed")
        self.user.user_permissions.add(permission)
        self.user.save()
        self.client.login(
            username=self.username,
            password=self.password
        )
        """
        .. todo:: this currently gives
        'AttributeError: 'module' object has no
        attribute 'CRISPY_TEMPLATE_PACK'.
        """
        # result = self.client.get(reverse('planet:feed-add'), follow=False)
        # self.assertEqual(result.status_code, 200)

    def test_feed_add_post_anonymous(self):
        """
        go to feed-add, anonymous client
        """
        result = self.client.post(reverse('planet:feed-add'))
        self.client.login(username=self.username, password=self.password)
        self.assertEqual(result.status_code, 302)

    def test_feed_view(self):
        """
        go to feed-view for feed 1

        .. todo::
        Requires login or credential.
        """
        feed_id = Feed.objects.all()[0].pk
        result = self.client.get(reverse('planet:feed-view', args=(feed_id,)))
        self.assertEqual(result.status_code, 302)

    def test_feed_refresh_view(self):
        """
        manually refresh a feed
        """
        c = Client()
        feeds = Feed.objects.all()
        result = c.get(reverse('planet:feed-refresh', args=(feeds[0].pk,)))
        self.assertEqual(result.status_code, 302)

    def test_create_post(self):
        """
        create a new post
        """
        feed = Feed.objects.all()[0]
        """
        Get first feed from the db.
        We use fixtures, so we can assume there are feeds.
        """
        with self.assertNumQueries(1):
            Post.objects.create(
                feed=feed,
                published=timezone.now()
            )
Beispiel #43
0
class PollFeedTest(TestCase):
    def setUp(self):
        self.feed = Feed(link="http://link.to/rss.xml", title="A Feed")
        self.feed.save()

        # Create an entry
        published = datetime.datetime(2013, 9, 25, 4, 0)
        published = published.timetuple()
        self.entry1 = FeedParserEntry(title="An Entry", link="http://entry", published_parsed=published)

        # Create another entry
        published = datetime.datetime(2013, 9, 28, 4, 0)
        published = published.timetuple()
        self.entry2 = FeedParserEntry(title="Another Entry", link="http://another/entry", published_parsed=published)

        # Create users
        user1 = User(username="******")
        user1.save()
        self.profile1 = UserProfile(user=user1)
        self.profile1.save()

        user2 = User(username="******")
        user2.save()
        self.profile2 = UserProfile(user=user2)
        self.profile2.save()

    def test_profile_display(self):
        self.assertEqual(str(self.profile1), "user1's profile")
        self.assertEqual(str(self.profile2), "user2's profile")

    @mock.patch("feedparser.parse")
    def test_poll_new_subscriber(self, mock_parse):
        """Test a successful polling of a feed."""

        # Set up mock data
        parser = mock.MagicMock()
        parser.entries = [self.entry1, self.entry2]
        mock_parse.return_value = parser
        Subscription(profile=self.profile1, feed=self.feed).save()

        # Verify initial state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 0)
        self.assertEqual(UserEntryDetail.objects.count(), 0)

        # Perform poll
        tasks.poll_feed(self.feed)

        # Verify final state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 2)
        self.assertEqual(UserEntryDetail.objects.count(), 2)

    @mock.patch("feedparser.parse")
    def test_poll_two_new_subscribers(self, mock_parse):
        """Test a successful polling of a feed."""

        # Set up mock data
        parser = mock.MagicMock()
        parser.entries = [self.entry1, self.entry2]
        mock_parse.return_value = parser
        Subscription(profile=self.profile1, feed=self.feed).save()
        Subscription(profile=self.profile2, feed=self.feed).save()

        # Verify initial state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 0)
        self.assertEqual(UserEntryDetail.objects.count(), 0)

        # Perform poll
        tasks.poll_feed(self.feed)

        # Verify final state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 2)
        self.assertEqual(UserEntryDetail.objects.count(), 4)

    @mock.patch("feedparser.parse")
    def test_poll_new_and_existing_subscribers(self, mock_parse):
        """Test a successful polling of a feed."""

        # Set up mock data
        parser = mock.MagicMock()
        parser.entries = [self.entry1, self.entry2]
        mock_parse.return_value = parser
        Subscription(profile=self.profile1, feed=self.feed).save()
        Subscription(profile=self.profile2, feed=self.feed).save()
        entry1 = Entry(
            link=self.entry1.link,
            feed=self.feed,
            title=self.entry1.title,
            published=datetime.datetime(2013, 9, 25, 4, 0),
        )
        entry1.save()
        UserEntryDetail(profile=self.profile1, entry=entry1).save()

        # Verify initial state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 1)
        self.assertEqual(UserEntryDetail.objects.count(), 1)

        # Perform poll
        tasks.poll_feed(self.feed)

        # Verify final state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 2)
        self.assertEqual(UserEntryDetail.objects.count(), 4)

    @mock.patch("feedparser.parse")
    def test_poll_after_unsubscribe(self, mock_parse):
        # Set up mock data
        parser = mock.MagicMock()
        parser.entries = [self.entry1]
        mock_parse.return_value = parser
        Subscription(profile=self.profile1, feed=self.feed).save()

        # Verify initial state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 0)
        self.assertEqual(UserEntryDetail.objects.count(), 0)

        # Perform poll
        tasks.poll_feed(self.feed)

        # Verify state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 1)
        self.assertEqual(UserEntryDetail.objects.count(), 1)

        # Unsubscribe
        self.profile1.unsubscribe(self.feed)

        # Verify state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 1)
        self.assertEqual(UserEntryDetail.objects.count(), 0)

        # Resubscribe
        self.profile1.subscribe(self.feed)

        # Perform poll (find another entry)
        parser.entries = [self.entry1, self.entry2]
        tasks.poll_feed(self.feed)

        # Verify final state
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Entry.objects.count(), 2)
        self.assertEqual(UserEntryDetail.objects.count(), 2)

    @mock.patch("feedparser.parse")
    def test_mark_read_unread(self, mock_parse):
        parser = mock.MagicMock()
        parser.entries = [self.entry1, self.entry2]
        mock_parse.return_value = parser

        unread_entries = self.profile1.unread_entries(self.feed)
        self.assertEqual(unread_entries, 0)

        self.profile1.subscribe(self.feed)
        tasks.poll_feed(self.feed)
        unread_entries = self.profile1.unread_entries(self.feed)
        self.assertEqual(unread_entries, 2)

        self.profile1.mark_read(self.feed)
        unread_entries = self.profile1.unread_entries(self.feed)
        self.assertEqual(unread_entries, 0)

        self.profile1.mark_unread(self.feed)
        unread_entries = self.profile1.unread_entries(self.feed)
        self.assertEqual(unread_entries, 2)
Beispiel #44
0
 def tearDown(self):
     for el in Feed.all():
         el.delete()
from feeds.models import Feed
keywords = ['cyclone', 'dhrought', 'earthquake', 'epidemic', 'fire', 'flood', 'heatwave', 'rain', 'infestation', 'landslide', 'snowfall', 'storm', 'tornado', 'tsunami', 'wind', 'volcano']

for keyword in keywords:
    # google
    print 'Generating a google feed for keyword: %s' % keyword
    f1 = Feed()
    f1.name = 'Feed from Google News for "%s"' % keyword
    f1.description = f1.name
    f1.url_xml = 'https://news.google.it/news/feeds?hl=en&q=%s' % keyword
    f1.url_html = f1.url_xml
    f1.enabled = True
    f1.save()
    f1.tags.add('crisis', keyword)
    # twitter
    f2 = Feed()
    f2.name = 'Tweets for "%s"' % keyword
    f2.description = f2.name
    f2.url_xml = 'http://search.twitter.com/search.rss?q=%s' % keyword
    f2.url_html = f2.url_xml
    f2.enabled = True
    f2.save()
    f2.tags.add('crisis', 'twitter', keyword)
Beispiel #46
0
 def test_create_feed(self):
     self.assertEquals(0, Feed.all().count())
     add_feed('http://rss.slashdot.org/Slashdot/slashdot')
     self.assertEquals(1, Feed.all().count())
Beispiel #47
0
 def test_get_feed(self):
     for feed in Feed.all():
         self.failUnless(get_feed(str(feed.key())))