Esempio n. 1
0
def friend(request):
    id = request.GET.get("id")
    user = User.objects.get(id=id)
    if request.user == user:
        return HttpResponseForbidden("Nope!!")
    
    us = UserService(request.user)
    data = us.getUserData()
    # add friend
    data.friends.add(user)
    data.save()
    
    # do reverse as well
    # TODO: check user settings before auto adding this
    
    to_data = UserService(user).getUserData()
    # add friend
    to_data .friends.add(request.user)
    to_data.save()
    
    # notify user
    ps = PollService()
    subject = "%s added you as  friend" % request.user.username
    body = "Hi, %s has just added you as a friend.  As a result %s has been automatically added to your friends list.\n This is because he/she added you to their list.  You can change this setting in your settings if you like." % (request.user.username, request.user.username)
    ps.sendPollsterMessage(to_user=user, from_user=request.user, subject=subject, body=body)    
    
    return HttpResponse(content="You are now friends!")
Esempio n. 2
0
def render(request, template, vars=None):
    baseVars = {}
    baseVars["debug"] = settings.DEBUG
    baseVars["FACEBOOK_API_KEY"] = settings.FACEBOOK_API_KEY
    baseVars["FACEBOOK_SECRET_KEY"] = settings.FACEBOOK_SECRET_KEY

    baseVars["USER_FILES_URL"] = StringUtils.addTrailingSlash(
        settings_local.USER_FILES_URL)
    baseVars["USER_FILES_THUMBS_BIG"] = StringUtils.addTrailingSlash(
        settings_local.USER_FILES_THUMBS_BIG)
    baseVars["USER_FILES_THUMBS_MEDIUM"] = StringUtils.addTrailingSlash(
        settings_local.USER_FILES_THUMBS_MEDIUM)
    baseVars["USER_FILES_THUMBS_SMALL"] = StringUtils.addTrailingSlash(
        settings_local.USER_FILES_THUMBS_SMALL)
    baseVars["USER_FILES_THUMBS_TINY"] = StringUtils.addTrailingSlash(
        settings_local.USER_FILES_THUMBS_TINY)

    baseVars["POLL_FILES_URL"] = StringUtils.addTrailingSlash(
        settings_local.POLL_FILES_URL)
    baseVars["POLL_RESULTS_MAGIC_THRESH"] = consts.POLL_RESULTS_MAGIC_THRESH
    baseVars["SITE_NAME"] = consts.SITE_NAME
    baseVars["leader_board_ad"] = adfactory.get_leaderboard()
    baseVars["med_square_ad"] = adfactory.get_medium_square()

    baseVars[
        "POLL_VOTES_BEFORE_PERMANENTLY_ACTIVE"] = consts.POLL_VOTES_BEFORE_PERMANENTLY_ACTIVE

    tags = Tag.objects.filter().order_by(
        '-poll_count')[:100]  #@UndefinedVariable
    baseVars["header_tags"] = tags
    if request.user.is_authenticated():
        user = request.user
        baseVars["user"] = user
        us = UserService(user)
        data = us.getUserData()
        msgCount = PollsterMessage.objects.filter(
            read=False, to_user=request.user).count()  #@UndefinedVariable
        baseVars["newMail"] = msgCount > 0
        baseVars["newMailCnt"] = msgCount
        baseVars["profile_pic"] = data.profile_pic

    # if conflict between child class and base class vars then child wins
    # so child can override base vars
    if vars:
        baseVars.update(vars)
    return render_to_response(template, baseVars)
