def revision(request, id, revision): ''' Get GeoJSON of a place at given revision ''' place = get_place_or_404(id) if request.method == 'GET': revision = Place.objects.revision(place,revision) geojson = revision['place'].to_geojson() geojson['version'] = revision['version'] geojson['digest'] = revision['digest'] return render_to_json_response(geojson) elif request.method == 'PUT': user_id = request.user.id username = request.user.username data = json.loads(request.body) comment = data.get('comment', '') metadata = { 'user': username, 'user_id': user_id, 'comment': comment } place = place.rollback(revision, metadata=metadata) #FIXME: handle invalid revision ids return render_to_json_response(place.to_geojson()) else: return render_to_json_response({'error': 'Method Not Allowed'}, status=405)
def similar(request, id): ''' Takes place ID Returns GeoJSON feed of similar places. Extra properties of feed: total: total number of similar places max_score: max score of similarity (?) ''' try: place = Place.objects.get(id) except ElasticHttpNotFoundError: return render_to_json_response({'error': 'Place not found'}, status=404) if request.method == 'GET': similar_places = place.find_similar() geojson = { 'type': 'FeatureCollection', 'total': similar_places['total'], 'max_score': similar_places['max_score'], 'features': [p.to_geojson() for p in similar_places['places']] } return render_to_json_response(geojson) #return render_to_json_response({'error': 'Not implemented'}, status=501) else: return render_to_json_response({'error': 'Method Not Allowed'}, status=405)
def revision(request, id, revision): ''' Get GeoJSON of a place at given revision ''' place = get_place_or_404(id) if request.method == 'GET': revision = Place.objects.revision(place, revision) geojson = revision['place'].to_geojson() geojson['version'] = revision['version'] geojson['digest'] = revision['digest'] return render_to_json_response(geojson) elif request.method == 'PUT': user_id = request.user.id username = request.user.username data = json.loads(request.body) comment = data.get('comment', '') metadata = {'user': username, 'user_id': user_id, 'comment': comment} place = place.rollback( revision, metadata=metadata) #FIXME: handle invalid revision ids return render_to_json_response(place.to_geojson()) else: return render_to_json_response({'error': 'Method Not Allowed'}, status=405)
def checkin(request): user = request.GET.get("user", None) time_in = request.GET.get("time_in", None) time_out = request.GET.get("time_out", None) centre = request.GET.get("centre", None) if not user or not time_in or not centre: return render_to_json_response({'error': 'Insufficient data'}) curr_user = request.user curr_user_type = curr_user.user_type if curr_user_type not in ['admin', 'staff', 'tutor']: return render_to_json_response({'error': 'Insufficient permissions'}) if user.user_type == 'tutor' and curr_user_type == 'tutor': return render_to_json_response( {'error': 'Tutors can only mark attendance for students'}) today = datetime.datetime.now() if Checkin.objects.filter(user=user).filter(time_in__date=today).filter( centre=centre).count() > 0: return render_to_json_response( {'error': 'Attendance already marked for today'}) checkin = Checkin(user=user, time_in=time_in, time_out=time_out, marked_by=curr_user) checkin.save() return render_to_json_response({'success': 'Attendance marked'})
def addClips(request): ''' takes { edit: string, index: int, clips: [] item: string, in: float, out: float, annotation: string } add clips with item/in/out or annotation to edit with id clips are added at index or end if index is not provided (annoation id is in the form item/annotation) returns { } ''' response = json_response() data = json.loads(request.POST['data']) edit = get_edit_or_404_json(data['edit']) clips = [] if edit.editable(request.user): index = data.get('index', edit.clips.count()) for c in data['clips']: clip = edit.add_clip(c, index) index += 1 if not clip: response = json_response(status=500, text='invalid in/out') return render_to_json_response(response) else: clips.append(clip.json(request.user)) response['data']['clips'] = clips else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def addAnnotations(request): ''' takes { item: itemId, layer: layerId, annotations: [{ in: float, out: float, value: string }, ...] } returns { taskId: string } ''' data = json.loads(request.POST['data']) for key in ('item', 'layer', 'annotations'): if key not in data: return render_to_json_response(json_response(status=400, text='invalid data')) item = get_object_or_404_json(Item, itemId=data['item']) layer_id = data['layer'] layer = filter(lambda l: l['id'] == layer_id, settings.CONFIG['layers'])[0] if item.editable(request.user) \ and layer['canAddAnnotations'].get(request.user.get_profile().get_level()): response = json_response() data['user'] = request.user.username t = add_annotations.delay(data) response['data']['taskId'] = t.task_id else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def add_relation(request): feature1 = request.GET.get("feature1", None) feature2 = request.GET.get("feature2", None) relation = request.GET.get("relation", None) if feature1 == None or feature2 == None or relation == None: return render_to_json_response({'error': 'bad request'}) if not request.user.is_staff: return render_to_json_response({'error': 'insufficient permissions error. try logging in again? are you staff / admin?'}) feature1 = get_object_or_404_json(Feature, pk=feature1) feature2 = get_object_or_404_json(Feature, pk=feature2) verb = rel_obj = None try: rel_obj = Relationship.objects.get(feature1=feature1, feature2=feature2) verb = "deleted" except ObjectDoesNotExist: rel_obj = Relationship(feature1=feature1, feature2=feature2, relationship_type=relation) verb = "created" if relation == "": if verb == "deleted": rel_obj.delete() if relation == "conflates": feature2.is_primary = True feature2.save() else: return render_to_json_response({'error': 'relation is already deleted'}) else: rel_obj.save() if relation == "conflates": feature2.is_primary = False feature2.save() return render_to_json_response({'success': 'relation %s successfully.' % verb})
def signup(request): username = request.POST.get("username", None) password = request.POST.get("password", None) password2 = request.POST.get("password2", None) email = request.POST.get("email", None) first_name = request.POST.get("first_name", None) last_name = request.POST.get("last_name", None) if not username or not password or not password2: return render_to_json_response({'error': 'insufficient data'}) if User.objects.filter(username=username).count() > 0: return render_to_json_response({'error': 'Username exists'}) if password != password2: return render_to_json_response({'error': 'Passwords do not match'}) u = User() u.username = username u.set_password(password) if email: u.email = email if first_name: u.first_name = first_name if last_name: u.last_name = last_name u.save() login(request, u) return render_to_json_response({'success': 'User logged in'})
def addAnnotations(request): ''' takes { item: itemId, layer: layerId, annotations: [{ in: float, out: float, value: string }, ...] } returns { taskId: string } ''' data = json.loads(request.POST['data']) for key in ('item', 'layer', 'annotations'): if key not in data: return render_to_json_response( json_response(status=400, text='invalid data')) item = get_object_or_404_json(Item, itemId=data['item']) layer_id = data['layer'] layer = filter(lambda l: l['id'] == layer_id, settings.CONFIG['layers'])[0] if item.editable(request.user) \ and layer['canAddAnnotations'].get(request.user.get_profile().get_level()): response = json_response() data['user'] = request.user.username t = add_annotations.delay(data) response['data']['taskId'] = t.task_id else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def add_relation(request): feature1 = request.GET.get("feature1", None) feature2 = request.GET.get("feature2", None) relation = request.GET.get("relation", None) if feature1 == None or feature2 == None or relation == None: return render_to_json_response({"error": "bad request"}) if not request.user.is_staff: return render_to_json_response( {"error": "insufficient permissions error. try logging in again? are you staff / admin?"} ) feature1 = get_object_or_404_json(Feature, pk=feature1) feature2 = get_object_or_404_json(Feature, pk=feature2) verb = rel_obj = None try: rel_obj = Relationship.objects.get(feature1=feature1, feature2=feature2) verb = "deleted" except ObjectDoesNotExist: rel_obj = Relationship(feature1=feature1, feature2=feature2, relationship_type=relation) verb = "created" if relation == "": if verb == "deleted": rel_obj.delete() if relation == "conflates": feature2.is_primary = True feature2.save() else: return render_to_json_response({"error": "relation is already deleted"}) else: rel_obj.save() if relation == "conflates": feature2.is_primary = False feature2.save() return render_to_json_response({"success": "relation %s successfully." % verb})
def upload(request): text = get_text_or_404_json(request.POST['id']) if text.editable(request.user): #post next chunk if 'chunk' in request.FILES: form = ChunkForm(request.POST, request.FILES) if form.is_valid() and text.editable(request.user): c = form.cleaned_data['chunk'] chunk_id = form.cleaned_data['chunkId'] response = { 'result': 1, 'resultUrl': request.build_absolute_uri(text.get_absolute_url()) } if not text.save_chunk(c, chunk_id, form.cleaned_data['done']): response['result'] = -1 if form.cleaned_data['done']: response['done'] = 1 return render_to_json_response(response) #init upload else: text.uploading = True if text.file: text.file.delete() text.save() return render_to_json_response({ 'uploadUrl': request.build_absolute_uri('/api/upload/text'), 'url': request.build_absolute_uri(text.get_absolute_url()), 'result': 1 }) else: response = json_response(status=404, text='permission denied') response = json_response(status=400, text='this request requires POST') return render_to_json_response(response)
def signin(request): username = request.POST.get("username", "") password = request.POST.get("password", "") user = authenticate(username=username, password=password) if user is not None: login(request, user) return render_to_json_response({'success': 'User logged in'}) return render_to_json_response({'error': 'Username / password do not match'})
def place_json(request, id): place = get_place_or_404(id) if request.method == 'GET': ''' Return GeoJSON for Place ''' geo_json = place.to_geojson() return render_to_json_response(geo_json) elif request.method == 'PUT': ''' Takes a GeoJSON string as PUT data and saves Place Saves and returns back GeoJSON for place. ''' #FIXME: check permissions # if not request.user.is_staff(): # return render_to_json_response({'error': 'You do not have permissions to edit this place.'}, status=403) geojson = json.loads(request.body) if geojson.has_key("comment"): comment = geojson.pop("comment") else: comment = '' json_obj = geojson.pop("properties") json_obj['geometry'] = geojson['geometry'] #handle getting centroid: if json_obj['geometry']: centroid = GEOSGeometry(json.dumps(json_obj['geometry'])).centroid json_obj['centroid'] = list(centroid.coords) else: json_obj['centroid'] = [] json_obj['geometry'] = {} #updates place but doesn't save it place.update(json_obj) user_id = request.user.id username = request.user.username metadata = { 'user': username, 'user_id': user_id, 'comment': comment } place.save(metadata=metadata) new_place = place.copy()#returns a copy of the newly saved place return render_to_json_response(new_place.to_geojson()) elif request.method == 'DELETE': return render_to_json_response({'error': 'Not implemented'}, status=501) else: return render_to_json_response({'error': 'Method Not Allowed'}, status=405)
def lenders(request): if request.method == 'GET': id = request.GET.get('id', None) if id: lenders = [Lender.objects.get(pk=id).get_json()] else: lenders = [l.get_json() for l in Lender.objects.all()] return render_to_json_response(lenders,status=200) return render_to_json_response([],status=501)
def direct_upload(request): if 'id' in request.GET: file = models.File.objects.get(oshash=request.GET['id']) else: oshash = request.POST['id'] response = json_response(status=400, text='this request requires POST') if 'chunk' in request.FILES: form = ChunkForm(request.POST, request.FILES) if form.is_valid() and file.editable(request.user): c = form.cleaned_data['chunk'] chunk_id = form.cleaned_data['chunkId'] response = { 'result': 1, 'resultUrl': request.build_absolute_uri(file.item.get_absolute_url()) } if not file.save_chunk(c, chunk_id, form.cleaned_data['done']): response['result'] = -1 if form.cleaned_data['done']: file.uploading = False file.queued = True file.save() #try/execpt so it does not fail if rabitmq is down try: t = file.extract_stream() response['resultUrl'] = t.task_id except: pass response['done'] = 1 return render_to_json_response(response) #init upload else: file, created = models.File.objects.get_or_create(oshash=oshash) if file.editable(request.user): #remove previous uploads if not created: file.streams.all().delete() file.delete_frames() if file.item.rendered and file.selected: Item.objects.filter(id=file.item.id).update(rendered=False) file.uploading = True file.save() upload_url = request.build_absolute_uri( '/api/upload/direct/?id=%s' % file.oshash) return render_to_json_response({ 'uploadUrl': upload_url, 'url': request.build_absolute_uri(file.item.get_absolute_url()), 'result': 1 }) else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def firefogg_upload(request): profile = request.GET['profile'] oshash = request.GET['id'] config = settings.CONFIG['video'] video_profile = "%sp.%s" % (max(config['resolutions']), config['formats'][0]) #handle video upload if request.method == 'POST': #post next chunk if 'chunk' in request.FILES and oshash: f = get_object_or_404(models.File, oshash=oshash) form = ChunkForm(request.POST, request.FILES) if form.is_valid() and profile == video_profile and f.editable(request.user): c = form.cleaned_data['chunk'] chunk_id = form.cleaned_data['chunkId'] response = { 'result': 1, 'resultUrl': request.build_absolute_uri('/%s'%f.item.itemId) } if not f.save_chunk_stream(c, chunk_id, form.cleaned_data['done']): response['result'] = -1 elif form.cleaned_data['done']: f.uploading = False f.queued = True f.save() #FIXME: this fails badly if rabbitmq goes down try: t = tasks.process_stream.delay(f.id) response['resultUrl'] = t.task_id except: pass response['result'] = 1 response['done'] = 1 return render_to_json_response(response) #init upload elif oshash and profile == video_profile: #404 if oshash is not know, files must be registered via update api first f = get_object_or_404(models.File, oshash=oshash) if f.editable(request.user): f.streams.all().delete() f.delete_frames() f.uploading = True f.save() if f.item.rendered and f.selected: Item.objects.filter(id=f.item.id).update(rendered=False) response = { 'uploadUrl': request.build_absolute_uri('/api/upload/?id=%s&profile=%s' % (f.oshash, profile)), 'url': request.build_absolute_uri('/%s' % f.item.itemId), 'result': 1 } return render_to_json_response(response) else: response = json_response(status=404, text='permission denied') response = json_response(status=400, text='this request requires POST') return render_to_json_response(response)
def place_json(request, id): place = get_place_or_404(id) if request.method == 'GET': ''' Return GeoJSON for Place ''' geo_json = place.to_geojson() return render_to_json_response(geo_json) elif request.method == 'PUT': ''' Takes a GeoJSON string as PUT data and saves Place Saves and returns back GeoJSON for place. ''' #FIXME: check permissions # if not request.user.is_staff(): # return render_to_json_response({'error': 'You do not have permissions to edit this place.'}, status=403) geojson = json.loads(request.body) if geojson.has_key("comment"): comment = geojson.pop("comment") else: comment = '' json_obj = geojson.pop("properties") json_obj['geometry'] = geojson['geometry'] #handle getting centroid: if json_obj['geometry']: centroid = GEOSGeometry(json.dumps(json_obj['geometry'])).centroid json_obj['centroid'] = list(centroid.coords) else: json_obj['centroid'] = [] json_obj['geometry'] = {} #updates place but doesn't save it place.update(json_obj) user_id = request.user.id username = request.user.username metadata = {'user': username, 'user_id': user_id, 'comment': comment} place.save(metadata=metadata) new_place = place.copy() #returns a copy of the newly saved place return render_to_json_response(new_place.to_geojson()) elif request.method == 'DELETE': return render_to_json_response({'error': 'Not implemented'}, status=501) else: return render_to_json_response({'error': 'Method Not Allowed'}, status=405)
def login_json(request): username = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(username=username, password=password) if user is not None: login(request, user) user_json = { 'id': user.id, 'username': user.username } return render_to_json_response({'success': 'User logged in', 'user': user_json}) return render_to_json_response({'error': 'Username / password do not match'})
def editUser(request): ''' takes { key: value } required key: id optional keys: username, email, level, notes returns { } ''' response = json_response() data = json.loads(request.POST['data']) user = get_object_or_404_json(User, pk=ox.fromAZ(data['id'])) profile = user.get_profile() if 'disabled' in data: user.is_active = not data['disabled'] if 'email' in data: if 'email' in data: data['email'] = ox.escape_html(data['email']) if User.objects.filter(email__iexact=data['email']).exclude( id=user.id).count() > 0: response = json_response(status=403, text='email already in use') return render_to_json_response(response) user.email = data['email'] if 'level' in data: profile.set_level(data['level']) if 'notes' in data: profile.notes = data['notes'] if 'newsletter' in data: profile.newsletter = data['newsletter'] if 'groups' in data: groups = data['groups'] if isinstance(groups, list): groups = filter(lambda g: g.strip(), groups) groups = [ox.escape_html(g) for g in groups] user.groups.exclude(name__in=groups).delete() current_groups = [g.name for g in user.groups.all()] for g in filter(lambda g: g not in current_groups, groups): group, created = Group.objects.get_or_create(name=g) user.groups.add(group) if 'username' in data: if User.objects.filter(username__iexact=data['username']).exclude( id=user.id).count() > 0: response = json_response(status=403, text='username already in use') return render_to_json_response(response) user.username = data['username'] user.save() profile.save() response['data'] = user.data.get().json() return render_to_json_response(response)
def login_json(request): username = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(username=username, password=password) if user is not None: login(request, user) user_json = {'id': user.id, 'username': user.username} return render_to_json_response({ 'success': 'User logged in', 'user': user_json }) return render_to_json_response( {'error': 'Username / password do not match'})
def hierarchy(request, id): try: place = Place.objects.get(id) except ElasticHttpNotFoundError: return render_to_json_response({'error': 'Place not found'}, status=404) if request.method == 'GET': #hierarchy_json = place.get_hierarchy() #return render_to_json_response(hierarchy_json) return render_to_json_response({'error': 'Not implemented'}, status=501) else: return render_to_json_response({'error': 'Method Not Allowed'}, status=405)
def messages_json(request): phone_no = request.GET.get("phone_no", None) #TODO: validate phone no if not phone_no: return render_to_json_response({'error': 'no phone number provided'}) messages = Message.objects.filter(connection__identity__endswith=phone_no) ret = [] for m in messages: ret.append({ 'text': m.text, 'direction': m.direction, 'datetime': m.date.isoformat() }) return render_to_json_response(ret)
def editUser(request): ''' takes { key: value } required key: id optional keys: username, email, level, notes returns { } ''' response = json_response() data = json.loads(request.POST['data']) user = get_object_or_404_json(User, pk=ox.fromAZ(data['id'])) profile = user.get_profile() if 'disabled' in data: user.is_active = not data['disabled'] if 'email' in data: if 'email' in data: data['email'] = ox.escape_html(data['email']) if User.objects.filter(email__iexact=data['email']).exclude(id=user.id).count()>0: response = json_response(status=403, text='email already in use') return render_to_json_response(response) user.email = data['email'] if 'level' in data: profile.set_level(data['level']) if 'notes' in data: profile.notes = data['notes'] if 'newsletter' in data: profile.newsletter = data['newsletter'] if 'groups' in data: groups = data['groups'] if isinstance(groups, list): groups = filter(lambda g: g.strip(), groups) groups = [ox.escape_html(g) for g in groups] user.groups.exclude(name__in=groups).delete() current_groups = [g.name for g in user.groups.all()] for g in filter(lambda g: g not in current_groups, groups): group, created = Group.objects.get_or_create(name=g) user.groups.add(group) if 'username' in data: if User.objects.filter( username__iexact=data['username']).exclude(id=user.id).count()>0: response = json_response(status=403, text='username already in use') return render_to_json_response(response) user.username = data['username'] user.save() profile.save() response['data'] = user.data.get().json() return render_to_json_response(response)
def upload(request): if 'id' in request.GET: file = models.Document.get(request.GET['id']) else: extension = request.POST['filename'].split('.') name = '.'.join(extension[:-1]) extension = extension[-1].lower() response = json_response(status=400, text='this request requires POST') if 'chunk' in request.FILES: form = ChunkForm(request.POST, request.FILES) if form.is_valid() and file.editable(request.user): c = form.cleaned_data['chunk'] chunk_id = form.cleaned_data['chunkId'] response = { 'result': 1, 'id': file.get_id(), 'resultUrl': request.build_absolute_uri(file.get_absolute_url()) } if not file.save_chunk(c, chunk_id, form.cleaned_data['done']): response['result'] = -1 if form.cleaned_data['done']: response['done'] = 1 return render_to_json_response(response) #init upload else: created = False num = 1 _name = name while not created: file, created = models.Document.objects.get_or_create( user=request.user, name=name, extension=extension) if not created: num += 1 name = _name + ' [%d]' % num file.name = name file.extension = extension file.uploading = True file.save() upload_url = request.build_absolute_uri('/api/upload/document?id=%s' % file.get_id()) return render_to_json_response({ 'uploadUrl': upload_url, 'url': request.build_absolute_uri(file.get_absolute_url()), 'result': 1 }) return render_to_json_response(response)
def stop(request, slug): srid = int(request.GET.get("srid", 4326)) if request.POST and request.POST.has_key('geojson'): if not request.user.is_staff: return render_to_json_response({'errors': 'No permission'}) if not slug: stop = Stop() #FIXME: should this return an error instead? else: stop = get_object_or_404_json(Stop, slug=slug) geojson = json.loads(request.POST['geojson']) return render_to_json_response(stop.from_geojson(geojson, srid)) else: stop = get_object_or_404_json(Stop, slug=slug) return render_to_json_response(stop.get_geojson(srid=srid)) #FIXME: please don't repeat this code, its retarded.
def direct_upload(request): if 'id' in request.GET: file = models.File.objects.get(oshash=request.GET['id']) else: oshash = request.POST['id'] response = json_response(status=400, text='this request requires POST') if 'chunk' in request.FILES: form = ChunkForm(request.POST, request.FILES) if form.is_valid() and file.editable(request.user): c = form.cleaned_data['chunk'] chunk_id = form.cleaned_data['chunkId'] response = { 'result': 1, 'resultUrl': request.build_absolute_uri(file.item.get_absolute_url()) } if not file.save_chunk(c, chunk_id, form.cleaned_data['done']): response['result'] = -1 if form.cleaned_data['done']: file.uploading = False file.queued = True file.save() #try/execpt so it does not fail if rabitmq is down try: t = tasks.extract_stream.delay(file.id) response['resultUrl'] = t.task_id except: pass response['done'] = 1 return render_to_json_response(response) #init upload else: file, created = models.File.objects.get_or_create(oshash=oshash) if file.editable(request.user): #remove previous uploads if not created: file.streams.all().delete() file.delete_frames() if file.item.rendered and file.selected: Item.objects.filter(id=file.item.id).update(rendered=False) file.uploading = True file.save() upload_url = request.build_absolute_uri('/api/upload/direct/?id=%s' % file.oshash) return render_to_json_response({ 'uploadUrl': upload_url, 'url': request.build_absolute_uri(file.item.get_absolute_url()), 'result': 1 }) else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def search_json(request): search_term = request.GET.get("q", "") threshold = request.GET.get("threshold", "0.5") bbox = request.GET.get("bbox", False) page = int(request.GET.get("page", "1")) count = int(request.GET.get("count", "100")) country = request.GET.get("cc", "US") # right now, unused adm1 = request.GET.get("adm1", "") adm2 = request.GET.get("adm2", "") srid = int(request.GET.get("srid", 4326)) if threshold: try: threshold = max(float(threshold), 0.1) except ValueError: return render_to_json_response({"error": "threshold must be a float"}) if bbox: try: bbox = map(float, bbox.split(",")) except ValueError: bbox = None return render_to_json_response({"error": "bbox must be in the form: minx,miny,maxx,maxy"}) if not bbox and not search_term: return render_to_json_response({"error": "must supply either a valid `bbox` or a `search` parameter"}) features_qset = Feature.search.find( bbox=bbox, text=search_term, threshold=threshold, adm1=adm1, adm2=adm2, srid=srid ) total_results = features_qset.count() paginator = Paginator(features_qset, count) num_pages = paginator.num_pages try: results = paginator.page(page) except (EmptyPage, InvalidPage): results = paginator.page(paginator.num_pages) features = [f.get_geojson(srid) for f in results.object_list] d = { "type": "FeatureCollection", "results": total_results, "current_page": page, "pages": num_pages, "features": features, } return render_to_json_response(d)
def route_headway(request, code): """ Given a route code, gets the current frequency of the buses at the current time. """ return render_to_json_response("hello") route = get_object_or_404(Route, code=code) import datetime.datetime current_time = datetime.datetime.now day = current_time.isoweekday scheds = [] for rs in RouteSchedule.objects.filter(unique_route__route=route): if day in SCHED[rs.schedule_type]: scheds.append(rs) return render_to_json_response("hello")
def within(request, id): ''' GET Gets places where the centroids are within this place's geometry Results are unsorted also accept per_page: results per page int, default=100 page: page no (starting with 1) int, default=1 Returns: GeoJSON feed of search results Extra properties of feed: total: total number of results max_score: max score in results (?) page: page number ''' place = get_place_or_404(id) per_page = int(request.GET.get("per_page", 100)) page = int(request.GET.get("page", 1)) page_0 = page - 1 result = Place.objects.within(place, per_page=per_page, page=page_0) total = result['total'] pages = int(math.ceil(total / (per_page + .0))) #get total number of pages ret = { 'type': 'FeatureCollection', 'features': [p.to_geojson() for p in result['places']], 'total': total, 'page': result['page'], 'pages': pages, 'per_page': result['per_page'], 'max_score': result['max_score'] } return render_to_json_response(ret)
def editDocument(request): ''' takes { id: string name: string description: string item(optional): edit descriptoin per item } returns { id: ... } ''' response = json_response() data = json.loads(request.POST['data']) item = 'item' in data and Item.objects.get(itemId=data['item']) or None if data['id']: document = models.Document.get(data['id']) if document.editable(request.user): document.edit(data, request.user, item=item) document.save() response['data'] = document.json(user=request.user, item=item) else: response = json_response(status=403, text='permission denied') else: response = json_response(status=500, text='invalid request') return render_to_json_response(response)
def addDocument(request): ''' add document(s) to item takes { item: string id: string or ids: [string] } returns { } ''' response = json_response() data = json.loads(request.POST['data']) if 'ids' in data: ids = data['ids'] else: ids = [data['id']] item = Item.objects.get(itemId=data['item']) if item.editable(request.user): for id in ids: document = models.Document.get(id) document.add(item) else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def add(request): ''' takes { title: string, //(optional) } returns { id: name: ... } ''' if not request.user.get_profile().capability('canAddItems'): response = json_response(status=403, text='permissino denied') else: data = json.loads(request.POST['data']) data['title'] = data.get('title', 'Untitled') i = models.Item() i.data['title'] = data['title'] i.user = request.user p = i.save() if p: p.wait() else: i.make_poster(True) response = json_response(status=200, text='created') response['data'] = i.get_json() return render_to_json_response(response)
def getMediaInfo(request): ''' takes { id: oshash of stream file } returns { item: itemId, file: oshash of source file } ''' data = json.loads(request.POST['data']) f = None qs = models.Stream.objects.filter(oshash=data['id']) if qs.count() > 0: s = qs[0] f = s.file else: qs = models.File.objects.filter(oshash=data['id']) if qs.count() > 0: f = qs[0] response = json_response() if f: response['data'] = { 'file': f.oshash, 'item': f.item.itemId } return render_to_json_response(response)
def lookup(request): ''' takes { title: string, director: [string], year: string, id: string } returns { title: string, director: [string], year: string, id: string } ''' data = json.loads(request.POST['data']) if 'id' in data: i = models.Item.objects.get(itemId=data['id']) r = {'id': i.itemId} for key in ('title', 'director', 'year'): r[key] = i.get(key) response = json_response(r) else: response = json_response(status=404, text='not found') return render_to_json_response(response)
def log(request): ''' takes { url: string, line: string, text: string } returns { } ''' data = json.loads(request.POST['data']) if request.user.is_authenticated(): user = request.user else: user = None url = data.get('url', '').split('/static/')[-1] if 'text' in data: if len(url) > 1000: url = url[:997] + '...' l = models.Log( text=data['text'], line=int(data.get('line', 0)), url=url ) if user: l.user = user l.save() response = json_response() return render_to_json_response(response)
def get_month_attendance(request): id = int(request.GET.get('id', 0)) month = int(request.GET.get('month', 1)) year = int(request.GET.get('year', 2013)) attendee = MyUser.objects.get(id=id) data = attendee.get_month_attendance(month, year) return render_to_json_response(data)
def setPoster(request): ''' takes { id: string, source: string // url } returns { poster: { url: string, width: int, height: int } } ''' data = json.loads(request.POST['data']) item = get_object_or_404_json(models.Item, itemId=data['id']) response = json_response() if item.editable(request.user): valid_sources = [p['source'] for p in item.get_posters()] if data['source'] in valid_sources: item.poster_source = data['source'] if item.poster: item.poster.delete() item.save() tasks.update_poster(item.itemId) response = json_response() response['data'][ 'posterAspect'] = item.poster_width / item.poster_height else: response = json_response(status=403, text='invalid poster url') else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def remove(request): ''' remove item with id, return status is 200/removed on sucess or 403/permission deinied. takes { id: string } returns { } ''' response = json_response({}) data = json.loads(request.POST['data']) item = get_object_or_404_json(models.Item, itemId=data['id']) user = request.user if user.get_profile().capability('canRemoveItems') == True or \ user.is_staff or \ item.user == user or \ item.groups.filter(id__in=user.groups.all()).count() > 0: item.log() #FIXME: is this cascading enough or do we end up with orphan files etc. item.delete() response = json_response(status=200, text='removed') else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def setPoster(request): ''' takes { id: string, source: string // url } returns { poster: { url: string, width: int, height: int } } ''' data = json.loads(request.POST['data']) item = get_object_or_404_json(models.Item, itemId=data['id']) response = json_response() if item.editable(request.user): valid_sources = [p['source'] for p in item.get_posters()] if data['source'] in valid_sources: item.poster_source = data['source'] if item.poster: item.poster.delete() item.save() tasks.update_poster(item.itemId) response = json_response() response['data']['posterAspect'] = item.poster_width/item.poster_height else: response = json_response(status=403, text='invalid poster url') else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def routes(request): q = request.GET.get("q", "") in_regex = re.compile(r'(\d{1,3})') # used to extract the route number string out of the query string - for eg, gets "21" from "21Ltd" match = re.findall(in_regex, q) if match: route_no = match[0] else: route_no = '' #ret = [] if route_no != '': code3 = route_no.zfill(3) # import pdb # pdb.set_trace() #out_regex = re.compile(r'.*(\D|\A)%s(\D|\Z).*' % route_no) # used for, for eg. to filter out '210Ltd' when user searches for '21'. Checks for non-digit or start of string, followed by route_no, followed by non-digit or end of string qset = Route.objects.filter(code3=code3) # for route in qset: # if re.match(out_regex, route.alias): # ret.append(route.alias) else: qset = Route.objects.all() # for route in qset: # ret.append(route.alias) # routes = [route.alias for route in qset] ret = [route.get_dict() for route in qset] return render_to_json_response(ret)
def editAnnotation(request): ''' takes { id:, in: float, out: float, value: string, } returns { id: ... } ''' response = json_response({}) data = json.loads(request.POST['data']) a = get_object_or_404_json(models.Annotation, public_id=data['id']) if a.editable(request.user): a.log() for key in ('value', 'in', 'out'): if key in data: setattr(a, { 'in': 'start', 'out': 'end' }.get(key, key), data[key]) a.save() #update sort/find tables async update_item.delay(a.id) response['data'] = a.json() response['data']['editable'] = True else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def getSequence(request): ''' takes { id mode position } returns { id mode in out } ''' data = json.loads(request.POST['data']) response = json_response() position = float('%0.03f' % data['position']) i = Item.objects.get(itemId=data['id']) qs = models.Sequence.objects.filter( sort_id=i.sort.pk, mode=models.Sequence.MODE[data['mode']], start__lte=position, end__gt=position ).order_by('start', 'end') for sequence in qs: response['data'] = sequence.json() break return render_to_json_response(response)
def getIds(request): ''' takes { title: string, director: [string], year: int } returns { items: [{ tite: string, director: [string], year: int, originalTitle: string }] } ''' data = json.loads(request.POST['data']) response = json_response({}) if settings.DATA_SERVICE: r = models.external_data('getIds', data) if r['status']['code'] == 200: response['data']['items'] = r['data']['items'] else: response['data']['items'] return render_to_json_response(response)
def editAnnotation(request): ''' takes { id:, in: float, out: float, value: string, } returns { id: ... } ''' response = json_response({}) data = json.loads(request.POST['data']) a = get_object_or_404_json(models.Annotation, public_id=data['id']) if a.editable(request.user): a.log() for key in ('value', 'in', 'out'): if key in data: setattr(a, { 'in': 'start', 'out': 'end' }.get(key,key), data[key]) a.save() #update sort/find tables async update_item.delay(a.id) response['data'] = a.json() response['data']['editable'] = True else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def search_related_json(request, id): # id = request.GET.get("id", "0") id = str(id) feature = get_object_or_404_json(Feature, pk=id) similar_features = feature.similar_features() d = [] for s in similar_features: time_frame = relates_to = related_by = "" if s.time_frame is not None: time_frame = s.time_frame.description if s.relationship_type is not None: if s.feature2_id == s.id: relates_to = s.relationship_type elif s.feature1_id == s.id: related_by = s.relationship_type d.append({ 'id': s.id, 'feature_type': s.feature_type.name, #FeatureType.objects.get(pk=s.feature_type_id).name, 'preferred_name': s.preferred_name, 'similarity': s.similarity, 'distance': s.distance, 'time_frame': time_frame, 'is_primary': s.is_primary, 'relates_to': relates_to, 'related_by': related_by }) return render_to_json_response(d)
def editClip(request): ''' takes { id: string, in: float, out: float } returns { } ''' response = json_response() data = json.loads(request.POST['data']) clip = get_object_or_404_json(models.Clip, pk=ox.fromAZ(data['id'])) valid = True if clip.edit.editable(request.user): for key in ('in', 'out'): if key in data: if clip.annotation: clip.start = clip.annotation.start clip.end = clip.annotation.end clip.item = clip.annotation.item clip.annotation = None setattr(clip, {'in': 'start', 'out': 'end'}.get(key), float(data[key])) if not clip.annotation: duration = clip.item.sort.duration if clip.start >= clip.end or clip.start >= duration or clip.end > duration: response = json_response(status=500, text='invalid in/out') valid = False if valid: clip.save() response['data'] = clip.json(user=request.user) else: response = json_response(status=403, text='permission denied') return render_to_json_response(response)
def search_layers(request): ''' Used for find raster Tile / WMS Layers that match a date range and/or a bounding box: returns list of matching layers accepts GET param 'start_date' YYYY (optional) (if not given, defaults to 100 AD) GET param 'end_date' YYYY (optional)(if not given, defaults to 3000 AD) GET param 'bbox' if not given, defaults to globe) returns json ''' from django.contrib.gis.geos import Polygon start_date = request.GET.get("start_date", "") end_date = request.GET.get("end_date", "") if not start_date: start_date = "0100" if not end_date: end_date = "3000" start = datetime.datetime.strptime(start_date, "%Y") end = datetime.datetime.strptime(end_date, "%Y") bbox_string = request.GET.get("bbox", "-180,-90,180,90") bbox = [float(b) for b in bbox_string.split(",")] query_geom = Polygon.from_bbox(tuple(bbox)) results = Layer.objects.filter(date__lte=end).filter(date__gte=start).filter(bbox__intersects=query_geom).order_by("date","name")[:25] items = [obj.to_json() for obj in results] return render_to_json_response({ 'items': items })
def findId(request): ''' takes { 'id': string 'title': string 'director': [string] 'year': int } ''' data = json.loads(request.POST['data']) response = json_response({}) response['data']['items'] = [] if 'id' in data: qs = models.Item.objects.filter(itemId=data['id']) if qs.count() == 1: response['data']['items'] = [ i.get_json(['title', 'director', 'year', 'id']) for i in qs ] if not response['data']['items'] \ and settings.USE_IMDB \ and settings.DATA_SERVICE: r = models.external_data('getId', data) if r['status']['code'] == 200: response['data']['items'] = [r['data']] return render_to_json_response(response)
def addDocument(request): ''' add document(s) to item takes { item: string id: string or ids: [string] } returns { } ''' response = json_response() data = json.loads(request.POST['data']) if 'ids' in data: ids = data['ids'] else: ids = [data['id']] item = Item.objects.get(itemId=data['item']) if item.editable(request.user): for id in ids: document = models.Document.get(id) document.add(item) else: response = json_response(status=403, file='permission denied') return render_to_json_response(response)
def getMetadata(request): ''' takes { id: string, keys: [string] } returns { key: value .. } ''' data = json.loads(request.POST['data']) response = json_response({}) if settings.DATA_SERVICE: ''' info = {} for c in data['query']['conditions']: info[c['key']] = c['value'] r = models.external_data('getId', info) ''' r = models.external_data('getData', {'id': data['id']}) if r['status']['code'] == 200: if 'keys' in data and data['keys']: for key in data['keys']: if key in r['data']: response['data'][key] = r['data'][key] else: response['data'] = r['data'] return render_to_json_response(response)