Compare commits

..

49 Commits

Author SHA1 Message Date
xxq250 d5b2acfe63 Merge pull request '20231011版本' (#341) from Trustie/forgeplus:dev_local_v1 into dev_local_v1 2023-10-11 16:09:24 +08:00
xxq250 29ea3dda26 merge dev_local 2023-10-11 16:06:27 +08:00
xxq250 111b91584d Merge branch 'standalone_develop' into dev_local_v1
# Conflicts:
#	app/controllers/projects_controller.rb
#	app/jobs/migrate_remote_repository_job.rb
#	public/assets/.sprockets-manifest-dd73942813e820b803d35c9915c0bb25.json
#	public/assets/admin-5a48f49881bac9e22c837c20db22ea3b51b424751ddb12208a3b422b752e60fd.js
#	public/assets/admin-5a48f49881bac9e22c837c20db22ea3b51b424751ddb12208a3b422b752e60fd.js.gz
#	public/assets/admin-a7edfa013f5e822c43ac1a1f813c1929ff7aa9e12cd1313f9e1b7292fa406470.css.gz
2023-10-11 15:57:09 +08:00
xxq250 13ebcca249 整理sql 2023-09-06 16:05:12 +08:00
xxq250 a37191350d fixed 表检测 2023-09-06 11:27:46 +08:00
xxq250 b7cea34760 utf8mb4 2023-09-06 11:17:09 +08:00
xxq250 7844f65466 ssl_mode取消 2023-09-06 11:16:48 +08:00
xxq250 8909ad2ba8 404状态码测试页面xml 2023-08-30 09:31:21 +08:00
xxq250 6bc0587168 404状态码测试页面 2023-08-30 09:31:20 +08:00
xxq250 7a82d93c85 gem版本整理 2023-08-16 15:30:24 +08:00
xxq250 d13ac9e9fe 部署调整去掉ssl_mode 2023-07-20 09:18:07 +08:00
xxq250 253196e000 部署说明调整 2023-07-18 15:46:45 +08:00
xxq250 4d751e6b3e 前端文件更新 2023-07-18 15:29:04 +08:00
xxq250 755fff03a1 fix 本地版调整 2023-07-18 15:15:05 +08:00
xxq250 a117f0bf73 gitea admin 2023-06-26 18:32:50 +08:00
xxq250 7176d3d2d5 开启redis缓存 2023-06-14 14:43:45 +08:00
xxq250 8874898ff3 Merge pull request '整理docker打包' (#336) from docker into dev_local_v1 2023-06-14 14:42:26 +08:00
xxq250 9e814ee16a Merge pull request '细化' (#335) from Trustie/forgeplus:dev_local_v1 into dev_local_v1 2023-06-14 14:14:42 +08:00
xxq250 fe47840e53 init Gemfile.lock 2023-06-01 14:53:12 +08:00
xxqfamous afecd95947 gemfile 2023-05-31 14:30:26 +08:00
xxq250 2ec14f6665 Delete 'Gemfile.lock' 2023-05-31 14:28:15 +08:00
xxqfamous 1c7e74ed1d gitea admin 禁用 2023-05-29 18:41:20 +08:00
xxqfamous 0a6957f193 gitea文件位置变化 2023-05-29 18:40:32 +08:00
xxqfamous 4bd3d98021 整理初始菜单sql 2023-05-29 18:18:00 +08:00
xxqfamous 14df764275 整理初始菜单sql 2023-05-29 17:16:50 +08:00
xxqfamous 24be0501b7 docker部署整理-gitea更新小镜像 2023-05-29 16:53:58 +08:00
xxqfamous b45fb35ea1 docker部署整理-gitea环境变量 2023-05-29 16:50:24 +08:00
xxqfamous 3646822ec3 docker部署整理 ssl禁用 2023-05-25 18:35:19 +08:00
xxqfamous 9d5609e544 docker部署整理 ssl禁用 2023-05-25 18:30:12 +08:00
xxqfamous 3f9a3aacfa docker部署整理 ssl禁用 2023-05-25 17:45:03 +08:00
xxqfamous 38458764b4 docker部署整理 启动 2023-05-25 14:06:44 +08:00
xxqfamous dd94480486 docker部署整理 启动 2023-05-25 13:58:24 +08:00
xxqfamous 3dd62f40df docker部署整理 启动 2023-05-25 11:33:29 +08:00
xxqfamous a0f13e3a0c docker部署整理 log目录 2023-05-25 11:19:40 +08:00
xxqfamous 600235effa docker部署整理 gem 2023-05-25 11:06:03 +08:00
xxqfamous 7578fb9e0a docker部署整理 2023-05-25 10:59:24 +08:00
xxqfamous c8a356b836 docker部署整理 2023-05-25 10:24:51 +08:00
xxqfamous eb38b3fda4 docker部署整理 2023-05-24 18:28:12 +08:00
xxqfamous 2c5c03f77c docker部署整理 2023-05-24 17:50:26 +08:00
xxq250 67f3a87afc fixed 审批utf8mb4 2023-05-18 09:37:16 +08:00
xxq250 b5553e2c97 fixed js zip 2023-05-16 20:51:27 +08:00
xxq250 a542b02181 fixed js zip 2023-05-16 20:44:11 +08:00
xxq250 b7786fc870 fixed js zip 2023-05-16 20:07:01 +08:00
xxq250 31f44685d9 fixed emj 2023-05-16 09:55:59 +08:00
xxq250 41e6d6ab09 fixed 用户项目包含私有 2023-05-16 09:20:00 +08:00
xxq250 d24703be75 完善资料去掉 2023-05-12 15:20:14 +08:00
xxq250 487d548e9f 本地版去掉触发的“引擎”相关通知 2023-05-12 10:11:56 +08:00
xxq250 07696682ca 本地版去掉三方登录 2023-05-12 10:06:40 +08:00
xxq250 c64f241cf8 本地版取消验证码 2023-05-08 15:55:54 +08:00
1449 changed files with 74029 additions and 103187 deletions

5
.gitignore vendored
View File

@ -10,7 +10,7 @@
# Ignore lock config file
*.log
.env
# mac
*.DS_Store
.bashrc
@ -84,5 +84,4 @@ redis_data/
dump.rdb
.tags*
ceshi_user.xlsx
public/trace_task_results
public/项目活跃度排行.xls
public/trace_task_results

View File

@ -1,59 +1,29 @@
FROM ubuntu:20.04
RUN apt-get update
FROM registry.cn-hangzhou.aliyuncs.com/gitlink/ruby:2.4.5
ADD ./ /home/pdl/gitlink
WORKDIR /home/pdl/gitlink
RUN DEBIAN_FRONTEND=noninteractive apt install -y tzdata
# basics
RUN apt-get install -y libssl-dev curl libmysqlclient-dev imagemagick nodejs mysql-server redis-server
RUN ln -fs /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
# confirm openssl version
RUN openssl version
RUN which openssl
# install RVM, Ruby, and Bundler
RUN \curl -L https://get.rvm.io | bash -s stable
# rvm environment variable
RUN /bin/bash -l -c "source /etc/profile.d/rvm.sh"
RUN /bin/bash -l -c "rvm requirements"
# replace ruby mirror url, accelerate install ruby
RUN sed -i 's/rvm_remote_server_url2/#rvm_remote_server_url2/g' /usr/local/rvm/config/db
RUN sed -i 's/cache.ruby-lang.org/cache.ruby-china.com/g' /usr/local/rvm/config/db
# install ruby
RUN /bin/bash -l -c "rvm install 2.4.5"
# confirm ruby version
RUN /bin/bash -l -c "rvm list"
RUN /bin/bash -l -c "ruby -v"
#RUN apt-get install -y nodejs
WORKDIR /home/app/gitlink
ADD ./ /home/app/gitlink
RUN cd /home/app/gitlink
RUN /bin/bash -l -c 'gem sources --add https://gems.ruby-china.com/ --remove https://rubygems.org/'
RUN /bin/bash -l -c 'gem update --system'
RUN /bin/bash -l -c 'gem install bundler -v 2.3.26'
RUN /bin/bash -l -c 'gem install rake'
RUN /bin/bash -l -c 'gem install puma -v 5.6.5'
RUN rm -rf Gemfile.lock
RUN cp config/configuration.yml.example config/configuration.yml
RUN cp config/database-docker.yml.example config/database.yml
RUN cp config/database.yml.example config/database.yml
RUN cp config/environments/production.rb.example config/environments/production.rb
RUN cp config/secrets.yml.example config/secrets.yml
RUN touch config/redis.yml
RUN touch config/elasticsearch.yml
RUN mkdir log
RUN /bin/bash -l -c 'bundle install'
#RUN /bin/bash -l -c 'RAILS_ENV=production rails db:create'
#RUN /bin/bash -l -c 'RAILS_ENV=production bundle exec rake sync_table_structure:import_csv'
#RUN /bin/bash -l -c 'RAILS_ENV=production rails db:migrate'
RUN redis-server &
RUN /bin/bash -l -c 'bundle exec rake sync_table_structure:import_csv'
RUN /bin/bash -l -c 'rails db:migrate RAILS_ENV=development'
RUN /bin/bash -l -c 'bundle exec sidekiq -C config/sidekiq.yml -e production -d'
EXPOSE 4000
RUN /bin/bash -l -c 'RAILS_ENV=production puma -C config/puma.rb'
#EXPOSE 4000
#RUN /bin/bash -l -c 'RAILS_ENV=production puma'

View File

@ -20,6 +20,8 @@ gem 'bootsnap', '>= 1.1.0', require: false
gem 'chinese_pinyin'
gem 'loofah','~> 2.20.0'
gem 'rack-cors'
gem 'redis-rails'
gem 'roo-xls'
@ -141,4 +143,4 @@ gem 'doorkeeper'
gem 'doorkeeper-jwt'
gem 'gitea-client', '~> 1.5.8'
gem 'gitea-client', '~> 1.4.2'

View File

@ -245,12 +245,13 @@ GEM
powerpack (0.1.2)
prettier (0.18.2)
public_suffix (4.0.3)
puma (5.6.5)
nio4r (~> 2.0)
puma (3.12.2)
raabro (1.4.0)
rack (2.0.9)
rack-cors (1.1.1)
rack (>= 2.0.0)
rack-mini-profiler (2.0.1)
rack (>= 1.2.0)
rack-protection (2.0.8.1)
rack
rack-test (1.1.0)
@ -513,8 +514,9 @@ DEPENDENCIES
parallel (~> 1.19, >= 1.19.1)
pdfkit
prettier
puma (~> 5.6.5)
puma (~> 3.11)
rack-cors
rack-mini-profiler
rails (~> 5.2.0)
rails-i18n (~> 5.1)
ransack
@ -536,7 +538,7 @@ DEPENDENCIES
sidekiq-cron (= 1.2.0)
sidekiq-failures
simple_form
simple_xlsx_reader (~> 1.0.4)
simple_xlsx_reader
sinatra
solargraph (~> 0.38.0)
spreadsheet

View File

@ -3,8 +3,7 @@
GitLink确实开源是中国计算机学会CCF官方指定的开源创新服务平台旨在以“为开源创新服务”为使命以“成为开源创新的汇聚地”为愿景秉承“创新、开放、协作、共享”的价值观致力于为大规模开源开放协同创新助力赋能打造创新成果孵化和新工科人才培养的开源创新生态
<center>
<img src="docs/figs/gitlink.png" width=80% /></center>
<img src="https://code.gitlink.org.cn/young/forgeplus/raw/branch/master/docs/figs/gitlink.png?raw=true" width=80% /></center>
## 特色功能
@ -175,31 +174,31 @@ http://localhost:3000/
- 项目列表
<center>
<img src="docs/figs/project_list.png" width=80% />
<img src="https://code.gitlink.org.cn/young/forgeplus/raw/branch/master/docs/figs/project_list.png?raw=true" width=50% />
</center>
- 代码仓库
<center>
<img src="docs/figs/repo.png" width=80% />
<img src="https://code.gitlink.org.cn/young/forgeplus/raw/branch/master/docs/figs/repo.png?raw=true" width=50% />
</center>
- 任务管理
<center>
<img src="docs/figs/issues.png" width=80% />
<img src="https://code.gitlink.org.cn/young/forgeplus/raw/branch/master/docs/figs/issues.png?raw=true" width=50% />
</center>
- 合并请求
<center>
<img src="docs/figs/PR.png" width=80% />
<img src="https://code.gitlink.org.cn/young/forgeplus/raw/branch/master/docs/figs/PR.png?raw=true" width=50% />
</center>
- 引擎配置
<center>
<img src="docs/figs/engine.png" width=80% />
<img src="https://code.gitlink.org.cn/young/forgeplus/raw/branch/master/docs/figs/engine.png?raw=true" width=50% />
</center>

View File

@ -24,7 +24,7 @@
//= require codemirror/mode/shell/shell
//= require editormd/editormd
//= require editormd/languages/zh-tw
//= require dragula/dragula
//= require_tree ./i18n
//= require_tree ./admins

View File

@ -201,12 +201,12 @@ class AccountsController < ApplicationController
return normal_status(-2, "违反平台使用规范,账号已被锁定") if @user.locked?
login_control = LimitForbidControl::UserLogin.new(@user)
return normal_status(-2, "登录密码出错已达上限,账号已被锁定#{login_control.forbid_expires/60}分钟后重新登录或找回密码") if login_control.forbid?
return normal_status(-2, "登录密码出错已达上限,账号已被锁定, #{login_control.forbid_expires/60}分钟后重新登录或找回密码") if login_control.forbid?
password_ok = @user.check_password?(params[:password].to_s)
unless password_ok
if login_control.remain_times-1 == 0
normal_status(-2, "登录密码出错已达上限,账号已被锁定#{login_control.forbid_expires/60}分钟后重新登录或找回密码")
normal_status(-2, "登录密码出错已达上限,账号已被锁定, #{login_control.forbid_expires/60}分钟后重新登录或找回密码")
else
normal_status(-2, "你已经输错密码#{login_control.error_times+1}次,还剩余#{login_control.remain_times-1}次机会")
end
@ -222,7 +222,6 @@ class AccountsController < ApplicationController
end
def change_password
return render_error("两次输入的密码不一致") if params[:password].to_s != params[:new_password_repeat].to_s
@user = User.find_by(login: params[:login])
return render_error("此用户禁止修改密码!") if @user.id.to_i === 104691
return render_error("未找到相关用户!") if @user.blank?

View File

@ -1,75 +0,0 @@
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

@ -1,76 +0,0 @@
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

@ -1,64 +0,0 @@
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

@ -1,69 +0,0 @@
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

@ -1,68 +0,0 @@
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,23 +23,10 @@ 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,13 +1,9 @@
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).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)
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
@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
@ -22,78 +18,16 @@ 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).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
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
@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
end
@month_active_project_count = Rails.cache.fetch("dashboardscontroller:month_active_project_count", expires_in: 1.hours) do
Project.where(updated_on: current_month).or(Project.where(id: month_project_ids)).count
end
@weekly_active_project_count = Project.where(updated_on: current_week).or(Project.where(id: weekly_project_ids)).count
@month_active_project_count = Project.where(updated_on: current_month).or(Project.where(id: month_project_ids)).count
# 新增项目数
@day_new_project_count = Rails.cache.fetch("dashboardscontroller:day_new_project_count", expires_in: 10.minutes) do
Project.where(created_on: today).count
end
@weekly_new_project_count = Rails.cache.fetch("dashboardscontroller:weekly_new_project_count", expires_in: 10.minutes) do
Project.where(created_on: current_week).count
end
@month_new_project_count = Rails.cache.fetch("dashboardscontroller:month_new_project_count", expires_in: 1.hours) do
Project.where(created_on: current_month).count
end
# 总的平台用户数
# 总的平台项目数
# 总的平台组织数
# 总的平台Issue数、评论数、PR数、Commit数
@user_count = Rails.cache.fetch("dashboardscontroller:platform:user_count", expires_in: 1.days) do
User.count
end
@project_count = Rails.cache.fetch("dashboardscontroller:platform:project_count", expires_in: 1.days) do
Project.count
end
@organization_count = Rails.cache.fetch("dashboardscontroller:platform:organization_count", expires_in: 1.days) do
Organization.count
end
@issue_count = Rails.cache.fetch("dashboardscontroller:platform:issue_count", expires_in: 1.days) do
Issue.count
end
@comment_count = Rails.cache.fetch("dashboardscontroller:platform:comment_count", expires_in: 1.days) do
Journal.count
end
@pr_count = Rails.cache.fetch("dashboardscontroller:platform:pr_count", expires_in: 1.days) do
PullRequest.count
end
@commit_count = Rails.cache.fetch("dashboardscontroller:platform:commit_count", expires_in: 1.days) do
CommitLog.count
end
@subject_name = ["用户数", "项目数", "组织数", "Issue数", "Issue评论数", "PR数", "Commit数"]
@subject_icon = ["fa-user","fa-git", "fa-sitemap", "fa-warning", "fa-comments", "fa-share-alt", "fa-upload"]
@subject_data = [@user_count, @project_count, @organization_count, @issue_count, @comment_count, @pr_count, @commit_count]
tongji_service = Baidu::TongjiService.new
@access_token = tongji_service.access_token
Rails.logger.info "baidu_tongji_auth access_token ===== #{@access_token}"
# @overview_data = tongji_service.api_overview
last_date = DailyPlatformStatistic.order(:date).last
start_date = last_date.date
end_date = Time.now
if @access_token.present?
@overview_data = Rails.cache.fetch("dashboardscontroller:baidu_tongji:overview_data", expires_in: 10.minutes) do
tongji_service.source_from_batch_add(start_date, end_date)
@overview_data = tongji_service.overview_batch_add(start_date, end_date)
@overview_data
end
end
@current_week_statistic = DailyPlatformStatistic.where(date: current_week)
@pre_week_statistic = DailyPlatformStatistic.where(date: pre_week)
@day_new_project_count = Project.where(created_on: today).count
@weekly_new_project_count = Project.where(created_on: current_week).count
@month_new_project_count = Project.where(created_on: current_month).count
end
def month_active_user
@ -108,19 +42,6 @@ class Admins::DashboardsController < Admins::BaseController
render_ok(data: data)
end
def baidu_tongji
tongji_service = Baidu::TongjiService.new
redirect_to tongji_service.code_url
end
def baidu_tongji_auth
if params[:code].present?
tongji_service = Baidu::TongjiService.new
tongji_service.get_access_token(params[:code])
end
redirect_to "/admins/"
end
def evaluate
names = []
data = []
@ -142,12 +63,8 @@ class Admins::DashboardsController < Admins::BaseController
Time.now.beginning_of_day..Time.now.end_of_day
end
def pre_7_days
7.days.ago.end_of_day..Time.now.end_of_day
end
def current_week
Time.now.beginning_of_week..Time.now.end_of_day
7.days.ago.end_of_day..Time.now.end_of_day
end
def current_month
@ -155,7 +72,6 @@ class Admins::DashboardsController < Admins::BaseController
end
def pre_week
# 14.days.ago.end_of_day..7.days.ago.end_of_day
Time.now.prev_week..Time.now.prev_week.end_of_week
14.days.ago.end_of_day..7.days.ago.end_of_day
end
end

