Beispiel #1
0
def born(request, id, born):
    #try:
    if request.user.is_superuser or request.is_admin:
        if born:
            year, month, day = born.split('-')
            born = datetime.datetime(int(year), int(month), int(day))
        else:
            born = None
            day = 0
            month = 0
            year = 0

        person = Person.objects.get(pk=id)
        
        act = None
        if person.born:
            if born != person.born:
                act = '2' if born else '3'
        else:
            if born:
                act = '1'
                
        person.born = born
        person.save()

        if person.kid:
            person_afisha = AfishaPersons.objects.using('afisha').filter(pk=person.kid).update(
                birth_year = year,
                birth_mounth = month,
                birth_day = day
            )
        
            actions_logger(22, id, request.profile, act) # персона Дата рождения
        
        born = tmp_date(born, "d E Y г.") if born else ''

        return simplejson.dumps({'status': True, 'content': born})
Beispiel #2
0
def borned(request, id, year, month, day):
    #try:
    access = False
    owner = False
    if request.profile.person_id == int(id):
        access = True
        owner = True
    elif request.user.is_superuser or request.is_admin:
        access = True
        
    if access:
        try:
            born = datetime.datetime(int(year), int(month), int(day))
        except ValueError:
            born = ''
            
        if born:
            person = Person.objects.get(pk=id)
            person.born = born
            person.save()

            born = tmp_date(born, "d E Y г.") if born else ''

        return simplejson.dumps({'status': True, 'content': born})
Beispiel #3
0
def women(request, m=None, topic=None):
    if m and m != 'm':
        raise Http404

    from forums.ajax import wf_ignored_msgs
    timer = time.time()
    
    if request.POST and 'refresh' in request.POST:
        if m:
            return HttpResponseRedirect(reverse('women_forum', kwargs={'m': m}))
        else:
            return HttpResponseRedirect(reverse('women_forum'))

    #wf_settings = request.session.get('fw_settings', {})
    
    default_show_topic = FORUM_SHOW_TOPIC['2']['val']
    default_show_last = FORUM_SHOW_LAST['1']['val']
    default_sh_style = FORUM_SH_STYLE['1']['val']

    wf_msg_open = True
    wf_theme = request.session.get('fw_theme_settings', [])
    wf_topic, wf_last, wf_style = (default_show_topic, default_show_last, default_sh_style)
    
    if request.profile:
        interface = request.profile.personinterface
        if interface.wf_topic is not None:
            wf_topic = None if int(interface.wf_topic) == 0 else interface.wf_topic
        if interface.wf_last is not None:
            wf_last = interface.wf_last
        if interface.wf_style is not None:
            wf_style = interface.wf_style
        if interface.wf_msg_open is not None:
            wf_msg_open = interface.wf_msg_open
    
    def tree_level(parent):
        for item in sorted(parent_map[parent]):
            yield q[item]
            sub_items = list(tree_level(item))
            if sub_items:
                yield sub_items
    
    def printTree(L, new, ind, readed_msg, data=0):
        for i in L:
            if isinstance(i, list):
                data = printTree(i, new, ind, readed_msg, data)
            else:
                if i.id not in readed_msg:
                    if ind == 0 and int(i.parent) != new:
                        data += 1
                    elif ind == 1:
                        data += 1
                        
        return data
    

    
    readed_msg = []
    nickname = ''
    ignored = {'msg': [], 'author': []}
    kid = request.profile.kid if request.profile else None
    
    if kid:
        try:
            #nick = request.user.first_name
            reg_user = RegisteredUsers.objects.only('nickname').using('afisha').get(pk=kid)
            nickname = reg_user.nickname
        except RegisteredUsers.DoesNotExist: pass

        ignored = wf_ignored_msgs(kid)

        readed_msg = list(WFUser.objects.using('afisha').filter(user=kid).values_list('opinion', flat=True))

    categories = WFOpinion.objects.using('afisha').only('id', 'subject').filter(type_obj=1, type=5).order_by('id')
    
    
    
    if not wf_theme:
        wf_theme = [str(i.id) for i in categories]

 
    settings_categories = []
    topics = {}
    for i in categories:
        if str(i.id) in wf_theme:
            topics[i.id] = {'id': i.id, 'subject': i.subject, 'topics': []}
            settings_categories.append({'obj': i, 'set': True})
        else:
            settings_categories.append({'obj': i, 'set': False})
    
    first_load = None
    first_title = ''
    first_cat_id = None
    topics_list = []
    
    filter = {}
    if wf_topic:
        now = datetime.datetime.now()
        from_date = now - datetime.timedelta(days=wf_topic)
        filter = {'date__gte': from_date}
    else:
        from_date = datetime.datetime(1990, 1, 1, 0, 0)
    

    topics_left_data = []
    branches = []
    
    themes = WFOpinion.objects.using('afisha').only('id', 'subject').filter(pk__in=wf_theme)
    
    filter = {'deleted': False}
    if request.user.is_superuser:
        filter = {}
    
    search_query = request.GET.get('q','')
    if search_query:
        search_query = BeautifulSoup(search_query, from_encoding="utf-8").text
        if len(search_query.replace(' ','').strip()) > 3:
            search_query = search_query
        else:
            search_query = ''
    
    
    
    themes_ids = {}
    for i in themes:
        themes_ids[i.id] = i.subject
     
    topics_in_category = {}
    topics_deleted = {}
    '''
    for i in WFOpinion.objects.using('afisha').only('id', 'parent', 'deleted').filter(parent__in=themes_ids.keys(), **filter).exclude(Q(user__id__in=ignored['author']) | Q(pk__in=ignored['msg'])).order_by('-date')[:15000]:
        if not topics_in_category.get(i.parent):
            subj = themes_ids.get(i.parent)
            topics_in_category[i.parent] = {'ids': [i.id], 'subj': subj}
        topics_in_category[i.parent]['ids'].append(i.id)
        if not topics_deleted.get(i.id):
            topics_deleted[i.id] = i.deleted
    '''
    # Получаю топики для списка категорий (например: для категории "Доска объявлений" 50 топиков, и т.д.)
    for k in themes_ids.keys():
        for i in WFOpinion.objects.using('afisha').only('id', 'parent', 'deleted').filter(parent=k, **filter).exclude(Q(user__id__in=ignored['author']) | Q(pk__in=ignored['msg'])).order_by('-date')[:wf_last]:
        
            if not topics_in_category.get(k):
                subj = themes_ids.get(k)
                topics_in_category[k] = {'ids': [i.id], 'subj': subj}
            topics_in_category[k]['ids'].append(i.id)
            if not topics_deleted.get(i.id):
                topics_deleted[i.id] = i.deleted
            
    
    for k, v in topics_in_category.iteritems():
        if search_query:
            messages_in_topics = WFOpinion.objects.using('afisha').only('id', 'branch', 'date', 'deleted').filter(Q(branch__in=v['ids']) | Q(pk__in=v['ids']), Q(subject__icontains=search_query) | Q(text__icontains=search_query), **filter).exclude(Q(user__id__in=ignored['author']) | Q(pk__in=ignored['msg'])).order_by('-date')[:2000]
        else:
            # получаю все сообщения для каждого топика
            messages_in_topics = WFOpinion.objects.using('afisha').only('id', 'branch', 'date', 'deleted').filter(Q(branch__in=v['ids']) | Q(pk__in=v['ids']), date__gte=from_date, **filter).exclude(Q(user__id__in=ignored['author']) | Q(pk__in=ignored['msg'])).order_by('-date')[:2000]
        
        
        msg_dict = {}
        for msg in messages_in_topics:
            branch = msg.branch if msg.branch else msg.id
            if not msg_dict.get(branch):
                deleted = topics_deleted.get(branch)
                msg_dict[branch] = {'id': branch, 'date': msg.date, 'count': 0, 'cat': v['subj'], 'cat_id': k, 'del': deleted}
                branches.append(branch)

        
        topics_left_data.append({
            'id': k,
            'subject': v['subj'],
            'topics': sorted(msg_dict.values(), key=operator.itemgetter('date'), reverse=True),
        })
    

    brnch_dict = {}
    for i in WFOpinion.objects.using('afisha').select_related('user__nickname').filter(pk__in=branches, **filter).only('id', 'nick', 'subject', 'user__nickname', 'parent'):
        try:
            nick = i.nick if i.nick else i.user.nickname
        except AttributeError:
            nick = ''
        brnch_dict[i.id] = {'nick': nick, 'count': 0, 'subject': i.subject, 'parent': i.parent, 'msgs': []}
    
    
    counter = {}
    
    for i in WFOpinion.objects.using('afisha').only('id', 'branch').filter(branch__in=brnch_dict.keys(), **filter).exclude(Q(user__id__in=ignored['author']) | Q(pk__in=ignored['msg']) | Q(parent__in=ignored['msg'])):
        
        if counter.get(i.branch):
            counter[i.branch]['count'] += 1
        else:
            counter[i.branch] = {'count': 1}
            


    #if not wf_msg_open:
    if kid:
        msgs_data = WFOpinion.objects.using('afisha').only('id', 'parent', 'branch').filter(Q(branch__in=brnch_dict.keys()) | Q(pk__in=brnch_dict.keys())).exclude(Q(user__id__in=ignored['author']) | Q(pk__in=ignored['msg']))

        for i, val in brnch_dict.iteritems():
            for md in msgs_data:
                if md.id == i or md.branch == i:
                    brnch_dict[i]['msgs'].append(md)

        for i, val in brnch_dict.iteritems():
            
            q = dict(zip([qi.id for qi in val['msgs']], val['msgs']))
            
            parent_map = defaultdict(list)
            
            for item in q.itervalues():
                parent_map[item.parent].append(item.id)

            read_n = 0
            
            for ind, j in enumerate((int(val['parent']), 0)):
                tmp = list(tree_level(j))
                read_n += printTree(tmp, j, ind, readed_msg)
            
            if counter.get(i):
                counter[i]['no_readed'] = read_n


    
    # добавляем к данным Автора темы и дату время последнего сообщение в теме
    for i in topics_left_data:
        for t in i['topics']:
            x = brnch_dict.get(t['id'])
            count = counter.get(t['id'], {'count': 0, 'no_readed': 0})
            if x:
                t['author'] = x['nick']
                t['count'] = count['count']
                t['no_readed'] = count.get('no_readed', 0)
                t['subject'] = x['subject']
    
    data = sorted(topics_left_data, key=operator.itemgetter('id'))
    stopic = sorted(FORUM_SHOW_TOPIC.values(), key=operator.itemgetter('id'))
    slast = sorted(FORUM_SHOW_LAST.values(), key=operator.itemgetter('id'))
    sstyle = sorted(FORUM_SH_STYLE.values(), key=operator.itemgetter('id'))
    smiles = sorted(FORUM_SMILES.values(), key=operator.itemgetter('id'))

    if topic:
        try:
            topic_obj = WFOpinion.objects.using('afisha').only('branch').get(id=topic)
            topic_br = WFOpinion.objects.using('afisha').only('parent').get(id=topic_obj.branch)
            first_load = topic
            for i in categories:
                if i.id == topic_br.parent:
                    first_title = i.subject
                    first_cat_id = i.id
                    break
        except WFOpinion.DoesNotExist: pass
            
    if not first_load:
        for i in data:
            if first_load:
                break
            for t in i['topics']:
                first_load = t['id']
                first_title = t['cat']
                first_cat_id = t['cat_id']
                break

    newmsg = request.session.get('wf_new_msg','')
    if newmsg:
        request.session['wf_new_msg'] = ''
    
    next_level = ''
    try:
        level_obj = WomenForumIgnoreLevel.objects.get(user=kid)
        now = datetime.datetime.now()
        
        future = level_obj.dtime + datetime.timedelta(days=7)
        if future < now and level_obj.type < 3:
            level_obj.type += 1
            level_obj.dtime = now
            level_obj.save()
            
        if level_obj.type < 3:
            next_level = level_obj.dtime + datetime.timedelta(days=7)
            next_level = tmp_date(next_level, "d E в H:i")
        level = level_obj.type
    except WomenForumIgnoreLevel.DoesNotExist:
        level = 1

    timer = '%5.2f' % (time.time()-timer)

    template = 'forums/women_main.html'
    if m:
        template = 'mobile/forums/women_main.html'

    return render_to_response(template, {'data': data, 'FORUM_SHOW_TOPIC': stopic, 'FORUM_SHOW_LAST': slast, 'wf_topic': wf_topic, 'wf_last': wf_last, 'wf_style': wf_style, 'categories': settings_categories, 'topic': topic, 'first_load': first_load, 'first_title': first_title, 'first_cat_id': first_cat_id, 'FORUM_SH_STYLE': sstyle, 'FORUM_SMILES': smiles, 'nickname': nickname, 'search_query': search_query, 'newmsg': newmsg, 'level': level, 'next_level': next_level, 'wf_msg_open': wf_msg_open, 'timer': timer}, context_instance=RequestContext(request))