Esempio n. 3
0
def render(request, template, vars=None):
    baseVars = {}
    baseVars["debug"] = settings.DEBUG
    baseVars["FACEBOOK_API_KEY"] = settings.FACEBOOK_API_KEY
    baseVars["FACEBOOK_SECRET_KEY"] = settings.FACEBOOK_SECRET_KEY
    
    baseVars["USER_FILES_URL"] = StringUtils.addTrailingSlash(settings_local.USER_FILES_URL)
    baseVars["USER_FILES_THUMBS_BIG"] = StringUtils.addTrailingSlash(settings_local.USER_FILES_THUMBS_BIG)
    baseVars["USER_FILES_THUMBS_MEDIUM"] = StringUtils.addTrailingSlash(settings_local.USER_FILES_THUMBS_MEDIUM)
    baseVars["USER_FILES_THUMBS_SMALL"] = StringUtils.addTrailingSlash(settings_local.USER_FILES_THUMBS_SMALL)
    baseVars["USER_FILES_THUMBS_TINY"] = StringUtils.addTrailingSlash(settings_local.USER_FILES_THUMBS_TINY)
    
    baseVars["POLL_FILES_URL"] = StringUtils.addTrailingSlash(settings_local.POLL_FILES_URL)
    baseVars["POLL_RESULTS_MAGIC_THRESH"] = consts.POLL_RESULTS_MAGIC_THRESH
    baseVars["SITE_NAME"] = consts.SITE_NAME
    baseVars["leader_board_ad"] = adfactory.get_leaderboard()
    baseVars["med_square_ad"] = adfactory.get_medium_square()
    
    
    baseVars["POLL_VOTES_BEFORE_PERMANENTLY_ACTIVE"] = consts.POLL_VOTES_BEFORE_PERMANENTLY_ACTIVE
     
    tags = Tag.objects.filter().order_by('-poll_count')[:100]   #@UndefinedVariable
    baseVars["header_tags"] = tags
    if request.user.is_authenticated():
        user = request.user    
        baseVars["user"] = user
        us = UserService(user)
        data = us.getUserData()
        msgCount = PollsterMessage.objects.filter(read=False, to_user=request.user).count()   #@UndefinedVariable
        baseVars["newMail"] = msgCount > 0
        baseVars["newMailCnt"] = msgCount
        baseVars["profile_pic"] = data.profile_pic
        
    
    
     
    # if conflict between child class and base class vars then child wins
    # so child can override base vars
    if vars:
        baseVars.update(vars)    
    return render_to_response(template, baseVars)
Esempio n. 4
0
def pic(request, username=None):
    vars= {}
    user = User.objects.get(username=username)
    if user != request.user:
        return HttpResponseForbidden("NopeLOL!")
    us = UserService(user)
    data = us.getUserData()
    if data.profile_pic:
        vars["pic"] = data.profile_pic
    
    form = ProfilePicForm()
    if request.method == 'POST':
        form = ProfilePicForm(request.POST)
        if form.is_valid():
            f = request.FILES['file']
            us.uploadUserPic(f)
            return HttpResponseRedirect("/profile/%s/pic/" % username)
        
    vars["form"] = form
    
    return base.render(request=request, template="user/profile_pic.html", vars=vars)
