def view_f_request(request, message): from friends.models import FriendshipInvitation ai = message.associated_item tolog(ai) fi = FriendshipInvitation.objects.cache().select_related('to_user','to_user___profile_cache','to_child','from_child','from_child__photo','from_child__album','from_child__school').get(id=message.associated_item) to_child = fi.to_child to_user = fi.to_user to_child_cv = create_childview(request.user, to_child) from_child = fi.from_child from_child_cv = create_childview(request.user, from_child) from_parents = from_child.parents from_caregiver = from_child.caregivers ctx = { 'message':message, 'fi':fi, 'from_user':fi.from_user, 'to_child':to_child_cv, 'to_user':to_user, 'from_child':from_child_cv, 'from_parents':from_parents, 'from_caregiver':from_caregiver, 'cat_messages': True, 'return_url': get_return_url(request), } template_name='messages/view_f_request.html' return render_to_response(template_name, ctx, context_instance=RequestContext(request))
def view_f_request(request, message): from friends.models import FriendshipInvitation ai = message.associated_item tolog(ai) fi = FriendshipInvitation.objects.cache().select_related( 'to_user', 'to_user___profile_cache', 'to_child', 'from_child', 'from_child__photo', 'from_child__album', 'from_child__school').get(id=message.associated_item) to_child = fi.to_child to_user = fi.to_user to_child_cv = create_childview(request.user, to_child) from_child = fi.from_child from_child_cv = create_childview(request.user, from_child) from_parents = from_child.parents from_caregiver = from_child.caregivers ctx = { 'message': message, 'fi': fi, 'from_user': fi.from_user, 'to_child': to_child_cv, 'to_user': to_user, 'from_child': from_child_cv, 'from_parents': from_parents, 'from_caregiver': from_caregiver, 'cat_messages': True, 'return_url': get_return_url(request), } template_name = 'messages/view_f_request.html' return render_to_response(template_name, ctx, context_instance=RequestContext(request))
def invites_cv(playdate, request): invites_cv = [] for invite in playdate.invites_list(): if invite.is_user: invite.childview = create_childview(request.user, invite.to_child) invites_cv.append(invite) return invites_cv
def invites_cv(playdate, request): invites_cv = [] for invite in playdate.invites_list(): if invite.is_user: invite.childview = create_childview(request.user, invite.to_child ) invites_cv.append(invite) return invites_cv
def create_list_of_parents_and_children(request, user_list): ajax_user_list = [] for user in user_list: profile = user.get_profile() for ac in profile.manage_playlist_children: ajax_user = { 'user': profile.get_profile(), 'child': create_childview(user=request.user, child=ac.child).get_profile() } ajax_user_list.append(ajax_user) return ajax_user_list
def get_condensed_calendar(request, child_id, **kwargs): if child_id: if not re.match('^[0-9]+$',child_id): raise Exception('Invalid input') try: child = Child.objects.get(id=child_id) except Child.DoesNotExist: raise Exception("Invalid input") childview = create_childview(user=request.user, child=child) if not childview.can_view_child_schedule: raise Exception("No permissions for this") else: raise Exception('Invalid input') start = datetime.now() start = start.replace(hour=0,minute=1,second=0) end = start + timedelta(days=7, hours=2) end = end.replace(hour=0,minute=1,second=0) days = [] day_to_array_map = {} day_counter = 0 current_day = start event_day_list = [] while not current_day.day == end.day: day = current_day.strftime('%d') day_to_array_map[day] = day_counter day_counter = day_counter + 1 event_day_list.append([]) current_day = current_day + timedelta(days=1) event_list = list(child.events.select_related('event').filter(event__start__gte = start, event__end__lte = end)) select_related_generic_prop(event_list, 'activity','event') max_events = 3 for ep in event_list: if not ep.status == '1' and not ep.status == '5': ev_day = ep.event.start.strftime('%d') ev_start = ep.event.start.strftime('%I:%M %p') ev_status = ep.status ev_index = day_to_array_map[ev_day] if len(event_day_list[ev_index]) < max_events: activity = ep.event.activity event_day_list[ev_index].append({ 'direct_url':activity.direct_url, 'type':activity.type, 'start': ev_start, 'status': ev_status, 'summary':activity.summary() }) return HttpResponse(simplejson.dumps(event_day_list), mimetype='application/javascript')
def create_list_of_parents_and_children(user_list): ajax_user_list = [] for user in user_list: profile = user.get_profile() vuser = User.objects.get(id=19) for ac in profile.manage_playlist_children: ajax_user = { 'user': profile.get_profile(), 'child': create_childview(user=vuser, child=ac.child).get_profile() } ajax_user_list.append(ajax_user) return simplejson.dumps(ajax_user_list, cls=PDEncoder) # , default=dthandler)
def create_list_of_children_and_parents(request, friend_suggestion_list): result = [] for child_suggestion in friend_suggestion_list: child = child_suggestion.suggested_child parent_list = [] for parent in child.parents: parent_list.append(parent.get_profile().get_profile()) childview = create_childview(user=request.user, child=child) result.append({"child": childview.profile, "parents": parent_list, "suggestion_id": child_suggestion.id}) return simplejson.dumps(result, cls=PDEncoder)
def create_list_of_children_and_parents(request, child_list): result = [] for sf in child_list: child = sf.suggested_child parent_list = [] for parent in child.parents: parent_list.append(parent.get_profile().get_profile()) childview = create_childview(user=request.user, child=child) result.append({ 'suggestion_id': int(sf.id), 'child':childview.profile, 'parents':parent_list }) return result
def create_list_of_children_and_parents(request, friend_suggestion_list): result = [] for child_suggestion in friend_suggestion_list: child = child_suggestion.suggested_child parent_list = [] for parent in child.parents: parent_list.append(parent.get_profile().get_profile()) childview = create_childview(user=request.user, child=child) result.append({ 'child':childview.profile, 'parents':parent_list, 'suggestion_id':child_suggestion.id }) return simplejson.dumps(result, cls=PDEncoder)
def create_list_of_children_and_parents(request, child_list): result = [] for sf in child_list: child = sf.suggested_child parent_list = [] for parent in child.parents: parent_list.append(parent.get_profile().get_profile()) childview = create_childview(user=request.user, child=child) result.append({ 'suggestion_id': int(sf.id), 'child': childview.profile, 'parents': parent_list }) return result
def view_playdate(request, playdate_id, **kwargs): if not re.match('^[0-9]+$', playdate_id): # user id raise Exception("Invalid Playdate") is_organizer = False playdate_invite_id = None token = email = contactfb = None set_status_yes = False first_response = False if 'pd_invites' in request.session and playdate_id in request.session[ "pd_invites"]: template = 'playdates/view_pd_non_user.html' if "token" in request.session["pd_invites"][playdate_id]: token = request.session["pd_invites"][playdate_id]['token'] email = request.session["pd_invites"][playdate_id]['email'] del request.session["pd_invites"] elif "contactfb" in request.session["pd_invites"][playdate_id]: contactfb = request.session["pd_invites"][playdate_id]['contactfb'] del request.session["pd_invites"] else: raise Exception('not fbid, no token. something is wrong') elif request.user.is_authenticated(): template = "playdates/view_pd_user.html" else: request.session["message"] = 'Please log in to view this playdate' path = urlquote(request.get_full_path()) tup = settings.LOGIN_URL, REDIRECT_FIELD_NAME, path return HttpResponseRedirect('%s?%s=%s' % tup) pd = None try: pd = Playdate.objects.select_related('organizer').get(id=playdate_id) except Playdate.DoesNotExist: raise Exception('NO PLAYDATE FOUND') if request.user.is_authenticated() and (request.user == pd.organizer): is_organizer = True my_invites = None if token is not None: try: my_invites = list( PlaydateInviteEmail.objects.filter(playdate=playdate_id, token=token).all()) except: raise Exception('unauthorized - email ') elif contactfb is not None: try: my_invites = list( PlaydateInviteFB.objects.filter( playdate=playdate_id, facebook_contact=contactfb).all()) except: raise Exception('unauthorized - email ') else: try: my_invites = list( PlaydateInviteUser.objects.select_related( 'to_user', 'to_child', 'organizer_child').filter(playdate=playdate_id, to_user=request.user)) except: raise Exception('unauthorized - user') if my_invites is None or len(my_invites) == 0: raise Exception('unauthorized') my_invite = None event = pd.get_event upload_url = reverse("upload_done", kwargs={"album_id": pd.album.id}) activities = list(PDActivity.objects.all()) if request.method == "GET" and "set_status" in request.GET: inv_status = request.GET['set_status'] inv_id = request.GET['invite_id'] inv_type = request.GET['invite_type'] if not re.match('^[0-9]+$', inv_status): raise Exception('Invalid input - status') if not re.match('^[0-9]+$', inv_id): raise Exception('Invalid input - id') if not re.match('^[\w]+', inv_type): raise Exception('Invalid input - type') # if 'pd_invites' in request.session and playdate_id in request.session["pd_invites"]: for inv in my_invites: if inv.id == int(inv_id): my_invite = inv # elif request.user.is_authenticated(): # for inv in my_invites: # if inv.id == inv_id: # my_invite = inv if my_invite is None: raise Exception('unauthorized - noone') if my_invite.nr: first_response = True if inv_status == '2': my_invite.accept_and_notify() set_status_yes = True elif inv_status == '3': my_invite.decline_and_notify() elif inv_status == '4': my_invite.maybe_and_notify() pd.status = my_invite.playdate.status # if my_invite is None: # my_invite = my_invites[0] responses = pd.response_breakdown() for inv_resp in responses: for pdi in responses[inv_resp]: if isinstance(pdi, PlaydateInviteUser): pdi.adult = pdi.to_user.get_profile().get_profile() pdi.child = create_childview(user=request.user, child=pdi.to_child) pd.to_user = None pd.to_child = None ctx = { 'pd': pd, 'album': pd.album, 'set_status_yes': set_status_yes, 'upload_url': upload_url, 'event': event, 'responses': responses, 'is_organizer': is_organizer, 'my_invite': my_invite, 'my_invites': my_invites, 'email': email, 'can_upload': pd.can_upload_photo(request.user), 'session_key': request.session.session_key, 'cat_playdates': True, 'first_response': first_response, 'activities': activities, } return render_to_response(template, RequestContext(request, ctx))
def new_playdate(request, key = None, start = None, end = None, **kwargs): template = 'playdates/new_playdate.html' edit_schedule_children = get_cv_list_from_ac(request.user, request.user.get_profile().edit_schedule_children) single_child = False if len(edit_schedule_children) == 1: single_child = True ctx = {} record = None oc = None start_date = '' start_time = '' end_time = '' if start is not None: todebug("start is not none") start_dt = dt_from_epoch(start) end_dt = dt_from_epoch(end) start_date = start_dt.strftime("%m/%d/%Y") start_time = start_dt.strftime("%I:%M%p") end_time = end_dt.strftime("%I:%M%p") todebug(start_time) todebug(end_time) todebug(start_date) if key is not None: if re.match('^[0-9]+_[0-9]+_[0-9]+$',key): parts = key.split('_') # key = str(which_child_friend_id) + '_' + str(parent_id) + '_' + str(self.child.id) oc = parts[0] child_id = parts[2] child = Child.objects.get(id=child_id) cv = create_childview(user=request.user, child=child) name = cv.profile["name"] if len(name) > 15: name = name[:15] + '...' record = { 'name': name, 'tip': cv.profile["name"], 'small_profile_pic': cv.profile["small_profile_pic"], 'key':key } elif re.match('^fb_[0-9]+$',key): #fb id parts = key.split('_') fb_contact_id = parts[1] fbc = ContactFB.objects.get(owner=request.user, id=int(fb_contact_id)) name = fbc.name if len(name) > 15: name = name[:15] + '..' record = { 'key':key, 'name':name, 'tip':fbc.name, 'small_profile_pic':'http://graph.facebook.com/'+ str(fbc.facebook_id) +'/picture?type=square' } elif re.match('^ce_[0-9]+$',key): parts = key.split('_') contact_id = parts[1] c = ContactEmail.objects.get(owner=request.user, id=contact_id) name = c.email if len(name) > 15: name = name[:15] + '..' record = { 'key': c.email, 'name': name, 'tip': c.email, } else: todebug("not matching nothing") if request.method == "POST": post = request.POST errors = [] if (post.get(u'dropoff',None) == 'yes'): dropoff = True else: dropoff = False min_participation = None max_participation = None expire_option = None new_loc_name = post.get(u'new_loc_name') address = post.get(u'address') ctx.update({ address: address }) details = post.get(u'details') # phone validation phone = post.get(u'phone') if not re.match('^[0-9\s\(\)\-]+$',phone): errors.append('phone contains invalid characters') ctx.update({ phone: phone }) activity = post.get(u'activity') if not re.match('^[0-9]+$',activity): raise Exception('invalid playdate activity') activity = PDActivity.objects.get(id=activity) # figure out how to have multiple organizer children organizer_child = post.getlist(u'organizer_child') invitees = post.getlist(u'invitee') # TODO validate invitees, organizer_child # date manipulation date_str = post.get(u'date') time_start_str = post.get(u'time_start') time_end_str = post.get(u'time_end') date_good = True if not re.match('^\d{1,2}/\d{1,2}/\d{4}$', date_str): errors.append("date not selected or is invalid") date_good = False if not re.match('^\d{1,2}:\d{2}\w{2}$', time_start_str): errors.append("start time not selected or is invalid") date_good = False if not re.match('^\d{1,2}:\d{2}\w{2}$', time_end_str): errors.append("end time not selected or is invalid") date_good = False if date_good: when_str = date_str + time_start_str when = datetime.strptime(when_str, '%m/%d/%Y%I:%M%p') until_str = date_str + time_end_str until = datetime.strptime(until_str, '%m/%d/%Y%I:%M%p') child_id = organizer_child[0] child = Child.objects.get(id=child_id) child_invite_design = child.default_invite if len(errors) > 0: tolog(str(errors)) ctx.update({ 'errors': errors }) else: pd = Playdate() pd.organizer = request.user pd.phone = phone # save phone for later profile = request.user.get_profile() profile.phone = phone profile.save() pd.details = details pd.address = address pd.when_from = when pd.when_until = until pd.is_dropoff = dropoff pd.max_participation = max_participation pd.min_participation = min_participation pd.expire_option = expire_option pd.invite_design = child_invite_design pd.activity = activity pd.save() ev = create_event(pd.when_from, pd.when_until, pd) if ((new_loc_name is not None) and (len(new_loc_name) > 0)): nl = Place(owner=request.user, name=new_loc_name, address=address) nl.save() child = None for child_id in organizer_child: if re.match('^[0-9]+$',child_id): child = Child.objects.get(id=child_id) pdi = PlaydateInviteUser() pdi.playdate = pd pdi.organizer_child = child pdi.to_child = child pdi.to_user = request.user pdi.phone = phone pdi.accept() create_eventplan(pdi.to_child, ev, "4") for invitee in invitees: if re.match('^[0-9]+_[0-9]+_[0-9]+$',invitee): # user id data_parts=invitee.split('_') pdi = PlaydateInviteUser() pdi.playdate = pd pdi.organizer_child=Child.objects.get(id=data_parts[0]) pdi.to_user=User.objects.get(id=data_parts[1]) pdi.to_child=Child.objects.get(id=data_parts[2]) pdi.save_and_invite() create_eventplan(pdi.to_child, ev, "4") elif re.match('^fb_[0-9]+$',invitee): #fb id data_parts=invitee.split('_') pdf = PlaydateInviteFB() pdf.playdate = pd pdf.organizer_child=child fbc = ContactFB.objects.get(owner=request.user, id=int(data_parts[1])) fbc.invited = True fbc.save() pdf.facebook_contact_id = int(data_parts[1]) pdf.save_and_invite() elif is_valid_email(invitee): pde = PlaydateInviteEmail() pde.playdate = pd pde.organizer_child=child pde.email = invitee pde.token = pde.assign_token() pde.save_and_invite() try: obj = ContactEmail.objects.get(owner=request.user, email=invitee) obj.invited=True obj.save() except ContactEmail.DoesNotExist: obj = ContactEmail(owner=request.user, email=invitee, invited=True) obj.save() request.session["event"] = 'Created a Playdate' return HttpResponseRedirect(reverse("view_playdate", kwargs={"playdate_id":pd.id})) places = list(request.user.places.all()) activities = list(PDActivity.objects.all()) children_without_default_designs = [] for cv in edit_schedule_children: if cv.child.default_invite is None: children_without_default_designs.append(cv) phone = request.user.get_profile().phone ctx.update( { 'edit_schedule_children':edit_schedule_children, 'places':places, 'children_without_default_designs': children_without_default_designs, 'phone':phone, 'single_child':single_child, 'activities':activities, 'fb_app_id':settings.FB_API_KEY, 'key':key, 'record':simplejson.dumps(record, cls=PDEncoder), 'oc':oc, 'start_date': start_date, 'start_time': start_time, 'end_time' : end_time, 'message': request.session.pop("message", None), }) return render_to_response(template, RequestContext(request, ctx))
def get_oc_pd_friends(request): if request.user.is_authenticated(): q = request.POST.get("q", None) oc = request.POST.get("oc") friend_child_ids = [] child_hash = {} friend_hash = {} result_hash = {} parent_hash = {} response = [] if q is not None and not re.match('^[\w\s]+$',q): raise Exception('Invalid input') if not re.match('^[0-9,]+$', oc): raise Exception('Invalid input') child_list = [] for child_id in oc.split(','): child = Child.objects.get(id=child_id) cv = ChildView(user=request.user, child=child) if not (cv.can_edit_child_schedule and cv.can_view_child_playlist): raise Exception("You do not have the access for this") child_list.append(child_id) child_friends = list(Friendship.objects.select_related('to_child').cache().filter(from_child__in=child_list).all()) for c in child_friends: child_hash[int(c.to_child_id)] = c.to_child friend_hash[int(c.to_child_id)] = int(c.from_child_id) friend_child_ids.append(int(c.to_child_id)) child_friend_parents = [] if child_friends: child_friend_parents = list(Adult_Child.objects.select_related('adult','adult___profile_cache','child').cache().filter(child__in=friend_child_ids).all()) for cf in child_friend_parents: parent_hash[int(cf.child_id)] = cf.adult.get_profile() for c in child_friends: child = c.to_child profile = parent_hash[int(child.id)] if int(child.id) in result_hash: continue else: result_hash[int(child.id)] = 1 cv = create_childview(user=request.user, child=child) name = cv.profile["first_name"] + ' (' + profile.name + '\'s Child) ' # if len(name) > 15: # name = name[:15] + '...' response.append({ 'key': str(friend_hash[child.id]) + '_' + str(profile.user_id) + '_' + str(child.id), 'name': name, 'tip': cv.profile["name"], 'small_profile_pic': cv.profile["small_profile_pic"], }) from operator import itemgetter response.sort(key=itemgetter('name')) return HttpResponse(simplejson.dumps(response), mimetype='application/javascript')
def view_playdate(request, playdate_id, **kwargs): if not re.match('^[0-9]+$',playdate_id): # user id raise Exception("Invalid Playdate") is_organizer = False playdate_invite_id = None token = email = contactfb = None set_status_yes = False first_response = False if 'pd_invites' in request.session and playdate_id in request.session["pd_invites"]: template='playdates/view_pd_non_user.html' if "token" in request.session["pd_invites"][playdate_id]: token = request.session["pd_invites"][playdate_id]['token'] email = request.session["pd_invites"][playdate_id]['email'] del request.session["pd_invites"] elif "contactfb" in request.session["pd_invites"][playdate_id]: contactfb = request.session["pd_invites"][playdate_id]['contactfb'] del request.session["pd_invites"] else: raise Exception('not fbid, no token. something is wrong') elif request.user.is_authenticated(): template = "playdates/view_pd_user.html" else: request.session["message"] = 'Please log in to view this playdate' path = urlquote(request.get_full_path()) tup = settings.LOGIN_URL, REDIRECT_FIELD_NAME, path return HttpResponseRedirect('%s?%s=%s' % tup) pd = None try: pd = Playdate.objects.select_related('organizer').get(id=playdate_id) except Playdate.DoesNotExist: raise Exception('NO PLAYDATE FOUND') if request.user.is_authenticated() and ( request.user == pd.organizer ): is_organizer = True my_invites = None if token is not None: try: my_invites = list(PlaydateInviteEmail.objects.filter(playdate=playdate_id, token=token).all()) except: raise Exception('unauthorized - email ') elif contactfb is not None: try: my_invites = list(PlaydateInviteFB.objects.filter(playdate=playdate_id, facebook_contact=contactfb).all()) except: raise Exception('unauthorized - email ') else: try: my_invites = list(PlaydateInviteUser.objects.select_related('to_user','to_child','organizer_child').filter(playdate=playdate_id, to_user=request.user)) except: raise Exception('unauthorized - user') if my_invites is None or len(my_invites) == 0: raise Exception('unauthorized') my_invite = None event = pd.get_event upload_url = reverse("upload_done", kwargs={"album_id":pd.album.id}) activities = list(PDActivity.objects.all()) if request.method == "GET" and "set_status" in request.GET: inv_status=request.GET['set_status'] inv_id = request.GET['invite_id'] inv_type = request.GET['invite_type'] if not re.match('^[0-9]+$',inv_status): raise Exception('Invalid input - status') if not re.match('^[0-9]+$',inv_id): raise Exception('Invalid input - id') if not re.match('^[\w]+',inv_type): raise Exception('Invalid input - type') # if 'pd_invites' in request.session and playdate_id in request.session["pd_invites"]: for inv in my_invites: if inv.id == int(inv_id): my_invite = inv # elif request.user.is_authenticated(): # for inv in my_invites: # if inv.id == inv_id: # my_invite = inv if my_invite is None: raise Exception('unauthorized - noone') if my_invite.nr: first_response = True if inv_status == '2': my_invite.accept_and_notify() set_status_yes = True elif inv_status == '3': my_invite.decline_and_notify() elif inv_status == '4': my_invite.maybe_and_notify() pd.status = my_invite.playdate.status # if my_invite is None: # my_invite = my_invites[0] responses = pd.response_breakdown() for inv_resp in responses: for pdi in responses[inv_resp]: if isinstance(pdi, PlaydateInviteUser): pdi.adult = pdi.to_user.get_profile().get_profile() pdi.child = create_childview(user=request.user, child=pdi.to_child) pd.to_user = None pd.to_child = None ctx = { 'pd': pd, 'album': pd.album, 'set_status_yes':set_status_yes, 'upload_url':upload_url, 'event': event, 'responses': responses, 'is_organizer': is_organizer, 'my_invite': my_invite, 'my_invites': my_invites, 'email':email, 'can_upload':pd.can_upload_photo(request.user), 'session_key': request.session.session_key, 'cat_playdates': True, 'first_response': first_response, 'activities': activities, } return render_to_response(template, RequestContext(request, ctx))
def contacts(request): contacts = [] contacts_email = list(ContactEmail.objects.filter(owner=request.user, invited=True, removed=False).all()) for contact in contacts_email: temp_hash = {} if contact.first_name: temp_hash['name'] = contact.first_name + ' ' + contact.last_name else: temp_hash['name'] = contact.email temp_hash['sort'] = temp_hash['name'].lower() temp_hash['type'] = 'email' temp_hash['email'] = contact.email temp_hash['id'] = contact.id temp_hash['key'] = contact.key contacts.append(temp_hash) contacts_fb = list(ContactFB.objects.filter(owner=request.user, invited=True, removed=False).all()) for contact in contacts_fb: temp_hash = {} temp_hash['name'] = contact.first_name + ' ' + contact.last_name temp_hash['sort'] = temp_hash['name'].lower() temp_hash['type'] = 'fb' temp_hash['fbid'] = contact.facebook_id temp_hash['id'] = contact.id temp_hash['key'] = contact.key contacts.append(temp_hash) child_ac_list = request.user.get_profile().view_schedule_children friends = [] for ac in child_ac_list: friends = friends + ac.child.friends friend_id_hash = {} for friend in friends: friend_id_hash[friend.id] = friend friend_ids = friend_id_hash.keys() friend_parents_ac = [] if friend_ids: friend_parents_ac = list(Adult_Child.objects.select_related('adult','adult___profile_cache','adult___profile_cache__photo','adult___profile_cache__album', 'child','child__photo','child__school','child__album').filter(child__in=friend_ids, relation='P')) contacts_pd_children = {} for ac in friend_parents_ac: if ac.adult.id in contacts_pd_children: contacts_pd_children[ac.adult.id].append( create_childview(user=request.user, child=ac.child) ) else: contacts_pd_children[ac.adult.id] = [ create_childview(user=request.user, child=ac.child) ] seen_adult = {} for ac in friend_parents_ac: if ac.adult.id in seen_adult: continue else: seen_adult[ac.adult.id] = 1 temp_hash = {} contact = ac.adult.get_profile() temp_hash['name'] = contact.first_name + ' ' + contact.last_name temp_hash['sort'] = temp_hash['name'].lower() temp_hash['type'] = 'pd' temp_hash['children'] = contacts_pd_children[ac.adult.id] temp_hash['id'] = contact.id temp_hash['profile'] = contact.get_profile() contacts.append(temp_hash) from operator import itemgetter contacts.sort(key=itemgetter('sort')) ctx = { 'contacts':contacts, 'cat_contacts':True } template = 'friends/contacts.html' return render_to_response(template, RequestContext(request, ctx))
def get_profiles(request, child_id): if not re.match('^[0-9]+$',child_id): raise Exception('Invalid input') if request.method == 'POST': offset = request.POST.get("offset", None) limit = request.POST.get("limit", None) # offset = '0' # limit = '1' if not re.match('^[0-9]+$',offset): raise Exception('Invalid input') if not re.match('^[0-9]+$',limit): raise Exception('Invalid input') try: child = Child.objects.select_related('album','photo','school').get(id=child_id) except Child.DoesNotExist: raise Exception("Invalid input") cv = ChildView(user=request.user, child=child) if not cv.can_view_child_playlist: raise Exception("You do not have permissions for this") max = int(offset)+int(limit) offset = int(offset) result = [] friends_all = child.friends friends = friends_all[offset:max] if len(friends): friend_id_dict = {} for obj in friends: friend_id_dict[obj.id] = [] friend_ids = friend_id_dict.keys() friend_parents_ac = list(Adult_Child.objects.select_related('adult','adult___profile_cache','adult___profile_cache__photo','adult___profile_cache__album').filter(child__in=friend_ids, relation='P')) for fpac in friend_parents_ac: friend_id_dict[fpac.child_id].append(fpac.adult) for friend in friends: parent_list = [] for parent in friend_id_dict[friend.id]: parent_list.append(parent.get_profile().get_profile()) childview = create_childview(user=request.user, child=friend) result.append({ 'child':childview.profile, 'key':childview.key(), 'parents':parent_list, 'is_friend':childview.is_in_friends, 'is_mine':childview.is_child_mine, 'is_pending_sent':childview.is_pending_sent, 'is_pending_received':childview.is_pending_received, }) return HttpResponse(simplejson.dumps(result, cls=PDEncoder), mimetype='application/javascript')
def get_profiles(request, child_id): if not re.match("^[0-9]+$", child_id): raise Exception("Invalid input") if request.method == "POST": offset = request.POST.get("offset", None) limit = request.POST.get("limit", None) # offset = '0' # limit = '1' if not re.match("^[0-9]+$", offset): raise Exception("Invalid input") if not re.match("^[0-9]+$", limit): raise Exception("Invalid input") try: child = Child.objects.select_related("album", "photo", "school").get(id=child_id) except Child.DoesNotExist: raise Exception("Invalid input") cv = ChildView(user=request.user, child=child) if not cv.can_view_child_playlist: raise Exception("You do not have permissions for this") max = int(offset) + int(limit) offset = int(offset) result = [] friends_all = child.friends friends = friends_all[offset:max] if len(friends): friend_id_dict = {} for obj in friends: friend_id_dict[obj.id] = [] friend_ids = friend_id_dict.keys() friend_parents_ac = list( Adult_Child.objects.select_related( "adult", "adult___profile_cache", "adult___profile_cache__photo", "adult___profile_cache__album" ).filter(child__in=friend_ids, relation="P") ) for fpac in friend_parents_ac: friend_id_dict[fpac.child_id].append(fpac.adult) for friend in friends: parent_list = [] for parent in friend_id_dict[friend.id]: parent_list.append(parent.get_profile().get_profile()) childview = create_childview(user=request.user, child=friend) result.append( { "child": childview.profile, "key": childview.key(), "parents": parent_list, "is_friend": childview.is_in_friends, "is_mine": childview.is_child_mine, "is_pending_sent": childview.is_pending_sent, "is_pending_received": childview.is_pending_received, } ) return HttpResponse(simplejson.dumps(result, cls=PDEncoder), mimetype="application/javascript")
def contacts(request): contacts = [] contacts_email = list(ContactEmail.objects.filter(owner=request.user, invited=True, removed=False).all()) for contact in contacts_email: temp_hash = {} if contact.first_name: temp_hash["name"] = contact.first_name + " " + contact.last_name else: temp_hash["name"] = contact.email temp_hash["sort"] = temp_hash["name"].lower() temp_hash["type"] = "email" temp_hash["email"] = contact.email temp_hash["id"] = contact.id temp_hash["key"] = contact.key contacts.append(temp_hash) contacts_fb = list(ContactFB.objects.filter(owner=request.user, invited=True, removed=False).all()) for contact in contacts_fb: temp_hash = {} temp_hash["name"] = contact.first_name + " " + contact.last_name temp_hash["sort"] = temp_hash["name"].lower() temp_hash["type"] = "fb" temp_hash["fbid"] = contact.facebook_id temp_hash["id"] = contact.id temp_hash["key"] = contact.key contacts.append(temp_hash) child_ac_list = request.user.get_profile().view_schedule_children friends = [] for ac in child_ac_list: friends = friends + ac.child.friends friend_id_hash = {} for friend in friends: friend_id_hash[friend.id] = friend friend_ids = friend_id_hash.keys() friend_parents_ac = [] if friend_ids: friend_parents_ac = list( Adult_Child.objects.select_related( "adult", "adult___profile_cache", "adult___profile_cache__photo", "adult___profile_cache__album", "child", "child__photo", "child__school", "child__album", ).filter(child__in=friend_ids, relation="P") ) contacts_pd_children = {} for ac in friend_parents_ac: if ac.adult.id in contacts_pd_children: contacts_pd_children[ac.adult.id].append(create_childview(user=request.user, child=ac.child)) else: contacts_pd_children[ac.adult.id] = [create_childview(user=request.user, child=ac.child)] seen_adult = {} for ac in friend_parents_ac: if ac.adult.id in seen_adult: continue else: seen_adult[ac.adult.id] = 1 temp_hash = {} contact = ac.adult.get_profile() temp_hash["name"] = contact.first_name + " " + contact.last_name temp_hash["sort"] = temp_hash["name"].lower() temp_hash["type"] = "pd" temp_hash["children"] = contacts_pd_children[ac.adult.id] temp_hash["id"] = contact.id temp_hash["profile"] = contact.get_profile() contacts.append(temp_hash) from operator import itemgetter contacts.sort(key=itemgetter("sort")) ctx = {"contacts": contacts, "cat_contacts": True} template = "friends/contacts.html" return render_to_response(template, RequestContext(request, ctx))
def get_condensed_calendar(request, child_id, **kwargs): if child_id: if not re.match('^[0-9]+$', child_id): raise Exception('Invalid input') try: child = Child.objects.get(id=child_id) except Child.DoesNotExist: raise Exception("Invalid input") childview = create_childview(user=request.user, child=child) if not childview.can_view_child_schedule: raise Exception("No permissions for this") else: raise Exception('Invalid input') start = datetime.now() start = start.replace(hour=0, minute=1, second=0) end = start + timedelta(days=7, hours=2) end = end.replace(hour=0, minute=1, second=0) days = [] day_to_array_map = {} day_counter = 0 current_day = start event_day_list = [] while not current_day.day == end.day: day = current_day.strftime('%d') day_to_array_map[day] = day_counter day_counter = day_counter + 1 event_day_list.append([]) current_day = current_day + timedelta(days=1) event_list = list( child.events.select_related('event').filter(event__start__gte=start, event__end__lte=end)) select_related_generic_prop(event_list, 'activity', 'event') max_events = 3 for ep in event_list: if not ep.status == '1' and not ep.status == '5': ev_day = ep.event.start.strftime('%d') ev_start = ep.event.start.strftime('%I:%M %p') ev_status = ep.status ev_index = day_to_array_map[ev_day] if len(event_day_list[ev_index]) < max_events: activity = ep.event.activity event_day_list[ev_index].append({ 'direct_url': activity.direct_url, 'type': activity.type, 'start': ev_start, 'status': ev_status, 'summary': activity.summary() }) return HttpResponse(simplejson.dumps(event_day_list), mimetype='application/javascript')
def new_playdate(request, key=None, start=None, end=None, **kwargs): template = 'playdates/new_playdate.html' edit_schedule_children = get_cv_list_from_ac( request.user, request.user.get_profile().edit_schedule_children) single_child = False if len(edit_schedule_children) == 1: single_child = True ctx = {} record = None oc = None start_date = '' start_time = '' end_time = '' if start is not None: todebug("start is not none") start_dt = dt_from_epoch(start) end_dt = dt_from_epoch(end) start_date = start_dt.strftime("%m/%d/%Y") start_time = start_dt.strftime("%I:%M%p") end_time = end_dt.strftime("%I:%M%p") todebug(start_time) todebug(end_time) todebug(start_date) if key is not None: if re.match('^[0-9]+_[0-9]+_[0-9]+$', key): parts = key.split('_') # key = str(which_child_friend_id) + '_' + str(parent_id) + '_' + str(self.child.id) oc = parts[0] child_id = parts[2] child = Child.objects.get(id=child_id) cv = create_childview(user=request.user, child=child) name = cv.profile["name"] if len(name) > 15: name = name[:15] + '...' record = { 'name': name, 'tip': cv.profile["name"], 'small_profile_pic': cv.profile["small_profile_pic"], 'key': key } elif re.match('^fb_[0-9]+$', key): #fb id parts = key.split('_') fb_contact_id = parts[1] fbc = ContactFB.objects.get(owner=request.user, id=int(fb_contact_id)) name = fbc.name if len(name) > 15: name = name[:15] + '..' record = { 'key': key, 'name': name, 'tip': fbc.name, 'small_profile_pic': 'http://graph.facebook.com/' + str(fbc.facebook_id) + '/picture?type=square' } elif re.match('^ce_[0-9]+$', key): parts = key.split('_') contact_id = parts[1] c = ContactEmail.objects.get(owner=request.user, id=contact_id) name = c.email if len(name) > 15: name = name[:15] + '..' record = { 'key': c.email, 'name': name, 'tip': c.email, } else: todebug("not matching nothing") if request.method == "POST": post = request.POST errors = [] if (post.get(u'dropoff', None) == 'yes'): dropoff = True else: dropoff = False min_participation = None max_participation = None expire_option = None new_loc_name = post.get(u'new_loc_name') address = post.get(u'address') ctx.update({address: address}) details = post.get(u'details') # phone validation phone = post.get(u'phone') if not re.match('^[0-9\s\(\)\-]+$', phone): errors.append('phone contains invalid characters') ctx.update({phone: phone}) activity = post.get(u'activity') if not re.match('^[0-9]+$', activity): raise Exception('invalid playdate activity') activity = PDActivity.objects.get(id=activity) # figure out how to have multiple organizer children organizer_child = post.getlist(u'organizer_child') invitees = post.getlist(u'invitee') # TODO validate invitees, organizer_child # date manipulation date_str = post.get(u'date') time_start_str = post.get(u'time_start') time_end_str = post.get(u'time_end') date_good = True if not re.match('^\d{1,2}/\d{1,2}/\d{4}$', date_str): errors.append("date not selected or is invalid") date_good = False if not re.match('^\d{1,2}:\d{2}\w{2}$', time_start_str): errors.append("start time not selected or is invalid") date_good = False if not re.match('^\d{1,2}:\d{2}\w{2}$', time_end_str): errors.append("end time not selected or is invalid") date_good = False if date_good: when_str = date_str + time_start_str when = datetime.strptime(when_str, '%m/%d/%Y%I:%M%p') until_str = date_str + time_end_str until = datetime.strptime(until_str, '%m/%d/%Y%I:%M%p') child_id = organizer_child[0] child = Child.objects.get(id=child_id) child_invite_design = child.default_invite if len(errors) > 0: tolog(str(errors)) ctx.update({'errors': errors}) else: pd = Playdate() pd.organizer = request.user pd.phone = phone # save phone for later profile = request.user.get_profile() profile.phone = phone profile.save() pd.details = details pd.address = address pd.when_from = when pd.when_until = until pd.is_dropoff = dropoff pd.max_participation = max_participation pd.min_participation = min_participation pd.expire_option = expire_option pd.invite_design = child_invite_design pd.activity = activity pd.save() ev = create_event(pd.when_from, pd.when_until, pd) if ((new_loc_name is not None) and (len(new_loc_name) > 0)): nl = Place(owner=request.user, name=new_loc_name, address=address) nl.save() child = None for child_id in organizer_child: if re.match('^[0-9]+$', child_id): child = Child.objects.get(id=child_id) pdi = PlaydateInviteUser() pdi.playdate = pd pdi.organizer_child = child pdi.to_child = child pdi.to_user = request.user pdi.phone = phone pdi.accept() create_eventplan(pdi.to_child, ev, "4") for invitee in invitees: if re.match('^[0-9]+_[0-9]+_[0-9]+$', invitee): # user id data_parts = invitee.split('_') pdi = PlaydateInviteUser() pdi.playdate = pd pdi.organizer_child = Child.objects.get(id=data_parts[0]) pdi.to_user = User.objects.get(id=data_parts[1]) pdi.to_child = Child.objects.get(id=data_parts[2]) pdi.save_and_invite() create_eventplan(pdi.to_child, ev, "4") elif re.match('^fb_[0-9]+$', invitee): #fb id data_parts = invitee.split('_') pdf = PlaydateInviteFB() pdf.playdate = pd pdf.organizer_child = child fbc = ContactFB.objects.get(owner=request.user, id=int(data_parts[1])) fbc.invited = True fbc.save() pdf.facebook_contact_id = int(data_parts[1]) pdf.save_and_invite() elif is_valid_email(invitee): pde = PlaydateInviteEmail() pde.playdate = pd pde.organizer_child = child pde.email = invitee pde.token = pde.assign_token() pde.save_and_invite() try: obj = ContactEmail.objects.get(owner=request.user, email=invitee) obj.invited = True obj.save() except ContactEmail.DoesNotExist: obj = ContactEmail(owner=request.user, email=invitee, invited=True) obj.save() request.session["event"] = 'Created a Playdate' return HttpResponseRedirect( reverse("view_playdate", kwargs={"playdate_id": pd.id})) places = list(request.user.places.all()) activities = list(PDActivity.objects.all()) children_without_default_designs = [] for cv in edit_schedule_children: if cv.child.default_invite is None: children_without_default_designs.append(cv) phone = request.user.get_profile().phone ctx.update({ 'edit_schedule_children': edit_schedule_children, 'places': places, 'children_without_default_designs': children_without_default_designs, 'phone': phone, 'single_child': single_child, 'activities': activities, 'fb_app_id': settings.FB_API_KEY, 'key': key, 'record': simplejson.dumps(record, cls=PDEncoder), 'oc': oc, 'start_date': start_date, 'start_time': start_time, 'end_time': end_time, 'message': request.session.pop("message", None), }) return render_to_response(template, RequestContext(request, ctx))
def get_oc_pd_friends(request): if request.user.is_authenticated(): q = request.POST.get("q", None) oc = request.POST.get("oc") friend_child_ids = [] child_hash = {} friend_hash = {} result_hash = {} parent_hash = {} response = [] if q is not None and not re.match('^[\w\s]+$', q): raise Exception('Invalid input') if not re.match('^[0-9,]+$', oc): raise Exception('Invalid input') child_list = [] for child_id in oc.split(','): child = Child.objects.get(id=child_id) cv = ChildView(user=request.user, child=child) if not (cv.can_edit_child_schedule and cv.can_view_child_playlist): raise Exception("You do not have the access for this") child_list.append(child_id) child_friends = list( Friendship.objects.select_related('to_child').cache().filter( from_child__in=child_list).all()) for c in child_friends: child_hash[int(c.to_child_id)] = c.to_child friend_hash[int(c.to_child_id)] = int(c.from_child_id) friend_child_ids.append(int(c.to_child_id)) child_friend_parents = [] if child_friends: child_friend_parents = list( Adult_Child.objects.select_related( 'adult', 'adult___profile_cache', 'child').cache().filter(child__in=friend_child_ids).all()) for cf in child_friend_parents: parent_hash[int(cf.child_id)] = cf.adult.get_profile() for c in child_friends: child = c.to_child profile = parent_hash[int(child.id)] if int(child.id) in result_hash: continue else: result_hash[int(child.id)] = 1 cv = create_childview(user=request.user, child=child) name = cv.profile[ "first_name"] + ' (' + profile.name + '\'s Child) ' # if len(name) > 15: # name = name[:15] + '...' response.append({ 'key': str(friend_hash[child.id]) + '_' + str(profile.user_id) + '_' + str(child.id), 'name': name, 'tip': cv.profile["name"], 'small_profile_pic': cv.profile["small_profile_pic"], }) from operator import itemgetter response.sort(key=itemgetter('name')) return HttpResponse(simplejson.dumps(response), mimetype='application/javascript')