Exemplo n.º 1
0
def run_batch(local_name, provider_name, method_name, tee_to_stdout=True):
    # This will force the loading of the molly.utils app, attaching its log
    # handler lest the batch logs anything that needs e-mailing.
    app_by_application_name("molly.utils")

    batch = Batch.objects.get(local_name=local_name, provider_name=provider_name, method_name=method_name)

    batch.run(tee_to_stdout)

    return batch.log
Exemplo n.º 2
0
def run_batch(local_name, provider_name, method_name, tee_to_stdout=True):
    # This will force the loading of the molly.utils app, attaching its log
    # handler lest the batch logs anything that needs e-mailing.
    app_by_application_name('molly.utils')

    batch = Batch.objects.get(local_name=local_name,
                              provider_name=provider_name,
                              method_name=method_name)

    batch.run(tee_to_stdout)

    return batch.log
Exemplo n.º 3
0
    def initial_context(self, request):
        
        context = super(RailView, self).initial_context(request)
        
        if context['train_station']:
            if getattr(self.conf, 'train_station_nearest', False) \
              and context['location']:
                et = EntityType.objects.get(slug='rail-station')
                entity = et.entities_completion.filter(location__isnull=False)
                entity = entity.distance(context['location']).order_by('distance')[0]
            else:
                scheme, value = self.conf.train_station.split(':')
                entity = get_entity(scheme, value)
                
            context['entity'] = entity
        else:
            raise Http404()
            
        places_conf = app_by_application_name('molly.apps.places')
        attributions = [provider._ATTRIBUTION for provider in places_conf.providers
                      if hasattr(provider, '_ATTRIBUTION')]
        context['attributions'] = attributions

        context['board'] = request.GET.get('board', 'departures')

        self.augment_metadata([entity], board=context['board'])
        
        return context
Exemplo n.º 4
0
def unify_users(request):
    user = request.user
    conf = app_by_application_name('molly.auth')

    users = set()
    for identifier in user.useridentifier_set.all():
        if not identifier.namespace in conf.unify_identifiers:
            continue

        identifiers = UserIdentifier.objects.filter(
            namespace=identifier.namespace, value=identifier.value)

        users |= set(i.user for i in identifiers)

    token_namespaces = set(t.namespace
                           for t in user.externalservicetoken_set.all())
    identifier_namespaces = set(i.namespace
                                for i in user.useridentifier_set.all())

    root_user = min(users, key=lambda u: u.date_joined)

    # Also need to update favourites
    Favourite.objects.filter(user__in=users).update(user=root_user)

    # Need to do the root_user first, otherwise if it's after the current user,
    # tokens get assigned from the current user to the root user, and then
    # removed from the root user, because it's not the current user.
    # We accomplish this by sorting the set into a list, with a custom
    # comparison function which gives the root_user the lowest value (and so is
    # first)
    for u in sorted(users,
                    cmp=lambda x, y: -1 if x == root_user else 1
                    if y == root_user else 0):

        u.usersession_set.all().update(user=root_user)

        for token in u.externalservicetoken_set.all():
            if u != user and token.namespace in token_namespaces:
                token.delete()
            else:
                token.user = root_user
                token.save()

        for identifier in u.useridentifier_set.all():
            if u != user and identifier.namespace in identifier_namespaces:
                identifier.delete()
            else:
                identifier.user = root_user
                identifier.save()

        if u != root_user:
            u.delete()
Exemplo n.º 5
0
def unify_users(request):
    user = request.user
    conf = app_by_application_name('molly.auth')

    users = set()
    for identifier in user.useridentifier_set.all():
        if not identifier.namespace in conf.unify_identifiers:
            continue

        identifiers = UserIdentifier.objects.filter(namespace=identifier.namespace, value=identifier.value)

        users |= set(i.user for i in identifiers)

    token_namespaces = set(t.namespace for t in user.externalservicetoken_set.all())
    identifier_namespaces = set(i.namespace for i in user.useridentifier_set.all())

    root_user = min(users, key=lambda u:u.date_joined)
    users_without_root = users.copy()
    users_without_root = users_without_root.remove(root_user)
    # Send signals to anyone else who needs to be merged
    unifying_users.send_robust(sender=request, users=users_without_root, into=root_user)
    
    # Need to do the root_user first, otherwise if it's after the current user,
    # tokens get assigned from the current user to the root user, and then
    # removed from the root user, because it's not the current user.
    # We accomplish this by sorting the set into a list, with a custom
    # comparison function which gives the root_user the lowest value (and so is
    # first)
    for u in sorted(users, cmp=lambda x, y: -1 if x == root_user else 1 if y == root_user else 0):

        u.usersession_set.all().update(user=root_user)

        for token in u.externalservicetoken_set.all():
            if u != user and token.namespace in token_namespaces:
                token.delete()
            else:
                token.user = root_user
                token.save()

        for identifier in u.useridentifier_set.all():
            if u != user and identifier.namespace in identifier_namespaces:
                identifier.delete()
            else:
                identifier.user = root_user
                identifier.save()

        if u != root_user:
            u.delete()
