def home(request, page=1): """Paginated recent videos and live videos.""" privacy_filter = {} privacy_exclude = {} if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: privacy_exclude = {'privacy': Event.PRIVACY_COMPANY} else: privacy_filter = {'privacy': Event.PRIVACY_PUBLIC} archived_events = Event.objects.archived() if privacy_filter: archived_events = archived_events.filter(**privacy_filter) elif privacy_exclude: archived_events = archived_events.exclude(**privacy_exclude) archived_events = archived_events.order_by('-start_time') tags = None if request.GET.getlist('tag'): requested_tags = request.GET.getlist('tag') found_tags = [] not_found_tags = False for each in requested_tags: try: found_tags.append(Tag.objects.get(name__iexact=each).name) except Tag.DoesNotExist: not_found_tags = True if not_found_tags: # invalid tags were used in the query string url = reverse('main:home') if found_tags: # some were good url += '?%s' % urllib.urlencode({'tag': found_tags}, True) return redirect(url, permanent=True) tags = Tag.objects.filter(name__in=found_tags) archived_events = archived_events.filter(tags__in=tags) if tags: # no live events when filtering by tag live_events = Event.objects.none() else: live_events = (Event.objects.live().order_by('start_time')) if privacy_filter: live_events = live_events.filter(**privacy_filter) elif privacy_exclude: live_events = live_events.exclude(**privacy_exclude) archived_paged = paginate(archived_events, page, 10) live = None also_live = [] if live_events: live, also_live = live_events[0], live_events[1:] return render( request, 'main/home.html', { 'events': archived_paged, 'live': live, 'also_live': also_live, 'tags': tags, 'Event': Event, })
def process_request(self, request): if (request.method != 'POST' and not request.is_ajax() and request.user.is_active and request.path not in self.exception_paths): cache_key = 'renew_id_token:{}'.format(request.user.id) if cache.get(cache_key): # still valid, we checked recently return # oh, no we need to check the id_token (and renew it) profile = get_profile_safely(request.user) if profile and profile.id_token: id_token = auth0.renew_id_token(profile.id_token) if id_token: assert isinstance(id_token, basestring) profile.id_token = id_token profile.save() cache.set(cache_key, True, settings.RENEW_ID_TOKEN_EXPIRY_SECONDS) else: # If that failed, your previous id_token is not valid # and you need to be signed out so you can get a new # one. logout(request) # XXX message? return redirect('authentication:signin')
def savedsearches_data(request): context = {} qs = SavedSearch.objects.filter(user=request.user).order_by('-created') searches = [] for savedsearch in qs: item = { 'id': savedsearch.id, 'name': savedsearch.name, 'summary': savedsearch.summary, 'modified': savedsearch.modified.isoformat(), } searches.append(item) # We need a general Feed URL that is tailored to this user from airmozilla.main.context_processors import base feed = base(request)['get_feed_data']() if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: calendar_privacy = 'contributors' else: calendar_privacy = 'company' else: calendar_privacy = 'public' context['savedsearches'] = searches context['urls'] = { 'search:savedsearch': reverse('search:savedsearch', args=(0, )), 'search:home': reverse('search:home'), 'feed': feed['url'], 'ical': reverse('main:calendar_ical', args=(calendar_privacy, )), } return context
def channels(request): channels = [] privacy_filter = {} privacy_exclude = {} if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: feed_privacy = 'contributors' privacy_exclude = {'privacy': Event.PRIVACY_COMPANY} else: feed_privacy = 'company' else: privacy_filter = {'privacy': Event.PRIVACY_PUBLIC} feed_privacy = 'public' events = Event.objects.archived().all() if privacy_filter: events = events.filter(**privacy_filter) elif privacy_exclude: events = events.exclude(**privacy_exclude) for channel in Channel.objects.exclude(slug=settings.DEFAULT_CHANNEL_SLUG): event_count = events.filter(channels=channel).count() channels.append((channel, event_count)) data = { 'channels': channels, 'feed_privacy': feed_privacy, } return render(request, 'main/channels.html', data)
def send_new_event_emails(verbose=False): now = timezone.now() yesterday = now - datetime.timedelta(hours=24) events = Event.objects.scheduled().filter( created__gt=yesterday, created__lt=now, ).approved().exclude( id__in=EventEmail.objects.values('event_id') ) optout_users = {} attempted = successful = skipped = 0 for event in events: if event.creator.email not in optout_users: user_profile = get_profile_safely(event.creator) # if they don't have a profile, assume not optout_users[event.creator.email] = ( user_profile and user_profile.optout_event_emails or False ) if optout_users[event.creator.email]: if verbose: # pragma: no cover print "Skipping sending to", event.creator.email skipped += 1 continue attempted += 1 send_failure = None try: sending.send_about_new_event(event) if verbose: # pragma: no cover print "Successfully sent about", repr(event) successful += 1 except Exception: if settings.DEBUG: # pragma: no cover raise exc_type, exc_value, exc_tb = sys.exc_info() send_failure = "{0}{1}: {2}".format( ''.join(traceback.format_tb(exc_tb)), exc_type.__name__, exc_value ) if verbose: # pragma: no cover print "Failed to send about", repr(event) print send_failure EventEmail.objects.create( event=event, user=event.creator, to=event.creator.email, send_failure=send_failure, ) return attempted, successful, skipped
def is_contributor(user): if not hasattr(user, 'pk'): return False cache_key = 'is-contributor-%s' % user.pk is_ = cache.get(cache_key) if is_ is None: profile = get_profile_safely(user) is_ = False if profile and profile.contributor: is_ = True cache.set(cache_key, is_, 60 * 60) return is_
def process_request(self, request): if ( request.method != 'POST' and not request.is_ajax() and request.user.is_active and request.path not in self.exception_paths ): cache_key = 'renew_id_token:{}'.format(request.user.id) if cache.get(cache_key): # still valid, we checked recently return # oh, no we need to check the id_token (and renew it) profile = get_profile_safely(request.user) if profile and profile.id_token: try: id_token = auth0.renew_id_token(profile.id_token) except (ConnectTimeout, ReadTimeout): messages.error( request, 'Unable to validate your authentication with Auth0. ' 'This can happen when there is temporary network ' 'problem. Please sign in again.' ) # If we don't do this, the user will be redirected # to the sign-in page, which runs this middleware # and you'd get caught in an infinite redirect loop. logout(request) return redirect('authentication:signin') if id_token: assert isinstance(id_token, basestring) profile.id_token = id_token profile.save() cache.set( cache_key, True, settings.RENEW_ID_TOKEN_EXPIRY_SECONDS ) else: # If that failed, your previous id_token is not valid # and you need to be signed out so you can get a new # one. logout(request) messages.error( request, 'Unable to validate your authentication with Auth0. ' 'This is most likely due to an expired authentication ' 'session. You have to sign in again.' ) return redirect('authentication:signin')
def can_view_event(event, user): """return True if the current user has right to view this event""" if event.privacy == Event.PRIVACY_PUBLIC: return True elif not user.is_active: return False # you're logged in if event.privacy == Event.PRIVACY_COMPANY: # but then it's not good enough to be contributor profile = get_profile_safely(user) if profile and profile.contributor: return False return True
def calendars(request): data = {} locations = [] now = datetime.datetime.utcnow().replace(tzinfo=utc) time_ago = now - datetime.timedelta(days=30) base_qs = Event.objects.filter(start_time__gte=time_ago) for location in Location.objects.all().order_by('name'): count = base_qs.filter(location=location).count() if count: locations.append(location) data['locations'] = locations if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: data['calendar_privacy'] = 'contributors' else: data['calendar_privacy'] = 'company' else: data['calendar_privacy'] = 'public' return render(request, 'main/calendars.html', data)
def calendars(request): data = {} locations = [] now = timezone.now() time_ago = now - datetime.timedelta(days=30) base_qs = Event.objects.filter(start_time__gte=time_ago) for location in Location.objects.all().order_by('name'): count = base_qs.filter(location=location).count() if count: locations.append(location) data['locations'] = locations if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: data['calendar_privacy'] = 'contributors' else: data['calendar_privacy'] = 'company' else: data['calendar_privacy'] = 'public' return render(request, 'main/calendars.html', data)
def calendars(request): data = {} locations = [] now = timezone.now() time_ago = now - datetime.timedelta(days=30) base_qs = Event.objects.filter(start_time__gte=time_ago) for location in Location.objects.all().order_by("name"): count = base_qs.filter(location=location).count() if count: locations.append(location) data["locations"] = locations if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: data["calendar_privacy"] = "contributors" else: data["calendar_privacy"] = "company" else: data["calendar_privacy"] = "public" return render(request, "main/calendars.html", data)
def unsubscribe(request, identifier): context = {} cache_key = 'unsubscribe-%s' % identifier user_id = cache.get(cache_key) if user_id: user = get_object_or_404(User, id=user_id) else: user = None cache.set(cache_key, request.user.id, 60) context['user'] = user if request.method == 'POST': if not user: return http.HttpResponseBadRequest('No user') user_profile = get_profile_safely(user, create_if_necessary=True) user_profile.optout_event_emails = True user_profile.save() cache.delete(cache_key) return redirect('new:unsubscribed') return render(request, 'new/unsubscribe.html', context)
def savedsearches_data(request): context = {} qs = SavedSearch.objects.filter( user=request.user ).order_by('-created') searches = [] for savedsearch in qs: item = { 'id': savedsearch.id, 'name': savedsearch.name, 'summary': savedsearch.summary, 'modified': savedsearch.modified.isoformat(), } searches.append(item) # We need a general Feed URL that is tailored to this user from airmozilla.main.context_processors import base feed = base(request)['get_feed_data']() if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: calendar_privacy = 'contributors' else: calendar_privacy = 'company' else: calendar_privacy = 'public' context['savedsearches'] = searches context['urls'] = { 'search:savedsearch': reverse('search:savedsearch', args=(0,)), 'search:home': reverse('search:home'), 'feed': feed['url'], 'ical': reverse('main:calendar_ical', args=(calendar_privacy,)), } return context
def sidebar(request): # none of this is relevant if you're in certain URLs if '/manage/' in request.path_info: return {} data = { # used for things like {% if event.attr == Event.ATTR1 %} 'Event': Event, } featured = (Event.objects.archived() .filter(featured=True).order_by('-start_time')) upcoming = Event.objects.upcoming().order_by('start_time') # if viewing a specific page is limited by channel, apply that filtering # here too if getattr(request, 'channels', None): channels = request.channels else: channels = Channel.objects.filter(slug=settings.DEFAULT_CHANNEL_SLUG) if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: feed_privacy = 'contributors' else: feed_privacy = 'company' else: feed_privacy = 'public' if settings.DEFAULT_CHANNEL_SLUG in [x.slug for x in channels]: feed_title = 'AirMozilla RSS' feed_url = reverse('main:feed', args=(feed_privacy,)) sidebar_channel = settings.DEFAULT_CHANNEL_SLUG else: _channel = channels[0] feed_title = 'AirMozilla - %s - RSS' % _channel.name feed_url = reverse('main:channel_feed', args=(_channel.slug, feed_privacy)) sidebar_channel = _channel.slug data['feed_title'] = feed_title data['feed_url'] = feed_url featured = featured.filter(channels__in=channels) upcoming = upcoming.filter(channels__in=channels) if not request.user.is_active: featured = featured.filter(privacy=Event.PRIVACY_PUBLIC) upcoming = upcoming.filter(privacy=Event.PRIVACY_PUBLIC) upcoming = upcoming[:settings.UPCOMING_SIDEBAR_COUNT] data['upcoming'] = upcoming data['featured'] = featured try: data['sidebar_top'] = FlatPage.objects.get( url='sidebar_top_%s' % sidebar_channel ) except FlatPage.DoesNotExist: data['sidebar_top'] = None try: data['sidebar_bottom'] = FlatPage.objects.get( url='sidebar_bottom_%s' % sidebar_channel ) except FlatPage.DoesNotExist: data['sidebar_bottom'] = None return data
def callback(request): """Much of this is copied from the callback done in django_auth0 but with the major difference that we handle checking if non-staff are vouched Mozillians.""" code = request.GET.get('code', '') if not code: # If the user is blocked, we will never be called back with a code. # What Auth0 does is that it calls the callback but with extra # query string parameters. if request.GET.get('error'): messages.error( request, "Unable to sign in because of an error from Auth0. " "({})".format( request.GET.get( 'error_description', request.GET['error'] ) ) ) return redirect('authentication:signin') return http.HttpResponseBadRequest("Missing 'code'") token_url = 'https://{}/oauth/token'.format(settings.AUTH0_DOMAIN) token_payload = { 'client_id': settings.AUTH0_CLIENT_ID, 'client_secret': settings.AUTH0_SECRET, 'redirect_uri': settings.AUTH0_CALLBACK_URL, 'code': code, 'grant_type': 'authorization_code', } try: token_info = requests.post( token_url, json=token_payload, timeout=settings.AUTH0_PATIENCE_TIMEOUT, ).json() except (ConnectTimeout, ReadTimeout): messages.error( request, 'Unable to authenticate with Auth0. The Auth0 service timed out. ' 'This is most likely temporary so you can try again in a couple ' 'of minutes.' ) return redirect('authentication:signin') if not token_info.get('access_token'): messages.error( request, 'Unable to authenticate with Auth0. Most commonly this ' 'happens because the authentication token has expired. ' 'Please refresh and try again.' ) return redirect('authentication:signin') user_url = 'https://{}/userinfo'.format( settings.AUTH0_DOMAIN, ) user_url += '?' + urllib.urlencode({ 'access_token': token_info['access_token'], }) try: user_response = requests.get( user_url, timeout=settings.AUTH0_PATIENCE_TIMEOUT, ) except (ConnectTimeout, ReadTimeout): messages.error( request, 'Unable to authenticate with Auth0. The Auth0 service timed out. ' 'This is most likely temporary so you can try again in a couple ' 'of minutes.' ) return redirect('authentication:signin') if user_response.status_code != 200: messages.error( request, 'Unable to retrieve user info from Auth0 ({}, {!r})'.format( user_response.status_code, user_response.text ) ) return redirect('authentication:signin') user_info = user_response.json() assert user_info['email'], user_info if not user_info['email_verified']: messages.error( request, 'Email {} not verified.'.format( user_info['email'] ) ) return redirect('authentication:signin') try: user = get_user(user_info) except BadStatusCodeError: messages.error( request, 'Email {} authenticated but unable to connect to ' 'Mozillians.org to see if are vouched. Please try again ' 'in a minute.'.format( user_info['email'] ) ) return redirect('authentication:signin') if user and not user.is_active: messages.error( request, "User account ({}) found but it has been made inactive.".format( user.email, ) ) return redirect('authentication:signin') elif user: if token_info.get('id_token'): profile = get_profile_safely(user, create_if_necessary=True) profile.id_token = token_info['id_token'] profile.save() else: # If you signed in with a domain found in settings.ALLOWED_BID # then we can't accept NOT getting an id_token if user.email.lower().split('@')[1] in settings.ALLOWED_BID: messages.error( request, "Staff can't log in without an ID token. " "Means you have to click the Google button if you're " "a member of staff.".format( user_info['email'] ) ) return redirect('authentication:signin') user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return redirect(settings.AUTH0_SUCCESS_URL) else: messages.error( request, 'Email {} authenticated but you are not a vouched Mozillian ' 'on Mozillians.org'.format( user_info['email'] ) ) return redirect('authentication:signin')
def callback(request): """Much of this is copied from the callback done in django_auth0 but with the major difference that we handle checking if non-staff are vouched Mozillians.""" code = request.GET.get('code', '') if not code: # If the user is blocked, we will never be called back with a code. # What Auth0 does is that it calls the callback but with extra # query string parameters. if request.GET.get('error'): messages.error( request, "Unable to sign in because of an error from Auth0. " "({})".format( request.GET.get('error_description', request.GET['error']))) return redirect('authentication:signin') return http.HttpResponseBadRequest("Missing 'code'") token_url = 'https://{}/oauth/token'.format(settings.AUTH0_DOMAIN) token_payload = { 'client_id': settings.AUTH0_CLIENT_ID, 'client_secret': settings.AUTH0_SECRET, 'redirect_uri': settings.AUTH0_CALLBACK_URL, 'code': code, 'grant_type': 'authorization_code', } token_info = requests.post( token_url, json=token_payload, ).json() if not token_info.get('access_token'): messages.error( request, 'Unable to authenticate with Auth0. Most commonly this ' 'happens because the authentication token has expired. ' 'Please refresh and try again.') return redirect('authentication:signin') user_url = 'https://{}/userinfo'.format(settings.AUTH0_DOMAIN, ) user_url += '?' + urllib.urlencode({ 'access_token': token_info['access_token'], }) user_response = requests.get(user_url) if user_response.status_code != 200: messages.error( request, 'Unable to retrieve user info from Auth0 ({}, {!r})'.format( user_response.status_code, user_response.text)) return redirect('authentication:signin') user_info = user_response.json() assert user_info['email'], user_info if not user_info['email_verified']: messages.error(request, 'Email {} not verified.'.format(user_info['email'])) return redirect('authentication:signin') try: user = get_user(user_info) except BadStatusCodeError: messages.error( request, 'Email {} authenticated but unable to connect to ' 'Mozillians.org to see if are vouched. Please try again ' 'in a minute.'.format(user_info['email'])) return redirect('authentication:signin') if user and not user.is_active: messages.error( request, "User account ({}) found but it has been made inactive.".format( user.email, )) return redirect('authentication:signin') elif user: if token_info.get('id_token'): profile = get_profile_safely(user, create_if_necessary=True) profile.id_token = token_info['id_token'] profile.save() else: # If you signed in with a domain found in settings.ALLOWED_BID # then we can't accept NOT getting an id_token if user.email.lower().split('@')[1] in settings.ALLOWED_BID: messages.error( request, "Staff can't log in without an ID token. " "Means you have to click the Google button if you're " "a member of staff.".format(user_info['email'])) return redirect('authentication:signin') user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return redirect(settings.AUTH0_SUCCESS_URL) else: messages.error( request, 'Email {} authenticated but you are not a vouched Mozillian ' 'on Mozillians.org'.format(user_info['email'])) return redirect('authentication:signin')
def home(request, page=1, channel_slug=settings.DEFAULT_CHANNEL_SLUG): """Paginated recent videos and live videos.""" channels = Channel.objects.filter(slug=channel_slug) if not channels.count(): if channel_slug == settings.DEFAULT_CHANNEL_SLUG: # then, the Main channel hasn't been created yet Channel.objects.create( name=settings.DEFAULT_CHANNEL_NAME, slug=settings.DEFAULT_CHANNEL_SLUG ) channels = Channel.objects.filter(slug=channel_slug) else: raise http.Http404('Channel not found') request.channels = channels privacy_filter = {} privacy_exclude = {} if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: privacy_exclude = {'privacy': Event.PRIVACY_COMPANY} else: privacy_filter = {'privacy': Event.PRIVACY_PUBLIC} archived_events = Event.objects.archived() if privacy_filter: archived_events = archived_events.filter(**privacy_filter) elif privacy_exclude: archived_events = archived_events.exclude(**privacy_exclude) archived_events = archived_events.order_by('-start_time') tags = None if request.GET.getlist('tag'): requested_tags = request.GET.getlist('tag') found_tags = [] not_found_tags = False for each in requested_tags: try: found_tags.append(Tag.objects.get(name__iexact=each).name) except Tag.DoesNotExist: not_found_tags = True if not_found_tags: # invalid tags were used in the query string url = reverse('main:home') if found_tags: # some were good url += '?%s' % urllib.urlencode({ 'tag': found_tags }, True) return redirect(url, permanent=True) tags = Tag.objects.filter(name__in=found_tags) archived_events = archived_events.filter(tags__in=tags) if tags: # no live events when filtering by tag live_events = Event.objects.none() else: live_events = (Event.objects.live() .order_by('start_time')) if privacy_filter: live_events = live_events.filter(**privacy_filter) elif privacy_exclude: live_events = live_events.exclude(**privacy_exclude) # apply the mandatory channels filter # but only do this if it's not filtered by tags live_events = live_events.filter(channels=channels) archived_events = archived_events.filter(channels=channels) archived_paged = paginate(archived_events, page, 10) live = None also_live = [] if live_events: live, also_live = live_events[0], live_events[1:] # to simplify the complexity of the template when it tries to make the # pagination URLs, we just figure it all out here next_page_url = prev_page_url = None channel = channels[0] if archived_paged.has_next(): if channel.slug == settings.DEFAULT_CHANNEL_SLUG: next_page_url = reverse( 'main:home', args=(archived_paged.next_page_number(),) ) else: next_page_url = reverse( 'main:home_channels', args=(channel.slug, archived_paged.next_page_number()) ) if archived_paged.has_previous(): if channel.slug == settings.DEFAULT_CHANNEL_SLUG: prev_page_url = reverse( 'main:home', args=(archived_paged.previous_page_number(),) ) else: prev_page_url = reverse( 'main:home_channels', args=(channel.slug, archived_paged.previous_page_number()) ) return render(request, 'main/home.html', { 'events': archived_paged, 'live': live, 'also_live': also_live, 'tags': tags, 'Event': Event, 'channel': channel, 'next_page_url': next_page_url, 'prev_page_url': prev_page_url, })
def home(request, page=1, channel_slug=settings.DEFAULT_CHANNEL_SLUG): """Paginated recent videos and live videos.""" channels = Channel.objects.filter(slug=channel_slug) if not channels.count(): if channel_slug == settings.DEFAULT_CHANNEL_SLUG: # then, the Main channel hasn't been created yet Channel.objects.create(name=settings.DEFAULT_CHANNEL_NAME, slug=settings.DEFAULT_CHANNEL_SLUG) channels = Channel.objects.filter(slug=channel_slug) else: raise http.Http404('Channel not found') request.channels = channels privacy_filter = {} privacy_exclude = {} if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: privacy_exclude = {'privacy': Event.PRIVACY_COMPANY} else: privacy_filter = {'privacy': Event.PRIVACY_PUBLIC} archived_events = Event.objects.archived() if privacy_filter: archived_events = archived_events.filter(**privacy_filter) elif privacy_exclude: archived_events = archived_events.exclude(**privacy_exclude) archived_events = archived_events.order_by('-start_time') tags = None if request.GET.getlist('tag'): requested_tags = request.GET.getlist('tag') found_tags = [] not_found_tags = False for each in requested_tags: try: found_tags.append(Tag.objects.get(name__iexact=each).name) except Tag.DoesNotExist: not_found_tags = True if not_found_tags: # invalid tags were used in the query string url = reverse('main:home') if found_tags: # some were good url += '?%s' % urllib.urlencode({'tag': found_tags}, True) return redirect(url, permanent=True) tags = Tag.objects.filter(name__in=found_tags) archived_events = archived_events.filter(tags__in=tags) if tags: # no live events when filtering by tag live_events = Event.objects.none() else: live_events = (Event.objects.live().order_by('start_time')) if privacy_filter: live_events = live_events.filter(**privacy_filter) elif privacy_exclude: live_events = live_events.exclude(**privacy_exclude) # apply the mandatory channels filter # but only do this if it's not filtered by tags live_events = live_events.filter(channels=channels) archived_events = archived_events.filter(channels=channels) archived_paged = paginate(archived_events, page, 10) live = None also_live = [] if live_events: live, also_live = live_events[0], live_events[1:] # to simplify the complexity of the template when it tries to make the # pagination URLs, we just figure it all out here next_page_url = prev_page_url = None channel = channels[0] if archived_paged.has_next(): if channel.slug == settings.DEFAULT_CHANNEL_SLUG: next_page_url = reverse('main:home', args=(archived_paged.next_page_number(), )) else: next_page_url = reverse('main:home_channels', args=(channel.slug, archived_paged.next_page_number())) if archived_paged.has_previous(): if channel.slug == settings.DEFAULT_CHANNEL_SLUG: prev_page_url = reverse( 'main:home', args=(archived_paged.previous_page_number(), )) else: prev_page_url = reverse( 'main:home_channels', args=(channel.slug, archived_paged.previous_page_number())) return render( request, 'main/home.html', { 'events': archived_paged, 'live': live, 'also_live': also_live, 'tags': tags, 'Event': Event, 'channel': channel, 'next_page_url': next_page_url, 'prev_page_url': prev_page_url, })
def sidebar(request): # none of this is relevant if you're in certain URLs if '/manage/' in request.path_info: return {} data = { # used for things like {% if event.attr == Event.ATTR1 %} 'Event': Event, } featured = (Event.objects.archived().filter( featured=True).order_by('-start_time')) upcoming = Event.objects.upcoming().order_by('start_time') # if viewing a specific page is limited by channel, apply that filtering # here too if getattr(request, 'channels', None): channels = request.channels else: channels = Channel.objects.filter(slug=settings.DEFAULT_CHANNEL_SLUG) if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: feed_privacy = 'contributors' else: feed_privacy = 'company' else: feed_privacy = 'public' if settings.DEFAULT_CHANNEL_SLUG in [x.slug for x in channels]: feed_title = 'AirMozilla RSS' feed_url = reverse('main:feed', args=(feed_privacy, )) sidebar_channel = settings.DEFAULT_CHANNEL_SLUG else: _channel = channels[0] feed_title = 'AirMozilla - %s - RSS' % _channel.name feed_url = reverse('main:channel_feed', args=(_channel.slug, feed_privacy)) sidebar_channel = _channel.slug data['feed_title'] = feed_title data['feed_url'] = feed_url featured = featured.filter(channels__in=channels) upcoming = upcoming.filter(channels__in=channels) if not request.user.is_active: featured = featured.filter(privacy=Event.PRIVACY_PUBLIC) upcoming = upcoming.filter(privacy=Event.PRIVACY_PUBLIC) upcoming = upcoming[:settings.UPCOMING_SIDEBAR_COUNT] data['upcoming'] = upcoming data['featured'] = featured try: data['sidebar_top'] = FlatPage.objects.get(url='sidebar_top_%s' % sidebar_channel) except FlatPage.DoesNotExist: data['sidebar_top'] = None try: data['sidebar_bottom'] = FlatPage.objects.get(url='sidebar_bottom_%s' % sidebar_channel) except FlatPage.DoesNotExist: data['sidebar_bottom'] = None return data
def home(request, page=1): """Paginated recent videos and live videos.""" privacy_filter = {} privacy_exclude = {} if request.user.is_active: profile = get_profile_safely(request.user) if profile and profile.contributor: privacy_exclude = {'privacy': Event.PRIVACY_COMPANY} else: privacy_filter = {'privacy': Event.PRIVACY_PUBLIC} archived_events = Event.objects.archived() if privacy_filter: archived_events = archived_events.filter(**privacy_filter) elif privacy_exclude: archived_events = archived_events.exclude(**privacy_exclude) archived_events = archived_events.order_by('-start_time') tags = None if request.GET.getlist('tag'): requested_tags = request.GET.getlist('tag') found_tags = [] not_found_tags = False for each in requested_tags: try: found_tags.append(Tag.objects.get(name__iexact=each).name) except Tag.DoesNotExist: not_found_tags = True if not_found_tags: # invalid tags were used in the query string url = reverse('main:home') if found_tags: # some were good url += '?%s' % urllib.urlencode({ 'tag': found_tags }, True) return redirect(url, permanent=True) tags = Tag.objects.filter(name__in=found_tags) archived_events = archived_events.filter(tags__in=tags) if tags: # no live events when filtering by tag live_events = Event.objects.none() else: live_events = (Event.objects.live() .order_by('start_time')) if privacy_filter: live_events = live_events.filter(**privacy_filter) elif privacy_exclude: live_events = live_events.exclude(**privacy_exclude) archived_paged = paginate(archived_events, page, 10) live = None also_live = [] if live_events: live, also_live = live_events[0], live_events[1:] return render(request, 'main/home.html', { 'events': archived_paged, 'live': live, 'also_live': also_live, 'tags': tags, 'Event': Event, })