Beispiel #4
0
def cinemate_cc_test(request):

    source = ImportSources.objects.get(url='http://cinemate.cc/')

    source_films = SourceFilms.objects.filter(source_obj=source, extra='new')
    if not source_films:
        source_films = SourceFilms.objects.filter(source_obj=source)

    films = {}
    for i in source_films:
        new = True if i.extra == 'new' else False
        films[i.kid] = {
            'obj': i,
            'names': {
                'name_en': None,
                'name_ru': None
            },
            'source_id': i.source_id,
            'new': new,
            'release': ''
        }

    for i in list(
            Film.objects.using('afisha').filter(pk__in=films.keys()).values(
                'id', 'date')):
        films[i['id']][
            'release'] = i['date'] if i['date'] else datetime.datetime(
                3000, 1, 1)

    names = list(
        FilmsName.objects.using('afisha').filter(
            type__in=(1, 2), status=1,
            film_id__id__in=films.keys()).values("film_id", "name", "type"))

    for i in names:
        if i['type'] == 1:
            films[i['film_id']]['names']['name_en'] = i['name'].strip()
        else:
            films[i['film_id']]['names']['name_ru'] = i['name'].strip()

    films = sorted(films.values(),
                   key=operator.itemgetter('release'),
                   reverse=True)

    upd = []

    html = u'''
        <link rel="stylesheet" href="http://kinoinfo.ru/static/base/css/style.css" type="text/css" media="screen" />
        <table class="modern_tbl">
            <th></th>
            <th>Релиз</th>
            <th>Название</th>
            <th>Источник</th>
        '''
    for i in films:
        kinoinfo_url = u'http://kinoinfo.ru/film/%s/' % i['obj'].kid
        name = u'%s / %s' % (i['names']['name_ru'], i['names']['name_en'])
        source_url = u'http://cinemate.cc/movie/%s/' % i['obj'].source_id
        if i['new']:
            new = '<span style="color: #009933;">NEW</span>'
            upd.append(i['obj'].id)
        else:
            new = ''
        release = tmp_date(i['release'],
                           'j E Y') if i['release'].year != 3000 else u'Нет'
        html += u'<tr><td>%s</td><td>%s</td><td><a href="%s" target="_blank">%s</a></td><td><a href="%s" target="_blank">перейти</a></td></tr>' % (
            new, release, kinoinfo_url, name, source_url)

    html += u'</table>'

    SourceFilms.objects.filter(pk__in=upd).update(extra=None)

    return HttpResponse(str(html.encode('utf-8')))
