def buy_tickets(request, event_id): from common.templatetags.commontags import referer_url event = get_object_or_404(Event.visible_objects.all(), pk=event_id) if not event.is_active: # can't buy tix for past events add_message(request, u"This event has expired.") return HttpResponseRedirect(event.get_absolute_url()) if not event.ticket_or_tm_url: # event doesn't have a ticket URL add_message(request, u"Sorry. This event doesn't have a ticket purchase link.") return HttpResponseRedirect(event.get_absolute_url()) redirect_to = sanitize_url(referer_url(event.ticket_or_tm_url)) # record this URL redirection src_email = 'email' == request.REQUEST.get('src', 'web').lower() if src_email: n_web, n_email = 0, 1 else: n_web, n_email = 1, 0 lnk, created = WebLink.objects.get_or_create( url=u"buy-tix-%s" % event.pk, defaults=dict(redirect_to=redirect_to, category='Buy Tickets'), ) lnk.redirect_to = redirect_to lnk.category = u'Buy Tickets' lnk.email_count += n_email lnk.web_count += n_web lnk.save() return HttpResponseRedirect(lnk.redirect_to)
def oauth_authorize(request): """Get an unauth token and redirect user to Foursquare's authorization URL.""" next = request.GET.get('next', None) if next: request.session['FOURSQUARE_NEXT_URL'] = next try: tw = FoursquareOAuthAPI() try: token = tw.get_unauthorised_request_token() except KeyError: # retry once tw.close() tw = FoursquareOAuthAPI() token = tw.get_unauthorised_request_token() request.session['FOURSQUARE_UNAUTH_TOKEN'] = token.to_string() auth_url = tw.get_authorisation_url(token) response = HttpResponseRedirect(auth_url) tw.close() return response except Exception, e: _log.exception(e) if request.user.is_authenticated(): add_message(request, u"We are unable to connect to Foursquare at the moment. Please try again in a few minutes.") else: add_message(request, u"We are unable to connect to Foursquare at the moment. Please try again in a few minutes.") return _denied_response(request)
def _logout_redirect(request, next): logout(request) request.delete_fb_cookies = True add_message( request, u"Ooops, your Facebook session has expired. Please sign-in again.") return HttpResponseRedirect(next)
def authorize(request): """Get an unauth token and redirect user to Twitter's authorization URL.""" next = request.GET.get('next', None) if next: request.session['TWITTER_NEXT_URL'] = next try: tw = TwitterAPI() try: token = tw.get_unauthorised_request_token() except KeyError: # retry once tw.close() tw = TwitterAPI() token = tw.get_unauthorised_request_token() request.session['TWITTER_UNAUTH_TOKEN'] = token.to_string() auth_url = tw.get_authorisation_url(token) response = HttpResponseRedirect(auth_url) tw.close() return response except Exception, e: _log.exception(e) if request.user.is_authenticated(): add_message(request, u"We are unable to connect to Twitter at the moment. Please try again in a few minutes.") else: add_message(request, u"We are unable to connect to Twitter at the moment. Please continue signing up below. You will be able to connect your account to Twitter later from our homepage.") return _denied_response(request)
async def get(self): podcast: Podcast = await self._get_object() episodes = await podcast.get_episodes_async(self.request.app.objects, self.user.id) await self._delete_files(podcast, episodes) await self.request.app.objects.delete(podcast, recursive=True) add_message(self.request, f'Podcast "{podcast.name}" was deleted') return redirect(self.request, "podcast_list")
async def get(self): invite_token = self.request.query.get("t", "") user_invite = await self._get_user_invite(self.request.app.objects, invite_token) if user_invite: return {"token": user_invite.token, "email": user_invite.email} add_message(self.request, "Provided token is missed or incorrect", kind="danger") return {}
async def get(self): token = self.request.query.get("t", "") try: user = await self.authenticate_user(self.request.app.objects, token) except AuthenticationFailedError as error: logger.error(f"We couldn't recognize recover password token: {error}") add_message(self.request, "Provided token is missed or incorrect", kind="danger") return {} return {"token": token, "email": user.email}
async def get(self): podcast_id = self.request.match_info.get("podcast_id") episode: Episode = await self._get_object() await self._delete_file(episode) await self.request.app.objects.delete(episode, recursive=True) await self._generate_rss(podcast_id) self.logger.info(f"Episode {episode} successful removed.") add_message( self.request, f"Episode for youtube ID {episode.source_id} was removed.") return redirect(self.request, "podcast_details", podcast_id=podcast_id)
async def get(self): episode: Episode = await self._get_object() self.logger.info(f'Start download process for "{episode.watch_url}"') add_message(self.request, f"Downloading for youtube {episode.source_id} started.") episode.status = Episode.STATUS_DOWNLOADING await self.request.app.objects.update(episode) await self._enqueue_task( tasks.download_episode, youtube_link=episode.watch_url, episode_id=episode.id, ) return redirect(self.request, "progress")
def fb_connect(request): """Merge FB session with current profile""" next = request.REQUEST.get("next", "/") if request.user_profile.fb_userid: # User has already connected an FB account add_message(request, u"You've already connected a Facebook account.") return HttpResponseRedirect(next) api_key, secret = settings.FB_API_KEY, settings.FB_SECRET_KEY fb_uid, fb_session_key, fb_session_secret = get_fb_session(request) if not fb_uid: return _logout_redirect(request, next) try: profile = UserProfile.objects.active().filter(fb_userid=fb_uid)[:1].get() add_message(request, u"You've already connected this Facebook account with another RiotVine account.") return HttpResponseRedirect(next) except UserProfile.DoesNotExist: # save fb id profile = request.user_profile profile.fb_userid = fb_uid profile.is_sso = False profile.fb_suggested = 0 profile.save() request.user_profile = profile request.session['fb_uid'] = fb_uid # if this user was invited by any existing users, create a friendship inv = FBInvitedUser.objects.select_related('inviter_profile').filter(fb_userid=fb_uid) for u in inv: inviter = u.inviter_profile Friendship.objects.make_friends(inviter, request.user_profile, source='fb') u.delete() # calculate new suggested friends and add their count to session try: user_profile = profile all_fb_friends = _get_connected_friends(api_key, secret, fb_session_key, fb_uid) fb_users = UserProfile.objects.active().exclude(fb_userid=u'') app_friends = set(list(fb_users.filter(friends2__user_profile1__pk=user_profile.pk).values_list('fb_userid', flat=True))) pending_friends = set(list(fb_users.filter(pending_friends_inviter__invitee_profile__pk=user_profile.pk).values_list('fb_userid', flat=True))) invited_friends = set(list(fb_users.filter(pending_friends_invitee__inviter_profile__pk=user_profile.pk).values_list('fb_userid', flat=True))) recommended_friends = all_fb_friends.difference(app_friends).difference(pending_friends).difference(invited_friends) db_reco, created = FBSuggestedFriends.objects.get_or_create(user_profile=user_profile) db_recommended_friends = db_reco.friendset new_friends = recommended_friends.difference(db_recommended_friends) if new_friends: if settings.FB_AUTO_FRIEND: num_auto_friended = auto_friend(profile, new_friends) _log.debug("Auto-friended %s friends of %s", num_auto_friended, profile) else: request.session['num_fb_new_friends'] = len(new_friends) except Exception, e: _log.exception(e)
async def wrapped(self, *args, **kwargs): try: return await func(self, *args, **kwargs) except AuthenticationRequiredError as ex: logger.warning(f"Trying to use unauth access: {ex}") add_message(self.request, "LogIn to continue.") redirect(self.request, "sign_in") except BaseApplicationError as ex: message = getattr(ex, "message", None) or str(ex) details = getattr(ex, "details", None) if details: message = f"{message}: {details}" add_message(self.request, message, kind="error") raise web.HTTPFound(self.request.path)
async def post(self): """ Check email and login """ cleaned_data = await self._validate() email = cleaned_data["email"] password = cleaned_data["password"] if not email: add_message(self.request, "Provide both email and password", kind="warning") redirect(self.request, "sign_in") try: user = await self.authenticate(email, password) self._login_and_redirect(user) except User.DoesNotExist: logger.info("Not found user with email [%s]", email) raise AuthenticationFailedError redirect(self.request, "sign_in")
def invited_friends(request): """Facebook posts the IDs of invited friends here""" next = request.REQUEST.get('next', reverse("account")) user_profile = request.user_profile if request.method == 'POST': data = request.POST fr_list = data.getlist("ids[]") if fr_list: for fb_uid in fr_list: FBInvitedUser.objects.get_or_create( inviter_profile=user_profile, fb_userid=unicode(fb_uid) ) n = len(fr_list) if n == 1: add_message(request, u"You've invited a friend to join %s!" % settings.UI_SETTINGS['UI_SITE_TITLE']) else: add_message(request, u"You've invited %s friends to join %s!" % (n, settings.UI_SETTINGS['UI_SITE_TITLE'])) return HttpResponseRedirect(next)
def oauth_callback(request): """This is where Foursquare will redirect the user after this app has been authorized.""" try: unauthed_token = request.session.get('FOURSQUARE_UNAUTH_TOKEN', None) oauth_verifier = request.GET.get('oauth_verifier', None) try: if unauthed_token: del request.session['FOURSQUARE_UNAUTH_TOKEN'] except KeyError: pass if not unauthed_token: _log.debug("Unauthenticated token not found in session") return _denied_response(request) token = oauth.OAuthToken.from_string(unauthed_token) oauth_token = request.GET.get('oauth_token', None) if token.key != oauth_token: _log.debug("Tokens did not match %s - %s", token.key, oauth_token) return _denied_response(request) tw = FoursquareOAuthAPI() try: access_token = tw.exchange_request_token_for_access_token(token, oauth_verifier) except KeyError: tw.close() return _denied_response(request) fsq_profile = tw.get_profile(access_token) tw.close() _log.debug("Foursquare profile response:\n%s", fsq_profile) fsq_profile = simplejson.loads(fsq_profile) if 'user' in fsq_profile: uid = fsq_profile.get('user', {}).get('id', None) if uid and not request.user_profile.fsq_userid: uid = unicode(uid) request.user_profile.fsq_userid = uid request.user_profile.save() checkin_uids = [uid] uid_userprofile_dict = {uid:request.user_profile} EventCheckin.objects.connect_profiles_to_checkins(checkin_uids, uid_userprofile_dict) add_message(request, u"Your Foursquare setup is now complete!") except Exception, e: _log.exception(e) add_message(request, u"We are unable to connect to Foursquare at the moment. Please try again in a few minutes.") return _denied_response(request)
def invited_friends(request): """Facebook posts the IDs of invited friends here""" next = request.REQUEST.get('next', reverse("account")) user_profile = request.user_profile if request.method == 'POST': data = request.POST fr_list = data.getlist("ids[]") if fr_list: for fb_uid in fr_list: FBInvitedUser.objects.get_or_create( inviter_profile=user_profile, fb_userid=unicode(fb_uid)) n = len(fr_list) if n == 1: add_message( request, u"You've invited a friend to join %s!" % settings.UI_SETTINGS['UI_SITE_TITLE']) else: add_message( request, u"You've invited %s friends to join %s!" % (n, settings.UI_SETTINGS['UI_SITE_TITLE'])) return HttpResponseRedirect(next)
def confirm_account(request, user_id=None, code=None, template='registration/confirm_account_form.html'): ctx = {} next = request.REQUEST.get("next", reverse("list_events")) if user_id and code: # user visited the direct confirmation link activation_code = u"%s-%s" % (user_id, code) profile, mesg = UserProfile.objects.activate_user(activation_code) if profile: add_message(request, u"Thank you for confirming your email address.") if not request.user.is_authenticated(): user = profile.user backend = get_backends()[0] user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) login(request, user) return HttpResponseRedirect(next) else: add_message(request, mesg) if request.method == 'POST': # user has typed in the confirmation code manually form = forms.ActivationForm(data=request.POST, files=request.FILES) if form.is_valid(): add_message(request, u"Thank you for confirming your email address.") if not request.user.is_authenticated(): user = form.user_profile.user backend = get_backends()[0] user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) login(request, user) return HttpResponseRedirect(next) else: form = forms.ActivationForm() ctx['form'] = form ctx['next'] = next return render_view(request, template, ctx)
async def get(self): self.request.session.pop("user") add_message(self.request, "You are logged out") redirect(self.request, "index")
def manage_friends(request, template='fb/manage_friends.html'): """Show current FB friends with checkboxes allowing user to connect/disconnect with their friends. The view is divided into these parts: * Friends you're sharing events with * Suggested Friends The old view (now defunt) was divided into more granular parts: * Users who've shared a friendship with this user (ordered by sharing recency) and are awaiting this user's confirmation (actions: confirm, reject) * Users that are friends of this user on FB but not on our site (actions: friend) * Users who are already friends of this user (actions: unfriend) * Users whom this user has already invited to be friends (actions: cancel invitation) """ next = request.REQUEST.get('next', reverse("fb_manage_friends")) user_profile = request.user_profile user = user_profile.user api_key, secret = settings.FB_API_KEY, settings.FB_SECRET_KEY fb_uid, fb_session_key, fb_session_secret = get_fb_session(request) if not fb_uid: return _logout_redirect(request, next) all_fb_friends = _get_connected_friends(api_key, secret, fb_session_key, fb_uid) fb_users = UserProfile.objects.active().exclude(fb_userid=u'') app_friends = set( list( fb_users.filter( friends2__user_profile1__pk=user_profile.pk).values_list( 'fb_userid', flat=True))) pending_friends = set( list( fb_users.filter( pending_friends_inviter__invitee_profile__pk=user_profile.pk). values_list('fb_userid', flat=True))) invited_friends = set( list( fb_users.filter( pending_friends_invitee__inviter_profile__pk=user_profile.pk). values_list('fb_userid', flat=True))) recommended_friends = all_fb_friends.difference(app_friends).difference( pending_friends).difference(invited_friends) if request.method == 'GET' and request.REQUEST.get("auto", False): # if there are no recommended friends, redirect to invite friends if not recommended_friends: return HttpResponseRedirect( reverse("fb_invite_friends") + "?next=%s" % next) db_reco, created = FBSuggestedFriends.objects.get_or_create( user_profile=user_profile) db_reco.friendset = recommended_friends db_reco.save() request.session['num_fb_new_friends'] = 0 # user has seen these friends ctx = { 'needs_fbml': True, 'next': next, # 'pending_friends':pending_friends, 'recommended_friends': recommended_friends, 'app_friends': app_friends, # 'invited_friends':invited_friends, } if request.method == 'POST': # process form submission data = request.POST # pends = set(data.getlist('pending')) # invs = set(data.getlist('invited')) curs = set(data.getlist('current')) recos = data.getlist('recommended') # Current for f in Friendship.objects.select_related('user_profile2').filter( user_profile1__pk=user_profile.pk): fb_uid = f.user_profile2.fb_userid if not fb_uid: continue if fb_uid not in app_friends: continue if fb_uid not in curs: # friendship was unchecked Friendship.objects.disconnect_friends(f.user_profile2, user_profile) # Recommended n = 0 for profile in UserProfile.objects.active().filter( fb_userid__in=recos): fb_uid = profile.fb_userid if fb_uid not in recommended_friends: continue # establish bi-directional friendship immediately Friendship.objects.make_friends(user_profile, profile, source='fb') n += 1 if n: if n == 1: add_message(request, u"You're sharing events with one new friend now.") else: add_message( request, u"You're sharing events with %s new friends now." % n) return HttpResponseRedirect(next) return render_view(request, template, ctx)
async def _get_episode_data(self, same_episode: Episode, podcast_id: int, video_id: str, youtube_link: str) -> dict: """ Allows to get information for new episode. This info can be given from same episode (episode which has same source_id) and part information - from YouTube. :return: dict with information for new episode """ if same_episode: self.logger.info( f"Episode for video {video_id} already exists: {same_episode}. " f"Using for information about downloaded file.") same_episode_data = same_episode.to_dict(field_names=[ "source_id", "watch_url", "title", "description", "image_url", "author", "length", "file_size", "file_name", "remote_url", ]) else: self.logger.info( f"New episode for video {video_id} will be created.") same_episode_data = {} youtube_info = None try: youtube_info = await get_youtube_info(youtube_link) except YoutubeExtractInfoError: add_message(self.request, "Sorry.. Fetching YouTube video was failed", kind="error") if youtube_info: new_episode_data = { "source_id": video_id, "watch_url": youtube_info.watch_url, "title": self._replace_special_symbols(youtube_info.title), "description": self._replace_special_symbols(youtube_info.description), "image_url": youtube_info.thumbnail_url, "author": youtube_info.author, "length": youtube_info.length, "file_size": same_episode_data.get("file_size"), "file_name": same_episode_data.get("file_name") or get_file_name(video_id), "remote_url": same_episode_data.get("remote_url"), } message = "Episode was successfully created from the YouTube video." self.logger.info(message) self.logger.debug("New episode data = %s", new_episode_data) add_message(self.request, message) elif same_episode: message = "Episode will be copied from other episode with same video." self.logger.info(message) add_message(self.request, message) new_episode_data = same_episode_data else: raise YoutubeFetchError new_episode_data.update({ "podcast_id": podcast_id, "created_by_id": self.user.id }) return new_episode_data
app_friends = set(list(fb_users.filter(friends2__user_profile1__pk=user_profile.pk).values_list('fb_userid', flat=True))) pending_friends = set(list(fb_users.filter(pending_friends_inviter__invitee_profile__pk=user_profile.pk).values_list('fb_userid', flat=True))) invited_friends = set(list(fb_users.filter(pending_friends_invitee__inviter_profile__pk=user_profile.pk).values_list('fb_userid', flat=True))) recommended_friends = all_fb_friends.difference(app_friends).difference(pending_friends).difference(invited_friends) db_reco, created = FBSuggestedFriends.objects.get_or_create(user_profile=user_profile) db_recommended_friends = db_reco.friendset new_friends = recommended_friends.difference(db_recommended_friends) if new_friends: if settings.FB_AUTO_FRIEND: num_auto_friended = auto_friend(profile, new_friends) _log.debug("Auto-friended %s friends of %s", num_auto_friended, profile) else: request.session['num_fb_new_friends'] = len(new_friends) except Exception, e: _log.exception(e) add_message(request, u"You've connected your Facebook account successfully.") return HttpResponseRedirect(next) @transaction.commit_on_success @login_required def manage_friends(request, template='fb/manage_friends.html'): """Show current FB friends with checkboxes allowing user to connect/disconnect with their friends. The view is divided into these parts: * Friends you're sharing events with * Suggested Friends The old view (now defunt) was divided into more granular parts: * Users who've shared a friendship with this user (ordered by sharing recency) and are awaiting this user's confirmation (actions: confirm, reject)
def manage_friends(request, template='fb/manage_friends.html'): """Show current FB friends with checkboxes allowing user to connect/disconnect with their friends. The view is divided into these parts: * Friends you're sharing events with * Suggested Friends The old view (now defunt) was divided into more granular parts: * Users who've shared a friendship with this user (ordered by sharing recency) and are awaiting this user's confirmation (actions: confirm, reject) * Users that are friends of this user on FB but not on our site (actions: friend) * Users who are already friends of this user (actions: unfriend) * Users whom this user has already invited to be friends (actions: cancel invitation) """ next = request.REQUEST.get('next', reverse("fb_manage_friends")) user_profile = request.user_profile user = user_profile.user api_key, secret = settings.FB_API_KEY, settings.FB_SECRET_KEY fb_uid, fb_session_key, fb_session_secret = get_fb_session(request) if not fb_uid: return _logout_redirect(request, next) all_fb_friends = _get_connected_friends(api_key, secret, fb_session_key, fb_uid) fb_users = UserProfile.objects.active().exclude(fb_userid=u'') app_friends = set(list(fb_users.filter(friends2__user_profile1__pk=user_profile.pk).values_list('fb_userid', flat=True))) pending_friends = set(list(fb_users.filter(pending_friends_inviter__invitee_profile__pk=user_profile.pk).values_list('fb_userid', flat=True))) invited_friends = set(list(fb_users.filter(pending_friends_invitee__inviter_profile__pk=user_profile.pk).values_list('fb_userid', flat=True))) recommended_friends = all_fb_friends.difference(app_friends).difference(pending_friends).difference(invited_friends) if request.method == 'GET' and request.REQUEST.get("auto", False): # if there are no recommended friends, redirect to invite friends if not recommended_friends: return HttpResponseRedirect(reverse("fb_invite_friends") + "?next=%s" % next) db_reco, created = FBSuggestedFriends.objects.get_or_create(user_profile=user_profile) db_reco.friendset = recommended_friends db_reco.save() request.session['num_fb_new_friends'] = 0 # user has seen these friends ctx = { 'needs_fbml':True, 'next':next, # 'pending_friends':pending_friends, 'recommended_friends':recommended_friends, 'app_friends':app_friends, # 'invited_friends':invited_friends, } if request.method == 'POST': # process form submission data = request.POST # pends = set(data.getlist('pending')) # invs = set(data.getlist('invited')) curs = set(data.getlist('current')) recos = data.getlist('recommended') # Current for f in Friendship.objects.select_related('user_profile2').filter(user_profile1__pk=user_profile.pk): fb_uid = f.user_profile2.fb_userid if not fb_uid: continue if fb_uid not in app_friends: continue if fb_uid not in curs: # friendship was unchecked Friendship.objects.disconnect_friends(f.user_profile2, user_profile) # Recommended n = 0 for profile in UserProfile.objects.active().filter(fb_userid__in=recos): fb_uid = profile.fb_userid if fb_uid not in recommended_friends: continue # establish bi-directional friendship immediately Friendship.objects.make_friends(user_profile, profile, source='fb') n += 1 if n: if n == 1: add_message(request, u"You're sharing events with one new friend now.") else: add_message(request, u"You're sharing events with %s new friends now." % n) return HttpResponseRedirect(next) return render_view(request, template, ctx)
async def post(self): podcast_id = int(self.request.match_info.get("podcast_id")) podcast: Podcast = await self._get_object() cleaned_data = await self._validate() youtube_link = cleaned_data["youtube_link"].strip() video_id = get_video_id(youtube_link) if not video_id: add_message(self.request, f"YouTube link is not correct: {youtube_link}") return redirect(self.request, "podcast_details", podcast_id=podcast_id) same_episodes: Iterable[ Episode] = await self.request.app.objects.execute( Episode.select().where(Episode.source_id == video_id).order_by( Episode.created_at.desc())) episode_in_podcast, last_same_episode = None, None for episode in same_episodes: last_same_episode = last_same_episode or episode if episode.podcast_id == podcast_id: episode_in_podcast = episode break if episode_in_podcast: self.logger.info( f"Episode for video [{video_id}] already exists for current " f"podcast {podcast_id}. Redirecting to {episode_in_podcast}..." ) add_message(self.request, "Episode already exists in podcast.") return redirect( self.request, "episode_details", podcast_id=podcast_id, episode_id=episode_in_podcast.id, ) try: episode_data = await self._get_episode_data( same_episode=last_same_episode, podcast_id=podcast_id, video_id=video_id, youtube_link=youtube_link, ) except YoutubeFetchError: return redirect(self.request, "podcast_details", podcast_id=podcast_id) episode = await self.request.app.objects.create( Episode, **episode_data) if podcast.download_automatically: episode.status = Episode.STATUS_DOWNLOADING await self.request.app.objects.update(episode) await self._enqueue_task( tasks.download_episode, youtube_link=episode.watch_url, episode_id=episode.id, ) add_message( self.request, f"Downloading for youtube {episode.source_id} was started.", ) if is_mobile_app(self.request): return redirect(self.request, "progress") return redirect( self.request, "episode_details", podcast_id=podcast_id, episode_id=str(episode.id), )
async def get(self): podcast = await self._get_object() await self._generate_rss(podcast.id) add_message(self.request, f"RSS for podcast {podcast.name} will be refreshed soon") return redirect(self.request, "podcast_details", podcast_id=podcast.id)
def fb_login(request): next = request.REQUEST.get("next", "/") if request.user.is_authenticated(): return HttpResponseRedirect(next) # if user has an FB Connect session, create account and # log the user in. api_key, secret = settings.FB_API_KEY, settings.FB_SECRET_KEY fb_uid, fb_session_key, fb_session_secret = get_fb_session(request) if not fb_uid: return _logout_redirect(request, next) # Create account if necessary new_signup = True try: profile = UserProfile.objects.active().filter( fb_userid=fb_uid)[:1].get() new_signup = False # account exists; log the user in user = profile.user if user.email.startswith("sso+fb_"): # get FB proxied email and save it under this user's record uinfo = get_user_info(api_key, secret, fb_session_key, fb_uid) if uinfo: name, email = uinfo['name'], uinfo['email'] if email: user.email = email user.save() profile.is_sso = False profile.send_reminders = True profile.send_favorites = True profile.save() except UserProfile.DoesNotExist: # create new acount new_signup = True email = request.session.get("email", None) if not email: add_message( request, u"Create a new account below in two easy steps before signing in with Facebook." ) return HttpResponseRedirect(reverse("signup") + "?next=" + next) uinfo = get_user_info(api_key, secret, fb_session_key, fb_uid) # screen_name, name, email = None, None, None screen_name, name = None, None if uinfo: # name, email = uinfo['name'], uinfo['email'] name = uinfo['name'] if name: # screen name is firstname followed by last initial; all lowercased screen_name = name.lower().strip() x = screen_name.split(' ') if len(x) > 1: firstname, lastname = x[0], x[1] if lastname: screen_name = firstname + lastname[0] else: screen_name = firstname screen_name = slugify(screen_name)[:25] unames = list( User.objects.filter( username__istartswith=screen_name).values_list( "username", flat=True).order_by("username")) unames = set([x.lower() for x in unames]) if screen_name in unames: # generate a unique screen_name by suffixing it with a number for n in range(2, 1000): s = u"%s%s" % (screen_name, n) if s not in unames: screen_name = s break if not screen_name: # Use FB User ID as the screen name screen_name = fb_uid if User.objects.filter(username=screen_name).count(): # screen name not available. Generate one with a random suffix screen_name = u''.join( [screen_name.strip()[:25], u'-', uuid4().hex[::6]]) # create user and profile user = User.objects.create( username=screen_name, first_name='', last_name='', email=email or u'*****@*****.**' % uuid4().hex[::5], ) profile = user.get_profile() profile.fb_userid = fb_uid profile.is_sso = False profile.send_reminders = bool(email) profile.send_favorites = bool(email) profile.fb_suggested = 0 profile.save() # annotate the user object with the path of the backend so that # login() works without a password: backend = get_backends()[0] user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) login(request, user) if new_signup: user.message_set.create( message=_(u'Thank you for signing-up with Facebook!')) _log.debug("FB user %s logged in" % profile.username) request.user_profile = profile request.session['fb_uid'] = fb_uid request.session['fb_session_key'] = fb_session_key # if this user was invited by any existing users, create a friendship inv = FBInvitedUser.objects.select_related('inviter_profile').filter( fb_userid=fb_uid) for u in inv: inviter = u.inviter_profile Friendship.objects.make_friends(inviter, request.user_profile, source='fb') u.delete() # calculate new suggested friends and add their count to session try: user_profile = profile all_fb_friends = _get_connected_friends(api_key, secret, fb_session_key, fb_uid) fb_users = UserProfile.objects.active().exclude(fb_userid=u'') app_friends = set( list( fb_users.filter( friends2__user_profile1__pk=user_profile.pk).values_list( 'fb_userid', flat=True))) pending_friends = set( list( fb_users.filter( pending_friends_inviter__invitee_profile__pk=user_profile. pk).values_list('fb_userid', flat=True))) invited_friends = set( list( fb_users.filter( pending_friends_invitee__inviter_profile__pk=user_profile. pk).values_list('fb_userid', flat=True))) recommended_friends = all_fb_friends.difference( app_friends).difference(pending_friends).difference( invited_friends) db_reco, created = FBSuggestedFriends.objects.get_or_create( user_profile=user_profile) db_recommended_friends = db_reco.friendset new_friends = recommended_friends.difference(db_recommended_friends) if new_friends: if new_signup and settings.FB_AUTO_FRIEND: num_auto_friended = auto_friend(profile, new_friends) _log.debug("Auto-friended %s friends of %s", num_auto_friended, profile) else: request.session['num_fb_new_friends'] = len(new_friends) except Exception, e: _log.exception(e)
def search_events(request, location=None): ctx = {'title':'Upcoming Events', 'searched':True, 'is_search':True, 'limit':None} ctx['rpp'] = int(request.REQUEST.get('rpp', 10)) location = location or request.location request.location = location # stick user to this location going forward request.location_name = settings.LOCATION_DATA.get(location, settings.EMPTY_LOCATION_DATA)[3] today, td = today_timedelta_by_location(location) qx = Event.objects.active(attending_user=request.user_profile, today=today).order_by('event_date', 'event_start_time', 'pk') loc = request.REQUEST.get("location", None) any_loc = loc == 'any' if not any_loc: # qx = qx.exclude(ext_event_source='mlb2010', location='user-entered') qx = qx.exclude(location='user-entered') # don't show user entered events on city pages f = request.GET.get('filter', '').lower() sort_by = request.GET.get('sort', '').lower() by_date = request.GET.get('date', None) choices = request.GET.getlist('choices') if 'free' in choices: qx = qx.filter(is_free=True) if 'checkins' in sort_by: # Checkins must automatically limit the view to today f = 'today' if f: if not request.user_profile and f in ('favorites', 'my-calendar', 'recommended'): add_message(request, "You will need to sign in first.") return HttpResponseRedirect(u"%s?next=%s" % (reverse("signin"), request.get_full_path())) ctx['filter'] = f if f in ('favorites', 'my-calendar') and request.user_profile: ctx['title'] = "I'm In For:" qx = qx.filter( attendee__attendee_profile=request.user_profile ).distinct().order_by('event_date', 'event_start_time', 'pk') if settings.CALENDAR_FILTER_BY_LOCATION: qx = qx.filter(location__in=('destination', 'user-entered', location)) elif f == 'recommended' and request.user_profile: ctx['title'] = "Friends' Events" qx = qx.filter( recommendedevent__user_profile=request.user_profile ).distinct().order_by('event_date', 'event_start_time', 'pk') if settings.RECOMMENDED_EVENTS_FILTER_BY_LOCATION: qx = qx.filter(location__in=('destination', 'user-entered', location)) elif f == 'most-popular': ctx['title'] = 'Most Popular Events' qx = qx.filter(location=location).order_by('-tweet_count', 'event_date', 'event_start_time', 'pk') elif f == 'our-picks': ctx['title'] = 'Our Picks' qx = qx.filter(location=location).filter(is_homepage_worthy=True).order_by('event_date', 'event_start_time', 'pk') elif f == 'destination': ctx['title'] = 'Destination Events' qx = qx.filter(location='destination').order_by('-destination_timestamp', 'event_date', 'event_start_time', 'pk') elif f == 'today': ctx['title'] = "Today's Events" qx = qx.filter(location=location).filter( event_date=today ).order_by('event_date', 'event_start_time', 'pk') elif f == 'date': # if date not specified, use today dt = by_date and datetime.strptime(by_date, "%m/%d/%Y") or date.today() ctx['title'] = "Events on %s" % dt.strftime("%A, %b %d, %Y") qx = qx.filter(location=location).filter( event_date=dt ).order_by('event_date', 'event_start_time', 'pk') elif f == 'tomorrow': ctx['title'] = "Tomorrow's Events" qx = qx.filter(location=location).filter( event_date=today + timedelta(days=1) ).order_by('event_date', 'event_start_time', 'pk') elif f == 'this-week': ctx['title'] = "This Week" start = today + relativedelta(weekday=MO(-1)) # greater than or equal to last Monday end = start + relativedelta(weekday=SU(+1)) # less than or equal to this Sunday qx = qx.filter(location=location).filter( event_date__gte=start, event_date__lte=end ).order_by('event_date', 'event_start_time', 'pk') ctx['start'] = start ctx['end'] = end elif f == 'this-weekend': ctx['title'] = "This Weekend" start = today + relativedelta(weekday=MO(-1)) + relativedelta(weekday=FR) # greater than or equal to this Friday end = start + relativedelta(weekday=SU(+1)) # less than or equal to this Sunday qx = qx.filter(location=location).filter( event_date__gte=start, event_date__lte=end ).order_by('event_date', 'event_start_time', 'pk') ctx['start'] = start ctx['end'] = end elif f == 'next-week': ctx['title'] = "Next Week" start = today + relativedelta(weekday=MO(-1), weeks=1) # greater than or equal to next Monday end = start + relativedelta(weekday=SU(+1)) # less than or equal to next Sunday qx = qx.filter(location=location).filter( event_date__gte=start, event_date__lte=end ).order_by('event_date', 'event_start_time', 'pk') ctx['start'] = start ctx['end'] = end elif f == 'next-weekend': ctx['title'] = "Next Weekend" start = today + relativedelta(weekday=MO(-1), weeks=1) + relativedelta(weekday=FR) # greater than or equal to next Friday end = start + relativedelta(weekday=SU(+1)) # less than or equal to next Sunday qx = qx.filter(location=location).filter( event_date__gte=start, event_date__lte=end ).order_by('event_date', 'event_start_time', 'pk') ctx['start'] = start ctx['end'] = end else: # no filter if not any_loc: qx = qx.filter(location__in=('destination', 'user-entered', location)) q = request.GET.get('q', '') if q: if not f: ctx['title'] = 'Events matching "%s"' % q ctx['q'] = q qx = qx.filter( Q(title__icontains=q) | Q(description__icontains=q) | Q(venue__name__icontains=q) | Q(hashtag__icontains=q) ) if 'sxsw' in q.lower(): if not request.mobile: ctx['rpp'] = 100 ctx['limit'] = 30 # start with events starting in 30 minutes or more if request.GET.get('page', '1') == '1': prefix = request.mobile and '/mobile/search' or '/help/search' qflat = q.replace('#', '').replace('@', '').lower() for k,v in settings.EVENT_SEARCH_NORMALIZATION.iteritems(): qflat = qflat.replace(k, v) try: flaturl = u"%s/%s/" % (prefix, qflat.replace(' ', '-')) fp = Site.objects.get_current().flatpage_set.get(url=flaturl.lower()) ctx['flatcontent'] = markdown(fp.content) except FlatPage.DoesNotExist: # if this search phrase has multiple space-separated keywords, # look for a flatpage for just the first word. if ' ' in qflat: x = qflat.split(' ') if x[0]: try: flaturl = u"%s/%s/" % (prefix, x[0]) fp = Site.objects.get_current().flatpage_set.get(url=flaturl.lower()) ctx['flatcontent'] = markdown(fp.content) except FlatPage.DoesNotExist: pass if sort_by and 'checkins' in sort_by: ctx['limit'] = 30 limit = request.GET.get('limit', ctx.get('limit', None)) if limit: minutes = int(limit) now = td and (datetime.now() - td) or datetime.now() threshold = now - timedelta(minutes=minutes) time_threshold = threshold.time() _log.debug("Excluding %s events started before %s (limit = %s minutes, td = %s)", today, time_threshold, limit, td) qx = qx.exclude( # event_start_time__isnull=False, # has start time event_date=today, # happened today event_start_time__lt=time_threshold # already happened ) if sort_by and sort_by in ('date', 'tweets', 'interested', 'new', 'checkins', 'mf_checkins', 'fm_checkins'): if 'checkins' in sort_by: # only include events that have no start time or that have already started or that are starting in the next 1 hour now = td and (datetime.now() - td) or datetime.now() threshold = now + timedelta(minutes=settings.CHECKIN_THRESHOLD_MINUTES) # 80 mins from now time_threshold = threshold.time() qx = qx.filter( Q(event_start_time__isnull=True) | Q(event_start_time__lte=time_threshold) ) if sort_by == 'date': qx = qx.order_by('event_date', 'event_start_time', 'pk') elif sort_by == 'tweets': qx = qx.order_by('-tweet_count', 'event_date', 'event_start_time', 'pk') elif sort_by == 'interested': qx = qx.order_by('-stats__num_attendees', 'event_date', 'event_start_time', 'pk') elif sort_by == 'new': qx = qx.order_by('-pk', 'event_date', 'event_start_time') elif sort_by == 'checkins': qx = qx.order_by('-venue__fsq_checkins', 'event_date', 'event_start_time', 'pk') ctx['title'] = "Checkins Today" elif request.user.is_authenticated(): if sort_by == 'mf_checkins': # where the ladies are qx = qx.filter(venue__fsq_checkins__gt=0, venue__fsq_f__gt=1).order_by('venue__fsq_mf', 'event_date', 'event_start_time', 'pk') ctx['title'] = "Checkins Today" elif sort_by == 'fm_checkins': # where the gents are qx = qx.filter(venue__fsq_checkins__gt=0, venue__fsq_m__gt=1).order_by('venue__fsq_fm', 'event_date', 'event_start_time', 'pk') ctx['title'] = "Checkins Today" ctx['sort_by'] = sort_by return list_events(request, location, queryset=qx, extra_context=ctx, hide_top3=True)
def fb_login(request): next = request.REQUEST.get("next", "/") if request.user.is_authenticated(): return HttpResponseRedirect(next) # if user has an FB Connect session, create account and # log the user in. api_key, secret = settings.FB_API_KEY, settings.FB_SECRET_KEY fb_uid, fb_session_key, fb_session_secret = get_fb_session(request) if not fb_uid: return _logout_redirect(request, next) # Create account if necessary new_signup = True try: profile = UserProfile.objects.active().filter(fb_userid=fb_uid)[:1].get() new_signup = False # account exists; log the user in user = profile.user if user.email.startswith("sso+fb_"): # get FB proxied email and save it under this user's record uinfo = get_user_info(api_key, secret, fb_session_key, fb_uid) if uinfo: name, email = uinfo['name'], uinfo['email'] if email: user.email = email user.save() profile.is_sso = False profile.send_reminders = True profile.send_favorites = True profile.save() except UserProfile.DoesNotExist: # create new acount new_signup = True email = request.session.get("email", None) if not email: add_message(request, u"Create a new account below in two easy steps before signing in with Facebook.") return HttpResponseRedirect(reverse("signup") + "?next=" + next) uinfo = get_user_info(api_key, secret, fb_session_key, fb_uid) # screen_name, name, email = None, None, None screen_name, name = None, None if uinfo: # name, email = uinfo['name'], uinfo['email'] name = uinfo['name'] if name: # screen name is firstname followed by last initial; all lowercased screen_name = name.lower().strip() x = screen_name.split(' ') if len(x) > 1: firstname, lastname = x[0], x[1] if lastname: screen_name = firstname + lastname[0] else: screen_name = firstname screen_name = slugify(screen_name)[:25] unames = list(User.objects.filter(username__istartswith=screen_name).values_list("username", flat=True).order_by("username")) unames = set([x.lower() for x in unames]) if screen_name in unames: # generate a unique screen_name by suffixing it with a number for n in range(2, 1000): s = u"%s%s" % (screen_name, n) if s not in unames: screen_name = s break if not screen_name: # Use FB User ID as the screen name screen_name = fb_uid if User.objects.filter(username=screen_name).count(): # screen name not available. Generate one with a random suffix screen_name = u''.join([screen_name.strip()[:25], u'-', uuid4().hex[::6]]) # create user and profile user = User.objects.create( username=screen_name, first_name='', last_name='', email=email or u'*****@*****.**' % uuid4().hex[::5], ) profile = user.get_profile() profile.fb_userid = fb_uid profile.is_sso = False profile.send_reminders = bool(email) profile.send_favorites = bool(email) profile.fb_suggested = 0 profile.save() # annotate the user object with the path of the backend so that # login() works without a password: backend = get_backends()[0] user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) login(request, user) if new_signup: user.message_set.create(message=_(u'Thank you for signing-up with Facebook!')) _log.debug("FB user %s logged in" % profile.username) request.user_profile = profile request.session['fb_uid'] = fb_uid request.session['fb_session_key'] = fb_session_key # if this user was invited by any existing users, create a friendship inv = FBInvitedUser.objects.select_related('inviter_profile').filter(fb_userid=fb_uid) for u in inv: inviter = u.inviter_profile Friendship.objects.make_friends(inviter, request.user_profile, source='fb') u.delete() # calculate new suggested friends and add their count to session try: user_profile = profile all_fb_friends = _get_connected_friends(api_key, secret, fb_session_key, fb_uid) fb_users = UserProfile.objects.active().exclude(fb_userid=u'') app_friends = set(list(fb_users.filter(friends2__user_profile1__pk=user_profile.pk).values_list('fb_userid', flat=True))) pending_friends = set(list(fb_users.filter(pending_friends_inviter__invitee_profile__pk=user_profile.pk).values_list('fb_userid', flat=True))) invited_friends = set(list(fb_users.filter(pending_friends_invitee__inviter_profile__pk=user_profile.pk).values_list('fb_userid', flat=True))) recommended_friends = all_fb_friends.difference(app_friends).difference(pending_friends).difference(invited_friends) db_reco, created = FBSuggestedFriends.objects.get_or_create(user_profile=user_profile) db_recommended_friends = db_reco.friendset new_friends = recommended_friends.difference(db_recommended_friends) if new_friends: if new_signup and settings.FB_AUTO_FRIEND: num_auto_friended = auto_friend(profile, new_friends) _log.debug("Auto-friended %s friends of %s", num_auto_friended, profile) else: request.session['num_fb_new_friends'] = len(new_friends) except Exception, e: _log.exception(e)
def sso_authorized(request): """Process Single Sign-On (SSO) authorization from Twitter. If authorized: If account doesn't already exist: - Create dummy user account with disabled password () - Create user profile with sso (including avatar image) - Save Twitter profile - Initiate AMQP tasks for user - Log the user in - Redirect to saved HTTP_REFERER or ``next`` value from sso_initiate """ from event.amqp.tasks import build_recommended_events next = request.session.get('SSO_NEXT', '/') if request.user.is_authenticated(): return HttpResponseRedirect(next) if 'OPEN_PROFILE' not in request.session: _log.debug("Lost session data during SSO authorization. Retrying.") return sso_initiate(request) oprofile = request.session['OPEN_PROFILE'] screen_name = oprofile['screen_name'].lower() new_signup = False try: # Use already created SSO account if one exists prof = UserProfile.objects.select_related('user').get(sso_username__iexact=screen_name) user = prof.user except UserProfile.DoesNotExist: try: # Use latest existing account if one linked to this twitter screen name exists prof = UserProfile.objects.select_related('user').filter( twitterprofile__screen_name__iexact=screen_name, twitterprofile__pk__isnull=False ).order_by("-pk")[:1].get() user = prof.user except UserProfile.DoesNotExist: # Create a new SSO account # If screenname is available, use it as username. # If not, suffix it with a number and use that. new_signup = True email = request.session.get("email", None) if not email: add_message(request, u"Create a new account below in two easy steps before signing in with Twitter.") return HttpResponseRedirect(reverse("signup") + "?next=" + next) screen_name = screen_name.strip()[:32] user = None if User.objects.filter(username=screen_name).count(): screen_name = screen_name[:27] # make room for suffixed digits for x in range(2, 100): uname = u"%s%s" % (screen_name, x) if not User.objects.filter(username=uname).count(): user = User.objects.create( username=uname, first_name=oprofile['first_name'], last_name=oprofile['last_name'], email=email, ) break else: user = User.objects.create( username=screen_name, first_name=oprofile['first_name'], last_name=oprofile['last_name'], email=email, ) if not user: # use a randomly suffixed username user = User.objects.create( username=u''.join([screen_name[:25], u'-', uuid4().hex[::6]]), first_name=oprofile['first_name'], last_name=oprofile['last_name'], email=email, ) prof = user.get_profile() prof.is_sso = True prof.sso_username = screen_name prof.send_reminders = False prof.send_favorites = False prof.save() # build AMQP headers so that recommended events are built right after # this user's friendships have been computed amqp_headers = { 'final_reply_to':'signal/signal.events.build_recommended_events', 'user_profile_id':prof.pk } save_open_profile(user, oprofile, amqp_headers) # this will also initiate the friendship builder AMQP task if not prof.avatar_image: url = oprofile.get('profile_image_url', None) copy_avatar_from_url_to_profile(url, prof, commit=True) # annotate the user object with the path of the backend so that # login() works without a password: backend = get_backends()[0] user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) login(request, user) if new_signup: user.message_set.create(message=_(u'Thank you for signing-up with Twitter!')) _log.debug("SSO user %s logged in" % prof.username) return HttpResponseRedirect(next)
def callback(request): """This is where Twitter will redirect the user after this app has been authorized.""" try: unauthed_token = request.session.get('TWITTER_UNAUTH_TOKEN', None) oauth_verifier = request.GET.get('oauth_verifier', None) try: if unauthed_token: del request.session['TWITTER_UNAUTH_TOKEN'] except KeyError: pass if not unauthed_token: _log.debug("Unauthenticated token not found in session") return _denied_response(request) token = oauth.OAuthToken.from_string(unauthed_token) oauth_token = request.GET.get('oauth_token', None) if token.key != oauth_token: _log.debug("Tokens did not match %s - %s", token.key, oauth_token) return _denied_response(request) tw = TwitterAPI() try: access_token = tw.exchange_request_token_for_access_token(token, oauth_verifier) except KeyError: tw.close() return _denied_response(request) twitter_profile = tw.get_profile(access_token) tw.close() if twitter_profile: _log.debug("Twitter profile downloaded:\n%s", twitter_profile) try: p = simplejson.loads(twitter_profile) except Exception, e: # try one more time try: tw = TwitterAPI() twitter_profile = tw.get_profile(access_token) tw.close() _log.debug("Twitter profile downloaded on retry:\n%s", twitter_profile) if not twitter_profile: raise Exception("OAuth error: retry failed on get_profile") p = simplejson.loads(twitter_profile) except Exception, e: _log.warn("Twitter profile could not be JSON decoded.\n%s", twitter_profile) _log.exception(e) add_message(request, u"We are unable to connect to Twitter at the moment. Please try again in a few minutes.") return _denied_response(request) _log.debug(p) screen_name = p.get('screen_name') full_name = p.get('name', p['screen_name']) # Split full_name into first name and last name x = full_name.split(' ', 1) first_name, last_name = u'', u'' if len(x) > 1: first_name, last_name = x[0], x[1] elif len(x) == 1: first_name, last_name = u'', x[0] profile_image = p.get('profile_image_url', '') if '/images/default_profile' in profile_image: profile_image = '' profile = dict( profile_type=u'twitter', screen_name=screen_name, first_name=first_name, last_name=last_name, appuser_id=p['id'], profile_image_url=profile_image, access_token=access_token.to_string() ) if request.user.is_authenticated(): user = request.user p = save_open_profile(user, profile) add_message(request, u"You've connected your Twitter account successfully.") # user.message_set.create(message=_(u"Thank you for authorizing us to update your Twitter status!")) else: request.session['OPEN_PROFILE'] = profile
def do_friending(request, username): profile = get_object_or_404(UserProfile.objects.active(), user__username__iexact=username) action = request.POST.get('action', None) if request.method != 'POST' or not action: return HttpResponseRedirect(profile.get_absolute_url()) if request.user_profile.pk == profile.pk: add_message(request, "Ummm, you just tried to friend yourself. You need to get out more often :)") return HttpResponseRedirect(profile.get_absolute_url()) action = action.lower().strip() if action not in ('add to friends', 'remove from friends', 'follow', 'unfollow'): return HttpResponseRedirect(profile.get_absolute_url()) rel_obj, viewer = profile.get_relationship(request.user_profile) # viewer can be 'friend', 'follower', 'followee' # rev_obj, rev_viewer = request.user_profile.get_relationship(profile) # reverse relationship if action == 'add to friends': if viewer == 'friend': add_message(request, "You and %s are already friends." % profile.username) elif viewer == 'follower': add_message(request, "You've already asked to be friends with %s. We are just waiting for %s to confirm your request." % (profile.username, profile.username)) elif viewer == 'followee': Friendship.objects.make_friends(profile, request.user_profile, source='site') add_message(request, "You and %s are now friends!" % profile.username) _log.info("Friendship established: %s <-> %s", profile.username, request.user_profile.username) email_template('%s is your friend!' % request.user_profile.username.title(), 'registration/email/new-friend.html', {'user':profile.user, 'user_profile':profile, 'profile2':request.user_profile}, to_list=[profile.user.email]) elif not viewer: # no existing relationship Follower.objects.get_or_create(followee=profile, follower=request.user_profile) add_message(request, "We've just asked %s to confirm your friend request." % profile.username) _log.info("Follower established: %s is followed by %s", profile.username, request.user_profile.username) email_template('%s is now following you!' % request.user_profile.username.title(), 'registration/email/new-follower.html', {'user':profile.user, 'user_profile':profile, 'profile2':request.user_profile, 'friendship_needed':True}, to_list=[profile.user.email]) elif action == 'remove from friends': if viewer != 'friend': add_message(request, "You and %s are not friends." % profile.username) elif viewer == 'friend' and rel_obj.source == 'twitter': add_message(request, "Your friendship with %s was established through Twitter. You will have to unfollow %s on Twitter to unfriend them here." % (profile.username, profile.username)) else: Friendship.objects.disconnect_friends(profile, request.user_profile) add_message(request, "You and %s are no longer friends." % profile.username) elif action == 'follow': if viewer in ('friend', 'follower'): add_message(request, "You are already following %s." % profile.username) elif viewer == 'followee': Friendship.objects.make_friends(profile, request.user_profile, source='site') add_message(request, "You and %s are now friends!" % profile.username) _log.info("Friendship established: %s <-> %s", profile.username, request.user_profile.username) email_template('%s is your friend!' % request.user_profile.username.title(), 'registration/email/new-friend.html', {'user':profile.user, 'user_profile':profile, 'profile2':request.user_profile}, to_list=[profile.user.email]) elif not viewer: # no existing relationship Follower.objects.get_or_create(followee=profile, follower=request.user_profile) add_message(request, "You are now following %s!" % profile.username) _log.info("Follower established: %s is followed by %s", profile.username, request.user_profile.username) email_template('%s is now following you!' % request.user_profile.username.title(), 'registration/email/new-follower.html', {'user':profile.user, 'user_profile':profile, 'profile2':request.user_profile, 'friendship_needed':False}, to_list=[profile.user.email]) elif action == 'unfollow': if viewer != 'follower': add_message(request, "You don't follow %s." % profile.username) else: Friendship.objects.disconnect_friends(profile, request.user_profile) add_message(request, "You no longer follow %s." % profile.username) build_recommended_events(request.user_profile.pk) return HttpResponseRedirect(profile.get_absolute_url())
def fb_connect(request): """Merge FB session with current profile""" next = request.REQUEST.get("next", "/") if request.user_profile.fb_userid: # User has already connected an FB account add_message(request, u"You've already connected a Facebook account.") return HttpResponseRedirect(next) api_key, secret = settings.FB_API_KEY, settings.FB_SECRET_KEY fb_uid, fb_session_key, fb_session_secret = get_fb_session(request) if not fb_uid: return _logout_redirect(request, next) try: profile = UserProfile.objects.active().filter( fb_userid=fb_uid)[:1].get() add_message( request, u"You've already connected this Facebook account with another RiotVine account." ) return HttpResponseRedirect(next) except UserProfile.DoesNotExist: # save fb id profile = request.user_profile profile.fb_userid = fb_uid profile.is_sso = False profile.fb_suggested = 0 profile.save() request.user_profile = profile request.session['fb_uid'] = fb_uid # if this user was invited by any existing users, create a friendship inv = FBInvitedUser.objects.select_related('inviter_profile').filter( fb_userid=fb_uid) for u in inv: inviter = u.inviter_profile Friendship.objects.make_friends(inviter, request.user_profile, source='fb') u.delete() # calculate new suggested friends and add their count to session try: user_profile = profile all_fb_friends = _get_connected_friends(api_key, secret, fb_session_key, fb_uid) fb_users = UserProfile.objects.active().exclude(fb_userid=u'') app_friends = set( list( fb_users.filter( friends2__user_profile1__pk=user_profile.pk).values_list( 'fb_userid', flat=True))) pending_friends = set( list( fb_users.filter( pending_friends_inviter__invitee_profile__pk=user_profile. pk).values_list('fb_userid', flat=True))) invited_friends = set( list( fb_users.filter( pending_friends_invitee__inviter_profile__pk=user_profile. pk).values_list('fb_userid', flat=True))) recommended_friends = all_fb_friends.difference( app_friends).difference(pending_friends).difference( invited_friends) db_reco, created = FBSuggestedFriends.objects.get_or_create( user_profile=user_profile) db_recommended_friends = db_reco.friendset new_friends = recommended_friends.difference(db_recommended_friends) if new_friends: if settings.FB_AUTO_FRIEND: num_auto_friended = auto_friend(profile, new_friends) _log.debug("Auto-friended %s friends of %s", num_auto_friended, profile) else: request.session['num_fb_new_friends'] = len(new_friends) except Exception, e: _log.exception(e)
def _logout_redirect(request, next): logout(request) request.delete_fb_cookies = True add_message(request, u"Ooops, your Facebook session has expired. Please sign-in again.") return HttpResponseRedirect(next)
async def wrapped(self, *args, **kwargs): if self.request.user is None: add_message(self.request, "LogIn to continue.") redirect(self.request, "sign_in") return await func(self, *args, **kwargs)
async def wrapped(self, *args, **kwargs): if self.request.user is not None: add_message(self.request, "Please log-out to continue.") redirect(self.request, "index") return await func(self, *args, **kwargs)
if request.user.is_authenticated(): user = request.user p = save_open_profile(user, profile) add_message(request, u"You've connected your Twitter account successfully.") # user.message_set.create(message=_(u"Thank you for authorizing us to update your Twitter status!")) else: request.session['OPEN_PROFILE'] = profile if request.user.is_authenticated(): next = request.session.pop('TWITTER_NEXT_URL', reverse('home')) return HttpResponseRedirect(next + '?open_profile=twitter') else: next = request.session.pop('TWITTER_NEXT_URL', reverse('register')) return HttpResponseRedirect(next + '?open_profile=twitter') except Exception, e: _log.exception(e) add_message(request, u"We are unable to connect to Twitter at the moment. Please try again in a few minutes.") return _denied_response(request) @login_required def post_status(request): mesg = None ret_ctx = {} # The return context sent to AJAX callers ret_ctx['success'] = False if request.method == 'POST': status = request.POST.get('status_text', '').strip() if not status: status = request.POST.get('status', '').strip() mesg = u"Status could not be posted to Twitter." if status: status = TWITTER_GENERAL_STATUS_FORMAT % {'status':status}
app_friends).difference(pending_friends).difference( invited_friends) db_reco, created = FBSuggestedFriends.objects.get_or_create( user_profile=user_profile) db_recommended_friends = db_reco.friendset new_friends = recommended_friends.difference(db_recommended_friends) if new_friends: if settings.FB_AUTO_FRIEND: num_auto_friended = auto_friend(profile, new_friends) _log.debug("Auto-friended %s friends of %s", num_auto_friended, profile) else: request.session['num_fb_new_friends'] = len(new_friends) except Exception, e: _log.exception(e) add_message(request, u"You've connected your Facebook account successfully.") return HttpResponseRedirect(next) @transaction.commit_on_success @login_required def manage_friends(request, template='fb/manage_friends.html'): """Show current FB friends with checkboxes allowing user to connect/disconnect with their friends. The view is divided into these parts: * Friends you're sharing events with * Suggested Friends The old view (now defunt) was divided into more granular parts: * Users who've shared a friendship with this user (ordered by sharing recency) and are awaiting this user's confirmation (actions: confirm, reject)