Esempio n. 5
0
def facebook_connect(request):
    next = request.GET.get("next", None)
    vars = {}
    form = FacebookConnectForm()
    vars["form"] = form
    
    log = logging.getLogger('facebook_connect')
    request.session['session_key'] = request.COOKIES.get(settings.FACEBOOK_API_KEY + '_session_key')
    request.session['uid'] = request.COOKIES.get(settings.FACEBOOK_API_KEY + '_uid')
    log.debug("session key: " + str(request.session['session_key'])) 
    log.debug("uid: " + str(request.session['uid'])) 
    fb = FacebookService().getFacebookSession(request)
    if not fb:
        log.critical("Facebook Service did not initialize")
        return HttpResponseRedirect(fb.get_login_url())
    
    vars["fb"] = fb    
    uid = fb.users.getLoggedInUser()
    uid = int(uid)
    log.debug("user id: " + str(uid))
        
    try:
        data = UserData.objects.get(facebook_id=uid)      #@UndefinedVariable
        # user already has facebook connected to an account
        # just log them in and redirect them        
        user = User.objects.get(id=data.user.id)
        log.debug("User already exists...")
        if not request.user.is_authenticated():
            user = auth.authenticate(username=user.username, password=FacebookService().getUserPassword(uid))
            try:            
                auth.login(request, user)
            except NotImplementedError:
                # user already had a pollstruck account with a diff password
                vars["login_block"] = True
                vars["no_facebook"] = True
                vars["form"] = LoginForm()
                return base.render(request=request, template="user/facebook_connect.html", vars=vars)            
        if next:
            return HttpResponseRedirect(next)
        return HttpResponseRedirect("/profile/%s/" % user.username)
    except UserData.DoesNotExist:      #@UndefinedVariable
        
        if request.user.is_authenticated() and request.user.userdata_set.get(user=request.user).facebook_id == None:
            log.debug("linking accounts")
            # user has pollstruck account already but no facebook
            # link their account to facebook automatically
            us = UserService(user=request.user)
            data = us.getUserData()
            data.facebook_id = uid 
            data.save()
            if next:
                return HttpResponseRedirect(next)
            return HttpResponseRedirect('/profile/%s/' % request.user.username)
        
        
    # they are good to go
    if request.method == 'POST':
        form = FacebookConnectForm(request.POST)
        vars["form"] = form
        if form.is_valid():
            # create a user for the facebook user
            username = form.cleaned_data["username"]
            email = form.cleaned_data["email"]
            if User.objects.filter(username=username).count() > 0:                
                vars["user_error"] = "That username exists"
                return base.render(request=request, template="user/facebook_connect.html", vars=vars)
            if User.objects.filter(email=email).count() > 0:
                vars["email_error"] = "That email exists"
                return base.render(request=request, template="user/facebook_connect.html", vars=vars)
                
            us = UserService()
            user = us.createUser(username=username, email=email, password=FacebookService().getUserPassword(uid))            
            auth.login(request, user)
            data = us.getUserData()
            data.facebook_id = uid
            # default all *new* incoming facebook users to use their facebook pic
            data.use_profile_pic = False 
            data.save()            
            if next:
                return HttpResponseRedirect(next)
            return HttpResponseRedirect('/')
    else:
        pass

    return base.render(request=request, template="user/facebook_connect.html", vars=vars)
Esempio n. 6
0
def facebook_connect(request):
    next = request.GET.get("next", None)
    vars = {}
    form = FacebookConnectForm()
    vars["form"] = form

    log = logging.getLogger('facebook_connect')
    request.session['session_key'] = request.COOKIES.get(
        settings.FACEBOOK_API_KEY + '_session_key')
    request.session['uid'] = request.COOKIES.get(settings.FACEBOOK_API_KEY +
                                                 '_uid')
    log.debug("session key: " + str(request.session['session_key']))
    log.debug("uid: " + str(request.session['uid']))
    fb = FacebookService().getFacebookSession(request)
    if not fb:
        log.critical("Facebook Service did not initialize")
        return HttpResponseRedirect(fb.get_login_url())

    vars["fb"] = fb
    uid = fb.users.getLoggedInUser()
    uid = int(uid)
    log.debug("user id: " + str(uid))

    try:
        data = UserData.objects.get(facebook_id=uid)  #@UndefinedVariable
        # user already has facebook connected to an account
        # just log them in and redirect them
        user = User.objects.get(id=data.user.id)
        log.debug("User already exists...")
        if not request.user.is_authenticated():
            user = auth.authenticate(
                username=user.username,
                password=FacebookService().getUserPassword(uid))
            try:
                auth.login(request, user)
            except NotImplementedError:
                # user already had a pollstruck account with a diff password
                vars["login_block"] = True
                vars["no_facebook"] = True
                vars["form"] = LoginForm()
                return base.render(request=request,
                                   template="user/facebook_connect.html",
                                   vars=vars)
        if next:
            return HttpResponseRedirect(next)
        return HttpResponseRedirect("/profile/%s/" % user.username)
    except UserData.DoesNotExist:  #@UndefinedVariable

        if request.user.is_authenticated() and request.user.userdata_set.get(
                user=request.user).facebook_id == None:
            log.debug("linking accounts")
            # user has pollstruck account already but no facebook
            # link their account to facebook automatically
            us = UserService(user=request.user)
            data = us.getUserData()
            data.facebook_id = uid
            data.save()
            if next:
                return HttpResponseRedirect(next)
            return HttpResponseRedirect('/profile/%s/' % request.user.username)

    # they are good to go
    if request.method == 'POST':
        form = FacebookConnectForm(request.POST)
        vars["form"] = form
        if form.is_valid():
            # create a user for the facebook user
            username = form.cleaned_data["username"]
            email = form.cleaned_data["email"]
            if User.objects.filter(username=username).count() > 0:
                vars["user_error"] = "That username exists"
                return base.render(request=request,
                                   template="user/facebook_connect.html",
                                   vars=vars)
            if User.objects.filter(email=email).count() > 0:
                vars["email_error"] = "That email exists"
                return base.render(request=request,
                                   template="user/facebook_connect.html",
                                   vars=vars)

            us = UserService()
            user = us.createUser(
                username=username,
                email=email,
                password=FacebookService().getUserPassword(uid))
            auth.login(request, user)
            data = us.getUserData()
            data.facebook_id = uid
            # default all *new* incoming facebook users to use their facebook pic
            data.use_profile_pic = False
            data.save()
            if next:
                return HttpResponseRedirect(next)
            return HttpResponseRedirect('/')
    else:
        pass

    return base.render(request=request,
                       template="user/facebook_connect.html",
                       vars=vars)
