Esempio n. 1
0
def channel_screenings(channel,
                       date,
                       films=None,
                       days=1,
                       past=False,
                       order_by=None):
    date = date.replace(tzinfo=None)
    to_date = date + datetime.timedelta(days=days)
    key = cache.Key("channel_screenings", channel, date, to_date, films)
    screenings = cache.get(key)
    if screenings is None:
        screenings = Screening.objects.filter(channel=channel, utc_time__gte=date, utc_time__lt=to_date)\
                                      .order_by('film__film', 'film', 'utc_time')
        screenings = dict((f, list(v)) for (f, v) in groupby(
            screenings, lambda s:
            (s.film.film or film_from_film_on_channel(s.film))))
        if films is None:
            films = sorted(screenings.keys(), cmp=__film_cmp)  #
        screenings = list((f, screenings[f]) for f in films if f in screenings)
        cache.set(key, screenings)

    comparator = _film_comparator(order_by)
    if comparator:
        _cmp = lambda a, b: comparator(a[0], b[0])
        logger.info(screenings)
        screenings = sorted(screenings, cmp=_cmp)

    return screenings
Esempio n. 2
0
def film_screenings(film, date, channels=None, days=1, past=False, type=None):
    channels = channels or []
    date = date.replace(tzinfo=None)
    to_date = date + datetime.timedelta(days=days)
    key = cache.Key("film_screenings", film.pk or film.title, date, to_date,
                    channels, type)
    screenings = cache.get(key)
    if screenings is None:
        if film.pk:
            q = Screening.objects.filter(film__film=film, utc_time__gte=date, utc_time__lt=to_date)\
                                  .order_by('channel', 'utc_time')
        else:
            q = Screening.objects.filter(film__title=film.title, utc_time__gte=date, utc_time__lt=to_date)\
                                  .order_by('channel', 'utc_time')

        q = q.filter(channel__in=channels)
        if type:
            q = q.filter(channel__type=type)

        q = q.select_related('film', 'film__film', 'channel')

        screenings = dict(
            (c, list(v)) for (c, v) in groupby(q, lambda s: s.channel))
        if channels:
            screenings = list(
                (c, screenings[c]) for c in channels if c in screenings)
        else:
            channels = sorted(screenings.keys(), key=lambda c: c.name)
            screenings = list((c, screenings[c]) for c in channels)
        cache.set(key, screenings)
    return screenings
Esempio n. 3
0
def film_similar_ratings(request, film=None):
    user = request.user
    film = film or get_object_or_404(Film, id=request.GET.get('film_id'))
    ratings = ()
    if user.is_authenticated():
        key = cache.Key("film_similar_ratings", film, user)
        ratings = cache.get(key)
        if ratings is None:
            N_SIMILAR = 100
            N = 5
            query = User.objs.similar(user)[:N_SIMILAR]
            similar_users = cache_query(query, "similar_users", user)
            if similar_users:
                d = dict((u.id, u) for u in similar_users)
                ratings = Rating.objects.select_related()
                ratings = list(ratings.film(film).filter(user__in=d.keys()))
                ratings = sorted(ratings, key=lambda r:d[r.user_id].score)[:N]
                logger.debug("%d of %d similar friends rated this film", len(ratings), N_SIMILAR)
                if len(ratings)<N:
                    logger.debug("not enough results, executing full query")
                    ratings = Rating.objects.select_related()
                    ratings = ratings.film(film).similar_ratings(user)[0:N]
                    logger.debug("similar ratings fetched")
            cache.set(key, ratings)
    return {
        'film':film,
        'title':_("Similar users ratings"),
        'ratings':ratings,
        'friends': False
    }
Esempio n. 4
0
    def threaded_messages(self, user):
        cache_key = "conversation_thread_%s" % self.pk
        thread = cache.get(cache_key)
        if thread is not None:
            return thread
        query = self.messages.order_by('id')
        messages = {}
        root = None
        for msg in query:
            msg.children = []
            messages[msg.id] = msg
            if msg.parent_msg_id:
                parent = messages.get(msg.parent_msg_id)
                if parent:
                    msg.level = parent.level + 1
                    parent.children.append(msg)
            else:
                msg.level = 0
                root = msg

        def traverse(root):
            yield root
            for c in root.children:
                for i in traverse(c):
                    yield i

        def not_deleted(msg):
            return msg.sender_id == user.id and msg.sender_deleted_at is None or \
                   msg.recipient_id == user.id and msg.recipient_deleted_at is None

        thread = root and list(traverse(root)) or ()
        thread = filter(not_deleted, thread)
        cache.set(cache_key, thread)
        return thread
Esempio n. 5
0
    def main_page_featured_activities(self):
        """Gets list of daily featured activities. """
        #TODO add filtering by featured activities but only when featuring
        #    becomes automatical. http://jira.filmaster.org/browse/FLM-700

        TYPES_OF_ACTIVITIES = \
                getattr(settings, 'MAIN_PAGE_TYPES_OF_ACTIVITIES')

        key = cache.Key('main_page_displayed_activities')
        displayed = cache.get(key)
        if not displayed:
            activities = UserActivity.objects.public().order_by('-created_at')
            displayed = []
            for act_type in TYPES_OF_ACTIVITIES:
                activity_type = vars(UserActivity)[act_type]
                DISPLAYED_NUMBER = TYPES_OF_ACTIVITIES[act_type]
                typed_activities = list(activities.filter(
                        activity_type=activity_type)[:DISPLAYED_NUMBER])
                displayed += typed_activities

            random.shuffle(displayed)
            logger.info(displayed)
            cache.set(key, displayed)

        return displayed
