Exemplo n.º 1
0
def edit_profile(request, username):

	if request.method == 'POST':
		if request.POST.get('type') == 'profile-pic':
			form = UploadFileForm(request.POST, request.FILES)
			if form.is_valid():
				f = request.FILES['file']
				file_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
				file_name += str(f)

				with open('django_project/media/avatars/' + file_name, 'wb+') as destination:
					for chunk in f.chunks():
						destination.write(chunk)
				u = UserProfile.objects.get(user=request.user)
				u.avatar = 'avatars/' + file_name
				u.save()
			return redirect('/user/' + username)
		if request.POST.get('type') == 'bio':
			u = UserProfile.objects.get(user=request.user)
			u.bio = request.POST.get('bio')
			u.save()
			return redirect('/user/' + username)
		if request.POST.get('type') == 'username':

			username = request.POST.get('username')

			# validação do novo nome de usuário:
			r = r'^[-\w_ ]+$'
			try:
				re.search(r, username)[0]
			except:
				html = '<div class="alert alert-danger"><p>O nome de usuário deve conter apenas caracteres alfanuméricos, hífens, underscores e espaços.</p></div>'
				return render(request, 'edit-profile.html', {'invalid_username_text': html,
															 'username': username,
															 'invalid_username': '******'})

			if len(username) > 30:
				return HttpResponse('Escolha um nome de usuário menor ou igual a 30 caracteres.')

			if User.objects.filter(username=username).exists():
				return render(request, 'edit-profile.html', {'user_p': UserProfile.objects.get(user=User.objects.get(username=username)), 'username_display': 'block', 'invalid_username': '******'})

			password = request.POST.get('password')
			user = authenticate(username=request.user.username, password=password)
			if user is None:
				if not User.objects.filter(username=request.POST.get('username')).exists():
					return render(request, 'edit-profile.html', {'user_p': UserProfile.objects.get(user=User.objects.get(username=username)), 'password_display': 'block', 'invalid_password': '******'})
			user.username = request.POST.get('username').strip()
			user.save()
			login(request, user)
			return redirect('/user/' + user.username)

	return render(request, 'edit-profile.html', {'user_p': UserProfile.objects.get(user=User.objects.get(username=username))})
Exemplo n.º 2
0
def ask(request):
	'''
	Teste de banimento.
	'''
	if Ban.objects.filter(ip=str(get_client_ip(request))).exists():
		return HttpResponse(Ban.objects.get(ip=client_ip).message)

	'''
	Controle de spam
	'''
	try:
		last_q = Question.objects.filter(creator=UserProfile.objects.get(user=request.user))
		last_q = last_q[last_q.count()-1] # pega a última questão feita pelo usuário.

		# verifica se já passou 20 segundos:
		if (timezone.now() - last_q.pub_date).seconds < 20:
			return HttpResponse('<p>Você deve esperar {} segundos para perguntar novamente.'.format(20 - (timezone.now() - last_q.pub_date).seconds))
	except:
		pass

	if request.method == 'POST':
		if request.POST.get('question') == '' or request.POST.get('question') == '.':
			return render(request, 'ask.html', {'error': '<p>Pergunta inválida.</p>'})

		description = bs(request.POST.get('description'), 'html.parser').text
		text = bs(request.POST.get('question'), 'html.parser').text
		description = replace_url_to_link(description) # transforma links (http, https, etc) em âncoras.

		if not is_a_valid_question(text, description):
			return HttpResponse('Proibido.')

		q = Question.objects.create(creator=UserProfile.objects.get(user=request.user), text=text, description=description)

		form = UploadFileForm(request.POST, request.FILES)
		if form.is_valid():
			f = request.FILES['file']

			file_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
			file_name += str(f)
			# em produção: with open('django_project/media/questions/' + file_name, 'wb+') as destination:
			with open('django_project/media/questions/' + file_name, 'wb+') as destination:
				for chunk in f.chunks():
					destination.write(chunk)
			q.image = 'questions/' + file_name
			q.save()

		u = UserProfile.objects.get(user=request.user)
		u.total_points += 1
		u.save()

		return redirect('/question/' + str(q.id))

	return render(request, 'ask.html', {'user_p': UserProfile.objects.get(user=request.user)})
