Beispiel #1
0
def get_schedule(request):
    '''
    вывод сенсов с фильтами по городу и кинотеатру
    '''
    if not request.user.is_anonymous(): login_counter(request)
    # получаю объекты сеансов
    schedule = Session.objects.select_related('demonstration', 'demonstration__place', 'demonstration__place__cinema', 'demonstration__place__cinema__city').filter(demonstration__time__gte=fdate)
    de = []
    ci = []
    sch = []
    city_id = None
    cinema_id = None
    # выборка городов в которых есть сеансы
    for i in schedule.order_by('demonstration__place__cinema__city__name__name'):
        if i.demonstration.place.cinema.city not in de: de.append(i.demonstration.place.cinema.city)
    if request.method == 'POST':
        # если редактором выбран город, выборка кинотеатров в этом городе где есть сеансы
        if 'city' in request.POST and request.POST['city'] != '':
            city_id = int(request.POST['city'])
            for i in schedule.order_by('demonstration__place__cinema__name__name'):
                if i.demonstration.place.cinema.city_id == city_id and i.demonstration.place.cinema not in ci: 
                    ci.append(i.demonstration.place.cinema)
            # если редактором выбран кинотеатр, выборка сеансов в этом кинотеатре
            if 'cinema' in request.POST and request.POST['cinema'] != '':
                try:
                    cinema_id = int(request.POST['cinema'])
                    Demonstration.objects.filter(place__cinema__id = cinema_id, place__cinema__city__id = city_id)[0]
                    for i in schedule.order_by('demonstration__name', 'demonstration__time'):
                        if i.demonstration.place.cinema_id == cinema_id: sch.append(i)
                except IndexError: pass
    return render_to_response('kai/test_schedule.html', {'city': de, 'city_id': city_id, 'cinema': ci, 'cinema_id': cinema_id, 'schedule': sch}, context_instance=RequestContext(request))
Beispiel #2
0
def get_cinema(request):
    '''
    вывод кинотеатров (100 шт)
    '''
    if not request.user.is_anonymous(): login_counter(request)
    cinema = Cinema.objects.select_related(depth=2).all()[:100]
    halls = Hall.objects.select_related(depth=1).all()
    return render_to_response('kai/test_cinema.html', {'cinema': cinema, 'halls': halls}, context_instance=RequestContext(request))
Beispiel #3
0
def get_log(request, event):
    '''
    вывод лога
    '''
    if not request.user.is_anonymous(): login_counter(request)
    log = Logger.objects.filter(event=event)
    log_count = log.count()
    return render_to_response('kai/test_logger.html', {'log': log, 'log_count': log_count, 'event': int(event)}, context_instance=RequestContext(request))
Beispiel #4
0
def get_films(request):
    '''
    вывод фильмов 2012 (100 шт)
    '''
    if not request.user.is_anonymous(): login_counter(request)
    film = FilmsSources.objects.select_related(depth=3).filter(source__source='Киноафиша', id_films__release_end='2012-12-31')[:100]
    #imdb_rel = FilmsSources.objects.select_related(depth=1).filter(source__source='IMDb')
    #imdb = IMDB.objects.all()
    return render_to_response('kai/test_films.html', {'film': film}, context_instance=RequestContext(request))
Beispiel #5
0
def get_files_list_sms_schedule(request):
    '''
    Вывод списка временных файлов в шаблон
    '''
    if not request.user.is_anonymous(): login_counter(request)
    # получаю список фалов
    files_list = get_files_list()
    # узнаю кол-во фалов
    files_count = len(files_list)
    return render_to_response('kai/test_files_list.html', {'files_list': files_list, 'files_count': files_count}, context_instance=RequestContext(request))