Esempio n. 6
0
 def get(cls, **kw):
     key = cls._create_key(**kw)
     obj = cache.get(key)
     if obj is None:
         obj = cls.objects.get(**kw)
         cache.set(key, obj)
     return obj
Esempio n. 7
0
def random_film_to_rate(request):
    """
        Widget for main page (for not logged in users)
        displaying a film to rate, selected from
        the list of 10 most popular films.
    """

    user = request.user

    if user.is_authenticated():
        film = Film.get_next_film_to_rate(user)
    else:
        key = cache.Key("popular_films_list")

        popular_films = cache.get(key)

        if popular_films is None:
            fhelper = FilmHelper()
            lang = getattr(settings, 'LANGUAGE_CODE', 'en')
            if lang == 'en':
                popular_films = fhelper.get_popular_films(
                    exclude_nonEnglish=True)
            else:
                popular_films = fhelper.get_popular_films()
            cache.set(key, popular_films)

        film = popular_films and random.choice(popular_films) or None

    return {
        'film': film,
    }
Esempio n. 8
0
def random_film_to_rate(request):
    """
        Widget for main page (for not logged in users)
        displaying a film to rate, selected from
        the list of 10 most popular films.
    """

    user = request.user
    
    if user.is_authenticated():
        film = Film.get_next_film_to_rate(user)
    else:
        key = cache.Key("popular_films_list")

        popular_films = cache.get(key)

        if popular_films is None:
            fhelper = FilmHelper()
            lang = getattr(settings, 'LANGUAGE_CODE', 'en')
            if lang == 'en':
                popular_films = fhelper.get_popular_films(exclude_nonEnglish=True)
            else:
                popular_films = fhelper.get_popular_films()
            cache.set(key, popular_films)

        film = popular_films and random.choice(popular_films) or None

    return {
        'film': film, 
    }
Esempio n. 9
0
def film_user_rating(context, film, user, type='SIMPLE'):
    R_TYPES = dict(Rating.ALL_RATING_TYPES)

    key = cache.Key(film, user, type)
    ratings = cache.get(key)

    simple = True
    if type == 'DETAILED':
        simple = False

    if not ratings:
            if type == 'DETAILED':
                ratings = Rating.objects.filter(film=film.id,
                        user=user, type__in=R_TYPES.keys(), rating__isnull=False).order_by('type').values('rating', 'type')
            else:
                ratings = Rating.objects.filter(film=film.id,
                        user=user, type=Rating.TYPE_FILM,
                        rating__isnull=False).values('rating', 'type')

            for rate in ratings:
                rate['desc'] = R_TYPES[rate['type']]

            cache.set(key, ratings)

    return {
        'film':film,
        'ratings':ratings,
        'simple': simple,
    }
Esempio n. 10
0
def film_user_rating(context, film, user, type='SIMPLE'):
    R_TYPES = dict(Rating.ALL_RATING_TYPES)

    key = cache.Key(film, user, type)
    ratings = cache.get(key)

    simple = True
    if type == 'DETAILED':
        simple = False

    if not ratings:
        if type == 'DETAILED':
            ratings = Rating.objects.filter(
                film=film.id,
                user=user,
                type__in=R_TYPES.keys(),
                rating__isnull=False).order_by('type').values(
                    'rating', 'type')
        else:
            ratings = Rating.objects.filter(film=film.id,
                                            user=user,
                                            type=Rating.TYPE_FILM,
                                            rating__isnull=False).values(
                                                'rating', 'type')

        for rate in ratings:
            rate['desc'] = R_TYPES[rate['type']]

        cache.set(key, ratings)

    return {
        'film': film,
        'ratings': ratings,
        'simple': simple,
    }
Esempio n. 11
0
    def threaded_messages(self, user):
        cache_key = "conversation_thread_%s" % self.pk
        thread = cache.get(cache_key)
        if thread is not None:
            return thread
        query = self.messages.order_by('id')
        messages = {}
        root = None
        for msg in query:
            msg.children = []
            messages[msg.id] = msg    
            if msg.parent_msg_id:
                parent = messages.get(msg.parent_msg_id)
                if parent:
                     msg.level = parent.level + 1
                     parent.children.append(msg)
            else:
                msg.level = 0
                root = msg

	def traverse(root):
	    yield root
	    for c in root.children:
	        for i in traverse(c):
	            yield i

        def not_deleted(msg):
            return msg.sender_id == user.id and msg.sender_deleted_at is None or \
                   msg.recipient_id == user.id and msg.recipient_deleted_at is None
            
        thread = root and list(traverse(root)) or ()
        thread = filter(not_deleted, thread)
        cache.set(cache_key, thread)
        return thread
