From cc4f986edbdbda3dc08678dd359dd652e9120a76 Mon Sep 17 00:00:00 2001
From: Andrew Williams
Date: Mon, 20 Dec 2010 12:17:14 +0000
Subject: [PATCH] Decoupled the "reddit" application from the main program
---
hr/models.py | 8 +--
hr/views.py | 11 ++--
reddit/urls.py | 11 ++++
reddit/views.py | 44 ++++++++++++++++
settings.py | 5 +-
sso/forms.py | 41 +++------------
sso/models.py | 1 -
sso/urls.py | 3 --
sso/views.py | 50 ++-----------------
templates/hr/applications/view.html | 5 +-
.../add_reddit_account.html} | 0
templates/sso/lookup/user.html | 6 ++-
templates/sso/profile.html | 3 ++
urls.py | 13 +++--
utils.py | 15 ++++++
15 files changed, 113 insertions(+), 103 deletions(-)
create mode 100644 reddit/urls.py
create mode 100644 reddit/views.py
rename templates/{sso/redditaccount.html => reddit/add_reddit_account.html} (100%)
diff --git a/hr/models.py b/hr/models.py
index 5a3d52e..b990bee 100644
--- a/hr/models.py
+++ b/hr/models.py
@@ -4,6 +4,7 @@ from django.contrib.auth.models import User
from eve_api.models import EVEPlayerCharacter, EVEPlayerCorporation
from hr.app_defines import *
+from utils import installed
class Application(models.Model):
""" Person's application to a corporation """
@@ -38,9 +39,10 @@ class Application(models.Model):
bl_items = Blacklist.objects.filter(models.Q(expiry_date__gt=datetime.now()) | models.Q(expiry_date=None))
# Check Reddit blacklists
- reddit_uids = self.user.redditaccount_set.all().values_list('username', flat=True)
- objs = bl_items.filter(type=BLACKLIST_TYPE_REDDIT, value__in=reddit_uids)
- blacklist.extend(objs)
+ if installed('reddit'):
+ reddit_uids = self.user.redditaccount_set.all().values_list('username', flat=True)
+ objs = bl_items.filter(type=BLACKLIST_TYPE_REDDIT, value__in=reddit_uids)
+ blacklist.extend(objs)
# Check email blacklists
blacklist.extend(bl_items.filter(type=BLACKLIST_TYPE_EMAIL, value=self.user.email.lower()))
diff --git a/hr/views.py b/hr/views.py
index 6100601..086bdd4 100644
--- a/hr/views.py
+++ b/hr/views.py
@@ -10,8 +10,9 @@ from django.template import RequestContext
from django.template.loader import render_to_string
from django.conf import settings
+from utils import installed
+
from eve_api.models import EVEAccount, EVEPlayerCorporation, EVEPlayerCharacter
-from reddit.models import RedditAccount
from hr.forms import CreateRecommendationForm, CreateApplicationForm, NoteForm
from hr.models import Recommendation, Application, Audit
from app_defines import *
@@ -28,9 +29,9 @@ def send_message(application, message_type, note=None):
except:
pass
- if len(application.user.redditaccount_set.all()) > 0:
- from reddit.tasks import send_reddit_message
- send_reddit_message.delay(to=application.user.redditaccount_set.all()[0].username, subject=subject, message=message)
+ if installed('reddit') and len(application.user.redditaccount_set.all()) > 0:
+ from reddit.tasks import send_reddit_message
+ send_reddit_message.delay(to=application.user.redditaccount_set.all()[0].username, subject=subject, message=message)
def check_permissions(user, application=None):
@@ -87,7 +88,7 @@ def view_application(request, applicationid):
else:
return HttpResponseRedirect(reverse('hr.views.index'))
- if request.GET.has_key('redditxhr') and request.is_ajax():
+ if installed('reddit') and request.GET.has_key('redditxhr') and request.is_ajax():
posts = []
for acc in app.user.redditaccount_set.all():
try:
diff --git a/reddit/urls.py b/reddit/urls.py
new file mode 100644
index 0000000..a06e0cd
--- /dev/null
+++ b/reddit/urls.py
@@ -0,0 +1,11 @@
+
+from django.conf.urls.defaults import *
+
+from sso import views
+
+urlpatterns = patterns('',
+ (r'^profile/add/reddit', views.reddit_add),
+ (r'^profile/del/reddit/$', views.reddit_del),
+ (r'^profile/del/reddit/(?P\d+)/$', views.reddit_del),
+)
+
diff --git a/reddit/views.py b/reddit/views.py
new file mode 100644
index 0000000..ceefdbd
--- /dev/null
+++ b/reddit/views.py
@@ -0,0 +1,44 @@
+from reddit.forms import RedditAccountForm
+from reddit.models import RedditAccount
+
+@login_required
+def reddit_add(request):
+ """ Add a Reddit account to a user's account """
+
+ if request.method == 'POST':
+ form = RedditAccountForm(request.POST)
+ if form.is_valid():
+ acc = RedditAccount()
+ acc.user = request.user
+ acc.username = form.cleaned_data['username']
+ try:
+ acc.api_update()
+ except RedditAccount.DoesNotExist:
+ messages.add_message(request, messages.ERROR, "Error, user %s does not exist on Reddit" % acc.username )
+ return render_to_response('sso/redditaccount.html', locals(), context_instance=RequestContext(request))
+ acc.save()
+
+ messages.add_message(request, messages.INFO, "Reddit account %s successfully added." % acc.username)
+ return redirect('sso.views.profile') # Redirect after POST
+ else:
+ defaults = { 'username': request.user.username, }
+ form = RedditAccountForm(defaults) # An unbound form
+
+ return render_to_response('reddit/add_reddit_account.html', locals(), context_instance=RequestContext(request))
+
+@login_required
+def reddit_del(request, redditid=0):
+ """ Delete a Reddit account from a user's account """
+
+ if redditid > 0 :
+ try:
+ acc = RedditAccount.objects.get(id=redditid)
+ except RedditAccount.DoesNotExist:
+ return redirect('sso.views.profile')
+
+ if acc.user == request.user:
+ acc.delete()
+ messages.add_message(request, messages.INFO, "Reddit account successfully deleted.")
+
+ return redirect('sso.views.profile')
+
diff --git a/settings.py b/settings.py
index b87388a..04cb246 100755
--- a/settings.py
+++ b/settings.py
@@ -182,8 +182,9 @@ CELERYBEAT_SCHEDULE = {
"schedule": timedelta(hours=6),
},
"api-log-clear": {
- "task": "eve_proxy.tasks.clear_old_logs"
- "schedule": timedelta(days=1)
+ "task": "eve_proxy.tasks.clear_old_logs",
+ "schedule": timedelta(days=1),
+ },
}
CELERY_SEND_TASK_ERROR_EMAILS = True
diff --git a/sso/forms.py b/sso/forms.py
index 33157cb..c66c6fe 100644
--- a/sso/forms.py
+++ b/sso/forms.py
@@ -4,9 +4,10 @@ from django import forms
from django.contrib.auth.models import User
from django.conf import settings
+from utils import installed
+
from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation
from sso.models import ServiceAccount, Service
-from reddit.models import RedditAccount
from registration.forms import RegistrationForm
class RegistrationFormUniqueEmailBlocked(RegistrationForm):
@@ -107,50 +108,20 @@ class ServiceAccountResetForm(forms.Form):
self.fields['password'] = self.password
-class RedditAccountForm(forms.Form):
- """ Reddit Account Form """
-
- username = forms.CharField(label = u'User ID', max_length=64)
-
- def clean(self):
- try:
- eaccount = RedditAccount.objects.get(username=self.cleaned_data['username'])
- except RedditAccount.DoesNotExist:
- return self.cleaned_data
- else:
- raise forms.ValidationError("This User ID is already registered")
-
class UserLookupForm(forms.Form):
""" User Lookup Form """
choices = [ (1, "Auth Username"),
(2, "Character"),
- (3, "Reddit ID"),
(4, "Email Address"), ]
type = forms.ChoiceField(label = u'Search type', choices = choices)
username = forms.CharField(label = u'User ID', max_length=64)
- def clean(self):
-
- if self.cleaned_data['type'] == 1:
- try:
- acc = User.objects.filter(username=self.cleaned_data['username'])
- except User.DoesNotExist:
- raise forms.ValidationError("User doesn't exist")
- elif self.cleaned_data['type'] == 2:
- try:
- acc = EVEPlayerCharacter.filter(name=self.cleaned_data['username'])
- except User.DoesNotExist:
- raise forms.ValidationError("Character doesn't exist")
- elif self.cleaned_data['type'] == 3:
- try:
- acc = RedditAccount.filter(name=self.cleaned_data['username'])
- except User.DoesNotExist:
- raise forms.ValidationError("Account doesn't exist")
-
- return self.cleaned_data
-
+ def __init__(self):
+ if installed('reddit'):
+ self.choices.append((3, "Reddit ID"))
+ forms.Form.__init__(self)
class APIPasswordForm(forms.Form):
diff --git a/sso/models.py b/sso/models.py
index 09bf928..3ef53c9 100644
--- a/sso/models.py
+++ b/sso/models.py
@@ -10,7 +10,6 @@ from django.utils import simplejson as json
from jsonfield.fields import JSONField
from eve_api.models import EVEAccount, EVEPlayerCorporation, EVEPlayerAlliance, EVEPlayerCharacter
-from reddit.models import RedditAccount
from services import get_api
diff --git a/sso/urls.py b/sso/urls.py
index 68d8a9e..06f13ea 100644
--- a/sso/urls.py
+++ b/sso/urls.py
@@ -13,9 +13,6 @@ urlpatterns = patterns('',
(r'^profile/del/service/(?P\d+)/$', views.service_del),
(r'^profile/reset/service/(?P\d+)/$', views.service_reset),
(r'^profile/reset/service/(?P\d+)/(?P\d+)$', views.service_reset),
- (r'^profile/add/reddit', views.reddit_add),
- (r'^profile/del/reddit/$', views.reddit_del),
- (r'^profile/del/reddit/(?P\d+)/$', views.reddit_del),
(r'^profile/refresh/eveapi/(?P\d+)/$', views.eveapi_refresh),
(r'^profile/log/eveapi/(?P\d+)/$', views.eveapi_log),
(r'^profile/characters$', views.characters),
diff --git a/sso/views.py b/sso/views.py
index 1a1337f..e103e2b 100644
--- a/sso/views.py
+++ b/sso/views.py
@@ -14,15 +14,15 @@ from django.template import RequestContext
from django.core import serializers
from django.conf import settings
+from utils import installed
+
from eve_api.models import EVEAccount, EVEPlayerCharacter
from eve_api.tasks import import_apikey, import_apikey_result
from eve_proxy.models import ApiAccessLog
from sso.models import ServiceAccount, Service, SSOUser, ExistingUser, ServiceError
-from sso.forms import EveAPIForm, UserServiceAccountForm, ServiceAccountResetForm, RedditAccountForm, UserLookupForm, APIPasswordForm
-
-from reddit.models import RedditAccount
+from sso.forms import EveAPIForm, UserServiceAccountForm, ServiceAccountResetForm, UserLookupForm, APIPasswordForm
def index(request):
@@ -244,47 +244,6 @@ def service_reset(request, serviceid=0):
return redirect('sso.views.profile')
-@login_required
-def reddit_add(request):
- """ Add a Reddit account to a user's account """
-
- if request.method == 'POST':
- form = RedditAccountForm(request.POST)
- if form.is_valid():
- acc = RedditAccount()
- acc.user = request.user
- acc.username = form.cleaned_data['username']
- try:
- acc.api_update()
- except RedditAccount.DoesNotExist:
- messages.add_message(request, messages.ERROR, "Error, user %s does not exist on Reddit" % acc.username )
- return render_to_response('sso/redditaccount.html', locals(), context_instance=RequestContext(request))
- acc.save()
-
- messages.add_message(request, messages.INFO, "Reddit account %s successfully added." % acc.username)
- return redirect('sso.views.profile') # Redirect after POST
- else:
- defaults = { 'username': request.user.username, }
- form = RedditAccountForm(defaults) # An unbound form
-
- return render_to_response('sso/redditaccount.html', locals(), context_instance=RequestContext(request))
-
-@login_required
-def reddit_del(request, redditid=0):
- """ Delete a Reddit account from a user's account """
-
- if redditid > 0 :
- try:
- acc = RedditAccount.objects.get(id=redditid)
- except RedditAccount.DoesNotExist:
- return redirect('sso.views.profile')
-
- if acc.user == request.user:
- acc.delete()
- messages.add_message(request, messages.INFO, "Reddit account successfully deleted.")
-
- return redirect('sso.views.profile')
-
@login_required
def user_view(request, username=None):
""" View a user's profile as a admin """
@@ -301,7 +260,6 @@ def user_view(request, username=None):
is_admin = request.user.is_staff
if is_admin:
services = ServiceAccount.objects.select_related('service').filter(user=user).only('service__name', 'service_uid', 'active')
- reddits = RedditAccount.objects.filter(user=user).all()
characters = EVEPlayerCharacter.objects.select_related('corporation').filter(eveaccount__user=user).only('id', 'name', 'corporation__name')
return render_to_response('sso/lookup/user.html', locals(), context_instance=RequestContext(request))
@@ -323,7 +281,7 @@ def user_lookup(request):
uid = EVEAccount.objects.filter(characters__name__icontains=form.cleaned_data['username']).values('user')
for u in uid: uids.append(u['user'])
users = User.objects.filter(id__in=uids).only('username')
- elif form.cleaned_data['type'] == '3':
+ elif installed('reddit') and form.cleaned_data['type'] == '3':
uid = RedditAccount.objects.filter(username__icontains=form.cleaned_data['username']).values('user')
for u in uid: uids.append(u['user'])
users = User.objects.filter(id__in=uids).only('username')
diff --git a/templates/hr/applications/view.html b/templates/hr/applications/view.html
index 2697866..8d6e073 100644
--- a/templates/hr/applications/view.html
+++ b/templates/hr/applications/view.html
@@ -2,6 +2,7 @@
{% load humanize %}
{% load if_extra %}
+{% load installed %}
{% block title %}View Application{% endblock %}
@@ -88,7 +89,7 @@
{% endfor %}
{% endfor %}
-
+{% if "reddit"|installed %}
{% if app.user.redditaccount_set.all %}
Reddit Accounts
@@ -151,7 +152,7 @@ function handleResponse() {
-
+{% endif %}
{% endif %}
{% endif %}
{% endblock %}
diff --git a/templates/sso/redditaccount.html b/templates/reddit/add_reddit_account.html
similarity index 100%
rename from templates/sso/redditaccount.html
rename to templates/reddit/add_reddit_account.html
diff --git a/templates/sso/lookup/user.html b/templates/sso/lookup/user.html
index 9da2a78..93d1a8d 100644
--- a/templates/sso/lookup/user.html
+++ b/templates/sso/lookup/user.html
@@ -70,15 +70,16 @@
{% endif %}
+{% if "reddit"|installed %}
Reddit Accounts
-{% if reddits %}
+{% if user.redditaccount_set.all %}
| Username | Created Date | Validated |
-{% for acc in reddits %}
+{% for acc in user.redditaccount_set.all %}
| {{ acc.username }} |
{{ acc.date_created }} |
{% if acc.validated %}Yes{% else %}No{% endif %} |
@@ -88,5 +89,6 @@
{% endif %}
{% endif %}
+{% endif %}
{% endblock %}
diff --git a/templates/sso/profile.html b/templates/sso/profile.html
index e3ec47a..f8bd731 100644
--- a/templates/sso/profile.html
+++ b/templates/sso/profile.html
@@ -1,6 +1,7 @@
{% extends "base.html" %}
{% load naturaltimediff %}
+{% load installed %}
{% block title %}Your Profile{% endblock %}
@@ -119,6 +120,7 @@ setup.
+{% if "reddit"|installed %}
Reddit Accounts
This is a list of all your current linked Reddit accounts
{% if user.redditaccount_set.all %}
@@ -140,6 +142,7 @@ setup.
Add a Reddit account
+{% endif %}
If you encounter any errors during using this service, copy the massive
error message into Pastebin and give
diff --git a/urls.py b/urls.py
index f61baa5..0134d44 100644
--- a/urls.py
+++ b/urls.py
@@ -1,7 +1,9 @@
from django.conf.urls.defaults import *
from django.contrib import admin
from django.contrib.auth.views import login
-import settings
+from django.conf import settings
+
+from utils import installed
from registration.views import register
from sso.forms import RegistrationFormUniqueEmailBlocked
@@ -17,8 +19,11 @@ urlpatterns = patterns('',
(r'^api/', include('api.urls')),
(r'^hr/', include('hr.urls')),
(r'^groups/', include('groups.urls')),
-)
-
-urlpatterns += patterns('',
(r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
+
+if installed('reddit'):
+ urlpatterns += patterns('',
+ ('', include('sso.urls')),
+ )
+
diff --git a/utils.py b/utils.py
index e32c049..5017612 100644
--- a/utils.py
+++ b/utils.py
@@ -38,3 +38,18 @@ def dump(qs, outfile_path, model=None):
row.append(val)
writer.writerow(row)
+
+def installed(value):
+ from django.conf import settings
+ apps = settings.INSTALLED_APPS
+ if "." in value:
+ for app in apps:
+ if app == value:
+ return True
+ else:
+ for app in apps:
+ fields = app.split(".")
+ if fields[-1] == value:
+ return True
+ return False
+