educoder/app/controllers/shixuns_controller.rb

654 lines
24 KiB
Ruby
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# encoding: utf-8
# REDO: 创建版本库权限控制
class ShixunsController < ApplicationController
layout 'base_shixun'
before_filter :require_login
before_filter :check_authentication
before_filter :find_shixun, :except => [ :index, :new, :create, :index, :search, :shixun_courses, :new_disscuss]
before_filter :shixun_view_allow, :only => [:show]
before_filter :require_manager, :only => [ :settings, :add_script, :publish, :collaborators_delete, :shixun_members_added, :add_collaborators]
#skip_before_filter :verify_authenticity_token, :only => :update_propaedeutics
include ApplicationHelper
def shixun_test
jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
uri = URI("#{jenkins_shixuns}/jenkins-exec/webssh/getConnectInfo")
user_id = User.current.id
params = {userID:user_id}
res = uri_exec uri, params
render :json => {data:"succesed"}
end
def delete_shixun_test
jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
uri = URI("#{jenkins_shixuns}/jenkins-exec/webssh/deleteSSH")
user_id = User.current.id
params = {userID:user_id}
res = uri_exec uri, params
render :json => {data:"succesed"}
end
def game_webssh
end
def entry_edit
g = Gitlab.client
@path = params[:path]
@rev = params[:rev]
file_content = g.files(@shixun.gpid, @path, @rev).content
@content = Base64.decode64(file_content) unless file_content.blank?
respond_to do |format|
format.js
end
end
def entry_update
g = Gitlab.client
@path = params[:path]
@rev = params[:rev]
@content = params[:content]
code_file = g.edit_file(@shixun.gpid, :content => params[:content], :file_path => @path, :branch_name => @rev, :commit_message => "shixun entry")
respond_to do |format|
format.js
end
end
def shixun_monitor
# monitor_filter
# if @had_exec
# @tpm = Myshixun.where(:user_id => User.current, :shixun_id => @shixun).first
# end
#
# respond_to do |format|
# format.js
# end
end
def statistics
@challenges = @shixun.challenges
@top_students = @shixun.myshixuns.where(:status => 1)
myshixuns = @shixun.myshixuns.includes(:games)
@latest_myshixuns = myshixuns.order("created_at desc").limit(4)
end
def autocompletion
end
def index
@order = "created_at"
@sort = "desc"
search = params[:search]
@shixun_all_count = Shixun.all.count
#@shixuns = Shixun.find_by_sql("select * from shixuns where id in (SELECT distinct(shixun_id) FROM `challenges`) and name like '%#{search}%' order by created_at desc")
@shixuns = Shixun.where("name like ?", "%#{search}%").reorder("created_at desc")
# @shixun_my_score = Game.find_by_sql("select sum(final_score) as score from games where myshixun_id in (select id from myshixuns where status =1
# and user_id=#{User.current.id} and shixun_id in (SELECT id FROM `shixuns` where status > 1))").first.try(:score).to_i
@shixun_my_score = Experience.find_by_sql("SELECT sum(score) as score FROM `experiences` where user_id=#{User.current.id}").first.try(:score).to_i
@current_user_had_passed = Myshixun.find_by_sql("select count(*) as had_passed from myshixuns where status =1 and user_id=#{User.current.id}
and shixun_id in (SELECT id FROM `shixuns` where status > 1)").first.try(:had_passed).to_i
@majors = Major.where(:id => [635, 636, 637, 638, 639, 622, 619])
@courses = CourseList.where(:id => MajorCourse.where(:major_id => @majors.map(&:id)).map(&:course_list_id))
@shixuns_count = @shixuns.count
@limit = 16
@is_remote = true
@shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
@offset ||= @shixun_pages.offset
@shixuns = paginateHelper @shixuns, @limit
render :layout => "base_edu"
end
def propaedeutics
respond_to do |format|
format.html
end
end
def update_propaedeutics
@shixun = Shixun.where(:identifier => params[:id]).first
@shixun.update_attribute("propaedeutics", params[:shixun][:propaedeutics])
redirect_to propaedeutics_shixun_path(@shixun)
end
def collaborators
@collaborators = @shixun.collaborators
end
def collaborators_delete
user_id = params[:c_id]
shixun_member = ShixunMember.where(:user_id => user_id, :shixun_id => @shixun.id, :role => 2).first
shixun_member.delete
@collaborators = @shixun.collaborators
respond_to do |format|
format.js
end
end
# 已存在的成员不添加
def add_collaborators
if !params[:search].nil?
# members = searchTeacherAndAssistant @course
member_ids = "(" + @shixun.shixun_members.map(&:user_id).join(',') + ")"
condition = "%#{params[:search].strip}%".gsub(" ","")
@users = User.where("id not in #{member_ids} and status = 1 and LOWER(concat(lastname, firstname)) LIKE '#{condition}'").includes(:user_extensions)
end
respond_to do |format|
format.js
end
end
def shixun_members_added
unless params[:membership][:user_ids].blank?
memberships = params[:membership][:user_ids]
memberships.each do |member|
ShixunMember.create(:user_id => member, :shixun_id => @shixun.id, :role => 2)
end
@collaborators = @shixun.collaborators
end
respond_to do |format|
format.js
end
end
def search
# 确定 sort 1升序 2 降序
@order = params[:order] || "created_at"
bsort = params[:sort] || "desc"
@sort = bsort == "desc" ? "asc" : "desc"
if @order == "created_at"
order_str = "#{Shixun.table_name}.created_at #{bsort}"
else
order_str = "myshixun_count #{bsort}, #{Shixun.table_name}.updated_at #{bsort}"
end
@language = params[:language]
@status = params[:status].to_i
@shixun_status = params[:shixun_status] # 2是已发布 3是未发布
@search = params[:search]
@major = params[:major]
@course = params[:course]
@trainee = params[:trainee]
#ids = Shixun.find_by_sql("select group_concat(id) as allId from shixuns where id in (SELECT distinct(shixun_id) FROM `challenges`)")
@shixuns = Shixun.where("0=0")
@shixuns = @shixuns.where(:language => @language) unless @language.blank?
@shixuns = @shixuns.where("name like ?", "%#{@search}%") unless @search.blank?
if !@major.blank?
@shixuns = @shixuns.where(:major_id => @major.to_i)
@courses = CourseList.where(:id => MajorCourse.where(:major_id => @major).map(&:course_list_id))
else
@courses = CourseList.where(:id => MajorCourse.where(:major_id => [635, 636, 637, 638, 639, 622, 619]).map(&:course_list_id))
end
if !@course.blank? && (@major.blank? || MajorCourse.where(:major_id => @major, :course_list_id => @course).count == 1)
@shixuns = @shixuns.where(:id => ShixunMajorCourse.where(:course_list_id => @course).map(&:shixun_id))
end
if !@major.blank? && MajorCourse.where(:major_id => @major, :course_list_id => @course).count == 0
@course = nil
end
@shixuns = @shixuns.where(:trainee => @trainee) unless @trainee.blank?
case @status
when 1, 0
@shixuns = @shixuns
when 2
@shixuns = @shixuns.where(:user_id => User.current)
when 3
shixun_ids = Myshixun.where(:user_id => User.current).blank? ? "(-1)" : "(" + Myshixun.where(:user_id => User.current).map(&:shixun_id).join(',') +")"
@shixuns = @shixuns.where("id not in #{shixun_ids}")
when 4
shixun_ids = Myshixun.where(:user_id => User.current, :status => 0).map(&:shixun_id)
@shixuns = @shixuns.where(:id => shixun_ids)
when 5
shixun_ids = Myshixun.where(:user_id => User.current, :status => 1).map(&:shixun_id)
@shixuns = @shixuns.where(:id => shixun_ids)
end
case @shixun_status
when "1"
@shixuns = @shixuns.where(:status => [0, 1])
when "2"
@shixuns = @shixuns.where(:status => 2)
when "3"
@shixuns = @shixuns.where(:status => 3)
when nil, "0"
@shixuns = @shixuns
end
if @order == "created_at"
@shixuns =@shixuns.reorder(order_str)
else
# 最热排序
@shixuns.each do |shixun|
shixun[:myshixunCount] = shixun.myshixuns.count
end
@shixuns = @shixuns.sort{|x, y| y[:myshixunCount] <=> x[:myshixunCount]}
end
# @shixuns = Shixun.where(:authentication => 1).reorder(order)
@shixuns_count = @shixuns.count
@limit = 16
@is_remote = true
@shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
@offset ||= @shixun_pages.offset
@shixuns = paginateHelper @shixuns, @limit
respond_to do |format|
format.js
end
end
# jenkins回调脚本
# gameID 及实训ID
def publish
jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
begin
gameInfo = @shixun.gameInfo
uri = URI("#{jenkins_shixuns}/jenkins-exec/game/publishGame")
logger.info(gameInfo)
params = {gameInfo:gameInfo}
logger.info(params)
res = uri_exec uri, params
logger.info("###################{res['code']}")
if res && res['code'].to_i == 0
logger.info("1111###################{res['code']}")
@shixun.update_attributes(:status => 1)
apply = ApplyAction.where(:container_type => "ApplyShixun", :container_id => @shixun.id).order("created_at desc").first
if apply && apply.status == 0
@status = 0
else
ApplyAction.create(:container_type => "ApplyShixun", :container_id => @shixun.id, :user_id => User.current.id, :status => 0)
notes = User.current.show_name.to_s + " 申请发布实训:<a href='#{shixun_path(@shixun)}'>#{@shixun.name}</a>"
JournalsForMessage.create(:jour_id => 1, :jour_type => 'Principal', :user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0)
@status = 1
end
shixun_modify_status_without_publish(@shixun, 1)
else
logger.error("res['code'] is #{res['code']}, res['msg'] is #{res['code']}")
@jenkin_error = true
end
rescue Exception => e
@jenkin_error = true
logger.error("pushlish game #{e}")
respond_to do |format|
format.js
end
end
end
def apply_publish
apply = ApplyAction.where(:container_type => "ApplyShixun", :container_id => @shixun.id).last
if apply && apply.status == 0
@status = 0
else
ApplyAction.create(:container_type => "ApplyShixun", :container_id => @shixun.id, :user_id => User.current.id, :status => 0)
notes = User.current.show_name.to_s + " 申请发布实训:<a href='#{shixun_path(@shixun)}'>#{@shixun.name}</a>"
JournalsForMessage.create(:jour_id => 1, :jour_type => 'Principal', :user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0)
@shixun.update_column('status', 1)
@status = 1
end
end
def cancel_publish
apply = ApplyAction.where(:container_type => "ApplyShixun", :container_id => @shixun.id).order("created_at desc").first
if apply && apply.status == 0
apply.update_attributes(:status => 3)
@shixun.update_column('status', 0)
end
redirect_to shixun_path(@shixun)
end
def close
@shixun.update_column('status', 3)
redirect_to shixun_path(@shixun)
end
# copy_shixun复制一个新的实训模块包括版本库
# copy_myshixun自动创建系列game,game中只包含状态等信息公共信息从Challeges中读取
# 开启过实训的则直接跳入my实训页面
def shixun_exec
unless allow_shixun_exec(@shixun) && (User.current.manager_of_shixun?(@shixun) || @shixun.status > 0)
render_403
return
end
myshixun = Myshixun.where(:user_id => User.current.id, :shixun_id => @shixun.id).first
unless myshixun.blank?
logger.info("current task id is #{myshixun.current_task}")
redirect_to myshixun_game_path(myshixun.current_task, :myshixun_id => myshixun)
return
end
repository = @shixun.repository
ActiveRecord::Base.transaction do
begin
@g = Gitlab.client
if User.current.gid.nil?
s = Trustie::Gitlab::Sync.new
s.sync_user(User.current)
end
gshixun = @g.fork(@shixun.gpid, User.current.gid)
logger.info("#############gshixun is #{gshixun}")
if !gshixun.id.nil?
myshixun = copy_myshixun(@shixun, gshixun)
# @shixun.update_attribute(:myshixun_count, (@shixun.myshixun_count + 1))
challenges = @shixun.challenges
# 之所以增加user_id是为了方便统计查询性能
challenges.each_with_index do |challenge, index|
status = (index == 0 ? 0 : 3)
code = CODES.sample(12).join
code = CODES.sample(12).join if Game.where(identifier: code).present?
game =Game.create!(:challenge_id => challenge.id, :myshixun_id => myshixun.id, :status => status, :user_id => myshixun.user_id, :open_time => Time.now, :identifier => code)
# 记录刚开始时默认代开文件原始代码
# 刚开始fork的一段时间是获取不了content内容的
game_passed_code(game.try(:id), challenge.try(:path), myshixun.try(:gpid), 0)
end
if params[:type] == "1" # 重置过来的请求
shixun_mod = ShixunModify.where(:shixun_id => myshixun.try(:shixun_id), :myshixun_id => myshixun.try(:id)).first
if shixun_mod.nil?
ShixunModify.create(:shixun_id => myshixun.shixun_id, :myshixun_id => myshixun.id, :status => 0)
else
shixun_mod.update_attributes(:status => 0)
end
end
# webssh类型开始实训的时候建立webssh连接
# if @shixun.webssh
# # username = Redmine::Configuration['webssh_username']
# # password = Redmine::Configuration['webssh_password']
# jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
# uri = URI("#{jenkins_shixuns}/jenkins-exec/webssh/getConnectInfo")
# user_id = User.current.id
# params = {userID:user_id}
# res = uri_exec uri, params
# if res && res['code'].to_i == 0
# myshixun_webssh = Webssh.where(:myshixun_id => myshixun.id).first
# if myshixun_webssh.nil?
# Webssh.create(:myshixun_id => myshixun.id, :host => @temp, :port => @temp)
# else
# myshixun_webssh.update_attributes(:host => @temp, :port => @temp)
# end
# else
# raise("实训云平台繁忙繁忙等级92")
# end
# end
else
raise("实训云平台繁忙繁忙等级81")
end
logger.info("myshixun id si #{myshixun.id} and current_task id is#{myshixun.current_task.id}")
redirect_to myshixun_game_path(myshixun.current_task, :myshixun_id => myshixun)
rescue Exception => e
flash[:error] = e.message
logger.info("failed to exec shixun: current task id is #{e}")
@g.delete_project(gshixun.id) if !gshixun.id.nil?
redirect_to shixun_challenges_path(@shixun)
raise ActiveRecord::Rollback
end
end
end
def shixun_courses
data = {result:0,options:[]}
if params[:major_id] != 0
major = Major.find params[:major_id]
if major
data[:result] = 1
major_courses = major.major_courses
CourseList.where(:id => major_courses.map(&:course_list_id)).each do |course|
option = []
option << course.name.to_s
option << course.id
data[:options] << option
end
else
data[:result] = 0
end
else
data[:result] = 0
end
render :json =>data
end
def new
@shixun = Shixun.new
respond_to do |format|
format.html{render :layout => 'base_edu'}
format.json
end
end
CODES = %W(2 3 4 5 6 7 8 9 A B C D E F G H J K L N M O P Q R S T U V W X Y Z)
def create
identifier = generate_identifier
@shixun = Shixun.new(params[:shixun])
@shixun.user_id = User.current.id
@shixun.language = params[:language]
@shixun.major_id = params[:major_id]
@shixun.trainee = params[:trainee]
@shixun.identifier = identifier
if params[:course_id]
params[:course_id].each do |course_id|
@shixun.shixun_major_courses << ShixunMajorCourse.new(:major_id => params[:major_id], :course_list_id => course_id)
end
end
(params[:shixun][:is_public] == "1" ? @shixun.is_public = true : @shixun.is_public = false)
respond_to do |format|
if @shixun.save
m = ShixunMember.new(:user_id => User.current.id, :role => 1)
@shixun.shixun_members << m
# 自动构建版本库
repository = Repository.new
repository.shixun = @shixun
repository.type = 'Repository::Gitlab'
repository.identifier = @shixun.identifier.downcase
repository.project_id = -1
ActiveRecord::Base.transaction do
if repository.save
begin
s = Trustie::Gitlab::Sync.new
gproject = s.create_shixun(@shixun, repository)
raise "sync failed" if @shixun.gpid.blank?
rescue Exception => e
@shixun.update_attribute(:gpid, nil)
if @repository && @repository.id
@repository.destroy
end
end
end
end
format.html { redirect_to shixun_path @shixun, notice: l(:notice_successful_create) }
format.js
else
format.html { render action: "new" }
format.js
end
end
end
def show
respond_to do |format|
format.html{redirect_to shixun_challenges_path(@shixun)}
end
end
CODES = %W(2 3 4 5 6 7 8 9 A B C D E F G H J K L N M O P Q R S T U V W X Y Z)
def generate_identifier
code = CODES.sample(8).join
return generate_identifier if Shixun.where(identifier: code).present?
code
end
def edit
end
def update
if @shixun.status == 0
language = @shixun.language
@shixun.attributes = params[:shixun]
@shixun.language = params[:language]
@shixun.trainee = params[:trainee]
if params[:course_id]
@shixun.shixun_major_courses.destroy_all
params[:course_id].each do |course_id|
@shixun.shixun_major_courses << ShixunMajorCourse.new(:major_id => params[:major_id], :course_list_id => course_id)
end
end
@shixun.major_id = params[:major_id]
params[:shixun][:is_public] == "on" ? @shixun.is_public = 1 : @shixun.is_public = 0
if @shixun.save
# 实训语言更改了会影响后续的评测所以需要更新is_updated
if language != params[:language]
add_shixun_modify_status(@shixun, 1)
end
end
else
@error = "该实训已申请发布了,暂不能编辑"
end
respond_to do |format|
format.html{redirect_to settings_shixun_url(@shixun)}
format.js
end
end
def shixun_discuss
@discusses = @shixun.discusses.where(:parent_id => nil).reorder("created_at desc")
@discusses_count = @discusses.count
@limit = 15
@is_remote = true
@discusses_pages = Paginator.new @discusses_count, @limit, params['page'] || 1
@offset ||= @discusses_pages.offset
@discusses = paginateHelper @discusses, @limit
end
def destroy
unless User.current.admin?
render_403
return
end
Subject.where(:id => @shixun.stage_shixuns.map(&:subject_id)).destroy_all
@shixun.destroy
respond_to do |format|
format.html{ redirect_to shixuns_managements_path }
format.js
end
end
def settings
@repository = Repository.where(:shixun_id => @shixun, :type => "Repository::Gitlab").first
unless @repository.nil?
gitlab_address = Redmine::Configuration['gitlab_address']
login = User.find_by_mail("educoder@163.com").try(:login)
@repos_url = git_shixun_url(@shixun, login)
end
end
# 添加实训脚本
def add_script
if @shixun.update_attribute(:script, params[:shixun_script])
@notice = "脚本添加成功"
else
@notice = "脚本添加失败"
end
end
# 创建实训job
def shixun_job_create
if @shixun.challenges.count == 0
@notice = "实训开启失败:请先发布实训任务"
return
elsif Repository.where(:shixun_id => @shixun.id, :type => "Repository::Gitlab").count == 0
@notice = "实训开启失败:请先创建版本库"
return
end
@shixun.update_attribute(:status, 1)
end
# 更新实训job
def shixun_job_update
# jobName = "#{@shixun.id}"
# pipeLine = "#{Base64.encode64(@shixun.script)}"
# uri = URI("http://123.59.135.74:9999/jenkins-exec/api/updateJob")
# params = {jobName: jobName, pipeLine: pipeLine}
# res = uri_exec uri, params
training_shixun_notice res
if res['code'] == 0
@shixun.update_attribute(:status, 1)
end
end
# Find shixun of id params[:id]
def find_shixun
@shixun = Shixun.find_by_identifier(params[:id])
render_404 if @shixun.nil?
rescue ActiveRecord::RecordNotFound
render_404
end
def monitor_filter
if User.current.id == @shixun.user_id
@notice = l(:label_shixun_mine)
else
if has_exec_cur_shixun(@shixun)
@notice = l(:label_shixun_had_forked)
@had_exec = true
else
@notice = l(:label_shixun_exec)
@had_exec = false
end
end
end
# 实训行为操作
def operation
@myshixun = Myshixun.where(:id => params[:myshixun_id]).first
@is_modify = ShixunModify.where(:myshixun_id => params[:myshixun_id], :shixun_id => @shixun.try(:id), :status => 1).first
@mail = User.current.mail.blank?
end
private
# REDO: 新增类型copy的时候
# 复制项目
# gshixun --> gitlab project
CODES = %W(2 3 4 5 6 7 8 9 a b c f e f g h i j k l m n o p q r s t u v w x y z)
def copy_myshixun shixun, gshixun
myshixun = Myshixun.new
myshixun.attributes = shixun.attributes.dup.except("id","user_id","visits","gpid","status", "identifier","propaedeutics")
myshixun.shixun_id = shixun.id
myshixun.user_id = User.current.id
myshixun.gpid = gshixun.id
jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
if myshixun.save!
code = CODES.sample(10).join
code = CODES.sample(10).join if Myshixun.where(identifier: code).present?
myshixun.update_attribute(:identifier, code)
MyshixunMember.create!(:myshixun_id => myshixun.id, :user_id => User.current.id, :role => 1)
rep = Repository.new(:myshixun_id => myshixun.id, :identifier => gshixun.name,:project_id => -1, :shixun_id => -2)
rep.type = "Repository::Gitlab"
rep.save!
login = User.find_by_mail("educoder@163.com").try(:login)
rep_url = Base64.encode64(git_shixun_url_ip shixun, login)
uri = URI("#{jenkins_shixuns}/jenkins-exec/game/openGameInstance")
pipeLine = "#{shixun.script}"
params = {jobNameForInstance: "myshixun_#{myshixun.id}", gameInfo: shixun.gameInfo, instanceGitURL:rep_url}
logger.info("openGameInstance params is #{params}")
res = uri_exec uri, params
if (res && res['code'].to_i != 0)
raise("实训云平台繁忙繁忙等级83")
end
return myshixun
end
end
def training_shixun_notice res
if res['code'] == 0
@notice = "实训开启成功"
else
@notice = res['msg'].nil? ? "实训开启失败" : res['msg']
end
end
# 权限控制
def shixun_view_allow
render_403 if (@shixun.status == 0 && !(User.current.manager_of_shixun?(@shixun) || User.current.admin?))
end
# 实训管理员或者超级管理员
def require_manager
render_403 unless (User.current.manager_of_shixun?(@shixun) || User.current.admin?)
end
end