Exemplo n.º 3
0
def profile(request, username):

    user = User.objects.filter(username=username)

    if user.exists():
        up = UserProfile.objects.filter(user=user.first())  # user profile
        if not up.exists():
            return user_does_not_exists(request)
        up = up.first()
    else:
        return user_does_not_exists(request)

    if request.user.username == username:
        user_p = UserProfile.objects.get(user=request.user)
        user_p.ip = get_client_ip(request)
        user_p.save()

    if request.user.username != username:
        up.total_views += 1
        up.save()

    context = {'user_p': up, 'change_profile_picture_form': UploadFileForm()}

    if request.user.username == username or not up.hide_activity:
        q_page = request.GET.get('q-page', 1)
        r_page = request.GET.get('r-page', 1)

        context['questions'] = Paginator(
            Question.objects.filter(creator=up).order_by('-pub_date'),
            10).page(q_page).object_list
        context['responses'] = Paginator(
            Response.objects.filter(creator=up).order_by('-pub_date'),
            10).page(r_page).object_list

    return render(request, 'profile.html', context)
Exemplo n.º 4
0
def profile(request, username):
	if request.user.username != username and request.user.username != 'Erick':
		u = UserProfile.objects.get(user=User.objects.get(username=username))
		u.total_views += 1
		u.save()

	context = {'user_p': UserProfile.objects.get(user=User.objects.get(username=username)),
			   'change_profile_picture_form': UploadFileForm()}

	if request.user.username == username:
		q_page = request.GET.get('q-page', 1)
		r_page = request.GET.get('r-page', 1)

		context['questions'] = Paginator(Question.objects.filter(creator=UserProfile.objects.get(user=request.user)).order_by('-pub_date'), 10).page(q_page).object_list
		context['responses'] = Paginator(Response.objects.filter(creator=UserProfile.objects.get(user=request.user)).order_by('-pub_date'), 10).page(r_page).object_list

	if request.method == 'POST':

		new_bio = request.POST.get('bio', None)

		if new_bio != None:
			u = UserProfile.objects.get(user=request.user)
			u.bio = new_bio
			u.save()
			return redirect('/user/' + username)

		form = UploadFileForm(request.POST, request.FILES)
		if form.is_valid():
			f = request.FILES['file']

			file_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
			file_name += str(f)

			with open('django_project/media/avatars/' + file_name, 'wb+') as destination:
				for chunk in f.chunks():
					destination.write(chunk)

			u = UserProfile.objects.get(user=request.user)
			u.avatar = 'avatars/' + file_name
			u.save()

			return redirect('/user/' + request.user.username)

	return render(request, 'profile.html', context)
Exemplo n.º 5
0
def edit_profile(request, username):

    if request.method == 'POST':
        if request.POST.get('type') == 'profile-pic':
            form = UploadFileForm(request.POST, request.FILES)
            if form.is_valid():

                u = UserProfile.objects.get(user=request.user)
                '''
                Já que vai trocar de avatar, apaga o avatar antigo se tiver.
                '''
                if u.avatar and u.avatar.name != 'avatars/default-avatar.png':
                    os.system('rm ' + u.avatar.path)

                f = request.FILES['file']
                '''
                Nome da imagem do usuário no sistema de arquivos: nome de usuário atual, data de alteração e horário da alteração.
                '''
                file_name = '{}-{}-{}'.format(request.user.username,
                                              timezone.now().date(),
                                              timezone.now().time())

                success = save_img_file(
                    f, 'django_project/media/avatars/' + file_name, (192, 192))
                if not success:
                    return redirect('/user/' + request.user.username + '/edit')

                u.avatar = 'avatars/' + file_name
                u.save()
            return redirect('/user/' + username)
        if request.POST.get('type') == 'bio':
            u = UserProfile.objects.get(user=request.user)
            u.bio = request.POST.get('bio')
            u.save()
            return redirect('/user/' + username)
        if request.POST.get('type') == 'username':

            username = request.POST.get('username')
            '''
            Validação do nome de usuário: é permitido apenas letras, números, hífens, undercores e espaços.
            '''
            # verificando caractere por caractere:
            pode = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_ '
            for ch in username:
                if ch in pode:
                    continue

                html = '<div class="alert alert-danger"><p>O nome de usuário deve conter apenas caracteres alfanuméricos, hífens, underscores e espaços.</p></div>'
                return render(
                    request, 'edit-profile.html', {
                        'invalid_username_text': html,
                        'username': username,
                        'invalid_username': '******'
                    })

            if '  ' in username:
                html = '<div class="alert alert-danger"><p>O nome de usuário não pode conter espaços concomitantes.</p></div>'
                return render(
                    request, 'edit-profile.html', {
                        'invalid_username_text': html,
                        'username': username,
                        'invalid_username': '******'
                    })

            if len(username) > 30:
                return HttpResponse('Erro.')

            if User.objects.filter(username=username).exists():
                return render(
                    request, 'edit-profile.html', {
                        'user_p':
                        UserProfile.objects.get(user=User.objects.get(
                            username=username)),
                        'username_display':
                        'block',
                        'invalid_username':
                        '******'
                    })

            password = request.POST.get('password')
            user = authenticate(username=request.user.username,
                                password=password)
            if user is None:
                if not User.objects.filter(
                        username=request.POST.get('username')).exists():
                    try:
                        return render(
                            request, 'edit-profile.html', {
                                'user_p':
                                UserProfile.objects.get(user=User.objects.get(
                                    username=username)),
                                'password_display':
                                'block',
                                'invalid_password':
                                '******'
                            })
                    except:
                        return render(
                            request, 'edit-profile.html', {
                                'user_p':
                                UserProfile.objects.get(user=User.objects.get(
                                    username=request.user.username)),
                                'password_display':
                                'block',
                                'invalid_password':
                                '******'
                            })
            user.username = request.POST.get('username').strip()
            user.save()
            login(request, user)
            return redirect('/user/' + user.username)
        if request.POST.get('type') == 'privacy':
            u = UserProfile.objects.get(user=request.user)
            if request.POST.get('hide-activity') is not None:
                u.hide_activity = True
            else:
                u.hide_activity = False
            u.save()
            return redirect('/user/' + username)

    return render(
        request, 'edit-profile.html', {
            'user_p':
            UserProfile.objects.get(user=User.objects.get(username=username))
        })