Esempio n. 12
0
def film_similar_ratings(request, film=None):
    user = request.user
    film = film or get_object_or_404(Film, id=request.GET.get('film_id'))
    ratings = ()
    if user.is_authenticated():
        key = cache.Key("film_similar_ratings", film, user)
        ratings = cache.get(key)
        if ratings is None:
            N_SIMILAR = 100
            N = 5
            query = User.objs.similar(user)[:N_SIMILAR]
            similar_users = cache_query(query, "similar_users", user)
            if similar_users:
                d = dict((u.id, u) for u in similar_users)
                ratings = Rating.objects.select_related()
                ratings = list(ratings.film(film).filter(user__in=d.keys()))
                ratings = sorted(ratings, key=lambda r: d[r.user_id].score)[:N]
                logger.debug("%d of %d similar friends rated this film",
                             len(ratings), N_SIMILAR)
                if len(ratings) < N:
                    logger.debug("not enough results, executing full query")
                    ratings = Rating.objects.select_related()
                    ratings = ratings.film(film).similar_ratings(user)[0:N]
                    logger.debug("similar ratings fetched")
            cache.set(key, ratings)
    link = film.get_absolute_url()
    link = str(link) + '?u=similar'
    return {
        'film': film,
        'title': _("Similar users ratings"),
        'link': link,
        'ratings': ratings,
        'friends': False
    }
Esempio n. 13
0
 def get(cls, **kw):
     key = cls._create_key(**kw)
     obj = cache.get(key)
     if obj is None:
         obj = cls.objects.get(**kw)
         cache.set(key, obj)
     return obj
Esempio n. 14
0
def film_screenings(film, date, channels=None, days=1, past=False, type=None):
    channels = channels or []
    date = date.replace(tzinfo=None)
    to_date = date + datetime.timedelta(days=days)
    key = cache.Key("film_screenings", film.pk or film.title, date, to_date, channels, type)
    screenings = cache.get(key)
    if screenings is None:
        if film.pk:
            q = Screening.objects.filter(film__film=film, utc_time__gte=date, utc_time__lt=to_date)\
                                  .order_by('channel', 'utc_time')
        else:
            q = Screening.objects.filter(film__title=film.title, utc_time__gte=date, utc_time__lt=to_date)\
                                  .order_by('channel', 'utc_time')

        q = q.filter(channel__in=channels)
        if type:
            q = q.filter(channel__type=type)
        
        q = q.select_related('film', 'film__film', 'channel')

        screenings = dict( (c, list(v)) for (c, v) in groupby(q, lambda s:s.channel) )
        if channels:
            screenings = list( (c, screenings[c]) for c in channels if c in screenings )
        else:
            channels = sorted(screenings.keys(), key=lambda c:c.name)
            screenings = list( (c, screenings[c]) for c in channels )
        cache.set(key, screenings)
    return screenings
Esempio n. 15
0
 def in_town(self, town):
     key = cache.Key("town_theaters", town)
     channels = cache.get(key)
     if channels is None:
         channels = self.theaters().filter(town=town).order_by('name')
         channels = list(channels.select_related('town'))
         cache.set(key, channels)
     return channels
Esempio n. 16
0
 def _tagged_film_ids(cls, tags):
     key = cache.Key('tagged_films', tags)
     ids = cache.get(key)
     if ids is None:
         ids = set(Film.objects.tagged(tags).values_list('id', flat=True))
         logger.info("%s ids: %r", tags, ids)
         cache.set(key, ids)
     return ids
Esempio n. 17
0
 def _tagged_film_ids(cls, tags):
     key = cache.Key('tagged_films', tags)
     ids = cache.get(key)
     if ids is None:
         ids = set(Film.objects.tagged(tags).values_list('id', flat=True))
         logger.info("%s ids: %r", tags, ids)
         cache.set(key, ids)
     return ids
Esempio n. 18
0
 def in_town(self, town):
     key = cache.Key("town_theaters", town)
     channels = cache.get(key)
     if channels is None:
         channels = self.theaters().filter(town=town).order_by('name')
         channels = list(channels.select_related('town'))
         cache.set(key, channels)
     return channels
Esempio n. 19
0
 def unread_counter(self, user):
     key = cache.Key("conversation_unread_counter", user.id)
     cnt = cache.get(key)
     if cnt is None:
         query = self.filter(models.Q(sender=user, sender_cnt__gt=0, sender_unread_cnt__gt=0) | \
                             models.Q(recipient=user, recipient_cnt__gt=0, recipient_unread_cnt__gt=0))
         cnt = query.distinct().count()
         cache.set(key, cnt)
     return cnt
Esempio n. 20
0
 def unread_counter(self, user):
     key = cache.Key("conversation_unread_counter", user.id)
     cnt = cache.get(key)
     if cnt is None:
         query = self.filter(models.Q(sender=user, sender_cnt__gt=0, sender_unread_cnt__gt=0) | \
                             models.Q(recipient=user, recipient_cnt__gt=0, recipient_unread_cnt__gt=0))
         cnt = query.distinct().count()
         cache.set(key, cnt)
     return cnt
Esempio n. 21
0
 def get_main_related_film(self):
     cache_key = cache.Key('film_related', self.permalink)
     self.main_related_film = cache.get(cache_key)
     if not self.main_related_film:
         all_related_films= Film.objects.filter(id__in=self.related_film.all())
         if all_related_films:
             if len(all_related_films) == 1:
                 self.main_related_film = all_related_films[0]
         cache.set(cache_key, self.main_related_film)
     return self.main_related_film
