Esempio n. 1
0
def bbsIndex(request):
    ret = {'login_status': False}
    ret, user_obj = loginInfo(request, ret)
    ret['user_info'] = user_obj

    #hot
    ret['hot_posts'] = getHotPost()

    #posts statistics
    board_dict = {
        'movie': ('mp', 'mpr'),
        'tv': ('tp', 'tpr'),
        'anime': ('ap', 'apr'),
        'show': ('sp', 'spr'),
        'notification': ('np', 'npr'),
        'relaxing': ('rp', 'rpr'),
        'feedback': ('fp', 'fpr')
    }
    for board, item in board_dict.items():
        post_count = models.Post.objects.filter(board=board).count()
        reply_count = models.PostReply.objects.filter(
            post__board=board).count()
        ret[item[0]] = post_count
        ret[item[1]] = post_count + reply_count

    return render_to_response('bbs/bbs_index.html',
                              ret,
                              context_instance=RequestContext(request))
Esempio n. 2
0
def topicIndex(request):
    ret = {}
    ret, user_obj = loginInfo(request, ret)
    ret['user_info'] = user_obj
    response = render_to_response('topic/topic_index.html',
                                  ret,
                                  context_instance=RequestContext(request))
    return response
Esempio n. 3
0
def postDetail(request, pid):
    ret = {'login_status': False, 'post': None}
    ret, user_obj = loginInfo(request, ret)
    ret['user_info'] = user_obj
    #post
    post_obj = models.Post.objects.filter(id=pid)
    if not post_obj.count():
        raise Http404
    else:
        old_visit_counts = post_obj[0].visit_counts
        post_obj.update(visit_counts=old_visit_counts + 1)

    ret['post'] = post_obj[0]
    ret['board'] = post_obj[0].board

    #post reply
    post_replies_obj = models.PostReply.objects.filter(
        post__id=pid).order_by('create_date')
    reply_counts = post_replies_obj.count()
    if reply_counts <= 9:
        ret['cur_page'] = 1
    else:
        #分页
        page = try_int(request.GET.get('p', 1), 1)
        ret['cur_page'] = page
        ret['layer_start'] = (page - 1) * 10 + 1  #需在模板中用forloop.counter0
        ret['post_counts'] = reply_counts
        pageObj = html_helper_search.PageInfo(page, reply_counts, 10,
                                              9)  #加1为了使分页加上1楼计算
        print pageObj.start, pageObj.end
        try:
            post_replies_obj = post_replies_obj[pageObj.start:pageObj.end]
        except Exception:
            post_replies_obj = ''
        filter_url = '/bbs/post/%s/?p=' % pid
        page_list = html_helper_search.Pager(page, pageObj.total_page_counts,
                                             filter_url)
        ret['page_list'] = page_list

    #for item in post_replies_obj:
    #item.content = htmlContentFilter(item.content)
    ret['post_replies'] = post_replies_obj
    focused_user_list = []
    if user_obj:
        uid = user_obj.id
        focused_obj = models.UserFocus.objects.filter(
            origin_user_of_focus__id=uid)  #我关注的
        for item in focused_obj:
            focused_user_list.append(item.target_user.id)
        #print focused_user_list
        ret['focused_user_list'] = focused_user_list
    #hot
    ret['hot_posts'] = getHotPost()

    return render_to_response('bbs/bbs_post_detail.html',
                              ret,
                              context_instance=RequestContext(request))
Esempio n. 4
0
def shadowsocks(request):
    ret = {'logined': False, 'ss_running': False}
    ret, user_obj = loginInfo(request, ret)
    ret['user_info'] = user_obj
    obj = _get_ss_info()
    ret['server'] = obj.get('server')
    ret['port'] = obj.get('server_port')
    if _ss_is_running(ret['port']):
        ret['ss_running'] = True
    return render(
        request,
        'tools/shadowsocks.html',
        ret,
    )
Esempio n. 5
0
def newsIndex(request):
    ret = {'logined': False}
    ret, user_obj = loginInfo(request, ret)
    ret['user_info'] = user_obj

    ret['slider'] = models.News_Index_Slider.objects.all().order_by(
        '-create_date')[:5]

    ret['recommend'] = models.News.objects.filter(
        recommended=True).order_by('-create_date')[:9]

    news_list = models.News.objects.all().order_by('-create_date')[:12]
    ret['news_list'] = news_list

    return render_to_response('news/news_index.html',
                              ret,
                              context_instance=RequestContext(request))
Esempio n. 6
0
def boardIndex(request):
    ret = {'login_status': False}
    ret, user_obj = loginInfo(request, ret)
    ret['user_info'] = user_obj
    b = request.GET.get('b', None)
    page = try_int(request.GET.get('p', 1), 1)
    #board
    b_list = [
        'movie', 'tv', 'anime', 'show', 'notification', 'feedback', 'relaxing'
    ]
    if not b in b_list:
        raise Http404
        #return render_to_response('404.html')
    else:
        ret['board'] = b

    # 计数,排序
    posts_obj = models.Post.objects.filter(
        board=b).order_by('-last_replied_date')
    post_counts = posts_obj.count()
    ret['post_counts'] = post_counts

    #分页
    pageObj = html_helper.PageInfo(page, post_counts, 20)
    try:
        posts_obj = posts_obj[pageObj.start:pageObj.end]
    except Exception:
        posts_obj = ''

    ret['posts'] = posts_obj

    filter_url = '/bbs/board/?b=%s&p=' % b
    page_list = html_helper.Pager(page, pageObj.total_page_counts, filter_url)
    ret['page_list'] = page_list

    #hot
    ret['hot_posts'] = getHotPost()

    return render_to_response('bbs/bbs_board_index.html',
                              ret,
                              context_instance=RequestContext(request))