Exemplo n.º 6
0
def ask(request):

    if request.user.is_anonymous:
        return redirect('/question/%d' % Question.objects.all().last().id)

    client_ip = get_client_ip(request)
    if Ban.objects.filter(ip=client_ip).exists():
        return redirect('/question/%d' % Question.objects.all().last().id)
    '''
    Controle de spam
    '''
    try:
        last_q = Question.objects.filter(creator=UserProfile.objects.get(
            user=request.user))
        last_q = last_q[last_q.count() -
                        1]  # pega a última questão feita pelo usuário.
        if (timezone.now() - last_q.pub_date).seconds < 25:
            return_to = request.META.get("HTTP_REFERER") if request.META.get(
                "HTTP_REFERER") is not None else '/'
            context = {
                'error':
                'Ação não autorizada',
                'err_msg':
                'Você deve esperar {} segundos para perguntar novamente.'.
                format(25 - (timezone.now() - last_q.pub_date).seconds),
                'redirect':
                return_to
            }
            return render(request, 'error.html', context)
    except:
        pass

    if request.method == 'POST':
        description = request.POST.get('description')
        description = description.replace('\r', '')
        description = html.escape(description)

        text = request.POST.get('question')

        if len(text) > 181:
            return HttpResponse('Proibido.')

        q = Question.objects.create(
            creator=UserProfile.objects.get(user=request.user),
            text=text,
            description=description.replace('\\', '\\\\'))

        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            f = request.FILES['file']

            file_name = 'qpic-{}{}'.format(timezone.now().date(),
                                           timezone.now().time())

            success = save_img_file(
                f, 'django_project/media/questions/' + file_name, (850, 850))
            if success:
                q.image = 'questions/' + file_name

            q.save()

        ccount = request.POST.get('choices-count')
        if ccount.isdigit():
            is_multichoice = request.POST.get('is-multichoice') is not None
            ccount = int(ccount)
            if ccount <= general_rules.MAXIMUM_POLL_CHOICES and ccount > 1:  # Proteção de POST manual
                qpoll = Poll.objects.create(question=q,
                                            is_anonymous=True,
                                            multichoice=is_multichoice)
                for i in range(1, ccount + 1):
                    choice = request.POST.get('choice-' + str(i))
                    if len(choice) <= 60 and len(
                            choice) >= 1 and choice.replace(' ', '') != '':
                        PollChoice.objects.create(poll=qpoll, text=choice)
                    else:
                        PollChoice.objects.create(poll=qpoll, text="...")

        u = UserProfile.objects.get(user=request.user)
        u.total_points += 1
        u.save()

        return redirect('/question/' + str(q.id))

    return render(request, 'ask.html',
                  {'user_p': UserProfile.objects.get(user=request.user)})
