Merge pull request '20240823版本' (#345) from Trustie/forgeplus:trustie_server into master

This commit is contained in:
xxq250 2024-08-23 15:06:57 +08:00
commit adf77df1bf
223 changed files with 99055 additions and 257 deletions

View File

@ -141,4 +141,4 @@ gem 'doorkeeper'
gem 'doorkeeper-jwt'
gem 'gitea-client', '~> 1.4.6'
gem 'gitea-client', '~> 1.5.8'

View File

@ -0,0 +1,75 @@
class Action::NodeInputsController < ApplicationController
before_action :require_admin, except: [:index]
before_action :find_action_node
def index
@node_inputs = @node.action_node_inputs
respond_to do |format|
format.html
format.json
end
end
def create
@node_input = Action::NodeInput.new(node_input_params)
@node_input.action_node = @node
respond_to do |format|
if @node_input.save
format.html { redirect_to action_node_node_inputs_path(@node), notice: '创建成功.' }
format.json { render_ok(data: @node_input.as_json) }
else
format.html { render :new }
format.json { render json: @node_input.errors, status: -1 }
end
end
end
def new
end
def show
end
def edit
end
def update
@node_input.update(node_input_params)
respond_to do |format|
format.html { redirect_to action_node_node_inputs_path(@node), notice: '更新成功.' }
format.json { render_ok(data: @node_input.as_json) }
end
end
def destroy
if @node_input.destroy!
flash[:success] = '删除成功'
else
flash[:danger] = '删除失败'
end
redirect_to "api/actions/nodes"
end
private
def find_action_node
@node = Action::Node.find(params[:node_id])
if params[:id].present?
@node_input = @node.action_node_inputs.find(params[:id])
else
@node_input = Action::NodeInput.new
end
end
def node_input_params
if params.require(:action_node_input)
params.require(:action_node_input).permit(:name, :input_type, :description, :is_required, :sort_no)
else
params.permit(:name, :input_type, :description, :is_required, :sort_no)
end
end
end

View File

@ -0,0 +1,76 @@
class Action::NodeSelectsController < ApplicationController
before_action :require_admin, except: [:index]
before_action :find_action_node
def index
@node_selects = @node.action_node_selects
respond_to do |format|
format.html
format.json
end
end
def create
@node_select = Action::NodeSelect.new(node_select_params)
@node_select.action_node = @node
respond_to do |format|
if @node_select.save
format.html { redirect_to action_node_node_selects_path(@node), notice: '创建成功.' }
format.json { render_ok(data: @node_select.as_json) }
else
format.html { render :new }
format.json { render json: @node_select.errors, status: -1 }
end
end
end
def new
end
def show
end
def edit
end
def update
@node_select.update(node_select_params)
respond_to do |format|
format.html { redirect_to action_node_node_selects_path(@node), notice: '更新成功.' }
format.json { render_ok(data: @node_select.as_json) }
end
end
def destroy
if @node_select.destroy!
flash[:success] = '删除成功'
else
flash[:danger] = '删除失败'
end
redirect_to "api/actions/nodes"
end
private
def find_action_node
@node = Action::Node.find(params[:node_id])
if params[:id].present?
@node_select = @node.action_node_selects.find(params[:id])
else
@node_select = Action::NodeSelect.new
end
end
def node_select_params
if params.require(:action_node_select)
params.require(:action_node_select).permit(:name, :val, :val_ext, :description, :sort_no)
else
params.permit(:name, :val, :val_ext, :description, :sort_no)
end
end
end

View File

@ -0,0 +1,64 @@
class Action::NodeTypesController < ApplicationController
before_action :require_admin, except: [:index]
before_action :find_node_type, except: [:index, :create, :new]
def index
@node_types = Action::NodeType.all
end
def create
@node_type = Action::NodeType.new(node_types_params)
respond_to do |format|
if @node_type.save
format.html { redirect_to action_node_types_path, notice: '创建成功.' }
format.json { render_ok(data: @node_type.as_json) }
else
format.html { render :new }
format.json { render json: @node_type.errors, status: -1 }
end
end
end
def show
end
def new
@node_type = Action::NodeType.new
end
def edit
end
def update
@node_type.update(node_types_params)
respond_to do |format|
format.html { redirect_to action_node_types_path, notice: '更新成功.' }
format.json { render_ok(data: @node_type.as_json) }
end
end
def destroy
if @node_type.destroy!
flash[:success] = '删除成功'
else
flash[:danger] = '删除失败'
end
redirect_to action_node_types_path
end
private
def find_node_type
@node_type = Action::NodeType.find(params[:id])
end
def node_types_params
if params.require(:action_node_type)
params.require(:action_node_type).permit(:name, :description, :sort_no)
else
params.permit(:name, :description, :sort_no)
end
end
end

View File

@ -0,0 +1,69 @@
class Action::NodesController < ApplicationController
before_action :require_admin, except: [:index]
before_action :find_action_node, except: [:index, :create, :new]
def index
@node_types = Action::NodeType.all
@no_type_nodes = Action::Node.where(action_node_types_id: nil)
respond_to do |format|
format.html { @nodes = Action::Node.all }
format.json
end
end
def create
@node = Action::Node.new(node_params)
respond_to do |format|
if @node.save
format.html { redirect_to action_nodes_path, notice: '创建成功.' }
format.json { render_ok(data: @node.as_json) }
else
format.html { render :new }
format.json { render json: @node.errors, status: -1 }
end
end
end
def new
@node = Action::Node.new
end
def show
end
def edit
end
def update
@node.update(node_params)
respond_to do |format|
format.html { redirect_to action_nodes_path, notice: '更新成功.' }
format.json { render_ok(data: @node.as_json) }
end
end
def destroy
if @node.destroy!
flash[:success] = '删除成功'
else
flash[:danger] = '删除失败'
end
redirect_to action_nodes_path
end
private
def find_action_node
@node = Action::Node.find(params[:id])
end
def node_params
if params.require(:action_node)
params.require(:action_node).permit(:name, :full_name, :description, :icon, :action_node_types_id, :is_local, :local_url, :yaml, :sort_no)
else
params.permit(:name, :full_name, :description, :icon, :action_node_types_id, :is_local, :local_url, :yaml, :sort_no)
end
end
end

View File

@ -0,0 +1,68 @@
class Action::TemplatesController < ApplicationController
before_action :require_admin, except: [:index]
before_action :find_action_template, except: [:index, :create, :new]
def index
@templates = Action::Template.all
respond_to do |format|
format.html
format.json
end
end
def create
@template = Action::Template.new(templates_params)
respond_to do |format|
if @template.save
format.html { redirect_to action_templates_path, notice: '创建成功.' }
format.json { render_ok(data: @template.as_json) }
else
format.html { render :new }
format.json { render json: @template.errors, status: -1 }
end
end
end
def show
end
def new
@template = Action::Template.new
end
def edit
end
def update
@template.update(templates_params)
respond_to do |format|
format.html { redirect_to action_templates_path, notice: '更新成功.' }
format.json { render_ok(data: @template.as_json) }
end
end
def destroy
if @template.destroy!
flash[:success] = '删除成功'
else
flash[:danger] = '删除失败'
end
redirect_to action_templates_path
end
private
def find_action_template
@template = Action::Template.find(params[:id])
end
def templates_params
if params.require(:action_template)
params.require(:action_template).permit(:name, :description, :img, :sort_no, :json, :yaml)
else
params.permit(:name, :description, :img, :sort_no, :json, :yaml)
end
end
end

View File

@ -23,10 +23,23 @@ class Admins::BaseController < ApplicationController
def require_admin!
return if current_user.blank? || !current_user.logged?
return if current_user.admin_or_business?
return if current_user.admin_or_glcc_admin?
render_forbidden
end
def require_admin
render_forbidden unless User.current.admin?
end
def require_business
render_forbidden unless admin_or_business?
end
def require_glcc_admin
render_forbidden unless admin_or_glcc_admin?
end
# 触发after ajax render partial hooks执行一些因为局部刷新后失效的绑定事件
def rebind_event_if_ajax_render_partial
return if request.format.symbol != :js

View File

@ -1,9 +1,13 @@
class Admins::DashboardsController < Admins::BaseController
def index
# 查询优化
week_greater_id = CommitLog.where(created_at: current_week).limit(1)[0]&.id
#月份统计还需要优化
month_greater_id = CommitLog.where(created_at: current_month).limit(1)[0]&.id
# 用户活跃数
day_user_ids = CommitLog.where(created_at: today).pluck(:user_id).uniq
weekly_user_ids = CommitLog.where(created_at: current_week).pluck(:user_id).uniq
month_user_ids = CommitLog.where(created_at: current_month).pluck(:user_id).uniq
weekly_user_ids = CommitLog.where(created_at: current_week).where("id>= ?", week_greater_id).distinct.pluck(:user_id)
month_user_ids = CommitLog.where(created_at: current_month).where("id>= ?", month_greater_id).distinct.pluck(:user_id)
@active_user_count = User.where(last_login_on: today).or(User.where(id: day_user_ids)).count
@weekly_active_user_count = User.where(last_login_on: current_week).or(User.where(id: weekly_user_ids)).count
@month_active_user_count = User.where(last_login_on: current_month).or(User.where(id: month_user_ids)).count
@ -18,8 +22,8 @@ class Admins::DashboardsController < Admins::BaseController
# 活跃项目数
day_project_ids = (CommitLog.where(created_at: today).pluck(:project_id).uniq + Issue.where(created_on: today).pluck(:project_id).uniq).uniq
weekly_project_ids = (CommitLog.where(created_at: current_week).pluck(:project_id).uniq + Issue.where(created_on: current_week).pluck(:project_id).uniq).uniq
month_project_ids = (CommitLog.where(created_at: current_month).pluck(:project_id).uniq + Issue.where(created_on: current_month).pluck(:project_id).uniq).uniq
weekly_project_ids = (CommitLog.where(created_at: current_week).where("id>= ?", week_greater_id).distinct.pluck(:project_id) + Issue.where(created_on: current_week).pluck(:project_id).uniq).uniq
month_project_ids = (CommitLog.where(created_at: current_month).where("id>= ?", month_greater_id).distinct.pluck(:project_id) + Issue.where(created_on: current_month).pluck(:project_id).uniq).uniq
@day_active_project_count = Project.where(updated_on: today).or(Project.where(id: day_project_ids)).count
@weekly_active_project_count = Rails.cache.fetch("dashboardscontroller:weekly_active_project_count", expires_in: 10.minutes) do
Project.where(updated_on: current_week).or(Project.where(id: weekly_project_ids)).count

View File

@ -1,4 +1,5 @@
class Admins::EduSettingsController < Admins::BaseController
before_action :require_admin
before_action :find_setting, only: [:edit,:update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::FaqsController < Admins::BaseController
before_action :require_business
before_action :find_faq, only: [:edit,:update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::FeedbacksController < Admins::BaseController
before_action :require_business
before_action :get_feedback, only: [:new_history, :create_history, :destroy]
def index

View File

@ -1,4 +1,6 @@
class Admins::GlccPrCheckController < Admins::BaseController
before_action :require_glcc_admin
def index
params[:sort_by] = params[:sort_by].presence || 'created_on'
params[:sort_direction] = params[:sort_direction].presence || 'desc'

View File

@ -1,4 +1,5 @@
class Admins::IdentityVerificationsController < Admins::BaseController
before_action :require_business
before_action :finder_identity_verification, except: [:index]
def index
params[:sort_by] = params[:sort_by].presence || 'created_at'

View File

@ -1,4 +1,5 @@
class Admins::IssuesRankController < Admins::BaseController
before_action :require_admin
def index
@statistics = DailyProjectStatistic.where('date >= ? AND date <= ?', begin_date, end_date)

View File

@ -1,4 +1,5 @@
class Admins::LaboratoriesController < Admins::BaseController
before_action :require_admin
def index
default_sort('id', 'desc')

View File

@ -1,4 +1,5 @@
class Admins::MessageTemplatesController < Admins::BaseController
before_action :require_admin
before_action :get_template, only: [:edit, :update, :destroy]
def index
@ -7,12 +8,12 @@ class Admins::MessageTemplatesController < Admins::BaseController
end
def new
@message_template = MessageTemplate.new
@message_template = MessageTemplate::CustomTip.new
end
def create
@message_template = MessageTemplate::CustomTip.new(message_template_params)
@message_template.type = "MessageTemplate::CustomTip"
def create
@message_template = MessageTemplate::CustomTip.new
@message_template.attributes = message_template_params
if @message_template.save!
redirect_to admins_message_templates_path
flash[:success] = "创建消息模板成功"
@ -47,9 +48,7 @@ class Admins::MessageTemplatesController < Admins::BaseController
private
def message_template_params
# type = @message_template.present? ? @message_template.type : "MessageTemplate::CustomTip"
# params.require(type.split("::").join("_").underscore.to_sym).permit!
params.require(:message_template_custom_tip).permit!
params.require(@message_template.type.split("::").join("_").underscore.to_sym).permit!
end
def get_template

View File

@ -1,4 +1,5 @@
class Admins::NpsController < Admins::BaseController
before_action :require_business
def index
@on_off_switch = EduSetting.get("nps-on-off-switch").to_s == 'true'
@user_nps = UserNp.joins(:user).order(created_at: :desc)

View File

@ -1,5 +1,6 @@
class Admins::OrganizationsController < Admins::BaseController
before_action :finder_org, except: [:index]
before_action :require_admin
before_action :finder_org, except: [:index]
def index
params[:sort_by] = params[:sort_by].presence || 'created_on'

View File

@ -1,4 +1,5 @@
class Admins::PageThemesController < Admins::BaseController
before_action :require_admin
before_action :finder_page_theme, only: [:edit, :update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::ProjectCategoriesController < Admins::BaseController
before_action :require_admin
before_action :get_category, only: [:edit,:update, :destroy]
before_action :validate_names, only: [:create, :update]

View File

@ -1,4 +1,5 @@
class Admins::ProjectIgnoresController < Admins::BaseController
before_action :require_admin
before_action :set_ignore, only: [:edit,:update, :destroy,:show]
# before_action :validate_params, only: [:create, :update]

View File

@ -1,4 +1,5 @@
class Admins::ProjectLanguagesController < Admins::BaseController
before_action :require_admin
before_action :get_language, only: [:edit,:update, :destroy]
before_action :validate_names, only: [:create, :update]

View File

@ -1,4 +1,5 @@
class Admins::ProjectLicensesController < Admins::BaseController
before_action :require_admin
before_action :set_license, only: [:edit,:update, :destroy,:show]
# before_action :validate_params, only: [:create, :update]
@ -6,7 +7,7 @@ class Admins::ProjectLicensesController < Admins::BaseController
sort_by = License.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_at'
sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
q = License.ransack(name_cont: params[:search])
project_licenses = q.result(distinct: true).order("#{sort_by} #{sort_direction}")
project_licenses = q.result(distinct: true).reorder("#{sort_by} #{sort_direction}")
@project_licenses = paginate(project_licenses)
end
@ -95,7 +96,7 @@ class Admins::ProjectLicensesController < Admins::BaseController
end
def license_params
params.require(:license).permit(:name,:content)
params.require(:license).permit(:name,:content,:position)
end
# def validate_params

View File

@ -1,11 +1,22 @@
class Admins::ProjectsController < Admins::BaseController
before_action :require_admin
before_action :find_project, only: [:edit, :update]
def index
sort_by = Project.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_on'
sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
search = params[:search].to_s.strip
projects = Project.where("name like ?", "%#{search}%").order("#{sort_by} #{sort_direction}")
projects = Project.where("name like ? OR identifier LIKE ?", "%#{search}%", "%#{search}%").order("#{sort_by} #{sort_direction}")
case params[:category]
when 'public'
projects = projects.where(is_public: true)
when 'private'
projects = projects.where(is_public: false)
when 'fork'
projects = projects.where.not(forked_from_project_id: nil)
when 'original'
projects = projects.where(forked_from_project_id: nil, project_type: 'common')
end
@projects = paginate projects.includes(:owner, :members, :issues, :versions, :attachments, :project_score)
end
@ -32,8 +43,12 @@ class Admins::ProjectsController < Admins::BaseController
def destroy
project = Project.find_by!(id: params[:id])
ActiveRecord::Base.transaction do
Gitea::Repository::DeleteService.new(project.owner, project.identifier).call
close_fork_pull_requests_by(project)
Gitea::Repository::DeleteService.new(project.owner, project.identifier, current_user.gitea_token).call
project.destroy!
project.forked_projects.update_all(forked_from_project_id: nil)
# 如果该项目有所属的项目分类以及为私有项目,需要更新对应数量
project.project_category.decrement!(:private_projects_count, 1) if project.project_category.present? && !project.is_public
# render_delete_success
UserAction.create(action_id: project.id, action_type: "DestroyProject", user_id: current_user.id, :ip => request.remote_ip, data_bank: project.attributes.to_json)
redirect_to admins_projects_path
@ -52,4 +67,19 @@ class Admins::ProjectsController < Admins::BaseController
def project_update_params
params.require(:project).permit(:is_pinned, :recommend, :recommend_index)
end
def close_fork_pull_requests_by(project)
open_pull_requests = PullRequest.where(fork_project_id: project.id)
if open_pull_requests.present?
open_pull_requests.each do |pull_request|
closed = PullRequests::CloseService.call(pull_request&.project.owner, pull_request&.project.repository, pull_request, current_user)
if closed === true
pull_request.project_trends.create!(user: current_user, project: pull_request&.project,action_type: ProjectTrend::CLOSE)
# 合并请求下issue处理为关闭
pull_request.issue&.update_attributes!({status_id:5})
SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, pull_request.id) if Site.has_notice_menu?
end
end
end
end
end

View File

@ -1,4 +1,6 @@
class Admins::ProjectsRankController < Admins::BaseController
before_action :require_admin
def index
@statistics = DailyProjectStatistic.where("date >= ? AND date <= ?", begin_date, end_date)
@statistics = @statistics.group(:project_id).select("project_id,
@ -10,7 +12,7 @@ class Admins::ProjectsRankController < Admins::BaseController
sum(issues) as issues,
sum(pullrequests) as pullrequests,
sum(commits) as commits").includes(:project)
@statistics = @statistics.order("#{sort_by} #{sort_direction}")
@statistics = paginate @statistics.order("#{sort_by} #{sort_direction}")
export_excel(@statistics.limit(50))
end

View File

@ -1,4 +1,5 @@
class Admins::ReversedKeywordsController < Admins::BaseController
before_action :require_admin
before_action :get_keyword, only: [:edit,:update, :destroy]
# before_action :validate_identifer, only: [:create, :update]

View File

@ -1,4 +1,5 @@
class Admins::SitePagesController < Admins::BaseController
before_action :require_admin
before_action :finder_site_page, except: [:index]
def index

View File

@ -1,4 +1,5 @@
class Admins::SitesController < Admins::BaseController
before_action :require_admin
before_action :find_site, only: [:edit,:update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::SystemNotificationsController < Admins::BaseController
before_action :require_business
before_action :get_notification, only: [:history, :edit,:update, :destroy]
# before_action :validate_identifer, only: [:create, :update]

View File

@ -1,4 +1,5 @@
class Admins::Topic::ActivityForumsController < Admins::Topic::BaseController
before_action :require_business
before_action :find_activity_forum, only: [:edit, :update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::Topic::BannersController < Admins::Topic::BaseController
before_action :require_business
before_action :find_banner, only: [:edit, :update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::Topic::CardsController < Admins::Topic::BaseController
before_action :require_business
before_action :find_card, only: [:edit, :update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::Topic::CooperatorsController < Admins::Topic::BaseController
before_action :require_business
before_action :find_cooperator, only: [:edit, :update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::Topic::ExcellentProjectsController < Admins::Topic::BaseController
before_action :require_business
before_action :find_excellent_project, only: [:edit, :update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::Topic::ExperienceForumsController < Admins::Topic::BaseController
before_action :require_business
before_action :find_experience_forum, only: [:edit, :update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::Topic::GlccNewsController < Admins::Topic::BaseController
before_action :require_glcc_admin
before_action :find_glcc, only: [:edit, :update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::Topic::PinnedForumsController < Admins::Topic::BaseController
before_action :require_business
before_action :find_pinned_forum, only: [:edit, :update, :destroy]
def index

View File

@ -1,4 +1,5 @@
class Admins::UsersController < Admins::BaseController
before_action :require_admin
before_action :finder_user, except: [:index]
def index
@ -73,6 +74,6 @@ class Admins::UsersController < Admins::BaseController
def update_params
params.require(:user).permit(%i[lastname nickname gender technical_title is_shixun_marker
mail phone location location_city school_id department_id admin
password login website_permission])
password login website_permission business glcc_admin])
end
end

View File

@ -1,4 +1,5 @@
class Admins::UsersRankController < Admins::BaseController
before_action :require_admin
def index
@rank_date = rank_date

View File

@ -55,6 +55,11 @@ class Api::V1::BaseController < ApplicationController
return render_forbidden if !current_user.admin? && !@project.operator?(current_user) && !(@project.fork_project.present? && @project.fork_project.operator?(current_user))
end
def require_member_above
@project = load_project
return render_forbidden if !current_user.admin? && !@project.member?(current_user)
end
# 具有对仓库的访问权限
def require_public_and_member_above
@project = load_project

View File

@ -0,0 +1,37 @@
class Api::V1::GitlinkCompetitionAppliesController < Api::V1::BaseController
def create
return render_error("请输入正确的竞赛ID") unless params[:competition_id].present?
return render_error("请输入正确的队伍ID") unless params[:team_id].present?
return render_error("请输入正确的队伍成员信息") unless params[:team_members].is_a?(Array)
params[:team_members].each do |member|
apply = GitlinkCompetitionApply.find_or_create_by(competition_id: params[:competition_id], team_id: params[:team_id], educoder_login: member[:login])
apply.competition_identifier = params[:competition_identifier]
apply.team_name = params[:team_name]
apply.school_name = member[:school_name]
apply.nickname = member[:nickname]
apply.identity = member[:identity]
apply.role = member[:role]
apply.email = member[:email]
user_info = get_user_info_by_educoder_login(member[:login])
apply.phone = user_info["phone"]
apply.save
end
render_ok
end
def get_user_info_by_educoder_login(edu_login)
req_params = { "login" => "#{edu_login}", "private_token" => "hriEn3UwXfJs3PmyXnqQ" }
api_url= "https://data.educoder.net"
client = Faraday.new(url: api_url)
response = client.public_send("get", "/api/sources/get_user_info_by_login", req_params)
result = JSON.parse(response.body)
return nil if result["status"].to_s != "0"
# login 邮箱 手机号 姓名 学校/单位
user_info = result["data"]
return user_info
end
end

View File

@ -0,0 +1,10 @@
class Api::V1::ProjectDatasetsController < Api::V1::BaseController
def index
return render_error("请输入正确的项目id字符串") unless params[:ids].present?
ids = params[:ids].split(",")
@project_datasets = ProjectDataset.where(project_id: ids).includes(:license, :project)
@project_datasets = kaminari_unlimit_paginate(@project_datasets)
end
end

View File

@ -5,8 +5,53 @@ class Api::V1::Projects::Actions::RunsController < Api::V1::Projects::Actions::B
puts @result_object
end
def create
return render_error("请输入正确的流水线文件!") if params[:workflow].blank?
return render_error("请输入正确的分支!") if params[:ref].blank?
gitea_result = $gitea_hat_client.post_repos_actions_runs_by_owner_repo(@project&.owner&.login, @project&.identifier, {query: {workflow: params[:workflow], ref: params[:ref]}})
if gitea_result
render_ok
else
ender_error("启动流水线任务失败")
end
end
def rerun
return render_error("请输入正确的流水线记录ID") if params[:run_id].blank?
gitea_result = $gitea_hat_client.post_repos_actions_runs_rerun_by_owner_repo_run(@project&.owner&.login, @project&.identifier, params[:run_id]) rescue nil
if gitea_result
render_ok
else
render_error("重启所有流水线任务失败")
end
end
def job_rerun
return render_error("请输入正确的流水线记录ID") if params[:run_id].blank?
return render_error("请输入正确的流水线任务ID") if params[:job].blank?
gitea_result = $gitea_hat_client.post_repos_actions_runs_jobs_rerun_by_owner_repo_run_job(@project&.owner&.login, @project&.identifier, params[:run_id], params[:job]) rescue nil
if gitea_result
render_ok
else
render_error("重启流水线任务失败")
end
end
def job_show
@result_object = Api::V1::Projects::Actions::Runs::JobShowService.call(@project, params[:run_id], params[:job], params[:log_cursors], current_user&.gitea_token)
end
def job_logs
return render_error("请输入正确的流水线记录ID") if params[:run_id].blank?
return render_error("请输入正确的流水线任务ID") if params[:job].blank?
domain = GiteaService.gitea_config[:domain]
api_url = GiteaService.gitea_config[:hat_base_url]
url = "/repos/#{@owner.login}/#{@repository.identifier}/actions/runs/#{CGI.escape(params[:run_id])}/jobs/#{CGI.escape(params[:job])}/logs"
file_path = [domain, api_url, url].join
file_path = [file_path, "access_token=#{@owner&.gitea_token}"].join("?")
redirect_to file_path
end
end

View File

@ -1,6 +1,29 @@
class Api::V1::Projects::BranchesController < Api::V1::BaseController
before_action :require_public_and_member_above, only: [:index, :all]
def gitee
url = URI("https://gitee.com/api/v5/repos/#{params[:owner]}/#{params[:repo]}/branches?access_token=#{params[:token]}&page=#{page}&per_page=#{limit}")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
response = https.request(request)
render :json => response.read_body
end
def github
url = URI("https://api.github.com/repos/#{params[:owner]}/#{params[:repo]}/branches?page=#{page}&per_page=#{limit}")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = "Bearer #{params[:token]}"
request["Accept"] = "application/vnd.github+json"
request["X-GitHub-Api-Version"] = "2022-11-28"
response = https.request(request)
render :json => response.read_body
end
def index
@result_object = Api::V1::Projects::Branches::ListService.call(@project, {name: params[:keyword], state: params[:state], page: page, limit: limit}, current_user&.gitea_token)
end

View File

@ -11,6 +11,9 @@ class Api::V1::Projects::CommitsController < Api::V1::BaseController
end
def recent
@result_object = Api::V1::Projects::Commits::RecentService.call(@project, {keyword: params[:keyword], page: page, limit: limit}, current_user&.gitea_token)
hash = Api::V1::Projects::Commits::RecentService.call(@project, {keyword: params[:keyword], page: page, limit: limit}, current_user&.gitea_token)
@result_object = hash[:result]
@object_detail = hash[:detail]
puts @object_detail
end
end

View File

@ -0,0 +1,51 @@
class Api::V1::Projects::DatasetsController < Api::V1::BaseController
before_action :require_public_and_member_above, only: [:show]
before_action :require_member_above, only: [:create, :update]
before_action :find_dataset, only: [:update, :show]
before_action :check_menu_authorize
def create
::Projects::Datasets::CreateForm.new(dataset_params).validate!
return render_error('该项目下已存在数据集!') if @project.project_dataset.present?
@project_dataset = ProjectDataset.new(dataset_params.merge!(project_id: @project.id))
if @project_dataset.save!
render_ok
else
render_error('创建数据集失败!')
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def update
::Projects::Datasets::CreateForm.new(dataset_params).validate!
@project_dataset.attributes = dataset_params
if @project_dataset.save!
render_ok
else
render_error("更新数据集失败!")
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def show
@attachments = kaminari_paginate(@project_dataset.attachments.includes(:author))
end
private
def dataset_params
params.permit(:title, :description, :license_id, :paper_content)
end
def find_dataset
@project_dataset = @project.project_dataset
return render_not_found unless @project_dataset.present?
end
def check_menu_authorize
return render_not_found unless @project.has_menu_permission("dataset")
end
end

View File

@ -0,0 +1,52 @@
class Api::V1::Projects::PortraitController < Api::V1::BaseController
before_action :require_public_and_member_above
def index
platform_statistic = $redis_cache.hgetall("v2-platform-statistic")
# 社区影响力
praise_count = PraiseTread.where(praise_tread_object_type: "Project", praise_tread_object_id: @project.id).count
watcher_count = Watcher.where(watchable_type:"Project", watchable_id: @project.id).count
fork_count = ForkUser.where(project_id: @project.id).count
community_impact_praise = platform_statistic['max-praise-count'].to_i == 0 ? 0 : 30*(praise_count.to_f/platform_statistic['max-praise-count'].to_i)
community_impact_watcher = platform_statistic['max-watcher-count'].to_i == 0 ? 0 : 30*(watcher_count.to_f/platform_statistic['max-watcher-count'].to_i)
community_impact_fork = platform_statistic['max-fork-count'].to_i == 0 ? 0 : 40*(fork_count.to_f/platform_statistic['max-fork-count'].to_i)
community_impact = format("%.2f", community_impact_praise + community_impact_watcher + community_impact_fork)
# 项目成熟度
pullrequest_count = PullRequest.where(project_id: @project.id).count
issue_count = Issue.issue_issue.where(project_id: @project.id).count
commit_count = CommitLog.joins(:project).merge(Project.common).where(project_id: @project.id).count
project_maturity_pullrequest = platform_statistic['max-pullrequest-count'].to_i == 0 ? 0 : 30*(pullrequest_count.to_f/platform_statistic['max-pullrequest-count'].to_i)
project_maturity_issue = platform_statistic['max-issue-count'].to_i == 0 ? 0 : 30*(issue_count.to_f/platform_statistic['max-issue-count'].to_i)
project_maturity_commit = platform_statistic['max-commit-count'].to_i == 0 ? 0 : 40*(commit_count.to_f/platform_statistic['max-commit-count'].to_i)
project_maturity = format("%.2f", project_maturity_pullrequest + project_maturity_issue + project_maturity_commit)
# 项目健康度
closed_pullrequest_count = PullRequest.where(project_id: @project.id).merged_and_closed.count
closed_issue_count = Issue.issue_issue.where(project_id: @project.id).closed.count
has_license = @project.license.present? ? 1 : 0
project_health_issue = (issue_count < 10 || closed_issue_count < 10) ? 0 : 40*(closed_issue_count-10).to_f/(issue_count-10)
project_health_pullrequest = (pullrequest_count < 5 || closed_pullrequest_count < 5) ? 0 : 30*(closed_pullrequest_count-5).to_f/(pullrequest_count-5)
project_health_license = 20*has_license
project_health = format("%.2f", project_health_issue + project_health_pullrequest + project_health_license)
# 团队影响度
member_count = Member.where(project_id: @project.id).count
recent_one_month_member_count = Member.where(project_id:@project.id).where("created_on > ?", Time.now - 30.days).count
team_impact_member = platform_statistic['max-member-count'].to_i == 0 ? 0 : 40*(member_count.to_f/platform_statistic['max-member-count'].to_i)
team_impact_recent_member = platform_statistic['max-recent-one-month-member-count'].to_i == 0 ? 0 : 60*(recent_one_month_member_count.to_f/platform_statistic['max-recent-one-month-member-count'].to_i)
team_impact = format("%.2f", team_impact_member + team_impact_recent_member)
# 开发活跃度
recent_one_month_pullrequest_count = PullRequest.where(project_id: @project.id).where("created_at > ?", Time.now - 30.days).count
recent_one_month_issue_count = Issue.issue_issue.where(project_id: @project.id).where("created_on > ?", Time.now - 30.days).count
recent_one_month_commit_count = CommitLog.joins(:project).merge(Project.common).where(project_id: @project.id).where("created_at > ?", Time.now - 30.days).count
develop_activity_pullrequest = platform_statistic['max-recent-one-month-pullrequest-count'].to_i == 0 ? 0 : 20*(recent_one_month_pullrequest_count.to_f/platform_statistic['max-recent-one-month-pullrequest-count'].to_i)
develop_activity_issue = platform_statistic['max-recent-one-month-issue-count'].to_i == 0 ? 0 : 20*(recent_one_month_issue_count.to_f/platform_statistic['max-recent-one-month-issue-count'].to_i)
develop_activity_commit = platform_statistic['max-recent-one-month-commit-count'].to_i == 0 ? 0 : 40*(recent_one_month_commit_count.to_f/platform_statistic['max-recent-one-month-commit-count'].to_i)
develop_activity = format("%.2f", 20 + develop_activity_pullrequest + develop_activity_issue + develop_activity_commit)
render :json => {community_impact: community_impact, project_maturity: project_maturity, project_health: project_health, team_impact: team_impact, develop_activity: develop_activity}
end
end

View File

@ -0,0 +1,148 @@
class Api::V1::Projects::SyncRepositoriesController < Api::V1::BaseController
before_action :require_public_and_member_above, except: [:sync]
before_action :load_project, only: [:sync]
def index
@sync_repositories = @project.sync_repositories
@group_sync_repository = @project.sync_repositories.group(:type, :external_repo_address, :sync_granularity, :external_token).count
end
def create
@sync_repository1, @sync_repository2, @sync_repository_branch1, @sync_repository_branch2 = Api::V1::Projects::SyncRepositories::CreateService.call(@project, sync_repository_params)
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def update_info
return render_error("请输入正确的同步仓库ID") unless params[:sync_repository_ids].present?
Api::V1::Projects::SyncRepositories::UpdateService.call(@project, params[:sync_repository_ids], sync_repository_update_params)
render_ok
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def sync
return render_error("请输入正确的同步方向!") if params[:sync_direction].blank?
if params[:repo_type].present?
@sync_repositories = SyncRepository.where(project: @project, type: params[:repo_type], sync_direction: params[:sync_direction])
else
@sync_repositories = SyncRepository.where(project: @project, sync_direction: params[:sync_direction])
end
branch = params[:payload].present? ? JSON.parse(params[:payload])["ref"].split("/")[-1] : params[:ref].split("/")[-1] rescue nil
if params[:sync_direction].to_i == 1
@sync_repository_branches = SyncRepositoryBranch.where(sync_repository_id: @sync_repositories, gitlink_branch_name: branch, enable: true)
else
@sync_repository_branches = SyncRepositoryBranch.where(sync_repository_id: @sync_repositories, external_branch_name: branch, enable: true)
end
# 全部分支同步暂时不做
# @sync_repositories.each do |item|
# TouchSyncJob.perform_later(item)
# end
@sync_repository_branches.each do |item|
TouchSyncJob.set(wait: 5.seconds).perform_later(item)
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def unbind
return render_error("请输入正确的同步仓库ID") unless params[:sync_repository_ids].present?
@sync_repositories = SyncRepository.where(id: params[:sync_repository_ids].split(","))
@sync_repositories.each do |repo|
# Reposync::DeleteRepoService.call(repo.repo_name) # 解绑操作放在回调里
Api::V1::Projects::Webhooks::DeleteService.call(@project, repo.webhook_gid)
repo.destroy
end
render_ok
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def change_enable
return render_error("请输入正确的仓库类型") if params[:repo_type].blank?
return render_error("请输入正确的分支名称") if params[:gitlink_branch_name].blank? || params[:external_branch_name].blank?
# return render_error("请输入正确的状态") if params[:enable].blank?
@sync_repository_branches = SyncRepositoryBranch.joins(:sync_repository).where(sync_repositories: {project_id: @project.id, type: params[:repo_type]}, gitlink_branch_name: params[:gitlink_branch_name], external_branch_name: params[:external_branch_name])
if @sync_repository_branches.update_all({enable: params[:enable]})
@sync_repository_branches.each do |branch|
branch_sync_direction = branch&.sync_repository&.sync_direction.to_i
if branch_sync_direction == 1
Reposync::UpdateBranchStatusService.call(branch&.sync_repository&.repo_name, branch.gitlink_branch_name, params[:enable])
else
Reposync::UpdateBranchStatusService.call(branch&.sync_repository&.repo_name, branch.external_branch_name, params[:enable])
end
TouchSyncJob.perform_later(branch) if params[:enable] && branch_sync_direction == params[:first_sync_direction].to_i
end
render_ok
else
render_error("更新失败!")
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def create_branch
return render_error("请输入正确的同步仓库ID") unless params[:sync_repository_ids].present?
return render_error("请输入正确的Gitlink分支名称") unless params[:gitlink_branch_name].present?
return render_error("请输入正确的外部仓库分支名称") unless params[:external_branch_name].present?
return render_error("请输入正确的首次同步方向") unless params[:first_sync_direction].present?
params[:sync_repository_ids].split(",").each do |id|
repo = SyncRepository.find_by_id id
branch = Reposync::CreateSyncBranchService.call(repo.repo_name, params[:gitlink_branch_name], params[:external_branch_name])
return render_error(branch[2]) if branch[0].to_i !=0
sync_branch = SyncRepositoryBranch.create!(sync_repository_id: id, gitlink_branch_name: params[:gitlink_branch_name], external_branch_name: params[:external_branch_name], reposync_branch_id: branch[1]['id'])
TouchSyncJob.perform_later(sync_branch) if params[:first_sync_direction].to_i == repo.sync_direction
end
render_ok
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def branches
return render_error("请输入正确的同步仓库ID") unless params[:sync_repository_ids].present?
@sync_repository_branches = SyncRepositoryBranch.where(sync_repository_id: params[:sync_repository_ids].split(","))
@sync_repository_branches = @sync_repository_branches.ransack(gitlink_branch_name_or_external_branch_name_cont: params[:branch_name]).result if params[:branch_name].present?
@group_sync_repository_branch = @sync_repository_branches.joins(:sync_repository).group("sync_repositories.type, sync_repository_branches.gitlink_branch_name, sync_repository_branches.external_branch_name").select("sync_repositories.type as type,max(sync_repository_branches.updated_at) as updated_at, sync_repository_branches.gitlink_branch_name, sync_repository_branches.external_branch_name").sort_by{|i|i.updated_at}
@each_json = []
@group_sync_repository_branch.each do |item|
branches = @sync_repository_branches.joins(:sync_repository).where(sync_repositories: {type: item.type}, gitlink_branch_name: item.gitlink_branch_name, external_branch_name: item.external_branch_name).order(sync_time: :desc)
branch = branches.first
@each_json << {
gitlink_branch_name: item.gitlink_branch_name,
external_branch_name: item.external_branch_name,
type: branch&.sync_repository&.type,
sync_time: branch.sync_time.present? ? branch.sync_time.strftime("%Y-%m-%d %H:%M:%S") : nil,
sync_status: branch.sync_status,
enable: branch.enable,
enable_num: branch.enable ? 1 : 0,
created_at: branch.created_at.to_i,
reposync_branch_ids: branches.pluck(:reposync_branch_id)
}
end
@each_json = @each_json.sort_by{|h| [-h[:enable_num], h[:created_at]]}
render :json => {total_count: @group_sync_repository_branch.count, sync_repository_branches: @each_json}
end
def history
return render_error("请输入正确的同步分支ID") unless params[:reposync_branch_ids]
@branch = SyncRepositoryBranch.find_by(reposync_branch_id: params[:reposync_branch_ids].split(",")[0])
_, @reposync_branch_logs, @total_count, _ = Reposync::GetLogsService.call(nil, params[:reposync_branch_ids], page, limit)
end
private
def sync_repository_params
params.permit(:type, :external_token, :external_repo_address, :sync_granularity, :external_branch_name, :gitlink_branch_name, :first_sync_direction)
end
def sync_repository_update_params
params.permit(:external_token, :external_repo_address)
end
end

View File

@ -0,0 +1,23 @@
class Api::V1::Users::HomeTopSettingsController < Api::V1::BaseController
before_action :load_observe_user
before_action :check_auth_for_observe_user
def create
@result = Api::V1::Users::HomeTopSettings::CreateService.call(@observe_user, home_top_setting_params)
return render_error("置顶失败.") if @result.nil?
return render_ok
end
def cancel
@result = Api::V1::Users::HomeTopSettings::DeleteService.call(@observe_user, home_top_setting_params)
return render_error("取消置顶失败.") if @result.nil?
return render_ok
end
private
def home_top_setting_params
params.permit(:top_type, :top_id)
end
end

View File

@ -75,7 +75,11 @@ class ApplicationController < ActionController::Base
def admin_or_business?
User.current.admin? || User.current.business?
User.current.admin? || User.current.business?
end
def admin_or_glcc_admin?
User.current.admin? || User.current.glcc_admin?
end
# 判断用户的邮箱或者手机是否可用
@ -195,6 +199,10 @@ class ApplicationController < ActionController::Base
normal_status(403, "") unless admin_or_business?
end
def require_glcc_admin
normal_status(403, "") unless admin_or_glcc_admin?
end
# 前端会捕捉401,弹登录弹框
# 未授权的捕捉407弹试用申请弹框
def require_login

View File

@ -95,6 +95,9 @@ class AttachmentsController < ApplicationController
@attachment.disk_directory = month_folder
@attachment.cloud_url = remote_path
@attachment.uuid = SecureRandom.uuid
@attachment.description = params[:description]
@attachment.container_id = params[:container_id]
@attachment.container_type = params[:container_type]
@attachment.save!
else
logger.info "文件已存在id = #{@attachment.id}, filename = #{@attachment.filename}"
@ -124,7 +127,7 @@ class AttachmentsController < ApplicationController
# 附件为视频时,点击播放
def preview_attachment
attachment = Attachment.find_by(id: params[:id])
attachment = Attachment.where_id_or_uuid(params[:id]).first
dir_path = "#{Rails.root}/public/preview"
Dir.mkdir(dir_path) unless Dir.exist?(dir_path)
if params[:status] == "preview"

View File

@ -19,9 +19,10 @@ class CommitLogsController < ApplicationController
params[:commits].each do |commit|
commit_id = commit[:id]
message = commit[:message]
commit_date = Time.parse(commit[:timestamp]) || Time.now
commit_log = CommitLog.create(user: user, project: project, repository_id: repository_id,
name: repository_name, full_name: repository_full_name,
ref: ref, commit_id: commit_id, message: message)
ref: ref, commit_id: commit_id, message: message, created_at: commit_date, updated_at: commit_date)
commit_log.project_trends.create(user_id: user.id, project_id: project&.id, action_type: "create") if user.id !=2
# 统计数据新增
CacheAsyncSetJob.perform_later("project_common_service", {commits: 1}, project.id)

View File

@ -21,6 +21,7 @@ class MainController < ApplicationController
end
def index
Rails.logger.info("request.referer============#{request.referer},#{params[:path]}") if request.referer.to_s.include?("educoder.net")
domain_session = params[:_educoder_session]
if domain_session
uid_logger("main start domain_session is #{domain_session}")

View File

@ -1,6 +1,18 @@
class Oauth::AcgeController < Oauth::BaseController
include RegisterHelper
def refer
uid = params['uid'].to_s.strip
tip_exception("uid不能为空") if uid.blank?
open_user = OpenUsers::Acge.find_by(uid: uid)
if open_user.present? && open_user.user.present?
render :json => {login: open_user.user.login}
else
render_not_found
end
end
def create
begin
uid = params['uid'].to_s.strip
@ -30,7 +42,7 @@ class Oauth::AcgeController < Oauth::BaseController
return
else
username = uid[0..7]
username = uid
password = SecureRandom.hex(4)
reg_result = autologin_register(username, email, password, 'acge', phone, name)
existing_rows = CSV.read("public/操作系统大赛用户信息.csv")

View File

@ -67,7 +67,18 @@ class Organizations::TeamsController < Organizations::BaseController
tip_exception("组织团队不允许被删除") if @team.owner?
ActiveRecord::Base.transaction do
Gitea::Organization::Team::DeleteService.call(@organization.gitea_token, @team.gtid)
other_user_ids = @organization.team_users.where.not(team_id: @team.id).pluck(:user_id)
team_user_ids = @team.team_users.pluck(:user_id)
# 当前删除团队中成员在其他组织其他团队不存在的成员需清除组织
remove_user_ids = team_user_ids - other_user_ids
Rails.logger.info "remove_user_ids ===========> #{remove_user_ids}"
@team.destroy!
if remove_user_ids.present?
User.where(id: remove_user_ids).each do |user|
@organization.organization_users.find_by(user_id: user.id).destroy!
Gitea::Organization::OrganizationUser::DeleteService.call(@organization.gitea_token, @organization.login, user.login)
end
end
end
render_ok
rescue Exception => e

View File

@ -21,6 +21,7 @@ class ProjectsController < ApplicationController
menu.append(menu_hash_by_name("issues")) if @project.has_menu_permission("issues")
menu.append(menu_hash_by_name("pulls")) if @project.has_menu_permission("pulls") && @project.forge?
menu.append(menu_hash_by_name("devops")) if @project.has_menu_permission("devops") && @project.forge?
menu.append(menu_hash_by_name("dataset")) if @project.has_menu_permission("dataset") && @project.forge?
menu.append(menu_hash_by_name("versions")) if @project.has_menu_permission("versions")
menu.append(menu_hash_by_name("wiki")) if @project.has_menu_permission("wiki") && @project.forge?
menu.append(menu_hash_by_name("services")) if @project.has_menu_permission("services") && @project.forge? && (current_user.admin? || @project.member?(current_user.id))
@ -35,6 +36,8 @@ class ProjectsController < ApplicationController
def index
scope = current_user.logged? ? Projects::ListQuery.call(params, current_user.id) : Projects::ListQuery.call(params)
# scope = scope.joins(repository: :mirror).where.not(mirrors: {status: 2}) # 导入失败项目不显示
@projects = kaminari_paginate(scope.includes(:project_category, :project_language, :repository, :project_educoder, :owner, :project_units, :project_topics))
# @projects = paginate scope.includes(:project_category, :project_language, :repository, :project_educoder, :owner, :project_units)
@ -42,7 +45,8 @@ class ProjectsController < ApplicationController
@total_count =
if category_id.blank? && params[:search].blank? && params[:topic_id].blank?
# 默认查询时count性能问题处理
ProjectCategory.sum("projects_count") - Project.visible.joins("left join organization_extensions on organization_extensions.organization_id = projects.user_id").where("organization_extensions.visibility =2").count
not_category_count = Project.where(project_category_id: nil).count
ProjectCategory.sum("projects_count") - Project.visible.joins("left join organization_extensions on organization_extensions.organization_id = projects.user_id").where("organization_extensions.visibility =2").count + not_category_count
elsif params[:search].present? || params[:topic_id].present?
@projects.total_count
else
@ -58,7 +62,11 @@ class ProjectsController < ApplicationController
OpenProjectDevOpsJob.set(wait: 5.seconds).perform_later(@project&.id, current_user.id)
UpdateProjectTopicJob.perform_later(@project.id) if @project.id.present?
end
rescue Exception => e
rescue Gitea::Api::ServerError => ex
uid_logger_error(ex.message)
# tip_exception(ex.http_code, ex.message)
tip_exception(ex.message)
rescue ApplicationService::Error => e
uid_logger_error(e.message)
tip_exception(e.message)
end
@ -209,7 +217,11 @@ class ProjectsController < ApplicationController
new_project_params = project_params.except(:private).merge(is_public: !private)
@project.update_attributes!(new_project_params)
@project.forked_projects.update_all(is_public: @project.is_public)
fork_pull_requests = PullRequest.where(fork_project_id: @project.id)
if fork_pull_requests.present?
fork_pull_requests.update_all(fork_project_identifier: @project.identifier)
end
@project.forked_projects.map{|p| p.update!(is_public: @project.is_public)}
gitea_params = {
private: private,
default_branch: @project.default_branch,
@ -250,7 +262,8 @@ class ProjectsController < ApplicationController
def destroy
if current_user.admin? || @project.manager?(current_user)
ActiveRecord::Base.transaction do
Gitea::Repository::DeleteService.new(@project.owner, @project.identifier).call
close_fork_pull_requests_by(@project)
Gitea::Repository::DeleteService.new(@project.owner, @project.identifier,current_user.gitea_token).call
@project.destroy!
@project.forked_projects.update_all(forked_from_project_id: nil)
# 如果该项目有所属的项目分类以及为私有项目,需要更新对应数量
@ -300,6 +313,30 @@ class ProjectsController < ApplicationController
end
def simple
if !@project.common? && @project&.repository&.mirror&.waiting?
gitea_result = $gitea_client.get_repos_by_owner_repo(@project&.owner&.login, @project&.identifier)
if !gitea_result["empty"]
@project&.update_columns(gpid: gitea_result["id"])
@project&.repository&.mirror&.succeeded!
project_id = @project&.id
user_id = @project&.owner&.id
Rails.logger.info "############ mirror project_id,user_id: #{project_id},#{user_id} ############"
OpenProjectDevOpsJob.set(wait: 5.seconds).perform_later(project_id, user_id) if project_id.present? && user_id.present?
UpdateProjectTopicJob.set(wait: 1.seconds).perform_later(project_id) if project_id.present?
Rails.logger.info "############ mirror status: #{@project&.repository&.mirror&.status} ############"
end
elsif !@project.common? && @project&.repository&.mirror&.failed?
# 导入失败的项目标记 project.status=0, 在列表中不显示
@project&.update_columns(status: 0) if @project&.status == 1
# Rails.logger.info "############ mirror status: #{@project&.repository&.mirror&.status}"
# Gitea::Repository::DeleteService.new(@project.owner, @project.identifier,current_user.gitea_token).call
# @project.destroy!
# @project.forked_projects.update_all(forked_from_project_id: nil)
# # 如果该项目有所属的项目分类以及为私有项目,需要更新对应数量
# @project.project_category.decrement!(:private_projects_count, 1) if @project.project_category.present? && !@project.is_public
# return render_error("导入失败,请重试!")
end
# 为了缓存活跃项目的基本信息,后续删除
Cache::V2::ProjectCommonService.new(@project.id).read
# 项目名称,标识,所有者变化时重置缓存
@ -376,4 +413,19 @@ class ProjectsController < ApplicationController
render_unauthorized('你还未登录.')
end
end
def close_fork_pull_requests_by(project)
open_pull_requests = PullRequest.where(fork_project_id: project.id)
if open_pull_requests.present?
open_pull_requests.each do |pull_request|
closed = PullRequests::CloseService.call(pull_request&.project.owner, pull_request&.project.repository, pull_request, current_user)
if closed === true
pull_request.project_trends.create!(user: current_user, project: pull_request&.project,action_type: ProjectTrend::CLOSE)
# 合并请求下issue处理为关闭
pull_request.issue&.update_attributes!({status_id:5})
SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, pull_request.id) if Site.has_notice_menu?
end
end
end
end
end

View File

@ -7,6 +7,7 @@ class RepositoriesController < ApplicationController
before_action :require_login, only: %i[edit update create_file update_file delete_file sync_mirror]
before_action :require_profile_completed, only: [:create_file]
before_action :load_repository
before_action :require_operate_above, only: %i[create_file update_file replace_file delete_file]
before_action :authorizate!, except: [:sync_mirror, :tags, :commit, :archive]
before_action :authorizate_user_can_edit_repo!, only: %i[sync_mirror]
before_action :get_ref, only: %i[entries sub_entries top_counts files archive]
@ -64,10 +65,9 @@ class RepositoriesController < ApplicationController
@entries = Educoder::Repository::Entries::ListService.call(@project&.project_educoder.repo_name)
else
@entries = Gitea::Repository::Entries::ListService.new(@owner, @project.identifier, ref: @ref).call
return render_not_found if @entries.is_a?(Array) && @entries.blank?
@entries = @entries.present? ? @entries.sort_by{ |hash| hash['type'] } : []
@path = GiteaService.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/"
@repo_detail = $gitea_client.get_repos_by_owner_repo(@owner.login, @project.identifier)
return render_not_found if @entries.blank? && !@repo_detail["empty"]
end
end
@ -438,4 +438,8 @@ class RepositoriesController < ApplicationController
end
end
def require_operate_above
return render_forbidden if !current_user.admin? && !@project.operator?(current_user)
end
end

View File

@ -10,7 +10,15 @@ class Users::OrganizationsController < Users::BaseController
end
@organizations = @organizations.ransack(login_cont: params[:search]).result if params[:search].present?
@organizations = @organizations.includes(:organization_extension).order("organization_extensions.#{sort_by} #{sort_direction}")
@home_top_ids = @organizations.joins(:home_top_settings).where(home_top_settings: {user_id: observed_user.id}).order("home_top_settings.created_at asc").pluck(:id)
if @home_top_ids.present?
@organizations = @organizations.joins(:organization_extension).order("FIELD(users.id, #{@home_top_ids.join(",")}) desc, organization_extensions.#{sort_by} #{sort_direction}")
else
@organizations = @organizations.joins(:organization_extension).order("organization_extensions.#{sort_by} #{sort_direction}")
end
@organizations = kaminari_paginate(@organizations)
end

View File

@ -408,7 +408,7 @@ class UsersController < ApplicationController
def projects
is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == @user.id)
scope = Projects::ListMyQuery.call(params, @user,is_current_admin_user)
scope, @home_top_ids = Projects::ListMyQuery.call(params, @user,is_current_admin_user)
@total_count = scope.size
@projects = kaminari_unlimit_paginate(scope)
end
@ -702,6 +702,15 @@ class UsersController < ApplicationController
@user = User.find_by(mail: params[:email])
end
#根据login获取用户信息
def get_user_info_by_login
private_token = "hriEn3UwXfJs3PmyXnSH"
sign = Digest::MD5.hexdigest("#{private_token}:#{params[:login]}")
tip_exception(401, '401 Unauthorized') unless params[:sign].to_s == sign
user = User.find_by_login params[:login]
render_ok(data: {username: user.real_name, school: user.custom_department, login: user.login, phone: user.phone, mail: user.mail})
end
private
def load_user
@user = User.find_by_login(params[:id]) || User.find_by(id: params[:id])
@ -731,7 +740,7 @@ class UsersController < ApplicationController
end
def sso_login
if params[:login].present? && !current_user.logged? && params[:websiteName].present?
if params[:login].present? && !current_user.logged? && params[:websiteName].present? && request.referer.to_s.include?("gitlink.org.cn")
user = User.where("login = ?", "#{params[:login].presence}").first
# 已同步注册,直接登录
if user.present?

View File

@ -1,8 +1,9 @@
class VersionReleasesController < ApplicationController
include ApplicationHelper
before_action :load_repository
before_action :set_user
before_action :require_login, except: [:index, :show]
before_action :check_release_authorize, except: [:index, :show]
before_action :require_login, except: [:index, :show, :download]
before_action :check_release_authorize, except: [:index, :show, :download]
before_action :find_version , only: [:show, :edit, :update, :destroy]
def index
@ -126,6 +127,16 @@ class VersionReleasesController < ApplicationController
end
end
def download
tip_exception(404, '您访问的页面不存在或已被删除') if params["tag_name"].blank? || params["filename"].blank?
version = @repository.version_releases.find_by(tag_name: params["tag_name"])
attachment = version.attachments.find_by(filename: params["filename"])
tip_exception(404, '您访问的页面不存在或已被删除') if attachment.blank?
send_file(absolute_path(local_path(attachment)), filename: attachment.title, stream: false, type: attachment.content_type.presence || 'application/octet-stream')
update_downloads(attachment)
# redirect_to "/api/attachments/#{attachment.uuid}"
end
private
def set_user
@ -146,7 +157,7 @@ class VersionReleasesController < ApplicationController
name: params[:name],
prerelease: params[:prerelease] || false,
tag_name: params[:tag_name],
target_commitish: params[:target_commitish] || "master" #分支
target_commitish: params[:target_commitish] || @project.default_branch #分支
}
end
@ -157,7 +168,6 @@ class VersionReleasesController < ApplicationController
attachment.container = target
attachment.author_id = current_user.id
attachment.description = ""
attachment.uuid = SecureRandom.uuid
attachment.save
end
end

View File

@ -26,6 +26,16 @@ class BaseForm
raise "项目标识已被使用." if Repository.where(user_id: user_id, identifier: repository_name.strip).exists?
end
def check_gitea_repository_name(user_id, repository_name)
user_login = User.find_by_id(user_id)&.login
begin
gitea_result = $gitea_client.get_repos_by_owner_repo(user_login, repository_name)
raise "项目标识已被使用." if gitea_result["id"].present?
rescue Gitea::Api::ServerError => e
raise "服务器错误,请联系系统管理员!" unless e.http_code.to_i == 404
end
end
def check_project_name(user_id, project_name)
raise "项目名称已被使用." if Project.where(user_id: user_id, name: project_name.strip).exists?
end

View File

@ -16,6 +16,7 @@ class Projects::CreateForm < BaseForm
check_project_language(project_language_id)
check_project_name(user_id, name) unless name.blank?
check_repository_name(user_id, repository_name) unless repository_name.blank?
# check_gitea_repository_name(user_id, repository_name) unless repository_name.blank?
check_blockchain_token_all(blockchain_token_all) unless blockchain_token_all.blank?
check_blockchain_init_token(blockchain_init_token) unless blockchain_init_token.blank?
end

View File

@ -0,0 +1,15 @@
class Projects::Datasets::CreateForm < BaseForm
attr_accessor :title, :description, :license_id, :paper_content
validates :title, presence: true, length: { maximum: 100 }
validates :description, presence: true, length: { maximum: 500 }
validates :paper_content, length: { maximum: 500 }
validate :check_license
def check_license
raise "license_id值无效. " if license_id && License.find_by(id: license_id).blank?
end
end

View File

@ -11,6 +11,7 @@ class Projects::MigrateForm < BaseForm
validate do
check_project_name(user_id, name) unless name.blank?
check_repository_name(user_id, repository_name) unless repository_name.blank?
# check_gitea_repository_name(user_id, repository_name) unless repository_name.blank?
check_project_category(project_category_id)
check_project_language(project_language_id)
check_owner

View File

@ -10,6 +10,7 @@ class Projects::UpdateForm < BaseForm
check_project_language(project_language_id)
check_repository_name(user_id, identifier) unless identifier.blank? || identifier == project_identifier
# check_gitea_repository_name(user_id, identifier) unless identifier.blank? || identifier == project_identifier
check_project_name(user_id, name) unless name.blank? || name == project_name
end

View File

@ -0,0 +1,2 @@
module Action::NodeHelper
end

View File

@ -479,7 +479,7 @@ module ApplicationHelper
return if url.blank?
content_tag(:li) do
sidebar_item(url, "数据统计", icon: 'bar-chart', controller: 'root')
sidebar_item(url, "数据统计", icon: 'bar-chart', controller: 'root', has_permission: true)
end
end

View File

@ -2,29 +2,33 @@ module ManageBackHelper
extend ActiveSupport::Concern
def sidebar_item_group(url, text, **opts)
link_opts = url.start_with?('/') ? {} : { 'data-toggle': 'collapse', 'aria-expanded': false }
content =
link_to url, link_opts do
content_tag(:i, '', class: "fa fa-#{opts[:icon]}", 'data-toggle': 'tooltip', 'data-placement': 'right', 'data-boundary': 'window', title: text) +
content_tag(:span, text)
end
if opts[:has_permission]
link_opts = url.start_with?('/') ? {} : { 'data-toggle': 'collapse', 'aria-expanded': false }
content =
link_to url, link_opts do
content_tag(:i, '', class: "fa fa-#{opts[:icon]}", 'data-toggle': 'tooltip', 'data-placement': 'right', 'data-boundary': 'window', title: text) +
content_tag(:span, text)
end
content +=
content_tag(:ul, id: url[1..-1], class: 'collapse list-unstyled', "data-parent": '#sidebar') do
yield
end
content +=
content_tag(:ul, id: url[1..-1], class: 'collapse list-unstyled', "data-parent": '#sidebar') do
yield
end
raw content
raw content
end
end
def sidebar_item(url, text, **opts)
content =
link_to url, 'data-controller': opts[:controller] do
content_tag(:i, '', class: "fa fa-#{opts[:icon]} fa-fw", 'data-toggle': 'tooltip', 'data-placement': 'right', 'data-boundary': 'window', title: text) +
content_tag(:span, text)
end
if opts[:has_permission]
content =
link_to url, 'data-controller': opts[:controller] do
content_tag(:i, '', class: "fa fa-#{opts[:icon]} fa-fw", 'data-toggle': 'tooltip', 'data-placement': 'right', 'data-boundary': 'window', title: text) +
content_tag(:span, text)
end
raw content
raw content
end
end
def admin_sidebar_controller

View File

@ -67,6 +67,8 @@ module ProjectsHelper
jianmu_devops_url: jianmu_devops_url,
cloud_ide_saas_url: cloud_ide_saas_url(user),
open_blockchain: Site.has_blockchain? && project.use_blockchain,
has_dataset: project.project_dataset.present?,
open_portrait: project.open_portrait,
ignore_id: project.ignore_id
}).compact

View File

@ -147,6 +147,7 @@ module RepositoriesHelper
ss_href = content.to_s.scan(href_regex)
ss_href_1 = content.to_s.scan(href_regex_1)
total_sources = {ss_c: ss_c,ss: ss, ss_1: ss_1, ss_2: ss_2, ss_src: ss_src, ss_src_1: ss_src_1, ss_src_2: ss_src_2, ss_src_3: ss_src_3, ss_src_4: ss_src_4, ss_src_5: ss_src_5, ss_href: ss_href, ss_href_1: ss_href_1}
puts total_sources
# total_sources.uniq!
total_sources.except(:ss, :ss_c).each do |k, sources|
sources.each do |s|
@ -157,6 +158,7 @@ module RepositoriesHelper
ext = File.extname(s_content)[1..-1]
ext = ext.split("?")[0] if ext.include?("?")
if (image_type?(ext) || download_type(ext)) && !ext.blank?
s_content = s_content.starts_with?("/") ? s_content[1..-1] : s_content[0..-1]
s_content = File.expand_path(s_content, file_path)
s_content = s_content.split("#{Rails.root}/")[1]
# content = content.gsub(s[0], "/#{s_content}")
@ -209,12 +211,14 @@ module RepositoriesHelper
end
end
after_ss_souces = content.to_s.scan(s_regex)
after_ss_souces = content.to_s.scan(s_regex)#.uniq
after_ss_souces.each_with_index do |s, index|
next if total_sources[:ss][index].nil?
content = content.gsub("#{s[0]}","#{total_sources[:ss][index][0]}")
end
after_ss_c_souces = content.to_s.scan(s_regex_c)
after_ss_c_souces = content.to_s.scan(s_regex_c)#.uniq
after_ss_c_souces.each_with_index do |s, index|
next if total_sources[:ss_c][index].nil?
content = content.gsub("#{s[0]}","#{total_sources[:ss_c][index][0]}")
end
return content

View File

@ -2,6 +2,7 @@ class CacheAsyncClearJob < ApplicationJob
queue_as :cache
def perform(type, id=nil)
return if id.nil?
case type
when "project_common_service"
Cache::V2::ProjectCommonService.new(id).clear

View File

@ -11,7 +11,7 @@ class CheckMirrorJob < ApplicationJob
unless response.present?
SyncLog.sync_log("==========check_project_error_id:#{project.id}============")
ActiveRecord::Base.transaction do
delete_gitea = Gitea::Repository::DeleteService.new(project.owner, project.identifier).call
delete_gitea = Gitea::Repository::DeleteService.new(project.owner, project.identifier, project.owner.gitea_token).call
if delete_gitea.status == 204 || delete_gitea.status == 404 #删除成功或者仓库不存在,都重新创建
repository_params= {
name: project.identifier,

View File

@ -12,7 +12,7 @@ class DailyPlatformStatisticsJob < ApplicationJob
ActiveJob::Base.logger.info "job baidu_tongji_auth access_token ===== #{access_token}"
# 从最后一个记录日期开始,如果遗漏日期数据可以补充数据
last_date = DailyPlatformStatistic.order(:date).last
start_date = last_date.date
start_date = last_date.present? ? last_date.date : 1.days.ago.beginning_of_day
end_date = Time.now
if access_token.present?
tongji_service.overview_batch_add(start_date, end_date)

View File

@ -10,7 +10,7 @@ class MigrateRemoteRepositoryJob < ApplicationJob
gitea_repository = Gitea::Repository::MigrateService.new(token, params).call
puts "#gitea_repository#{gitea_repository}"
if gitea_repository[0]==201
repo&.project&.update_columns(gpid: gitea_repository[2]["id"])
repo&.project&.update_columns(gpid: gitea_repository[2]["id"], default_branch: gitea_repository[2]["default_branch"])
repo&.mirror&.succeeded!
## open jianmu devops
project_id = repo&.project&.id
@ -19,9 +19,21 @@ class MigrateRemoteRepositoryJob < ApplicationJob
UpdateProjectTopicJob.set(wait: 1.seconds).perform_later(project_id) if project_id.present?
puts "############ mirror status: #{repo.mirror.status} ############"
else
repo&.mirror&.failed!
gitea_result = $gitea_client.get_repos_by_owner_repo(repo&.project&.owner&.login, repo&.project&.identifier)
if gitea_result["empty"]
repo&.mirror&.failed!
repo&.project&.update_columns(status: 0)
else
repo&.project&.update_columns(gpid: gitea_repository[2]["id"], default_branch: gitea_repository[2]["default_branch"])
repo&.mirror&.succeeded!
project_id = repo&.project&.id
puts "############ mirror project_id,user_id: #{project_id},#{user_id} ############"
OpenProjectDevOpsJob.set(wait: 5.seconds).perform_later(project_id, user_id) if project_id.present? && user_id.present?
UpdateProjectTopicJob.set(wait: 1.seconds).perform_later(project_id) if project_id.present?
puts "############ mirror status: #{repo.mirror.status} ############"
end
end
# UpdateProjectTopicJob 中语言要延迟1S才能获取
BroadcastMirrorRepoMsgJob.set(wait: 1.seconds).perform_later(repo.id) unless repo&.mirror.waiting?
BroadcastMirrorRepoMsgJob.set(wait: 10.seconds).perform_later(repo.id) unless repo&.mirror.waiting?
end
end

View File

@ -0,0 +1,24 @@
class TouchSyncJob < ApplicationJob
queue_as :default
def perform(touchable)
puts "aaaa"
case touchable.class.to_s
when 'SyncRepositories::Github' || 'SyncRepositories::Gitee'
Reposync::SyncRepoService.call(touchable.repo_name)
when 'SyncRepositoryBranch'
sync_repository = touchable.sync_repository
result = []
if sync_repository.sync_direction == 1
result = Reposync::SyncBranchService.call(sync_repository.repo_name, touchable.gitlink_branch_name, sync_repository.sync_direction)
else
result = Reposync::SyncBranchService.call(sync_repository.repo_name, touchable.external_branch_name, sync_repository.sync_direction)
end
if result.is_a?(Array) && result[0].to_i == 0
touchable.update_attributes!({sync_status: 1, sync_time: Time.now})
else
touchable.update_attributes!({sync_status: 2, sync_time: Time.now})
end
end
end
end

View File

@ -9,7 +9,7 @@ module CustomRegexp
URL = /\Ahttps?:\/\/[-A-Za-z0-9+&@#\/%?=~_|!:,.;]+[-A-Za-z0-9+&@#\/%=~_|]\z/
IP = /^((\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/
URL_REGEX = /\A(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\z/i
URL_REGEX = /\A(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\z/i
# REPOSITORY_NAME_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9\-\_\.]+[a-zA-Z0-9]$/ #只含有数字、字母、下划线不能以下划线开头和结尾
REPOSITORY_NAME_REGEX = /^[a-zA-Z0-9\-\_\.]+[a-zA-Z0-9]$/ #只含有数字、字母、下划线不能以下划线开头和结尾
MD_REGEX = /^.+(\.[m|M][d|D])$/

71
app/models/action/node.rb Normal file
View File

@ -0,0 +1,71 @@
# == Schema Information
#
# Table name: action_nodes
#
# id :integer not null, primary key
# name :string(255)
# full_name :string(255)
# description :string(255)
# icon :string(255)
# action_node_types_id :integer
# is_local :boolean default("0")
# local_url :string(255)
# yaml :text(65535)
# sort_no :integer default("0")
# use_count :integer default("0")
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_action_nodes_on_action_types_id (action_node_types_id)
# index_action_nodes_on_user_id (user_id)
#
class Action::Node < ApplicationRecord
self.table_name = 'action_nodes'
default_scope { order(sort_no: :asc) }
has_many :action_node_inputs, :class_name => 'Action::NodeInput', foreign_key: "action_nodes_id"
has_many :action_node_selects, :class_name => 'Action::NodeSelect', foreign_key: "action_nodes_id"
belongs_to :action_node_type, :class_name => 'Action::NodeType', foreign_key: "action_node_types_id"
belongs_to :user, optional: true
# def content_yaml
# "foo".to_yaml
# <<~YAML
# - name: Set up JDK ${{ matrix.java }}
# uses: actions/setup-java@v3
# with:
# distribution: 'temurin'
# java-version: ${{ matrix.java }}
# YAML
# end
def yaml_hash
<<~YAML
name: Check dist
on:
push:
branches:
- main
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
workflow_dispatch:
jobs:
call-check-dist:
name: Check dist/
uses: actions/reusable-workflows/.github/workflows/check-dist.yml@main
with:
node-version: '20.x'
YAML
end
end

View File

@ -0,0 +1,27 @@
# == Schema Information
#
# Table name: action_node_inputs
#
# id :integer not null, primary key
# action_nodes_id :integer
# name :string(255)
# input_type :string(255)
# description :string(255)
# is_required :boolean default("0")
# sort_no :string(255) default("0")
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_action_node_inputs_on_action_nodes_id (action_nodes_id)
# index_action_node_inputs_on_user_id (user_id)
#
class Action::NodeInput < ApplicationRecord
self.table_name = 'action_node_inputs'
default_scope { order(sort_no: :asc) }
belongs_to :action_node, :class_name => 'Action::Node', foreign_key: "action_nodes_id"
end

View File

@ -0,0 +1,39 @@
# == Schema Information
#
# Table name: action_node_selects
#
# id :integer not null, primary key
# action_nodes_id :integer
# name :string(255)
# val :string(255)
# val_ext :string(255)
# description :string(255)
# download_url :string(255)
# sort_no :integer default("0")
# use_count :integer default("0")
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_action_node_selects_on_action_nodes_id (action_nodes_id)
# index_action_node_selects_on_name (name)
# index_action_node_selects_on_user_id (user_id)
#
class Action::NodeSelect < ApplicationRecord
self.table_name = 'action_node_selects'
default_scope { order(sort_no: :asc) }
belongs_to :action_node, :class_name => 'Action::Node', foreign_key: "action_nodes_id"
belongs_to :user, optional: true
def value
if self.val_ext.blank?
self.val
else
"#{self.val}@#{self.val_ext}"
end
end
end

View File

@ -0,0 +1,18 @@
# == Schema Information
#
# Table name: action_node_types
#
# id :integer not null, primary key
# name :string(255)
# description :string(255)
# sort_no :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Action::NodeType < ApplicationRecord
self.table_name = 'action_node_types'
default_scope { order(sort_no: :asc) }
has_many :action_nodes, :class_name => 'Action::Node', foreign_key: "action_node_types_id"
end

View File

@ -0,0 +1,20 @@
# == Schema Information
#
# Table name: action_templates
#
# id :integer not null, primary key
# name :string(255)
# description :string(255)
# img :string(255)
# sort_no :string(255) default("0")
# json :text(65535)
# yaml :text(65535)
# created_at :datetime not null
# updated_at :datetime not null
#
class Action::Template < ApplicationRecord
self.table_name = 'action_templates'
default_scope { order(sort_no: :asc) }
end

View File

@ -1,45 +1,45 @@
# == Schema Information
#
# Table name: attachments
#
# id :integer not null, primary key
# container_id :integer
# container_type :string(30)
# filename :string(255) default(""), not null
# disk_filename :string(255) default(""), not null
# filesize :integer default("0"), not null
# content_type :string(255) default("")
# digest :string(60) default(""), not null
# downloads :integer default("0"), not null
# author_id :integer default("0"), not null
# created_on :datetime
# description :text(65535)
# disk_directory :string(255)
# attachtype :integer default("1")
# is_public :integer default("1")
# copy_from :integer
# quotes :integer default("0")
# is_publish :integer default("1")
# publish_time :datetime
# resource_bank_id :integer
# unified_setting :boolean default("1")
# cloud_url :string(255) default("")
# course_second_category_id :integer default("0")
# delay_publish :boolean default("0")
# memo_image :boolean default("0")
# extra_type :integer default("0")
# uuid :string(255)
#
# Indexes
#
# index_attachments_on_author_id (author_id)
# index_attachments_on_container_id_and_container_type (container_id,container_type)
# index_attachments_on_course_second_category_id (course_second_category_id)
# index_attachments_on_created_on (created_on)
# index_attachments_on_is_public (is_public)
# index_attachments_on_quotes (quotes)
#
# == Schema Information
#
# Table name: attachments
#
# id :integer not null, primary key
# container_id :integer
# container_type :string(30)
# filename :string(255) default(""), not null
# disk_filename :string(255) default(""), not null
# filesize :integer default("0"), not null
# content_type :string(255) default("")
# digest :string(60) default(""), not null
# downloads :integer default("0"), not null
# author_id :integer default("0"), not null
# created_on :datetime
# description :text(65535)
# disk_directory :string(255)
# attachtype :integer default("1")
# is_public :integer default("1")
# copy_from :integer
# quotes :integer default("0")
# is_publish :integer default("1")
# publish_time :datetime
# resource_bank_id :integer
# unified_setting :boolean default("1")
# cloud_url :string(255) default("")
# course_second_category_id :integer default("0")
# delay_publish :boolean default("0")
# memo_image :boolean default("0")
# extra_type :integer default("0")
# uuid :string(255)
#
# Indexes
#
# index_attachments_on_author_id (author_id)
# index_attachments_on_container_id_and_container_type (container_id,container_type)
# index_attachments_on_course_second_category_id (course_second_category_id)
# index_attachments_on_created_on (created_on)
# index_attachments_on_is_public (is_public)
# index_attachments_on_quotes (quotes)
#
@ -72,7 +72,7 @@ class Attachment < ApplicationRecord
scope :unified_setting, -> {where("unified_setting = ? ", 1)}
scope :where_id_or_uuid, -> (id) { (Float(id) rescue nil).present? ? where(id: id) : where(uuid: id) }
validates_length_of :description, maximum: 100, message: "不能超过100个字符"
validates_length_of :description, maximum: 255, message: "不能超过255个字符"
DCODES = %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)

View File

@ -7,6 +7,7 @@ module Matchable
scope :with_project_type, ->(project_type) { where(project_type: project_type) if Project.project_types.include?(project_type) }
scope :by_name_or_identifier, ->(search) { where("name like :search or identifier LIKE :search", :search => "%#{search.split(" ").join('|')}%") unless search.blank? }
scope :with_project_topic, ->(topic_id) {joins(:project_topics).where(project_topics: {id: topic_id}) unless topic_id.blank?}
scope :with_project_topic_name, ->(topic_name) {joins(:project_topics).where(project_topics: {name: topic_name}) unless topic_name.blank?}
end
end

View File

@ -0,0 +1,21 @@
# == Schema Information
#
# Table name: gitlink_competition_applies
#
# id :integer not null, primary key
# competition_id :integer
# competition_identifier :string(255)
# team_id :integer
# team_name :string(255)
# school_name :string(255)
# login :string(255)
# nickname :string(255)
# phone :string(255)
# identity :string(255)
# role :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class GitlinkCompetitionApply < ApplicationRecord
end

View File

@ -0,0 +1,23 @@
# == Schema Information
#
# Table name: home_top_settings
#
# id :integer not null, primary key
# user_id :integer
# top_type :string(255)
# top_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_home_top_settings_on_top_type_and_top_id (top_type,top_id)
# index_home_top_settings_on_user_id (user_id)
#
class HomeTopSetting < ApplicationRecord
belongs_to :user
belongs_to :top, polymorphic: true
end

View File

@ -7,10 +7,12 @@
# content :text(65535)
# created_at :datetime not null
# updated_at :datetime not null
# is_secret :boolean default("0")
# position :integer default("0")
#
class License < ApplicationRecord
default_scope { order(position: :desc) }
include Projectable
validates :name, :content, presence: true

View File

@ -76,6 +76,7 @@ class Organization < Owner
has_many :team_users, dependent: :destroy
has_many :pinned_projects, class_name: 'PinnedProject', foreign_key: :user_id, dependent: :destroy
has_many :is_pinned_projects, through: :pinned_projects, source: :project, validate: false
has_many :home_top_settings, as: :top, dependent: :destroy
validates :login, presence: true
validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, case_sensitive: false
@ -216,4 +217,9 @@ class Organization < Owner
ids.uniq.size
end
# user容错处理
def get_letter_avatar_url
""
end
end

View File

@ -28,7 +28,7 @@ class Page < ApplicationRecord
belongs_to :project
# language_frame 前端语言框架
enum language_frame: { hugo: 0, jekyll: 1, hexo: 2}
enum language_frame: { hugo: 0, jekyll: 1, hexo: 2, files: 3}
after_create do
PageService.genernate_user(user_id)

View File

@ -13,7 +13,7 @@
#
class PageTheme < ApplicationRecord
enum language_frame: { hugo: 0, jeklly: 1, hexo: 2}
enum language_frame: { hugo: 0, jeklly: 1, hexo: 2, files:3}
validates :name, presence: {message: "主题名不能为空"}, uniqueness: {message: "主题名已存在",scope: :language_frame},length: {maximum: 255}
def image

View File

@ -55,14 +55,13 @@
# default_branch :string(255) default("master")
# website :string(255)
# lesson_url :string(255)
# use_blockchain :boolean default("0")
# is_pinned :boolean default("0")
# recommend_index :integer default("0")
# use_blockchain :boolean default("0")
# pr_view_admin :boolean default("0")
#
# Indexes
#
# index_projects_on_forked_count (forked_count)
# index_projects_on_forked_from_project_id (forked_from_project_id)
# index_projects_on_identifier (identifier)
# index_projects_on_invite_code (invite_code)
@ -72,7 +71,6 @@
# index_projects_on_license_id (license_id)
# index_projects_on_name (name)
# index_projects_on_platform (platform)
# index_projects_on_praises_count (praises_count)
# index_projects_on_project_category_id (project_category_id)
# index_projects_on_project_language_id (project_language_id)
# index_projects_on_project_type (project_type)
@ -80,7 +78,6 @@
# index_projects_on_rgt (rgt)
# index_projects_on_status (status)
# index_projects_on_updated_on (updated_on)
# index_projects_on_user_id (user_id)
#
class Project < ApplicationRecord
@ -90,6 +87,8 @@ class Project < ApplicationRecord
include ProjectOperable
include Dcodes
default_scope {where.not(id: 0)}
# common:开源托管项目
# mirror:普通镜像项目,没有定时同步功能
# sync_mirror:同步镜像项目,有系统定时同步功能,且用户可手动同步操作
@ -137,6 +136,9 @@ class Project < ApplicationRecord
has_many :project_topics, through: :project_topic_ralates
has_many :commit_logs, dependent: :destroy
has_many :daily_project_statistics, dependent: :destroy
has_one :project_dataset, dependent: :destroy
has_many :sync_repositories, dependent: :destroy
has_many :home_top_settings, as: :top, dependent: :destroy
after_create :incre_user_statistic, :incre_platform_statistic
after_save :check_project_members
before_save :set_invite_code, :reset_unmember_followed, :set_recommend_and_is_pinned, :reset_cache_data
@ -180,14 +182,14 @@ class Project < ApplicationRecord
end
if changes[:is_public].present?
if changes[:is_public][0] && !changes[:is_public][1]
CacheAsyncClearJob.perform_later('project_rank_service', self.id)
CacheAsyncClearJob.set(wait: 5.seconds).perform_later('project_rank_service', self.id)
end
if !changes[:is_public][0] && changes[:is_public][1]
$redis_cache.srem("v2-project-rank-deleted", self.id)
end
end
if !self.common?
CacheAsyncClearJob.perform_later('project_rank_service', self.id)
CacheAsyncClearJob.set(wait: 5.seconds).perform_later('project_rank_service', self.id)
end
end
@ -456,6 +458,19 @@ class Project < ApplicationRecord
$redis_cache.hdel("issue_cache_delete_count", self.id)
end
def open_portrait
EduSetting.get("open_portrait_projects").present? ? EduSetting.get("open_portrait_projects").split(",").include?(self.id.to_s) : false
end
def has_pull_request(branch_name)
return true if self.pull_requests.opening.where(head: branch_name).present? || self.pull_requests.opening.where(base: branch_name).present?
if self.forked_from_project_id.present?
return true if self.fork_project.pull_requests.opening.where(head: branch_name).present? || self.fork_project.pull_requests.opening.where(base: branch_name).present?
end
return false
end
def self.mindspore_contributors
cache_result = $redis_cache.get("ProjectMindsporeContributors")
if cache_result.nil?

View File

@ -0,0 +1,26 @@
# == Schema Information
#
# Table name: project_datasets
#
# id :integer not null, primary key
# title :string(255)
# description :text(65535)
# project_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# license_id :integer
# paper_content :text(65535)
#
# Indexes
#
# index_project_datasets_on_license_id (license_id)
# index_project_datasets_on_project_id (project_id)
#
class ProjectDataset < ApplicationRecord
belongs_to :project
belongs_to :license, optional: true
has_many :attachments, as: :container, dependent: :destroy
end

View File

@ -17,12 +17,13 @@ class ProjectUnit < ApplicationRecord
belongs_to :project
enum unit_type: {code: 1, issues: 2, pulls: 3, wiki:4, devops: 5, versions: 6, resources: 7, services: 8}
enum unit_type: {code: 1, issues: 2, pulls: 3, wiki:4, devops: 5, versions: 6, resources: 7, services: 8, dataset: 9}
validates :unit_type, uniqueness: { scope: :project_id}
def self.init_types(project_id, project_type='common')
unit_types = project_type == 'sync_mirror' ? ProjectUnit::unit_types.except("pulls") : ProjectUnit::unit_types
unit_types = unit_types.except("dataset")
unit_types.each do |_, v|
self.create!(project_id: project_id, unit_type: v)
end

View File

@ -2,25 +2,27 @@
#
# Table name: pull_requests
#
# id :integer not null, primary key
# gitea_id :integer
# gitea_number :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# status :integer default("0")
# project_id :integer
# title :string(255)
# milestone :integer
# body :text(4294967295)
# head :string(255)
# base :string(255)
# issue_id :integer
# fork_project_id :integer
# is_original :boolean default("0")
# comments_count :integer default("0")
# commits_count :integer default("0")
# files_count :integer default("0")
# id :integer not null, primary key
# gitea_id :integer
# gitea_number :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# status :integer default("0")
# project_id :integer
# title :string(255)
# milestone :integer
# body :text(4294967295)
# head :string(255)
# base :string(255)
# issue_id :integer
# fork_project_id :integer
# is_original :boolean default("0")
# comments_count :integer default("0")
# commits_count :integer default("0")
# files_count :integer default("0")
# fork_project_owner :string(255)
# fork_project_identifier :string(255)
#
class PullRequest < ApplicationRecord

View File

@ -0,0 +1,22 @@
# == Schema Information
#
# Table name: sync_repositories
#
# id :integer not null, primary key
# project_id :integer
# type :string(255)
# repo_name :string(255)
# external_repo_address :string(255)
# sync_granularity :integer
# sync_direction :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_sync_repositories_on_project_id (project_id)
#
class SyncRepositories::Gitee < SyncRepository
end

View File

@ -0,0 +1,21 @@
# == Schema Information
#
# Table name: sync_repositories
#
# id :integer not null, primary key
# project_id :integer
# type :string(255)
# repo_name :string(255)
# external_repo_address :string(255)
# sync_granularity :integer
# sync_direction :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_sync_repositories_on_project_id (project_id)
#
class SyncRepositories::Github < SyncRepository
end

View File

@ -0,0 +1,35 @@
# == Schema Information
#
# Table name: sync_repositories
#
# id :integer not null, primary key
# project_id :integer
# type :string(255)
# repo_name :string(255)
# external_repo_address :string(255)
# sync_granularity :integer
# sync_direction :integer
# created_at :datetime not null
# updated_at :datetime not null
# external_token :string(255)
# webhook_gid :integer
#
# Indexes
#
# index_sync_repositories_on_project_id (project_id)
#
class SyncRepository < ApplicationRecord
belongs_to :project
has_many :sync_repository_branches, dependent: :destroy
before_destroy :unbind_reposyncer
validates :repo_name, uniqueness: { message: "已存在" }
def unbind_reposyncer
Reposync::DeleteRepoService.call(self.repo_name) rescue nil
end
end

View File

@ -0,0 +1,38 @@
# == Schema Information
#
# Table name: sync_repository_branches
#
# id :integer not null, primary key
# sync_repository_id :integer
# gitlink_branch_name :string(255)
# external_branch_name :string(255)
# sync_time :datetime
# sync_status :integer default("0")
# reposync_branch_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# enable :boolean default("1")
#
# Indexes
#
# index_sync_repository_branches_on_sync_repository_id (sync_repository_id)
#
class SyncRepositoryBranch < ApplicationRecord
belongs_to :sync_repository
before_destroy :unbind_reposyncer
enum sync_status: {success: 1, failure: 2}
def unbind_reposyncer
if self.sync_repository.sync_direction.to_i == 1
Reposync::DeleteBranchService.call(self.sync_repository&.repo_name, self.gitlink_branch_name) rescue nil
else
Reposync::DeleteBranchService.call(self.sync_repository&.repo_name, self.external_branch_name) rescue nil
end
end
end

View File

@ -190,6 +190,7 @@ class User < Owner
has_many :clas, through: :user_clas
has_one :page, :dependent => :destroy
has_many :home_top_settings, dependent: :destroy
# Groups and active users
scope :active, lambda { where(status: [STATUS_ACTIVE, STATUS_EDIT_INFO]) }
@ -833,7 +834,11 @@ class User < Owner
end
def admin_or_business?
admin? || business?
admin? || business?
end
def admin_or_glcc_admin?
admin? || glcc_admin?
end
def self.generate_login(prefix)

View File

@ -13,11 +13,8 @@ class Admins::GlccExamineMaterial < ApplicationQuery
materials = GlccMediumTermExamineMaterial.all
# term
term = params[:term] || [1,2]
if term.present?
materials = materials.where(term: term)
end
#year
materials = materials.where(term: params[:term]) if params[:term].present?
#year
year = if params[:date]
params[:date][:year]
end

View File

@ -20,11 +20,11 @@ class Projects::ListMyQuery < ApplicationQuery
if params[:category].blank?
normal_projects = projects.members_projects(user.id).to_sql
org_projects = projects.joins(team_projects: [team: :team_users]).where(team_users: {user_id: user.id}).to_sql
projects = Project.from("( #{ normal_projects} UNION #{ org_projects } ) AS projects").distinct
projects = Project.from("( #{ normal_projects} UNION #{ org_projects } ) AS projects")#.distinct
elsif params[:category].to_s == "join"
normal_projects = projects.where.not(user_id: user.id).members_projects(user.id).to_sql
org_projects = projects.joins(team_projects: [team: :team_users]).where(team_users: {user_id: user.id}).to_sql
projects = Project.from("( #{ normal_projects} UNION #{ org_projects } ) AS projects").distinct
projects = Project.from("( #{ normal_projects} UNION #{ org_projects } ) AS projects")#.distinct
elsif params[:category].to_s == "manage"
projects = projects.where(user_id: user.id)
elsif params[:category].to_s == "watched" #我关注的
@ -37,7 +37,7 @@ class Projects::ListMyQuery < ApplicationQuery
elsif params[:category].to_s == "admin"
normal_projects = projects.joins(members: :roles).where(members: {user_id: user.id}, roles: {name: %w(Manager)}).to_sql
org_projects = projects.joins(team_projects: [team: :team_users]).where(teams: {authorize: %w(owner admin)},team_users: {user_id: user.id}).to_sql
projects = Project.from("( #{ normal_projects} UNION #{ org_projects } ) AS projects").distinct
projects = Project.from("( #{ normal_projects} UNION #{ org_projects } ) AS projects")#.distinct
# elsif params[:category].to_s == "public"
# projects = projects.visible.joins(:members).where(members: { user_id: user.id })
# elsif params[:category].to_s == "private"
@ -71,11 +71,19 @@ class Projects::ListMyQuery < ApplicationQuery
sort = Project.column_names.include?(params[:sort_by]) ? params[:sort_by] : "updated_on"
sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : "desc"
@home_top_ids = scope.joins(:home_top_settings).where(home_top_settings: {user_id: user.id}).order("home_top_settings.created_at asc").pluck(:id)
if params[:choosed].present? && params[:choosed].is_a?(Array)
scope.order("FIELD(id, #{params[:choosed].reverse.join(",")}) desc")
scope = scope.distinct.order("FIELD(projects.id, #{params[:choosed].reverse.join(",")}) desc")
else
scope.order("projects.#{sort} #{sort_direction}")
if @home_top_ids.present?
scope = scope.distinct.order("FIELD(projects.id, #{@home_top_ids.join(",")}) desc, projects.#{sort} #{sort_direction}")
else
scope = scope.distinct.order("projects.#{sort} #{sort_direction}")
end
end
return scope, @home_top_ids
end
end

Some files were not shown because too many files have changed in this diff Show More