Esempio n. 7
0
def tvDetail(request, *args, **kwargs):
    ret = {'logined': False, 'user_info': '', 'has_rated': False}
    ret, user_obj = loginInfo(request, ret)
    ret['user_info'] = user_obj
    if user_obj:
        uid = user_obj.id

    #右侧边栏
    billboard1 = models.Tv.objects.all().order_by('-week_visit_count')[0]
    billboard2 = models.Tv.objects.all().order_by('-week_visit_count')[1:10]
    ret['billboard1'] = billboard1
    if not path.exists(BASE_DIR + ret['billboard1'].poster):
        ret['billboard1'].poster = '/static/images/default/poster/p_200x284.png'
    ret['billboard2'] = billboard2
    for item in ret['billboard2']:
        if not path.exists(BASE_DIR + item.poster):
            item.poster = '/static/images/default/poster/p_200x284.png'

    #电视剧信息
    tid = args[0]
    ret['tid'] = tid
    try:
        tv_obj = models.Tv.objects.get(id=tid)
    except Exception:
        raise Http404
        #return render_to_response('404.html')

    tv_obj.visit_count += 1
    tv_obj.week_visit_count += 1
    tv_obj.month_visit_count += 1
    tv_obj.save()

    ret['detail'] = movie_helper.replaceWrongImg([tv_obj], 'ps')[0]

    down_list = []
    if tv_obj.down_urls and not tv_obj.down_urls == '无下载':
        name_list = tv_obj.down_names.splitlines()
        url_list = tv_obj.down_urls.splitlines()
        for i in range(len(name_list)):
            try:
                down_list.append([name_list[i], url_list[i]])
            except IndexError:
                break

        ret['urls'] = down_list
        print down_list[0]
    else:
        ret['urls'] = None

    #ret['face_id'] = str(randint(1,11))   #卡通头像文件名编号

    reply_obj = models.TvReply.objects.filter(
        tv__id=tid).order_by('-create_date')
    reply_counts = tv_obj.tv_r.all().count()
    ret['reply_counts'] = reply_counts
    ret['reply'] = reply_obj

    #判断是否已评过分
    if user_obj:
        has_rated = models.TvReply.objects.filter(tv__id=tid,
                                                  user__id=user_obj.id,
                                                  rating__gt=0)
        has_rated_counts = has_rated.count()
        if has_rated_counts == 1:
            ret['has_rated'] = True
            ret['cur_user_rating'] = has_rated[0].rating
        elif has_rated_counts > 1:
            ret['has_rated'] = 'error'

    #收藏
    if user_obj:
        collect_obj = models.Collect_Tv.objects.filter(tv__id=tid,
                                                       user__id=uid)
        if collect_obj:
            ret['collected'] = True
    '''
        猜你喜欢
    '''
    all_tv_obj = models.Tv.objects.exclude(id=tid)
    tv_related_obj = movie_helper.relatedMovies(tv_obj, all_tv_obj)
    ret['related'] = movie_helper.replaceWrongImg(tv_related_obj, 'p')

    #标签云
    tags_obj = models.Tv.objects.all().order_by('-week_visit_count').values(
        'id', 'ch_name', 'director', 'actor')[:50]
    da_dict, mn_list = movie_helper.tagsCloud(tags_obj, 'tv')
    ret['da_dict'] = json.dumps(da_dict)
    ret['mn_list'] = json.dumps(mn_list)
    response = render_to_response('tv/tv_detail.html',
                                  ret,
                                  context_instance=RequestContext(request))

    #cookie
    if user_obj:
        response.set_cookie('logined', 'yes')
    else:
        response.set_cookie('logined', 'no')
    return response
