Example #1
0
def set_answer_time(request, question_id):
    if request.user.is_authenticated() and request.method == 'POST':
        answer_time = request.POST.get('answer_time')
        video_id = request.POST.get('video_id')
        if answer_time:
            question = Question.objects.get(pk=question_id)
            group_name = question.room.legislative_body_initials
            if belongs_to_group(request.user, group_name):
                if answer_time == '0':
                    question.answer_time = None
                    question.answered = False
                else:
                    video = Video.objects.filter(video_id=video_id).first()
                    question.answer_time = answer_time
                    question.answered = True
                    question.video = video
                question.save()
                vote_list = []
                for vote in question.votes.all():
                    vote_list.append(encrypt(str(vote.user.id).rjust(10)))

                html = question.html_question_body(request.user, 'room')
                text = {
                    'question': True,
                    'html': html,
                    'id': question.id,
                    'voteList': vote_list,
                    'answered': question.answered,
                    'groupName': group_name,
                    'handlerAction': encrypt(str(request.user.id).rjust(10)),
                }
                Group(question.room.group_room_name).send(
                    {'text': json.dumps(text)}
                )

                html_question_panel = question.html_question_body(
                    request.user, 'question-panel')
                text_question_panel = {
                    'html': html_question_panel,
                    'id': question.id
                }
                Group(question.room.group_room_questions_name).send(
                    {'text': json.dumps(text_question_panel)}
                )
                return HttpResponse(status=200)
            else:
                return HttpResponseForbidden()
        else:
            return HttpResponseBadRequest('Invalid format.')
    else:
        return HttpResponseForbidden()
Example #2
0
def on_receive(message, pk):
    video = get_video(pk)
    data = get_data(message)

    if not video.closed_date:
        if set(data.keys()) != set(('handler', 'question', 'is_vote')):
            log.debug("Message unexpected format data")
            return
        else:
            log.debug('Question message is ok.')

        if not data['handler']:
            return

        user = User.objects.get(id=decrypt(data['handler']))
        if data['is_vote']:
            question = Question.objects.get(id=data['question'])
            if question.user != user:
                vote, created = UpDownVote.objects.get_or_create(
                    user=user, question=question, vote=True)
                if not created:
                    vote.delete()
        else:
            blackList = settings.WORDS_BLACK_LIST
            wordList = re.sub("[^\w]", " ", data['question'].lower()).split()
            censured_words = list(set(blackList) & set(wordList))
            query = data['question']

            if censured_words:
                for word in censured_words:
                    query = re.sub(word, '♥', query, flags=re.IGNORECASE)
            question = Question.objects.create(video=video,
                                               user=user,
                                               question=query)
            UpDownVote.objects.create(question=question, user=user, vote=True)

        vote_list = []
        for vote in question.votes.all():
            vote_list.append(encrypt(str(vote.user.id).rjust(10)))

        Group(video.group_questions_name).send({
            'text':
            json.dumps({
                'id': question.id,
                'user': encrypt(str(user.id).rjust(10)),
                'voteList': vote_list,
                'html': question.html_question_body(user)
            })
        })
Example #3
0
def send_change_email(user, email, site, request=None):
    ctx_dict = {} if request is None else RequestContext(request, {})
    prefix = getattr(settings, 'URL_PREFIX', 'http')
    redirect_url = ''
    if request:
        if getattr(request, 'GET'):
            if getattr(request.GET, 'next'):
                redirect_url = request.GET.get('next', '')

    ctx_dict.update({
        'user': user,
        'activation_key': '{}1'.format(encrypt('{0}||{1}||{2}'.format(user.id, email, random.randint(1, 100000)))),
        'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
        'site': site,
        'redirect_url': redirect_url,
        'prefix': prefix,
    })

    subject = (getattr(settings, 'REGISTRATION_EMAIL_SUBJECT_PREFIX', '') +
               render_to_string(
            'registration/activation_email_subject.txt', ctx_dict))

    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    from_email = getattr(settings, 'REGISTRATION_DEFAULT_FROM_EMAIL',
                         settings.DEFAULT_FROM_EMAIL)
    message_txt = render_to_string('registration/change_email.txt', ctx_dict)
    if request is None:
        message_txt = render_to_string('registration/change_email_fix.txt', ctx_dict)
    email_message = EmailMultiAlternatives(subject, message_txt,
                                           from_email, [email])
    email_message.send()