Beispiel #5
0
def booking_get_excel_doc(request):
    from openpyxl import Workbook
    from openpyxl.cell import get_column_letter
    from openpyxl.styles import Font

    if request.user.is_superuser:
        access = True
    else:
        access = request.user.groups.filter(name='Букер').exists()

    data = {}
    halls = {}
    if access and request.POST:
        '''
        halls_ids = [3552, 1970, 2539]
        date_from = datetime.date(2016, 4, 25)
        date_to = datetime.date(2016, 5, 5)
        date_to = date_to + datetime.timedelta(days=1)
        print_temp = False
        all_dates = False
        '''

        halls_ids = request.POST.getlist('ex_halls')
        date_from = request.POST.get('ex_date_from')
        date_to = request.POST.get('ex_date_to')
        all_dates = request.POST.get('ex_date_all')
        print_temp = request.POST.get('ex_temp')

        date_from = datetime.datetime.strptime(str(date_from), '%Y-%m-%d')
        date_to = datetime.datetime.strptime(str(date_to), '%Y-%m-%d')
        all_dates = True if all_dates else False
        print_temp = True if print_temp else False

        # все кинотеатры из настроек букера
        cinemas = {}
        cinemas_kids = []
        for i in Cinema.objects.filter(bookingsettings__profile=request.profile, bookercinemas__permission='1').distinct('pk').values('id', 'code', 'bookercinemas__permission'):
            cinemas[i['id']] = {'id': i['id'], 'kid': i['code'], 'name': '', 'access': i['bookercinemas__permission']}
            cinemas_kids.append(i['code'])

        for i in list(NameCinema.objects.filter(cinema__code__in=cinemas_kids, status=1).values('name', 'cinema')):
            cinemas[i['cinema']]['name'] = i['name']

        # залы
        for i in list(NameHall.objects.filter(status=1, hall__cinema__code__in=cinemas_kids).distinct('hall').values('name', 'hall', 'hall__cinema')):
            cinema = cinemas.get(i['hall__cinema'])
            halls[i['hall']] = {'hall_id': i['hall'], 'cinema': cinema, 'cinema_name': cinema['name'], 'name': i['name'], 'dates': {}, 'date_range': {}}

        filter = {'hall__id__in': halls_ids, 'temp': print_temp}
        if all_dates:
            filter['dtime__gte'] = datetime.date.today()
        else:
            filter['dtime__gte'] = date_from
            filter['dtime__lt'] = date_to

        schedules = BookingSchedules.objects.select_related('hall').filter(**filter)

        schedules_ids = [i.id for i in schedules]
        source_films_data = list(SourceFilms.objects.filter(bookingschedules__pk__in=schedules_ids).values('kid', 'bookingschedules'))
        source_kids = set([i['kid'] for i in source_films_data])

        names = {}
        for i in FilmsName.objects.using('afisha').filter(film_id__pk__in=source_kids, status=1, type__in=(1, 2)).exclude(film_id__id__in=names.keys()):
            if not names.get(i.film_id_id):
                names[i.film_id_id] = {}
            names[i.film_id_id][i.type] = i.name

        # фильмы
        source_films = {}
        for i in source_films_data:
            if not source_films.get(i['bookingschedules']):
                source_films[i['bookingschedules']] = []
            name = names.get(i['kid'])
            name = name[2] if name.get(2) else name[1]
            source_films[i['bookingschedules']].append({'kid': i['kid'], 'name': name})

        # удобно складываем все данные
        for i in schedules:
            if not data.get(i.hall_id):
                #cinema = cinemas.get(i.hall.cinema_id)
                hall = halls.get(i.hall_id)
                data[i.hall_id] = {'hall_id': i.hall_id, 'cinema': hall['cinema'], 'name': hall['name'], 'dates': {}, 'date_range': {}}
            films = source_films.get(i.id)
            
            if not data[i.hall_id]['dates'].get(i.dtime.date()):
                data[i.hall_id]['dates'][i.dtime.date()] = {'date': i.dtime.date(), 'ids': [], 'times': []}

            data[i.hall_id]['dates'][i.dtime.date()]['times'].append({'time': i.dtime, 'films': films, 'tmp': i.temp, 'id': i.id})
            data[i.hall_id]['dates'][i.dtime.date()]['ids'].append('%s%s' % (i.dtime.time(), films))
            data[i.hall_id]['dates'][i.dtime.date()]['ids'].sort()

        # формируем диапозон дат с одинкаовыми сеансами
        for i in data.values():
            i['dates'] = sorted(i['dates'].values(), key=operator.itemgetter('date'))

            old_date_times = []
            sch_date_from = None
            sch_date_to = None
            for j in i['dates']:
                set_dates = True
                if old_date_times:
                    if old_date_times == j['ids']:
                        sch_date_to = j['date']
                        set_dates = False
                
                if set_dates:
                    sch_date_from = j['date']
                    sch_date_to = j['date']

                old_date_times = j['ids']

                if not i['date_range'].get(sch_date_from):
                    i['date_range'][sch_date_from] = {'from': sch_date_from, 'to': None, 'times': j['times']}
                i['date_range'][sch_date_from]['to'] = sch_date_to


        wb = Workbook()
        
        for index, i in enumerate(data.values()):
            if index == 0:
                ws = wb.active
            else:
                ws = wb.create_sheet()

            ws.title = u'%s, %s' % (i['cinema']['name'][:13], i['name'][:13])

            count = 0
            for j in i['date_range'].values():
                count += len(j['times']) + 1

            last_row = 0
            for j in sorted(i['date_range'].values(), key=operator.itemgetter('from')):
                last_row += 1

                cells = 'A%s:B%s' % (last_row, last_row)

                ws.merge_cells(cells)
                ws["A%s" % last_row].font = Font(name='Calibri', size=12, bold=True)
                ws["A%s" % last_row] = '%s - %s' % (j['from'], j['to'])

                j['times'] = sorted(j['times'], key=operator.itemgetter('time'))

                for row in range(len(j['times'])):
                    last_row += 1

                    t = tmp_date(j['times'][row]['time'], 'H:i')
                    t = t.encode('utf-8')
                    tfilms = ''
                    for f in j['times'][row]['films']:
                        if tfilms:
                            tfilms += u', '
                        tfilms += f['name']
                    
                    for ind, col in enumerate((t, tfilms)):
                        ws.cell(column=ind+1, row=last_row, value=col)

        file_name = 'booking_schedules_%s.xlsx' % request.user.id
        file_path = '%s/%s' % (settings.BOOKING_EXCEL_PATH, file_name)

        wb.save(filename=file_path)

        with open(file_path, 'r') as f:
            file = f.read()

        response = HttpResponse(file, mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = 'attachment; filename=%s' % file_name
        return response

        '''
        doc = ''

        for i in data.values():
            doc += u'<b>%s / %s</b><br />' % (i['cinema']['name'][:13], i['name'][:13])
            
            for j in sorted(i['date_range'].values(), key=operator.itemgetter('from')):

                doc += u'- - - - - %s - %s<br />' % (j['from'], j['to'])

                for t in sorted(j['times'], key=operator.itemgetter('time')):

                    doc += u'%s, ' % t['time'].time()
                    for f in t['films']:
                        doc += u'%s, ' % f['name']
                    doc += u'<br />'

        return HttpResponse(str(doc.encode('utf-8')))
        '''

    raise Http404
Beispiel #6
0
def get_film(request, id, val=None):
    try:
        mobile = False
        if request.subdomain == 'm' and request.current_site.domain in (
                'kinoafisha.ru', 'kinoinfo.ru'):
            mobile = True

        current_language = translation.get_language()
        current_site = request.current_site

        is_cached = cache.get('get_film__%s' % id, 'nocaсhed')

        if is_cached == 'nocaсhed':  # объекта нет в кэше, значит создаем
            film = get_film_data(id)
            if not film:
                return simplejson.dumps({'status': 'False'})
            cache.set('get_film__%s' % id, film, 60 * 60 * 4)
        else:
            film = is_cached

        film = get_film_data(id)

        if film:
            subscriptions_accept = True
            description = ''
            poster = ''
            uk_name_person = []
            name = ''
            okino = False
            if current_site.domain == 'kinoafisha.in.ua':
                try:
                    ReleasesRelations.objects.get(film_kid=id,
                                                  rel_double=False,
                                                  rel_ignore=False)
                except ReleasesRelations.DoesNotExist:
                    subscriptions_accept = False
                except ReleasesRelations.MultipleObjectsReturned:
                    pass

                if current_language == 'uk':
                    actors_ids = [i['id'] for i in film['actors']]
                    uk_name_person = list(
                        NamePerson.objects.filter(
                            person__kid__in=actors_ids,
                            status=1,
                            language__name='Украинский').values(
                                'person__kid', 'name'))

                    try:
                        source_film = SourceFilms.objects.select_related(
                            'source_obj').filter(
                                kid=id,
                                source_obj__url='http://kino-teatr.ua/')[0]
                    except IndexError:
                        try:
                            source_film = SourceFilms.objects.select_related(
                                'source_obj').filter(
                                    kid=id,
                                    source_obj__url='http://www.okino.ua/')[0]
                        except IndexError:
                            try:
                                source_film = Okinoua.objects.filter(kid=id)[0]
                                okino = True
                            except IndexError:
                                source_film = None

                    if source_film:
                        if okino:
                            name = source_film.name_ua
                        else:
                            name = source_film.name
                            if source_film.source_obj.url == 'http://kino-teatr.ua/' and source_film.text:
                                description = source_film.text.encode('utf-8')
                                if description == 'Проект оголошений':
                                    description = ''

                    try:
                        poster = UkrainePosters.objects.filter(
                            kid=id)[0].poster
                        poster = str(poster).split('/')[-1:][0]
                        poster = '/upload/films/posters/uk/%s' % poster
                    except IndexError:
                        pass

            if not poster:
                poster = film['posters'].replace('_small',
                                                 '') if film['posters'] else ''

            posters = u'<a class="fancybox" href="%s"><img src="%s" /></a>' % (
                poster, poster) if poster else ''

            slides = []
            for ind, i in enumerate(film['slides']):
                poster_path = u'<div class="slide"><a class="fancybox" rel="group" href="%s"><img class="fancy_slide" src="%s" /></a></div>' % (
                    i.replace('_small', ''), i)
                slides.append(poster_path)
                if ind == 2:
                    break

            slides_count = len(slides)
            trailers_count = len(film['trailers'])

            range_to = 3 - slides_count
            for i in range(range_to):
                slides.append('<div class="slide">Нет слайда</div>')

            trailer = '<div class="trailer">Нет трейлера</div>'
            for i in film['trailers']:
                trailer = '<div class="trailer">%s</div>' % i['code']
                break

            imdb_rate = film['imdb_rate'] if film['imdb_num'] else 0
            imdb_vote = film['imdb_num'] if film['imdb_num'] else 0
            afisha_rate_tag = u'<b>Оценки посетителей Киноафиши:</b> %s (%s голоса)' % (
                film['afisha_rate'],
                film['afisha_num']) if film['afisha_num'] else ''
            comment_tag = u'<b>Примечания:</b> %s' % film['comment'].replace(
                '&#034;', '"') if film['comment'] else ''
            limit = age_limits(film['limits']) if film['limits'] else ''

            if not description:
                description = u'%s' % film['description'] if film[
                    'description'] else ''

            description_cut = ''
            if description:
                description_cut = BeautifulSoup(
                    description,
                    from_encoding='utf-8').text.strip().split()[:30]
                description_cut = ' '.join(description_cut)
                description_cut = '%s ...' % description_cut.rstrip(
                    u'…').rstrip(u'...')
                description += '<br /><br />'

            runtime_tag = u'%s' % film['runtime'] if film['runtime'] else ''

            person_ids = [i['id'] for i in film['directors']]
            person_ids += [i['id'] for i in film['actors']]

            extresids = {}
            extresid = Objxres.objects.using('afisha').filter(
                objtypeid=302,
                objpkvalue__in=set(person_ids)).only('extresid', 'objpkvalue')
            for i in extresid:
                extresids[int(i.extresid_id)] = int(i.objpkvalue)

            person_photos = {}
            photos = Extres.objects.using('afisha').filter(
                extresid__in=extresids.keys(),
                filename__icontains='small',
                info__icontains='*t')

            for i in photos:
                pkid = extresids.get(i.extresid)
                if pkid:
                    person_photos[
                        pkid] = 'http://persons.nodomain.kinoafisha.ru/%s' % i.filename

            directors_tag = u''
            directors_top_line = u''
            for v in film['directors']:
                pphoto = person_photos.get(int(v['id']), '')
                if pphoto:
                    if mobile:
                        pphoto = '<img src="%s" id="img_under" />' % pphoto
                    else:
                        pphoto = '<img src="%s" />' % pphoto

                if directors_tag:
                    directors_tag += u', '
                try:
                    director_afisha_link = u'/person/%s/' % v['id']
                    director_afisha_link = u'<a href="%s">%s</a>' % (
                        director_afisha_link, v['name'][0]['name'])

                    #director_imdb = get_imdb_id(v['imdb'])
                    #director_imdb_link = u'http://www.imdb.com/name/nm%s/' % director_imdb
                    #director_imdb_link = u'<a href="%s" target="_blank">%s</a>' % (director_imdb_link, v['name'][1]['name'])
                    director_imdb_link = u'<span class="small_star">%s</span>' % v[
                        'name'][1]['name']

                    directors_tag += u'%s <span id="person_imdb_link">(%s)</span>' % (
                        director_afisha_link, director_imdb_link)
                except IndexError:
                    director_afisha_link = u'/person/%s/' % v['id']
                    director_afisha_link = u'<a href="%s">%s</a>' % (
                        director_afisha_link, v['name'][0]['name'])
                    directors_tag += u'%s' % director_afisha_link

                parental_name = NamePerson.objects.filter(
                    person__kid=v['id'], status=3,
                    language__id=1).order_by('-id')
                parental_name = parental_name[0] if parental_name else v[
                    'name'][0]['name']
                if directors_top_line:
                    directors_top_line += u' и '
                directors_top_line += u'<a href="/person/%s/">%s%s</a>' % (
                    v['id'], pphoto, parental_name)

            if directors_tag:
                directors_tag = u'<b>Режиссер:</b> %s<br /><br />' % directors_tag

            other_person_tag = u''
            '''
            for v in film['other_person']:
                if other_person_tag:
                    other_person_tag += u', '
 
                try:
                    other_person_afisha_link = u'/person/%s/' % v['id']
                    other_person_afisha_link = u'<a href="%s">%s</a>' % (other_person_afisha_link, v['name'][0]['name'])
                    other_person_imdb_link = u'<span class="small_star">%s</span>' % v['name'][1]['name']
                    other_person_tag += u'%s <span id="person_imdb_link">(%s)</span> - %s' % (other_person_afisha_link, other_person_imdb_link, v['type_name'])
                except IndexError:
                    other_person_afisha_link = u'/person/%s/' % v['id']
                    other_person_afisha_link = u'<a href="%s">%s</a> - %s' % (other_person_afisha_link, v['name'][0]['name'], v['type_name'])
                    other_person_tag += u'%s' % other_person_afisha_link

            if other_person_tag:
                other_person_tag = u'<b>Прочие создатели:</b> %s' % other_person_tag
            '''

            countries_tag = u''
            for i in film['countries'].values():
                if countries_tag:
                    countries_tag += u' / '
                try:
                    countries_tag += u'%s' % i
                except UnicodeDecodeError:
                    countries_tag += u'%s' % i.decode('utf-8')

            genres_tag = u''
            for i in film['genres'].values():
                if genres_tag:
                    genres_tag += u' / '
                try:
                    genres_tag += u'%s' % i
                except UnicodeDecodeError:
                    genres_tag += u'%s' % i.decode('utf-8')

            distributors_tag = u''
            for i in film['distributors']:
                if distributors_tag:
                    distributors_tag += u', '
                try:
                    distributors_tag += u'%s' % i['name']
                except UnicodeDecodeError:
                    distributors_tag += u'%s' % i['name'].decode('utf-8')

            if mobile:
                if distributors_tag:
                    distributors_tag = u'<div style="margin-bottom: 10px;"><b>Дистрибьютор:</b> %s</div>' % distributors_tag
                else:
                    distributors_tag = u''
            else:
                if distributors_tag:
                    distributors_tag = u'<span class="nolink" title="%s">дистрибьютор</span>' % distributors_tag
                else:
                    distributors_tag = u'<span style="color: #666;">дистрибьютор</span>'

            voices = [
                int(i['id']) for i in film['other_person']
                if int(i['type'] == 5)
            ]

            actors_top_line = u''
            actors_tag = u''
            actors_count = 0
            for v in film['actors']:
                if v['id'] not in voices:
                    name_person = v['name'][0]['name']

                    pphoto = person_photos.get(int(v['id']), '')
                    if pphoto:
                        if mobile:
                            pphoto = '<img src="%s" id="img_under" />' % pphoto
                        else:
                            pphoto = '<img src="%s" />' % pphoto

                    for i in uk_name_person:
                        if i['person__kid'] == v['id']:
                            name_person = i['name']

                    if actors_tag:
                        actors_tag += u', '
                    try:
                        actor_afisha_link = u'/person/%s/' % v['id']
                        actor_afisha_link = u'<a href="%s">%s</a>' % (
                            actor_afisha_link, name_person)

                        #actor_imdb = get_imdb_id(v['imdb'])
                        #actor_imdb_link = u'http://www.imdb.com/name/nm%s/' % actor_imdb
                        #actor_imdb_link = u'<a href="%s" target="_blank">%s</a>' % (actor_imdb_link, v['name'][1]['name'])
                        actor_imdb_link = u'<span class="small_star">%s</span>' % v[
                            'name'][1]['name']

                        actors_tag += u'%s <span id="actor_imdb_link">(%s)</span>' % (
                            actor_afisha_link, actor_imdb_link)
                    except IndexError:
                        actor_afisha_link = u'/person/%s/' % v['id']
                        actor_afisha_link = u'<a href="%s">%s</a>' % (
                            actor_afisha_link, name_person)
                        actors_tag += u'%s' % actor_afisha_link

                    actors_count += 1
                    if actors_count < 4:
                        if actors_top_line:
                            actors_top_line += ', '
                        actors_top_line += u'<a href="/person/%s/">%s%s</a>' % (
                            v['id'], pphoto, name_person)

            if actors_tag:
                actors_tag = u'<b>Звезды:</b> %s<br /><br />' % actors_tag

            top_line = u''
            if actors_top_line:
                top_line = u'%s в фильме ' % actors_top_line

            if directors_top_line:
                if not actors_top_line:
                    top_line = u'Фильм '
                top_line += directors_top_line

            name_en = ''
            if not name:
                name = film['name_ru']
            if request.subdomain == 'm':
                name_ru_url = 'http://m.kinoinfo.ru/film/%s/' % id
            else:
                name_ru_url = 'http://kinoinfo.ru/film/%s/' % id
            name_ru = u'<a href="%s">%s</a>' % (name_ru_url, name)
            if film['idimdb']:
                if mobile:
                    name_en = u'<a href="http://www.imdb.com/title/tt%s" target="_blank" style="display: inline-block; margin-top: 10px;">%s</a>' % (
                        film['idimdb'], film['name_en'])
                else:
                    name_en = u'<a href="http://www.imdb.com/title/tt%s" target="_blank">%s</a>' % (
                        film['idimdb'], film['name_en'])

            details_tag = u''
            if countries_tag or runtime_tag or genres_tag:
                if countries_tag:
                    details_tag += countries_tag
                if genres_tag:
                    if details_tag:
                        details_tag += u', '
                    details_tag += genres_tag
                if runtime_tag:
                    if details_tag:
                        details_tag += u', '
                    details_tag += u'%s мин.' % runtime_tag
                details_tag = '%s' % details_tag

            subr = False
            if request.user.is_authenticated():
                subr = get_subscription_status(id, request.user.get_profile())
                if subr:
                    subr = True

            likes = get_film_likes(id)

            player = False
            if val:
                player, psource = get_film_player(id, mobile)
                if not mobile:
                    if player and request.user.is_superuser:
                        player = u'%s <div><input type="button" value="Удалить этот плеер" class="remove_online_player" id="%s__%s"/></div>' % (
                            player, id, psource)

            rate, show_ir, show_imdb, rotten = check_int_rates(id)

            rate_text = 'Репутация фильма: '
            m_rate = ''

            if show_imdb or rotten or show_ir:
                if show_imdb:
                    rate_text += 'IMDb - %s' % show_imdb
                    if mobile:
                        m_rate += '<div>Рейтинг IMDb: %s</div>' % show_imdb
                if rotten:
                    rate_text += ' / RottenTomatoes - %s' % rotten
                    if mobile:
                        m_rate += '<div>Рейтинг RottenTomatoes: %s</div>' % rotten
                if show_ir:
                    rate_text += ' / Киномэтры - %s' % show_ir
                    if mobile:
                        m_rate += '<div>Рейтинг от Киномэтров: %s</div>' % show_ir
            else:
                rate_text += 'нет'

            if rate == 0:
                rate = '?'

            rate_color = ''
            if rate == 5:
                rate_color = 'border-left: 20px solid rgba(60, 179, 113, 0.8);'
            elif rate == 4:
                rate_color = 'border-left: 20px solid rgba(126, 192, 238, 0.8);'
            elif rate == 3:
                rate_color = 'border-left: 20px solid rgba(255, 218, 185, 0.8);'
            elif rate == 2:
                rate_color = 'border-left: 20px solid rgba(238, 130, 238, 0.8);'

            details_data = get_film_details_data(id, mobile)

            if film['release']:
                if mobile:
                    releases = u'<div style="margin-bottom: 10px;"><b>Дата релиза:</b> %s</div>' % tmp_date(
                        film['release'], "d E Y")
                else:
                    releases = u'<span class="nolink" title="%s">дата релиза</span>' % tmp_date(
                        film['release'], "d E Y")
            else:
                if mobile:
                    releases = ''
                if not mobile:
                    releases = u'<span style="color: #666;" >дата релиза</span>'

            subscribe_me = ''
            #if request.user.is_superuser:
            #    subscribe_me = '<br />Ссылка для подписки "Хочу смотреть в кино":\
            #    <br />http://kinoinfo.ru/releases/%s/?subscribe' % id

            likes.update(details_data)

            likes.update({
                'status': True,
                'player': player,
                'name_ru': name_ru,
                'name_en': name_en,
                'year': film['year'],
                'afisha_rate': afisha_rate_tag,
                'imdb_rate': imdb_rate,
                'imdb_vote': imdb_vote,
                'comment': comment_tag,
                'description': description,
                'description_cut': description_cut,
                'limits': limit,
                'runtime': runtime_tag,
                'directors': directors_tag,
                'actors': actors_tag,
                'other_person': other_person_tag,
                'top_line': top_line,
                'posters': posters,
                'slides': slides,
                'slides_count': slides_count,
                'trailers': trailer,
                'trailers_count': trailers_count,
                'countries': countries_tag,
                'details': details_tag,
                'distributors': distributors_tag,
                'id': id,
                'subscription': subr,
                'subscriptions_accept': subscriptions_accept,
                'genre': genres_tag,
                'rate': rate,
                'rate_color': rate_color,
                'rate_text': rate_text,
                'subscribe_me': subscribe_me,
                'release': releases,
                'm_rate': m_rate,
            })

            return simplejson.dumps(likes)
        else:
            return simplejson.dumps({'status': 'False'})
    except Exception as e:
        open('errors.txt', 'a').write('%s * (%s)' % (dir(e), e.args))
Beispiel #7
0
def get_film_schedule(request, fkid, ckid):
    try:
        now = datetime.datetime.now()
        today = datetime.date.today()

        time_now = now.time()

        next_month = today + datetime.timedelta(days=14)

        sch = SourceSchedules.objects.select_related(
            'film', 'cinema', 'cinema__cinema', 'cinema__city',
            'source_obj').filter(dtime__gte=today,
                                 dtime__lte=next_month,
                                 cinema__cinema__id=ckid,
                                 film__kid=fkid).exclude(film__source_id=0)

        kinoinfo_dict = {}
        time_links = {}
        for i in sch:
            d = tmp_date(i.dtime.date(), 'd b').encode('utf-8')
            t = i.dtime.time()

            if i.extra:
                key = '%s%s' % (d, t)
                if not time_links.get(key):
                    time_links[key] = i

            if kinoinfo_dict.get(d):
                kinoinfo_dict[d]['times'].append(t)
            else:
                kinoinfo_dict[d] = {'date': i.dtime.date(), 'times': [t]}

        kinohod_tickets = ''
        rambler_tickets = ''

        if not kinohod_tickets:
            cinema = Cinema.objects.select_related('city').get(pk=ckid)

            sch = list(
                SourceSchedules.objects.filter(
                    dtime__gte=today,
                    dtime__lte=next_month,
                    cinema__city__city=cinema.city,
                    film__kid=fkid,
                    source_obj__url__in=('http://kinohod.ru/',
                                         'http://www.rambler.ru/'),
                    sale=True).exclude(
                        film__source_id=0).distinct('source_obj').values(
                            'film__name', 'cinema__city__name',
                            'film__source_id', 'cinema__city__source_id',
                            'source_obj__url'))

            for i in sch:
                if i['source_obj__url'] == 'http://kinohod.ru/':
                    #kinohod_tickets = u'<a href="http://kinohod.ru/" class="kh_boxoffice" ticket movie="%s" city="%s"></a>' % (i['film__name'], i['cinema__city__name'])
                    kinohod_tickets = u'<a href="http://kinohod.ru/movie/%s/" class="kh_boxoffice" kh:ticket kh:widget="movie" kh:id="%s" kh:city="%s"><span>Билеты</span></a>' % (
                        i['film__source_id'], i['film__source_id'],
                        i['cinema__city__name'])
                else:
                    rambler_tickets = u'<rb:movie key="%s" movieName="" cityName="" movieID="%s" cityID="%s" xmlns:rb="http://kassa.rambler.ru"></rb:movie>' % (
                        settings.RAMBLER_TICKET_KEY, i['film__source_id'],
                        i['cinema__city__source_id'])

        kinohod_key = settings.KINOHOD_APIKEY_CLIENT if kinohod_tickets else ''

        schedules = []
        for k, v in kinoinfo_dict.iteritems():
            times = ''
            for t in sorted(set(v['times'])):
                key = '%s%s' % (k, t)
                link = time_links.get(key)
                if times:
                    times += ', '

                if today == v['date'] and time_now > t:
                    link = None

                if link:
                    #times += "<a href='%s'>%s</a>" % (link.extra, t.strftime("%H:%M"))
                    times += "<a id='%s' title='Купить билет' class='ticket_widget'>%s</a>" % (
                        link.id, t.strftime("%H:%M"))
                else:
                    times += t.strftime("%H:%M")

            schedules.append({
                'dates': str(k),
                'times': times,
                'date': str(v['date'])
            })

        schedules = sorted(schedules, key=operator.itemgetter('date'))
        return simplejson.dumps({
            'status': 'True',
            'schedules': schedules,
            'kinohod_tickets': kinohod_tickets,
            'kinohod_key': kinohod_key,
            'rambler_tickets': rambler_tickets,
        })

    except Exception as e:
        open('errors.txt', 'a').write('%s * (%s)' % (dir(e), e.args))
Beispiel #8
0
def add_answer(request, text):
    try:

        if request.acc_list['acc']:
            text = BeautifulSoup(text.strip(),
                                 from_encoding='utf-8').text.strip()
            lang = get_language()

            try:
                language = Language.objects.get(code=lang)
            except Language.DoesNotExist:
                language = Language.objects.get(code='en')

            if len(text) > 2:
                question_id = request.META.get('HTTP_REFERER').split(
                    '/question/')[1].split('/')[0]

                filter = {
                    'reader_type': '22',
                    'questionanswer__id': question_id,
                    'translation_for': None
                }
                question_obj = News.objects.get(**filter)

                answer, created = News.objects.get_or_create(
                    title='',
                    text=text,
                    visible=True,
                    autor=request.profile,
                    site=request.current_site,
                    subdomain=0,
                    reader_type='23',
                    language=language,
                    parent=question_obj,
                    defaults={
                        'title': '',
                        'text': text,
                        'visible': True,
                        'autor': request.profile,
                        'site': request.current_site,
                        'subdomain': 0,
                        'reader_type': '23',
                        'language': language,
                        'parent': question_obj,
                    })

                html = u''
                if created:
                    qa = QAnswers.objects.create()
                    qa.item.add(answer)

                    author = org_peoples([answer.autor])[0]
                    text = answer.text

                    answer_txt = _(u'отвечает')

                    if lang == 'ru':
                        dtime = tmp_date(answer.dtime, 'd M Y г. H:i')
                    else:
                        dtime = tmp_date(answer.dtime, 'M d, Y, g:i a')

                    html += u'<div class="answer-item">'
                    html += u'<div class="answer-item-head">'
                    html += u'<div class="answer-item-author"><a href="/user/profile/%s/">%s</a> %s:</div>' % (
                        author['id'], author['name'], answer_txt)
                    html += u'<div class="answer-item-datetime">%s</div>' % dtime
                    html += u'</div>'
                    html += u'<div class="answer-item-body">'
                    html += u'<div class="answer-item-text">%s</div>' % text
                    html += u'</div></div>'

                return simplejson.dumps({'status': True, 'content': html})

        return simplejson.dumps({})
    except Exception as e:
        open('errors.txt', 'a').write('%s * (%s)' % (dir(e), e.args))
Beispiel #9
0
def add_question(request, subject, text, tags):
    try:

        if request.acc_list['acc']:
            subject = BeautifulSoup(subject.strip(),
                                    from_encoding='utf-8').text.strip()
            text = BeautifulSoup(text.strip(),
                                 from_encoding='utf-8').text.strip()
            lang = get_language()

            try:
                language = Language.objects.get(code=lang)
            except Language.DoesNotExist:
                language = Language.objects.get(code='en')

            if len(subject) > 1 and len(text) > 1:

                question, created = News.objects.get_or_create(
                    title=subject,
                    text=text,
                    visible=True,
                    autor=request.profile,
                    site=request.current_site,
                    subdomain=0,
                    reader_type='22',
                    language=language,
                    defaults={
                        'title': subject,
                        'text': text,
                        'visible': True,
                        'autor': request.profile,
                        'site': request.current_site,
                        'subdomain': 0,
                        'reader_type': '22',
                        'language': language,
                    })

                html = u''
                if created:
                    qa = QuestionAnswer.objects.create()
                    qa.item.add(question)

                    vid = request.META.get('HTTP_REFERER').split(
                        '/view/')[1].split('/')[0]

                    html_tags = u''
                    for tag in set(tags):
                        tag = tag.strip()
                        if tag:
                            obj, created = NewsTags.objects.get_or_create(
                                name=tag, defaults={'name': tag})
                            question.tags.add(obj)

                            html_tags += u'<a href="/view/%s/tag/%s/"><div class="item-tag">%s</div></a> ' % (
                                vid, tag, tag)

                    author = org_peoples([question.autor])[0]
                    #text = cut_description(question.text, True, 60)

                    answer_txt = _(u'спрашивает')

                    if lang == 'ru':
                        dtime = tmp_date(question.dtime, 'd M Y г. H:i')
                    else:
                        dtime = tmp_date(question.dtime, 'M d, Y, g:i a')

                    html += u'<div class="question-item">'
                    html += u'<div class="question-item-head">'
                    html += u'<div class="question-item-author"><a href="/user/profile/%s/">%s</a> %s:</div>' % (
                        author['id'], author['name'], answer_txt)
                    html += u'<div class="question-item-datetime">%s</div>' % dtime
                    html += u'</div>'
                    html += u'<div class="question-item-body">'
                    html += u'<div class="question-item-subject"><h2><a href="/view/%s/question/%s/">%s</a></h2></div>' % (
                        vid, qa.id, question.title)
                    #html += u'<div class="question-item-text">%s</div>' % text
                    html += u'<div class="question-item-tags">%s</div>' % html_tags
                    html += u'</div></div>'

                return simplejson.dumps({'status': True, 'content': html})

        return simplejson.dumps({})
    except Exception as e:
        open('errors.txt', 'a').write('%s * (%s)' % (dir(e), e.args))
Beispiel #10
0
def msg_html_wrapper(user_kid, obj, files, wfstat, statistic, likes,
                     is_mobile):
    html = ''
    if obj:
        text = obj.text
        subject = obj.subject
        for key, val in FORUM_SMILES.iteritems():
            text = text.replace(
                key,
                u'<img src="%sbase/images/forums/smiles/sk_%s.gif" alt="%s"/>'
                % (settings.STATIC_URL, val['id'], key))
            subject = subject.replace(
                key,
                u'<img src="%sbase/images/forums/smiles/sk_%s.gif" alt="%s"/>'
                % (settings.STATIC_URL, val['id'], key))

        date_msg = tmp_date(obj.date, "d b Y")

        try:
            nick = obj.nick if obj.nick else obj.user.nickname
        except AttributeError:
            nick = ''

        img = files.get(str(obj.id))
        if img:

            filesize = ''
            try:
                filepath = '%s/forums/women/%s' % (settings.MEDIA_ROOT, img)
                filesize = os.path.getsize(filepath)
                if filesize < 1048576:
                    filesize = '%.2f KB' % (float(filesize) / 1024)
                else:
                    filesize = '%.2f MB' % (float(filesize) / (1024 * 1024))
            except (OSError, IOError):
                pass

            url = '%sforums/women/%s' % (settings.MEDIA_URL, img)
            img = '<a class="fancybox wf_img" href="%s"><div> IMG<br />%s</div></a>' % (
                url, filesize)
        else:
            img = ''

        like_data = likes.get(obj.id)

        disl = 0
        like = 0
        if like_data:
            disl = like_data['d']
            like = like_data['l']

        edit_btn = ''
        if user_kid == obj.user_id:
            edit_btn = u'<input type="button" class="wf_edit" title="Редактировать" />'
            if not is_mobile:
                edit_btn += '''<input type="button" class="wf_xlike" value="%s" disabled />
                    <input type="button" class="wf_xdlike" value="%s" disabled />
                    ''' % (like, disl)
        elif user_kid and not is_mobile:
            edit_btn = u'''
                <input type="button" class="wf_ignore" title="Игнорировать"/>
                <input type="button" class="wf_like like" id="t1" title="Нравится" value="%s" />
                <input type="button" class="wf_like dislike" id="t0" title="Не нравится" value="%s" />
                <p id="wfi"></p>
                ''' % (like, disl)

        count = wfstat.get(obj.id, 0)

        msg_ignored = statistic['msg'].get(obj.id, {'count': 0})['count']
        topic_ignored = statistic['topic'].get(obj.id, {'count': 0})['count']
        author_ignored = statistic['author'].get(
            obj.id, {'count': 0}) if obj.user_id else {
                'count': 0
            }
        author_ignored = author_ignored['count']

        ignored_txt = u''
        if msg_ignored:
            ignored_txt += u'%sх' % msg_ignored
        if topic_ignored:
            if msg_ignored:
                ignored_txt += u'+'
            ignored_txt += u'%sхх' % topic_ignored
        if author_ignored:
            if msg_ignored or topic_ignored:
                ignored_txt += u'+'
            ignored_txt += u'%sххх' % author_ignored
        if ignored_txt:
            ignored_txt = ' <p id="igc"></p><a href="#" id="igi">%s</a> -' % ignored_txt

        html += u'''
            <tr class="fmsg" id="%s" >
            <td colspan="3">
            <div class="fmsg_h"><b>%s</b><span>%s</span>, %s</div>
            <div class="fmsg_b"><b>%s</b>%s <span>%s</span></div>
            <div class="fmsg_f">
                <input type="button" value="Ответить" id="answ" onclick="wf_msg(3, %s)"/> 
                <div class="wf_eye" title="Просмотров"><i>%s</i></div> 
                <div id="fmsg_fr">%s %s </div>
            </div>
            </td>
            </tr>
            ''' % (obj.id, nick, obj.date.strftime('%H:%M'), date_msg,
                   obj.subject, img, text, obj.id, count, ignored_txt,
                   edit_btn)
    return html
Beispiel #11
0
def forum_send_msg(request,
                   topic,
                   parent,
                   name,
                   email,
                   subject,
                   text,
                   anonim,
                   mtype,
                   preview=False,
                   edit=['0', '0']):
    try:
        from news.views import cut_description

        mtypes = {
            u'1': 1,  # Новая тема
            u'2': 2,  # Новое сообщение
            u'3': 3,  # Ответ на сообщение
        }

        name_error = ''
        text_error = ''
        name = name.strip()[:25]
        email = email.strip()[:50]
        text = text.strip()
        subject = subject.strip()[:128]

        if not name:
            name_error = u'Слишком короткое имя (не менее 1 символа)'
        if not text and not subject:
            text_error = u'Слишком короткая тема или сообщение'

        subj_end = ''
        if subject:
            subject, subj_end = cut_description(subject, False, 47, True)
        else:
            subject = text[:128]
            subject = cut_description(subject, False, 47)

        if subj_end:
            text = '%s %s' % (subj_end, text)

        mtype = mtypes.get(mtype)

        subject = html_entities_to_tags(subject)
        text = html_entities_to_tags(text)

        text = BeautifulSoup(text, from_encoding="utf-8").text
        subject = BeautifulSoup(subject, from_encoding="utf-8").text
        name = BeautifulSoup(name, from_encoding="utf-8").text
        email = BeautifulSoup(email, from_encoding="utf-8").text

        if mtype:

            if not name_error and not text_error:

                tmp_txt = text[:len(subject)]
                if tmp_txt == subject:
                    text = text[len(subject):]

                text = text.replace('\n', '<br />')

                if edit[0] == '0':
                    check_user = True if anonim or not request.profile.kid else False

                    error = False
                    if check_user:
                        try:
                            RegisteredUsers.objects.using('afisha').get(
                                nickname=name)
                            error = True
                        except RegisteredUsers.DoesNotExist:
                            error = False
                        except RegisteredUsers.MultipleObjectsReturned:
                            error = True

                        if not error:
                            try:
                                user = User.objects.get(
                                    first_name=name, profile__auth_status=True)
                                error = True
                            except User.DoesNotExist:
                                error = False

                else:
                    error = False

                if error:
                    name_error = u'В базе есть такой пользователь, <a class="kinoafisha_button">авторизуйтесь</a> или укажите другое имя!'
                    return simplejson.dumps({
                        'status': True,
                        'nerr': name_error,
                        'terr': ''
                    })
                else:
                    # если новое сообщение
                    if edit[0] == '0':
                        if request.profile.kid:
                            # зарегистрированный юзер
                            kid = request.profile.kid
                            if not anonim:
                                name = ''
                        else:
                            # новый/неавторизованный юзер с уникальным никнэймом
                            anonim = False

                            null_date = datetime.date(1900, 1, 1)
                            reg_obj = RegisteredUsers.objects.using(
                                'afisha').create(
                                    nickname='Bk276lPLIO83hjsdfJsdjj23',
                                    date_of_birth=null_date,
                                )

                            kid = reg_obj.id

                            reg_obj.nickname = name
                            reg_obj.save()

                            name = ''

                            request.profile.kid = kid
                            request.profile.save()

                    # редактирование
                    else:
                        try:
                            t = WFOpinion.objects.using(
                                'afisha').select_related('user').get(
                                    pk=edit[1])
                        except WFOpinion.DoesNotExist:
                            return simplejson.dumps({'status': False})
                        else:
                            if t.user_id == request.profile.kid:
                                kid = request.profile.kid
                                name = t.nick if t.nick else t.user.nickname

                    if preview:

                        html = ''
                        for key, val in FORUM_SMILES.iteritems():
                            text = text.replace(
                                key,
                                '<img src="%sbase/images/forums/smiles/sk_%s.gif"/>'
                                % (settings.STATIC_URL, val['id']))
                            subject = subject.replace(
                                key,
                                '<img src="%sbase/images/forums/smiles/sk_%s.gif"/>'
                                % (settings.STATIC_URL, val['id']))

                        date_now = datetime.datetime.now()
                        date_msg = tmp_date(date_now, "d E Y")

                        if name:
                            nick = name
                        else:
                            nick = ''
                            if kid:
                                try:
                                    nick = RegisteredUsers.objects.using(
                                        'afisha').get(pk=kid).nickname
                                except RegisteredUsers.DoesNotExist:
                                    pass

                        html += u'''
                            <div>
                            <div class="fmsg_h"><b>%s</b><p style="color: #FF5C33;">ПРЕДПРОСМОТР СООБЩЕНИЯ</p></div>
                            <div class="fmsg_b"><b>%s</b> <span>%s</span></div>
                            <div class="fmsg_f"></div>
                            </div>
                            ''' % (nick, subject, text)

                        return simplejson.dumps({
                            'status': True,
                            'content': html
                        })
                    else:

                        if edit[0] == '0':
                            newmsg = create_forum_msg(parent, topic, mtype,
                                                      kid, anonim, subject,
                                                      text, name, email)
                            vcount = 0 if mtype == 1 else 1
                            WFStat.objects.using('afisha').create(
                                opinion=newmsg.id, count=vcount)
                            WFUser.objects.using('afisha').create(
                                user=kid, opinion=newmsg.id)
                            request.session['wf_new_msg'] = newmsg.id
                        elif edit[0] == '1' and t.user_id == kid:
                            t.subject = subject
                            t.text = text
                            t.save()
                            newmsg = t

                        ref = request.META.get('HTTP_REFERER',
                                               '').split('?')[0]
                        mobile = 'm/' if '/m/' in ref else ''

                        redirect_to = '/women/%s' % mobile
                        next = ''
                        if topic:
                            redirect_to = '/women/%stopic/%s/' % (mobile,
                                                                  topic)
                            next = topic
                        if mtype == 1 and newmsg:
                            redirect_to = '/women/%stopic/%s/' % (mobile,
                                                                  newmsg.id)
                            next = newmsg.id

                        new_id = ''
                        if mtype in (2, 3) and newmsg:
                            new_id = newmsg.id

                        return simplejson.dumps({
                            'status': True,
                            'redirect_to': redirect_to,
                            'mid': new_id,
                            'next': next
                        })
            else:
                return simplejson.dumps({
                    'status': True,
                    'nerr': name_error,
                    'terr': text_error
                })

    except Exception as e:
        open('errors.txt', 'a').write('%s * (%s)' % (dir(e), e.args))