296 lines
12 KiB
Python
296 lines
12 KiB
Python
from django.shortcuts import render
|
||
from django.views import View
|
||
from django.conf import settings
|
||
from django.db.models import Count
|
||
import os
|
||
import logging
|
||
from datetime import datetime
|
||
|
||
from .task import import_project
|
||
from .models import Project, File
|
||
from .forms import NewProjectForm
|
||
from operations.models import Article, Annotation, Issue, QuestionAnswer,AnnotationStrategy
|
||
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
|
||
from utils import get_project_tree,scanner_project
|
||
from utils.models import projectTreeObj
|
||
|
||
from users.models import User
|
||
from django.contrib.auth.hashers import make_password #把明文密码加密
|
||
from django.contrib.auth import authenticate, login, logout
|
||
import requests
|
||
import json
|
||
import random
|
||
|
||
|
||
logger = logging.getLogger('django')
|
||
sourcepath = settings.SOURCEPATH
|
||
|
||
class NewProjectView(View):
|
||
|
||
def get(self, request):
|
||
project_form = NewProjectForm()
|
||
return render(request, 'projects/new.html', locals())
|
||
|
||
def post(self, request):
|
||
project_form = NewProjectForm(request.POST)
|
||
if project_form.is_valid():
|
||
# print(Project.objects.filter(name=project_form.name))
|
||
# if len(Project.objects.filter(name=project_form.name))>0:
|
||
# return HttpResponse("导入失败,项目名字已存在,请联系管理员更换后台名字")
|
||
logging.info('开始尝试导入工程')
|
||
project = project_form.save(commit=False)
|
||
print(project)
|
||
# project.path = project.name
|
||
project.save()
|
||
project_form.save_m2m()
|
||
project_id = project.id
|
||
root_path = project.path
|
||
try:
|
||
logging.info(str(datetime.now()) + '准备导入工程')
|
||
print("import_project start")
|
||
import_project(project_id, root_path)
|
||
print("import_project done")
|
||
# scanner_project
|
||
print("scanner_project start")
|
||
scanner_project_obj = scanner_project.Scanner_Project_Object()
|
||
scanner_project_obj.get_anno_issue_summary("/opt/opengrok/source/"+project.name, project.id)
|
||
print("scanner_project done")
|
||
# 设置默认的权限,默认为所有人都可以看见
|
||
stragegy = AnnotationStrategy()
|
||
stragegy.project = project
|
||
stragegy.choice = 1
|
||
stragegy.save()
|
||
print("set annotationStrategy done")
|
||
# return render(request, 'projects/list.html', locals())
|
||
return HttpResponse("New Project Done!!")
|
||
|
||
except Exception as e:
|
||
print(str(e))
|
||
# # logging.error(str(datetime.now()) + ' 导入' + str(project.name) + '失败,错误原因是:' + str(e) + '准备删除工程')
|
||
# # logging.info(str(datetime.now()) + '开始删除导入本工程,稍后重新导入')
|
||
# project.delete()
|
||
# logging.info(str(datetime.now()) + '删除完成稍后重新导入')
|
||
# error_msg = '导入失败,请查看日志发现错误后重新导入'
|
||
# return render(request, 'projects/new.html', locals())
|
||
class SetCompetitionProjectView(View):
|
||
def get(self,request):
|
||
try:
|
||
project_name = request.GET.get('project_name','')
|
||
strategy = int(request.GET.get('strategy',''))
|
||
path = request.GET.get('path',None)
|
||
project = Project.objects.get(name=project_name)
|
||
if not project.is_competition_project:
|
||
project.is_competition_project=True
|
||
project.save()
|
||
if strategy>=0 and strategy<=2:
|
||
anno_strategy = AnnotationStrategy.objects.get(project=project)
|
||
anno_strategy.choice = strategy
|
||
anno_strategy.save()
|
||
if path is not None:
|
||
self.set_competition_files(path,project)
|
||
return HttpResponse("Successful")
|
||
except Exception as e:
|
||
return HttpResponse(str(e))
|
||
|
||
def set_competition_files(self,path,project):
|
||
file = File.objects.get(path=path,project=project)
|
||
file.is_competition_file=True
|
||
file.save()
|
||
file_ids = [file.id]
|
||
while len(file_ids)>0:
|
||
file_id = file_ids.pop(0)
|
||
for file in File.objects.filter(super_path_id=file_id):
|
||
file.is_competition_file=True
|
||
file.save()
|
||
file_ids.append(file.id)
|
||
|
||
|
||
|
||
class RemoveProjectView(View):
|
||
def get(self, request):
|
||
project_id = request.GET.get('projectid', '')
|
||
project = Project.objects.get(id=project_id)
|
||
project.delete()
|
||
return HttpResponse("Remove Done!!")
|
||
|
||
class ProjectListView(View):
|
||
def get(self, request):
|
||
all_projects = Project.objects.filter(is_open=True)
|
||
# 工程排序
|
||
sort = request.GET.get('sort', '')
|
||
if sort == '':
|
||
all_projects = all_projects.order_by('-create_time')
|
||
elif sort == 'hot':
|
||
all_projects = all_projects.order_by('-views')
|
||
return render(request, 'projects/project-list.html', locals())
|
||
|
||
|
||
class ProjectInfoView(View):
|
||
def get(self, request, name):
|
||
project = Project.objects.filter(name=name).first()
|
||
articles = Article.objects.filter(project_id=project.id)
|
||
return render(request, 'projects/info.html', locals())
|
||
|
||
# FIXME
|
||
# 每一行问题的数量有待修复
|
||
# 目前做的是总数/3,但是对于问答题而言,应该是全部都要算上的
|
||
# class ProjectSourceView_Before(View):
|
||
# def get(self, request, name, path):
|
||
# project = Project.objects.filter(name=name).first()
|
||
# # 判断是否是根目录
|
||
|
||
# #parent_dir保存了上一级目录
|
||
# if path=='/':
|
||
# file = File.objects.filter(path='', project=project).first()
|
||
# parent_dir = None
|
||
# else:
|
||
# file = File.objects.filter(path=path, project=project).first()
|
||
# parent_dir = path[:path.rindex("/")]
|
||
|
||
# #默认会进入当前文件夹的第一个文件,如果当前文件夹没有任何的文件,那么进入指定的文件
|
||
# enter_project_url = "/src/net/micode/notes/gtask/data/TaskList.java"
|
||
|
||
# # 判断当前文件是否是文件夹
|
||
# # 获取目录
|
||
# path = file.path.split('/')
|
||
# path_dict = {}
|
||
# for i in range(1, len(path)):
|
||
# path_dict[path[i]] = '/'.join(path[:i + 1])
|
||
|
||
# #file.type=1 means it's a dir
|
||
# #file.type=0 means it's a file
|
||
# if file.type == '1':
|
||
|
||
# #enter_flag如果当前文件夹下有文件,
|
||
# #那么将它设置为False,并将enter_project_url改为第一个文件的path
|
||
# enter_flag = True
|
||
# files = File.objects.filter(super_path=file, project=project)
|
||
|
||
# annos_count = {}
|
||
# for file in files:
|
||
# if enter_flag and file.type=='0':
|
||
# enter_project_url = file.path;
|
||
# enter_flag = False
|
||
# # 取出每个文件的注释数量
|
||
# anno_count = Annotation.objects.filter(file=file).count()
|
||
# # print("%s:%i"%(file.name,anno_count))
|
||
# if anno_count > 0:
|
||
# annos_count[file.name] = str(anno_count)
|
||
# return render(request, 'projects/directory.html', locals())
|
||
|
||
# else:
|
||
# print(11111111)
|
||
# print(request.user)
|
||
# # 按linenum取出注释数目 返回结果是 <QuerySet [{'linenum': 0, 'nums': 1}, {'linenum': 1, 'nums': 2}, {'linenum': 2, 'nums': 2}]>
|
||
# # 因此需要进行一个转化
|
||
# # 这是django中分组的一种写法
|
||
# annos = Annotation.objects.filter(file=file).values('linenum').annotate(nums=Count('linenum'))
|
||
# annos_count = {}
|
||
# for i in annos:
|
||
# annos_count[str(i['linenum'])] = i['nums']
|
||
# # 两种问题,一种是问答题一种是选择题
|
||
# # 对于选择题而言,是从三种问题中随机选择一个的
|
||
# # 对于问答题而言,目前应该是全部选择
|
||
# # issue_type=1对应选择题,issue_type=2对应这问答题
|
||
# issues=choose_issue_type_1(file)
|
||
|
||
# question_count = {}
|
||
# for key in issues:
|
||
# question_count[key]=len(issues[key])//2
|
||
|
||
# project_tree = get_project_tree.getHtml(settings.SOURCEPATH+project.path)
|
||
|
||
# return render(request, 'projects/source.html', locals())
|
||
|
||
|
||
class ProjectSourceView(View):
|
||
|
||
def login_educoder(self,educoder_userid,request):
|
||
private_token = "hriEn3UwXfJs3PmyXnSG"
|
||
userinfo_url = "http://www.educoder.net/api/v1/sources/"+str(educoder_userid)+"/get_user_info?private_token="+private_token
|
||
response = requests.get(userinfo_url)
|
||
response = json.loads(response.text)
|
||
email = response['email']
|
||
exist_records = User.objects.filter(email=email).first()
|
||
pass_word = "init_password"
|
||
if not exist_records:
|
||
user = User()
|
||
user.username = response['username']
|
||
while User.objects.filter(username=user.username).first():
|
||
user.username += str(random.randint(0,10))
|
||
user.password = make_password(pass_word)
|
||
user.password_codepedia = user.password
|
||
user.educoder_userid = int(educoder_userid)
|
||
user.email = response['email']
|
||
user.is_active = True
|
||
user.save()
|
||
user = authenticate(username=email, password=pass_word)
|
||
# 现在的策略是密码与educoder保持一致
|
||
else:
|
||
user = exist_records
|
||
user.password = make_password(pass_word)
|
||
if user.educoder_userid is None:
|
||
user.educoder_userid = response['user_id']
|
||
user.save()
|
||
user = authenticate(username=email, password=pass_word)
|
||
# 否则用当前用户名和密码登录
|
||
if user is not None:
|
||
login(request, user)
|
||
|
||
def get(self, request, name, path):
|
||
educoder_userid = request.GET.get("eid","")
|
||
if educoder_userid!="" and educoder_userid!="2":
|
||
self.login_educoder(educoder_userid,request)
|
||
name = name.split("?")[0]
|
||
path = path.split("?")[0]
|
||
project = Project.objects.filter(name=name).first()
|
||
if project.is_open:
|
||
# project_tree = projectTreeObj.get_project_tree_by_projectid(project.id)
|
||
return render(request, 'projects/source.html', locals())
|
||
else:
|
||
return HttpResponse("This project is not open now!")
|
||
|
||
class GetProjectJstreeView(View):
|
||
def post(self, request):
|
||
name = request.POST.get("project_name","")
|
||
project = Project.objects.filter(name=name).first()
|
||
project_tree = projectTreeObj.get_project_tree_by_projectid(project.id)
|
||
return HttpResponse(json.dumps({"status": "success","jstree_content":project_tree}), content_type='application/json')
|
||
|
||
|
||
#文件列表页
|
||
class FileListlView(View):
|
||
def get(self, request):
|
||
all_files = File.objects.all()
|
||
hot_blobs = File.objects.order_by('-views')[:5]
|
||
|
||
sort = request.GET.get('sort', '')
|
||
if sort=='' or sort=="hot":
|
||
all_files = all_files.order_by('-anno_num')
|
||
else:
|
||
all_files = all_files.order_by('-create_time')
|
||
#分页功能
|
||
try:
|
||
page = request.GET.get('page', 1)
|
||
except PageNotAnInteger:
|
||
page = 1
|
||
p = Paginator(all_files, 10, request=request)
|
||
files = p.page(page)
|
||
|
||
return render(request, 'projects/file-list.html', {
|
||
'all_files': files,
|
||
'hot_objs': hot_blobs,
|
||
})
|
||
|
||
from django.http import HttpResponse
|
||
class ScannerProjectView(View):
|
||
def get(self,request):
|
||
project_name = request.GET.get('project_name','')
|
||
try:
|
||
project = Project.objects.get(name=project_name)
|
||
scanner_project_obj = scanner_project.Scanner_Project_Object()
|
||
scanner_project_obj.get_anno_issue_summary("/opt/opengrok/source/"+project_name, project.pk)
|
||
return HttpResponse("Scanner Done!!")
|
||
except:
|
||
return HttpResponse("Scanner Fail!!")
|