Exemplo n.º 1
0
    def handle_GET(self, request, context):
        # Check whether the referer header is from the same host as the server
        # is responding as
        try:
            referer_host = request.META.get('HTTP_REFERER', '').split('/')[2]
            internal_referer = referer_host == request.META.get('HTTP_HOST')
        except IndexError:
            internal_referer = False

        # Redirects if the user is a desktop browser who hasn't been referred
        # from this site. Also extra checks for preview mode and DEBUG.
        if ("generic_web_browser" in device_parents[request.device.devid]
                and not request.session.get('home:desktop_shown', False)
                and not request.GET.get('preview') == 'true'
                and not internal_referer and not settings.DEBUG
                and conf.has_app('molly.apps.desktop')):
            return HttpResponseRedirect(reverse('desktop:index'))

        # Add any one-off messages to be shown to this user
        messages = []

        if not request.session.get('home:opera_mini_warning', False) \
          and request.browser.mobile_browser == u'Opera Mini':
            messages.append("""Please note that the "Mobile View" on Opera Mini
                            does not display this site correctly. To ensure
                            correct operation of this site, ensure "Mobile View"
                            is set to Off in Opera settings""")
            request.session['home:opera_mini_warning'] = True

        applications = [{
            'application_name': app.application_name,
            'local_name': app.local_name,
            'title': app.title,
            'url': reverse('%s:index' % app.local_name) \
                    if app.has_urlconf else None,
            'display_to_user': app.display_to_user,
        } for app in conf.all_apps()]

        # Add accesskeys to the first 9 apps to be displayed to the user
        for i, app in enumerate(
            [app for app in applications if app['display_to_user']][:9]):
            app['accesskey'] = i + 1

        context = {
            'applications': applications,
            'hide_feedback_link': True,
            'is_christmas': datetime.now().month == 12,
            'messages': messages,
            'favourites': get_favourites(request),
        }
        return self.render(request,
                           context,
                           'home/index',
                           expires=timedelta(minutes=10))
Exemplo n.º 2
0
    def handle_GET(self, request, context):
        # Check whether the referer header is from the same host as the server
        # is responding as
        try:
            referer_host = request.META.get('HTTP_REFERER', '').split('/')[2]
            internal_referer = referer_host == request.META.get('HTTP_HOST')
        except IndexError:
            internal_referer = False

        # Redirects if the user is a desktop browser who hasn't been referred
        # from this site. Also extra checks for preview mode and DEBUG.
        if ("generic_web_browser" in device_parents[request.device.devid]
            and not request.session.get('home:desktop_shown', False)
            and not request.GET.get('preview') == 'true'
            and not internal_referer
            and not settings.DEBUG
            and conf.has_app('molly.apps.desktop')):
            return HttpResponseRedirect(reverse('desktop:index'))
        
        # Add any one-off messages to be shown to this user
        messages = []
        
        if not request.session.get('home:opera_mini_warning', False) \
          and request.browser.mobile_browser == u'Opera Mini':
            messages.append("""Please note that the "Mobile View" on Opera Mini
                            does not display this site correctly. To ensure
                            correct operation of this site, ensure "Mobile View"
                            is set to Off in Opera settings""")
            request.session['home:opera_mini_warning'] = True

        applications = [{
            'application_name': app.application_name,
            'local_name': app.local_name,
            'title': app.title,
            'url': reverse('%s:index' % app.local_name) \
                    if app.has_urlconf else None,
            'display_to_user': app.display_to_user,
        } for app in conf.all_apps()]

        # Add accesskeys to the first 9 apps to be displayed to the user
        for i, app in enumerate(
                [app for app in applications if app['display_to_user']][:9]
            ):
            app['accesskey'] = i + 1

        context = {
            'applications': applications,
            'hide_feedback_link': True,
            'is_christmas': datetime.now().month == 12,
            'messages': messages,
            'favourites': get_favourites(request),
        }
        return self.render(request, context, 'home/index',
                           expires=timedelta(minutes=10))