View File

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

View File

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

View File

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

View File

@ -1,6 +1,4 @@
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,5 +1,4 @@
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'
@ -15,14 +14,12 @@ class Admins::IdentityVerificationsController < Admins::BaseController
end
def update
if update_params[:state] == "已拒绝" && update_params[:description].blank?
flash[:danger] = '拒绝理由不能为空'
render 'edit'
else
UserAction.create(action_id: @identity_verification.id, action_type: "UpdateIdentityVerifications", user_id: current_user.id, :ip => request.remote_ip, data_bank: @identity_verification.attributes.to_json)
@identity_verification.update(update_params)
if @identity_verification.update(update_params)
redirect_to admins_identity_verifications_path
flash[:success] = "更新成功"
else
redirect_to admins_identity_verifications_path
flash[:danger] = "更新失败"
end
end

View File

@ -1,30 +0,0 @@
class Admins::IssuesRankController < Admins::BaseController
before_action :require_admin
def index
@statistics = DailyProjectStatistic.where('date >= ? AND date <= ?', begin_date, end_date)
@statistics = @statistics.group(:project_id).joins(:project).select("project_id,
sum(issues) as issues,
sum(closed_issues) as closed_issues,
projects.issues_count as issues_count")
@statistics = @statistics.order("#{sort_by} #{sort_direction}").limit(50)
end
private
def begin_date
params.fetch(:begin_date, (Date.yesterday-7.days).to_s)
end
def end_date
params.fetch(:end_date, Date.yesterday.to_s)
end
def sort_by
DailyProjectStatistic.column_names.include?(params.fetch(:sort_by, "issues")) ? params.fetch(:sort_by, "issues") : "issues"
end
def sort_direction
%w(desc asc).include?(params.fetch(:sort_direction, "desc")) ? params.fetch(:sort_direction, "desc") : "desc"
end
end

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,4 @@
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,5 +1,4 @@
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,5 +1,4 @@
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,5 +1,4 @@
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]
@ -7,7 +6,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).reorder("#{sort_by} #{sort_direction}")
project_licenses = q.result(distinct: true).order("#{sort_by} #{sort_direction}")
@project_licenses = paginate(project_licenses)
end
@ -96,7 +95,7 @@ class Admins::ProjectLicensesController < Admins::BaseController
end
def license_params
params.require(:license).permit(:name,:content,:position)
params.require(:license).permit(:name,:content)
end
# def validate_params