Exemplo n.º 7
0
def save_answer(request):

    client_ip = get_client_ip(request)
    if Ban.objects.filter(ip=client_ip).exists():
        return HttpResponse('Você não pode responder perguntas.')

    question = Question.objects.get(id=request.POST.get('question_id'))

    response_creator = UserProfile.objects.get(
        user=request.user)  # criador da nova resposta.
    '''
    Testa se o usuário já respondeu a pergunta:
    '''
    if Response.objects.filter(creator=response_creator,
                               question=question).exists():
        return HttpResponse('Você já respondeu essa pergunta.')

    if question.creator.blocked_users.filter(
            username=request.user.username).exists():
        return HttpResponse('Você não pode responder essa pergunta.')

    response = Response.objects.create(question=question,
                                       creator=response_creator,
                                       text=request.POST.get('text'))

    question.total_responses += 1
    question.save()

    response_creator.total_points += 2
    response_creator.save()

    if response_creator.user not in question.creator.silenced_users.all():
        notification = Notification.objects.create(
            receiver=question.creator.user, type='question-answered')
        notification.set_text(response.id)
        notification.save()

    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        f = request.FILES['file']

        now = timezone.now()

        file_name = 'rpic-{}{}'.format(now.date(), now.time())

        success = save_img_file(f,
                                'django_project/media/responses/' + file_name,
                                (850, 850))
        if success:
            response.image = 'responses/' + file_name

        response.save()

    if request.POST.get('from') == 'index':
        return render(request, 'base/response-content-index.html', {
            'question': question,
            'ANSWER': response,
        })

    return render(request, 'base/response-content.html', {
        'question': question,
        'response': response,
    })
Exemplo n.º 8
0
def question(request, question_id):

	try:
		q = Question.objects.get(id=question_id)
	except:
		# pergunta não encontrada:
		return HttpResponse('''<html>
			<head>
				<meta charset="utf-8">
				<meta name="viewport" content="width=device-width, initial-scale=1">
			</head>
			<body>
				<p>Essa pergunta não existe, talvez ela tenha sido apagada pelo criador da pergunta. <a href="/">Clique aqui</a> para voltar para a página inicial.</p>
			</body>
			</html>''')

	if request.method == 'POST':

		# para evitar respostas duplas:
		if Response.objects.filter(creator=UserProfile.objects.get(user=request.user), question=q).exists():
			return HttpResponse('OK')

		text = request.POST.get('response')
		if not is_a_valid_response(text):
			return HttpResponse('Proibido.')

		r = Response.objects.create(question=q, creator=UserProfile.objects.get(user=request.user), text=text)

		''' Upload de imagens: '''
		form = UploadFileForm(request.POST, request.FILES)
		if form.is_valid():
			f = request.FILES['file']

			file_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
			file_name += str(f)
			# em produção: with open('django_project/media/responses/' + file_name, 'wb+') as destination:
			with open('django_project/media/responses/' + file_name, 'wb+') as destination:
				for chunk in f.chunks():
					destination.write(chunk)
			r.image = 'responses/' + file_name
			r.save()

		u = UserProfile.objects.get(user=request.user)
		u.total_points += 2
		u.save()

		# cria a notificação da resposta:
		n = Notification.objects.create(receiver=r.question.creator.user,
										type='question-answered')
		n.set_text(r.id)
		n.save()

		q.total_responses += 1
		q.save()

		json = {'answer_id': r.id}

		try:
			image_url = r.image.url
			json['has_image'] = True
			json['image_url'] = r.image.url
		except:
			json['has_image'] = False

		return JsonResponse(json)

	context = {'question': q,
			   'responses': Response.objects.filter(question=q).order_by('-pub_date').order_by('-total_likes')}

	if not request.user.is_anonymous:
		context['user_p'] = UserProfile.objects.get(user=request.user)
		context['answered'] = Response.objects.filter(creator=UserProfile.objects.get(user=request.user), question=q).exists()

	# questões recomendadas:
	qs = Question.objects.all().order_by('-pub_date')[:50]
	qs_list = list(qs)
	shuffle(qs_list)

	context['recommended_questions'] = qs_list[:20]

	return render(request, 'question.html', context)