Exemple #1
0
def tweet_new_published_events(verbose=False):
    """Create EventTweet instances for events that have recently been
    published and are ready for public consumption."""
    now = timezone.now()
    yesterday = now - datetime.timedelta(hours=24)
    events = Event.objects.scheduled().filter(
        created__gt=yesterday,
        created__lt=now,
        privacy=Event.PRIVACY_PUBLIC,
    ).approved().exclude(id__in=EventTweet.objects.values('event_id'))

    site = Site.objects.get_current()
    base_url = 'https://%s' % site.domain  # yuck!
    for event in events:
        if event.channels.filter(no_automated_tweets=True):
            if verbose:
                print "Skipping", repr(event.title), "because it's part of"
                print event.channels.filter(no_automated_tweets=True)
            continue
        # we have to try to manually create an appropriate tweet
        url = reverse('main:event', args=(event.slug, ))
        abs_url = urlparse.urljoin(base_url, url)
        try:
            abs_url = shorten_url(abs_url)
        except (ImproperlyConfigured, ValueError) as err:  # pragma: no cover
            if verbose:  # pragma: no cover
                print "Failed to shorten URL"
                print err

        text = event.title
        if len(text) > 115:
            # Why not 140?
            # We've found that sometimes when you're trying to tweet
            # a piece of text that actually is less than 140 when
            # doing text+URL you can get strange errors from Twitter
            # that it's still too long.
            text = text[:115]

        text = unhtml('%s\n%s' % (text, abs_url))
        text += '\n'
        tags = (event.tags.all().extra(select={
            'lower_name': 'lower(name)'
        }).order_by('lower_name'))
        for tag in tags:
            _tag = '#' + tag.name.replace(' ', '')
            # see comment above why we use 115 instead of 140
            if len(text + _tag) + 1 < 115:
                text += '%s ' % _tag
            else:
                break
        text = text.strip()

        event_tweet = EventTweet.objects.create(
            event=event,
            text=text,
            include_placeholder=True,
        )
        if verbose:  # pragma: no cover
            print "Created", repr(event_tweet)
Exemple #2
0
def new_event_tweet(request, id):
    data = {}
    event = get_object_or_404(Event, id=id)

    if request.method == 'POST':
        form = forms.EventTweetForm(event, data=request.POST)
        if form.is_valid():
            event_tweet = form.save(commit=False)
            if event_tweet.send_date:
                assert event.location, "event must have a location"
                tz = pytz.timezone(event.location.timezone)
                event_tweet.send_date = tz_apply(event_tweet.send_date, tz)
            else:
                now = timezone.now()
                event_tweet.send_date = now
            event_tweet.event = event
            event_tweet.creator = request.user
            event_tweet.save()
            messages.info(request, 'Tweet saved')
            url = reverse('manage:event_edit', args=(event.pk, ))
            return redirect(url)
    else:
        initial = {}
        event_url = reverse('main:event', args=(event.slug, ))
        base_url = ('%s://%s' % (request.is_secure() and 'https'
                                 or 'http', RequestSite(request).domain))
        abs_url = urlparse.urljoin(base_url, event_url)
        try:
            abs_url = shorten_url(abs_url)
            data['shortener_error'] = None
        except (ImproperlyConfigured, ValueError) as err:
            data['shortener_error'] = str(err)
        # except OtherHttpRelatedErrors?
        #    data['shortener_error'] = "Network error trying to shorten URL"

        initial['text'] = unhtml('%s\n%s' % (short_desc(event), abs_url))
        initial['include_placeholder'] = bool(event.placeholder_img)
        initial['send_date'] = ''
        form = forms.EventTweetForm(initial=initial, event=event)

    data['event'] = event
    data['form'] = form
    data['tweets'] = EventTweet.objects.filter(event=event)

    return render(request, 'manage/new_event_tweet.html', data)
Exemple #3
0
    def test_url_shortener_ok(self, rget):
        def mocked_read(url, params):
            return Response({
                u'status_code': 200,
                u'data': {
                    u'url': u'http://mzl.la/1adh2wT',
                    u'hash': u'1adh2wT',
                    u'global_hash': u'1adh2wU',
                    u'long_url': u'https://air.mozilla.org/it-buildout/',
                    u'new_hash': 0
                },
                u'status_txt': u'OK'
            })

        rget.side_effect = mocked_read
        url = 'https://air.mozilla.org/something/'
        short = utils.shorten_url(url)
        eq_(short, 'http://mzl.la/1adh2wT')