Example #4
0
 def html_question_body(self, user, page=None):
     return render_to_string(
         'includes/question_card.html', {
             'question': self,
             'user': user,
             'page': page,
             'author': encrypt(str(self.user.id).rjust(10))
         })
Example #5
0
 def html_question_body(self, user):
     return render_to_string(
         'includes/video_questions.html', {
             'question': self,
             'user': user,
             'object': self.video,
             'author': encrypt(str(self.user.id).rjust(10))
         })
Example #6
0
def set_priotity(request, question_id):
    if request.user.is_authenticated() and request.method == 'POST':
        is_priority = request.POST.get('is_priority')
        question = Question.objects.get(pk=question_id)
        group_name = question.room.legislative_body_initials
        if belongs_to_group(request.user, group_name):
            if is_priority == 'true':
                question.is_priority = True
            else:
                question.is_priority = False

            question.save()
            vote_list = []
            for vote in question.votes.all():
                vote_list.append(encrypt(str(vote.user.id).rjust(10)))
            html = question.html_question_body(request.user, 'room')
            text = {
                'question': True,
                'html': html,
                'id': question.id,
                'voteList': vote_list,
                'answered': question.answered,
                'groupName': group_name,
                'handlerAction': encrypt(str(request.user.id).rjust(10)),
            }
            Group(question.room.group_room_name).send(
                {'text': json.dumps(text)}
            )
            html_question_panel = question.html_question_body(
                request.user, 'question-panel')
            text_question_panel = {
                'html': html_question_panel,
                'id': question.id
            }
            Group(question.room.group_room_questions_name).send(
                {'text': json.dumps(text_question_panel)}
            )
            return HttpResponse(status=200)
        else:
            return HttpResponseForbidden()
    else:
        return HttpResponseForbidden()
Example #7
0
 def get_context_data(self, **kwargs):
     context = super(WidgetVideoDetail, self).get_context_data(**kwargs)
     if self.request.user.is_authenticated():
         context['handler'] = encrypt(str(self.request.user.id).rjust(10))
         context['groups'] = list(self.request.user.groups.all()
                                  .values_list('name', flat=True))
     context['questions'] = sorted(self.object.questions.all(),
                                   key=lambda vote: vote.votes_count,
                                   reverse=True)
     context['domain'] = Site.objects.get_current().domain
     return context
Example #8
0
    def get_context_data(self, **kwargs):
        context = super(VideoDetail, self).get_context_data(**kwargs)
        if self.request.user.is_authenticated():
            context['handler'] = encrypt(str(self.request.user.id).rjust(10))
        context['questions'] = sorted(self.object.questions.all(),
                                      key=lambda vote: vote.votes_count,
                                      reverse=True)
        context['answer_time'] = self.request.GET.get('t', None)
        context['domain'] = Site.objects.get_current().domain
        context['domain'] += settings.FORCE_SCRIPT_NAME

        return context
 def get_context_data(self, **kwargs):
     context = super(RoomQuestionList, self).get_context_data(**kwargs)
     priorities = self.object.questions.filter(
         is_priority=True, answered=False)
     other = self.object.questions.filter(is_priority=False, answered=False)
     answered = self.object.questions.filter(answered=True)
     priority_questions = sorted(
         priorities, key=lambda vote: vote.votes_count, reverse=True)
     other_questions = sorted(
         other, key=lambda vote: vote.votes_count, reverse=True)
     answered_questions = sorted(
         answered, key=lambda vote: vote.votes_count, reverse=True)
     context['no_offset_top'] = 'no-offset-top'
     context['questions'] = list(chain(
         priority_questions, other_questions, answered_questions))
     context['counter'] = self.object.questions.count()
     if self.request.user.is_authenticated():
         context['handler'] = encrypt(str(self.request.user.id).rjust(10))
     return context