Esempio n. 22
0
 def default_tv(self, country_code):
     key = cache.Key("default_tv", country_code)
     ret = cache.get(key)
     if ret is None:
         if country_code not in settings.COUNTRIES_WITH_SHOWTIMES:
             ret = ()
         else:
             ret = list(self.tv().filter(country__code=country_code, is_active=True, is_default=True))
         cache.set(key, ret)
     return ret
Esempio n. 23
0
def top_personalized_recommendations(request):
    user = request.user
    has_location = user.is_authenticated() and user.get_profile().has_location(
    )

    cinema_films = []
    tv_films = []

    today = get_today(request.timezone)
    a_day = datetime.timedelta(days=1)

    key = cache.Key("top_personalized_recommendations", today, request.user)

    films = cache.get(key)
    if films is None:
        cinemas = showtimes_helper.get_theaters(request)
        tvs = showtimes_helper.get_tv_channels(request)

        # How many days ahead we want to check
        PERSONALIZED_CINEMA_DAYS = settings.PERSONALIZED_CINEMA_DAYS
        PERSONALIZED_TV_DAYS = settings.PERSONALIZED_TV_DAYS
        # How many films we want to get
        PERS_CINEMA_NUMBER = settings.PERSONALIZED_CINEMA_FILMS_NUMBER
        PERS_TV_NUMBER = settings.PERSONALIZED_TV_FILMS_NUMBER

        # We get films sorted by personal taste of user
        if cinemas:
            cinema_films = showtimes_helper.collect_unique_films(
                today,
                cinemas,
                PERS_CINEMA_NUMBER,
                settings.PERSONALIZED_CINEMA_DAYS,
                user=user)

        if tvs:
            tv_films = showtimes_helper.collect_unique_films(
                today,
                tvs,
                PERS_TV_NUMBER,
                settings.PERSONALIZED_TV_DAYS,
                user=user)

        films = (cinema_films, tv_films)
        cache.set(key, films)

    (cinema_films, tv_films) = films

    display = (not has_location) | bool(tv_films) | bool(cinema_films)

    return {
        'display': display,
        'has_location': has_location,
        'tv_films': tv_films,
        'cinema_films': cinema_films,
    }
Esempio n. 24
0
def _user_film_recommendations(user, ids):
    if not ids:
        return {}
    ids = sorted(ids)
    key = cache.Key("user_recommendations", user, ids)
    recommendations = cache.get(key)
    if recommendations is None:
        recommendations = dict((r.film_id, r.guess_rating_alg2)
                for r in Recommendation.objects.filter(user=user, film__in=ids))
        cache.set(key, recommendations)
    return recommendations
Esempio n. 25
0
 def get_main_related_film(self):
     cache_key = cache.Key('film_related', self.permalink)
     self.main_related_film = cache.get(cache_key)
     if not self.main_related_film:
         all_related_films = Film.objects.filter(
             id__in=self.related_film.all())
         if all_related_films:
             if len(all_related_films) == 1:
                 self.main_related_film = all_related_films[0]
         cache.set(cache_key, self.main_related_film)
     return self.main_related_film
Esempio n. 26
0
 def iterator(self):
     items = super(QuerySet, self).iterator()
     cache_prefix, cache_timeout = getattr(self, 'cache_params', (None, None))
     cache_key = self._make_key()
     
     if cache_key:
         result = cache.get(cache_key)
         if result is None:
             result = list(items)
             cache.set(cache_key, result, cache_timeout)
         items = iter(result)
     return self.postprocess_query(items)
Esempio n. 27
0
 def user_basket(cls, user):
     if not hasattr(user, '_basket'):
         key = cache.Key("user_basket", user)
         user._basket = cache.get(key)
         if user._basket is None:
             basket = BasketItem.objects.filter(user=user)\
                     .filter(Q(wishlist__isnull=False) | Q(owned__isnull=False))
             user._basket = dict(
                     (b.film_id, (b.wishlist, b.owned)) for b in basket
             )
             cache.set(key, user._basket)
     return user._basket
Esempio n. 28
0
 def default_tv(self, country_code):
     key = cache.Key("default_tv", country_code)
     ret = cache.get(key)
     if ret is None:
         if country_code not in settings.COUNTRIES_WITH_SHOWTIMES:
             ret = ()
         else:
             ret = list(self.tv().filter(country__code=country_code,
                                         is_active=True,
                                         is_default=True))
         cache.set(key, ret)
     return ret
Esempio n. 29
0
def related_articles(activity, user):
    """ Displays list of related articles """

    MAX_RELATED_ARTICLES = getattr(settings, 'MAX_RELATED_ARTICLES')

    key = cache.Key("related_posts", activity)
    related_posts = cache.get(key)
    if not related_posts:
        related_posts = get_related_posts(activity, user, MAX_RELATED_ARTICLES)
        cache.set(key, related_posts, cache.A_DAY)

    return {'related_posts': related_posts}
Esempio n. 30
0
 def get_town_films(cls, town_id, date, to_date, tags=None):
     extra = tags and (tags,) or ()
     key = cache.Key("showtimes_town_films", date, to_date, town_id, *extra)
     films = cache.get(key)
     if films is None:
         s = cls.get_screenings(date, to_date, tags)
         s = s.filter(channel__type=1)
         s = list(s.filter(channel__town=town_id))
         films = cls._get_films(s)
         timeout = not s and settings.SHOWTIMES_EMPTY_CACHE_TIMEOUT or None
         cache.set(key, films, timeout)
     return films