Exemplo n.º 3
0
    def initial_context(self, request, *args, **kwargs):

        context = super(FavouritableView, self).initial_context(request, *args, **kwargs)

        # Add whether or not this is favouritable to the context
        context["is_favouritable"] = True

        # Also, add whether or not this particular thing already is favourited
        context["is_favourite"] = request.path_info in [f.url for f in get_favourites(request)]

        # And the URL of this page (so it can be favourited)
        context["favourite_url"] = request.path_info

        return context
Exemplo n.º 4
0
    def initial_context(self, request, *args, **kwargs):

        context = super(FavouritableView,
                        self).initial_context(request, *args, **kwargs)

        # Add whether or not this is favouritable to the context
        context['is_favouritable'] = True

        # Also, add whether or not this particular thing already is favourited
        context['is_favourite'] = request.path_info in [
            f.url for f in get_favourites(request)
        ]

        # And the URL of this page (so it can be favourited)
        context['favourite_url'] = request.path_info

        return context
Exemplo n.º 5
0
 def handle_GET(self, request, context):
     """
     Show a list of favourited things, and allow removal of these
     """
     context["favourites"] = get_favourites(request)
     return self.render(request, context, "favourites/index")
Exemplo n.º 6
0
    def handle_GET(self, request, context):
        # Check whether the referer header is from the same host as the server
        # is responding as
        try:
            referer_host = request.META.get('HTTP_REFERER', '').split('/')[2]
            internal_referer = referer_host == request.META.get('HTTP_HOST')
        except IndexError:
            internal_referer = False

        # Redirects if the user is a desktop browser who hasn't been referred
        # from this site. Also extra checks for preview mode and DEBUG.
        if ("generic_web_browser" in device_parents[request.device.devid]
            and not request.session.get('home:desktop_shown', False)
            and not request.GET.get('preview') == 'true'
            and not internal_referer
            and not settings.DEBUG
            and has_app('molly.apps.desktop')
            and request.REQUEST.get('format') is None):
            return self.redirect(reverse('desktop:index'), request)
        
        messages = []
        # Add any one-off messages to be shown to this user
        if UserMessage.objects.filter(
                read=False, session_key=request.session.session_key).count():
            messages.append({
                'url': reverse('home:messages'),
                'body': _('You have a message from the developers')
            })
        
        # Warn users who use Opera devices
        if not request.session.get('home:opera_mini_warning', False) \
          and request.browser.mobile_browser == u'Opera Mini':
            messages.append(
                { 'body': _("""Please note that the "Mobile View" on Opera Mini does not display this site correctly. To ensure correct operation of this site, ensure "Mobile View" is set to Off in Opera settings""") })
            request.session['home:opera_mini_warning'] = True
        
        if has_app_by_application_name('molly.apps.weather'):
            weather_id = app_by_application_name('molly.apps.weather').location_id
            try:
                weather = Weather.objects.get(ptype='o', location_id=weather_id)
            except Weather.DoesNotExist:
                weather = None
        else:
            weather = None
        
        applications = [{
            'application_name': app.application_name,
            'local_name': app.local_name,
            'title': app.title,
            'url': reverse('%s:index' % app.local_name) \
                    if app.has_urlconf else None,
            'display_to_user': app.display_to_user,
        } for app in all_apps()]

        # Add accesskeys to the first 9 apps to be displayed to the user
        for i, app in enumerate(
                [app for app in applications if app['display_to_user']][:9]
            ):
            app['accesskey'] = i + 1

        context = {
            'applications': applications,
            'hide_feedback_link': True,
            'messages': messages,
            'favourites': get_favourites(request),
            'weather': weather,
        }
        return self.render(request, context, 'home/index',
                           expires=timedelta(minutes=10))