Example #10
0
def send_validation(strategy, backend, code):
    encoded = base64.b64encode(strategy.request.session.session_key)
    verification_code = encrypt('{0}||{1}'.format(code.code, encoded))

    url = '{0}?verification_code={1}'.format(
        reverse('email_complete', args=(backend.name,)), verification_code
    )
    url = strategy.request.build_absolute_uri(url)
    # Убедимся, что мы правильно ходим в случае https
    url_parts = url.split('://')
    if hasattr(settings, 'URL_PREFIX'):
        url_parts[0] = settings.URL_PREFIX
    text = u'''
    Регистрация на сайте Открытое образование.

    Для активации вашего аккаунта необходимо перейти по ссылке:
    {0}://{1}

    Спасибо!
    '''.format(url_parts[0], url_parts[1])
    send_mail(u'Активация аккаунта Открытое образование', text,
              settings.EMAIL_FROM, [code.email], fail_silently=False)
Example #11
0
def send_validation(strategy, backend, code):
    encoded = base64.b64encode(strategy.request.session.session_key)
    verification_code = encrypt('{0}||{1}'.format(code.code, encoded))

    url = '{0}?verification_code={1}'.format(
        reverse('email_complete', args=(backend.name, )), verification_code)
    url = strategy.request.build_absolute_uri(url)
    # Убедимся, что мы правильно ходим в случае https
    url_parts = url.split('://')
    if hasattr(settings, 'URL_PREFIX'):
        url_parts[0] = settings.URL_PREFIX
    text = u'''
    Регистрация на сайте Открытое образование.

    Для активации вашего аккаунта необходимо перейти по ссылке:
    {0}://{1}

    Спасибо!
    '''.format(url_parts[0], url_parts[1])
    send_mail(u'Активация аккаунта Открытое образование',
              text,
              settings.EMAIL_FROM, [code.email],
              fail_silently=False)
Example #12
0
def on_receive(message, pk):
    room = get_room(pk)
    data = get_data(message)

    if 'heartbeat' in data.keys():
        Presence.objects.touch(message.reply_channel.name)
        return

    if not data['handler']:
        return

    blackList = [x.strip() for x in config.WORDS_BLACK_LIST.split(',')]

    if set(data.keys()) == set(('handler', 'question', 'is_vote')):
        user = User.objects.get(id=decrypt(data['handler']))
        if data['is_vote']:
            question = Question.objects.get(id=data['question'])
            if question.user != user:
                vote, created = UpDownVote.objects.get_or_create(
                    user=user, question=question, vote=True)
                if not created:
                    vote.delete()
        else:
            if len(data['question']) <= 300:
                wordList = re.sub("[^\w]", " ",
                                  data['question'].lower()).split()
                censured_words = list(set(blackList) & set(wordList))
                query = data['question']

                if censured_words:
                    for word in censured_words:
                        query = re.sub(word, '♥', query, flags=re.IGNORECASE)
                question = Question.objects.create(room=room,
                                                   user=user,
                                                   question=query)
                UpDownVote.objects.create(question=question,
                                          user=user,
                                          vote=True)
            else:
                return

        vote_list = []
        for vote in question.votes.all():
            vote_list.append(encrypt(str(vote.user.id).rjust(10)))

        Group(room.group_room_name).send({
            'text':
            json.dumps({
                'id': question.id,
                'question': True,
                'user': encrypt(str(user.id).rjust(10)),
                'groupName': question.room.legislative_body_initials,
                'voteList': vote_list,
                'answered': question.answered,
                'html': question.html_question_body(user, 'room')
            })
        })

        log.debug('Question message is ok.')

    elif set(data.keys()) == set(('handler', 'message')):
        word_list = re.sub("[^\w]", " ", data['message'].lower()).split()
        censured_words = list(set(blackList) & set(word_list))

        message = data['message']

        if message.strip():
            if censured_words:
                for word in censured_words:
                    message = re.sub(word, '♥', message, flags=re.IGNORECASE)

            user = User.objects.get(id=decrypt(data['handler']))
            message = Message.objects.create(room=room,
                                             user=user,
                                             message=message)
            Group(room.group_room_name).send({
                'text':
                json.dumps({
                    "chat": True,
                    "html": message.html_body()
                })
            })

        log.debug('Chat message is ok.')

    else:
        log.debug("Message unexpected format data")
        return