Esempio n. 7
0
    def getUserFeed(self, user, owner=False, phase=0, request_user=None):
        """
        Gets the activity feed for a user
        This method is the hoss method of all methods in methodtown
        """

        us = UserService(user=user)
        userdata = us.getUserData()
        userdata_friends = userdata.friends.all()
        if not owner:
            request_user_friends = UserService(user=request_user).getFriends()
            friend_ids = [friend.id for friend in request_user_friends]
            userdata_friends = userdata_friends.filter(id__in=friend_ids)

        user_feed = []
        # create the motherfuckin window bitches!!!!!!
        start_index = phase * consts.POLL_ACTIVITY_WINDOW
        end_index = (phase + 1) * consts.POLL_ACTIVITY_WINDOW
        self.log.debug("start index: %d -- end index: %d" %
                       (start_index, end_index))
        self.log.debug("Phase: %d" % phase)
        if owner:
            # only show friends stuff on owner feed
            for f in userdata_friends:
                # get polls friends created
                friend_polls = Poll.objects.filter(
                    user=f,
                    active=True).order_by('-date_created')  #@UndefinedVariable
                for fp in friend_polls:
                    timestamp = time.mktime(fp.date_created.timetuple())
                    ci = CreatedItem(timestamp=timestamp,
                                     poll=fp,
                                     date=fp.date_created)
                    ci.friend_related = True
                    user_feed.append(ci)

                # get friends votes
                friend_votes = PollVote.objects.filter(user=f).order_by(
                    '-date_created')  #@UndefinedVariable
                for fv in friend_votes:
                    timestamp = time.mktime(fv.date_created.timetuple())
                    vi = VoteItem(vote=fv,
                                  timestamp=timestamp,
                                  poll=fv.poll,
                                  date=fv.date_created)
                    vi.friend_related = True
                    vi.friend_voted = True
                    user_feed.append(vi)

                # get friends comments
                friend_comments = ThreadedComment.objects.filter(
                    user=f).order_by('-date_modified')
                for fc in friend_comments:
                    timestamp = time.mktime(fc.date_modified.timetuple())
                    ci = CommentItem(comment=fc,
                                     timestamp=timestamp,
                                     poll=fc.content_object,
                                     date=fc.date_modified)
                    ci.friend_related = True
                    ci.friend_commented = True
                    user_feed.append(ci)

        # get polls created by user
        user_polls = Poll.objects.filter(user=user, active=True).order_by(
            '-date_created')  #@UndefinedVariable
        for poll in user_polls:
            self.appendPollVotesAndComments(user_feed=user_feed,
                                            poll=poll,
                                            user_related=True,
                                            start_index=start_index,
                                            end_index=end_index)

            # add polls user created
            timestamp = time.mktime(poll.date_created.timetuple())
            ci = CreatedItem(timestamp=timestamp,
                             poll=poll,
                             date=poll.date_created)
            ci.user_related = True
            user_feed.append(ci)

        # get user's watched polls
        watched_polls = userdata.polls_watched.order_by('-poll__date_modified')
        for wp in watched_polls:
            self.appendPollVotesAndComments(user_feed=user_feed,
                                            poll=wp.poll,
                                            watching=True,
                                            start_index=start_index,
                                            end_index=end_index)

        # get users votes
        user_votes = PollVote.objects.filter(user=user).order_by(
            '-date_created')  #@UndefinedVariable
        for uv in user_votes:
            timestamp = time.mktime(uv.date_created.timetuple())
            vi = VoteItem(vote=uv,
                          timestamp=timestamp,
                          poll=uv.poll,
                          date=uv.date_created)
            try:
                vi = user_feed[user_feed.index(vi)]
            except ValueError:
                user_feed.append(vi)
            vi.user_voted = True

        # get user comments
        user_comments = ThreadedComment.objects.filter(
            user=user).order_by('-date_modified')
        for uc in user_comments:
            timestamp = time.mktime(uc.date_modified.timetuple())
            ci = CommentItem(comment=uc,
                             timestamp=timestamp,
                             poll=uc.content_object,
                             date=uc.date_modified)
            try:
                ci = user_feed[user_feed.index(ci)]
            except ValueError:
                user_feed.append(ci)
            ci.user_commented = True

        # sort that shit out
        remain = len(user_feed) > end_index
        user_feed.sort()
        user_feed.reverse()
        # TODO: FOR THE LOVE OF GOD CACHE THE F*****G USER_FEED RIGHT HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
        user_feed = user_feed[start_index:end_index]
        return user_feed, remain