Exemplo n.º 7
0
 def initial_context(self, request):
     
     # Get our location for location sorting
     location = request.session.get('geolocation:location')
     if location:
         location = Point(location, srid=4326)
     
     context, entities = {'location':location}, set()
     
     # If train station is set on config, then include that
     if hasattr(self.conf, 'train_station'):
         if getattr(self.conf, 'train_station_nearest', False) and location:
             et = EntityType.objects.get(slug='rail-station')
             entity = et.entities_completion.filter(location__isnull=False).distance(location).order_by('distance')[0]
         else:
             scheme, value = self.conf.train_station.split(':')
             entity = get_entity(scheme, value)
         entities.add(entity)
         context['train_station'] = entity
     
     # If park and ride variable is set, then include those too:
     if hasattr(self.conf, 'park_and_rides'):
         park_and_rides = []
         for park_and_ride in self.conf.park_and_rides:
             scheme, value = park_and_ride.split(':')
             entity = get_entity(scheme, value)
             park_and_rides.append(entity)
             entities.add(entity)
         context['park_and_rides'] = park_and_rides
     
     # If service status provider is set, then include those too:
     if hasattr(self.conf, 'transit_status_provider'):
         context['transit_status'] = self.conf.transit_status_provider.get_status()
     
     context['nearby'] = {}
     for context_key in getattr(self.conf, 'nearby', {}):
         type_slug, count = self.conf.nearby[context_key]
         et = EntityType.objects.get(slug=type_slug)
         
         favourites = filter(
             lambda e: e is not None and et in e.all_types_completion.all(),
             [f.metadata.get('entity') for f in get_favourites(request)])
         
         if request.GET.get(context_key) == 'nearby':
             
             if location:
                 es = et.entities_completion.filter(location__isnull=False).distance(location).order_by('distance')[:count]
             else:
                 es = []
             results_type = 'Nearby'
             
         elif request.GET.get(context_key) == 'favourites':
             
             es = favourites    
             results_type = 'Favourite'
             
         else:
             
             if len(favourites) == 0:
                 if location:
                     es = et.entities_completion.filter(location__isnull=False).distance(location).order_by('distance')[:count]
                 else:
                     es = []
             else:
                 es = favourites
             
             results_type = 'Favourite' if len(favourites) > 0 else 'Nearby'
         
         for e in (e for e in es if hasattr(e, 'distance')):
             distance, e.bearing = e.get_distance_and_bearing_from(location)
         
         entities |= set(es)
         context['nearby'][context_key] = {
             'type': et,
             'entities': es,
             'results_type': results_type,
         }
         
     if getattr(self.conf, 'travel_alerts', False):
         es = Entity.objects.filter(primary_type__slug='travel-alert')
         if location:
             es = es.filter(location__isnull=False).distance(location).order_by('distance')
         else:
             es = es.order_by('title')
         entities |= set(es)
         context['travel_alerts'] = es
     
     # Get any real-time information for all the places we're about to display
     places_conf = app_by_application_name('molly.apps.places')
     for provider in reversed(places_conf.providers):
         provider.augment_metadata(entities,
                                   board=request.GET.get('board', 'departures'))
     
     context['board'] = request.GET.get('board', 'departures')
     return context
Exemplo n.º 8
0
 def handle_GET(self, request, context):
     """
     Show a list of favourited things, and allow removal of these
     """
     context['favourites'] = get_favourites(request)
     return self.render(request, context, 'favourites/index')