Esempio n. 31
0
 def get_similar_users_list(self, request):
     users = []
     if request.user.is_authenticated():
         key = cache.Key('similar_users_list', request.user)
         similar_users_list = cache.get(key)
         if not similar_users_list:
             similar_users_list = RatingComparator.objects.filter(main_user=request.user, score__lte=SIMILAR_USER_LEVEL).select_related('user')
             cache.set(key, similar_users_list)
         if similar_users_list:
             for similar_user in similar_users_list:
                 users.append(similar_user.compared_user)
     return users
Esempio n. 32
0
def related_articles(activity, user):
    """ Displays list of related articles """

    MAX_RELATED_ARTICLES = getattr(settings, 'MAX_RELATED_ARTICLES')

    key = cache.Key("related_posts", activity)
    related_posts = cache.get(key)
    if not related_posts:
        related_posts = get_related_posts(activity, user, MAX_RELATED_ARTICLES)
        cache.set(key, related_posts, cache.A_DAY)

    return {'related_posts': related_posts}
Esempio n. 33
0
 def get_town_films(cls, town_id, date, to_date, tags=None):
     extra = tags and (tags, ) or ()
     key = cache.Key("showtimes_town_films", date, to_date, town_id, *extra)
     films = cache.get(key)
     if films is None:
         s = cls.get_screenings(date, to_date, tags)
         s = s.filter(channel__type=1)
         s = list(s.filter(channel__town=town_id))
         films = cls._get_films(s)
         timeout = not s and settings.SHOWTIMES_EMPTY_CACHE_TIMEOUT or None
         cache.set(key, films, timeout)
     return films
Esempio n. 34
0
 def __init__(self, country_code, show_nearby, *args, **kw):
     super(SelectTownForm, self).__init__(*args, **kw)
     key = cache.Key("country_towns", country_code)
     if country_code in settings.COUNTRIES_WITH_SHOWTIMES:
         self.towns = cache.get(key)
         if not self.towns:
             self.towns = Town.objects_with_cinemas.filter(country__code=country_code)
             cache.set(key, self.towns)
     else:
         self.towns = ()
     choices = show_nearby and [('', _('Nearby'))] or []
     choices.extend((t.id, t.name) for t in self.towns)
     self.fields['city'].choices = choices
Esempio n. 35
0
def top_recommendations_all(context, films_number=4):
    """
        Displays user's top recommended movies
        (most popular for not logged in).
    """
    POPULAR_FILMS_NUMBER_ALL = getattr(settings,
                                       'POPULAR_FILMS_MAIN_PAGE_NUMBER_ALL')

    user = context.get('recommendations_user', context['request'].user)
    key = cache.Key("popular_films_main_page", user)

    films = cache.get(key)
    if (not films) or len(films) < films_number:

        key_all = cache.Key("popular_films_main_page_all", user)
        all_films = cache.get(key_all)
        if not all_films:
            has_recommendations = user.is_authenticated() and \
                    user.get_profile().recommendations_status
            if has_recommendations:
                recom_helper = RecomHelper()
                all_films = list(
                    recom_helper.get_best_psi_films_queryset(user)
                    [:POPULAR_FILMS_NUMBER_ALL])
            else:
                fhelper = FilmHelper()
                all_films = list(
                    fhelper.get_popular_films(
                        number_of_films=POPULAR_FILMS_NUMBER_ALL,
                        exclude_nonEnglish=True))

            cache.set(key_all, all_films, cache.A_MONTH)

        # Select random few films
        random.shuffle(all_films)
        films = all_films[:films_number]
        cache.set(key, films, cache.A_QUARTER)

    return films[:films_number]
Esempio n. 36
0
    def iterator(self):
        items = super(QuerySet, self).iterator()
        cache_prefix, cache_timeout = getattr(self, 'cache_params',
                                              (None, None))
        cache_key = self._make_key()

        if cache_key:
            result = cache.get(cache_key)
            if result is None:
                result = list(items)
                cache.set(cache_key, result, cache_timeout)
            items = iter(result)
        return self.postprocess_query(items)
Esempio n. 37
0
def top_recommendations_all(context, films_number=4):
    """
        Displays user's top recommended movies
        (most popular for not logged in).
    """
    POPULAR_FILMS_NUMBER_ALL = getattr(settings,
            'POPULAR_FILMS_MAIN_PAGE_NUMBER_ALL')

    user = context['request'].user
    key = cache.Key("popular_films_main_page", user)

    films = cache.get(key)
    if (not films) or len(films) < films_number:

        key_all = cache.Key("popular_films_main_page_all", user)
        all_films = cache.get(key_all)
        if not all_films:
            has_recommendations = user.is_authenticated() and \
                    user.get_profile().recommendations_status
            if has_recommendations:
                recom_helper = RecomHelper()
                all_films = list(recom_helper.get_best_psi_films_queryset(
                    user_id = user.id, offset=0,
                    limit=POPULAR_FILMS_NUMBER_ALL))
            else:
                fhelper = FilmHelper()
                all_films = list(fhelper.get_popular_films(
                        number_of_films=POPULAR_FILMS_NUMBER_ALL,
                        exclude_nonEnglish=True))

            cache.set(key_all, all_films, cache.A_MONTH)

        # Select random few films
        random.shuffle(all_films)
        films = all_films[:films_number]
        cache.set(key, films, cache.A_QUARTER)

    return films[:films_number]