View File

@ -1,22 +1,11 @@
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 ? 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 = Project.where("name like ?", "%#{search}%").order("#{sort_by} #{sort_direction}")
@projects = paginate projects.includes(:owner, :members, :issues, :versions, :attachments, :project_score)
end
@ -43,12 +32,8 @@ class Admins::ProjectsController < Admins::BaseController
def destroy
project = Project.find_by!(id: params[:id])
ActiveRecord::Base.transaction do
close_fork_pull_requests_by(project)
Gitea::Repository::DeleteService.new(project.owner, project.identifier, current_user.gitea_token).call
Gitea::Repository::DeleteService.new(project.owner, project.identifier).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
@ -67,19 +52,4 @@ 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,57 +1,16 @@
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,
sum(score) as score,
sum(visits) as visits,
sum(watchers) as watchers,
sum(praises) as praises,
sum(forks) as forks,
sum(issues) as issues,
sum(pullrequests) as pullrequests,
sum(commits) as commits").includes(:project)
@statistics = paginate @statistics.order("#{sort_by} #{sort_direction}")
export_excel(@statistics.limit(50))
@rank_date = rank_date
deleted_data = $redis_cache.smembers("v2-project-rank-deleted")
$redis_cache.zrem("v2-project-rank-#{rank_date}", deleted_data) unless deleted_data.blank?
@date_rank = $redis_cache.zrevrange("v2-project-rank-#{rank_date}", 0, -1, withscores: true)
end
private
def begin_date
params.fetch(:begin_date, (Date.yesterday-7.days).to_s)
end
def end_date
params.fetch(:end_date, Date.yesterday.to_s)
end
def sort_by
DailyProjectStatistic.column_names.include?(params.fetch(:sort_by, "score")) ? params.fetch(:sort_by, "score") : "score"
end
def sort_direction
%w(desc asc).include?(params.fetch(:sort_direction, "desc")) ? params.fetch(:sort_direction, "desc") : "desc"
end
def export_excel(data)
book = Spreadsheet::Workbook.new
sheet = book.create_worksheet :name => "项目活跃度排行"
sheet.row(0).concat %w(排名 项目全称 项目地址 得分 访问数 关注数 点赞数 fork数 疑修数 合并请求数 提交数)
data.each_with_index do |d, index|
sheet[index+1,0] = index+1
sheet[index+1,1] = "#{d&.project&.owner&.real_name}/#{d&.project&.name}"
sheet[index+1,2] = "#{Rails.application.config_for(:configuration)['platform_url']}/#{d&.project&.owner&.login}/#{d&.project&.identifier}"
sheet[index+1,3] = d.score
sheet[index+1,4] = d.visits
sheet[index+1,5] = d.watchers
sheet[index+1,6] = d.praises
sheet[index+1,7] = d.forks
sheet[index+1,8] = d.issues
sheet[index+1,9] = d.pullrequests
sheet[index+1,10] = d.commits
end
book.write "#{Rails.root}/public/项目活跃度排行.xls"
def rank_date
params.fetch(:date, Date.today.to_s)
end
end

View File

@ -1,5 +1,4 @@
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,5 +1,4 @@
class Admins::SitePagesController < Admins::BaseController
before_action :require_admin
before_action :finder_site_page, except: [:index]
def index
@ -30,12 +29,8 @@ class Admins::SitePagesController < Admins::BaseController
end
def update
if update_params[:state] == "false" && update_params[:state_description].blank?
flash[:danger] = '关闭站点理由不能为空'
else
@site_page.update(update_params)
flash[:success] = '保存成功'
end
@site_page.update(update_params)
flash[:success] = '保存成功'
render 'edit'
end

View File

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

View File