Esempio n. 8
0
def index(request, poll_url=None, demographics=None, preview=False):
    """
    index handler
    """
    
    log = logging.getLogger("POLL VIEW")
    pollService = PollService()
    vars = {}
    vars['show_ad'] = True
    vars["pollview"] = True
    vars["preview"] = preview
    p = None
    random_poll = pollService.get_random_polls(1, request.user)
    if len(random_poll) > 0:        
        vars["random_poll"] = random_poll[0]
    if poll_url == None:        
        return HttpResponseRedirect("/view-poll/%s/" % random_poll.url)        
    else:       
        try:
            # get the poll and its tags                
            if preview:
                p = Poll.objects.get(url=poll_url) #@UndefinedVariable
                if request.user != p.user:
                    log.debug("User %s trying to preview poll he doesn't own, %s" % (request.user.username, p.url))
                    raise Http404
            else:
                p = Poll.objects.get(url=poll_url, active=True) #@UndefinedVariable
        except Poll.DoesNotExist: #@UndefinedVariable
            log.debug("Attempt to view poll which is not active or does not exist, trying to send to create, slug: %s" % poll_url)
            return HttpResponseRedirect("/create-poll/answers/%s/" % poll_url)    
    
    tags = p.tags.all()
    vars["tags"] = tags
    vars["poll"] = p
    if p.description and p.description != "":
        vars["poll_desc"] = p.description
    if p.link:
        vars["domain"] = urlparse(p.link)[1]
    
    if p.total_votes == 0:
        vars["noVotes"] = True
    
    
    # get the poll files
    pf = PollFile.objects.filter(poll=p) #@UndefinedVariable
    vars["pollFiles"] = pollService.get_poll_file_w_icons(pf)
    
    # check for content box
    if len(pf) > 0 or p.video_link or p.link:
        vars["showContentBox"] = True
    
    # do not show voting form if user has already voted
    form = None     

    results = pollService.get_poll_results(p, drop_zero_results=False)

    # user is logged in   
    if request.user.is_authenticated():
        # check to see if user is watching this
        us = UserService(request.user)
        data = us.getUserData() 
        if data.polls_watched.filter(poll=p).count() > 0:
            vars["watching"] = True
                
        if request.user == p.user:
            vars["creator"] = True
        
        # get the answer forms
        try:
            # check if user has voted
            poll_vote = PollVote.objects.get(poll=p, user=request.user) #@UndefinedVariable
            vars['your_answer'] = poll_vote.poll_answer.answer
        except PollVote.DoesNotExist: #@UndefinedVariable
            # they haven't so show them the answer form
            form = poll_answer_style_factory(consts.PREDEFINED_ANSWERS, p, results)
        except PollVote.MultipleObjectsReturned: #@UndefinedVariable
            # oh jesus, somehow they have multiple votes, log it and take their first one
            poll_vote = PollVote.objects.filter(poll=p, user=request.user)[0] #@UndefinedVariable
            logging.getLogger("PollView").critical("user has more than one vote for a poll id: %d and user: %s." % (p.id, request.user.username)) 
    else:
        form = poll_answer_style_factory(consts.PREDEFINED_ANSWERS, p, results)

    # open flash chart
    demographic_url_param = ''
    if demographics:
        demographic_url_param = demographics
    
    ansForm = AnswerForm()
    vars["answerForm"] = ansForm
    vars['form'] = form
    
    
    # poll display type
    chart_type = consts.DEFAULT_CHART_TYPE
    vars["link_in_new_window"] = True
    if request.user.is_authenticated():
        data = UserService(request.user).getUserData()
        vars["link_in_new_window"] = data.link_in_new_window
        chart_type = data.default_chart_type
    
    # get the gchart
    vars["chart_type"] = chart_type
    gcf = GChartFactory()
    res_w_votes = []
    res_wo_votes = []
    # grab only the results with votes to display on the chart
    for r in results:
        if r.votes > 0:
            res_w_votes.append(r)
        else:
            res_wo_votes.append(r)
    pchart = gcf.get_chart(res_w_votes)
    vars["gChart"] = pchart.get_url()
    vars["results"] = res_w_votes
    vars['results_wo_votes'] = res_wo_votes
    
    # create description tag:
    description = ""
    description += "Is it: "
    for i in range(0, len(vars["results"])):
        a = vars["results"][i]
        if isinstance(a.answer, PollAnswer):            
            description += a.answer.answer + ", "
            if i+1 == len(vars["results"]) - 1:
                description += "or "
    description = description.rstrip(", ")
    description += "?  "
    if p.description:
        description += p.description
    vars["meta_desc"] = description
    
    if p.link:
        vars['domain'] = urlparse(p.link)  
    return base.render(request, "pollview.html", vars)