Esempio n. 38
0
 def render(self, context):
     key = cache.Key("all-comments-tag", self.object.resolve(context))
     query = cache.get(key)
     if query is None:
         query = ThreadedComment.objects.select_related().\
                 filter(object_id=self.object.resolve(context),
                        status=ThreadedComment.PUBLIC_STATUS).\
                 order_by('date_submitted')
         cache.set(key, query)
         context[self.context_name] = query
         return ''
     else:
         context[self.context_name] = query
         return ''
Esempio n. 39
0
 def __init__(self, country_code, show_nearby, *args, **kw):
     super(SelectTownForm, self).__init__(*args, **kw)
     key = cache.Key("country_towns", country_code)
     if country_code in settings.COUNTRIES_WITH_SHOWTIMES:
         self.towns = cache.get(key)
         if not self.towns:
             self.towns = Town.objects_with_cinemas.filter(
                 country__code=country_code)
             cache.set(key, self.towns)
     else:
         self.towns = ()
     choices = show_nearby and [('', _('Nearby'))] or []
     choices.extend((t.id, t.name) for t in self.towns)
     self.fields['city'].choices = choices
Esempio n. 40
0
 def get_checkins(self):
     date = self.utc_time.date()
     to_date = date + datetime.timedelta(days=1)
     if not hasattr(self, '_checkins'):
         cache_key = cache.Key("checkins", date, self.channel_id)
         self._checkins = cache.get(cache_key)
         if self._checkins is None:
             ss = ScreeningCheckIn.objects.filter(
                      screening__utc_time__gte=date,
                      screening__utc_time__lt=to_date).\
                  order_by('screening__id', 'created_at').select_related('screening', 'user')
             self._checkins = dict((k, list(g)) for k, g in groupby(ss, lambda s:s.screening))
             cache.set(cache_key, self._checkins)
     return self._checkins.get(self, [])
Esempio n. 41
0
 def get_country_tv_films(cls, country_id, date, to_date, tags=None):
     extra = tags and (tags,) or ()
     key = cache.Key("showtimes_country_tv_films", date, to_date, country_id, *extra)
     films = cache.get(key)
     if films is None:
         s = cls.get_screenings(date, to_date, tags)
         s = s.filter(film__film__isnull=False)
         s = s.filter(channel__type=2)
         s = s.filter(film__is_tv_series=False)
         s = list(s.filter(channel__country=country_id))
         films = cls._get_films(s)
         timeout = not s and settings.SHOWTIMES_EMPTY_CACHE_TIMEOUT or None
         cache.set(key, films, timeout)
     return films
Esempio n. 42
0
 def render(self, context):
     key = cache.Key("all-comments-tag", self.object.resolve(context))
     query = cache.get(key)
     if query is None:
         query = ThreadedComment.objects.select_related().\
                 filter(object_id=self.object.resolve(context),
                        status=ThreadedComment.PUBLIC_STATUS).\
                 order_by('date_submitted')
         cache.set(key, query)
         context[self.context_name] = query
         return ''
     else:
         context[self.context_name] = query
         return ''
Esempio n. 43
0
 def selected_by(self, user, type=TYPE_CINEMA):
     if not user.is_authenticated():
         return ()
     profile = user.get_profile()
     if profile.country not in settings.COUNTRIES_WITH_SHOWTIMES:
         return ()
     key = cache.Key("user_channels", user)
     channels = cache.get(key)
     if channels is None:
         channels = Channel.objects.filter(selected_by=user, is_active=True, country__code=profile.country)
         channels = channels.order_by('type', 'userchannel__distance', 'name')
         channels = channels.extra(select={"distance":"showtimes_userchannel.distance"})
         channels = channels.select_related('town')
         cache.set(key, channels)
     return [c for c in channels if (c.type & type)]
Esempio n. 44
0
 def get_country_tv_films(cls, country_id, date, to_date, tags=None):
     extra = tags and (tags, ) or ()
     key = cache.Key("showtimes_country_tv_films", date, to_date,
                     country_id, *extra)
     films = cache.get(key)
     if films is None:
         s = cls.get_screenings(date, to_date, tags)
         s = s.filter(film__film__isnull=False)
         s = s.filter(channel__type=2)
         s = s.filter(film__is_tv_series=False)
         s = list(s.filter(channel__country=country_id))
         films = cls._get_films(s)
         timeout = not s and settings.SHOWTIMES_EMPTY_CACHE_TIMEOUT or None
         cache.set(key, films, timeout)
     return films
