def initial_context(self, request, scheme, value): context = super(EntityDetailView, self).initial_context(request) entity = get_entity(scheme, value) associations = [] if hasattr(self.conf, 'associations'): for association in self.conf.associations: id_type, id, associated_entities = association try: if id in entity.identifiers[id_type]: associations += [{'type': type, 'entities': [get_entity(ns, value) for ns, value in es]} for type, es in associated_entities] except (KeyError, Http404): pass for entity_group in entity.groups.all(): group_entities = filter(lambda e: e != entity, Entity.objects.filter(groups=entity_group)) if len(group_entities) > 0: associations.append({ 'type': entity_group.title, 'entities': group_entities, }) board = request.GET.get('board', 'departures') if board != 'departures': board = 'arrivals' context.update({ 'entity': entity, 'train_station': entity, # This allows the ldb metadata to be portable 'board': board, 'entity_types': entity.all_types.all(), 'associations': associations, }) return context
def handle_POST(self, request, context, scheme, value): entity = context['entity'] = get_entity(scheme, value) if entity.source.module_name != 'mobile.providers.apps.maps.osm': raise Http404 form = UpdateOSMForm(request.POST) if form.is_valid(): new_metadata = copy.deepcopy(entity.metadata['osm']) for k in ('name', 'operator', 'phone', 'opening_hours', 'url', 'cuisine', 'food', 'food__hours', 'atm', 'collection_times', 'ref', 'capacity'): tag_name = k.replace('__', ':') if tag_name in new_metadata and not form.cleaned_data[k]: del new_metadata['osm']['tags'][tag_name] elif form.cleaned_data[k]: new_metadata['tags'][tag_name] = form.cleaned_data[k] new_metadata['attrs']['version'] = str(int(new_metadata['attrs']['version']) + 1) osm_update = OSMUpdate( contributor_name=form.cleaned_data['contributor_name'], contributor_email=form.cleaned_data['contributor_email'], contributor_attribute=form.cleaned_data['contributor_attribute'], entity=entity, old=simplejson.dumps(entity.metadata), new=simplejson.dumps(new_metadata), notes=form.cleaned_data['notes'], ) osm_update.save() return self.redirect( reverse('places:entity-update', args=[scheme, value]) + '?submitted=true', request) else: context['form'] = form return self.render(request, context, 'places/update_osm')
def breadcrumb(self, request, context, scheme, value): scheme = unquote(scheme) value = unquote(value) if request.session.get('geolocation:location'): parent_view = 'nearby-detail' else: parent_view = 'category-detail' entity = get_entity(scheme, value) return Breadcrumb( 'places', lazy_parent(parent_view, ptypes=entity.primary_type.slug), context['entity'].title, lazy_reverse('entity', args=[scheme, value]), )
def get_entity(self): """ Gets the entity for this library. This look up is done using the identifier namespace defined in the config. Returns None if no identifier can be found. """ if hasattr(app_by_local_name("library"), "library_identifier"): library_identifier = app_by_local_name("library").library_identifier try: return get_entity(library_identifier, self.location[1]) except (Http404, Entity.MultipleObjectsReturned): return None else: return None
def get_metadata(self, request, scheme, value): entity = get_entity(scheme, value) user_location = request.session.get('geolocation:location') distance, bearing = entity.get_distance_and_bearing_from(user_location) additional = '<strong>%s</strong>' % capfirst(entity.primary_type.verbose_name) if distance: additional += ', ' + _('about %(distance)dm %(bearing)s') % { 'distance': int(math.ceil(distance / 10) * 10), 'bearing': bearing } routes = sorted(set(sor.route.service_id for sor in entity.stoponroute_set.all())) if routes: additional += ', ' + ungettext('service %(services)s stops here', 'services %(services)s stop here', len(routes)) % { 'services': ' '.join(routes) } return { 'title': entity.title, 'additional': additional, 'entity': entity, }
def initial_context(self, request, scheme, value): context = super(ServiceDetailView, self).initial_context(request) service_id = request.GET.get('id') route_id = request.GET.get('route') route_pk = request.GET.get('routeid') journey = request.GET.get('journey') if service_id or route_id or route_pk or journey: entity = get_entity(scheme, value) else: raise Http404() context.update({ 'entity': entity, }) if service_id: # Add live information from the providers for provider in reversed(self.conf.providers): provider.augment_metadata((entity,)) # If we have no way of getting further journey details, 404 if 'service_details' not in entity.metadata: raise Http404 # Deal with train service data if entity.metadata['service_type'] == 'ldb': # LDB has + in URLs, but Django converts that to space service = entity.metadata['service_details'](service_id.replace(' ', '+')) else: service = entity.metadata['service_details'](service_id) if service is None: raise Http404 if 'error' in service: context.update({ 'title': 'An error occurred', 'service': { 'error': service['error'], }, }) return context context.update({ 'service': service, 'title': service['title'], 'zoom_controls': False, }) elif route_id or route_pk: if route_id: route = entity.route_set.filter(service_id=route_id).distinct() if route.count() == 0: raise Http404() elif route.count() > 1: context.update({ 'title': _('Multiple routes found'), 'multiple_routes': route }) return context else: route = route[0] else: route = get_object_or_404(Route, id=route_pk) i = 1 calling_points = [] previous = True for stop in route.stoponroute_set.all(): if stop.entity == entity: previous = False calling_point = { 'entity': stop.entity, 'at': previous } if stop.entity.location is not None: calling_point['stop_num'] = i i += 1 calling_points.append(calling_point) service = { 'entities': route.stops.all(), 'operator': route.operator, 'has_timetable': False, 'has_realtime': False, 'calling_points': calling_points } if entity not in service['entities']: raise Http404() context.update({ 'title': '%s: %s' % (route.service_id, route.service_name), 'service': service }) elif journey: journey = get_object_or_404(Journey, id=journey) route = journey.route entity_passed = False i = 1 calling_points = [] for stop in journey.scheduledstop_set.all(): if stop.entity == entity: entity_passed = True if not entity_passed and stop.std < datetime.now().time(): calling_point = { 'entity': stop.entity, 'st': stop.std.strftime('%H:%M'), 'at': True } else: calling_point = { 'entity': stop.entity, # Show arrival time (if it exists, else departure time) # if this stop is AFTER where we currently are, otherwise # show the time the bus left stops before this one (if # it exists) 'st': ((stop.sta or stop.std) if entity_passed else (stop.std or stop.sta)).strftime('%H:%M'), 'at': False } if stop.entity.location is not None: calling_point['stop_num'] = i i += 1 calling_points.append(calling_point) service = { 'entities': [s.entity for s in journey.scheduledstop_set.all()], 'operator': journey.route.operator, 'has_timetable': True, 'has_realtime': False, 'calling_points': calling_points, 'notes': journey.notes } if entity not in service['entities']: raise Http404() context.update({ 'title': '%s: %s' % (route.service_id, route.service_name), 'service': service }) if entity.location or len(filter(lambda e: e.location is not None, service['entities'])): map = Map( centre_point=(entity.location[0], entity.location[1], 'green', entity.title) if entity.location else None, points=[(e.location[0], e.location[1], 'red', e.title) for e in service['entities'] if e.location is not None], min_points=len(service['entities']), zoom=None, width=request.map_width, height=request.map_height, ) context.update({ 'map': map }) return context
def handle_GET(self, request, context, scheme, value, ptype): entity = get_entity(scheme, value) return super(NearbyEntityDetailView, self).handle_GET(request, context, ptype, entity)
def get_metadata(self, request, scheme, value, ptype): entity = get_entity(type_slug, id) return super(NearbyEntityDetailView, self).get_metadata(request, ptype, entity)
def initial_context(self, request, scheme, value, ptype): entity = get_entity(scheme, value) context = super(NearbyEntityDetailView, self).initial_context(request, ptype, entity) context['entity'] = entity return context
def handle_GET(self, request, context, scheme, value): entity = get_entity(scheme, value) return super(NearbyEntityListView, self).handle_GET(request, context, entity)
def initial_context(self, request, scheme, value): return { 'entity': get_entity(scheme, value), }
def get_metadata(self, request, scheme, value): entity = get_entity(scheme, value) return super(NearbyEntityListView, self).get_metadata(request, entity)
def initial_context(self, request, scheme, value): return dict( super(EntityUpdateView, self).initial_context(request), entity=get_entity(scheme, value), )
def get_entity_filter(value): return get_entity(*value)
def _scrape(self, route, url, output): url += '&showall=1' service = etree.parse(urlopen(url), parser=etree.HTMLParser()) route.stops.clear() for i, tr in enumerate(service.find('.//table').findall('tr')[1:]): try: stop_code = tr[1][0].text except IndexError: # Stops on ACIS Live that don't have codes, e.g., out of county # stops stop_name = tr[3][0].text try: entity = Entity.objects.get(source=self._get_source(), _identifiers__scheme='acisroute', _identifiers__value=stop_name) except Entity.DoesNotExist: entity = Entity(source=self._get_source()) entity_type = self._get_entity_type() entity.primary_type = entity_type identifiers = { 'acisroute': stop_name } entity.save(identifiers=identifiers) set_name_in_language(entity, 'en', title=stop_name) entity.all_types = (entity_type,) entity.update_all_types_completion() else: if stop_code.startswith('693') or stop_code.startswith('272') \ or stop_code.startswith('734') or stop_code.startswith('282'): # Oxontime uses NaPTAN code scheme = 'naptan' elif stop_code.startswith('450'): # West Yorkshire uses plate code scheme = 'plate' else: # Everyone else uses ATCO scheme = 'atco' if stop_code.startswith('370'): # Except South Yorkshire, which mangles the code stop_code = '3700%s' % stop_code[3:] try: entity = get_entity(scheme, stop_code) if entity.source == self._get_source(): # Raise Http404 if this is a bus stop we came up with, # so any name changes, etc, get processed raise Http404() except Http404: # Out of zone bus stops with NaPTAN codes - alternatively, # the fake bus stops Oxontime made up for the TUBE route try: entity = Entity.objects.get(source=self._get_source(), _identifiers__scheme=scheme, _identifiers__value=stop_code) except Entity.DoesNotExist: entity = Entity(source=self._get_source()) identifiers = {scheme: stop_code} entity_type = self._get_entity_type() entity.primary_type = entity_type entity.save(identifiers=identifiers) set_name_in_language(entity, 'en', title=tr[3][0].text) entity.all_types = (entity_type,) entity.update_all_types_completion() entity.save() StopOnRoute.objects.create(route=route, entity=entity, order=i)