示例#1
0
def edit_location(request):
    """
    Location selection of the user profile
    """
    profile = request.user.get_profile()

    if request.method == "POST":
        form = LocationForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            if profile.any_field_changed('latitude', 'longitude'):
                messages.add_message(request, messages.INFO,
                                     _("Your new location has been set"))
            # invalidate personalized recommendations in area cache
            cache.delete(
                cache.Key("top_personalized_recommendations", request.user))
            cache.delete(cache.Key("tv_user_recommended", request.user))
            cache.delete(cache.Key("cinema_user_recommended", request.user))
            next = request.GET.get('next')
            if next:
                return HttpResponseRedirect(next)
    else:
        form = LocationForm(instance=profile)

    template = "usersettings/edit_location.html"
    data = {
        'section': 'location',
        'form': form,
    }
    return render(request, template, data)
示例#2
0
    def post(self, *args, **kw):
        key = cache.Key("questions_", self.request.unique_user)
        questions = cache.get(key)

        if "start" not in self.request.POST:
            self.check_answer(time.time())

        if not questions:
            return self.on_end_questions()

        question = questions.pop()
        if question:
            cache.delete(key) # delete cache for questions
            cache.set(key, questions) # set cache for questions-1
            key = cache.Key("answer_", self.request.unique_user)
            cache.set(key, question) # set cache for user answer

        context = self.get_context_data()
        context.update({
            'question': question or [],
            'tstamp': time.time(),
            'progress': (100-len(questions)*10),
            'answered': 10-len(questions)
        })
        return render(self.request, self.template_name, context )
示例#3
0
 def invalidate_cache(self):
     cache.delete(cache.Key("open_festivals"))
     cache.delete(cache.Key("festival_theaters", self))
     cache.delete(cache.Key("festival_screening_dates", self))
     cache.delete(cache.Key("festival_participants", self))
     cache.delete(cache.Key("festival_films", self))
     cache.delete(cache.Key("festival_screening_set", self))
     cache.delete(cache.Key("festival_screening_set", self, True))
     cache.delete(cache.Key("festival_screening_set", self, False))
     for date in self.get_screening_dates():
         cache.delete(cache.Key("festival_screenings", self, date))
示例#4
0
 def get_screening_set(self, past=False):
     key = cache.Key("festival_screening_set", self, past)
     screening_set = cache.get(key)
     if screening_set is None:
         screening_set = FestivalScreeningSet(self, past=past)
         cache.set(key, screening_set)
     return screening_set
示例#5
0
def get_country_and_tz_by_lat_lng(lat, lng):
    key = cache.Key('country_tz', lat, lng)
    data = cache.get(key)
    if data is None:
        data = _get_country_and_tz_by_lat_lng(lat, lng)
        cache.set(key, data)
    return data
示例#6
0
def latest_checkins():
    """
        Widget for main page (for unregistered users) displaying X
        random check-ins by Filmaster users.
    """
    key = cache.Key("latest-checkins")
    latest = cache.get(key)

    NUMBER_OF_LATEST_CHECKINS = getattr(settings, 'NUMBER_OF_LATEST_CHECKINS',
                                        10)
    NUMBER_OF_CHECKINS_AT_MAIN_PAGE = getattr(
        settings, 'NUMBER_OF_CHECKINS_AT_MAIN_PAGE', 4)

    if not latest:

        now = datetime.now()
        ago = now - timedelta(hours=3)
        checkins = UserActivity.objects.all_checkins().order_by('-created_at')

        latest = list(
            checkins.filter(created_at__gte=ago)[:NUMBER_OF_LATEST_CHECKINS])
        if len(latest) < NUMBER_OF_CHECKINS_AT_MAIN_PAGE:
            latest = list(checkins)[:NUMBER_OF_LATEST_CHECKINS]

        cache.set(key, latest, cache.CACHE_HOUR * 3)

    try:
        latest = random.sample(latest, NUMBER_OF_CHECKINS_AT_MAIN_PAGE)
    except ValueError:
        latest = latest[:NUMBER_OF_CHECKINS_AT_MAIN_PAGE]

    return {
        'activities': latest,
    }
示例#7
0
def latest_ratings():
    """
        Widget for main page (for unregistered users)
        displaying X random ratings by Filmaster users.
    """

    key = cache.Key("latest_ratings")
    ratings = cache.get(key)

    NUMBER_OF_LATEST_RATINGS = getattr(settings, 'NUMBER_OF_LATEST_RATINGS',
                                       10)
    NUMBER_OF_RATINGS_AT_MAIN_PAGE = getattr(settings,
                                             'NUMBER_OF_RATINGS_AT_MAIN_PAGE',
                                             4)

    if not ratings:
        ratings = UserActivity.objects.all_ratings().\
                order_by('-created_at')[:NUMBER_OF_LATEST_RATINGS]
        cache.set(key, ratings, cache.A_DAY)

    try:
        ratings = random.sample(ratings, NUMBER_OF_RATINGS_AT_MAIN_PAGE)
    except ValueError:
        ratings = ratings[:NUMBER_OF_RATINGS_AT_MAIN_PAGE]

    return {
        'activities': ratings,
    }