Esempio n. 45
0
def top_personalized_recommendations(request):
    user = request.user
    has_location = user.is_authenticated() and user.get_profile().has_location()
    
    cinema_films = []
    tv_films = []
    
    today = get_today(request.timezone)
    a_day = datetime.timedelta(days=1)

    key = cache.Key("top_personalized_recommendations", today, request.user)

    films = cache.get(key)
    if films is None:
        cinemas = showtimes_helper.get_theaters(request)
        tvs = showtimes_helper.get_tv_channels(request)

        # How many days ahead we want to check
        PERSONALIZED_CINEMA_DAYS = settings.PERSONALIZED_CINEMA_DAYS
        PERSONALIZED_TV_DAYS = settings.PERSONALIZED_TV_DAYS
        # How many films we want to get
        PERS_CINEMA_NUMBER = settings.PERSONALIZED_CINEMA_FILMS_NUMBER
        PERS_TV_NUMBER = settings.PERSONALIZED_TV_FILMS_NUMBER

        # We get films sorted by personal taste of user
        if cinemas:
            cinema_films = showtimes_helper.collect_unique_films(
                    today, cinemas, PERS_CINEMA_NUMBER, 
                    settings.PERSONALIZED_CINEMA_DAYS, user=user)

        if tvs:
            tv_films = showtimes_helper.collect_unique_films(
                    today, tvs, PERS_TV_NUMBER, 
                    settings.PERSONALIZED_TV_DAYS, user=user)
        
        films = (cinema_films, tv_films)
        cache.set(key, films)
    
    (cinema_films, tv_films) = films

    display = (not has_location) | bool(tv_films) | bool(cinema_films)

    return {
        'display': display,
        'has_location': has_location,
        'tv_films': tv_films,
        'cinema_films': cinema_films,
    }
Esempio n. 46
0
def random_top_movie():
    """Displays some random popular movie on Filmaster."""

    key = cache.Key("popular_films")
    popular_films = cache.get(key)
    if popular_films is None:
        # Get most popular films
        fhelper = FilmHelper()
        popular_films = list(fhelper.get_popular_films(
            exclude_nonEnglish=True))
        cache.set(key, popular_films)
    random.shuffle(popular_films)
    if len(popular_films) > 0:
        return {'movie': popular_films[0]}
    else:
        return {'movie': None}
Esempio n. 47
0
def random_top_movie():
    """Displays some random popular movie on Filmaster."""

    key = cache.Key("popular_films")
    popular_films = cache.get(key)
    if popular_films is None:
        # Get most popular films
        fhelper = FilmHelper()
        popular_films = list(
            fhelper.get_popular_films(exclude_nonEnglish=True))
        cache.set(key, popular_films)
    random.shuffle(popular_films)
    if len(popular_films) > 0:
        return {'movie': popular_films[0]}
    else:
        return {'movie': None}
Esempio n. 48
0
 def get_checkins(self):
     date = self.utc_time.date()
     to_date = date + datetime.timedelta(days=1)
     if not hasattr(self, '_checkins'):
         cache_key = cache.Key("checkins", date, self.channel_id)
         self._checkins = cache.get(cache_key)
         if self._checkins is None:
             ss = ScreeningCheckIn.objects.filter(
                      screening__utc_time__gte=date,
                      screening__utc_time__lt=to_date).\
                  order_by('screening__id', 'created_at').select_related('screening', 'user')
             self._checkins = dict(
                 (k, list(g))
                 for k, g in groupby(ss, lambda s: s.screening))
             cache.set(cache_key, self._checkins)
     return self._checkins.get(self, [])
Esempio n. 49
0
def get_avatar_path(user, size, **kw):
    url = None
    is_username = isinstance(user, basestring)
    
    if settings.CACHE_AVATARS:
        key = cache.Key("avatar", str(user), str(size))
        url = cache.get(key)

        # FLM-694
        if url is not None and not os.path.exists( os.path.join( settings.MEDIA_ROOT, url ) ):
            logger.debug( "cached avatar %s does not exists ! [REMOVING]" % url )
            url = None
            cache.delete(key)

    if not url:
        avatar_path = DEFAULT_AVATAR
        try:
            # if is_username is True, user variable is username as text, used by
            # useractivities
            if is_username:
                avatar = Avatar.objects.get(user__username=user, valid=True).image
            else:
                avatar = Avatar.objects.get(user=user, valid=True).image
            if avatar:
                path = os.path.join(settings.MEDIA_ROOT, unicode(avatar))
                if os.path.isfile(path):
                    avatar_path = path
        except Avatar.DoesNotExist:
            pass
        
        path, ext = os.path.splitext(avatar_path)
        thumb_path = "%s.%s%s" % (path, size, ext)
        valid = True
        if not os.path.isfile(thumb_path):
            try:
                image = Image.open(avatar_path)
                image.thumbnail((size, size), Image.ANTIALIAS)
                image.save(thumb_path, "JPEG")
                logger.debug("new avatar generated: %s", thumb_path)
            except IOError, e:
                logger.warning(e)
                valid = False
        url = thumb_path.replace(settings.MEDIA_ROOT, '')
        # eventually cache (if caching allowed)
        if settings.CACHE_AVATARS and valid and url:
            cache.set(key, url)
            logger.debug("Storing avatar in cache under %s" % key)
Esempio n. 50
0
def top_recommendations_cinema(context, films_number=4):
    """
        Displays user's top recommended movies in cinemas
        (most popular for not logged in).
    """

    request = context['request']
    user = request.user

    key = cache.Key("cinema_user_recommended", user)
    films = cache.get(key)
    if films is None:
        channels = get_theaters(request)
        now = get_today(request.timezone)
        films = collect_unique_films(now, channels, films_number, days=3, user=user)
        cache.set(key, films)
    return films