@ -1,5 +1,4 @@
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]
@ -26,7 +25,7 @@ class Admins::SystemNotificationsController < Admins::BaseController
@notification = SystemNotification.new(notification_params)
if @notification.save
redirect_to admins_system_notifications_path
flash[:success] = '系统公告创建成功'
flash[:success] = '系统消息创建成功'
else
redirect_to admins_system_notifications_path
flash[:danger] = @notification.errors.full_messages.join(",")
@ -38,7 +37,7 @@ class Admins::SystemNotificationsController < Admins::BaseController
if @notification.update_attributes(notification_params)
format.html do
redirect_to admins_system_notifications_path
flash[:success] = '系统公告更新成功'
flash[:success] = '系统消息更新成功'
end
format.js {render_ok}
else
@ -54,10 +53,10 @@ class Admins::SystemNotificationsController < Admins::BaseController
def destroy
if @notification.destroy
redirect_to admins_system_notifications_path
flash[:success] = "系统公告删除成功"
flash[:success] = "系统消息删除成功"
else
redirect_to admins_system_notifications_path
flash[:danger] = "系统公告删除失败"
flash[:danger] = "系统消息删除失败"
end
end

View File

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

View File

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

View File

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

View File

@ -1,5 +1,4 @@
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,5 +1,4 @@
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,5 +1,4 @@
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,5 +1,4 @@
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,5 +1,4 @@
class Admins::UsersController < Admins::BaseController
before_action :require_admin
before_action :finder_user, except: [:index]
def index
@ -74,6 +73,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 business glcc_admin])
password login website_permission])
end
end

View File

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

View File

@ -55,11 +55,6 @@ 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

@ -1,37 +0,0 @@
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

@ -7,12 +7,4 @@ class Api::V1::Issues::IssuePrioritiesController < Api::V1::BaseController
@priorities = @priorities.ransack(name_cont: params[:keyword]).result if params[:keyword]
@priorities = kaminary_select_paginate(@priorities)
end
def pm_index
@priorities = IssuePriority.order(position: :asc)
@priorities = @priorities.ransack(name_cont: params[:keyword]).result if params[:keyword]
@priorities = kaminary_select_paginate(@priorities)
render "index"
end
end

View File

@ -1,5 +1,5 @@
class Api::V1::Issues::IssueTagsController < Api::V1::BaseController
before_action :require_login, except: [:index, :pm_index]
before_action :require_login, except: [:index]
before_action :require_public_and_member_above, only: [:index]
before_action :require_operate_above, only: [:create, :update, :destroy]
@ -7,17 +7,12 @@ class Api::V1::Issues::IssueTagsController < Api::V1::BaseController
@issue_tags = @project.issue_tags.reorder("#{sort_by} #{sort_direction}")
@issue_tags = @issue_tags.ransack(name_cont: params[:keyword]).result if params[:keyword].present?
if params[:only_name]
@issue_tags = kaminary_select_paginate(@issue_tags.select(:id, :name, :color))
@issue_tags = kaminary_select_paginate(@issue_tags.select(:id, :name, :color))
else
@issue_tags = kaminari_paginate(@issue_tags.includes(:project, :user, :issue_issues, :pull_request_issues))
end
end
def pm_index
@issue_tags = IssueTag.init_mp_issues_tags
render_ok(@issue_tags)
end
def create
@issue_tag = @project.issue_tags.new(issue_tag_params)
if @issue_tag.save!

View File

@ -8,11 +8,4 @@ class Api::V1::Issues::StatuesController < Api::V1::BaseController
@statues = @statues.ransack(name_cont: params[:keyword]).result if params[:keyword].present?
@statues = kaminary_select_paginate(@statues)
end
def pm_index
@statues = IssueStatus.order("position asc")
@statues = @statues.ransack(name_cont: params[:keyword]).result if params[:keyword].present?
@statues = kaminary_select_paginate(@statues)
render "index"
end
end

View File

@ -1,6 +1,6 @@
class Api::V1::IssuesController < Api::V1::BaseController
before_action :require_login, except: [:index, :show, :show_by_id]
before_action :require_public_and_member_above, only: [:index, :show, :show_by_id, :create, :update, :destroy]
before_action :require_login, except: [:index, :show]
before_action :require_public_and_member_above, only: [:index, :show, :create, :update, :destroy]
before_action :require_operate_above, only: [:batch_update, :batch_destroy]
def index
@ -22,15 +22,8 @@ class Api::V1::IssuesController < Api::V1::BaseController
before_action :load_issue, only: [:show, :update, :destroy]
before_action :check_issue_operate_permission, only: [:update, :destroy]
before_action :load_issue_by_id, only: [:show_by_id]
def show_by_id
@issue.associate_attachment_container
@user_permission = current_user.present? && current_user.logged? && (@project.member?(current_user) || current_user.admin? || @issue.user == current_user)
end
def show
@issue.associate_attachment_container
def show
@user_permission = current_user.present? && current_user.logged? && (@project.member?(current_user) || current_user.admin? || @issue.user == current_user)
end
@ -76,13 +69,6 @@ class Api::V1::IssuesController < Api::V1::BaseController
end
end
def load_issue_by_id
@issue = Issue.find_by_id(params[:index])
if @issue.blank?
render_not_found("疑修不存在!")
end
end
def load_issues
return render_error("请输入正确的ID数组") unless params[:ids].is_a?(Array)
params[:ids].each do |id|

View File

@ -1,10 +0,0 @@
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

@ -1,31 +0,0 @@
class Api::V1::Projects::Actions::ActionsController < Api::V1::Projects::Actions::BaseController
def index
begin
gitea_result = $gitea_hat_client.get_repos_actions_by_owner_repo(@project&.owner&.login, @project&.identifier)
@data = gitea_result[:data]["Workflows"]
rescue
@data = []
end
end
def disable
return render_error("请输入正确的流水线文件!") if params[:workflow].blank?
gitea_result = $gitea_hat_client.post_repos_actions_disable(@project&.owner&.login, @project&.identifier, {query: {workflow: params[:workflow]}}) rescue nil
if gitea_result
render_ok
else
render_error("禁用流水线失败")
end
end
def enable
return render_error("请输入正确的流水线文件!") if params[:workflow].blank?
gitea_result = $gitea_hat_client.post_repos_actions_enable(@project&.owner&.login, @project&.identifier, {query: {workflow: params[:workflow]}}) rescue nil
if gitea_result
render_ok
else
render_error("取消禁用流水线失败")
end
end
end

View File

@ -1,4 +0,0 @@
class Api::V1::Projects::Actions::BaseController < Api::V1::BaseController
before_action :require_public_and_member_above
end

View File

@ -1,57 +0,0 @@
class Api::V1::Projects::Actions::RunsController < Api::V1::Projects::Actions::BaseController
def index
@result_object = Api::V1::Projects::Actions::Runs::ListService.call(@project, {workflow: params[:workflow], page: page, limit: limit}, current_user&.gitea_token)
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,38 +1,15 @@
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)
@result_object = Api::V1::Projects::Branches::ListService.call(@project, {name: params[:keyword], page: page, limit: limit}, current_user&.gitea_token)
end
def all
@result_object = Api::V1::Projects::Branches::AllListService.call(@project, current_user&.gitea_token)
end
before_action :require_operate_above, only: [:create, :destroy, :restore]
before_action :require_operate_above, only: [:create, :destroy]
def create
@result_object = Api::V1::Projects::Branches::CreateService.call(@project, branch_params, current_user&.gitea_token)
@ -56,15 +33,6 @@ class Api::V1::Projects::BranchesController < Api::V1::BaseController
end
end
def restore
@result_object = Api::V1::Projects::Branches::RestoreService.call(@project, params[:branch_id], params[:branch_name], current_user&.gitea_token)
if @result_object
return render_ok
else
return render_error('恢复分支失败!')
end
end
before_action :require_manager_above, only: [:update_default_branch]
def update_default_branch

View File

@ -1,5 +1,5 @@
class Api::V1::Projects::CommitsController < Api::V1::BaseController
before_action :require_public_and_member_above, only: [:index, :diff, :recent]
before_action :require_public_and_member_above, only: [:index, :diff]
def index
@result_object = Api::V1::Projects::Commits::ListService.call(@project, {page: page, limit: limit, sha: params[:sha]}, current_user&.gitea_token)
@ -9,11 +9,4 @@ class Api::V1::Projects::CommitsController < Api::V1::BaseController
def diff
@result_object = Api::V1::Projects::Commits::DiffService.call(@project, params[:sha], current_user&.gitea_token)
end
def recent
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

@ -1,51 +0,0 @@
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

@ -1,52 +0,0 @@
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

@ -1,148 +0,0 @@
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

@ -1,13 +1,10 @@
class Api::V1::Projects::TagsController < Api::V1::BaseController
before_action :require_public_and_member_above, only: [:index, :show]
before_action :require_public_and_member_above, only: [:index]
def index
@release_tags = @repository.version_releases.pluck(:tag_name)
@result_object = Api::V1::Projects::Tags::ListService.call(@project, {page: page, limit: limit}, current_user&.gitea_token)
end
def show
@result_object = Api::V1::Projects::Tags::GetService.call(@project, params[:name], current_user&.gitea_token)
puts @result_object
end
before_action :require_operate_above, only: [:destroy]