Exemplo n.º 9
0
    def handle_GET(self, request, context):
        # Check whether the referer header is from the same host as the server
        # is responding as
        try:
            referer_host = request.META.get('HTTP_REFERER', '').split('/')[2]
            internal_referer = referer_host == request.META.get('HTTP_HOST')
        except IndexError:
            internal_referer = False

        # Redirects if the user is a desktop browser who hasn't been referred
        # from this site. Also extra checks for preview mode and DEBUG.
        if ("generic_web_browser" in device_parents[request.device.devid]
                and not request.session.get('home:desktop_shown', False)
                and not request.GET.get('preview') == 'true'
                and not internal_referer and not settings.DEBUG
                and conf.has_app('molly.apps.desktop')
                and request.REQUEST.get('format') is None):
            return self.redirect(reverse('desktop:index'), request)

        messages = []
        # Add any one-off messages to be shown to this user
        if UserMessage.objects.filter(
                read=False, session_key=request.session.session_key).count():
            messages.append({
                'url': reverse('home:messages'),
                'body': _('You have a message from the developers')
            })

        # Warn users who use Opera devices
        if not request.session.get('home:opera_mini_warning', False) \
          and request.browser.mobile_browser == u'Opera Mini':
            messages.append({
                'body':
                _("""Please note that the "Mobile View" on Opera Mini does not display this site correctly. To ensure correct operation of this site, ensure "Mobile View" is set to Off in Opera settings"""
                  )
            })
            request.session['home:opera_mini_warning'] = True

        if has_app_by_application_name('molly.apps.weather'):
            weather_id = app_by_application_name(
                'molly.apps.weather').location_id
            try:
                weather = Weather.objects.get(ptype='o',
                                              location_id=weather_id)
            except Weather.DoesNotExist:
                weather = None
        else:
            weather = None

        applications = [{
            'application_name': app.application_name,
            'local_name': app.local_name,
            'title': app.title,
            'url': reverse('%s:index' % app.local_name) \
                    if app.has_urlconf else None,
            'display_to_user': app.display_to_user,
        } for app in conf.all_apps()]

        # Add accesskeys to the first 9 apps to be displayed to the user
        for i, app in enumerate(
            [app for app in applications if app['display_to_user']][:9]):
            app['accesskey'] = i + 1

        context = {
            'applications': applications,
            'hide_feedback_link': True,
            'messages': messages,
            'favourites': get_favourites(request),
            'weather': weather,
        }
        return self.render(request,
                           context,
                           'home/index',
                           expires=timedelta(minutes=10))
Exemplo n.º 10
0
 def initial_context(self, request, key):
     
     context = super(PublicTransportView, self).initial_context(request)
     
     location = context['location']
     selected_routes = request.GET.getlist('route')
     
     if key not in getattr(self.conf, 'nearby', {}):
         raise Http404()
     
     # If service status provider is set, then include those too:
     if hasattr(self.conf, '%s_status_provider' % key):
         provider = getattr(self.conf, '%s_status_provider' % key)
         context['line_status'] = provider.get_status()
     
     type_slug, count = self.conf.nearby[key]
     et = EntityType.objects.get(slug=type_slug)
     
     favourites = filter(
         lambda e: e is not None and et in e.all_types_completion.all(),
         [f.metadata.get('entity') for f in get_favourites(request)])
     
     if selected_routes:
         
         if location:
             es = et.entities_completion.filter(
                 location__isnull=False, route__service_id__in=selected_routes)
             es = es.distinct().distance(location).order_by('distance')[:count]
         else:
             es = []
     
     else:
         
         if location:
             es = et.entities_completion.filter(location__isnull=False)
             es = es.distance(location).order_by('distance')[:count]
         else:
             es = []
     
     for e in (e for e in es if hasattr(e, 'distance')):
         distance, e.bearing = e.get_distance_and_bearing_from(location)
     
     self.augment_metadata(es, routes=selected_routes)
     
     for e in (e for e in favourites if hasattr(e, 'distance')):
         distance, e.bearing = e.get_distance_and_bearing_from(location)
     self.augment_metadata(favourites)
     
     context.update({
         'pageslug': key,
         'type': et,
         'entities': es,
         'favourites': favourites
     })
     
     # Only show routes which serve this type of thing
     routes = Route.objects.filter(stoponroute__entity__all_types_completion=et).distinct()
     route_ids = routes.values_list('service_id').distinct()
     
     context['route_ids'] = sorted(map(itemgetter(0), route_ids), key=bus_route_sorter)
     context['selected_routes'] = selected_routes
     
     return context