Exemple #4
0
def new_event_tweet(request, id):
    data = {}
    event = get_object_or_404(Event, id=id)

    if request.method == 'POST':
        form = forms.EventTweetForm(event, data=request.POST)
        if form.is_valid():
            event_tweet = form.save(commit=False)
            if event_tweet.send_date:
                assert event.location, "event must have a location"
                tz = pytz.timezone(event.location.timezone)
                event_tweet.send_date = tz_apply(event_tweet.send_date, tz)
            else:
                now = timezone.now()
                event_tweet.send_date = now
            event_tweet.event = event
            event_tweet.creator = request.user
            event_tweet.save()
            messages.info(request, 'Tweet saved')
            url = reverse('manage:event_edit', args=(event.pk,))
            return redirect(url)
    else:
        initial = {}
        event_url = reverse('main:event', args=(event.slug,))
        base_url = get_base_url(request)
        abs_url = urlparse.urljoin(base_url, event_url)
        try:
            abs_url = shorten_url(abs_url)
            data['shortener_error'] = None
        except (ImproperlyConfigured, ValueError) as err:
            data['shortener_error'] = str(err)
        # except OtherHttpRelatedErrors?
        #    data['shortener_error'] = "Network error trying to shorten URL"

        initial['text'] = unhtml('%s\n%s' % (short_desc(event), abs_url))
        initial['include_placeholder'] = bool(event.placeholder_img)
        initial['send_date'] = ''
        form = forms.EventTweetForm(initial=initial, event=event)

    data['event'] = event
    data['form'] = form
    data['tweets'] = EventTweet.objects.filter(event=event)

    return render(request, 'manage/new_event_tweet.html', data)
Exemple #5
0
    def test_url_shortener_ok(self, rget):

        def mocked_read(url, params):
            return Response({
                u'status_code': 200,
                u'data': {
                    u'url': u'http://mzl.la/1adh2wT',
                    u'hash': u'1adh2wT',
                    u'global_hash': u'1adh2wU',
                    u'long_url': u'https://air.mozilla.org/it-buildout/',
                    u'new_hash': 0
                },
                u'status_txt': u'OK'
            })

        rget.side_effect = mocked_read
        url = 'https://air.mozilla.org/something/'
        short = utils.shorten_url(url)
        eq_(short, 'http://mzl.la/1adh2wT')
Exemple #6
0
    def test_url_shortener_ok(self, p_urlopen):
        def mocked_read():
            r = {
                u'status_code': 200,
                u'data': {
                    u'url': u'http://mzl.la/1adh2wT',
                    u'hash': u'1adh2wT',
                    u'global_hash': u'1adh2wU',
                    u'long_url': u'https://air.mozilla.org/it-buildout/',
                    u'new_hash': 0
                },
                u'status_txt': u'OK'
            }
            return json.dumps(r)

        p_urlopen().read.side_effect = mocked_read
        url = 'https://air.mozilla.org/something/'
        short = utils.shorten_url(url)
        eq_(short, 'http://mzl.la/1adh2wT')
    def test_url_shortener_ok(self, p_urlopen):

        def mocked_read():
            r = {
                u'status_code': 200,
                u'data': {
                    u'url': u'http://mzl.la/1adh2wT',
                    u'hash': u'1adh2wT',
                    u'global_hash': u'1adh2wU',
                    u'long_url': u'https://air.mozilla.org/it-buildout/',
                    u'new_hash': 0
                },
                u'status_txt': u'OK'
            }
            return json.dumps(r)

        p_urlopen().read.side_effect = mocked_read
        url = 'https://air.mozilla.org/something/'
        short = utils.shorten_url(url)
        eq_(short, 'http://mzl.la/1adh2wT')
Exemple #8
0
def tweet_new_published_events(verbose=False):
    """Create EventTweet instances for events that have recently been
    published and are ready for public consumption."""
    now = timezone.now()
    events = Event.objects.scheduled().filter(
        created__gt=now - datetime.timedelta(days=7),
        created__lt=now,
        privacy=Event.PRIVACY_PUBLIC,
    ).approved().exclude(
        id__in=EventTweet.objects.values('event_id')
    )

    site = Site.objects.get_current()
    base_url = 'https://%s' % site.domain  # yuck!
    for event in events:
        if event.channels.filter(no_automated_tweets=True):
            if verbose:
                print "Skipping", repr(event.title), "because it's part of"
                print event.channels.filter(no_automated_tweets=True)
            continue
        # we have to try to manually create an appropriate tweet
        url = reverse('main:event', args=(event.slug,))
        abs_url = urlparse.urljoin(base_url, url)
        try:
            abs_url = shorten_url(abs_url)
        except (ImproperlyConfigured, ValueError) as err:  # pragma: no cover
            if verbose:  # pragma: no cover
                print "Failed to shorten URL"
                print err

        text = event.title
        if len(text) > 115:
            # Why not 140?
            # We've found that sometimes when you're trying to tweet
            # a piece of text that actually is less than 140 when
            # doing text+URL you can get strange errors from Twitter
            # that it's still too long.
            text = text[:115]

        text = unhtml('%s\n%s' % (
            text,
            abs_url
        ))
        text += '\n'
        tags = (
            event.tags.all()
            .extra(
                select={'lower_name': 'lower(name)'}
            ).order_by('lower_name')
        )
        for tag in tags:
            _tag = '#' + tag.name.replace(' ', '')
            # see comment above why we use 115 instead of 140
            if len(text + _tag) + 1 < 115:
                text += '%s ' % _tag
            else:
                break
        text = text.strip()

        if event.start_time > timezone.now():
            send_date = event.start_time - datetime.timedelta(minutes=30)
        else:
            send_date = timezone.now()  # send as soon as possible
        event_tweet = EventTweet.objects.create(
            event=event,
            text=text,
            include_placeholder=True,
            send_date=send_date,
        )
        if verbose:  # pragma: no cover
            print "Created", repr(event_tweet)