Esempio n. 8
0
def tvIndex(request, *args, **kwargs):
    ret = {
        'logined': False,
        'show': '',
        'pagelist': '',
        'search_ok': False,
        'counts': 0
    }
    #判断用户是否登录,获取用户信息
    ret, user_obj = loginInfo(request, ret)
    ret['user_info'] = user_obj
    bill_obj = models.Tv.objects.all().order_by('-week_visit_count')
    billboard1 = bill_obj[0]
    billboard2 = bill_obj[1:10]
    ret['billboard1'] = billboard1
    if not path.exists(BASE_DIR + ret['billboard1'].poster):
        ret['billboard1'].poster = '/static/images/default/poster/p_200x284.png'
    ret['billboard2'] = billboard2
    for item in ret['billboard2']:
        if not path.exists(BASE_DIR + item.poster):
            item.poster = '/static/images/default/poster/p_200x284.png'
    '''
    内容显示及分页
    '''

    page = try_int(request.GET.get('p', 1), 1)
    target_focus = request.GET.get('focus', 'af')
    target_type = request.GET.get('type', 'at')
    target_region = request.GET.get('region', 'ar')

    #type
    if target_type == 'at':
        type_result = models.Tv.objects.all()
    else:
        typedict = {
            'juqing': '剧情',
            'xiju': '喜剧',
            'aiqing': '爱情',
            'qihuan': '奇幻',
            'guzhuang': '古装',
            'dongzuo': '动作',
            'maoxian': '冒险',
            'kehuan': '科幻',
            'xuanyi': '悬疑',
            'jingsong': '惊悚',
            'kongbu': '恐怖',
            'fanzui': '犯罪',
            'zhanzheng': '战争',
            'donghua': '动画',
            'jilupian': '纪录片',
            'tongxing': '同性',
            'qingse': '情色',
            'jiating': '家庭',
            'ertong': '儿童',
            'lishi': '历史',
            'yundong': '运动',
            'zhuanji': '传记'
        }
        for item in typedict:
            if target_type == item:
                type_result = models.Tv.objects.filter(
                    types__contains=typedict[item])
        if not 'type_result' in dir():
            raise Http404
            return render_to_response('404.html')

    #region
    if target_region == 'ar':
        region_result = type_result

    elif target_region == 'otherregion':
        region_result = type_result.exclude(
            Q(region__contains='中国大陆') | Q(region__contains='香港')
            | Q(region__contains='台湾') | Q(region__contains='美国')
            | Q(region__contains='英国') | Q(region__contains='法国')
            | Q(region__contains='日本') | Q(region__contains='韩国')
            | Q(region__contains='泰国') | Q(region__contains='印度'))
    else:
        regiondict = {
            'mainland': '中国大陆',
            'hongkong': '香港',
            'taiwan': '台湾',
            'america': '美国',
            'uk': '英国',
            'french': '法国',
            'japan': '日本',
            'korea': '韩国',
            'thailand': '泰国',
            'india': '印度'
        }

        for item in regiondict:
            if target_region == item:
                region_result = type_result.filter(
                    region__contains=regiondict[item])
        #print region_result_tv
        if not 'region_result' in dir():
            raise Http404
            return render_to_response('404.html')

    #focus
    if target_focus == 'af':
        focus_result = region_result.filter().order_by('-release_date')
    elif target_focus == 'guonei':
        focus_result = region_result.filter(
            release_date_show__contains='中国').exclude(
                score=0).order_by('-release_date')
    elif target_focus == 'guowai':
        focus_result = region_result.exclude(
            Q(release_date_show__contains='中国')
            | Q(score=0)).order_by('-release_date')
    elif target_focus == 'gaofen':
        focus_result = region_result.filter(score__gte=8).order_by('-score')
    elif target_focus == 'gengxin':
        focus_result = region_result.all().order_by('-create_date')
    elif target_focus == 'not_released':
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        focus_result = region_result.filter(
            release_date__gt=today).order_by('release_date')
    if not 'focus_result' in dir():
        raise Http404
        return render_to_response('404.html')
    items_per_page = try_int(request.COOKIES.get('page_num', 20), 20)
    try:
        all_item_counts = focus_result.count()
    except Exception:
        all_item_counts = 0
    ret['counts'] = all_item_counts

    pageObj = html_helper.PageInfo(page, all_item_counts, items_per_page)

    try:
        final_result = focus_result[pageObj.start:pageObj.end]
    except Exception:
        final_result = ''
    filter_url = '/tv/?focus=' + target_focus + '&type=' + target_type + '&region=' + target_region + '&p='
    page_list = html_helper.Pager(page, pageObj.total_page_counts, filter_url)

    #popular
    popular_id_list = []
    popular = bill_obj[:30]
    for item in popular:
        popular_id_list.append(item.id)

    #判断图片是否存在,不存在替换为默认图片
    ret['show'] = final_result
    for item in ret['show']:
        if not path.exists(BASE_DIR + item.poster):
            item.poster = '/static/images/default/poster/p_200x284.png'
        for p in popular_id_list:
            if p == item.id:
                item.popular = True

    ret['pages'] = pageObj.total_page_counts

    if pageObj.total_page_counts == 1:
        ret['page_list'] = ''
    elif pageObj.total_page_counts == 0:
        ret['no_result'] = True
    else:
        ret['page_list'] = page_list
    '''
    *标签云
    '''
    tags_obj = models.Tv.objects.all().order_by('-week_visit_count').values(
        'id', 'ch_name', 'director', 'actor')[:50]
    da_dict, mn_list = movie_helper.tagsCloud(tags_obj, 'tv')
    ret['da_dict'] = json.dumps(da_dict)
    ret['mn_list'] = json.dumps(mn_list)

    thumb_switch = request.COOKIES.get('switch', 't1')
    if thumb_switch == 't1':
        response = render_to_response('tv/tv_index.html',
                                      ret,
                                      context_instance=RequestContext(request))
    elif thumb_switch == 't2':
        response = render_to_response('tv/tv_index_t2.html',
                                      ret,
                                      context_instance=RequestContext(request))
    elif thumb_switch == 't3':
        response = render_to_response('tv/tv_index_t3.html',
                                      ret,
                                      context_instance=RequestContext(request))
    response.set_cookie('page_num', items_per_page)
    return response