Exemplo n.º 11
0
 def initial_context(self, request):
     location = request.session.get('geolocation:location')
     if location:
         location = Point(location, srid=4326)
     
     context, entities = {'location':location}, set()
     
     if self.conf.train_station:
         scheme, value = self.conf.train_station.split(':')
         entity = Entity.objects.get(_identifiers__scheme=scheme, _identifiers__value=value)
         entities.add(entity)
         context['train_station'] = entity
         
     for context_key in getattr(self.conf, 'nearby', {}):
         type_slug, count, without_location, fav_override = self.conf.nearby[context_key]
         et = EntityType.objects.get(slug=type_slug)
         if fav_override:
             favourites = filter(lambda e: e is not None and et in e.all_types_completion.all(), [f.metadata.get('entity') for f in get_favourites(request)])
         
         if not fav_override or len(favourites) == 0:
             if without_location:
                 es = et.entities_completion.order_by('title')[:count]
             elif location:
                 es = et.entities_completion.filter(location__isnull=False).distance(location).order_by('distance')[:count]
             else:
                 context[context_key] = {
                     'results_type': 'Nearby'
                 }
                 continue
         else:
             es = favourites
         
         if context_key == 'park_and_rides' and getattr(self.conf, 'park_and_ride_sort', None) is not None:
             sorted_es = []
             for key, id in [s.split(':') for s in self.conf.park_and_ride_sort]:
                 for e in es:
                     if id in e.identifiers[key]:
                         sorted_es.append(e)
                         continue
             es = sorted_es
         
         entities |= set(es)
         context[context_key] = {
             'type': et,
             'entities': es,
             'results_type': 'Favourite' if fav_override and len(favourites) > 0 else 'Nearby'
         }
         
     if getattr(self.conf, 'travel_alerts', False):
         es = Entity.objects.filter(primary_type__slug='travel-alert')
         if location:
             es = es.filter(location__isnull=False).distance(location).order_by('distance')
         else:
             es = es.order_by('title')
         entities |= set(es)
         context['travel_alerts'] = es
     
     # Get any real-time information for all the places we're about to display
     places_conf = app_by_application_name('molly.apps.places')
     for provider in reversed(places_conf.providers):
         provider.augment_metadata(entities)
     
     return context
Exemplo n.º 12
0
    def initial_context(self, request):
        location = request.session.get('geolocation:location')
        if location:
            location = Point(location, srid=4326)

        context, entities = {'location': location}, set()

        if self.conf.train_station:
            scheme, value = self.conf.train_station.split(':')
            entity = Entity.objects.get(_identifiers__scheme=scheme,
                                        _identifiers__value=value)
            entities.add(entity)
            context['train_station'] = entity

        for context_key in getattr(self.conf, 'nearby', {}):
            type_slug, count, without_location, fav_override = self.conf.nearby[
                context_key]
            et = EntityType.objects.get(slug=type_slug)
            if fav_override:
                favourites = filter(
                    lambda e: e is not None and et in e.all_types_completion.
                    all(), [
                        f.metadata.get('entity')
                        for f in get_favourites(request)
                    ])

            if not fav_override or len(favourites) == 0:
                if without_location:
                    es = et.entities_completion.order_by('title')[:count]
                elif location:
                    es = et.entities_completion.filter(
                        location__isnull=False).distance(location).order_by(
                            'distance')[:count]
                else:
                    context[context_key] = {'results_type': 'Nearby'}
                    continue
            else:
                es = favourites

            if context_key == 'park_and_rides' and getattr(
                    self.conf, 'park_and_ride_sort', None) is not None:
                sorted_es = []
                for key, id in [
                        s.split(':') for s in self.conf.park_and_ride_sort
                ]:
                    for e in es:
                        if id in e.identifiers[key]:
                            sorted_es.append(e)
                            continue
                es = sorted_es

            entities |= set(es)
            context[context_key] = {
                'type':
                et,
                'entities':
                es,
                'results_type':
                'Favourite'
                if fav_override and len(favourites) > 0 else 'Nearby'
            }

        if getattr(self.conf, 'travel_alerts', False):
            es = Entity.objects.filter(primary_type__slug='travel-alert')
            if location:
                es = es.filter(location__isnull=False).distance(
                    location).order_by('distance')
            else:
                es = es.order_by('title')
            entities |= set(es)
            context['travel_alerts'] = es

        # Get any real-time information for all the places we're about to display
        places_conf = app_by_application_name('molly.apps.places')
        for provider in reversed(places_conf.providers):
            provider.augment_metadata(entities)

        return context