示例#8
0
def regional_info(context):
    """
        Display local info
    """

    slug_city = None
    slug_region = None

    request = context['request']
    user = request.user
    if user.is_authenticated():
        profile = user.get_profile()
        try:
            slug_city = slughifi(profile.location)
        except AttributeError:
            slug_city = None

    if not slug_city:
        try:
            city = request.city
        except AttributeError:
            city = None

        slug_city = city and slughifi(city) or None

    key = cache.Key(CACHE_REGIONAL_INFO, slug_city)
    regional_info_obj = cache.get(key)

    if regional_info_obj is None and slug_city is not None:
        regional_info_obj = get_regional_info_obj(slug_city)
        cache.set(key, regional_info_obj)

    return {
        'regional_info': regional_info_obj,
    }
示例#9
0
    def get_films_to_rate(self, number_of_films=1, tag=None):
        key = cache.Key("vue_rater_user_films", self.user)
        user_films = cache.get(key)
        if user_films is None:
            user_films = vue.get_ordered_known_film_ids()
            if self.SHUFFLE_BLOCK_SIZE:
                shuffled = []
                while user_films:
                    block = user_films[:self.SHUFFLE_BLOCK_SIZE]
                    user_films = user_films[self.SHUFFLE_BLOCK_SIZE:]
                    random.shuffle(block)
                    shuffled.extend(block)
                user_films = shuffled
            cache.set(key, user_films)

        excluded = self.get_excluded_films()

        out = []
        for film_id in user_films:
            if film_id not in excluded:
                out.append(film_id)
            if len(out) >= number_of_films:
                break
        out = [Film.get(id=id) for id in out]
        return out
示例#10
0
def clear_filmaster_recommends_cache(sender, instance, **kw):
    """
        If flat page is saved clear filmaster_recommends cache
    """
    if instance.url == FLATPAGE_FILMASTER_RECOMMENDS:
        key = cache.Key(FLATPAGE_FILMASTER_RECOMMENDS)
        cache.delete(key)
示例#11
0
def count_guessed_rate(user, film):
    ratings = Rating.get_user_ratings(user)
    logger.info("counting guessed rate for film %d", film.id)

    if len(ratings) < MIN_USER_RATES:
        return None

    average_rate, average_weight = AVERAGE_RATE, AVERAGE_WEIGHT

    film_weight = 0.0
    film_rate = film.average_score() or 0.0
    film_rate = float(film_rate)

    if film_rate:
        film_weight = FILM_WEIGHT * pow(
                float(film.number_of_votes() / FILM_RELIABILITY_BAR), 0.3)

    user_rate = sum(ratings.values()) / len(ratings)
    user_weight = USER_WEIGHT * (len(ratings) / USER_RELIABILITY_BAR) ** 0.3

#    film_ids = ratings.keys()
#    scores = dict(FilmComparator.objects.filter(
#            main_film=film, compared_film__id__in=film_ids).\
#            values_list('compared_film', 'score'))

    key = cache.Key("compared_films", film.id)
    scores = cache.get(key)
    if scores is None:
        query = FilmComparator.objects.filter(main_film=film).values_list(
                    'compared_film', 'score')
        scores = dict((f, float(s)) for (f, s) in query)
        cache.set(key, scores)


    sum_weights = 0.0
    sum_rate = 0.0
    for film_id, rating in ratings.items():
        if film_id in scores:
            weight = float(scores[film_id])
            sum_weights += weight
            sum_rate += float(rating) * weight

    sum_rate += film_weight * film_rate + user_weight * user_rate
    sum_rate += average_weight * average_rate
    sum_weights += film_weight + user_weight + average_weight
    recommendation = None
    if sum_weights > 0.0 and sum_rate >= 0.0:
        score = Decimal(str(sum_rate / sum_weights))
        if score <= 10:
            recommendation, created = Recommendation.objects.get_or_create(
                user=user, 
                film=film,
                defaults=dict(guess_rating_alg2=score),
            )
            if not created:
                recommendation.guess_rating_alg2 = score
                recommendation.save()
    # transaction.commit()
    return recommendation