Esempio n. 9
0
def newstemplate(request, *args):
    ret = {'logined': False}
    ret, user_obj = loginInfo(request, ret)
    ret['user_info'] = user_obj
    nid = args[0]
    try:
        news_obj = models.News.objects.get(id=nid)
    except Exception:
        raise Http404
    ret['news'] = news_obj

    news_obj.visit_count += 1
    news_obj.day_visit_count += 1
    news_obj.week_visit_count += 1
    news_obj.save()

    ret['detail'] = news_obj

    reply_obj = models.NewsReply.objects.filter(
        news__id=nid).order_by('-create_date')
    reply_counts = news_obj.news_r.all().count()
    ret['reply_counts'] = reply_counts
    ret['reply'] = reply_obj
    '''
    文章分页部分
    '''
    #page = try_int(page, 1)
    #news_content = news_obj.news_content
    #ret['news_content'] = news_content
    ret['keywords'] = news_obj.keywords.split()
    keywords_a = []
    for keyword in ret['keywords']:
        keywords_a.append('<a href="/tags/?n=' + keyword + '">' + keyword +
                          '</a>')
        #keywords_a.append(keyword)
    ret['keywords_a'] = keywords_a

    #找出相关电影/电视剧链接
    temp_list = []
    rel_links = re.findall(
        r'<a.*?href=[\'\"](/\w+/\d+/)[\'\""].*?>[^/].*?</a>',
        news_obj.news_content)
    for item in rel_links:
        temp_list.append(item)
    rel_link_set = set(temp_list)  #相关电影电视剧链接列表
    rel_link_list = []
    for item in rel_link_set:
        res = re.findall(r'^/(\w+)/(\d+)/', item)[0]  #拿出每个链接中的两部分
        item_category = res[0]
        item_id = res[1]
        if item_category == 'movie':
            try:
                item_obj = models.Movie.objects.filter(
                    id=item_id)  #得到相关电影model对象
                item_obj = replaceWrongImg(item_obj, img_type='p')[0]
                item_obj.link = item

                item_obj.director = item_obj.director.split('/')[0].strip()
                item_obj.actor = item_obj.actor.split('/')[0].strip()
                rel_link_list.append(item_obj)
            except Exception:
                pass

        elif item_category == 'tv':
            try:
                item_obj = models.Tv.objects.filter(id=item_id)  #得到相关电影model对象
                item_obj = replaceWrongImg(item_obj, img_type='p')[0]
                item_obj.link = item
                item_obj.director = item_obj.director.split('/')[0].strip()
                item_obj.actor = item_obj.actor.split('/')[0].strip()
                rel_link_list.append(item_obj)
            except Exception:
                pass

    ret['rel_link_list'] = rel_link_list

    if news_obj.title_bg:
        return render_to_response('news/news_template_zhuanti.html',
                                  ret,
                                  context_instance=RequestContext(request))
    elif news_obj.ga_content:
        return render_to_response('news/news_template_ga.html',
                                  ret,
                                  context_instance=RequestContext(request))
    else:
        return render_to_response('news/news_template.html',
                                  ret,
                                  context_instance=RequestContext(request))
Esempio n. 10
0
def index(request):
    ret = {'logined': False}
    #判断用户是否登录
    ret, user_obj = loginInfo(request, ret)
    ret['user_info'] = user_obj
    #sliders
    ret['sliders'] = models.Index_Slider.objects.all().order_by('-id')[:5]

    today_str = getTodayStr()

    #Movies
    movie_new_obj = models.Movie.objects.filter(
        release_date__lte=today_str).order_by('-release_date')[:12]
    movie_future_obj = models.Movie.objects.filter(
        release_date__gt=today_str).order_by('release_date')[:12]
    ret['movie_new_release'] = replaceWrongImg(movie_new_obj, img_type='p')
    ret['movie_near_future'] = replaceWrongImg(movie_future_obj, img_type='p')
    movie_recommend_obj = models.Movie_Recommend.objects.filter(
        cate=1).order_by('-create_date')[:4]
    ret['movie_recommend'] = []
    for item in movie_recommend_obj:
        try:
            temp_obj = models.Movie.objects.get(id=item.media_id)
            temp_obj.reason = item.reason
            ret['movie_recommend'].append(temp_obj)
        except Exception:
            pass
    ret['movie_weekly_top'] = models.Movie.objects.filter(
        release_date__lte=today_str).values('id', 'ch_name', 'score').order_by(
            '-week_visit_count', '-release_date')[:10]
    ret['movie_monthly_top'] = models.Movie.objects.filter(
        release_date__lte=today_str).values('id', 'ch_name', 'score').order_by(
            '-month_visit_count', '-release_date')[:10]

    #TVs
    tv_new_obj = models.Tv.objects.filter(
        score__gt=0).order_by('-release_date')[:12]
    ret['tv_new_release'] = replaceWrongImg(tv_new_obj, img_type='p')
    tv_recommend_obj = models.Movie_Recommend.objects.filter(
        cate=2).order_by('-create_date')[:4]
    ret['tv_recommend'] = []
    for item in tv_recommend_obj:
        try:
            temp_obj = models.Tv.objects.get(id=item.media_id)
            temp_obj.reason = item.reason
            ret['tv_recommend'].append(temp_obj)
        except Exception:
            pass
    ret['tv_weekly_top'] = models.Tv.objects.values('id', 'ch_name',
                                                    'score').order_by(
                                                        '-week_visit_count',
                                                        '-release_date')[:10]
    ret['tv_monthly_top'] = models.Tv.objects.values('id', 'ch_name',
                                                     'score').order_by(
                                                         '-month_visit_count',
                                                         '-release_date')[:10]

    #News
    ret['news_new'] = models.News.objects.all().values(
        'id', 'title', 'subtitle', 'news_image',
        'create_date').order_by('-create_date')[:6]
    ret['news_hot'] = models.News.objects.all().values(
        'id', 'title', 'subtitle', 'news_image',
        'create_date').order_by('-week_visit_count')[:6]

    ret['news_weekly_top'] = models.News.objects.all().values(
        'id', 'title').order_by('-week_visit_count', '-create_date')[:10]
    ret['news_daily_top'] = models.News.objects.all().values(
        'id', 'title').order_by('-day_visit_count', '-create_date')[:10]

    #anime
    anime_new_obj = models.Anime.objects.filter(
        release_date__lte=today_str).order_by('-release_date')[:12]
    ret['anime_new_release'] = replaceWrongImg(anime_new_obj, img_type='p')
    anime_recommend_obj = models.Movie_Recommend.objects.filter(
        cate=3).order_by('-create_date')[:4]
    ret['anime_recommend'] = []
    for item in anime_recommend_obj:
        try:
            temp_obj = models.Anime.objects.get(id=item.media_id)
            temp_obj.reason = item.reason
            ret['anime_recommend'].append(temp_obj)
        except Exception:
            pass
    ret['anime_weekly_top'] = models.Anime.objects.values(
        'id', 'ch_name', 'score').order_by('-week_visit_count',
                                           '-release_date')[:10]
    ret['anime_monthly_top'] = models.Anime.objects.values(
        'id', 'ch_name', 'score').order_by('-month_visit_count',
                                           '-release_date')[:10]

    #show
    show_new_obj = models.Show.objects.filter(
        release_date__lte=today_str).order_by('-release_date')[:12]
    ret['show_new_release'] = replaceWrongImg(show_new_obj, img_type='p')
    show_recommend_obj = models.Movie_Recommend.objects.filter(
        cate=4).order_by('-create_date')[:4]
    ret['show_recommend'] = []
    for item in show_recommend_obj:
        try:
            temp_obj = models.Show.objects.get(id=item.media_id)
            temp_obj.reason = item.reason
            ret['show_recommend'].append(temp_obj)
        except Exception:
            pass
    ret['show_weekly_top'] = models.Show.objects.values(
        'id', 'ch_name', 'score').order_by('-week_visit_count',
                                           '-release_date')[:10]
    ret['show_monthly_top'] = models.Show.objects.values(
        'id', 'ch_name', 'score').order_by('-month_visit_count',
                                           '-release_date')[:10]

    return render_to_response('index/index.html',
                              ret,
                              context_instance=RequestContext(request))