Beispiel #6
0
def main(request, article=None):
    current_site = request.current_site
    if current_site.domain == 'kinoinfo.ru':
        template = 'articles/articles_main.html'
    elif current_site.domain == 'umru.net':
        template = 'articles/umrunet_articles_main.html'
    elif current_site.domain == 'kinoafisha.in.ua':
        template = 'articles/kua_articles_main.html'

    if request.user.is_authenticated():
        login_counter(request)
    if article:
        try:
            article = int(article)
            article = get_object_or_404(Articles,
                                        pk=article,
                                        site=current_site.id)
        except (ValueError, TypeError):
            raise Http404

    return render_to_response(template, {'article': article},
                              context_instance=RequestContext(request))
Beispiel #7
0
def main(request):
    """
    Главная страница, навигация
    """
    if not request.user.is_anonymous(): login_counter(request)
    return render_to_response('kai/main.html', context_instance=RequestContext(request)) 
Beispiel #8
0
def editor(request, event, code, id):
    '''
    Исправление ошибок в логе
    '''
    # удаление временного файла с данными о сеансах
    def delete_file_schedule(content):
        if content != '':
            # если после обработки файла осталась полезная информация, записываю в него
            file_sch = open(rel('sources/SMS/%s' % (extra)),'w').write(content)
            content = ''
        else:
            # если нет полезной информации, то удаляю файл
            os.remove(rel('sources/SMS/%s' % (extra)))
        # обновляю файл содержащий имена временных файлов
        file_counter = open(rel('sources/counter_hallssources_files'),'r').read()
        file_counter = file_counter.replace('%s ' % (extra), '')
        open(rel('sources/counter_hallssources_files'),'w').write(file_counter)
        
    # если метод GET
    def method_get(lang, search_msg, result, extra):
        # получаю частичные совпадения из БД
        result = part_search(model[0], model[2], name, extra) 
        return render_to_response('editor/editor.html', {'event': event, 'code': code, 'obj': name, 'result': result, 'id': id, 'lang': lang, 'search_msg': search_msg}, context_instance=RequestContext(request))
    
    # если метод POST
    def method_post(lang, search_msg, result):
        content = ''
        # если редактор удаляет запись из лога
        if 'log_del' in request.POST:
            # дополнительная обработка для имен фильмов
            if event == '1' and code == '4' or event == '3' and code == '3':
                file_sch = open(rel('sources/SMS/%s' % (extra)),'r')
                # во временном файле остаются только необходимые строки
                try:
                    for lines in file_sch.read().split('\n'):
                        line = lines.split('\t')
                        if line[2].replace('+', ' ') != name.encode('utf8'):
                            content += '%s\t%s\t%s\t%s\n' % (line[0], line[1], line[2], line[3])
                except IndexError: pass
                file_sch.close()
                # удаляю временный файл, если потребуется
                delete_file_schedule(content)
            # удаляю запись лога из БД
            Logger.objects.get(pk=id).delete()
        # если редактор производит поиск
        elif 'search' in request.POST:
            query = request.POST['search']
            # для городов/фильмов минимальное кол-во символов в с строке поиска должно быть не менее 3,
            # а для кинотеатров 2, иначе выведу сообщение об ошибке
            max_char = 3 if model[2] == 1 or model[2] == 2 else 2
            if len(query) >= max_char: result = search(model[0], model[2], query, extra) 
            else: search_msg = True
            return render_to_response('editor/editor.html', {'event': event, 'code': code, 'obj': name, 'result': result, 'id': id, 'lang': lang, 'search_msg': search_msg}, context_instance=RequestContext(request))
        # если редактор устанвлявает связь (сохранение алт.названия)
        else:
            # получаю данные
            obj = model[0].objects.get(pk=request.POST['set_rel_obj'])
            lang = Language.objects.get(pk=request.POST['set_rel_lang'])
            # если связь для фильмов
            if event == '1' and code == '4' or event == '3' and code == '3':
                file_sch = open(rel('sources/SMS/%s' % (extra)),'r')
                # извлекаю данные о сеансе из временного файла
                try:
                    for lines in file_sch.read().split('\n'):
                        line = lines.split('\t')
                        film_name = line[2].replace('+', ' ')
                        # получаю необходимую строку в файле
                        if film_name == name.encode('utf8'):
                            time = line[0]
                            # получаю объект зала
                            hall = Hall.objects.get(pk=line[1])
                            # сохраняю новое альт.название для фильма 
                            try: obj_name = model[1].objects.get(status=0, language=lang, name=line[2])
                            except model[1].DoesNotExist: obj_name = model[1].objects.create(status=0, language=lang, name=line[2])
                            # передаю извлеченные данные и сохранию сеанс
                            save_schedule(time, hall, obj_name, line[2])
                            # удаляю запись лога из БД
                            try: Logger.objects.get(pk=id).delete()
                            except Logger.DoesNotExist: pass
                        # все другие строки сохраняются дальше обратно в файл
                        else:
                            content += '%s\t%s\t%s\t%s\n' % (line[0], line[1], line[2], line[3])
                except IndexError: pass
                file_sch.close()
                # удаляю временный файл, если потребуется
                delete_file_schedule(content)
            # если связь для городов/кинотеатров
            else:
                # создаю новое альт.название для города/кинотеатра
                try: model[1].objects.get(status=0, language=lang, name=name)
                except model[1].DoesNotExist:           
                    obj_name = model[1].objects.create(status=0, language=lang, name=name)
                    # устанвляиваю связь
                    obj.name.add(obj_name)
                    # удаляю запись лога из БД
                    Logger.objects.get(pk=id).delete()
        return HttpResponseRedirect(reverse("get_log", kwargs={'event': event}))
    if not request.user.is_anonymous(): login_counter(request)
    # получаю переданные данные
    if request.method == 'GET' or request.method == 'POST':
        name = request.GET['obj']
        extra = request.GET['extra'] if 'extra' in request.GET else None
        lang = Language.objects.all()
        search_msg = False
        result = None
        #if event == '1' and code == '4' or event == '3' and code == '3': model = (Films, NameProduct) # для новой БД
        # задаю имена моделей в зависимости от события вызвавшее ошибку и запись в лог
        if event == '1' and code == '4' or event == '3' and code == '3': model = (NameProduct, NameProduct, 1) # для старой БД
        elif event == '2' and code == '1': model = (City, NameCity, 2)
        elif event == '2' and code == '2': model = (Cinema, NameCinema, 3)
    # обрабатываю данные в зависимости от метода
    if request.method == 'GET':
        return method_get(lang, search_msg, result, extra)
    elif request.method == 'POST':
        return method_post(lang, search_msg, result) 
    return HttpResponse('ошибка')