Esempio n. 9
0
    def getUserFeed(self, user, owner=False, phase=0, request_user=None):
        """
        Gets the activity feed for a user
        This method is the hoss method of all methods in methodtown
        """
        
        us = UserService(user=user)
        userdata = us.getUserData()
        userdata_friends = userdata.friends.all()
        if not owner:
            request_user_friends = UserService(user=request_user).getFriends()
            friend_ids = [friend.id for friend in request_user_friends]
            userdata_friends = userdata_friends.filter(id__in=friend_ids) 
                        
        user_feed = []
        # create the motherfuckin window bitches!!!!!!
        start_index = phase * consts.POLL_ACTIVITY_WINDOW
        end_index = (phase+1) *  consts.POLL_ACTIVITY_WINDOW
        self.log.debug("start index: %d -- end index: %d" % (start_index, end_index))
        self.log.debug("Phase: %d" % phase)
        if owner:
            # only show friends stuff on owner feed
            for f in userdata_friends:
                # get polls friends created                
                friend_polls = Poll.objects.filter(user=f, active=True).order_by('-date_created')   #@UndefinedVariable
                for fp in friend_polls:
                    timestamp = time.mktime(fp.date_created.timetuple())
                    ci = CreatedItem(timestamp=timestamp, poll=fp, date=fp.date_created)
                    ci.friend_related = True
                    user_feed.append(ci)
                    
                # get friends votes
                friend_votes = PollVote.objects.filter(user=f).order_by('-date_created')   #@UndefinedVariable
                for fv in friend_votes:
                    timestamp = time.mktime(fv.date_created.timetuple())
                    vi = VoteItem(vote=fv, timestamp=timestamp, poll=fv.poll, date=fv.date_created)
                    vi.friend_related = True
                    vi.friend_voted = True
                    user_feed.append(vi)
                
                # get friends comments
                friend_comments = ThreadedComment.objects.filter(user=f).order_by('-date_modified')
                for fc in friend_comments:
                    timestamp = time.mktime(fc.date_modified.timetuple())
                    ci = CommentItem(comment=fc, timestamp=timestamp, poll=fc.content_object, date=fc.date_modified)
                    ci.friend_related = True
                    ci.friend_commented = True
                    user_feed.append(ci)

        # get polls created by user
        user_polls = Poll.objects.filter(user=user, active=True).order_by('-date_created')   #@UndefinedVariable
        for poll in user_polls:
            self.appendPollVotesAndComments(user_feed=user_feed, poll=poll, user_related=True, start_index=start_index, end_index=end_index)
            
            # add polls user created
            timestamp = time.mktime(poll.date_created.timetuple())
            ci = CreatedItem(timestamp=timestamp, poll=poll, date=poll.date_created)
            ci.user_related = True
            user_feed.append(ci)
        
        # get user's watched polls
        watched_polls = userdata.polls_watched.order_by('-poll__date_modified')                
        for wp in watched_polls:
            self.appendPollVotesAndComments(user_feed=user_feed, poll=wp.poll, watching=True, start_index=start_index, end_index=end_index)
        
        # get users votes
        user_votes = PollVote.objects.filter(user=user).order_by('-date_created')   #@UndefinedVariable
        for uv in user_votes:
            timestamp = time.mktime(uv.date_created.timetuple())
            vi = VoteItem(vote=uv, timestamp=timestamp, poll=uv.poll, date=uv.date_created)
            try:
                vi = user_feed[user_feed.index(vi)]                                        
            except ValueError:                                
                user_feed.append(vi)
            vi.user_voted = True
        
        # get user comments
        user_comments = ThreadedComment.objects.filter(user=user).order_by('-date_modified')
        for uc in user_comments:
            timestamp = time.mktime(uc.date_modified.timetuple())
            ci = CommentItem(comment=uc, timestamp=timestamp, poll=uc.content_object, date=uc.date_modified)
            try:
                ci = user_feed[user_feed.index(ci)]                                        
            except ValueError:                                
                user_feed.append(ci)
            ci.user_commented = True
        
        # sort that shit out
        remain = len(user_feed) > end_index
        user_feed.sort()
        user_feed.reverse()
        # TODO: FOR THE LOVE OF GOD CACHE THE F*****G USER_FEED RIGHT HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
        user_feed = user_feed[start_index:end_index]
        return user_feed, remain