Exemplo n.º 6
0
def geolocation(request):
    """
    Provides location-based information to the template (i.e. lat/long, google
    placemark data, and whether we would like to request the device's location
    information.
    """

    # Use the epoch in the place of -inf; a time it has been a while since.
    epoch = datetime(1970, 1, 1, 0, 0, 0)

    # Only request a location if our current location is older than one minute
    # and the user isn't updating their location manually.
    # The one minute timeout applies to the more recent of a request and an
    # update.

    location = request.session.get('geolocation:location')
    requested = request.session.get('geolocation:requested', epoch)
    updated = request.session.get('geolocation:updated', epoch)
    method = request.session.get('geolocation:method')

    period = getattr(app_by_application_name('molly.geolocation'),
                     'location_request_period', 180)

    if max(requested, updated) + timedelta(0, period) < datetime.now() \
     and method in ('html5', 'gears', 'html5request', None):
        require_location = True
        request.session['geolocation:requested'] = datetime.now()
    else:
        require_location = False
    return {
        'require_location': require_location,
        'geolocation': {
            'location': request.session.get('geolocation:location'),
            'name': request.session.get('geolocation:name'),
            'accuracy': request.session.get('geolocation:accuracy'),
            'history': request.session.get('geolocation:history'),
            'favourites': request.session.get('geolocation:favourites'),
            'method': request.session.get('geolocation:method'),
        },
        'location_error': request.GET.get('location_error'),
    }
def geolocation(request):
    """
    Provides location-based information to the template (i.e. lat/long, google
    placemark data, and whether we would like to request the device's location
    information.
    """

    # Use the epoch in the place of -inf; a time it has been a while since.
    epoch = datetime(1970,1,1, 0, 0, 0)
    
    # Only request a location if our current location is older than one minute
    # and the user isn't updating their location manually.
    # The one minute timeout applies to the more recent of a request and an
    # update.
    
    location = request.session.get('geolocation:location')
    requested = request.session.get('geolocation:requested', epoch)
    updated = request.session.get('geolocation:updated', epoch)
    method = request.session.get('geolocation:method')

    period = getattr(app_by_application_name('molly.geolocation'), 'location_request_period', 180)    
    
    if max(requested, updated) + timedelta(0, period) < datetime.now() \
     and method in ('html5', 'gears', 'html5request', None):
        require_location = True
        request.session['geolocation:requested'] = datetime.now()
    else:
        require_location = False
    return {
        'require_location': require_location,
        'geolocation': {
            'location': request.session.get('geolocation:location'),
            'name': request.session.get('geolocation:name'),
            'accuracy': request.session.get('geolocation:accuracy'),
            'history': request.session.get('geolocation:history'),
            'favourites': request.session.get('geolocation:favourites'),
            'method': request.session.get('geolocation:method'),
        },
        'location_error': request.GET.get('location_error'),
    }
Exemplo n.º 8
0
def unify_users(request):
    user = request.user
    conf = app_by_application_name('molly.auth')

    users = set()
    for identifier in user.useridentifier_set.all():
        if not identifier.namespace in conf.unify_identifiers:
            continue

        identifiers = UserIdentifier.objects.filter(namespace=identifier.namespace, value=identifier.value)

        users |= set(i.user for i in identifiers)

    token_namespaces = set(t.namespace for t in user.externalservicetoken_set.all())
    identifier_namespaces = set(i.namespace for i in user.useridentifier_set.all())

    root_user = min(users, key=lambda u:u.date_joined)

    for u in users:

        u.usersession_set.all().update(user=root_user)

        for token in u.externalservicetoken_set.all():
            if u != user and token.namespace in token_namespaces:
                token.delete()
            else:
                token.user = root_user
                token.save()

        for identifier in u.useridentifier_set.all():
            if u != user and identifier.namespace in identifier_namespaces:
                identifier.delete()
            else:
                identifier.user = root_user
                identifier.save()

        if u != root_user:
            u.delete()
Exemplo n.º 9
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.º 10
0
 def augment_metadata(self, entities, **kwargs):
     # 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, **kwargs)
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