Beispiel #9
0
    def process_request(self, request):
        reg_b = re.compile(
            r"(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino",
            re.I | re.M)
        reg_v = re.compile(
            r"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-",
            re.I | re.M)

        domain_parts = request.get_host().split('.')
        if (len(domain_parts) > 2):
            if domain_parts[1] in ('com', 'net', 'biz', 'org', 'in'):
                subdomain = None
                domain = '.'.join(domain_parts)
            else:
                subdomain = domain_parts[0]
                if (subdomain.lower() == 'www'):
                    subdomain = None
                if subdomain == '127':
                    subdomain = None
                domain = '.'.join(domain_parts[1:])
            # для локального
            if domain == 'vseti.net:8000':
                domain = 'vsetiinter.net'
        else:
            subdomain = None
            domain = request.get_host()

        request.subdomain = subdomain
        request.domain = domain

        current_site = DjangoSite.objects.get_current()

        get_full_path = request.get_full_path().replace(u'/myapp.wsgi', '')

        if 'HTTP_USER_AGENT' in request.META:
            user_agent = request.META['HTTP_USER_AGENT']
            rb = reg_b.search(user_agent)
            rv = reg_v.search(user_agent[0:4])

            if rb or rv:
                mobile_cookie = request.COOKIES.get('mobile', '1')
                if mobile_cookie == '1':
                    if not subdomain and current_site.domain == 'kinoinfo.ru':
                        return HttpResponseRedirect("http://m.kinoinfo.ru/")
                    elif not subdomain and current_site.domain == 'kinoafisha.ru':
                        return HttpResponseRedirect("http://m.kinoafisha.ru/")
                    elif current_site.domain == 'vsetiinter.net' and subdomain == 'forums':
                        if '/women/' in get_full_path and '/m/' not in get_full_path:
                            if '/topic/' in get_full_path:
                                topic = get_full_path.split(
                                    'topic/')[-1].replace('/', '')
                                return HttpResponseRedirect(
                                    reverse('women_forum',
                                            kwargs={
                                                'm': 'm',
                                                'topic': topic
                                            }))
                            else:
                                return HttpResponseRedirect(
                                    reverse('women_forum', kwargs={'m': 'm'}))

        noob = False

        current_url = get_full_path.split(u'/api/')

        rating_img = False
        if '/ratingi' in get_full_path and '.png' in get_full_path:
            rating_img = True

        noindex = True if '/inform/' in get_full_path else False

        profile = None

        agent = False
        api = False
        if request.user.is_authenticated():
            try:
                profile = Profile.objects.select_related(
                    'person', 'user', 'personinterface').get(user=request.user)
            except Profile.DoesNotExist:
                auth.logout(request)

        if not rating_img and not request.user.is_authenticated():
            try:
                user_agent = low(request.META.get('HTTP_USER_AGENT', ''))
            except UnicodeDecodeError:
                open('LOGGING.TXT',
                     'a').write(str(request.META.get('HTTP_USER_AGENT')))
                raise UnicodeDecodeError

            agent = re.findall(
                '(yandexbot|yandexdirect|googlebot|yahoo|bingbot|mj12bot|spider|dotbot|siteexplorer|ahrefsbot|org_bot|hosttracker|smtbot|xovibot|ccbot|semrushbot|crawl|slurp|typhoeus|sputnikbot|blexbot|exabot|ru_bot|crawler)',
                user_agent)

            # не авторегистрируем юзера если это запрос к API
            if len(current_url) == 1 or u'/details/' in request.get_full_path(
            ):
                if agent:
                    agent_name = '%s__(BOT)' % agent[0]
                    profile = Profile.objects.filter(
                        accounts__login=agent_name).order_by('-id')

                    if len(profile) > 0:
                        profile = profile[0]

                    if profile:
                        # u = auth.authenticate(pk=profile.user_id, password='******')
                        # auth.login(request, u)

                        u = profile.user
                        u = auth.authenticate(username=u.username,
                                              password='******')
                        auth.login(request, u)
                    else:
                        auth_user(request)
                        profile = Profile.objects.select_related('person', 'user', 'personinterface').\
                            get(user=request.user)
                        acc = Accounts.objects.create(login=agent_name,
                                                      validation_code=None,
                                                      email=None)
                        profile.accounts.add(acc)
                else:
                    auth_user(request)
                    profile = Profile.objects.select_related(
                        'person', 'user',
                        'personinterface').get(user=request.user)
                    noob = True
                    # open('%s/ddd.txt' % settings.API_DUMP_PATH, 'a').write(str(user_agent) + '\n')
                    # pr = request.user.get_profile() # !
                    # pr.path = user_agent # !
                    # pr.save() # !
            else:
                api = True

        request.noob = noob

        current_user_city = None
        current_user_city_id = None
        country = None
        accounts = None
        fio = None
        money = '0.00'
        money_int = '0'
        my_sites = []

        now = datetime.datetime.now()

        bg_disable = False
        if profile:
            bg_disable = SiteBanners.objects.filter(
                btype='0', user=profile,
                bg_disable_dtime_to__gte=now).exists()

        bg_filter = {
            'site': current_site,
            'country__id': 2,
            'subdomain': subdomain
        }
        is_admin = False

        capitals = {
            2: {
                'id': 1,
                'name': 'Москва'
            },
            4: {
                'id': 48,
                'name': 'Минск'
            },
            43: {
                'id': 42,
                'name': 'Киев'
            },
            49: {
                'id': 105,
                'name': 'Астана'
            }
        }

        if request.user.is_authenticated() and not rating_img:
            accounts = org_peoples([profile])
            accounts = accounts[0] if accounts else {}

            if accounts and u'__(BOT)' in accounts['acc']:
                agent = True
            else:
                fio = accounts.get('fio')

                country = accounts.get('country_id')
                if country:
                    person_city = accounts['city_id']
                    bg_filter['country__id'] = accounts['country_id']
                    bg_filter['city__id'] = person_city

                    if person_city:
                        current_user_city_id = person_city
                        current_user_city = accounts['city']

                if not current_user_city_id:
                    # Определяем страну и город юзера
                    if not country:
                        ip = get_client_ip(request)
                        # для локальной машины
                        if ip == '127.0.0.1':
                            ip = '91.224.86.255'
                        country = get_country_by_ip(ip)
                        country = country.id if country else 2
                        if not capitals.get(country):
                            country = 2

                if not api and not agent:
                    my_sites = list(profile.site_admin.all().values_list(
                        'id', flat=True))
                    is_admin = True if long(
                        current_site.id) in my_sites else False

                    money = "%.2f" % profile.personinterface.money
                    money_int = int(profile.personinterface.money)

        if not country:
            country = 2

        if not current_user_city_id and not api and not rating_img:
            city = capitals.get(country)
            current_user_city_id = city['id']
            current_user_city = city['name']
            if profile:
                profile.person.city_id = current_user_city_id
                profile.person.country_id = country
                profile.person.save()

        new_messages = 0
        if not agent and not api and not rating_img and subdomain != 'forums':
            if profile:
                new_messages = NewsReaders.objects.filter(user=profile,
                                                          status='0').count()

        current_language = translation.get_language()
        if current_site.domain == 'imiagroup.com.au' and not translation.get_language(
        ):
            translation.activate('en')
            current_language = 'en'
        elif current_site.domain == 'vsetiinter.net':
            if subdomain in ('ivanov', ):
                translation.activate('en')
                current_language = 'en'

        if not agent and not api and not rating_img:
            login_counter(request)

        site_file = '%s/%s__mainpage.json' % (settings.SEO_PATH,
                                              current_site.domain)
        try:
            with open(site_file, 'r') as f:
                seo_data = json.loads(f.read())
            if seo_data.get('tags'):
                random.shuffle(seo_data['tags'])
        except IOError:
            seo_data = {}

        request.acc_list = accounts
        request.current_user_city = current_user_city
        request.current_user_city_id = current_user_city_id
        request.current_user_country_id = country
        request.profile = profile
        request.new_messages = new_messages
        request.fio = fio
        request.mymoney = money
        request.mymoney_int = money_int
        request.current_site = current_site
        request.is_admin = is_admin
        request.current_language = current_language
        request.noindex = noindex
        request.seo_data = seo_data
        request.bot = agent

        # Бэкграунд и рекламная ссылка
        adv = {'img': '', 'url': '', 'id': ''}
        if subdomain == 'forums':
            try:
                with open('%s/wf_top_banner.swf' % settings.BACKGROUND_PATH,
                          'r') as b:
                    b.read()
                adv['img'] = '%sbg/wf_top_banner.swf' % settings.MEDIA_URL
            except IOError:
                pass

            with open('%s/wf_ticker.txt' % settings.API_EX_PATH, 'r') as f:
                adv['url'] = f.read()
        else:
            if not agent and not api and not rating_img and not bg_disable:
                adv = get_bg(request)

        request.bg_img = adv['img']
        request.advert_url = adv['url']
        request.advert_id = adv['id']