View File

@ -1,23 +0,0 @@
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,11 +75,7 @@ class ApplicationController < ActionController::Base
def admin_or_business?
User.current.admin? || User.current.business?
end
def admin_or_glcc_admin?
User.current.admin? || User.current.glcc_admin?
User.current.admin? || User.current.business?
end
# 判断用户的邮箱或者手机是否可用
@ -199,10 +195,6 @@ 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
@ -230,11 +222,11 @@ class ApplicationController < ActionController::Base
end
def require_profile_completed
tip_exception(411, "请完善资料后再操作") unless User.current.profile_is_completed?
# tip_exception(411, "请完善资料后再操作") unless User.current.profile_is_completed?
end
def require_user_profile_completed(user)
tip_exception(412, "请用户完善资料后再操作") unless user.profile_is_completed?
# tip_exception(412, "请用户完善资料后再操作") unless user.profile_is_completed?
end
# 异常提醒
@ -723,7 +715,7 @@ class ApplicationController < ActionController::Base
end
def find_user_with_id
@user = User.find_by(type: 'User', id: params[:user_id])
@user = User.find_by_id params[:user_id]
# render_not_found("未找到’#{params[:login]}’相关的用户") unless @user
render_error("未找到相关的用户") unless @user
end

View File

@ -39,8 +39,7 @@ class AttachmentsController < ApplicationController
filepath, ref = url.split("/")[-1].split("?")
url.gsub!(url.split("/")[-1], '')
Rails.logger.info("url===#{url}")
Rails.logger.info(filepath)
request_url = [domain, api_url, URI.encode(url), URI.escape(filepath), "?ref=#{URI.escape(ref.split('ref=')[1])}&access_token=#{User.where(admin: true).take&.gitea_token}"].join
request_url = [domain, api_url, URI.encode(url), CGI.escape(filepath), "?ref=#{CGI.escape(ref.split('ref=')[1])}&access_token=#{User.where(admin: true).take&.gitea_token}"].join
Rails.logger.info("request_url===#{request_url}")
response = Faraday.get(request_url)
filename = filepath
@ -94,10 +93,6 @@ class AttachmentsController < ApplicationController
@attachment.author_id = current_user.id
@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}"
@ -127,7 +122,7 @@ class AttachmentsController < ApplicationController
# 附件为视频时,点击播放
def preview_attachment
attachment = Attachment.where_id_or_uuid(params[:id]).first
attachment = Attachment.find_by(id: params[:id])
dir_path = "#{Rails.root}/public/preview"
Dir.mkdir(dir_path) unless Dir.exist?(dir_path)
if params[:status] == "preview"
@ -147,14 +142,12 @@ class AttachmentsController < ApplicationController
private
def find_file
tip_exception(404, "您访问的页面不存在或已被删除") if params[:id].blank?
@file =
if params[:type] == 'history'
AttachmentHistory.find params[:id]
else
Attachment.where_id_or_uuid(params[:id]).first
Attachment.find params[:id]
end
tip_exception(404, "您访问的页面不存在或已被删除") if @file.blank?
end
def delete_file(file_path)
@ -224,22 +217,18 @@ class AttachmentsController < ApplicationController
def attachment_candown
unless current_user.admin? || current_user.business?
candown = true
if @file.container && @file.uuid.nil?
if @file.container
if @file.container.is_a?(Issue)
project = @file.container.project
candown = project.is_public || (current_user.logged? && project.member?(current_user))
elsif @file.container.is_a?(Journal)
project = @file.container.issue.project
candown = project.is_public || (current_user.logged? && project.member?(current_user))
elsif @file.container.is_a?(Project)
project = @file.container
candown = project.is_public || (current_user.logged? && project.member?(current_user))
else
project = nil
end
tip_exception(403, "您没有权限进入") if project.present? && !candown
end
tip_exception(403, "您没有权限查看") if @file.is_public == 0 && @file.author_id != current_user.id
end
end

View File

@ -8,7 +8,7 @@ class BindUsersController < ApplicationController
bind_user = User.try_to_login(params[:username], params[:password])
tip_exception '用户名或者密码错误' if bind_user.blank?
tip_exception '用户名或者密码错误' unless bind_user.check_password?(params[:password].to_s)
tip_exception '参数错误' unless ["qq", "wechat", "gitee", "github", "educoder", "acge"].include?(params[:type].to_s)
tip_exception '参数错误' unless ["qq", "wechat", "gitee", "github", "educoder"].include?(params[:type].to_s)
tip_exception '该账号已被绑定,请更换其他账号进行绑定' if bind_user.bind_open_user?(params[:type].to_s)
"OpenUsers::#{params[:type].to_s.capitalize}".constantize.create!(user: bind_user, uid: session[:unionid])

View File

@ -19,10 +19,9 @@ 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, created_at: commit_date, updated_at: commit_date)
ref: ref, commit_id: commit_id, message: message)
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

@ -139,7 +139,7 @@ class IssuesController < ApplicationController
SendTemplateMessageJob.perform_later('ProjectIssue', current_user.id, @issue&.id) if Site.has_notice_menu?
if params[:attachment_ids].present?
params[:attachment_ids].each do |id|
attachment = Attachment.where_id_or_uuid(id).select(:id, :container_id, :container_type)&.first
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?
attachment.container = @issue
attachment.author_id = current_user.id
@ -232,7 +232,7 @@ class IssuesController < ApplicationController
if issue_files.present?
change_files = true
issue_files.each do |id|
attachment = Attachment.where_id_or_uuid(id).select(:id, :container_id, :container_type)&.first
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?
attachment.container = @issue
attachment.author_id = current_user.id
@ -321,7 +321,6 @@ class IssuesController < ApplicationController
@issue_user = @issue.user
@issue_assign_to = @issue.get_assign_user
@join_users = join_users(@issue)
@issue.associate_attachment_container
#总耗时
# cost_time(@issue)

View File

@ -35,7 +35,7 @@ class JournalsController < ApplicationController
if journal.save
if params[:attachment_ids].present?
params[:attachment_ids].each do |id|
attachment = Attachment.where_id_or_uuid(id).select(:id, :container_id, :container_type)&.first
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?
attachment.container = journal
attachment.author_id = current_user.id

View File

@ -21,7 +21,6 @@ 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,79 +0,0 @@
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
tip_exception("uid不能为空") if uid.blank?
redirect_uri = params['redirect_uri'].to_s.strip
tip_exception("redirect_uri不能为空") if redirect_uri.blank?
email = params['email'].to_s.strip
tip_exception("email不能为空") if email.blank?
phone = params['phone'].to_s.strip
tip_exception("phone不能为空") if phone.blank?
name = params['name'].to_s.strip
tip_exception("name不能为空") if name.blank?
open_user = OpenUsers::Acge.find_by(uid: uid)
if open_user.present? && open_user.user.present?
successful_authentication(open_user.user)
redirect_to redirect_uri
return
else
if current_user.blank? || !current_user.logged?
session[:unionid] = uid
user = User.find_by(mail: email) || User.find_by(phone: phone)
if user.present?
OpenUsers::Acge.create!(user: user, uid: uid)
successful_authentication(user)
redirect_to redirect_uri
return
else
username = uid
password = SecureRandom.hex(4)
reg_result = autologin_register(username, email, password, 'acge', phone, name)
existing_rows = CSV.read("public/操作系统大赛用户信息.csv")
new_row = [username, email, password, phone, name]
existing_rows << new_row
CSV.open("public/操作系统大赛用户信息.csv", 'wb') do |csv|
existing_rows.each { |row| csv << row }
end
if reg_result[:message].blank?
open_user = OpenUsers::Acge.create!(user_id: reg_result[:user][:id], uid: uid)
successful_authentication(open_user.user)
redirect_to redirect_uri
return
else
render_error(reg_result[:message])
end
end
else
OpenUsers::Acge.create!(user: current_user, uid: uid)
successful_authentication(current_user)
redirect_to redirect_uri
return
end
end
Rails.logger.info("[OAuth2] session[:unionid] -> #{session[:unionid]}")
# redirect_to "/bindlogin/acge?redirect_uri=#{redirect_uri}"
rescue Exception => ex
render_error(ex.message)
end
end
end

View File

