Decoupled the "reddit" application from the main program

This commit is contained in:
2010-12-20 12:17:14 +00:00
parent 0aef422d9a
commit cc4f986edb
15 changed files with 113 additions and 103 deletions

View File

@@ -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()))

View File

@@ -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:

11
reddit/urls.py Normal file
View File

@@ -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<redditid>\d+)/$', views.reddit_del),
)

44
reddit/views.py Normal file
View File

@@ -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')

View File

@@ -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

View File

@@ -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):

View File

@@ -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

View File

@@ -13,9 +13,6 @@ urlpatterns = patterns('',
(r'^profile/del/service/(?P<serviceid>\d+)/$', views.service_del),
(r'^profile/reset/service/(?P<serviceid>\d+)/$', views.service_reset),
(r'^profile/reset/service/(?P<serviceid>\d+)/(?P<accept>\d+)$', views.service_reset),
(r'^profile/add/reddit', views.reddit_add),
(r'^profile/del/reddit/$', views.reddit_del),
(r'^profile/del/reddit/(?P<redditid>\d+)/$', views.reddit_del),
(r'^profile/refresh/eveapi/(?P<userid>\d+)/$', views.eveapi_refresh),
(r'^profile/log/eveapi/(?P<userid>\d+)/$', views.eveapi_log),
(r'^profile/characters$', views.characters),

View File

@@ -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')

View File

@@ -2,6 +2,7 @@
{% load humanize %}
{% load if_extra %}
{% load installed %}
{% block title %}View Application{% endblock %}
@@ -88,7 +89,7 @@
{% endfor %}
{% endfor %}
</table>
{% if "reddit"|installed %}
{% if app.user.redditaccount_set.all %}
<h3>Reddit Accounts</h3>
<table>
@@ -151,7 +152,7 @@ function handleResponse() {
<div id="redditposts">
</div>
{% endif %}
{% endif %}
{% endif %}
{% endblock %}

View File

@@ -70,15 +70,16 @@
</table>
{% endif %}
{% if "reddit"|installed %}
<br/>
<h2>Reddit Accounts</h2>
{% if reddits %}
{% if user.redditaccount_set.all %}
<table>
<thead>
<tr><th>Username</th><th>Created Date</th><th>Validated</th></tr>
</thead>
<tbody>
{% for acc in reddits %}
{% for acc in user.redditaccount_set.all %}
<tr><td><a href="http://reddit.com/user/{{ acc.username }}/">{{ acc.username }}</a></td>
<td>{{ acc.date_created }}</td>
<td>{% if acc.validated %}Yes{% else %}No{% endif %}</td>
@@ -88,5 +89,6 @@
</table>
{% endif %}
{% endif %}
{% endif %}
{% endblock %}

View File

@@ -1,6 +1,7 @@
{% extends "base.html" %}
{% load naturaltimediff %}
{% load installed %}
{% block title %}Your Profile{% endblock %}
@@ -119,6 +120,7 @@ setup.</p>
<br/>
{% if "reddit"|installed %}
<h2>Reddit Accounts</h2>
<p>This is a list of all your current linked Reddit accounts</p>
{% if user.redditaccount_set.all %}
@@ -140,6 +142,7 @@ setup.</p>
<p>
<a href="{% url sso.views.reddit_add %}">Add a Reddit account</a>
</p>
{% endif %}
<p>If you encounter any errors during using this service, copy the massive
error message into <a href="http://pastebin.com/">Pastebin</a> and give

13
urls.py
View File

@@ -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<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
if installed('reddit'):
urlpatterns += patterns('',
('', include('sso.urls')),
)

View File

@@ -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