Esempio n. 51
0
def comment_form_url(activity, app_label, model):
    """
        Returns url planet comment form
    """

    key = cache.Key("planet-comment-form", app_label, model)
    content_type = cache.get(key)

    if content_type is None:
        content_type = ContentType.objects.get(app_label=app_label, model=model).id
        cache.set(key, content_type)

    kwargs = {
        'content_type' : content_type,
        'object_id' : activity.object_id,
    }

    return reverse('tc_comment', kwargs=kwargs)
Esempio n. 52
0
def users_shitlist(user):
    """ Displays on sidebar, movies user doesn't want to watch."""

    key = cache.Key("user_shitlist_sidebar", user)
    movies = cache.get(key)
    NUMBER_OF_MOVIES_SHITLIST_SIDEBAR = \
            getattr(settings, 'NUMBER_OF_MOVIES_SHITLIST_SIDEBAR')

    if not movies:
        movies = [item.film for item in BasketItem.objects.filter(user=user,
                wishlist=BasketItem.NOT_INTERESTED)\
                [:NUMBER_OF_MOVIES_SHITLIST_SIDEBAR + 1]]
        cache.set(key, movies, 3 * cache.CACHE_HOUR)

    show_more = len(movies) == NUMBER_OF_MOVIES_SHITLIST_SIDEBAR + 1
    movies = movies[:NUMBER_OF_MOVIES_SHITLIST_SIDEBAR]

    return {'movies': movies, 'show_more': show_more, 'act_user': user}
Esempio n. 53
0
def users_shitlist(user):
    """ Displays on sidebar, movies user doesn't want to watch."""

    key = cache.Key("user_shitlist_sidebar", user)
    movies = cache.get(key)
    NUMBER_OF_MOVIES_SHITLIST_SIDEBAR = \
            getattr(settings, 'NUMBER_OF_MOVIES_SHITLIST_SIDEBAR')

    if not movies:
        movies = [item.film for item in BasketItem.objects.filter(user=user,
                wishlist=BasketItem.NOT_INTERESTED)\
                [:NUMBER_OF_MOVIES_SHITLIST_SIDEBAR + 1]]
        cache.set(key, movies, 3 * cache.CACHE_HOUR)

    show_more = len( movies ) == NUMBER_OF_MOVIES_SHITLIST_SIDEBAR + 1
    movies = movies[:NUMBER_OF_MOVIES_SHITLIST_SIDEBAR]

    return {'movies': movies, 'show_more': show_more, 'act_user': user }
Esempio n. 54
0
def users_best_rated(user):
    """Displays user's top rated movies."""

    cache_key = cache.Key("profile_page_best_films", user)
    best_movies = cache.get(cache_key)
    NUMBER_OF_USER_BEST_FILMS = \
            getattr(settings, 'NUMBER_OF_USER_BEST_FILMS')
    
    if not best_movies:
        fhelper = FilmHelper()
        best_movies = fhelper.get_users_best_films(user,
                NUMBER_OF_USER_BEST_FILMS + 1)
        cache.set(cache_key, best_movies)

    show_more = len( best_movies ) == NUMBER_OF_USER_BEST_FILMS + 1
    best_movies = best_movies[:NUMBER_OF_USER_BEST_FILMS]

    return {'movies': best_movies, 'show_more': show_more, 'act_user': user }
Esempio n. 55
0
def users_best_rated(user):
    """Displays user's top rated movies."""

    cache_key = cache.Key("profile_page_best_films", user)
    best_movies = cache.get(cache_key)
    NUMBER_OF_USER_BEST_FILMS = \
            getattr(settings, 'NUMBER_OF_USER_BEST_FILMS')

    if not best_movies:
        fhelper = FilmHelper()
        best_movies = fhelper.get_users_best_films(
            user, NUMBER_OF_USER_BEST_FILMS + 1)
        cache.set(cache_key, best_movies)

    show_more = len(best_movies) == NUMBER_OF_USER_BEST_FILMS + 1
    best_movies = best_movies[:NUMBER_OF_USER_BEST_FILMS]

    return {'movies': best_movies, 'show_more': show_more, 'act_user': user}
Esempio n. 56
0
 def selected_by(self, user, type=TYPE_CINEMA):
     if not user.is_authenticated():
         return ()
     profile = user.get_profile()
     if profile.country not in settings.COUNTRIES_WITH_SHOWTIMES:
         return ()
     key = cache.Key("user_channels", user)
     channels = cache.get(key)
     if channels is None:
         channels = Channel.objects.filter(selected_by=user,
                                           is_active=True,
                                           country__code=profile.country)
         channels = channels.order_by('type', 'userchannel__distance',
                                      'name')
         channels = channels.extra(
             select={"distance": "showtimes_userchannel.distance"})
         channels = channels.select_related('town')
         cache.set(key, channels)
     return [c for c in channels if (c.type & type)]
Esempio n. 57
0
def top_recommendations_cinema(context, films_number=4):
    """
        Displays user's top recommended movies in cinemas
        (most popular for not logged in).
    """

    request = context['request']
    user = context.get('recommendations_user', context['request'].user)

    key = cache.Key("cinema_user_recommended", user)
    films = cache.get(key)
    if films is None:
        channels = get_theaters(request)
        now = get_today(request.timezone)
        films = collect_unique_films(now,
                                     channels,
                                     films_number,
                                     days=3,
                                     user=user)
        cache.set(key, films)
    return films