@ -20,12 +20,12 @@ class Oauth2Controller < ActionController::Base
return @error = {msg: '违反平台使用规范,账号已被锁定', id: 'login'} if @user.locked?
login_control = LimitForbidControl::UserLogin.new(@user)
return @error = {msg: "登录密码出错已达上限,账号已被锁定#{login_control.forbid_expires/60}分钟后重新登录或找回密码", id: 'account'} if login_control.forbid?
return @error = {msg: "登录密码出错已达上限,账号已被锁定, #{login_control.forbid_expires/60}分钟后重新登录或找回密码", id: 'account'} if login_control.forbid?
password_ok = @user.check_password?(params[:password].to_s)
unless password_ok
if login_control.remain_times-1 == 0
@error = {msg: "登录密码出错已达上限,账号已被锁定#{login_control.forbid_expires/60}分钟后重新登录或找回密码", id: 'account'}
@error = {msg: "登录密码出错已达上限,账号已被锁定, #{login_control.forbid_expires/60}分钟后重新登录或找回密码", id: 'account'}
else
@error = {msg: "你已经输错密码#{login_control.error_times+1}次,还剩余#{login_control.remain_times-1}次机会", id: 'account'}
end

View File

@ -1,38 +1,19 @@
class Organizations::OrganizationUsersController < Organizations::BaseController
before_action :load_organization
before_action :load_operate_user, :load_organization_user, only: [:destroy, :pm_check_user]
before_action :check_user_can_edit_org, only: [:destroy]
before_action :load_operate_user, :load_organization_user, :check_user_can_edit_org, only: [:destroy]
def index
# @organization_users = @organization.organization_users.includes(:user)
# if params[:search].present?
# search = params[:search].to_s.downcase
# user_condition_users = User.like(search).to_sql
# team_condition_teams = User.joins(:teams).merge(@organization.teams.like(search)).to_sql
# users = User.from("( #{user_condition_users} UNION #{team_condition_teams }) AS users")
#
# @organization_users = @organization_users.where(user_id: users).distinct
# end
#
# @organization_users = kaminari_paginate(@organization_users)
organization_user_ids = @organization.organization_users.pluck(:user_id).uniq
project_member_user_ids = @organization.projects.joins(:members).pluck("members.user_id").uniq
ids = organization_user_ids + project_member_user_ids
users = User.where(id: ids).reorder(Arel.sql("FIELD(users.id,#{ids.join(',')})"))
@organization_users = @organization.organization_users.includes(:user)
if params[:search].present?
search = params[:search].to_s.downcase
user_condition_users = User.like(search).to_sql
team_condition_teams = User.joins(:teams).merge(@organization.teams.like(search)).to_sql
user_ids = User.from("( #{user_condition_users} UNION #{team_condition_teams }) AS users").pluck(:id)
users = User.from("( #{user_condition_users} UNION #{team_condition_teams }) AS users")
users = users.where(id: user_ids)
@organization_users = @organization_users.where(user_id: users).distinct
end
@users = kaminari_paginate(users)
end
def pm_check_user
render_ok
@organization_users = kaminari_paginate(@organization_users)
end
def destroy

View File

@ -1,8 +1,8 @@
class Organizations::TeamUsersController < Organizations::BaseController
before_action :load_organization, :load_team
before_action :load_operate_user, only: [:create, :destroy, :pm_check_user]
before_action :load_operate_user, only: [:create, :destroy]
before_action :check_user_profile_completed, only: [:create]
before_action :load_team_user, only: [:destroy, :pm_check_user]
before_action :load_team_user, only: [:destroy]
before_action :check_user_can_edit_org, only: [:create, :destroy]
def index
@ -14,10 +14,6 @@ class Organizations::TeamUsersController < Organizations::BaseController
@team_users = kaminari_paginate(@team_users)
end
def pm_check_user
render_ok
end
def create
ActiveRecord::Base.transaction do
@team_user = TeamUser.build(@organization.id, @operate_user.id, @team.id)

View File

@ -67,18 +67,7 @@ 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

@ -4,9 +4,9 @@ class ProjectsController < ApplicationController
include ProjectsHelper
include Acceleratorable
before_action :require_login, except: %i[index branches branches_slice group_type_list simple show mp_show fork_users praise_users watch_users recommend banner_recommend about menu_list verify_auth_token]
before_action :require_login, except: %i[index branches branches_slice group_type_list simple show fork_users praise_users watch_users recommend banner_recommend about menu_list verify_auth_token]
before_action :require_profile_completed, only: [:create, :migrate,:page_migrate,:verify_auth_token]
before_action :load_repository, except: %i[index mp_show group_type_list migrate page_migrate create recommend banner_recommend verify_auth_token]
before_action :load_repository, except: %i[index group_type_list migrate page_migrate create recommend banner_recommend verify_auth_token]
before_action :authorizate_user_can_edit_project!, only: %i[update]
before_action :project_public?, only: %i[fork_users praise_users watch_users]
before_action :request_limit, only: %i[index]
@ -21,7 +21,6 @@ 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))
@ -36,8 +35,6 @@ 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)
@ -45,8 +42,7 @@ class ProjectsController < ApplicationController
@total_count =
if category_id.blank? && params[:search].blank? && params[:topic_id].blank?
# 默认查询时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
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
elsif params[:search].present? || params[:topic_id].present?
@projects.total_count
else
@ -59,14 +55,10 @@ class ProjectsController < ApplicationController
ActiveRecord::Base.transaction do
Projects::CreateForm.new(project_params).validate!
@project = Projects::CreateService.new(current_user, project_params).call
OpenProjectDevOpsJob.set(wait: 5.seconds).perform_later(@project&.id, current_user.id)
#OpenProjectDevOpsJob.set(wait: 5.seconds).perform_later(@project&.id, current_user.id)
UpdateProjectTopicJob.perform_later(@project.id) if @project.id.present?
end
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
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
@ -109,7 +101,7 @@ class ProjectsController < ApplicationController
def page_migrate
return normal_status(-1, "您还未开通Page服务无法进行新建站点") unless current_user.id_card_verify
return normal_status(-1, "你已使用了 #{page_site_params[:identifier]} 作为page标识") if Page.exists?(identifier: page_site_params[:identifier], user: current_user)
Projects::MigrateForm.new(mirror_params).validate!
@project =
@ -201,27 +193,17 @@ class ProjectsController < ApplicationController
default_branch: @project.default_branch
}
Gitea::Repository::UpdateService.call(@owner, @project.identifier, gitea_params)
elsif project_params.has_key?("has_actions")
gitea_params = {
has_actions: project_params[:has_actions]
}
Gitea::Repository::UpdateService.call(@owner, @project.identifier, gitea_params)
else
validate_params = project_params.slice(:name, :description,
:project_category_id, :project_language_id, :private, :identifier)
Projects::UpdateForm.new(validate_params.merge(user_id: @project.user_id, project_identifier: @project.identifier, project_name: @project.name)).validate!
private = params[:private].nil? ? !@project.is_public : params[:private]
private = @project.forked_from_project.present? ? !@project.forked_from_project.is_public : private
private = @project.forked_from_project.present? ? !@project.forked_from_project.is_public : params[:private] || false
new_project_params = project_params.except(:private).merge(is_public: !private)
@project.update_attributes!(new_project_params)
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)}
@project.forked_projects.update_all(is_public: @project.is_public)
gitea_params = {
private: private,
default_branch: @project.default_branch,
@ -250,20 +232,10 @@ class ProjectsController < ApplicationController
def show
end
def mp_show
@project = Project.joins(:owner).find params[:project_id]
data={
owner:@project.owner.try(:login),
identifier:@project.identifier
}
render_ok(data:data)
end
def destroy
if current_user.admin? || @project.manager?(current_user)
ActiveRecord::Base.transaction do
close_fork_pull_requests_by(@project)
Gitea::Repository::DeleteService.new(@project.owner, @project.identifier,current_user.gitea_token).call
Gitea::Repository::DeleteService.new(@project.owner, @project.identifier).call
@project.destroy!
@project.forked_projects.update_all(forked_from_project_id: nil)
# 如果该项目有所属的项目分类以及为私有项目,需要更新对应数量
@ -313,30 +285,6 @@ 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
# 项目名称,标识,所有者变化时重置缓存
@ -390,7 +338,7 @@ class ProjectsController < ApplicationController
def project_params
params.permit(:user_id, :name, :description, :repository_name, :website, :lesson_url, :default_branch, :identifier,
:project_category_id, :project_language_id, :license_id, :ignore_id, :private, :has_actions,
:project_category_id, :project_language_id, :license_id, :ignore_id, :private,
:blockchain, :blockchain_token_all, :blockchain_init_token, :pr_view_admin)
end
@ -413,19 +361,4 @@ 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

@ -203,7 +203,6 @@ class PullRequestsController < ApplicationController
def pr_merge
return render_forbidden("你没有权限操作.") unless @project.operator?(current_user)
return normal_status(-1, "该分支存在冲突,无法自动合并.") unless @pull_request.conflict_files.blank?
if params[:do].blank?
normal_status(-1, "请选择合并方式")
@ -253,7 +252,6 @@ class PullRequestsController < ApplicationController
normal_status(-1, result.message)
end
rescue => e
logger_error(e)
normal_status(-1, e.message)
raise ActiveRecord::Rollback
end

View File

@ -7,7 +7,6 @@ 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]
@ -65,7 +64,6 @@ 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}/"
end
@ -438,8 +436,4 @@ class RepositoriesController < ApplicationController
end
end
def require_operate_above
return render_forbidden if !current_user.admin? && !@project.operator?(current_user)
end
end

