indexden is now optional
[oweals/karmaworld.git] / karmaworld / apps / notes / tasks.py
1 #!/usr/bin/env python
2 # -*- coding:utf8 -*-
3 # Copyright (C) 2013  FinalsClub Foundation
4 import os
5
6 import traceback
7 from celery import task
8 from celery.utils.log import get_task_logger
9 from karmaworld.apps.notes.models import Note
10 import twitter
11 import gdshortener
12
13 logger = get_task_logger(__name__)
14
15 @task(name="tweet_note")
16 def tweet_note():
17     """Tweet about a new note."""
18
19     try:
20         TWITTER_CONSUMER_KEY = os.environ['TWITTER_CONSUMER_KEY']
21         TWITTER_CONSUMER_SECRET = os.environ['TWITTER_CONSUMER_SECRET']
22         TWITTER_ACCESS_TOKEN_KEY = os.environ['TWITTER_ACCESS_TOKEN_KEY']
23         TWITTER_ACCESS_TOKEN_SECRET = os.environ['TWITTER_ACCESS_TOKEN_SECRET']
24     except:
25         logger.warn("No twitter secrets found, not running tweet_note")
26         return
27
28     try:
29         api = twitter.Api(consumer_key=TWITTER_CONSUMER_KEY,
30                           consumer_secret=TWITTER_CONSUMER_SECRET,
31                           access_token_key=TWITTER_ACCESS_TOKEN_KEY,
32                           access_token_secret=TWITTER_ACCESS_TOKEN_SECRET)
33
34         newest_notes = Note.objects.all().order_by('-uploaded_at')[:100]
35         for n in newest_notes:
36             if not n.tweeted:
37                 update = tweet_string(n)
38                 logger.info("Tweeting: " + update)
39
40                 # Mark this tweeted before we actually tweet it
41                 # to be extra safe against double tweets
42                 n.tweeted = True
43                 n.save()
44
45                 api.PostUpdate(tweet_string(n))
46
47                 break
48     except:
49         logger.error(traceback.format_exc())
50
51
52 def tweet_string(note):
53     # This url will use 13 or less characters
54     shortener = gdshortener.ISGDShortener()
55     url = "http://www.karmanotes.org" + \
56         note.get_absolute_url()
57     short_url = shortener.shorten(url)[0]
58
59     # 50 characters
60     short_course = note.course.name[:50]
61
62     # 57 characters
63     short_note = note.name[:57]
64
65     if note.course.school:
66         school = note.course.school
67     else:
68         school = note.course.department.school
69
70     if school.hashtag:
71         return short_url + " #" + school.hashtag + " " + \
72         short_course + ": " + \
73         short_note
74     else:
75         return short_url + " " + \
76             short_course + ": " + \
77             short_note