Esempio n. 11
0
def movieDetail(request, *args, **kwargs):
    ret = {'logined': False, 'user_info': '', 'has_rated': False}
    ret, user_obj = loginInfo(request, ret)
    ret['user_info'] = user_obj
    if user_obj:
        uid = user_obj.id
    #右侧边栏
    billboard1 = models.Movie.objects.all().order_by('-week_visit_count')[0]
    billboard2 = models.Movie.objects.all().order_by('-week_visit_count')[1:10]
    ret['billboard1'] = billboard1
    if not path.exists(BASE_DIR + ret['billboard1'].poster):
        ret['billboard1'].poster = '/static/images/default/poster/p_200x284.png'
    ret['billboard2'] = billboard2
    for item in ret['billboard2']:
        if not path.exists(BASE_DIR + item.poster):
            item.poster = '/static/images/default/poster/p_200x284.png'

    #电影信息
    mid = args[0]
    ret['mid'] = mid
    try:
        movie_obj = models.Movie.objects.get(id=mid)
    except Exception:
        raise Http404
        #return render_to_response('404.html')

    movie_obj.visit_count += 1
    movie_obj.week_visit_count += 1
    movie_obj.month_visit_count += 1
    movie_obj.save()

    #ret['detail'] = movie_obj
    ret['detail'] = movie_helper.replaceWrongImg([movie_obj], 'ps')[0]
    #ret['face_id'] = str(randint(1,11))   #卡通头像文件名编号

    reply_obj = models.MovieReply.objects.filter(
        movie__id=mid).order_by('-create_date')[:10]
    reply_counts = movie_obj.movie_r.all().count()
    ret['reply_counts'] = reply_counts
    ret['reply'] = reply_obj

    #判断是否已评过分
    if user_obj:
        has_rated = models.MovieReply.objects.filter(movie__id=mid,
                                                     user__id=user_obj.id,
                                                     rating__gt=0)
        has_rated_counts = has_rated.count()
        if has_rated_counts == 1:
            ret['has_rated'] = True
            ret['cur_user_rating'] = has_rated[0].rating
        elif has_rated_counts > 1:
            ret['has_rated'] = 'error'

    #收藏
    if user_obj:
        collect_obj = models.Collect_Movie.objects.filter(movie__id=mid,
                                                          user__id=uid)
        if collect_obj:
            ret['collected'] = True
    '''
        猜你喜欢
    '''
    all_movie_obj = models.Movie.objects.exclude(id=mid)
    movie_related_obj = movie_helper.relatedMovies(movie_obj, all_movie_obj)
    ret['related'] = movie_helper.replaceWrongImg(movie_related_obj, 'p')

    #标签云
    tags_obj = models.Movie.objects.all().order_by('-week_visit_count').values(
        'id', 'ch_name', 'director', 'actor')[:50]
    da_dict, mn_list = movie_helper.tagsCloud(tags_obj, 'movie')
    ret['da_dict'] = json.dumps(da_dict)
    ret['mn_list'] = json.dumps(mn_list)
    response = render_to_response('movie/movie_detail.html',
                                  ret,
                                  context_instance=RequestContext(request))

    #cookie
    """
    if user_obj:
        response.set_cookie('logined', 'yes')
    else:
        response.set_cookie('logined', 'no')
    """
    return response