View File

@ -82,6 +82,7 @@ class SettingsController < ApplicationController
def get_third_party
@third_party = []
return if EduSetting.get("is_local") == "true"
@third_party << {
name: 'educoder',
url: EducoderOauth.oauth_url
@ -90,6 +91,7 @@ class SettingsController < ApplicationController
def get_third_party_new
@third_party_new = []
return if EduSetting.get("is_local") == "true"
@third_party_new << {
name: 'educoder',
url: EducoderOauth.oauth_url,

View File

@ -17,31 +17,23 @@ class SitePagesController < ApplicationController
end
def create
return normal_status(-1, '你还未开通Page服务无法进行部署') unless current_user.website_permission
return normal_status(-1, '你已开通Page服务') if Page.exists?(user: current_user)
return normal_status(-1, '该仓库已开通Page服务') if Page.exists?(project: @project)
return normal_status(-1, "你还未开通Page服务无法进行部署") unless current_user.website_permission
return normal_status(-1, "你已使用了 #{params[:identifier]} 作为page标识") if Page.exists?(identifier: params[:identifier], user: current_user)
return normal_status(-1, "该仓库已开通Page服务") if Page.exists?(project: @project)
@page = Page.new(create_params)
@page.user = current_user
@page.project = @project
@page.save
end
def update
return normal_status(-1, '你还未开通Page服务') unless current_user.website_permission
return normal_status(-1, '你还未开通Page站点') unless Page.exists?(user: current_user)
@page = Page.find_by(user: current_user)
@page.update(language_frame: params[:language_frame])
render_ok
end
def build
return normal_status(-1, '你还未开通Page服务无法进行部署') unless current_user.website_permission
return normal_status(-1, '该仓库还未开通Page服务无法进行部署') unless Page.exists?(project: @project)
return normal_status(-1, "你还未开通Page服务无法进行部署") unless current_user.website_permission
return normal_status(-1, "该仓库还未开通Page服务无法进行部署") unless Page.exists?(project: @project)
@page = Page.find params[:id]
return normal_status(-1, @page.state_description) unless @page.state
response_str = @page.deploy_page(params[:branch])
data = JSON.parse(response_str)['result'] || (data = JSON.parse(response_str)['error'])
if data.to_s.include?('部署成功')
data = JSON.parse(response_str)["result"] || data = JSON.parse(response_str)["error"]
if data.to_s.include?("部署成功")
@page.update(last_build_at: Time.now, build_state: true, last_build_info: data)
else
@page.update(build_state:false, last_build_info: data)
@ -50,22 +42,22 @@ class SitePagesController < ApplicationController
end
def softbot_build
branch = params[:ref].split('/').last
branch = params[:ref].split("/").last
user = User.find_by_login params[:repository][:owner][:login]
return normal_status(-1, '你还未开通Page服务无法进行部署') unless user.website_permission
return normal_status(-1, "你还未开通Page服务无法进行部署") unless user.website_permission
project = Project.where(identifier: params[:repository][:name],user_id: user.id)
return normal_status(-1, '你没有权限操作') if project.owner?(user)
return normal_status(-1, '该仓库还未开通Page服务无法进行部署') if Page.exists?(user: user, project: project)
return normal_status(-1, "你没有权限操作") if project.owner?(user)
return normal_status(-1, "该仓库还未开通Page服务无法进行部署") if Page.exists?(user: user, project: project)
@page = Page.find_by(user: user, project: project)
response_str = @page.deploy_page(branch)
data = JSON.parse(response_str)['result']
data = JSON.parse(response_str)["result"]
if data.nil?
data = JSON.parse(response_str)['error']
data = JSON.parse(response_str)["error"]
end
if data.include?('部署成功')
if data.include?("部署成功")
@page.update(last_build_at: Time.now, build_state: true, last_build_info: data)
else
@page.update(build_state:false, last_build_info: data)
@ -93,7 +85,7 @@ class SitePagesController < ApplicationController
end
def theme_params
params[:language_frame] || 'hugo'
params[:language_frame] || "hugo"
end
def create_params

View File

@ -10,15 +10,7 @@ class Users::OrganizationsController < Users::BaseController
end
@organizations = @organizations.ransack(login_cont: params[:search]).result if params[:search].present?
@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 = @organizations.includes(:organization_extension).order("organization_extensions.#{sort_by} #{sort_direction}")
@organizations = kaminari_paginate(@organizations)
end

View File

@ -22,7 +22,7 @@ class UsersController < ApplicationController
end
def list
scope = User.active.like(params[:search]).includes(:user_extension).order(nickname: :desc, last_login_on: :desc)
scope = User.active.recent.like(params[:search]).includes(:user_extension)
@total_count = scope.size
@users = paginate(scope)
end
@ -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, @home_top_ids = Projects::ListMyQuery.call(params, @user,is_current_admin_user)
scope = Projects::ListMyQuery.call(params, @user,is_current_admin_user)
@total_count = scope.size
@projects = kaminari_unlimit_paginate(scope)
end
@ -702,15 +702,6 @@ 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])
@ -740,7 +731,7 @@ class UsersController < ApplicationController
end
def sso_login
if params[:login].present? && !current_user.logged? && params[:websiteName].present? && request.referer.to_s.include?("gitlink.org.cn")
if params[:login].present? && !current_user.logged? && params[:websiteName].present?
user = User.where("login = ?", "#{params[:login].presence}").first
# 已同步注册,直接登录
if user.present?

View File

@ -1,9 +1,8 @@
class VersionReleasesController < ApplicationController
include ApplicationHelper
before_action :load_repository
before_action :set_user
before_action :require_login, except: [:index, :show, :download]
before_action :check_release_authorize, except: [:index, :show, :download]
before_action :require_login, except: [:index, :show]
before_action :check_release_authorize, except: [:index, :show]
before_action :find_version , only: [:show, :edit, :update, :destroy]
def index
@ -127,16 +126,6 @@ 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
@ -157,13 +146,13 @@ class VersionReleasesController < ApplicationController
name: params[:name],
prerelease: params[:prerelease] || false,
tag_name: params[:tag_name],
target_commitish: params[:target_commitish] || @project.default_branch #分支
target_commitish: params[:target_commitish] || "master" #分支
}
end
def create_attachments(attachment_ids, target)
attachment_ids.each do |id|
attachment = Attachment.where_id_or_uuid(id).select(:id, :container_id, :container_type)&.first
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?
attachment.container = target
attachment.author_id = current_user.id

View File

@ -26,16 +26,6 @@ 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
@ -68,6 +58,7 @@ class BaseForm
def check_verifi_code(verifi_code, code)
code = strip(code)
return if code == "123123" && EduSetting.get("code_debug") # 万能验证码,用于测试 # TODO 万能验证码,用于测试
return if EduSetting.get("is_local") == "true" || Rails.application.config_for(:configuration)['is_local'].to_s =="true" # 本地版不需要验证码
raise VerifiCodeError, "验证码已失效" if !verifi_code&.effective?
raise VerifiCodeError, "验证码不正确" if verifi_code&.code != code
end

View File

