newmediamonitoring/dashboard/views.py

447 lines
16 KiB
Python

import csv
import json
import http.client
import random
from django.contrib.auth.decorators import login_required
from django.contrib.auth.hashers import make_password
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.utils import timezone
import time
from urllib import parse
from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
from dateutil import relativedelta
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.models import User
from django.db.models import Q
from django.http import Http404, HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render
import datetime
# Create your views here.
from dashboard.models import Userprofile, Organization, Area_code_2020, Weixin, Weibo, Toutiao, Qita, News, Douyin, \
CheckCode
from dashboard.yunpian import YunPian
import os
def refresh_captcha(request):
to_json_response = dict()
to_json_response['status'] = 1
to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])
return JsonResponse(to_json_response)
def index(request):
weixin_count = Weixin.objects.all().count()
weibo_count = Weibo.objects.all().count()
toutiao_count = Toutiao.objects.all().count()
qita_count = Qita.objects.all().count()
douyin_count = Douyin.objects.all().count()
organization_count = Organization.objects.filter(status='1').count()
# year = datetime.datetime.now().year
# month = datetime.datetime.now().month
# month = datetime.datetime.now().month
return render(request, 'dashboard/index.html',
{'weixin_count': weixin_count, 'weibo_count': weibo_count, 'toutiao_count': toutiao_count,
'qita_count': qita_count, 'douyin_count': douyin_count, 'organization_count': organization_count})
def user_login(request):
username = None
password = None
hash_key = CaptchaStore.generate_key()
image_url = captcha_image_url(hash_key)
if request.method == 'POST':
if not request.POST.get('username'):
messages.error(request, '请输入用户名')
else:
username = request.POST.get('username')
if not request.POST.get('password'):
messages.error(request, '请输入密码')
else:
password = request.POST.get('password')
captcha_input = request.POST.get('captcha_1')
captcha_hashkey = request.POST.get('captcha_0')
try:
CaptchaStore.objects.get(response=captcha_input.lower(), hashkey=captcha_hashkey,
expiration__gt=datetime.datetime.now()).delete()
except CaptchaStore.DoesNotExist:
messages.error(request, '验证码错误')
return HttpResponseRedirect('/')
print(username, password)
if username is not None and password is not None:
try:
user = authenticate(username=username, password=password)
# user = User.objects.get(username=phone)
if user is not None:
if user.check_password(password):
login(request, user)
return HttpResponseRedirect('/index/')
else:
messages.error(request, '无效的账号')
else:
messages.error(request, '账号或密码错误,请您确认账号和密码')
except:
messages.error(request, '账号或密码错误,请您确认账号和密码')
return render(request, 'dashboard/login.html', {'hash_key': hash_key, 'image_url': image_url})
def user_login_for_phone(request):
if request.method == 'GET':
return render(request, 'dashboard/login-for-phone.html')
elif request.method == 'POST':
p_code = request.POST.get('check_code')
phone = request.POST.get('phone')
print(phone, p_code)
results = CheckCode.objects.filter(phone=phone).count()
print(str(results) + "11111111111111111")
# try:
res = User.objects.filter(username=phone).count()
if res > 0:
messages.error(request, '您的账号已经存在,请您使用密码登录!!!')
return HttpResponseRedirect('/')
if results > 0:
check_code = CheckCode.objects.get(phone_code=p_code, phone=phone)
if User.objects.filter(username=phone).count() > 0:
user = User.objects.get(username=phone)
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
# check_code.delete()
return HttpResponseRedirect('/user/improve/personal/information/%s/' % (user.id))
else:
user = User(username=phone, last_login=timezone.now())
user.save()
# userprofile = Userprofile(user_id=user.id, image='default.png')
# userprofile.save()
u = authenticate(username=phone)
login(request, u, backend='django.contrib.auth.backends.ModelBackend')
return HttpResponseRedirect('/user/improve/personal/information/%s/' % (user.id))
# if float(time.time()) - float(check_code.c_time) > 60:
# check_code.delete()
# return '验证码超时已被删除'
# print(21333333333)
#
# except:
else:
print(1233333333)
messages.error(request, '请输入正确的验证码!!!')
return render(request, 'dashboard/login-for-phone.html')
def improve_personal_information(request, pk):
name = None
email = None
image = None
password = None
confirm_password = None
o_id = None
user = User.objects.get(id=pk)
if request.method == 'POST':
o = request.POST.get('organization')
if Organization.objects.get(name=o):
o_id = Organization.objects.get(name=o).id
else:
messages.error(request,'您填写的单位不存在!!!')
if request.POST.get('name'):
name = request.POST.get('name')
else:
messages.error(request,'请输入您的姓名!!!')
if request.POST.get('email'):
email = request.POST.get('email')
else:
messages.error(request,'请输入您的邮箱!!!')
if request.FILES.get('image'):
image = request.POST.get('image')
else:
image = '/profile/user_default.jpg'
if request.POST.get('password'):
password = request.POST.get('password')
else:
messages.error(request,'请输入密码')
confirm_password = request.POST.get('confirm_password')
if password is not None and confirm_password is not None:
if password == confirm_password:
User.objects.filter(id=pk).update(email=email,password=make_password(password))
userprofile=Userprofile(name=name,image=image,organization_id=o_id,user_id=user.id)
userprofile.save()
messages.success(request,'修改成功')
return render(request, 'dashboard/user-improve-personal-information.html', {'usee': user})
def author_code(request):
sms_host = "sms.yunpian.com"
voice_host = "voice.yunpian.com"
# 端口号
port = 443
# 版本号
version = "v2"
# 模板短信接口的URI
sms_tpl_send_uri = "/" + version + "/sms/tpl_single_send.json"
apikey = "304eb08353f7ebf00596737acfc31f53"
# mobile = "18119305139"
mobile = request.POST.get('mobile')
print(str(mobile) + "99999999999999999999999999999999999999999")
tpl_id = 4045320
code = ""
for i in range(6):
ch = chr(random.randrange(ord('0'), ord('9') + 1))
code += ch
print(code)
# tpl_value = {'#dateStart#': '10月1日', '#dateEnd#': '10日', '#type#': '微信公众号', '#name#': code}
tpl_value = {'#code#': code}
params = parse.urlencode({
'apikey': apikey,
'tpl_id': tpl_id,
'tpl_value': parse.urlencode(tpl_value),
'mobile': mobile
})
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"
}
conn = http.client.HTTPSConnection(sms_host, port=port, timeout=30)
conn.request("POST", sms_tpl_send_uri, params, headers)
response = conn.getresponse()
response_str = response.read()
try:
check_code = CheckCode.objects.get(phone=mobile)
check_code.phone_code = code
check_code.save()
except:
print(code, mobile, 1111111111)
check_code = CheckCode(phone_code=code, phone=mobile)
check_code.save()
conn.close()
return response_str
def user_logout(request):
logout(request)
return HttpResponseRedirect('/')
def register(request):
username = None
email = None
password = None
confirm_password = None
name = None
# phone = None
image = None
flag = False
user_organization = None
sex = None
user_organization = None
hash_key = CaptchaStore.generate_key()
image_url = captcha_image_url(hash_key)
organization = Organization.objects.filter(status='1')
if request.method == 'POST':
if not request.POST.get('organization'):
messages.error(request, '请选择单位')
else:
o = request.POST.get('organization')
res = Organization.objects.filter(name=o).count()
if res > 0:
user_organization = Organization.objects.get(name=o).id
else:
messages.error(request,'您填写的单位不存在')
if not request.POST.get('name'):
messages.error(request, '请输入姓名')
else:
name = request.POST.get('name')
if not request.POST.get('email'):
messages.error(request, '请输入邮箱')
else:
email = request.POST.get('email')
if not request.POST.get('username'):
messages.error(request, '请输入用户名')
else:
username = request.POST.get('username')
if not request.POST.get('password'):
messages.error(request, '请输入密码')
else:
password = request.POST.get('password')
if not request.POST.get('confirm_password'):
messages.error(request, '请再次输入密码')
else:
confirm_password = request.POST.get('confirm_password')
if not request.FILES.get('image'):
image='/profile/user_default.jpg'
else:
image = request.FILES.get('image')
print(str(image) + "1111111111111111111111111111111111111111111")
if request.POST.get('sex') == '1':
sex = ''
elif request.POST.get('sex') == '2':
sex = ''
captcha_input = request.POST.get('captcha_1')
captcha_hashkey = request.POST.get('captcha_0')
try:
CaptchaStore.objects.get(response=captcha_input.lower(), hashkey=captcha_hashkey,
expiration__gt=datetime.datetime.now()).delete()
except CaptchaStore.DoesNotExist:
messages.error(request, '验证码错误')
return HttpResponseRedirect('/register/')
if password is not None and confirm_password is not None:
if password == confirm_password:
flag = True
else:
messages.error(request, '两次输入的密码不一致,请重新输入')
filter_result = User.objects.filter(username=username)
if len(filter_result) > 0:
messages.error(request, '对不起,您输入的电话号码已被注册')
return HttpResponseRedirect('/register/')
if username is not None and password is not None and confirm_password is not None and email is not None and flag:
user = User.objects.create_user(username, email, password, last_login=timezone.now())
user.is_active = True
# user.is_staff = True
# user.first_name = phone
userprofile = Userprofile(name=name, image=image, user_id=user.id, organization_id=user_organization,
sex=sex, status=0)
userprofile.save()
user.save()
messages.success(request, '注册成功,请登录')
return HttpResponseRedirect('/')
return render(request, 'dashboard/register.html',
{'hash_key': hash_key, 'image_url': image_url, 'organization': organization})
def get_province(request):
# 省
province = Area_code_2020.objects.filter(level=1, name='甘肃省')
res = []
for i in province:
res.append([i.code, i.name, i.level, i.pcode])
return JsonResponse({"province": res})
def get_city(request):
code = request.GET.get('code')
print(code)
# 市
cities = Area_code_2020.objects.filter(pcode=code)
res = []
for i in cities:
res.append([i.code, i.name, i.level, i.pcode])
return JsonResponse({"city": res})
def get_district(request):
code = request.GET.get('code')
# 县
district = Area_code_2020.objects.filter(pcode=code)
res = []
for i in district:
res.append([i.code, i.name, i.level, i.pcode])
return JsonResponse({"district": res})
def get_town(request):
code = request.GET.get('code')
# 乡
town = Area_code_2020.objects.filter(pcode=code)
res = []
for i in town:
res.append([i.code, i.name, i.level, i.pcode])
return JsonResponse({"town": res})
def get_village(request):
code = request.GET.get('code')
# 村
village = Area_code_2020.objects.filter(pcode=code)
res = []
for i in village:
res.append([i.code, i.name, i.level, i.pcode])
return JsonResponse({"village": res})
def get_organization(request):
keywords = request.GET.get('keyword')
if len(keywords) != 0:
o = Organization.objects.filter(Q(name__contains=keywords))[:10]
topten_list = []
for i in o:
d = dict()
d['id'] = str(i.id)
d['name'] = i.name
if i.province:
d['province'] = Area_code_2020.objects.get(code=i.province).name
else:
d['province'] = ''
if i.cities:
d['cities'] = Area_code_2020.objects.get(code=i.cities).name
else:
d['cities'] = ''
if i.district:
d['district'] = Area_code_2020.objects.get(code=i.district).name
else:
d['district'] = ''
topten_list.append(d)
print(str(topten_list))
return render(request, 'dashboard/results_by_keywords.html', {'topten_list': topten_list})
def wechat_verify(request):
return HttpResponse("11833201729252855821")
def import_user(request):
with open('F:/总.csv') as csvfile:
reader = csv.reader(csvfile)
for r in reader:
organization = r[0]
name = r[1]
zhiwei = r[2]
phone = r[3]
o = Organization.objects.get(name=organization)
password = str(phone)[5:]
if phone:
try:
user = User.objects.create_user(username=phone, password=password, last_login=timezone.now())
user.save()
u = Userprofile(user_id=user.id, organization_id=o.id, status=1, image='/profile/user_default.jpg',
sex='', name=name, zhiwei=zhiwei)
u.save()
except:
print(phone)
return HttpResponse('ok')
@login_required
def user_search_by_keyword(request):
keytype = request.POST.get('keytype')
keyword = request.POST.get('ketword')
userprofile = None
if keytype == '1':
userprofile = Userprofile.objects.filter(name__contains=keyword)
elif keytype == '2':
userprofile = Userprofile.objects.filter(organization__name__contains=keyword)
paginator = Paginator(userprofile, 6)
page = int(request.GET.get('page', 1))
try:
userprofile = paginator.page(page)
except PageNotAnInteger:
userprofile = paginator.page(1)
except EmptyPage:
userprofile = paginator.page(paginator.num_pages)
for u in userprofile:
o = dict()
o['id'] = str(u.id)
o['name'] = u.name
o['image'] = u.image.url