Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make migrations that remove all twitter models #924

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 0 additions & 20 deletions amelie/twitter/admin.py
Original file line number Diff line number Diff line change
@@ -1,21 +1 @@
from django.contrib import admin

from amelie.twitter.models import TwitterAccount, Tweet


class TwitterAccountAdmin(admin.ModelAdmin):
list_display = ('screenname', 'oauth_token', 'is_active', 'date_added',)
search_fields = ('screenname',)
list_filter = ('date_added', 'is_active',)
date_hierarchy = 'date_added'


class TweetAdmin(admin.ModelAdmin):
list_display = ('id', 'timestamp', 'account', 'content')
search_fields = ('account__screenname', 'content', )
list_filter = ('account',)
date_hierarchy = 'timestamp'


admin.site.register(TwitterAccount, TwitterAccountAdmin)
admin.site.register(Tweet, TweetAdmin)
22 changes: 0 additions & 22 deletions amelie/twitter/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,3 @@
from django.utils.translation import gettext_lazy as _l

from amelie.style.forms import inject_style
from amelie.twitter.models import TwitterAccount


class TweetForm(forms.Form):
account = forms.ModelChoiceField(queryset=TwitterAccount.active.filter(is_readonly=False), required=True)
template = forms.CharField(max_length=140, widget=widgets.Textarea(attrs={'class': 'characters', 'rows':'10', 'cols': '50'}))

def clean_template(self):
value = self.cleaned_data['template']

try:
t = Template(value)
except Exception:
raise forms.ValidationError(_l("Invalid template"))
return value

def send_tweet(self):
account = value = self.cleaned_data['account'].get_twython_instance()
account.updateStatus(status=self.cleaned_data['template'])
return True

inject_style(TweetForm)
5 changes: 0 additions & 5 deletions amelie/twitter/manager.py
Original file line number Diff line number Diff line change
@@ -1,6 +1 @@
from django.db import models


class TwitterAccountManager(models.Manager):
def get_queryset(self):
return super(TwitterAccountManager, self).get_queryset().filter(is_active=True)
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Generated by Django 4.2.16 on 2025-02-03 20:55

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
('twitter', '0002_auto_20201103_2220'),
]

operations = [
migrations.DeleteModel(
name='Tweet',
),
migrations.DeleteModel(
name='TwitterAccount',
),
]
53 changes: 0 additions & 53 deletions amelie/twitter/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,57 +2,4 @@
from django.db import models
from twython import Twython

from amelie.twitter.manager import TwitterAccountManager


class TwitterAccount(models.Model):
screenname = models.CharField(max_length=100, blank=False, null=False, unique=True)

oauth_token = models.CharField(max_length=100, blank=True)
oauth_token_secret = models.CharField(max_length=100, blank=True)

date_added = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_readonly = models.BooleanField(default=False)

objects = models.Manager()
active = TwitterAccountManager()

#some data to keep track of which tweets we already have
last_tweet = models.CharField(max_length=25, blank=True)
last_update = models.DateTimeField(auto_now_add=True)

#should the stream show in the app
show_in_app = models.BooleanField(default=True)

#app specific data
image_url = models.CharField(max_length=100, blank=True)

class Meta:
ordering = ['screenname', 'date_added']

def __str__(self):
return str(self.screenname)

def get_twython_instance(self):
# Not if we aren't active
if self.is_active == False:
raise Exception("Twitter account not active")
token = self.oauth_token if self.oauth_token else settings.TWITTER_OAUTH_TOKEN
secret = self.oauth_token_secret if self.oauth_token_secret else settings.TWITTER_OAUTH_SECRET
# Create a Twython instance
instance = Twython(
settings.TWITTER_APP_KEY, settings.TWITTER_APP_SECRET, token, secret
)

# Done
return instance


class Tweet(models.Model):
account = models.ForeignKey(TwitterAccount, on_delete=models.PROTECT)
content = models.TextField()
timestamp = models.DateTimeField()

def __str__(self):
return str(self.content)
28 changes: 0 additions & 28 deletions amelie/twitter/twitter.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,7 @@
from datetime import datetime, timedelta

from django.utils import timezone

from amelie.twitter.models import TwitterAccount, Tweet

update_interval = timedelta(seconds=300)


def update_streams():
twitter_accounts = TwitterAccount.objects.filter(is_active=True, last_update__lt=(timezone.now() - update_interval))

for account in twitter_accounts:
twython_instance = account.get_twython_instance()
tweet_set = None
if account.last_tweet is "":
tweet_set = twython_instance.get_user_timeline(screen_name=account.screenname, count=20)
else:
tweet_set = twython_instance.get_user_timeline(screen_name=account.screenname, since_id=account.last_tweet)

if(len(tweet_set) > 0):
account.last_tweet = tweet_set[0]["id"]
account.image_url = tweet_set[0]["user"]["profile_image_url_https"]
#twitter uses _normal images as default, we want the big images
#sadly twitter doesn't provide them in their api format, so we just replace normal with bigger
account.image_url.replace("normal", "bigger")
account.last_update = timezone.now()
account.save()

utc = timezone.utc
for raw_tweet in tweet_set:
date = datetime.strptime(raw_tweet["created_at"], "%a %b %d %H:%M:%S +0000 %Y")
date = date.replace(tzinfo=utc)
tweet = Tweet(account=account, content=raw_tweet["text"], timestamp=date)
tweet.save()
1 change: 0 additions & 1 deletion amelie/twitter/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,4 @@

urlpatterns = [
path('', views.index, name='index'),
path('new/', views.new_tweet, name='new_tweet'),
]
21 changes: 0 additions & 21 deletions amelie/twitter/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,8 @@
from django.utils.translation import gettext_lazy as _l

from amelie.tools.decorators import require_board
from amelie.twitter.forms import TweetForm


@require_board
def index(request):
return render(request, 'twitter_index.html', locals())


@require_board
def new_tweet(request):
form = TweetForm(data=request.POST or None)
preview = None
max_length = 140

if request.method == "POST":
if form.is_valid() and request.POST.get('preview', None):
preview = Template(form.cleaned_data['template']).render(RequestContext(request, {}))
elif form.is_valid():
if form.send_tweet():
message = _l('The tweet has been sent!')
else:
message = _l('Unfortunately, an error occurred.')

return render(request, 'message.html', locals())

return render(request, 'twitter_new_tweet.html', locals())
Loading