Permalink
Browse files

Merge remote branch 'alex/friends-refactor'

  • Loading branch information...
2 parents 46e83ac + dbfc216 commit 6aa7a492ac7e391bebd4c28d881c2fca93d17c33 @brosner brosner committed Apr 12, 2010
View
@@ -1,5 +1,12 @@
+0.2
+---
+
+ * changed the status field on the FriendshipInivtation to be an IntegerField
+ rather than a CharField
+ * removed any code not directly related to Friendship
+
0.1.5
-----
* fixed dependancy on django-email-confirmation which crept in by accident
- * doesn't directly depend on simplejson for in contact importer
+ * doesn't directly depend on simplejson for in contact importer
View
@@ -1,22 +1,12 @@
from django.contrib import admin
-from friends.models import Contact
from friends.models import Friendship, FriendshipInvitation, FriendshipInvitationHistory
-from friends.models import JoinInvitation
-
-
-class ContactAdmin(admin.ModelAdmin):
- list_display = ('id', 'name', 'email', 'user', 'added')
class FriendshipAdmin(admin.ModelAdmin):
list_display = ('id', 'from_user', 'to_user', 'added',)
-class JoinInvitationAdmin(admin.ModelAdmin):
- list_display = ('id', 'from_user', 'contact', 'status')
-
-
class FriendshipInvitationAdmin(admin.ModelAdmin):
list_display = ('id', 'from_user', 'to_user', 'sent', 'status',)
@@ -25,8 +15,6 @@ class FriendshipInvitationHistoryAdmin(admin.ModelAdmin):
list_display = ('id', 'from_user', 'to_user', 'sent', 'status',)
-admin.site.register(Contact, ContactAdmin)
admin.site.register(Friendship, FriendshipAdmin)
-admin.site.register(JoinInvitation, JoinInvitationAdmin)
admin.site.register(FriendshipInvitation, FriendshipInvitationAdmin)
admin.site.register(FriendshipInvitationHistory, FriendshipInvitationHistoryAdmin)
View
@@ -3,49 +3,24 @@
from django.contrib.auth.models import User
-from friends.models import *
+from friends.models import FriendshipInvitation
if "notification" in settings.INSTALLED_APPS:
from notification import models as notification
else:
notification = None
-if "emailconfirmation" in settings.INSTALLED_APPS:
- from emailconfirmation.models import EmailAddress
-else:
- EmailAddress = None
-
class UserForm(forms.Form):
-
def __init__(self, user=None, *args, **kwargs):
self.user = user
super(UserForm, self).__init__(*args, **kwargs)
-if EmailAddress:
- class JoinRequestForm(forms.Form):
-
- email = forms.EmailField(label="Email", required=True, widget=forms.TextInput(attrs={'size':'30'}))
- message = forms.CharField(label="Message", required=False, widget=forms.Textarea(attrs = {'cols': '30', 'rows': '5'}))
-
- def clean_email(self):
- # @@@ this assumes email-confirmation is being used
- self.existing_users = EmailAddress.objects.get_users_for(self.cleaned_data["email"])
- if self.existing_users:
- raise forms.ValidationError(u"Someone with that email address is already here.")
- return self.cleaned_data["email"]
-
- def save(self, user):
- join_request = JoinInvitation.objects.send_invitation(user, self.cleaned_data["email"], self.cleaned_data["message"])
- user.message_set.create(message="Invitation to join sent to %s" % join_request.contact.email)
- return join_request
-
-
class InviteFriendForm(UserForm):
-
to_user = forms.CharField(widget=forms.HiddenInput)
- message = forms.CharField(label="Message", required=False, widget=forms.Textarea(attrs = {'cols': '20', 'rows': '5'}))
+ message = forms.CharField(label="Message", required=False,
+ widget=forms.Textarea(attrs={'cols': '20', 'rows': '5'}))
def clean_to_user(self):
to_username = self.cleaned_data["to_user"]
@@ -58,22 +33,34 @@ def clean_to_user(self):
def clean(self):
to_user = User.objects.get(username=self.cleaned_data["to_user"])
- previous_invitations_to = FriendshipInvitation.objects.invitations(to_user=to_user, from_user=self.user)
+ previous_invitations_to = FriendshipInvitation.objects.invitations(
+ to_user=to_user,
+ from_user=self.user
+ )
if previous_invitations_to.count() > 0:
- raise forms.ValidationError(u"Already requested friendship with %s" % to_user.username)
+ raise forms.ValidationError(u"Already requested friendship with %s" %
+ to_user.username)
# check inverse
- previous_invitations_from = FriendshipInvitation.objects.invitations(to_user=self.user, from_user=to_user)
+ previous_invitations_from = FriendshipInvitation.objects.invitations(
+ to_user=self.user,
+ from_user=to_user
+ )
if previous_invitations_from.count() > 0:
- raise forms.ValidationError(u"%s has already requested friendship with you" % to_user.username)
+ raise forms.ValidationError(u"%s has already requested friendship with you" %
+ to_user.username)
return self.cleaned_data
def save(self):
to_user = User.objects.get(username=self.cleaned_data["to_user"])
message = self.cleaned_data["message"]
- invitation = FriendshipInvitation(from_user=self.user, to_user=to_user, message=message, status="2")
+ invitation = FriendshipInvitation(from_user=self.user,
+ to_user=to_user, message=message, status="2")
invitation.save()
if notification:
notification.send([to_user], "friends_invite", {"invitation": invitation})
- notification.send([self.user], "friends_invite_sent", {"invitation": invitation})
- self.user.message_set.create(message="Friendship requested with %s" % to_user.username) # @@@ make link like notification
+ notification.send([self.user], "friends_invite_sent", {
+ "invitation": invitation
+ })
+ self.user.message_set.create(message="Friendship requested with %s" %
+ to_user.username) # @@@ make link like notification
return invitation
View
@@ -1,112 +0,0 @@
-from django.conf import settings
-from django.utils import simplejson as json
-
-import gdata.contacts.service
-import vobject
-import ybrowserauth
-
-from friends.models import Contact
-
-
-def import_vcards(stream, user):
- """
- Imports the given vcard stream into the contacts of the given user.
-
- Returns a tuple of (number imported, total number of cards).
- """
-
- total = 0
- imported = 0
- for card in vobject.readComponents(stream):
- total += 1
- try:
- name = card.fn.value
- email = card.email.value
- try:
- Contact.objects.get(user=user, email=email)
- except Contact.DoesNotExist:
- Contact(user=user, name=name, email=email).save()
- imported += 1
- except AttributeError:
- pass # missing value so don't add anything
- return imported, total
-
-
-def import_yahoo(bbauth_token, user):
- """
- Uses the given BBAuth token to retrieve a Yahoo Address Book and
- import the entries with an email address into the contacts of the
- given user.
-
- Returns a tuple of (number imported, total number of entries).
- """
-
- ybbauth = ybrowserauth.YBrowserAuth(settings.BBAUTH_APP_ID, settings.BBAUTH_SHARED_SECRET)
- ybbauth.token = bbauth_token
- address_book_json = ybbauth.makeAuthWSgetCall("http://address.yahooapis.com/v1/searchContacts?format=json&email.present=1&fields=name,email")
- address_book = json.loads(address_book_json)
-
- total = 0
- imported = 0
-
- for contact in address_book["contacts"]:
- total += 1
- email = contact['fields'][0]['data']
- try:
- first_name = contact['fields'][1]['first']
- except (KeyError, IndexError):
- first_name = None
- try:
- last_name = contact['fields'][1]['last']
- except (KeyError, IndexError):
- last_name = None
- if first_name and last_name:
- name = first_name + " " + last_name
- elif first_name:
- name = first_name
- elif last_name:
- name = last_name
- else:
- name = None
- try:
- Contact.objects.get(user=user, email=email)
- except Contact.DoesNotExist:
- Contact(user=user, name=name, email=email).save()
- imported += 1
-
- return imported, total
-
-
-def import_google(authsub_token, user):
- """
- Uses the given AuthSub token to retrieve Google Contacts and
- import the entries with an email address into the contacts of the
- given user.
-
- Returns a tuple of (number imported, total number of entries).
- """
-
- contacts_service = gdata.contacts.service.ContactsService()
- contacts_service.auth_token = authsub_token
- contacts_service.UpgradeToSessionToken()
- entries = []
- feed = contacts_service.GetContactsFeed()
- entries.extend(feed.entry)
- next_link = feed.GetNextLink()
- while next_link:
- feed = contacts_service.GetContactsFeed(uri=next_link.href)
- entries.extend(feed.entry)
- next_link = feed.GetNextLink()
- total = 0
- imported = 0
- for entry in entries:
- name = entry.title.text
- for e in entry.email:
- email = e.address
- total += 1
- try:
- Contact.objects.get(user=user, email=email)
- except Contact.DoesNotExist:
- Contact(user=user, name=name, email=email).save()
- imported += 1
- return imported, total
@@ -12,7 +12,6 @@ def create_notice_types(app, created_models, verbosity, **kwargs):
notification.create_notice_type("friends_accept", _("Acceptance Received"), _("an invitation you sent has been accepted"), default=2)
notification.create_notice_type("friends_accept_sent", _("Acceptance Sent"), _("you have accepted an invitation you received"), default=1)
notification.create_notice_type("friends_otherconnect", _("Other Connection"), _("one of your friends has a new connection"), default=2)
- notification.create_notice_type("join_accept", _("Join Invitation Accepted"), _("an invitation you sent to join this site has been accepted"), default=2)
signals.post_syncdb.connect(create_notice_types, sender=notification)
else:
View
@@ -0,0 +1,56 @@
+from django.conf import settings
+from django.db import models
+from django.db.models import Q
+
+
+if "notification" in settings.INSTALLED_APPS:
+ from notification import models as notification
+else:
+ notification = None
+
+
+class FriendshipManager(models.Manager):
+ def friends_for_user(self, user):
+ friends = []
+ qs = self.filter(Q(from_user=user) | Q(to_user=user)).select_related(depth=1)
+ for friendship in qs:
+ if friendship.from_user == user:
+ friends.append({"friend": friendship.to_user, "friendship": friendship})
+ else:
+ friends.append({"friend": friendship.from_user, "friendship": friendship})
+ return friends
+
+ def are_friends(self, user1, user2):
+ return self.filter(
+ Q(from_user=user1, to_user=user2) |
+ Q(from_user=user2, to_user=user1)
+ ).count() > 0
+
+ def remove(self, user1, user2):
+ if self.filter(from_user=user1, to_user=user2):
+ friendship = self.filter(from_user=user1, to_user=user2)
+ elif self.filter(from_user=user2, to_user=user1):
+ friendship = self.filter(from_user=user2, to_user=user1)
+ friendship.delete()
+
+
+class FriendshipInvitationManager(models.Manager):
+ def invitations(self, user):
+ return self.filter(Q(from_user=user) | Q(to_user=user)).exclude(status__in=(5, 6, 7))
+
+ def create_friendship_request(self, from_user, to_user, msg=None):
+ inv = self.create(from_user=from_user, to_user=to_user,
+ message=msg or "", status=2)
+ if notification:
+ notification.send([to_user], "friends_invite", {"invitation": inv})
+ notification.send([from_user], "friends_invite_sent", {"invitation": inv})
+ return inv
+
+ def invitation_status(self, user1, user2):
+ invs = self.filter(
+ Q(from_user=user1, to_user=user2) |
+ Q(from_user=user2, to_user=user1)
+ )
+ if not invs:
+ return None
+ return max(inv.status for inv in invs)
Oops, something went wrong.

0 comments on commit 6aa7a49

Please sign in to comment.