示例#12
0
def change_user_display_name(user):
    logger.info("check display name for user %s" % user)
    from film20.core.models import Profile
    profile = Profile.objects.get(user = user)
    logger.info("get profile: %s" % profile)
    key = cache.Key("display_name_profile", user.id)
    cache.delete(key)
    logger.info("end of username changes")
示例#13
0
    def get_fragments(self):
        key = cache.Key("fragments-set-%s" % self.key)
        fragments = cache.get(key)
        if fragments is None:
            fragments = Fragment.objects.filter(key=self.key)
            cache.set(key, fragments, cache.A_MONTH)

        return fragments
示例#14
0
 def get_open_festivals(self):
     key = cache.Key("open_festivals")
     festivals = cache.get(key)
     if festivals is None:
         festivals = Festival.objects.filter(event_status=self.STATUS_OPEN)
         festivals = list(festivals)
         cache.set(key, festivals)
     return festivals
示例#15
0
 def __init__(self, queryset, page_size):
     self.queryset = queryset.order_by('id')
     key = cache.Key("sitemap_paginator", str(self.queryset.query))
     self.ids = cache.get(key)
     if self.ids is None:
         self.ids = list(self.queryset.values_list('id',
                                                   flat=True))[::page_size]
         cache.set(key, self.ids)
     self.num_pages = len(self.ids)
示例#16
0
 def get_films(self):
     key = cache.Key("festival_films", self)
     films = cache.get(key)
     if films is None:
         films = Film.objects.tagged(self.tag.lower())
         films = list(films[:1000])
         Film.update_ranking(films)
         cache.set(key, films)
     return films
示例#17
0
 def get_theaters(self):
     key = cache.Key("festival_theaters", self)
     theaters = cache.get(key)
     if theaters is None:
         from film20.tagging.models import TaggedItem
         channels = self.theaters.all()
         theaters = list(Channel.objects.theaters().filter(id__in=channels))
         cache.set(key, theaters)
     return theaters
示例#18
0
 def get_user(self, user_id):
     key = cache.Key("user", user_id)
     user = settings.CACHED_USERS and cache.get(key) or None
     if not user:
         try:
             user = super(CachedModelBackend, self).get_user(user_id)
             if settings.CACHED_USERS:
                 cache.set(key, user)
         except User.DoesNotExist, e:
             pass
示例#19
0
 def matching_film_ids(self, include_ids, exclude_ids):
     key = cache.Key("features_film_ids", include_ids, exclude_ids)
     film_ids = cache.get(key)
     if film_ids is None:
         film_ids = Film.objects.filter(features__type__in=include_ids)
         if exclude_ids:
             film_ids = film_ids.exclude(features__type__in=exclude_ids)
         film_ids = set(film_ids.values_list('id', flat=True))
         cache.set(key, film_ids)
     return film_ids
示例#20
0
 def get_unliked_film_ids(cls, user):
     if not user.id:
         return ()
     key = cache.Key("unliked_recommendations", user.id)
     ret = cache.get(key)
     if ret is None:
         ret = cls.objects.filter(user=user, vote=0).values_list('film_id',
                                                                 flat=True)
         cache.set(key, ret)
     return ret
示例#21
0
def tvchannels(request):
    """
    user TVChannel selection view
    """
    from forms import TVChannelsForm
    from film20.showtimes.models import TYPE_TV_CHANNEL, UserChannel

    profile = request.user.get_profile()
    user_channels = list(
        u.pk
        for u in request.user.selected_channels.filter(type=TYPE_TV_CHANNEL))

    queryset = Channel.objects.tv().filter(is_active=True)
    if profile.country:
        queryset = queryset.filter(country__code=profile.country)

    is_post = request.method == 'POST'
    form = TVChannelsForm(request.POST if is_post else None,
                          initial={'channels': user_channels})
    form.fields['channels'].choices = [(c.id, c.name) for c in queryset]
    if is_post:
        if form.is_valid():
            channels = form.cleaned_data['channels']
            UserChannel.objects.filter(
                user=request.user,
                channel__type=TYPE_TV_CHANNEL,
                channel__country__code=profile.country,
            ).delete()
            logger.info(channels)
            for c in channels:
                UserChannel(user=request.user, channel_id=c).save()
            # invalidate personalized recommendations in area cache
            cache.delete(
                cache.Key("top_personalized_recommendations", request.user))
            cache.delete(cache.Key("tv_user_recommended", request.user))
            cache.delete(cache.Key("cinema_user_recommended", request.user))

    ctx = dict(
        form=form,
        channels=list(queryset),
    )
    return render(request, "usersettings/tvchannels.html", ctx)