Esempio n. 12
0
def searchResult(request, *args, **kwargs):
    ret = {'logined': False, 'show': '', 'pagelist': '', 'search_ok': False}
    #判断用户是否登录,获取用户信息
    ret, user_obj = general.loginInfo(request, ret)
    ret['user_info'] = user_obj
    '''
    内容显示及分页
    '''

    page = general.try_int(request.GET.get('p', 1), 1)
    u_focus = request.GET.get('focus', 'af')
    u_type = request.GET.get('type', 'at')
    u_region = request.GET.get('region', 'ar')
    u_category = request.GET.get('category', 'all')

    type_list = [
        'at', 'juqing', 'xiju', 'aiqing', 'qihuan', 'guzhuang', 'dongzuo',
        'maoxian', 'kehuan', 'xuanyi', 'jingsong', 'kongbu', 'fanzui',
        'zhanzheng', 'donghua', 'jilupian', 'tongxing', 'qingse', 'jiating',
        'ertong', 'lishi', 'yundong', 'zhuanji', 'yinyue', 'gewu', 'xiqu'
    ]
    region_list = [
        'ar', 'otherregion', 'mainland', 'hongkong', 'taiwan', 'america', 'uk',
        'french', 'japan', 'korea', 'thailand', 'india'
    ]
    focus_list = [
        'af', 'guonei', 'guowai', 'gaofen', 'gengxin', 'not_released'
    ]
    category_list = ['all', 'movie', 'tv', 'anime', 'show']

    if not all([
            u_focus in focus_list, u_type in type_list, u_region
            in region_list, u_category in category_list
    ]):
        raise Http404

    u_sv_str = request.GET.get('keyword', '').strip()
    if not u_sv_str:
        return HttpResponseRedirect('/search/')

    #type filter
    if u_type == 'at':
        movie_result = models.Movie.objects.all()
        tv_result = models.Tv.objects.all()
        anime_result = models.Anime.objects.all()
        show_result = models.Show.objects.all()
    else:
        #type_query = False
        for item in typedict:
            if u_type == item:
                movie_result = models.Movie.objects.filter(
                    types__contains=typedict[item])
                tv_result = models.Tv.objects.filter(
                    types__contains=typedict[item])
                anime_result = models.Anime.objects.filter(
                    types__contains=typedict[item])
                show_result = models.Show.objects.filter(
                    types__contains=typedict[item])
                #type_query = True
        #if not type_query:
        #raise Http404

    #region filter
    if u_region == 'ar':
        pass
    elif u_region == 'otherregion':
        movie_result = movie_result.exclude(
            Q(region__contains='中国大陆') | Q(region__contains='香港')
            | Q(region__contains='台湾') | Q(region__contains='美国')
            | Q(region__contains='英国') | Q(region__contains='法国')
            | Q(region__contains='日本') | Q(region__contains='韩国')
            | Q(region__contains='泰国') | Q(region__contains='印度'))
        tv_result = tv_result.exclude(
            Q(region__contains='中国大陆') | Q(region__contains='香港')
            | Q(region__contains='台湾') | Q(region__contains='美国')
            | Q(region__contains='英国') | Q(region__contains='法国')
            | Q(region__contains='日本') | Q(region__contains='韩国')
            | Q(region__contains='泰国') | Q(region__contains='印度'))
        anime_result = anime_result.exclude(
            Q(region__contains='中国大陆') | Q(region__contains='香港')
            | Q(region__contains='台湾') | Q(region__contains='美国')
            | Q(region__contains='英国') | Q(region__contains='法国')
            | Q(region__contains='日本') | Q(region__contains='韩国')
            | Q(region__contains='泰国') | Q(region__contains='印度'))
        show_result = show_result.exclude(
            Q(region__contains='中国大陆') | Q(region__contains='香港')
            | Q(region__contains='台湾') | Q(region__contains='美国')
            | Q(region__contains='英国') | Q(region__contains='法国')
            | Q(region__contains='日本') | Q(region__contains='韩国')
            | Q(region__contains='泰国') | Q(region__contains='印度'))
    else:
        regiondict = {
            'mainland': '中国大陆',
            'hongkong': '香港',
            'taiwan': '台湾',
            'america': '美国',
            'uk': '英国',
            'french': '法国',
            'japan': '日本',
            'korea': '韩国',
            'thailand': '泰国',
            'india': '印度'
        }
        #region_query = False
        for item in regiondict:
            if u_region == item:
                movie_result = movie_result.filter(
                    region__contains=regiondict[item])
                tv_result = tv_result.filter(region__contains=regiondict[item])
                anime_result = anime_result.filter(
                    region__contains=regiondict[item])
                show_result = show_result.filter(
                    region__contains=regiondict[item])
                #region_query = True

        #if not region_query:
        #raise Http404

    #focus filter
    if u_focus == 'af':
        pass
    elif u_focus == 'guonei':
        movie_result = movie_result.filter(
            release_date_show__contains='中国').exclude(score=0)
        tv_result = tv_result.filter(release_date_show__contains='中国').exclude(
            score=0)
        anime_result = anime_result.filter(
            release_date_show__contains='中国').exclude(score=0)
        show_result = show_result.filter(
            release_date_show__contains='中国').exclude(score=0)
    elif u_focus == 'guowai':
        movie_result = movie_result.exclude(
            Q(release_date_show__contains='中国') | Q(score=0))
        tv_result = tv_result.exclude(
            Q(release_date_show__contains='中国') | Q(score=0))
        anime_result = anime_result.exclude(
            Q(release_date_show__contains='中国') | Q(score=0))
        show_result = show_result.exclude(
            Q(release_date_show__contains='中国') | Q(score=0))
    elif u_focus == 'gaofen':
        movie_result = movie_result.filter(score__gte=8)
        tv_result = tv_result.filter(score__gte=8)
        anime_result = anime_result.filter(score__gte=8)
        show_result = show_result.filter(score__gte=8)
    elif u_focus == 'gengxin':
        pass  #后面排序
    elif u_focus == 'not_released':
        movie_result = movie_result.filter(score=0)
        tv_result = tv_result.filter(score=0)
        anime_result = anime_result.filter(score=0)
        show_result = show_result.filter(score=0)
    #else:
    #raise Http404

    #keywords
    print 'u_sv_str: ' + u_sv_str
    if u_sv_str:
        sv_str = u_sv_str  #待处理
        #u_sv_list = u_sv_str.split()  #需返回给前端
        illegal_chars = [
            '!', '!', '@', '#', '$', '%', '^', '&', '*', '-', '_', '"', "'",
            ':', ':', '·', '+', '=', '~', '`', '|', '\\', '/', ',', ',', '.',
            '。', '?', '?', '(', ')', '<', '>', '{', '}', '[', ']', '【', '】',
            ' '
        ]  #空格也去掉
        for item in illegal_chars:
            if item in sv_str:
                sv_str = sv_str.replace(item, '')
        print 'sv_str: ' + sv_str
        try:
            key_word = jieba.analyse.extract_tags(sv_str, topK=1)[0]
        except IndexError:
            key_word = ''

        #去掉所有特殊字符后用jieba分词
        sv_list_filtered = jieba.lcut(sv_str)
        print 'sv_list_filtered: ' + str(sv_list_filtered)
        all_list = []  #查询到的结果结合(含重复项)
        m_list, t_list, a_list, s_list = [], [], [], []
        # 求并集
        for item in sv_list_filtered:

            temp_m = movie_result.filter(
                Q(ch_name__contains=item) | Q(actor__contains=item)
                | Q(director__contains=item) | Q(other_name__contains=item)
                | Q(foreign_name__contains=item))
            if temp_m:
                m_list.extend(temp_m)
            temp_t = tv_result.filter(
                Q(ch_name__contains=item) | Q(actor__contains=item)
                | Q(director__contains=item) | Q(other_name__contains=item)
                | Q(foreign_name__contains=item))
            if temp_t:
                t_list.extend(temp_t)
            temp_a = anime_result.filter(
                Q(ch_name__contains=item) | Q(actor__contains=item)
                | Q(director__contains=item) | Q(other_name__contains=item)
                | Q(foreign_name__contains=item))
            if temp_a:
                a_list.extend(temp_a)
            temp_s = show_result.filter(
                Q(ch_name__contains=item) | Q(actor__contains=item)
                | Q(director__contains=item) | Q(other_name__contains=item)
                | Q(foreign_name__contains=item))
            if temp_s:
                s_list.extend(temp_s)
        if u_category == 'all':
            all_list = m_list + t_list + a_list + s_list
        elif u_category == 'movie':
            all_list = m_list
        elif u_category == 'tv':
            all_list = t_list
        elif u_category == 'anime':
            all_list = a_list
        elif u_category == 'show':
            all_list = s_list

        # 统计(去重)
        c = Counter(all_list)
        #print c
        #print 'dict_c:'+ str(c.items())

        # 数量
        m_counts = len(set(m_list))
        t_counts = len(set(t_list))
        a_counts = len(set(a_list))
        s_counts = len(set(s_list))
        ret['movie_counts'] = m_counts
        ret['tv_counts'] = t_counts
        ret['anime_counts'] = a_counts
        ret['show_counts'] = s_counts
        ret['all_counts'] = sum([m_counts, t_counts, a_counts, s_counts])

        print ret['all_counts']

        #排序
        if key_word:
            sorted_all_list = sorted(c.items(),
                                     key=lambda x:
                                     (-(key_word == x[0].ch_name), -x[1], -(
                                         key_word in x[0].ch_name)))
        else:
            sorted_all_list = sorted(
                c.items(),
                key=lambda x: ((sv_list_filtered[0] == x[0].ch_name), x[1],
                               sv_list_filtered[0] in x[0].ch_name),
                reverse=True)
        print 'sorted_all_list:' + str(sorted_all_list)

        #分页
        items_per_page = general.try_int(request.COOKIES.get('page_num', 20),
                                         20)
        pageObj = html_helper.PageInfo(page, len(c), items_per_page)
        try:
            paged_sorted_list = sorted_all_list[pageObj.start:pageObj.end]
        except IndexError:
            paged_sorted_list = []
        print 'paged_sorted_list: ' + str(paged_sorted_list)
        #print 'paged_sorted_list:' + str(paged_sorted_list)
        final_list = [x[0] for x in paged_sorted_list]
        print len(final_list)
        # 替换不存在海报
        #print 'final_list:' + str(final_list)
        for item in final_list:
            if not path.exists(BASE_DIR + item.poster):
                item.poster = '/static/images/default/poster/p_200x284.png'
        filter_url = '/search/result/?category=%s&focus=%s&type=%s&region=%s&keyword=%s&p=' % (
            u_category, u_focus, u_type, u_region, u_sv_str
        )  #r_cate为返回分类名,默认为movie(若movie搜索不为空)
        page_list = html_helper.Pager(page, pageObj.total_page_counts,
                                      filter_url)
        if pageObj.total_page_counts == 1:
            ret['page_list'] = ''
        else:
            ret['page_list'] = page_list
        # 最终结果
        ret['show'] = final_list
        ret['pages'] = pageObj.total_page_counts
        if pageObj.total_page_counts == 1:
            ret['page_list'] = ''
        elif pageObj.total_page_counts == 0:
            ret['no_result'] = True
        else:
            ret['page_list'] = page_list

    # 推荐电影,根据搜索结果的类型&地区来推荐
    r_count = 5  #推荐显示个数
    if final_list:
        t_list = []
        r_list = []
        for item in final_list:
            for t in item.types.split('/'):
                t_list.append(t.strip())
            for r in item.region.split('/'):
                r_list.append(r.strip())
        ct = Counter(t_list)
        del ct[u'剧情']  #去掉剧情,╮(╯_╰)╭
        cr = Counter(r_list)
        common_t = ct.most_common(1)[0][0]
        common_r = cr.most_common(1)[0][0]
        if u_category == 'all':
            rec_movie = models.Movie.objects.filter(types__contains=common_t,
                                                    region__contains=common_r,
                                                    score__gt=7)
            rec_tv = models.Tv.objects.filter(types__contains=common_t,
                                              region__contains=common_r,
                                              score__gt=7)
            rec_aniem = models.Anime.objects.filter(types__contains=common_t,
                                                    region__contains=common_r,
                                                    score__gt=7)
            rec_show = models.Show.objects.filter(types__contains=common_t,
                                                  region__contains=common_r,
                                                  score__gt=7)
            temp_list = [rec_movie, rec_tv, rec_aniem, rec_show]
            rec_list = [x for j in temp_list for x in j if j]
            rec_result = sorted(rec_list,
                                key=attrgetter('release_date'),
                                reverse=True)[:r_count]
        elif u_category == 'movie':
            rec_result = models.Movie.objects.filter(
                types__contains=common_t,
                region__contains=common_r,
                score__gt=7).order_by('-release_date')[:r_count]
        elif u_category == 'tv':
            rec_result = models.Tv.objects.filter(
                types__contains=common_t,
                region__contains=common_r,
                score__gt=7).order_by('-release_date')[:r_count]
        elif u_category == 'anime':
            rec_result = models.Anime.objects.filter(
                types__contains=common_t,
                region__contains=common_r,
                score__gt=7).order_by('-release_date')[:r_count]
        elif u_category == 'show':
            rec_result = models.Show.objects.filter(
                types__contains=common_t,
                region__contains=common_r,
                score__gt=7).order_by('-release_date')[:r_count]
        ret['rec_result'] = movie_helper.replaceWrongImg(rec_result,
                                                         img_type='p')
    else:  #若搜索无结果,从推荐表里取
        rec_res = models.Movie_Recommend.objects.all().order_by('-create_date')
        rec_list = []
        for item in rec_res:
            if item.cate == 1:
                try:
                    m_obj = models.Movie.objects.get(id=item.media_id)
                    rec_list.append(m_obj)
                except ObjectDoesNotExist:
                    pass
            elif item.cate == 2:
                try:
                    m_obj = models.Tv.objects.get(id=item.media_id)
                    rec_list.append(m_obj)
                except ObjectDoesNotExist:
                    pass
            elif item.cate == 3:
                try:
                    m_obj = models.Anime.objects.get(id=item.media_id)
                    rec_list.append(m_obj)
                except ObjectDoesNotExist:
                    pass
            elif item.cate == 4:
                try:
                    m_obj = models.Show.objects.get(id=item.media_id)
                    rec_list.append(m_obj)
                except ObjectDoesNotExist:
                    pass
            if len(rec_list) == r_count:
                break
        ret['rec_result'] = rec_list

    # 用户选择分类的中文
    cate_dict = {'movie': '电影', 'tv': '电视剧', 'anime': '动漫', 'show': '综艺'}
    for k, v in cate_dict.items():
        if k == u_category:
            ret['cate_name'] = v

    r_base_url = '/search/result/?category=%s&focus=%s&type=%s&region=%s&keyword=' % (
        u_category, u_focus, u_type, u_region)
    ret['cur_url'] = r_base_url + u_sv_str
    ret['u_sv_str'] = u_sv_str
    thumb_switch = request.COOKIES.get('switch', 't1')

    if thumb_switch == 't1' or not thumb_switch:
        response = render_to_response('search/search_result.html',
                                      ret,
                                      context_instance=RequestContext(request))
    elif thumb_switch == 't2':
        response = render_to_response('search/search_result_t2.html',
                                      ret,
                                      context_instance=RequestContext(request))
    elif thumb_switch == 't3':
        response = render_to_response('search/search_result_t3.html',
                                      ret,
                                      context_instance=RequestContext(request))

    response.set_cookie('page_num', items_per_page)
    return response