def check_fbid(request): if 'fbid' not in request.POST: return HttpResponseBadRequest() fbid = request.POST['fbid'] if not fbid: return json_response({'exists' : 0}) try: u = User.objects.get(facebook_id = fbid, is_active=True) return json_response({'exists' : 1}) except: pass return json_response({'exists' : 0})
def check_fbid(request): if 'fbid' not in request.POST: return HttpResponseBadRequest() fbid = request.POST['fbid'] if not fbid: return json_response({'exists': 0}) try: u = User.objects.get(facebook_id=fbid, is_active=True) return json_response({'exists': 1}) except: pass return json_response({'exists': 0})
def ajax_search(request): search_results = [] query = request.GET.get('q', None) selected_facet = request.GET.get('type', None) try: limit = int(request.GET.get('limit', DEFAULT_LIMIT)) except ValueError: limit = DEFAULT_LIMIT try: offset = int(request.GET.get('offset', 0)) except ValueError: offset = 0 search_results = Autocomplete.search(query, restrict_type=selected_facet, limit=limit, offset=offset, restrict_location = request.GET.get('location', None)) lat, lon = request.GET.get('lat', None), request.GET.get('lng', None) orgs_near_me = _get_orgs_near_me(request, query, lat, lon) more_results = (search_results.hits - int(offset)) > limit related_searches = _get_related_searches(query) if 'format' in request.GET and request.GET['format']=='html': ret = {'items': render_string(request, 'search/search_items.html', {'search_results' : search_results, 'query': query}), 'facets': render_string(request, 'search/facets.html', {'search_results': search_results, 'selected_facet': selected_facet, 'query': query}), 'related': render_string(request, 'search/related_searches.html', {'related_searches': related_searches}), 'more_results': render_string(request, 'search/more_results.html', {'more_results': more_results}) } if orgs_near_me: ret['nearMe'] = render_string(request, 'search/near_me.html', {'orgs_near_me': orgs_near_me}) return json_response(ret)
def related_searches(request): q = request.GET.get('q') if not q: return [] else: resp = classifier.classify(q) return json_response(resp)
def fbot_update(request): if 'ot' not in request.POST: return HttpResponseBadRequest() request.user.fb_access_token = request.POST['ot'] request.user.save() cache.bust_on_handle(request.user, request.user.username) return json_response({})
def org_create(request): o = Org() o.name = request.POST['name'].encode('utf-8') o.handle = create_handle(request.POST['name']) o.vision_statement = request.POST['vision_statement'].encode('utf-8') if request.POST['social_mission'] == 'yes': o.social_mission = True else: o.social_mission = False if request.POST['profit'] == 'yes': o.profit_seeking = True else: o.profit_seeking = False o.save() if request.POST['admin'] == 'yes': o.admins.add(request.user) o.save() f, created = UserToOrgFollow.objects.get_or_create(user=request.user, org=o) f.following = True f.save() request.user.refresh_orgs_following() return json_response(json_encode(o))
def normalize_facebook_id(request): facebook_id = request.POST['fbid'] if facebook_id: try: facebook_id = facebook_id_magic(facebook_id) except: return json_error(123, 'Sorry, your Facebook ID is invalid') return json_response({"facebook_id": facebook_id })
def normalize_facebook_id(request): facebook_id = request.POST['fbid'] if facebook_id: try: facebook_id = facebook_id_magic(facebook_id) except: return json_error(123, 'Sorry, your Facebook ID is invalid') return json_response({"facebook_id": facebook_id})
def fetch_org_by_centroid(request): try: lat = float(request.POST.get('lat')) lon = float(request.POST.get('lon')) limit = float(request.POST.get('limit', 20)) except AttributeError: json_error(INVALID_CENTROID_ERROR) orgs = Org.objects.filter(location__latitude__range = (lat - limit, lat + limit)).filter(location__longitude__range = (lon - limit, lon + limit))[0:limit] return json_response(json_encode(orgs))
def delete(request, commitment_id): commitment = get_object_or_404(Commitment, user=request.user, id=commitment_id) commitment.delete() response = redirect(commitment.entity) if request.is_ajax(): button = render_inclusiontag(request, "commitment_button entity", "commitment_tags", {'entity': commitment.entity}) response = json_response({'button': button}) return response
def action_list(request, entity_id, model_name): model = get_model(*model_name.split('.')) entity = model.objects.get(id=entity_id) actions = entity.actions.all() html = render_string(request, 'action/includes/action_list.html', { 'entity': entity, 'actions': actions, }) return json_response({'html': html})
def ajax_search(request): search_results = [] query = request.GET.get('q', None) selected_facet = request.GET.get('type', None) try: limit = int(request.GET.get('limit', DEFAULT_LIMIT)) except ValueError: limit = DEFAULT_LIMIT try: offset = int(request.GET.get('offset', 0)) except ValueError: offset = 0 search_results = Autocomplete.search(query, restrict_type=selected_facet, limit=limit, offset=offset, restrict_location=request.GET.get( 'location', None)) lat, lon = request.GET.get('lat', None), request.GET.get('lng', None) orgs_near_me = _get_orgs_near_me(request, query, lat, lon) more_results = (search_results.hits - int(offset)) > limit related_searches = _get_related_searches(query) if 'format' in request.GET and request.GET['format'] == 'html': ret = { 'items': render_string(request, 'search/search_items.html', { 'search_results': search_results, 'query': query }), 'facets': render_string( request, 'search/facets.html', { 'search_results': search_results, 'selected_facet': selected_facet, 'query': query }), 'related': render_string(request, 'search/related_searches.html', {'related_searches': related_searches}), 'more_results': render_string(request, 'search/more_results.html', {'more_results': more_results}) } if orgs_near_me: ret['nearMe'] = render_string(request, 'search/near_me.html', {'orgs_near_me': orgs_near_me}) return json_response(ret)
def fb_login(request): if 'id' not in request.POST or 'ot' not in request.POST: return HttpResponseBadRequest() user = User.objects.get(facebook_id=request.POST['id'], is_active=True) if user.fb_access_token != request.POST['ot']: user.fb_access_token = request.POST['ot'] user.save() cache.put_on_handle(user, user.username) #perform for all that login magic that happens under the covers login(request, user) response = {'user_id': user.id, 'fb_access_token': user.fb_access_token} return set_auth_cookies(json_response({'result': response}), user)
def fetch_org_by_centroid(request): try: lat = float(request.POST.get('lat')) lon = float(request.POST.get('lon')) limit = float(request.POST.get('limit', 20)) except AttributeError: json_error(INVALID_CENTROID_ERROR) orgs = Org.objects.filter( location__latitude__range=(lat - limit, lat + limit)).filter( location__longitude__range=(lon - limit, lon + limit))[0:limit] return json_response(json_encode(orgs))
def fb_login(request): if 'id' not in request.POST or 'ot' not in request.POST: return HttpResponseBadRequest() user = User.objects.get(facebook_id = request.POST['id'], is_active=True) if user.fb_access_token != request.POST['ot']: user.fb_access_token = request.POST['ot'] user.save() cache.put_on_handle(user, user.username) #perform for all that login magic that happens under the covers login(request, user) response = {'user_id':user.id, 'fb_access_token':user.fb_access_token} return set_auth_cookies(json_response({'result' : response}), user)
def autocomplete(request): """Legacy autocomplete, still used in the top search bar around the site""" def _format_search_result(res, idx): type, id = res.id.split(':') image_url = res.image_url if image_url and not image_url.startswith('http'): image_url=_create_static_url(image_url) return {'id' : id, 'index': idx, 'name' : res.name[0], 'type' : type, 'url' : res.url, 'image_url' : image_url, 'num_followers' : res.popularity} results = Autocomplete.search(request.GET['search']) return json_response([_format_search_result(t, idx) for idx, t in enumerate(results)])
def following_list(request, user_id): start = int(request.GET.get('start', 0)) end = int(request.GET.get('end', 20)) user = get_object_or_404(User, id=user_id) followings = user.get_active_followings()[start:end] html = render_string(request, "user/includes/user_list.html", { 'users': followings, 'start_index': start, 'list_type': 'followings', }) return json_response({ 'html': html, 'has_more': end < user.get_num_users_following, })
def follow(request, user_id): followed = get_object_or_404(User, pk=user_id) follow_instance, created = UserToUserFollow.objects.get_or_create(follower=request.user, followed=followed) if not follow_instance.is_following: follow_instance.is_following = True follow_instance.save() if created: send_notification(type=EmailTypes.FOLLOW, user=followed, entity=request.user) cache.bust(followed) if request.is_ajax(): button = render_inclusiontag(request, "follow_button followed", "users_tags", {'followed': followed}) return json_response({'button': button}) else: return redirect(followed)
def list(request, entity_id, model_name): start = int(request.GET.get('start', 0)) end = int(request.GET.get('end', 20)) model = get_model(*model_name.split('.')) entity = get_object_or_404(model, id=entity_id) commitments = entity.commitments.active()[start:end].select_related() html = render_string(request, "commitment/includes/committer_list.html", { 'commitments': commitments, 'start_index': start, }) return json_response({ 'html': html, 'has_more': end < entity.commitments.count(), })
def unfollow(request, user_id): followed = get_object_or_404(User, pk=user_id) try: follow_instance = UserToUserFollow.objects.get(follower=request.user, followed=followed) follow_instance.is_following = False follow_instance.stopped_following = datetime.datetime.now() follow_instance.save() except UserToUserFollow.DoesNotExist: pass cache.bust(followed) if request.is_ajax(): button = render_inclusiontag(request, "follow_button followed", "users_tags", {'followed': followed}) return json_response({'button': button}) else: return redirect(followed)
def forgot_password(request): email = request.POST['email'].strip() try: u = User.objects.get(email = email, is_active=True) except: return json_error(INVALID_EMAIL_ERROR, 'No user at that email address.') pr = PasswordResetRequest() pr.user = u pr.uid = str(uuid4().hex) pr.save() p = PasswordResetRequest.objects.all() send_notification(type=EmailTypes.RESET_PASSWORD, user=u, entity=u, password_reset_id=pr.uid) return json_response({'response' : 1})
def forgot_password(request): email = request.POST['email'].strip() try: u = User.objects.get(email=email, is_active=True) except: return json_error(INVALID_EMAIL_ERROR, 'No user at that email address.') pr = PasswordResetRequest() pr.user = u pr.uid = str(uuid4().hex) pr.save() p = PasswordResetRequest.objects.all() send_notification(type=EmailTypes.RESET_PASSWORD, user=u, entity=u, password_reset_id=pr.uid) return json_response({'response': 1})
def followed_issue_list(request, user_id): start = int(request.GET.get('start', 0)) end = int(request.GET.get('end', 20)) user = get_object_or_404(User, id=user_id) issue_commitments = user.commitments.with_issues()[start:end].fetch_generic_relations() issues = [commitment.entity for commitment in issue_commitments] num_issues = user.commitments.with_issues().count() html = render_string(request, "issue/includes/followed_issue_list.html", { 'issues': issues, 'start_index': start, }) return json_response({ 'html': html, 'has_more': end < num_issues, })
def followed_issue_list(request, user_id): start = int(request.GET.get('start', 0)) end = int(request.GET.get('end', 20)) user = get_object_or_404(User, id=user_id) issue_commitments = user.commitments.with_issues( )[start:end].fetch_generic_relations() issues = [commitment.entity for commitment in issue_commitments] num_issues = user.commitments.with_issues().count() html = render_string(request, "issue/includes/followed_issue_list.html", { 'issues': issues, 'start_index': start, }) return json_response({ 'html': html, 'has_more': end < num_issues, })
def follow(request, user_id): followed = get_object_or_404(User, pk=user_id) follow_instance, created = UserToUserFollow.objects.get_or_create( follower=request.user, followed=followed) if not follow_instance.is_following: follow_instance.is_following = True follow_instance.save() if created: send_notification(type=EmailTypes.FOLLOW, user=followed, entity=request.user) cache.bust(followed) if request.is_ajax(): button = render_inclusiontag(request, "follow_button followed", "users_tags", {'followed': followed}) return json_response({'button': button}) else: return redirect(followed)
def autocomplete(request): """Legacy autocomplete, still used in the top search bar around the site""" def _format_search_result(res, idx): type, id = res.id.split(':') image_url = res.image_url if image_url and not image_url.startswith('http'): image_url = _create_static_url(image_url) return { 'id': id, 'index': idx, 'name': res.name[0], 'type': type, 'url': res.url, 'image_url': image_url, 'num_followers': res.popularity } results = Autocomplete.search(request.GET['search']) return json_response( [_format_search_result(t, idx) for idx, t in enumerate(results)])
def create(request): entity_id = request.POST['object_id'] entity_type = request.POST['content_type'] content_type = ContentType.objects.get(id=entity_type) entity = content_type.get_object_for_this_type(id=entity_id) commitment = Commitment(entity=entity, user=request.user) response = redirect(entity) try: commitment.full_clean() commitment.save() if request.is_ajax(): button = render_inclusiontag(request, "commitment_button entity", "commitment_tags", {'entity': entity}) actions = render_string(request, "action/includes/action_list.html", { 'entity': entity, 'actions': entity.actions.all(), }) response = json_response({'button': button, 'actions': actions}) except ValidationError: if request.is_ajax(): response = json_error(400, "You have already committed to this issue/org.") return response
def org_create(request): o = Org() o.name = request.POST['name'].encode('utf-8') o.handle = create_handle(request.POST['name']) o.vision_statement = request.POST['vision_statement'].encode('utf-8') if request.POST['social_mission'] == 'yes': o.social_mission = True else: o.social_mission = False if request.POST['profit'] == 'yes': o.profit_seeking = True else: o.profit_seeking = False o.save() if request.POST['admin'] == 'yes': o.admins.add(request.user) o.save() f, created = UserToOrgFollow.objects.get_or_create(user = request.user, org = o) f.following = True f.save() request.user.refresh_orgs_following() return json_response(json_encode(o))
request.user.refresh_users_following() ent.refresh_followers() if created: #FeedStream.post_new_follow(request.user, ent) send_notification(type=EmailTypes.FOLLOW, user=ent, entity=request.user) except Exception, inst: log(inst) if not ent: continue else: cache.bust(ent) return json_response({'result' : 1}) @AccountRequired @PostOnly def remove_user(request): request.user.is_active = False request.user.save() cache.bust_on_handle(request.user, request.user.username) logout(request) return unset_auth_cookies(json_response({'result':1})) @PostOnly def forgot_password(request): email = request.POST['email'].strip() try: u = User.objects.get(email = email, is_active=True)
acc_header = acc.header acc_description = acc.description delete = True for new_acc in org["accomplishments"]: if new_acc["year"] == acc_header and new_acc[ "text"] == acc_description: delete = False if delete: acc.delete() original.save() try: cache.bust_on_handle(original, original.handle) except: pass return json_response({'result': original.handle}) @PostOnly def remove_org(request): try: id = getattr(request.POST, 'id') org = Org.objects.get(id=id) except AttributeError, ObjectDoesNotExist: return json_error(INVALID_ORG_ID_ERROR) # TODO: so, uh, we need to figure out if the current user is authorized to do this? org.delete() cache.bust_on_handle(org, org.handle, False) return json_response({'result': 1})
def remove_user(request): request.user.is_active = False request.user.save() cache.bust_on_handle(request.user, request.user.username) logout(request) return unset_auth_cookies(json_response({'result':1}))
def update_user(request): if 'user' not in request.POST: return HttpResponseBadRequest() user = json.loads(request.POST['user']) if 'location' in user and user['location']: loc = user['location'] raw_geodata = json.dumps(loc["raw_geodata"]) if isinstance(loc.get("raw_geodata"), dict) else loc.get("raw_geodata") #Until we fix duplicate locations we have to do the following...lame. _locs = Location.objects.filter(raw_geodata = raw_geodata, longitude = loc.get('longitude', None), latitude = loc.get('latitude', None), address = loc.get('address', ' '), region = loc.get('region', ' '), locality = loc.get('locality', ' '), postal_code = loc.get('postal_code', ' '), country_name = loc.get('country_name', ' ')) if len(_locs) > 0: _loc = _locs[0] else: _loc = Location(raw_geodata = raw_geodata, longitude = loc.get('longitude', None), latitude = loc.get('latitude', None), address = loc.get('address', ' '), region = loc.get('region', ' '), locality = loc.get('locality', ' '), postal_code = loc.get('postal_code', ' '), country_name = loc.get('country_name', ' '),) _loc.save() request.user.location = _loc else: request.user.location = None str_fields = [ 'first_name', 'last_name', 'email', 'gender', 'bio', 'url', 'twitter_id', 'flickr_id', 'youtube_id', 'vimeo_id', 'blog_url', ] settings_fields = [ 'enable_jumo_updates', 'email_stream_frequency', 'post_to_fb', ] int_fields = [ 'birth_year', ] if 'enable_followed_notification' in user: try: sub = request.user.subscriptions.get(id=NOTIFICATIONS_PUB) except Subscription.DoesNotExist: sub = Subscription.get_or_create(user=request.user, pub_id=NOTIFICATIONS_PUB) if sub.subscribed <> user['enable_follow_notification']: sub.subscribed = user['enable_follow_notification'] sub.save() for f in str_fields: if f in user and user[f] != getattr(request.user, f): setattr(request.user, f, user[f]) for f in settings_fields: settings = user['settings'] if f in settings: setattr(request.user, f, settings[f]) for f in int_fields: if f in user and user[f] != getattr(request.user, f): if user[f] == '': user[f] = None setattr(request.user, f, user[f]) if 'password' in user and user['password'] != '': request.user.password = hash_password(user['password']) if 'username' in user and user['username'] != request.user.username: _username = request.user.username request.user.username = create_handle(user['username']) cache.bust_on_handle(request.user, _username, False) request.user.save() cache.bust_on_handle(request.user, request.user.username) return json_response({'result' : request.user.username})
def ajax_term_complete(request): """Term prefix autocomplete, Google-style, completes the phrase""" results = {} term = request.GET.get('q', None) results = Autocomplete.autocomplete(term) return json_response(results)
request.user.refresh_users_following() ent.refresh_followers() if created: #FeedStream.post_new_follow(request.user, ent) send_notification(type=EmailTypes.FOLLOW, user=ent, entity=request.user) except Exception, inst: log(inst) if not ent: continue else: cache.bust(ent) return json_response({'result': 1}) @AccountRequired @PostOnly def remove_user(request): request.user.is_active = False request.user.save() cache.bust_on_handle(request.user, request.user.username) logout(request) return unset_auth_cookies(json_response({'result': 1})) @PostOnly def forgot_password(request): email = request.POST['email'].strip()
def remove_user(request): request.user.is_active = False request.user.save() cache.bust_on_handle(request.user, request.user.username) logout(request) return unset_auth_cookies(json_response({'result': 1}))
def update_user(request): if 'user' not in request.POST: return HttpResponseBadRequest() user = json.loads(request.POST['user']) if 'location' in user and user['location']: loc = user['location'] raw_geodata = json.dumps(loc["raw_geodata"]) if isinstance( loc.get("raw_geodata"), dict) else loc.get("raw_geodata") #Until we fix duplicate locations we have to do the following...lame. _locs = Location.objects.filter( raw_geodata=raw_geodata, longitude=loc.get('longitude', None), latitude=loc.get('latitude', None), address=loc.get('address', ' '), region=loc.get('region', ' '), locality=loc.get('locality', ' '), postal_code=loc.get('postal_code', ' '), country_name=loc.get('country_name', ' ')) if len(_locs) > 0: _loc = _locs[0] else: _loc = Location( raw_geodata=raw_geodata, longitude=loc.get('longitude', None), latitude=loc.get('latitude', None), address=loc.get('address', ' '), region=loc.get('region', ' '), locality=loc.get('locality', ' '), postal_code=loc.get('postal_code', ' '), country_name=loc.get('country_name', ' '), ) _loc.save() request.user.location = _loc else: request.user.location = None str_fields = [ 'first_name', 'last_name', 'email', 'gender', 'bio', 'url', 'twitter_id', 'flickr_id', 'youtube_id', 'vimeo_id', 'blog_url', ] settings_fields = [ 'enable_jumo_updates', 'email_stream_frequency', 'post_to_fb', ] int_fields = [ 'birth_year', ] if 'enable_followed_notification' in user: try: sub = request.user.subscriptions.get(id=NOTIFICATIONS_PUB) except Subscription.DoesNotExist: sub = Subscription.get_or_create(user=request.user, pub_id=NOTIFICATIONS_PUB) if sub.subscribed <> user['enable_follow_notification']: sub.subscribed = user['enable_follow_notification'] sub.save() for f in str_fields: if f in user and user[f] != getattr(request.user, f): setattr(request.user, f, user[f]) for f in settings_fields: settings = user['settings'] if f in settings: setattr(request.user, f, settings[f]) for f in int_fields: if f in user and user[f] != getattr(request.user, f): if user[f] == '': user[f] = None setattr(request.user, f, user[f]) if 'password' in user and user['password'] != '': request.user.password = hash_password(user['password']) if 'username' in user and user['username'] != request.user.username: _username = request.user.username request.user.username = create_handle(user['username']) cache.bust_on_handle(request.user, _username, False) request.user.save() cache.bust_on_handle(request.user, request.user.username) return json_response({'result': request.user.username})
for acc in original.accomplishment_set.all(): acc_header = acc.header acc_description = acc.description delete = True for new_acc in org["accomplishments"]: if new_acc["year"] == acc_header and new_acc["text"] == acc_description: delete = False if delete: acc.delete() original.save() try: cache.bust_on_handle(original, original.handle) except: pass return json_response({'result' : original.handle}) @PostOnly def remove_org(request): try: id = getattr(request.POST, 'id') org = Org.objects.get(id = id) except AttributeError, ObjectDoesNotExist: return json_error(INVALID_ORG_ID_ERROR) # TODO: so, uh, we need to figure out if the current user is authorized to do this? org.delete() cache.bust_on_handle(org, org.handle, False) return json_response({'result' : 1})