Esempio n. 10
0
def index(request, poll_url=None, demographics=None, preview=False):
    """
    index handler
    """

    log = logging.getLogger("POLL VIEW")
    pollService = PollService()
    vars = {}
    vars['show_ad'] = True
    vars["pollview"] = True
    vars["preview"] = preview
    p = None
    random_poll = pollService.get_random_polls(1, request.user)
    if len(random_poll) > 0:
        vars["random_poll"] = random_poll[0]
    if poll_url == None:
        return HttpResponseRedirect("/view-poll/%s/" % random_poll.url)
    else:
        try:
            # get the poll and its tags
            if preview:
                p = Poll.objects.get(url=poll_url)  #@UndefinedVariable
                if request.user != p.user:
                    log.debug(
                        "User %s trying to preview poll he doesn't own, %s" %
                        (request.user.username, p.url))
                    raise Http404
            else:
                p = Poll.objects.get(url=poll_url,
                                     active=True)  #@UndefinedVariable
        except Poll.DoesNotExist:  #@UndefinedVariable
            log.debug(
                "Attempt to view poll which is not active or does not exist, trying to send to create, slug: %s"
                % poll_url)
            return HttpResponseRedirect("/create-poll/answers/%s/" % poll_url)

    tags = p.tags.all()
    vars["tags"] = tags
    vars["poll"] = p
    if p.description and p.description != "":
        vars["poll_desc"] = p.description
    if p.link:
        vars["domain"] = urlparse(p.link)[1]

    if p.total_votes == 0:
        vars["noVotes"] = True

    # get the poll files
    pf = PollFile.objects.filter(poll=p)  #@UndefinedVariable
    vars["pollFiles"] = pollService.get_poll_file_w_icons(pf)

    # check for content box
    if len(pf) > 0 or p.video_link or p.link:
        vars["showContentBox"] = True

    # do not show voting form if user has already voted
    form = None

    results = pollService.get_poll_results(p, drop_zero_results=False)

    # user is logged in
    if request.user.is_authenticated():
        # check to see if user is watching this
        us = UserService(request.user)
        data = us.getUserData()
        if data.polls_watched.filter(poll=p).count() > 0:
            vars["watching"] = True

        if request.user == p.user:
            vars["creator"] = True

        # get the answer forms
        try:
            # check if user has voted
            poll_vote = PollVote.objects.get(
                poll=p, user=request.user)  #@UndefinedVariable
            vars['your_answer'] = poll_vote.poll_answer.answer
        except PollVote.DoesNotExist:  #@UndefinedVariable
            # they haven't so show them the answer form
            form = poll_answer_style_factory(consts.PREDEFINED_ANSWERS, p,
                                             results)
        except PollVote.MultipleObjectsReturned:  #@UndefinedVariable
            # oh jesus, somehow they have multiple votes, log it and take their first one
            poll_vote = PollVote.objects.filter(
                poll=p, user=request.user)[0]  #@UndefinedVariable
            logging.getLogger("PollView").critical(
                "user has more than one vote for a poll id: %d and user: %s." %
                (p.id, request.user.username))
    else:
        form = poll_answer_style_factory(consts.PREDEFINED_ANSWERS, p, results)

    # open flash chart
    demographic_url_param = ''
    if demographics:
        demographic_url_param = demographics

    ansForm = AnswerForm()
    vars["answerForm"] = ansForm
    vars['form'] = form

    # poll display type
    chart_type = consts.DEFAULT_CHART_TYPE
    vars["link_in_new_window"] = True
    if request.user.is_authenticated():
        data = UserService(request.user).getUserData()
        vars["link_in_new_window"] = data.link_in_new_window
        chart_type = data.default_chart_type

    # get the gchart
    vars["chart_type"] = chart_type
    gcf = GChartFactory()
    res_w_votes = []
    res_wo_votes = []
    # grab only the results with votes to display on the chart
    for r in results:
        if r.votes > 0:
            res_w_votes.append(r)
        else:
            res_wo_votes.append(r)
    pchart = gcf.get_chart(res_w_votes)
    vars["gChart"] = pchart.get_url()
    vars["results"] = res_w_votes
    vars['results_wo_votes'] = res_wo_votes

    # create description tag:
    description = ""
    description += "Is it: "
    for i in range(0, len(vars["results"])):
        a = vars["results"][i]
        if isinstance(a.answer, PollAnswer):
            description += a.answer.answer + ", "
            if i + 1 == len(vars["results"]) - 1:
                description += "or "
    description = description.rstrip(", ")
    description += "?  "
    if p.description:
        description += p.description
    vars["meta_desc"] = description

    if p.link:
        vars['domain'] = urlparse(p.link)
    return base.render(request, "pollview.html", vars)