@ -1,12 +1,12 @@
class Organizations::CreateForm < BaseForm
NAME_REGEX = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*$/ #只含有数字、字母、下划线不能以下划线开头和结尾
NAME_REGEX = /^(?!_)(?!.*?_$)[a-zA-Z0-9_-]+$/ #只含有数字、字母、下划线不能以下划线开头和结尾
attr_accessor :name, :description, :website, :location, :repo_admin_change_team_access, :visibility, :max_repo_creation, :nickname, :original_name
validates :name, :nickname, :visibility, presence: true
validates :name, :nickname, length: { maximum: 100 }
validates :location, length: { maximum: 50 }
validates :description, length: { maximum: 200 }
validates :name, format: { with: NAME_REGEX, multiline: true, message: "只能以数字或字母开头仅支持横杠、下划线、点三种符号不允许符号连续排列长度4-50个字符" }
validates :name, format: { with: NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" }
validate do
check_name(name) unless name.blank? || name == original_name

View File

@ -16,7 +16,6 @@ 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
@ -29,10 +28,6 @@ class Projects::CreateForm < BaseForm
raise "ignore_id值无效." if ignore_id && Ignore.find_by(id: ignore_id).blank?
end
def check_auto_init
raise "auto_init值无效." if ignore_id && license_id && !auto_init
end
def check_owner
@project_owner = Owner.find_by(id: user_id)
raise "user_id值无效." if user_id && @project_owner.blank?

View File

@ -1,15 +0,0 @@
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,7 +11,6 @@ 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,7 +10,6 @@ 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

@ -9,7 +9,7 @@ module Register
login_exist = Owner.exists?(login: login) || ReversedKeyword.check_exists?(login)
if user.present?
raise LoginError, '登录名已被他人使用' if login_exist && login != user&.login
raise LoginError, '登录名已被使用' if login_exist && login != user&.login
else
raise LoginError, '登录名已被使用' if login_exist
end

View File

@ -8,7 +8,7 @@ module Register
def check!
user = User.find_by(id: user_id)
Rails.logger.info "Register::RemoteForm params: id: #{user_id}; username: #{username}; email: #{email}; password: #{password}; platform: #{platform}"
Rails.logger.info "Register::RemoteForm params: id: #{user&.id}; username: #{username}; email: #{email}; password: #{password}; platform: #{platform}"
check_login(username, user)
check_mail(email,user)
check_password(password)

View File

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

View File

@ -299,7 +299,7 @@ module ApplicationHelper
end
def download_url attachment,options={}
attachment&.uuid.present? ? attachment_path(attachment.uuid,options) : attachment_path(attachment,options)
attachment_path(attachment,options)
end
# 耗时:天、小时、分、秒
@ -479,7 +479,7 @@ module ApplicationHelper
return if url.blank?
content_tag(:li) do
sidebar_item(url, "数据统计", icon: 'bar-chart', controller: 'root', has_permission: true)
sidebar_item(url, "数据统计", icon: 'bar-chart', controller: 'root')
end
end

View File

@ -2,33 +2,29 @@ module ManageBackHelper
extend ActiveSupport::Concern
def sidebar_item_group(url, text, **opts)
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
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
end
raw content
end
def sidebar_item(url, text, **opts)
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
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
end
raw content
end
def admin_sidebar_controller

View File

@ -67,8 +67,6 @@ 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

@ -132,8 +132,6 @@ module RepositoriesHelper
src_regex_3 = /src= (.*?) /
src_regex_4 = /src =(.*?) /
src_regex_5 = /src =(.*?) /
href_regex = /href=\"(.*?)\"/
href_regex_1 = /href=\'(.*?)\'/
ss_c = content.to_s.scan(s_regex_c)
ss = content.to_s.scan(s_regex)
ss_1 = content.to_s.scan(s_regex_1)
@ -144,10 +142,7 @@ module RepositoriesHelper
ss_src_3 = content.to_s.scan(src_regex_3)
ss_src_4 = content.to_s.scan(src_regex_4)
ss_src_5 = content.to_s.scan(src_regex_5)
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 = {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}
# total_sources.uniq!
total_sources.except(:ss, :ss_c).each do |k, sources|
sources.each do |s|
@ -158,7 +153,6 @@ 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}")
@ -179,17 +173,13 @@ module RepositoriesHelper
content = content.gsub("src=#{s[0]}", "src=\'#{s_content}\'")
when 'ss_2'
content = content.gsub(/]:#{s[0]}/, "]: #{s_content.to_s.gsub(" ","").gsub("\r", "")}")
when 'ss_href'
content = content.gsub("href=\"#{s[0]}\"", "href=\"#{s_content}\"")
when 'ss_href_1'
content = content.gsub("href=\'#{s[0]}\'", "href=\'#{s_content}\'")
else
else
content = content.gsub("(#{s[0]})", "(#{s_content})")
end
else
path = [owner&.login, repo&.identifier, 'tree', ref, file_path].join("/")
s_content = File.expand_path(s_content, path)
s_content = s_content.split("#{Rails.root}")[1]
s_content = s_content.split("#{Rails.root}/")[1]
case k.to_s
when 'ss_src'
content = content.gsub("src=\"#{s[0]}\"", "src=\"/#{s_content}\"")
@ -197,11 +187,7 @@ module RepositoriesHelper
content = content.gsub("src=\'#{s[0]}\'", "src=\'/#{s_content}\'")
when 'ss_2'
content = content.gsub(/]:#{s[0]}/, "]: /#{s_content.to_s.gsub(" ","").gsub("\r", "")}")
when 'ss_href'
content = content.gsub("href=\"#{s[0]}\"", "href=\"#{s_content}\"")
when 'ss_href_1'
content = content.gsub("href=\'#{s[0]}\'", "href=\'#{s_content}\'")
else
else
content = content.gsub("(#{s[0]})", "(/#{s_content})")
end
end
@ -211,14 +197,12 @@ module RepositoriesHelper
end
end
after_ss_souces = content.to_s.scan(s_regex)#.uniq
after_ss_souces = content.to_s.scan(s_regex)
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)#.uniq
after_ss_c_souces = content.to_s.scan(s_regex_c)
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

@ -45,7 +45,6 @@ module Gitea
else
Rails.logger.error("Gitea::Repository::Entries::DeleteService error[#{response.status}]======#{response.body}")
@error = "删除失败,请确认该分支是否是保护分支。"
@error = "删除失败参数sha不匹配。" if response.body.to_s.include?("sha does not match")
end
end

View File

@ -2,7 +2,6 @@ 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, project.owner.gitea_token).call
delete_gitea = Gitea::Repository::DeleteService.new(project.owner, project.identifier).call
if delete_gitea.status == 204 || delete_gitea.status == 404 #删除成功或者仓库不存在,都重新创建
repository_params= {
name: project.identifier,

View File

@ -1,44 +0,0 @@
# 按天获取百度统计数据pv访问ip和来源分类占比
# 其他统计:前一周用户留存率
class DailyPlatformStatisticsJob < ApplicationJob
queue_as :default
def perform(*args)
Rails.logger.info("*********开始统计*********")
tongji_service = Baidu::TongjiService.new
access_token = tongji_service.access_token
Rails.logger.info "job baidu_tongji_auth access_token ===== #{access_token}"
ActiveJob::Base.logger.info "job baidu_tongji_auth access_token ===== #{access_token}"
# 从最后一个记录日期开始,如果遗漏日期数据可以补充数据
last_date = DailyPlatformStatistic.order(:date).last
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)
# 本周访问来源占比,每天记录一次,如果遗漏日期数据可以补充数据
tongji_service.source_from_batch_add(start_date, end_date)
end
# 周用户留存率
pre_week_user_ids = User.where(created_on: pre_week).pluck(:id).uniq
weekly_keep_user_count = User.where(id: pre_week_user_ids).where(last_login_on: current_week).count
weekly_keep_rate = format("%.2f", pre_week_user_ids.size > 0 ? weekly_keep_user_count.to_f / pre_week_user_ids.size : 0)
job_date = 1.days.ago
daily_statistic = DailyPlatformStatistic.find_or_initialize_by(date: job_date)
daily_statistic.weekly_keep_rate = weekly_keep_rate
daily_statistic.save
end
private
def current_week
Time.now.beginning_of_week..Time.now.end_of_day
end
def pre_week
# 7.days.ago.beginning_of_week..7.days.ago.beginning_of_week.end_of_week
Time.now.prev_week..Time.now.prev_week.end_of_week
end
end

View File

@ -1,35 +0,0 @@
class DailyProjectStatisticsJob < ApplicationJob
queue_as :cache
def perform
date = (Date.today - 1.days).to_s
daily_data_keys = $redis_cache.keys("v2-project-statistic:*-#{date}")
daily_data_keys.each do |key|
result = $redis_cache.hgetall(key)
project_id = key.gsub('v2-project-statistic:', '').gsub("-#{date}", '')
next unless Project.find_by_id(project_id).present?
visits = result["visits"].to_i
watchers = result["watchers"].to_i
praises = result["praises"].to_i
forks = result["forks"].to_i
issues = result["issues"].to_i
closed_issues = result["closed_issues"].to_i
pullrequests = result["pullrequests"].to_i
commits = result["commits"].to_i
score = visits *1 + watchers *5 + praises * 5 + forks * 10 + issues *5 + pullrequests * 10 + commits * 5
DailyProjectStatistic.create!(
project_id: project_id,
date: date,
score: score ,
visits: visits,
watchers: watchers,
praises: praises,
forks: forks,
issues: issues,
closed_issues: closed_issues,
pullrequests: pullrequests,
commits: commits
)
end
end
end

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