示例#22
0
def compute_guess_score_for_all_films(user):
    if not hasattr(user, '_guess_score'):
        key = cache.Key("guess_score", user.id)
        user._guess_score = cache.get(key)
        if user._guess_score is None:
            from film20.core.models import Recommendation
            items = Recommendation.objects.filter(user=user.id)
            items = items.values_list('film_id', 'guess_rating_alg2')
            user._guess_score = dict((r[0], float(r[1])) for r in items)
        cache.set(key, user._guess_score)
    return user._guess_score
示例#23
0
    def check_answer(self, serv_tstamp):
        question_key = cache.Key("answer_", self.request.unique_user)
        question = cache.get(question_key)

        if question:
            answer = question.get('answer', '')
            choice = int(self.request.POST.get('choice', 0))
            user_tstamp = float(self.request.POST.get('tstamp'))
            if answer == choice:
                self.count_points(user_tstamp, serv_tstamp)
        cache.delete(question_key)
示例#24
0
 def to_recommend_ids(self, request):
     tag = request.GET.get('tag')
     key = cache.Key('saas_to_recommend_ids', tag)
     film_ids = cache.get(key)
     if film_ids is None:
         if tag:
             film_ids = Film.objects.tagged(tag)
         else:
             film_ids = Film.objects.filter(popularity__gt=20)
         film_ids = list(film_ids.values_list('id', flat=True))
         cache.set(key, film_ids)
     return film_ids
示例#25
0
    def count_points(self, user_tstamp, serv_tstamp):
        quiz_points_key = cache.Key("points_", self.request.unique_user)
        quiz_points = cache.get(quiz_points_key)
        cache.delete(quiz_points_key)

        if not quiz_points:
            quiz_points = 0

        tdelta = serv_tstamp - user_tstamp
        tdelta = int(round(tdelta))

        quiz_points += settings.FBAPP.get('points').get('seconds').get(tdelta, 0)
        cache.set(quiz_points_key, quiz_points)
        return quiz_points
示例#26
0
    def get(self, *args, **kw):
        context = self.get_context_data()

        contest = self.get_contest()
        participant = ContestParticipation.objects.get(user=self.request.unique_user, contest=contest)
        if participant.state >= ContestParticipation.STATE_QUIZ:
            return http.HttpResponseRedirect(self.get_next_step())

        key = cache.Key("questions_", self.request.unique_user)
        questions = cache.get(key)
        if not questions:
            questions = self.quiz_mixer()        
            cache.set(key, questions)
        return render(self.request, self.on_start, context)
示例#27
0
    def add_points(self):
        quiz_points_key = cache.Key("points_", self.request.unique_user)
        quiz_points = cache.get(quiz_points_key)

        contest = self.get_contest()
        participant = ContestParticipation.objects.get(user=self.request.unique_user, contest=contest)

        if participant.state == ContestParticipation.STATE_TICKET:
            participant.quiz_count = quiz_points
            participant.score += quiz_points
            participant.state = ContestParticipation.STATE_QUIZ
            participant.save()
        cache.delete(quiz_points_key)
        return participant.score
示例#28
0
    def get_contest( self ):
        contest_key = cache.Key("contest")
        contest = cache.get(contest_key)
        if not contest:
            try:
                contest = Contest.objects.get(state=Contest.STATE_OPEN)
            except Contest.DoesNotExist:
                contest = Contest.objects.all().order_by('-final_date')[0]

            if contest.final_date < datetime.date.today():
                contest.state = Contest.STATE_CLOSED
                contest.save()
                contest = Contest.objects.get(id=contest.id)
            cache.set(contest_key, contest)
        return contest
示例#29
0
def get_vue_recommendations(user, mood=None, similar=True, limit=True):
    from film20.new_recommendations.rateless_alg import rec_engine
    if not user.id:
        return ()
    ratings = rating_helper.get_user_ratings(user.id)
    unliked = RecommendationVote.get_unliked_film_ids(user)
    recommendations = rec_engine.get_recommendations(ratings.items(), 1000)

    key = cache.Key("user_vue_recommendations", user.id)
    cache.set(key, recommendations, cache.A_WEEK)

    return RecommendationsWrapper(recommendations,
                                  ratings,
                                  mood,
                                  similar=similar,
                                  limit=limit,
                                  exclude=unliked)
示例#30
0
def filmaster_recommends():
    """
        A widget displaying HTML from a selected flat page.
        Define this page in settings.py to FLATPAGE_FILMASTER_RECOMMENDS
    """
    key = cache.Key(FLATPAGE_FILMASTER_RECOMMENDS)

    flat_page = cache.get(key)

    if flat_page is None:
        try:
            flat_page = FlatPage.objects.get(url=FLATPAGE_FILMASTER_RECOMMENDS)
        except FlatPage.DoesNotExist:
            flat_page = False
        cache.set(key, flat_page, cache.A_DAY)

    return {'flat_page': flat_page}