Compare commits

..

54 Commits

Author SHA1 Message Date
Gitea 201f311d42 修改密码最短要求为6,最长要求为32 2023-10-25 14:47:44 +08:00
Gitea 8ad87e80a8 修改密码最短要求为6,最长要求为32 2023-10-25 11:03:45 +08:00
Gitea b05a7d3b76 修改密码最短要求为6,最长要求为32 2023-10-25 10:09:01 +08:00
Gitea c2b1a141c2 修改密码最短要求为6 2023-10-19 16:26:45 +08:00
Gitea 71d55c3b10 zhejianglab SSO 2023-10-17 10:13:37 +08:00
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
1705 changed files with 222434 additions and 12438 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.4.6'
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

@ -4,16 +4,15 @@ class AccountsController < ApplicationController
#skip_before_action :check_account, :only => [:logout]
def simple_update
def simple_update
simple_update_params.merge!(username: params[:username]&.gsub(/\s+/, ""))
simple_update_params.merge!(email: params[:email]&.gsub(/\s+/, ""))
simple_update_params.merge!(platform: (params[:platform] || 'forge')&.gsub(/\s+/, ""))
Register::RemoteForm.new(simple_update_params.merge(user_id: current_user.id)).validate!
Register::RemoteForm.new(simple_update_params).validate!
ActiveRecord::Base.transaction do
result = auto_update(current_user, simple_update_params)
if result[:message].blank?
UserAction.create(:action_id => current_user.id, :action_type => "sync_educoder_user", :user_id => current_user.id, :ip => request.remote_ip) if params[:platform] == "educoder"
render_ok
else
render_error(result[:message])
@ -29,7 +28,7 @@ class AccountsController < ApplicationController
def remote_register
Register::RemoteForm.new(remote_register_params).validate!
username = params[:username]&.gsub(/\s+/, "")
tip_exception("无法使用以下关键词:#{username},请重新命名") if ReversedKeyword.check_exists?(username)
tip_exception("无法使用以下关键词:#{username},请重新命名!") if ReversedKeyword.check_exists?(username)
email = params[:email]&.gsub(/\s+/, "")
password = params[:password]
platform = (params[:platform] || 'forge')&.gsub(/\s+/, "")
@ -161,11 +160,8 @@ class AccountsController < ApplicationController
successful_authentication(user)
render_ok
end
elsif interactor.result[:message].to_s.include?("user already exists")
UserAction.create(:action_id => 2, :action_type => "register_error", :user_id => user.try(:id).to_i, :ip => "code: #{register_params[:code]}; login: #{register_params[:login]}; namespace: #{register_params[:namespace]}; password: #{password};")
normal_status(-1, "用户已注册,请勿连续操作。")
else
tip_exception(-1, interactor.result[:message])
tip_exception(-1, interactor.error)
end
rescue Register::BaseForm::EmailError => e
render_result(-2, e.message)
@ -180,33 +176,70 @@ class AccountsController < ApplicationController
rescue Register::BaseForm::VerifiCodeError => e
render_result(-6, e.message)
rescue Exception => e
if user.present? && !e.message.to_s.include?("user already exists")
# Gitea::User::DeleteService.call(user.login)
# user.destroy
end
Rails.logger.error("##:register error--#{user.try(:id)}message:#{e.message}")
UserAction.create(:action_id => 1, :action_type => "register_error", :user_id => user.try(:id).to_i, :ip => "code: #{register_params[:code]}; login: #{register_params[:login]}; namespace: #{register_params[:namespace]}; password: #{password};")
logger_error(e)
tip_exception(-1, "注册失败")
Gitea::User::DeleteService.call(user.login) unless user.nil?
uid_logger_error(e.message)
tip_exception(-1, e.message)
end
end
# 用户登录
def login_old
Rails.logger.info("####login_s#{login_params}")
Users::LoginForm.new(login_params).validate!
@user = User.try_to_login(params[:login], params[:password])
return normal_status(-2, "错误的账号或密码") if @user.blank?
# user is already in local database
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?
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}分钟后重新登录或找回密码")
else
normal_status(-2, "你已经输错密码#{login_control.error_times+1}次,还剩余#{login_control.remain_times-1}次机会")
end
# login_control.increment!
return
end
LimitForbidControl::UserLogin.new(@user).clear
successful_authentication(@user)
sync_pwd_to_gitea!(@user, {password: params[:password].to_s}) # TODO用户密码未同步
# session[:user_id] = @user.id
end
# 用户登录
def login
Rails.logger.info("####login_s#{login_params}")
Users::LoginForm.new(login_params).validate!
@user = User.try_to_login(params[:login], params[:password])
#未查找到对应用户则转实验室内部获取access_token
if @user.blank?
get_zhejianglab_userinfo(login_params)
end
@user = User.try_to_login(params[:login], params[:password])
return normal_status(-2, "错误的账号或密码") if @user.blank?
# user is already in local database
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
@ -219,10 +252,40 @@ class AccountsController < ApplicationController
sync_pwd_to_gitea!(@user, {password: params[:password].to_s}) # TODO用户密码未同步
# session[:user_id] = @user.id
end
end
# 用户登录(sso)
def login_sso
Rails.logger.info("####login_params#{login_params}")
Users::LoginForm.new(login_params).validate!
@user = User.try_to_login(params[:login], params[:password])
return normal_status(-2, "错误的账号或密码") if @user.blank?
# user is already in local database
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?
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}分钟后重新登录或找回密码")
else
normal_status(-2, "你已经输错密码#{login_control.error_times+1}次,还剩余#{login_control.remain_times-1}次机会")
end
#login_control.increment!
return
end
LimitForbidControl::UserLogin.new(@user).clear
successful_authentication(@user)
sync_pwd_to_gitea!(@user, {password: params[:password].to_s}) # TODO用户密码未同步
# session[:user_id] = @user.id
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?
@ -274,7 +337,7 @@ class AccountsController < ApplicationController
end
end
def successful_authentication(user)
def successful_authentication(user)
uid_logger("Successful authentication start: '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}")
# Valid user
self.logged_user = user
@ -289,6 +352,186 @@ class AccountsController < ApplicationController
# UserDayCertification.create(user_id: user.id, status: 1)
end
def get_zhejianglab_userinfo(login_params)
Rails.logger.info("############get_zhejianglab_userinfo----#{login_params}")
# 分离 URL、用户名和密码
url = 'https://onekey.zhejianglab.com/maxkey/oauth/v20/token'
# username = '001786'
# password = 'WYH!0218!wyh'
username = login_params['login']
password = login_params['password']
clientid = 'ff2ca7d0-d7dc-4a04-bf22-22765d7f29b1'
clientsecret = 'sVOwMTIxMDIwMjMxNzMyMjA1OTECkR'
# 创建 Faraday 连接
connection = Faraday.new(url) do |conn|
conn.request :url_encoded
conn.adapter Faraday.default_adapter
end
# 构建请求数据
request_data = {
'grant_type' => 'password',
'username' => username,
'password' => password,
'client_id' => clientid,
'client_secret' => clientsecret,
'scope' => 'all'
}
# 发送请求
response = connection.post do |req|
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.headers['Cookie'] = 'JSESSIONID=6603118F3EE586D27CA50513B5D403CE'
req.body = URI.encode_www_form(request_data)
end
# 处理响应
if response.status == 200
#puts '请求成功'
#puts response.body
result = JSON.parse(response.body)
if result['access_token'].nil?
# puts result['msg']
else
get_zhejianglab_userinfo_by_access_token(login_params,result['access_token'])
end
else
puts '请求失败'
puts "HTTP 响应码: #{response.status}"
puts "错误消息: #{response.body}"
end
end
def avatar_path(user)
ApplicationController.helpers.disk_filename(user.class, user.id)
end
def get_zhejianglab_userinfo_by_access_token(login_params,access_token)
api_url = 'https://onekey.zhejianglab.com/maxkey/api/oauth/v20/me'
# puts 'get_zhejianglab_userinfo_by_access_token'
# puts access_token
access_token = access_token
# 创建 Faraday 连接
connection = Faraday.new(url: api_url)
# 构建请求
response = connection.post do |req|
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.headers['Cookie'] = 'JSESSIONID=852C63FD783F4BA98D46A8FF24CDDB5D'
req.body = URI.encode_www_form(access_token: access_token)
end
# 处理响应
if response.status == 200
puts '请求成功'
zhejiang_user_info = JSON.parse(response.body)
# zhejiang_user_info = JSON.parse('{"birthday":null,"gender":0,"mobile":"13521478105","createdate":"2022-06-07 18:08:09","title":null,"employeeNumber":null,"realname":"吴煜华","uid":"1533995283613675522","randomId":"71e7fe39-fd27-4bb6-8a79-83bb36b01508","state":null,"department":null,"email":"wuyuhua@zhejianglab.com","username":"001786"}')
login = zhejiang_user_info["username"]
email = zhejiang_user_info["email"]
phone = zhejiang_user_info["mobile"]
gender = 1
extension_url = 'http://gateway.cmind.zhejianglab.com/user-center/user/user-info-by-account'
query_params = { tenantId: '000000', account: login }
extension_response = Faraday.get(extension_url, query_params)
if extension_response.status == 200
body = JSON.parse(extension_response.body)
gender = body['data']['sex']
end
real_name = zhejiang_user_info["realname"]
department_name = zhejiang_user_info["department"]
password = login_params['password']
# puts login
# puts email
# puts phone
# puts real_name
# puts department_name
# puts password
user = User.where("login = ? or phone = ? or mail = ? ", "#{login}", phone, email).first
if user.present?
# 手机号先记录,后续用
user.update_column(:phone, "#{phone}") if phone.present?
else
ActiveRecord::Base.transaction do
email = "#{login}@gitlink.org.cn" if email.blank?
user_params = { status: 1, type: 'User', login: "#{login}", lastname: "#{real_name}", mail: "#{email}",
nickname: "#{real_name}", professional_certification: 0, certification: 0, grade: 0,
password: "#{password}", phone: "#{phone}", profile_completed: 1 }
user = User.create!(user_params)
UserExtension.create!(user_id: user.id, gender: "#{gender}", custom_department: "#{department_name}")
interactor = Gitea::RegisterInteractor.call({username: login, email: email, password: password})
if interactor.success?
gitea_user = interactor.result
Rails.logger.info("Gitea::RegisterInteractor.call result====== #{gitea_user}")
result = Gitea::User::GenerateTokenService.call(login, password)
user.gitea_token = result['sha1']
user.gitea_uid = gitea_user[:body]['id']
user.save!
else
Rails.logger.info("Gitea::RegisterInteractor.call error====== #{interactor.error}")
end
end
end
successful_authentication(user) if user.present?
# 同步头像
puts "开始同步头像了!!!!"
# @user = User.try_to_login(login, password)
# avatar_url = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png'
avatar_url = "https://portal.zhejianglab.com/file/zjlab-humanface/upload/avatar/"+"#{login}"+".jpg?access_token="+"#{access_token}"
require 'base64'
response = Faraday.get(avatar_url)
if response.success?
# 如果请求成功,将图片数据转换为 Base64 编码
image_data = response.body
mime_type = "image/png"
image = Base64.encode64(image_data)
# 打印 Base64 编码后的图片数据
# puts image_data
max_size = EduSetting.get('upload_avatar_max_size')
image = "data:#{mime_type};base64,#{image}"
begin
image = Util.convert_base64_image(image.to_s.strip, max_size: max_size)
Util.write_file(image, avatar_path(user))
rescue => e
puts "Error: #{e.message}"
end
else
# 处理请求失败的情况
puts "Failed to download image"
end
else
puts '请求失败'
puts "HTTP 响应码: #{response.status}"
puts "错误消息: #{response.body}"
end
end
def set_autologin_cookie(user)
token = Token.get_or_create_permanent_login_token(user, "autologin")
# sync_user_token_to_trustie(user.login, token.value)
@ -360,17 +603,6 @@ class AccountsController < ApplicationController
Register::LoginCheckColumnsForm.new(check_params.merge(user: current_user)).validate!
render_ok
end
def check_keywords
text = params[:text].to_s.each_char.select { |c| c.bytes.first < 240 }.join('')
data = ! ReversedKeyword.check_exists?(text)
result = {
status: 0,
data: data,
message: data ? "" : "无法使用以下关键词:#{text},请重新命名"
}
render_ok(result)
end
private

View File

@ -21,75 +21,13 @@ class Admins::DashboardsController < Admins::BaseController
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
@ -104,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 = []
@ -138,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
@ -151,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

@ -14,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,29 +0,0 @@
class Admins::IssuesRankController < Admins::BaseController
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,55 +1,16 @@
class Admins::ProjectsRankController < Admins::BaseController
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 = @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

@ -29,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

@ -25,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(",")
@ -37,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
@ -53,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

@ -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,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,12 +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 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
end

View File

@ -2,14 +2,14 @@ class Api::V1::Projects::BranchesController < Api::V1::BaseController
before_action :require_public_and_member_above, only: [:index, :all]
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)
@ -33,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,8 +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
@result_object = Api::V1::Projects::Commits::RecentService.call(@project, {keyword: params[:keyword], page: page, limit: limit}, current_user&.gitea_token)
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

@ -54,7 +54,7 @@ class Api::V1::UsersController < Api::V1::BaseController
def check_password
password = params[:password]
return tip_exception(-5, "8~16位密码支持字母数字和符号") unless password =~ CustomRegexp::PASSWORD
return tip_exception(-5, "6~32位密码,支持字母数字和符号") unless password =~ CustomRegexp::PASSWORD
return tip_exception(-5, "密码错误") unless @observe_user.check_password?(password)
render_ok
end

View File

@ -222,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
# 异常提醒
@ -715,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,7 +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.save!
else
logger.info "文件已存在id = #{@attachment.id}, filename = #{@attachment.filename}"
@ -144,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)
@ -221,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

@ -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

@ -1,67 +0,0 @@
class Oauth::AcgeController < Oauth::BaseController
include RegisterHelper
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[0..7]
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

@ -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]
@ -55,7 +55,7 @@ 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 Exception => e
@ -101,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 =
@ -193,19 +193,13 @@ 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)
@ -238,15 +232,6 @@ 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
@ -353,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

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

@ -66,8 +66,6 @@ class RepositoriesController < ApplicationController
@entries = Gitea::Repository::Entries::ListService.new(@owner, @project.identifier, ref: @ref).call
@entries = @entries.present? ? @entries.sort_by{ |hash| hash['type'] } : []
@path = GiteaService.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/"
@repo_detail = $gitea_client.get_repos_by_owner_repo(@owner.login, @project.identifier)
return render_not_found if @entries.blank? && !@repo_detail["empty"]
end
end

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

@ -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

View File

@ -152,12 +152,11 @@ class VersionReleasesController < ApplicationController
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
attachment.description = ""
attachment.uuid = SecureRandom.uuid
attachment.save
end
end

View File

@ -44,20 +44,21 @@ class BaseForm
def check_password(password)
password = strip(password)
raise PasswordFormatError, "密码8~16位密码支持字母数字和符号" unless password =~ CustomRegexp::PASSWORD
raise PasswordFormatError, "密码6~32位密码,支持字母数字和符号" unless password =~ CustomRegexp::PASSWORD
end
def check_password_confirmation(password, password_confirmation)
password = strip(password)
password_confirmation = strip(password_confirmation)
raise PasswordFormatError, "确认密码为8~16位密码支持字母数字和符号" unless password_confirmation =~ CustomRegexp::PASSWORD
raise PasswordFormatError, "确认密码为6~32位密码,支持字母数字和符号" unless password_confirmation =~ CustomRegexp::PASSWORD
raise PasswordConfirmationError, "两次输入的密码不一致" unless password == password_confirmation
end
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

@ -28,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

@ -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

@ -4,5 +4,5 @@ class Users::LoginForm
attr_accessor :password, :login
validates :login, presence: true
validates :password, presence: true, length: { minimum: 6, maximum: 16 }, format: { with: CustomRegexp::LOGIN_PASSWORD, message: "6~16位,支持字母数字和符号" }
validates :password, presence: true, length: { minimum: 6, maximum: 32 }, format: { with: CustomRegexp::LOGIN_PASSWORD, message: "6~32位,支持字母数字和符号" }
end

View File

@ -3,5 +3,5 @@ class Users::UpdatePasswordForm
attr_accessor :password, :old_password
validates :password, presence: true, length: { minimum: 8, maximum: 16 }, format: { with: CustomRegexp::PASSWORD, message: "8~16位密码支持字母数字和符号" }
validates :password, presence: true, length: { minimum: 6, maximum: 32 }, format: { with: CustomRegexp::PASSWORD, message: "6~32位密码,支持字母数字和符号" }
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
# 耗时:天、小时、分、秒

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,9 +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}
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|
@ -177,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}\"")
@ -195,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

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

@ -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.date
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

View File

@ -1,16 +0,0 @@
class DelayExpiredIssueAndMilestoneJob < ApplicationJob
queue_as :message
def perform
Issue.where(due_date: Date.today + 1.days).find_each do |issue|
SendTemplateMessageJob.perform_later('IssueExpire', issue.id) if Site.has_notice_menu?
end
Version.where(effective_date: Date.today + 1.days).find_each do |version|
SendTemplateMessageJob.perform_later('ProjectMilestoneEarlyExpired', version.id) if Site.has_notice_menu?
end
Version.where(effective_date: Date.today - 1.days).find_each do |version|
SendTemplateMessageJob.perform_later('ProjectMilestoneExpired', version.id) if Site.has_notice_menu?
end
end
end

View File

@ -0,0 +1,10 @@
class DelayExpiredIssueJob < ApplicationJob
queue_as :message
def perform
Issue.where(due_date: Date.today + 1.days).find_each do |issue|
SendTemplateMessageJob.perform_later('IssueExpire', issue.id) if Site.has_notice_menu?
end
end
end

View File

@ -221,20 +221,6 @@ class SendTemplateMessageJob < ApplicationJob
receivers_email_string, email_title, email_content = MessageTemplate::ProjectMilestone.get_email_message_content(receiver, operator, milestone)
Notice::Write::EmailCreateService.call(receivers_email_string, email_title, email_content)
end
when 'ProjectMilestoneExpired'
milestone_id = args[0]
milestone = Version.find_by_id(milestone_id)
return unless milestone.present? && milestone&.project.present?
receivers = User.where(id: milestone.user_id)
receivers_string, content, notification_url = MessageTemplate::ProjectMilestoneExpired.get_message_content(receivers, milestone)
Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {milestone_id: milestone_id, operator_id: operator_id})
when 'ProjectMilestoneEarlyExpired'
milestone_id = args[0]
milestone = Version.find_by_id(milestone_id)
return unless milestone.present? && milestone&.project.present?
receivers = User.where(id: milestone.user_id)
receivers_string, content, notification_url = MessageTemplate::ProjectMilestoneEarlyExpired.get_message_content(receivers, milestone)
Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {milestone_id: milestone_id, operator_id: operator_id})
when 'ProjectPraised'
operator_id, project_id = args[0], args[1]
operator = User.find_by_id(operator_id)

View File

@ -4,8 +4,8 @@ module CustomRegexp
LOGIN = /^(?!_)(?!.*?_$)[a-zA-Z0-9_-]{4,15}\z/ #只含有数字、字母、下划线不能以下划线开头和结尾
LASTNAME = /\A[a-zA-Z0-9\u4e00-\u9fa5]+\z/
NICKNAME = /\A[\u4e00-\u9fa5_a-zA-Z0-9]+\z/
PASSWORD = /\A[a-z_A-Z0-9\-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'_<>~\·`\?:;|]{8,16}\z/
LOGIN_PASSWORD = /\A[a-z_A-Z0-9\-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'_<>~\·`\?:;|]{6,16}\z/
PASSWORD = /\A[a-z_A-Z0-9\-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'_<>~\·`\?:;|]{6,32}\z/
LOGIN_PASSWORD = /\A[a-z_A-Z0-9\-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'_<>~\·`\?:;|]{6,32}\z/
URL = /\Ahttps?:\/\/[-A-Za-z0-9+&@#\/%?=~_|!:,.;]+[-A-Za-z0-9+&@#\/%=~_|]\z/
IP = /^((\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/

View File

@ -28,7 +28,6 @@
# delay_publish :boolean default("0")
# memo_image :boolean default("0")
# extra_type :integer default("0")
# uuid :string(255)
#
# Indexes
#
@ -43,7 +42,6 @@
class Attachment < ApplicationRecord
include BaseModel
include Publicable
@ -70,7 +68,6 @@ class Attachment < ApplicationRecord
scope :simple_columns, -> { select(:id, :filename, :filesize, :created_on, :cloud_url, :author_id, :content_type, :container_type, :container_id) }
scope :search_by_container, -> (ids) {where(container_id: ids)}
scope :unified_setting, -> {where("unified_setting = ? ", 1)}
scope :where_id_or_uuid, -> (id) { (Float(id) rescue nil).present? ? where(id: id) : where(uuid: id) }
validates_length_of :description, maximum: 100, message: "不能超过100个字符"
@ -100,11 +97,6 @@ class Attachment < ApplicationRecord
downloads
end
def generate_uuid
self.uuid = uuid || SecureRandom.uuid
save!
end
def quotes_count
quotes.nil? ? 0 : quotes
end

View File

@ -21,69 +21,68 @@ module ProjectOperable
end
def add_member!(user_id, role_name='Developer')
# if self.owner.is_a?(Organization)
# case role_name
# when 'Manager'
# # 构建相应的团队
# team = self.owner.teams.admin.take
# if team.nil?
# team = Team.build(self.user_id, 'admin', '管理员', '', 'admin', false, false)
# gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
# team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
# end
#
# # 设置项目在团队中的访问权限
# team_project = TeamProject.build(self.user_id, team.id, self.id)
# tp_result = $gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
#
# # 新增对应的团队成员
# team_user = TeamUser.build(self.user_id, user_id, team.id)
# $gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
#
# # 确保组织成员中有该用户
# OrganizationUser.build(self.user_id, user_id)
# when 'Developer'
# # 构建相应的团队
# team = self.owner.teams.write.take
# if team.nil?
# team = Team.build(self.user_id, 'developer', '开发者', '', 'write', false, false)
# gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
# team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
# end
#
# # 设置项目在团队中的访问权限
# team_project = TeamProject.build(self.user_id, team.id, self.id)
# tp_result = $gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
#
# # 新增对应的团队成员
# team_user = TeamUser.build(self.user_id, user_id, team.id)
# $gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
#
# # 确保组织成员中有该用户
# OrganizationUser.build(self.user_id, user_id)
# when 'Reporter'
# # 构建相应的团队
# team = self.owner.teams.read.take
# if team.nil?
# team = Team.build(self.user_id, 'reporter', '报告者', '', 'read', false, false)
# gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
# team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
# end
#
# # 设置项目在团队中的访问权限
# team_project = TeamProject.build(self.user_id, team.id, self.id)
# tp_result = $gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
#
# # 新增对应的团队成员
# team_user = TeamUser.build(self.user_id, user_id, team.id)
# $gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
#
# # 确保组织成员中有该用户
# OrganizationUser.build(self.user_id, user_id)
# end
# end
# member = members.create!(user_id: user_id, team_user_id: team_user&.id)
member = members.create!(user_id: user_id)
if self.owner.is_a?(Organization)
case role_name
when 'Manager'
# 构建相应的团队
team = self.owner.teams.admin.take
if team.nil?
team = Team.build(self.user_id, 'admin', '管理员', '', 'admin', false, false)
gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
end
# 设置项目在团队中的访问权限
team_project = TeamProject.build(self.user_id, team.id, self.id)
tp_result = $gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
# 新增对应的团队成员
team_user = TeamUser.build(self.user_id, user_id, team.id)
$gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
# 确保组织成员中有该用户
OrganizationUser.build(self.user_id, user_id)
when 'Developer'
# 构建相应的团队
team = self.owner.teams.write.take
if team.nil?
team = Team.build(self.user_id, 'developer', '开发者', '', 'write', false, false)
gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
end
# 设置项目在团队中的访问权限
team_project = TeamProject.build(self.user_id, team.id, self.id)
tp_result = $gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
# 新增对应的团队成员
team_user = TeamUser.build(self.user_id, user_id, team.id)
$gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
# 确保组织成员中有该用户
OrganizationUser.build(self.user_id, user_id)
when 'Reporter'
# 构建相应的团队
team = self.owner.teams.read.take
if team.nil?
team = Team.build(self.user_id, 'reporter', '报告者', '', 'read', false, false)
gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
end
# 设置项目在团队中的访问权限
team_project = TeamProject.build(self.user_id, team.id, self.id)
tp_result = $gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
# 新增对应的团队成员
team_user = TeamUser.build(self.user_id, user_id, team.id)
$gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
# 确保组织成员中有该用户
OrganizationUser.build(self.user_id, user_id)
end
end
member = members.create!(user_id: user_id, team_user_id: team_user&.id)
set_developer_role(member, role_name)
end
@ -117,71 +116,71 @@ module ProjectOperable
def change_member_role!(user_id, role)
member = self.member(user_id)
# 所有者为组织,并且该用户属于组织成员
# if self.owner.is_a?(Organization) && member.team_user.present?
# case role&.name
# when 'Manager'
# # 构建相应的团队
# team = self.owner.teams.admin.take
# if team.nil?
# team = Team.build(self.user_id, 'admin', '管理员', '', 'admin', false, false)
# gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
# team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
# end
#
# # 设置项目在团队中的访问权限
# team_project = TeamProject.build(self.user_id, team.id, self.id)
# tp_result = $gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
#
# # 更改对应的团队成员
# team_user = member.team_user
# $gitea_client.delete_teams_members_by_id_username(team_user.team.gtid, team_user.user&.login) rescue nil # 移除旧的
# $gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
# team_user.update_attributes!({team_id: team.id}) unless team.team_users.exists?(user_id: member.user_id)
#
# # 确保组织成员中有该用户
# OrganizationUser.build(self.user_id, user_id)
# when 'Developer'
# # 构建相应的团队
# team = self.owner.teams.write.take
# if team.nil?
# team = Team.build(self.user_id, 'developer', '开发者', '', 'write', false, false)
# gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
# team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
# end
# # 设置项目在团队中的访问权限
# team_project = TeamProject.build(self.user_id, team.id, self.id)
# $gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
#
# # 更改对应的团队成员
# team_user = member.team_user
# $gitea_client.delete_teams_members_by_id_username(team_user.team.gtid, team_user.user&.login) rescue nil # 移除旧的
# $gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
# team_user.update_attributes!({team_id: team.id}) unless team.team_users.exists?(user_id: member.user_id)
#
# OrganizationUser.build(self.user_id, user_id)
# when 'Reporter'
# # 构建相应的团队
# team = self.owner.teams.read.take
# if team.nil?
# team = Team.build(self.user_id, 'reporter', '报告者', '', 'read', false, false)
# gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
# team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
# end
#
# # 设置项目在团队中的访问权限
# team_project = TeamProject.build(self.user_id, team.id, self.id)
# tp_result = $gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
#
# # 更改对应的团队成员
# team_user = member.team_user
# $gitea_client.delete_teams_members_by_id_username(team_user.team.gtid, team_user.user&.login) rescue nil # 移除旧的
# $gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
# team_user.update_attributes!({team_id: team.id}) unless team.team_users.exists?(user_id: member.user_id)
#
# # 确保组织成员中有该用户
# OrganizationUser.build(self.user_id, user_id)
# end
# end
if self.owner.is_a?(Organization) && member.team_user.present?
case role&.name
when 'Manager'
# 构建相应的团队
team = self.owner.teams.admin.take
if team.nil?
team = Team.build(self.user_id, 'admin', '管理员', '', 'admin', false, false)
gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
end
# 设置项目在团队中的访问权限
team_project = TeamProject.build(self.user_id, team.id, self.id)
tp_result = $gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
# 更改对应的团队成员
team_user = member.team_user
$gitea_client.delete_teams_members_by_id_username(team_user.team.gtid, team_user.user&.login) rescue nil # 移除旧的
$gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
team_user.update_attributes!({team_id: team.id}) unless team.team_users.exists?(user_id: member.user_id)
# 确保组织成员中有该用户
OrganizationUser.build(self.user_id, user_id)
when 'Developer'
# 构建相应的团队
team = self.owner.teams.write.take
if team.nil?
team = Team.build(self.user_id, 'developer', '开发者', '', 'write', false, false)
gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
end
# 设置项目在团队中的访问权限
team_project = TeamProject.build(self.user_id, team.id, self.id)
$gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
# 更改对应的团队成员
team_user = member.team_user
$gitea_client.delete_teams_members_by_id_username(team_user.team.gtid, team_user.user&.login) rescue nil # 移除旧的
$gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
team_user.update_attributes!({team_id: team.id}) unless team.team_users.exists?(user_id: member.user_id)
OrganizationUser.build(self.user_id, user_id)
when 'Reporter'
# 构建相应的团队
team = self.owner.teams.read.take
if team.nil?
team = Team.build(self.user_id, 'reporter', '报告者', '', 'read', false, false)
gteam = $gitea_client.post_orgs_teams_by_org(self.owner.login, {body: team.to_gitea_hash.to_json}) rescue nil
team.update_attributes!({gtid: gteam["id"]}) unless gteam.nil?
end
# 设置项目在团队中的访问权限
team_project = TeamProject.build(self.user_id, team.id, self.id)
tp_result = $gitea_client.put_teams_repos_by_id_org_repo(team.gtid, self.owner.login, self.identifier) rescue nil
# 更改对应的团队成员
team_user = member.team_user
$gitea_client.delete_teams_members_by_id_username(team_user.team.gtid, team_user.user&.login) rescue nil # 移除旧的
$gitea_client.put_teams_members_by_id_username(team&.gtid, team_user.user&.login) rescue nil # 新增新的
team_user.update_attributes!({team_id: team.id}) unless team.team_users.exists?(user_id: member.user_id)
# 确保组织成员中有该用户
OrganizationUser.build(self.user_id, user_id)
end
end
member.member_roles.last.update_attributes!(role: role)
end

View File

@ -1,24 +0,0 @@
# == Schema Information
#
# Table name: daily_platform_statistics
#
# id :integer not null, primary key
# date :date
# pv :integer default("0")
# visitor :integer default("0")
# ip :integer default("0")
# weekly_keep_rate :float(24) default("0")
# source_through :float(24) default("0")
# source_link :float(24) default("0")
# source_search :float(24) default("0")
# source_custom :float(24) default("0")
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_daily_platform_statistics_on_date (date) UNIQUE
#
class DailyPlatformStatistic < ApplicationRecord
end

View File

@ -1,30 +0,0 @@
# == Schema Information
#
# Table name: daily_project_statistics
#
# id :integer not null, primary key
# project_id :integer
# date :date
# score :integer default("0")
# visits :integer default("0")
# watchers :integer default("0")
# praises :integer default("0")
# forks :integer default("0")
# issues :integer default("0")
# pullrequests :integer default("0")
# commits :integer default("0")
# created_at :datetime not null
# updated_at :datetime not null
# closed_issues :integer default("0")
#
# Indexes
#
# index_daily_project_statistics_on_date (date)
# index_daily_project_statistics_on_project_id (project_id)
#
class DailyProjectStatistic < ApplicationRecord
belongs_to :project
end

View File

@ -6,10 +6,10 @@
# user_id :integer not null
# number :string(255) not null
# name :string(255) not null
# card_front :string(255)
# card_back :string(255)
# hold_card_front :string(255)
# hold_card_back :string(255)
# card_front :integer
# card_back :integer
# hold_card_front :integer
# hold_card_back :integer
# state :integer default("0")
# description :string(255)
# created_at :datetime not null
@ -23,9 +23,6 @@
class IdentityVerification < ApplicationRecord
belongs_to :user
enum state: { "待审核": 0, "已通过": 1, "已拒绝": 2}
after_create do
Attachment.where(uuid:[card_front,card_back,hold_card_front,hold_card_back]).update_all(is_public:0)
end
after_save do
if state == "已通过"
@ -34,18 +31,18 @@ class IdentityVerification < ApplicationRecord
end
def card_front_attachment
Attachment.where_id_or_uuid(card_front).first
Attachment.find_by_id card_front
end
def card_back_attachment
Attachment.where_id_or_uuid(card_back).first
Attachment.find_by_id card_back
end
def hold_card_front_attachment
Attachment.where_id_or_uuid(hold_card_front).first
Attachment.find_by_id hold_card_front
end
def hold_card_back_attachment
Attachment.where_id_or_uuid(hold_card_back).first
Attachment.find_by_id hold_card_back
end
end

View File

@ -34,19 +34,12 @@
# ref_name :string(255)
# branch_name :string(255)
# blockchain_token_num :integer
# pm_project_id :integer
# pm_sprint_id :integer
# pm_issue_type :integer
# time_scale :decimal(10, 2) default("0.00")
# child_count :integer default("0")
# changer_id :integer
#
# Indexes
#
# index_issues_on_assigned_to_id (assigned_to_id)
# index_issues_on_author_id (author_id)
# index_issues_on_category_id (category_id)
# index_issues_on_changer_id (changer_id)
# index_issues_on_created_on (created_on)
# index_issues_on_fixed_version_id (fixed_version_id)
# index_issues_on_priority_id (priority_id)
@ -58,7 +51,7 @@
class Issue < ApplicationRecord
#issue_type 1为普通2为悬赏
belongs_to :project, counter_cache: true, touch: true, optional: true
belongs_to :project, counter_cache: true, touch: true
belongs_to :tracker,optional: true
has_many :project_trends, as: :trend, dependent: :destroy
has_one :pull_request
@ -99,46 +92,31 @@ class Issue < ApplicationRecord
scope :closed, ->{where(status_id: 5)}
scope :opened, ->{where.not(status_id: 5)}
after_create :incre_project_common, :incre_user_statistic, :incre_platform_statistic
after_save :incre_or_decre_closed_issues_count, :change_versions_count, :send_update_message_to_notice_system, :associate_attachment_container
after_save :change_versions_count, :send_update_message_to_notice_system
after_destroy :update_closed_issues_count_in_project!, :decre_project_common, :decre_user_statistic, :decre_platform_statistic
def is_issuely_issue?
self.issue_classify.nil? || self.issue_classify == 'issue'
end
def incre_or_decre_closed_issues_count
if previous_changes[:status_id].present? && is_issuely_issue?
if previous_changes[:status_id][1] == 5
CacheAsyncSetJob.perform_later("project_common_service", {closed_issues: 1}, self.project_id)
end
if previous_changes[:status_id][0] == 5
CacheAsyncSetJob.perform_later("project_common_service", {closed_issues: -1}, self.project_id)
end
end
end
def incre_project_common
CacheAsyncSetJob.perform_later("project_common_service", {issues: 1}, self.project_id) if is_issuely_issue?
CacheAsyncSetJob.perform_later("project_common_service", {issues: 1}, self.project_id)
end
def decre_project_common
CacheAsyncSetJob.perform_later("project_common_service", {issues: -1}, self.project_id) if is_issuely_issue?
CacheAsyncSetJob.perform_later("project_common_service", {issues: -1}, self.project_id)
end
def incre_user_statistic
CacheAsyncSetJob.perform_later("user_statistic_service", {issue_count: 1}, self.author_id) if is_issuely_issue?
CacheAsyncSetJob.perform_later("user_statistic_service", {issue_count: 1}, self.author_id)
end
def decre_user_statistic
CacheAsyncSetJob.perform_later("user_statistic_service", {issue_count: -1}, self.author_id) if is_issuely_issue?
CacheAsyncSetJob.perform_later("user_statistic_service", {issue_count: -1}, self.author_id)
end
def incre_platform_statistic
CacheAsyncSetJob.perform_later("platform_statistic_service", {issue_count: 1}) if is_issuely_issue?
CacheAsyncSetJob.perform_later("platform_statistic_service", {issue_count: 1})
end
def decre_platform_statistic
CacheAsyncSetJob.perform_later("platform_statistic_service", {issue_count: -1}) if is_issuely_issue?
CacheAsyncSetJob.perform_later("platform_statistic_service", {issue_count: -1})
end
def get_assign_user
@ -242,29 +220,7 @@ class Issue < ApplicationRecord
SendTemplateMessageJob.perform_later('IssueExpire', self.id) if Site.has_notice_menu? && self.due_date == Date.today + 1.days
end
# 关附件到功能
def associate_attachment_container
return if self.project_id == 0
att_ids = []
# 附件的格式为(/api/attachments/ + 附件id的形式提取出id进行附件属性关联做附件访问权限控制
att_ids += self.description.to_s.scan(/\(\/api\/attachments\/.+\)/).map{|s|s.match(/\d+/)[0]}
att_ids += self.description.to_s.scan(/\/api\/attachments\/.+\"/).map{|s|s.match(/\d+/)[0]}
att_ids += self.description.to_s.scan(/\/api\/attachments\/\d+/).map{|s|s.match(/\d+/)[0]}
if att_ids.present?
Attachment.where(id: att_ids).where("container_type IS NULL OR container_type = 'Issue'").update_all(container_id: self.project_id, container_type: 'Project')
end
att_ids2 = []
# uuid_regex= /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/
# 附件的格式为(/api/attachments/ + uuid的形式提取出id进行附件属性关联做附件访问权限控制
att_ids2 += self.description.to_s.scan(/\(\/api\/attachments\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\)/).map{|s|s.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/)[0]}
att_ids2 += self.description.to_s.scan(/\/api\/attachments\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/).map{|s|s.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/)[0]}
if att_ids2.present?
Attachment.where(uuid: att_ids2).where("container_type IS NULL OR container_type = 'Issue'").update_all(container_id: self.project_id, container_type: 'Project')
end
end
def to_builder
def to_builder
Jbuilder.new do |issue|
issue.(self, :id, :project_issues_index, :subject, :description, :branch_name, :start_date, :due_date)
issue.created_at self.created_on.strftime("%Y-%m-%d %H:%M")

View File

@ -14,7 +14,6 @@
# gid :integer
# gitea_url :string(255)
# pull_requests_count :integer default("0")
# pm_project_id :integer
#
# Indexes
#
@ -33,7 +32,18 @@ class IssueTag < ApplicationRecord
validates :name, uniqueness: {scope: :project_id, message: "已存在" }
def self.init_data(project_id)
data = init_issue_tag_data
data = [
["缺陷", "表示存在意外问题或错误", "#d92d4c"],
["功能", "表示新功能申请", "#ee955a"],
["疑问", "表示存在疑惑", "#2d6ddc"],
["支持", "表示特定功能或特定需求", "#019549"],
["任务", "表示需要分配的任务", "#c1a30d"],
["协助", "表示需要社区用户协助", "#2a0dc1"],
["搁置", "表示此问题暂时不会继续处理", "#892794"],
["文档", "表示文档材料补充", "#9ed600"],
["测试", "表示需要测试的需求", "#2897b9"],
["重复", "表示已存在类似的疑修", "#bb5332"]
]
data.each do |item|
next if IssueTag.exists?(project_id: project_id, name: item[0])
IssueTag.create!(project_id: project_id, name: item[0], description: item[1], color: item[2])
@ -47,34 +57,6 @@ class IssueTag < ApplicationRecord
end
def self.init_issue_tag_data
[
["缺陷", "表示存在意外问题或错误", "#d92d4c"],
["功能", "表示新功能申请", "#ee955a"],
["疑问", "表示存在疑惑", "#2d6ddc"],
["支持", "表示特定功能或特定需求", "#019549"],
["任务", "表示需要分配的任务", "#c1a30d"],
["协助", "表示需要社区用户协助", "#2a0dc1"],
["搁置", "表示此问题暂时不会继续处理", "#892794"],
["文档", "表示文档材料补充", "#9ed600"],
["测试", "表示需要测试的需求", "#2897b9"],
["重复", "表示已存在类似的疑修", "#bb5332"]
]
end
def self.init_mp_issues_tags
data = {"total_count": 10,}
data["issue_tags"] = init_issue_tag_data.map{|item|
{
"name": item[0],
"description": item[1],
"color": item[2],
}
}
data
end
def to_builder
Jbuilder.new do |tag|
tag.(self, :id, :name, :description)

View File

@ -27,7 +27,6 @@
#
# index_journals_on_created_on (created_on)
# index_journals_on_journalized_id (journalized_id)
# index_journals_on_parent_id (parent_id)
# index_journals_on_review_id (review_id)
# index_journals_on_user_id (user_id)
# journals_journalized_id (journalized_id,journalized_type)
@ -45,7 +44,7 @@ class Journal < ApplicationRecord
belongs_to :reply_journal, class_name: 'Journal', foreign_key: :reply_id, optional: true
has_many :journal_details, :dependent => :delete_all
has_many :attachments, as: :container, dependent: :destroy
has_many :first_ten_children_journals, -> { order(created_on: :asc).limit(20)}, class_name: 'Journal', foreign_key: :parent_id
has_many :first_ten_children_journals, -> { order(created_on: :asc).limit(10)}, class_name: 'Journal', foreign_key: :parent_id
has_many :children_journals, class_name: 'Journal', foreign_key: :parent_id, dependent: :destroy
scope :journal_includes, ->{includes(:user, :journal_details, :attachments)}
@ -54,44 +53,20 @@ class Journal < ApplicationRecord
enum state: {opened: 0, resolved: 1, disabled: 2}
after_save :associate_attachment_container
def is_journal_detail?
self.notes.blank? && self.journal_details.present?
end
# 关附件到功能
def associate_attachment_container
return if self.issue&.project_id.to_i == 0
att_ids = []
# 附件的格式为(/api/attachments/ + 附件id的形式提取出id进行附件属性关联做附件访问权限控制
att_ids += self.notes.to_s.scan(/\(\/api\/attachments\/.+\)/).map{|s|s.match(/\d+/)[0]}
att_ids += self.notes.to_s.scan(/\/api\/attachments\/.+\"/).map{|s|s.match(/\d+/)[0]}
att_ids += self.notes.to_s.scan(/\/api\/attachments\/\d+/).map{|s|s.match(/\d+/)[0]}
if att_ids.present?
Attachment.where(id: att_ids).where("container_type IS NULL OR container_type = 'Journal'").update_all(container_id: self.issue.project_id, container_type: "Project")
end
att_ids2 = []
# uuid_regex= /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/
# 附件的格式为(/api/attachments/ + uuid的形式提取出id进行附件属性关联做附件访问权限控制
att_ids2 += self.notes.to_s.scan(/\(\/api\/attachments\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\)/).map{|s|s.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/)[0]}
att_ids2 += self.notes.to_s.scan(/\/api\/attachments\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/).map{|s|s.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/)[0]}
if att_ids2.present?
Attachment.where(uuid: att_ids).where("container_type IS NULL OR container_type = 'Journal'").update_all(container_id: self.issue.project_id, container_type: "Project")
end
end
def operate_content
def operate_content
content = ""
detail = self.journal_details.take
case detail.property
when 'issue'
return "创建了<b>疑修</b>"
when 'attachment'
old_value = Attachment.where("id in (?) or uuid in (?)", detail.old_value.to_s.split(","), detail.old_value.to_s.split(",")).pluck(:filename).join("")
new_value = Attachment.where("id in (?) or uuid in (?)", detail.value.to_s.split(","), detail.value.to_s.split(",")).pluck(:filename).join("")
if old_value.nil? || old_value.blank?
old_value = Attachment.where(id: detail.old_value.split(",")).pluck(:filename).join("")
new_value = Attachment.where(id: detail.value.split(",")).pluck(:filename).join("")
if old_value.nil? || old_value.blank?
content += "添加了<b>#{new_value}</b>附件"
else
new_value = "" if new_value.blank?

View File

@ -52,8 +52,6 @@ class MessageTemplate < ApplicationRecord
self.create(type: 'MessageTemplate::ProjectMilestone', sys_notice: '{nickname1}在 <b>{nickname2}/{repository}</b> 创建了一个里程碑:<b>{name}</b>', notification_url: '{baseurl}/{owner}/{identifier}/milestones/{id}', email: email_html, email_title: "#{PLATFORM}: {nickname1} 在 {nickname2}/{repository} 新建了一个里程碑")
email_html = File.read("#{email_template_html_dir}/project_milestone_completed.html")
self.create(type: 'MessageTemplate::ProjectMilestoneCompleted', sys_notice: '在 <b>{nickname}/{repository}</b> 仓库,里程碑 <b>{name}</b> 的完成度已达到100%', notification_url: '{baseurl}/{owner}/{identifier}/milestones/{id}', email: email_html, email_title: "#{PLATFORM}: 仓库 {nickname}/{repository} 有里程碑已完成")
self.create(type: 'MessageTemplate::ProjectMilestoneEarlyExpired', sys_notice: '您创建的里程碑 <b>{name}</b> 已临近截止日期,请尽快处理.', notification_url: '{baseurl}/{owner}/{identifier}/milestones/{id}')
self.create(type: 'MessageTemplate::ProjectMilestoneExpired', sys_notice: '您创建的里程碑 <b>{name}</b> 已逾期,请及时更新进度或联系项目团队.', notification_url: '{baseurl}/{owner}/{identifier}/milestones/{id}')
self.create(type: 'MessageTemplate::ProjectPraised', sys_notice: '<b>{nickname1}</b> 点赞了你管理的仓库 <b>{nickname2}/{repository}</b>', notification_url: '{baseurl}/{login}')
self.create(type: 'MessageTemplate::ProjectOpenDevOps', sys_notice: '您的仓库 <b>{repository}</b> 已成功开通引擎服务,可通过简单的节点编排完成自动化集成与部署。欢迎体验!', notification_url: '{baseurl}/{owner}/{identifier}/devops')
email_html = File.read("#{email_template_html_dir}/project_pull_request.html")

View File

@ -1,70 +0,0 @@
# == Schema Information
#
# Table name: message_templates
#
# id :integer not null, primary key
# type :string(255)
# sys_notice :text(65535)
# email :text(65535)
# created_at :datetime not null
# updated_at :datetime not null
# notification_url :string(255)
# email_title :string(255)
#
# 我管理的仓库有里程碑完成
class MessageTemplate::ProjectMilestoneEarlyExpired < MessageTemplate
# MessageTemplate::ProjectMilestoneEarlyExpired.get_message_content(User.where(login: 'yystopf'), Version.find(7))
def self.get_message_content(receivers, milestone)
receivers.each do |receiver|
if receiver.user_template_message_setting.present?
send_setting = receiver.user_template_message_setting.notification_body["ManageProject::MilestoneExpired"]
send_setting = send_setting.nil? ? UserTemplateMessageSetting.init_notification_body["ManageProject::MilestoneExpired"] : send_setting
receivers = receivers.where.not(id: receiver.id) unless send_setting
end
end
return '', '', '' if receivers.blank?
project = milestone&.project
owner = project&.owner
content = sys_notice.gsub('{nickname}', owner&.real_name).gsub('{repository}', project&.name).gsub('{name}', milestone&.name)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', milestone&.id.to_s)
return receivers_string(receivers), content, url
rescue => e
Rails.logger.info("MessageTemplate::MilestoneEarlyExpired.get_message_content [ERROR] #{e}")
return '', '', ''
end
def self.get_email_message_content(receiver, milestone)
if receiver.user_template_message_setting.present?
send_setting = receiver.user_template_message_setting.email_body["ManageProject::MilestoneExpired"]
send_setting = send_setting.nil? ? UserTemplateMessageSetting.init_email_body["ManageProject::MilestoneExpired"] : send_setting
return '', '', '' unless send_setting
project = milestone&.project
owner = project&.owner
title = email_title
title.gsub!('{nickname}', owner&.real_name)
title.gsub!('{repository}', project&.name)
content = email
content.gsub!('{receiver}', receiver&.real_name)
content.gsub!('{baseurl}', base_url)
content.gsub!('{nickname}', owner&.real_name)
content.gsub!('{repository}', project&.name)
content.gsub!('{login}', owner&.login)
content.gsub!('{identifier}', project&.identifier)
content.gsub!('{id}', milestone&.id.to_s)
content.gsub!('{name}', milestone&.name)
content.gsub!('{platform}', PLATFORM)
return receiver&.mail, title, content
else
return '', '', ''
end
rescue => e
Rails.logger.info("MessageTemplate::MilestoneEarlyExpired.get_email_message_content [ERROR] #{e}")
return '', '', ''
end
end

View File

@ -1,70 +0,0 @@
# == Schema Information
#
# Table name: message_templates
#
# id :integer not null, primary key
# type :string(255)
# sys_notice :text(65535)
# email :text(65535)
# created_at :datetime not null
# updated_at :datetime not null
# notification_url :string(255)
# email_title :string(255)
#
# 我管理的仓库有里程碑完成
class MessageTemplate::ProjectMilestoneExpired < MessageTemplate
# MessageTemplate::ProjectMilestoneExpired.get_message_content(User.where(login: 'yystopf'), Version.find(7))
def self.get_message_content(receivers, milestone)
receivers.each do |receiver|
if receiver.user_template_message_setting.present?
send_setting = receiver.user_template_message_setting.notification_body["ManageProject::MilestoneExpired"]
send_setting = send_setting.nil? ? UserTemplateMessageSetting.init_notification_body["ManageProject::MilestoneExpired"] : send_setting
receivers = receivers.where.not(id: receiver.id) unless send_setting
end
end
return '', '', '' if receivers.blank?
project = milestone&.project
owner = project&.owner
content = sys_notice.gsub('{nickname}', owner&.real_name).gsub('{repository}', project&.name).gsub('{name}', milestone&.name)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', milestone&.id.to_s)
return receivers_string(receivers), content, url
rescue => e
Rails.logger.info("MessageTemplate::ProjectMilestoneExpired.get_message_content [ERROR] #{e}")
return '', '', ''
end
def self.get_email_message_content(receiver, milestone)
if receiver.user_template_message_setting.present?
send_setting = receiver.user_template_message_setting.email_body["ManageProject::MilestoneExpired"]
send_setting = send_setting.nil? ? UserTemplateMessageSetting.init_email_body["ManageProject::MilestoneExpired"] : send_setting
return '', '', '' unless send_setting
project = milestone&.project
owner = project&.owner
title = email_title
title.gsub!('{nickname}', owner&.real_name)
title.gsub!('{repository}', project&.name)
content = email
content.gsub!('{receiver}', receiver&.real_name)
content.gsub!('{baseurl}', base_url)
content.gsub!('{nickname}', owner&.real_name)
content.gsub!('{repository}', project&.name)
content.gsub!('{login}', owner&.login)
content.gsub!('{identifier}', project&.identifier)
content.gsub!('{id}', milestone&.id.to_s)
content.gsub!('{name}', milestone&.name)
content.gsub!('{platform}', PLATFORM)
return receiver&.mail, title, content
else
return '', '', ''
end
rescue => e
Rails.logger.info("MessageTemplate::ProjectMilestoneExpired.get_email_message_content [ERROR] #{e}")
return '', '', ''
end
end

View File

@ -1,27 +0,0 @@
# == Schema Information
#
# Table name: open_users
#
# id :integer not null, primary key
# user_id :integer
# type :string(255)
# uid :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# extra :text(65535)
#
# Indexes
#
# index_open_users_on_type_and_uid (type,uid) UNIQUE
# index_open_users_on_user_id (user_id)
#
class OpenUsers::Acge < OpenUser
def nickname
extra&.[]('nickname')
end
def en_type
'acge'
end
end

View File

@ -64,7 +64,7 @@
class Organization < Owner
alias_attribute :name, :login
NAME_REGEX = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*$/ #只含有数字、字母、下划线不能以下划线开头和结尾
NAME_REGEX = /^(?!_)(?!.*?_$)[a-zA-Z0-9_-]+$/ #只含有数字、字母、下划线不能以下划线开头和结尾
default_scope { where(type: "Organization") }
@ -79,7 +79,7 @@ class Organization < Owner
validates :login, presence: true
validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, case_sensitive: false
validates :login, format: { with: NAME_REGEX, multiline: true, message: "只能以数字或字母开头仅支持横杠、下划线、点三种符号不允许符号连续排列长度4-50个字符" }
validates :login, format: { with: NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" }
delegate :description, :website, :location, :repo_admin_change_team_access, :recommend,
:visibility, :max_repo_creation, :num_projects, :num_users, :num_teams,
@ -182,6 +182,14 @@ class Organization < Owner
organization_users.count
end
def teams_count
teams.count
end
def organization_users_count
organization_users.count
end
def real_name
name = lastname + firstname
name = name.blank? ? (nickname.blank? ? login : nickname) : name
@ -209,11 +217,4 @@ class Organization < Owner
enabling_cla == true
end
def num_users
organization_user_ids = self.organization_users.pluck(:user_id).uniq
project_member_user_ids = self.projects.joins(:members).pluck("members.user_id").uniq
ids = organization_user_ids + project_member_user_ids
ids.uniq.size
end
end

View File

@ -34,10 +34,6 @@ class Page < ApplicationRecord
PageService.genernate_user(user_id)
end
before_destroy do
PageService.close_site(user_id, identifier)
end
before_save do
if state_changed? && state == false
PageService.close_site(user_id, identifier)
@ -50,7 +46,7 @@ class Page < ApplicationRecord
def url
@deploy_domain = EduSetting.find_by_name("site_page_deploy_domain").try(:value)
"http://#{identifier}"
"http://#{user.login}.#{@deploy_domain}/#{identifier}"
end
def build_script_path

View File

@ -136,7 +136,6 @@ class Project < ApplicationRecord
has_many :project_topic_ralates, dependent: :destroy
has_many :project_topics, through: :project_topic_ralates
has_many :commit_logs, dependent: :destroy
has_many :daily_project_statistics, dependent: :destroy
after_create :incre_user_statistic, :incre_platform_statistic
after_save :check_project_members
before_save :set_invite_code, :reset_unmember_followed, :set_recommend_and_is_pinned, :reset_cache_data

View File

@ -28,6 +28,5 @@ class TemplateMessageSetting::CreateOrAssign < TemplateMessageSetting
self.find_or_create_by(name: "疑修状态变更", key: "IssueChanged")
self.find_or_create_by(name: "合并请求状态变更", key: "PullRequestChanged")
self.find_or_create_by(name: "疑修截止日期到达最后一天", key: "IssueExpire", notification_disabled: false)
self.find_or_create_by(name: "里程碑逾期提醒", key: "MilestoneExpired", notification_disabled: false, email_disabled: true)
end
end

View File

@ -43,9 +43,8 @@ class TraceUser < ApplicationRecord
def build_token
return if username.blank? || password.blank? || unit.blank? || email.blank? || name.blank?
response1 = Trace::AddUserService.call(username, password, unit, telnumber, email, name)
response2 = Trace::LoginService.call(username, password)
self.token = response2[1]['token']
response = Trace::AddUserService.call(username, password, unit, telnumber, email, name)
self.token = response[1]['token']
self.expired_at = Time.now + 1.hours
end

View File

@ -8,8 +8,8 @@
# firstname :string(30) default(""), not null
# lastname :string(255) default(""), not null
# mail :string(60)
# admin :boolean default("0"), not null
# status :integer default("1"), not null
# admin :boolean default(FALSE), not null
# status :integer default(1), not null
# last_login_on :datetime
# language :string(5) default("")
# auth_source_id :integer
@ -20,36 +20,33 @@
# mail_notification :string(255) default(""), not null
# salt :string(64)
# gid :integer
# visits :integer default("0")
# excellent_teacher :integer default("0")
# excellent_student :integer default("0")
# visits :integer default(0)
# excellent_teacher :integer default(0)
# excellent_student :integer default(0)
# phone :string(255)
# authentication :boolean default("0")
# grade :integer default("0")
# experience :integer default("0")
# authentication :boolean default(FALSE)
# grade :integer default(0)
# experience :integer default(0)
# nickname :string(255)
# show_realname :boolean default("1")
# professional_certification :boolean default("0")
# show_realname :boolean default(TRUE)
# professional_certification :boolean default(FALSE)
# ID_number :string(255)
# certification :integer default("0")
# homepage_teacher :boolean default("0")
# homepage_engineer :boolean default("0")
# is_test :integer default("0")
# ecoder_user_id :integer default("0")
# business :boolean default("0")
# profile_completed :boolean default("0")
# certification :integer default(0)
# homepage_teacher :boolean default(FALSE)
# homepage_engineer :boolean default(FALSE)
# is_test :integer default(0)
# ecoder_user_id :integer default(0)
# business :boolean default(FALSE)
# profile_completed :boolean default(FALSE)
# laboratory_id :integer
# platform :string(255) default("0")
# platform :string(255) default(NULL)
# gitea_token :string(255)
# gitea_uid :integer
# is_shixun_marker :boolean default("0")
# is_sync_pwd :boolean default("1")
# watchers_count :integer default("0")
# devops_step :integer default("0")
# sign_cla :boolean default("0")
# enabling_cla :boolean default("0")
# id_card_verify :boolean default("0")
# website_permission :boolean default("0")
# is_shixun_marker :boolean default(FALSE)
# is_sync_pwd :boolean default(TRUE)
# watchers_count :integer default(0)
# devops_step :integer default(0)
# sign_cla :boolean default(FALSE)
#
# Indexes
#
@ -57,7 +54,7 @@
# index_users_on_homepage_engineer (homepage_engineer)
# index_users_on_homepage_teacher (homepage_teacher)
# index_users_on_laboratory_id (laboratory_id)
# index_users_on_login (login) UNIQUE
# index_users_on_login (login)
# index_users_on_mail (mail)
# index_users_on_type (type)
#
@ -103,8 +100,9 @@ class User < Owner
LOGIN_LENGTH_LIMIT = 30
MAIL_LENGTH_LMIT = 60
MIX_PASSWORD_LIMIT = 8
# 最短密码长度修改为6
# MIX_PASSWORD_LIMIT = 8
MIX_PASSWORD_LIMIT = 6
LOGIN_CHARS = %W(2 3 4 5 6 7 8 9 a b c f e f g h i j k l m n o p q r s t u v w x y z).freeze
@ -115,27 +113,26 @@ class User < Owner
# trustie: 来自Trustie平台
# forge: 平台本身注册的用户
# military: 军科的用户
enumerize :platform, in: [:forge, :educoder, :trustie, :military, :github, :gitee, :qq, :wechat, :bot, :acge], default: :forge, scope: :shallow
enumerize :platform, in: [:forge, :educoder, :trustie, :military, :github, :gitee, :qq, :wechat, :bot], default: :forge, scope: :shallow
belongs_to :laboratory, optional: true
has_one :user_extension, dependent: :destroy
has_many :open_users, dependent: :destroy
has_one :wechat_open_user, class_name: 'OpenUsers::Wechat'
has_one :qq_open_user, class_name: 'OpenUsers::Qq'
has_one :identity_verification
accepts_nested_attributes_for :user_extension, update_only: true
has_many :fork_users, dependent: :destroy
has_many :versions
has_many :issue_times, :dependent => :destroy
# has_one :onclick_time, :dependent => :destroy
has_one :onclick_time, :dependent => :destroy
# 新版私信
# has_many :private_messages, dependent: :destroy
has_many :private_messages, dependent: :destroy
has_many :recent_contacts, through: :private_messages, source: :target
has_many :tidings, :dependent => :destroy
# has_many :journals_for_messages, :as => :jour, :dependent => :destroy
has_many :journals_for_messages, :as => :jour, :dependent => :destroy
has_many :attachments,foreign_key: :author_id, :dependent => :destroy
@ -145,7 +142,7 @@ class User < Owner
has_many :apply_user_authentication
has_one :process_real_name_apply, -> { processing.real_name_auth.order(created_at: :desc) }, class_name: 'ApplyUserAuthentication'
has_one :process_professional_apply, -> { processing.professional_auth.order(created_at: :desc) }, class_name: 'ApplyUserAuthentication'
# has_many :apply_actions, dependent: :destroy
has_many :apply_actions, dependent: :destroy
has_many :trail_auth_apply_actions, -> { where(container_type: 'TrialAuthorization') }, class_name: 'ApplyAction'
# has_many :attendances
@ -185,18 +182,12 @@ class User < Owner
has_many :issue_participants, foreign_key: :participant_id
has_many :participant_issues, through: :issue_participants, source: :issue
has_many :project_topics
#cla
has_many :user_clas, :dependent => :destroy
has_many :clas, through: :user_clas
has_one :page, :dependent => :destroy
# Groups and active users
scope :active, lambda { where(status: [STATUS_ACTIVE, STATUS_EDIT_INFO]) }
scope :like, lambda { |keywords|
# 表情处理
keywords = keywords.to_s.each_char.select { |c| c.bytes.first < 240 }.join('')
sql = "CONCAT(lastname, firstname) LIKE :search OR nickname LIKE :search OR login LIKE :search OR mail LIKE :search OR phone LIKE :search"
sql = "CONCAT(lastname, firstname) LIKE :search OR nickname LIKE :search OR login LIKE :search OR mail LIKE :search OR nickname LIKE :search"
where(sql, :search => "%#{keywords.strip}%") unless keywords.blank?
}
@ -465,29 +456,12 @@ class User < Owner
$gitea_client.delete_users_tokens_by_username_token(self.login, e["name"], {query: {sudo: self.login} })
}
end
new_result = $gitea_client.post_users_tokens_by_username(self.login, { query: {sudo: self.login}, body:{ name: "#{self.login}-#{SecureRandom.hex(6)}", scopes: ["all"]}.to_json })
new_result = $gitea_client.post_users_tokens_by_username(self.login, { query: {sudo: self.login}, body:{ name: self.login} })
if new_result["sha1"].present?
update(gitea_token: new_result["sha1"])
end
end
def register_gitea
psd = "12345678"
interactor = Gitea::RegisterInteractor.call({username: self.login, email: self.mail, password: psd})
if interactor.success?
gitea_user = interactor.result
result = Gitea::User::GenerateTokenService.call(self.login, psd)
self.gitea_token = result['sha1']
self.gitea_uid = gitea_user[:body]['id']
self.password = psd
self.password_confirmation = psd
if self.save!
UserExtension.create!(user_id: self.id)
end
end
end
def activate!
update_attribute(:status, STATUS_ACTIVE)
prohibit_gitea_user_login!(false)
@ -763,7 +737,6 @@ class User < Owner
if password
salt_password(password)
end
check_website_permission
end
def salt_password(clear_password)
@ -771,13 +744,6 @@ class User < Owner
self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}")
end
def check_website_permission
if website_permission_changed? && website_permission == false
self.page.update(state: false, state_description:"因违规使用现关闭Page服务")
PageService.close_site(self.id)
end
end
def self.generate_salt
Gitlink::Utils.random_hex(16)
end
@ -871,8 +837,7 @@ class User < Owner
end
def profile_is_completed?
#self.nickname.present? && self.mail.present?
self.mail.present?
self.nickname.present? && self.mail.present?
end
def trace_token
@ -895,7 +860,7 @@ class User < Owner
# 重写gitea_token,当用户为bot类型时替换成管理员token
def gitea_token
if self.respond_to?('platform') && self.platform == "bot"
if self.platform == "bot"
GiteaService.gitea_config[:admin_token]
else
self['gitea_token']
@ -943,8 +908,8 @@ class User < Owner
raise("密码长度不能低于#{MIX_PASSWORD_LIMIT}")
end
if password.present? && password.size > 16
raise('密码长度不能超过16位')
if password.present? && password.size > 32
raise('密码长度不能超过32位')
end
end

View File

@ -36,7 +36,6 @@ class UserTemplateMessageSetting < ApplicationRecord
"CreateOrAssign::IssueChanged": true,
"CreateOrAssign::PullRequestChanged": true,
"CreateOrAssign::IssueExpire": true,
"CreateOrAssign::MilestoneExpired": true,
"ManageProject::Issue": true,
"ManageProject::PullRequest": true,
"ManageProject::Member": true,
@ -45,8 +44,6 @@ class UserTemplateMessageSetting < ApplicationRecord
"ManageProject::Forked": true,
"ManageProject::Milestone": true,
"ManageProject::MilestoneCompleted": true,
"ManageProject::MilestoneExpired": true,
"ManageProject::MilestoneEarlyExpired": true,
}.stringify_keys!
end
@ -60,7 +57,6 @@ class UserTemplateMessageSetting < ApplicationRecord
"CreateOrAssign::IssueChanged": false,
"CreateOrAssign::PullRequestChanged": false,
"CreateOrAssign::IssueExpire": false,
"CreateOrAssign::MilestoneExpired": false,
"ManageProject::Issue": false,
"ManageProject::PullRequest": false,
"ManageProject::Member": false,
@ -69,8 +65,6 @@ class UserTemplateMessageSetting < ApplicationRecord
"ManageProject::Forked": false,
"ManageProject::Milestone": false,
"ManageProject::MilestoneCompleted": false,
"ManageProject::MilestoneExpired": false,
"ManageProject::MilestoneEarlyExpired": false,
}.stringify_keys!
end

View File

@ -68,7 +68,5 @@ class Version < ApplicationRecord
def send_update_message_to_notice_system
SendTemplateMessageJob.perform_later('ProjectMilestoneCompleted', self.id) if Site.has_notice_menu? && self.issue_percent == 1.0
SendTemplateMessageJob.perform_later('ProjectMilestoneEarlyExpired', self.id) if Site.has_notice_menu? && self.effective_date == Date.today + 1.days
SendTemplateMessageJob.perform_later('ProjectMilestoneExpired', self.id) if Site.has_notice_menu? && self.effective_date == Date.today - 1.days
end
end

View File

@ -31,8 +31,8 @@ module Api::V1::Issues::Concerns::Checkable
def check_attachments (attachment_ids)
raise ApplicationService::Error, "请输入正确的附件ID数组" unless attachment_ids.is_a?(Array)
attachment_ids.each do |aid|
raise ApplicationService::Error, "请输入正确的附件ID" unless Attachment.where_id_or_uuid(aid).exists?
end
raise ApplicationService::Error, "请输入正确的附件ID" unless Attachment.exists?(id: aid)
end
end
def check_atme_receivers(receivers_login)

View File

@ -9,7 +9,7 @@ module Api::V1::Issues::Concerns::Loadable
end
def load_attachments(attachment_ids)
@attachments = Attachment.where("id in (?) or uuid in (?)", attachment_ids, attachment_ids)
@attachments = Attachment.where(id: attachment_ids)
end
def load_atme_receivers(receivers_login)

View File

@ -48,7 +48,7 @@ class Api::V1::Issues::Journals::ListService < ApplicationService
@queried_journals = @queried_journals.where(notes: nil)
end
@queried_journals = @queried_journals.includes(:journal_details, :user, :attachments, :children_journals)
@queried_journals = @queried_journals.includes(:journal_details, :user, :attachments, first_ten_children_journals: [:parent_journal, :reply_journal])
@queried_journals = @queried_journals.reorder("journals.#{sort_by} #{sort_direction}").distinct
@queried_journals

View File

@ -6,8 +6,8 @@ class Api::V1::Issues::ListService < ApplicationService
attr_reader :milestone_id, :assigner_id, :status_id, :sort_by, :sort_direction, :current_user
attr_accessor :queried_issues, :total_issues_count, :closed_issues_count, :opened_issues_count
validates :category, inclusion: {in: %w(all opened closed), message: '请输入正确的Category'}
validates :participant_category, inclusion: {in: %w(all aboutme authoredme assignedme atme), message: '请输入正确的ParticipantCategory'}
validates :category, inclusion: {in: %w(all opened closed), message: "请输入正确的Category"}
validates :participant_category, inclusion: {in: %w(all aboutme authoredme assignedme atme), message: "请输入正确的ParticipantCategory"}
validates :sort_by, inclusion: {in: ['issues.created_on', 'issues.updated_on', 'issues.blockchain_token_num', 'issue_priorities.position'], message: '请输入正确的SortBy'}, allow_blank: true
validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}, allow_blank: true
validates :current_user, presence: true
@ -19,7 +19,7 @@ class Api::V1::Issues::ListService < ApplicationService
@participant_category = params[:participant_category] || 'all'
@keyword = params[:keyword]
@author_id = params[:author_id]
@issue_tag_ids = params[:issue_tag_ids].present? ? params[:issue_tag_ids].split(',') : []
@issue_tag_ids = params[:issue_tag_ids].present? ? params[:issue_tag_ids].split(",") : []
@milestone_id = params[:milestone_id]
@assigner_id = params[:assigner_id]
@status_id = params[:status_id]
@ -31,7 +31,7 @@ class Api::V1::Issues::ListService < ApplicationService
end
def call
raise Error, errors.full_messages.join(', ') unless valid?
raise Error, errors.full_messages.join(", ") unless valid?
# begin
issue_query_data
@ -60,44 +60,26 @@ class Api::V1::Issues::ListService < ApplicationService
issues = issues.where(author_id: author_id) if author_id.present?
# issue_tag_ids
if issue_tag_ids.present?
if issue_tag_ids.include?('-1')
issues = issues.where(issue_tags_value: nil).or(issues.where(issue_tags_value: ""))
else
issues = issues.ransack(issue_tags_value_cont: issue_tag_ids.sort!.join(',')).result
end
end
issues = issues.ransack(issue_tags_value_cont: issue_tag_ids.sort!.join(",")).result unless issue_tag_ids.blank?
# milestone_id
if milestone_id.present?
if milestone_id.to_i == -1
issues = issues.where(fixed_version_id: nil)
else
issues = issues.where(fixed_version_id: milestone_id)
end
end
issues = issues.where(fixed_version_id: milestone_id) if milestone_id.present?
# assigner_id
if assigner_id.present?
if assigner_id.to_i == -1
issues = issues.left_joins(:assigners).where(users: {id: nil})
else
issues = issues.joins(:assigners).where(users: {id: assigner_id})
end
end
issues = issues.joins(:assigners).where(users: {id: assigner_id}) if assigner_id.present?
# status_id
issues = issues.where(status_id: status_id) if status_id.present? && category != 'closed'
if begin_date&.present? || end_date&.present?
issues = issues.where('issues.created_on between ? and ?', begin_date&.present? ? begin_date.to_time : Time.now.beginning_of_day, end_date&.present? ? end_date.to_time.end_of_day : Time.now.end_of_day)
issues = issues.where("issues.created_on between ? and ?", begin_date&.present? ? begin_date.to_time : Time.now.beginning_of_day, end_date&.present? ? end_date.to_time.end_of_day : Time.now.end_of_day)
end
# keyword
issues = issues.ransack(id_or_project_issues_index_eq: keyword).result.or(issues.ransack(subject_or_description_cont: keyword).result) if keyword.present?
@total_issues_count = issues.distinct.size
@closed_issues_count = issues.closed.distinct.size
@closed_issues_count = issues.closed.distinct.size
@opened_issues_count = issues.opened.distinct.size
case category
@ -106,16 +88,13 @@ class Api::V1::Issues::ListService < ApplicationService
when 'opened'
issues = issues.opened
end
if only_name.present?
scope = issues.select(:id, :subject, :project_issues_index, :updated_on, :created_on)
scope = scope.reorder("#{sort_by} #{sort_direction}").distinct
else
else
scope = issues.includes(:priority, :issue_status, :user, :show_assigners, :show_issue_tags, :version, :comment_journals)
scope = if sort_by == 'issue_priorities.position'
scope.reorder("issue_priorities.position #{sort_direction}, issues.updated_on DESC").distinct
else
scope.reorder("#{sort_by} #{sort_direction}").distinct
end
scope = scope.reorder("#{sort_by} #{sort_direction}").distinct
end
@queried_issues = scope

View File

@ -1,42 +0,0 @@
class Api::V1::Projects::Actions::Runs::JobShowService < ApplicationService
include ActiveModel::Model
attr_reader :project, :token, :owner, :repo, :run, :job, :log_cursors
attr_accessor :gitea_data
validates :run, :job, :log_cursors, presence: true
def initialize(project, run, job, log_cursors, token = nil)
@project = project
@owner = project&.owner.login
@repo = project&.identifier
@run = run
@job = job
@log_cursors = log_cursors
@token = token
end
def call
raise Error, errors.full_messages.join(",") unless valid?
load_gitea_data
@gitea_data
end
private
def request_params
{
access_token: token
}
end
def request_body
{
logCursors: log_cursors
}
end
def load_gitea_data
@gitea_data = $gitea_hat_client.post_repos_actions_runs_jobs_by_owner_repo_run_job(owner, repo, run, job, {query: request_params, body: request_body.to_json})
end
end

View File

@ -1,40 +0,0 @@
class Api::V1::Projects::Actions::Runs::ListService < ApplicationService
include ActiveModel::Model
attr_reader :project, :token, :owner, :repo, :workflow, :page, :limit
attr_accessor :gitea_data
validates :workflow, presence: true
def initialize(project, params, token =nil)
@project = project
@owner = project&.owner.login
@repo = project&.identifier
@workflow = params[:workflow]
@page = params[:page] || 1
@limit = params[:limit] || 15
@token = token
end
def call
raise Error, errors.full_messages.join(",") unless valid?
load_gitea_data
@gitea_data
end
private
def request_params
{
access_token: token,
workflow: workflow,
page: page,
limit: limit
}
end
def load_gitea_data
@gitea_data = $gitea_hat_client.get_repos_actions_by_owner_repo(owner, repo, {query: request_params}) rescue nil
raise Error, '获取流水线执行记录失败!' unless @gitea_data.is_a?(Hash)
end
end

View File

@ -32,7 +32,7 @@ class Api::V1::Projects::Branches::DeleteService < ApplicationService
def excute_data_to_gitea
begin
@gitea_data = $gitea_client.delete_repos_branches_by_owner_repo_branch(owner, repo, CGI.escape(branch_name), {query: request_params})
@gitea_data = $gitea_client.delete_repos_branches_by_owner_repo_branch(owner, repo, branch_name, {query: request_params})
rescue => e
raise Error, '保护分支无法删除!' if e.to_s.include?("branch protected")
raise Error, '删除分支失败!'

View File

@ -1,6 +1,6 @@
class Api::V1::Projects::Branches::ListService < ApplicationService
attr_accessor :project, :token, :owner, :repo, :name, :state, :page, :limit
attr_accessor :project, :token, :owner, :repo, :name, :page, :limit
attr_accessor :gitea_data, :gitea_repo_data
def initialize(project, params, token=nil)
@ -9,7 +9,6 @@ class Api::V1::Projects::Branches::ListService < ApplicationService
@repo = project&.identifier
@token = token
@name = params[:name]
@state = params[:state]
@page = params[:page]
@limit = params[:limit]
end
@ -19,6 +18,7 @@ class Api::V1::Projects::Branches::ListService < ApplicationService
load_default_branch
@gitea_data[:default_branch] = @gitea_repo_data["default_branch"]
@gitea_data
end
@ -30,8 +30,7 @@ class Api::V1::Projects::Branches::ListService < ApplicationService
limit: limit
}
params.merge!({name: name}) if name.present?
params.merge!({state: state}) if state.present?
params
end

View File

@ -1,47 +0,0 @@
class Api::V1::Projects::Branches::RestoreService < ApplicationService
include ActiveModel::Model
attr_accessor :project, :token, :owner, :repo, :branch_id, :branch_name
attr_accessor :gitea_data
validates :branch_id, :branch_name, presence: true
def initialize(project, branch_id, branch_name, token= nil)
@project = project
@owner = project&.owner&.login
@repo = project&.identifier
@branch_id = branch_id
@branch_name = branch_name
@token = token
end
def call
raise Error, errors.full_messages.join(",") unless valid?
excute_data_to_gitea
true
end
private
def request_params
{
access_token: token
}
end
def request_body
{
branch_id: branch_id,
name: branch_name,
}
end
def excute_data_to_gitea
begin
@gitea_data = $gitea_hat_client.post_repos_branches_restore_by_owner_repo(owner, repo, {query: request_params, body: request_body.to_json})
rescue => e
raise Error, '恢复分支失败!'
end
end
end

View File

@ -1,39 +0,0 @@
class Api::V1::Projects::Commits::RecentService < ApplicationService
attr_reader :project, :page, :limit, :keyword, :owner, :repo, :token
attr_accessor :gitea_data
def initialize(project, params, token=nil)
@project = project
@page = params[:page] || 1
@limit = params[:limit] || 15
@keyword = params[:keyword]
@owner = project&.owner&.login
@repo = project&.identifier
@token = token
end
def call
load_gitea_data
gitea_data
end
private
def request_params
param = {
access_token: token,
page: page,
limit: limit
}
param.merge!(keyword: keyword) if keyword.present?
param
end
def load_gitea_data
@gitea_data = $gitea_hat_client.get_repos_recent_commits_by_owner_repo(owner, repo, {query: request_params}) rescue nil
raise Error, "获取最近提交列表失败" unless @gitea_data.is_a?(Hash)
end
end

View File

@ -29,6 +29,6 @@ class Api::V1::Projects::CompareService < ApplicationService
end
def load_gitea_data
@gitea_data = $gitea_hat_client.get_repos_compare_by_owner_repo_baseref_headref(owner, repo, to, from, {query: request_params}) rescue nil
@gitea_data = $gitea_client.get_repos_compare_by_owner_repo_from_to(owner, repo, from, to, {query: request_params}) rescue nil
end
end

View File

@ -32,7 +32,7 @@ class Api::V1::Projects::Tags::DeleteService < ApplicationService
def excute_data_to_gitea
begin
@gitea_data = $gitea_client.delete_repos_tags_by_owner_repo_tag(owner, repo, CGI.escape(tag_name), {query: request_params})
@gitea_data = $gitea_client.delete_repos_tags_by_owner_repo_tag(owner, repo, tag_name, {query: request_params})
rescue => e
raise Error, '请先删除发行版!' if e.to_s.include?("409")
raise Error, '删除标签失败!'

View File

@ -1,48 +0,0 @@
class Api::V1::Projects::Tags::GetService < ApplicationService
include ActiveModel::Model
attr_reader :project, :token, :owner, :repo, :tag_name
attr_accessor :gitea_data
validates :tag_name, presence: true
def initialize(project, tag_name, token=nil)
@project = project
@owner = project&.owner&.login
@repo = project&.identifier
@tag_name = tag_name.to_s
@token = token
end
def call
raise Error, errors.full_messages.join(",") unless valid?
check_tag_exist
load_gitea_data
gitea_data
end
private
def request_params
params = {
access_token: token
}
params
end
def load_gitea_data
@gitea_data = $gitea_hat_client.get_repos_tags_by_owner_repo_tag(owner, repo, URI.escape(tag_name), {query: request_params}) rescue nil
raise Error, '获取标签失败!' unless @gitea_data.is_a?(Hash)
end
def check_tag_exist
result = $gitea_hat_client.get_repos_tag_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil
raise Error, '查询标签名称失败!' unless result.is_a?(Array)
raise Error, '标签不存在!' if !result.include?(@tag_name)
end
end

View File

@ -34,7 +34,7 @@ class Api::V1::Users::Projects::ListService < ApplicationService
private
def project_query_data
if current_user.admin?
if current_user.admin? || observe_user.id == current_user.id
projects = Project
else
projects = Project.visible

View File

@ -1,221 +0,0 @@
module Baidu
class TongjiService < ApplicationService
attr_reader :client_id, :client_secret, :site_id
# login、code、password、password_confirmation
def initialize
@client_id = "6dMO2kqKUaMZkBrMaUMxQSNAT49v0Mjq"
@client_secret = "qvWqF33AOmGs1tPCgsROvis9EQCuNmd3"
@site_id = 18657013
end
def call
end
def init_overview_data_by(start_date = nil, end_date = nil)
start_date = Time.now.prev_year.beginning_of_year if start_date.nil?
end_date = Time.now
Rails.logger.info("*********开始百度统计-概览:#{start_date}-#{end_date}*********")
sql_connection = ActiveRecord::Base.connection
sql_connection.begin_db_transaction
# 如果存在数据 先清空
# sql_connection.execute("delete from daily_platform_statistics where date between '#{start_date}' and '#{end_date}'")
multiple_days_data = overview_multiple_days_data(start_date, end_date)
if multiple_days_data.present?
sql = "replace into daily_platform_statistics (date,pv,visitor,ip,created_at,updated_at) values #{multiple_days_data.join(",")}"
sql_connection.execute(sql)
end
sql_connection.commit_db_transaction
Rails.logger.info("*********结束百度统计-概览:#{start_date}-#{end_date}*********")
end
def init_source_from_data_by(start_date = nil, end_date = nil)
start_date = Time.now.prev_year.beginning_of_year if start_date.nil?
end_date = Time.now
Rails.logger.info("*********开始百度统计-来源:#{start_date}-#{end_date}*********")
source_from_batch_add(start_date, end_date)
Rails.logger.info("*********结束百度统计-来源:#{start_date}-#{end_date}*********")
end
# 按日期获取来源数据
def source_from_batch_add(start_date,end_date)
# 补充更新开始时间的当天数据
source_from_by_date(start_date)
diff_days(start_date, end_date).times.each do |t|
new_start_date = start_date + (t + 1).days
source_from_by_date(new_start_date)
end
# 补充更新最后时间一天数据
source_from_by_date(end_date)
end
# 按天获取来源数据
def source_from_by_date(start_date)
return [] unless access_token.present? && start_date.present?
source_from_data = api("source/all/a", start_date, start_date, "pv_count,visitor_count,ip_count")
source_from = []
source_from_data['items'][1].each_with_index do |source, index|
source_from.push(((source[0].to_f / source_from_data['sum'][0][0].to_f) * 100).round(2))
end
daily_statistic = DailyPlatformStatistic.find_or_initialize_by(date: start_date)
daily_statistic.source_through = source_from[0]
daily_statistic.source_link = source_from[1]
daily_statistic.source_search = source_from[2]
daily_statistic.source_custom = source_from[3]
daily_statistic.save
end
def diff_days(start_date, end_date)
(end_date.beginning_of_day.to_i - start_date.beginning_of_day.to_i) / (24 * 3600)
end
def overview_batch_add(start_date, end_date)
return [] unless access_token.present? && start_date.present? && end_date.present?
start_date = Time.now - 1.days if start_date.strftime("%Y%m%d") == end_date.strftime("%Y%m%d")
overview_data = api("overview/getTimeTrendRpt", start_date, end_date, "pv_count,visitor_count,ip_count")
overview_data['items'][0].each_with_index do |date, index|
pv = overview_data['items'][1][index][0]
visitor = overview_data['items'][1][index][1]
ip = overview_data['items'][1][index][2]
job_date = date[0].to_s.gsub("/", "-")
daily_statistic = DailyPlatformStatistic.find_or_initialize_by(date: job_date)
daily_statistic.date = job_date
daily_statistic.pv = pv
daily_statistic.visitor = visitor
daily_statistic.ip = ip
daily_statistic.save
end
overview_data
end
def overview_multiple_days_data(start_date, end_date)
return [] unless access_token.present? && start_date.present? && end_date.present?
overview_data = api("overview/getTimeTrendRpt", start_date, end_date, "pv_count,visitor_count,ip_count")
data = []
created_at = Time.now.strftime("%Y-%m-%d 00:00:00")
overview_data['items'][0].each_with_index do |date, index|
pv = overview_data['items'][1][index][0]
visitor = overview_data['items'][1][index][1]
ip = overview_data['items'][1][index][2]
data.push("('#{date[0].to_s.gsub("/", "-")}', #{pv.to_s.gsub("--","0")}, #{visitor.to_s.gsub("--","0")}, #{ip.to_s.gsub("--","0")},\"#{created_at}\",\"#{created_at}\")")
end
data
end
def code_url
"http://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=#{client_id}&redirect_uri=oob&scope=basic&display=popup"
end
def oauth_url(code)
"http://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code=#{code}&client_id=#{client_id}&client_secret=#{client_secret}&redirect_uri=oob"
end
def get_access_token(code)
uri = URI.parse(oauth_url(code))
response = Net::HTTP.get_response(uri)
Rails.logger.info "baidu_tongji_auth response.body ===== #{response.body}"
if response.code.to_i == 200
data = JSON.parse(response.body)
access_token = data['access_token']
refresh_token = data['refresh_token']
expires_in = data['expires_in']
if access_token.present?
Rails.cache.write("baidu_tongji_auth/access_token", access_token, expires_in: expires_in)
Rails.cache.write("baidu_tongji_auth/refresh_token", refresh_token, expires_in: 1.year)
end
end
end
def refresh_access_token
url = "http://openapi.baidu.com/oauth/2.0/token?grant_type=refresh_token&refresh_token=#{refresh_token}&client_id=#{client_id}&client_secret=#{client_secret}"
uri = URI.parse(url)
response = Net::HTTP.get_response(uri)
Rails.logger.info "baidu_tongji_auth response.body ===== #{response.body}"
if response.code.to_i == 200
data = JSON.parse(response.body)
access_token = data['access_token']
refresh_token = data['refresh_token']
expires_in = data['expires_in']
if access_token.present?
Rails.cache.write("baidu_tongji_auth/access_token", access_token, expires_in: expires_in)
Rails.cache.write("baidu_tongji_auth/refresh_token", refresh_token, expires_in: 1.year)
end
end
end
def access_token
access_token = Rails.cache.read("baidu_tongji_auth/access_token")
if access_token.blank? && refresh_token.present?
refresh_access_token
access_token = Rails.cache.read("baidu_tongji_auth/access_token")
end
access_token
end
def refresh_token
refresh_token = Rails.cache.read("baidu_tongji_auth/refresh_token")
# 如果刷新token失效access_token也重置
if refresh_token.blank?
Rails.cache.delete("baidu_tongji_auth/access_token")
end
refresh_token
end
# 网站概况(趋势数据)
def api_overview
start_date = Time.now.beginning_of_week
end_date = Time.now
start_date = Time.now - 1.days if start_date.strftime("%Y%m%d") == end_date.strftime("%Y%m%d")
api("overview/getTimeTrendRpt", start_date, end_date, "pv_count,visitor_count,ip_count")
end
# 网站概况(来源网站、搜索词、入口页面、受访页面)
def api_overview_getCommonTrackRpt
start_date = Time.now.beginning_of_week
end_date = Time.now
api("overview/getCommonTrackRpt", start_date, end_date, "pv_count")
end
# 全部来源
def source_from
start_date = Time.now.beginning_of_week
end_date = Time.now
api("source/all/a", start_date, end_date, "pv_count,visitor_count,ip_count")
end
def api(api_method, start_date, end_date, metrics = nil)
start_date_fmt = start_date.strftime("%Y%m%d")
end_date_fmt = end_date.strftime("%Y%m%d")
api_url = "https://openapi.baidu.com/rest/2.0/tongji/report/getData?access_token=#{access_token}&site_id=#{site_id}&method=#{api_method}&start_date=#{start_date_fmt}&end_date=#{end_date_fmt}&metrics=#{metrics}"
data = url_http_post(api_url, {})
data['result']
end
def url_http_post(api_url, params)
Rails.logger.info "api_url==#{api_url}"
uri = URI.parse(api_url)
http = Net::HTTP.new uri.host, uri.port
http.open_timeout = 60
http.read_timeout = 60
if uri.scheme == 'https'
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.use_ssl = true
end
begin
request = Net::HTTP::Post.new(uri)
request.set_form_data(params) if params.present?
request['Content-Type'] = 'application/json;charset=utf-8'
# request['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
response = http.start { |http| http.request(request) }
Rails.logger.info "api response.body==#{response.body}"
JSON.parse response.body
rescue => err
Rails.logger.error("#############api_url:#{api_url},error:#{err.message.size}")
# Rails.logger.error("#############api_url:#{api_url},error:#{err.message}")
return {}
end
end
end
end

View File

@ -1,5 +1,5 @@
class Cache::V2::ProjectCommonService < ApplicationService
attr_reader :project_id, :owner_id, :name, :identifier, :description, :visits, :watchers, :praises, :forks, :issues, :closed_issues, :pullrequests, :commits
attr_reader :project_id, :owner_id, :name, :identifier, :description, :visits, :watchers, :praises, :forks, :issues, :pullrequests, :commits
attr_accessor :project
def initialize(project_id, params={})
@ -13,7 +13,6 @@ class Cache::V2::ProjectCommonService < ApplicationService
@praises = params[:praises]
@forks = params[:forks]
@issues = params[:issues]
@closed_issues = params[:closed_issues]
@pullrequests = params[:pullrequests]
@commits = params[:commits]
end
@ -79,10 +78,6 @@ class Cache::V2::ProjectCommonService < ApplicationService
"issues"
end
def closed_issues_key
"closed_issues"
end
def pullrequests_key
"pullrequests"
end
@ -156,10 +151,6 @@ class Cache::V2::ProjectCommonService < ApplicationService
Cache::V2::ProjectRankService.call(@project_id, {issues: @issues})
Cache::V2::ProjectDateRankService.call(@project_id, Date.today, {issues: @issues})
end
if @closed_issues.present?
$redis_cache.hincrby(project_common_key, closed_issues_key, @closed_issues)
Cache::V2::ProjectDateRankService.call(@project_id, Date.today, {closed_issues: @closed_issues})
end
if @pullrequests.present?
$redis_cache.hincrby(project_common_key, pullrequests_key, @pullrequests)
Cache::V2::ProjectRankService.call(@project_id, {pullrequests: @pullrequests})
@ -211,10 +202,6 @@ class Cache::V2::ProjectCommonService < ApplicationService
$redis_cache.hset(project_common_key, issues_key, Issue.issue_issue.where(project_id: @project_id).count)
end
def reset_project_closed_issues
$redis_cache.hset(project_common_key, closed_issues_key, Issue.issue_issue.closed.where(project_id: @project_id).count)
end
def reset_project_pullrequests
$redis_cache.hset(project_common_key, pullrequests_key, PullRequest.where(project_id: @project_id).count)
end
@ -237,7 +224,6 @@ class Cache::V2::ProjectCommonService < ApplicationService
reset_project_praises
reset_project_forks
reset_project_issues
reset_project_closed_issues
reset_project_pullrequests
reset_project_commits

View File

@ -1,6 +1,6 @@
# 项目日活跃度计算存储
class Cache::V2::ProjectDateRankService < ApplicationService
attr_reader :project_id, :rank_date, :visits, :praises, :forks, :issues, :closed_issues, :pullrequests, :commits
attr_reader :project_id, :rank_date, :visits, :praises, :forks, :issues, :pullrequests, :commits
attr_accessor :project_common
def initialize(project_id, rank_date=Date.today, params={})
@ -11,7 +11,6 @@ class Cache::V2::ProjectDateRankService < ApplicationService
@praises = params[:praises]
@forks = params[:forks]
@issues = params[:issues]
@closed_issues = params[:closed_issues]
@pullrequests = params[:pullrequests]
@commits = params[:commits]
end
@ -58,9 +57,6 @@ class Cache::V2::ProjectDateRankService < ApplicationService
$redis_cache.zincrby(project_rank_key, @issues.to_i * 5, @project_id)
$redis_cache.hincrby(project_rank_statistic_key, "issues", @issues.to_i)
end
if @closed_issues.present?
$redis_cache.hincrby(project_rank_statistic_key, "closed_issues", @closed_issues.to_i)
end
if @pullrequests.present?
$redis_cache.zincrby(project_rank_key, @pullrequests.to_i * 10, @project_id)
$redis_cache.hincrby(project_rank_statistic_key, "pullrequests", @pullrequests.to_i)

View File

@ -16,6 +16,6 @@ class Getway::Cms::GetService < Getway::ClientService
end
def url
"/cms/doc/open/baseInfo/#{doc_id}".freeze
"/cms/doc/open/#{doc_id}".freeze
end
end

View File

@ -59,11 +59,7 @@ class Gitea::Repository::Entries::CreateService < Gitea::ClientService
if @body[:new_branch].present? && (@body[:new_branch].include?('/') || @body[:new_branch].include?('\'') || @body[:new_branch].include?('^') || @body[:new_branch].include?('*'))
error("不合法的分支名称!")
else
if json_parse!(body)["message"].present? && json_parse!(body)["message"].starts_with?("branch already exists")
error("#{@body[:new_branch]}分支已存在!")
else
error("#{filepath}文件已存在,不能重复创建!")
end
error("#{filepath}文件已存在,不能重复创建!")
end
else
Rails.logger.error("Gitea api url==#{url},status:#{status},body=#{body}")

View File

@ -29,7 +29,7 @@ class Gitea::User::GenerateTokenService < Gitea::ClientService
end
def request_params
{ name: "#{@username}-#{token_name}", scopes: ["all"] }
{ name: "#{@username}-#{token_name}" }
end
def token_name

View File

@ -26,7 +26,7 @@ class PageService
Rails.logger.info "################### PageService close_site #{user_id} / #{identifier}"
user = User.find user_id
uri = if identifier.present?
URI.parse("http://gitlink.#{@deploy_domain}/gitlink_execute_script?key=#{@deploy_key}&script_path=remove_dir&owner=#{user.login.downcase}/*")
URI.parse("http://gitlink.#{@deploy_domain}/gitlink_execute_script?key=#{@deploy_key}&script_path=remove_dir&owner=#{user.login.downcase}/#{identifier}/")
else
URI.parse("http://gitlink.#{@deploy_domain}/gitlink_execute_script?key=#{@deploy_key}&script_path=remove_dir&owner=#{user.login.downcase}/")
end

View File

@ -67,7 +67,7 @@ class Repositories::CreateService < ApplicationService
end
def repository_params
params.merge(project_id: project.id).except(:auto_init)
params.merge(project_id: project.id)
end
def gitea_repository_params

View File

@ -1,6 +1,6 @@
<%
define_admin_breadcrumbs do
add_admin_breadcrumb('导航栏配置', admins_laboratories_path)
add_admin_breadcrumb('云上实验室', admins_laboratories_path)
add_admin_breadcrumb('轮播图')
end
%>

View File

@ -1,68 +0,0 @@
<div>
数据来源百度统计,本周 [<%= @current_week_statistic.first&.date %> / <%= @current_week_statistic.last&.date %>]
</div>
<table class="table table-hover text-center subject-list-table">
<thead class="thead-light">
<tr>
<th width="20%">日期</th>
<th width="15%">访问量</th>
<th width="15%">访客数</th>
<th width="15%">IP数</th>
<th width="15%">直接访问占比</th>
<th width="15%">外部链接占比</th>
<th width="15%">搜索引擎占比</th>
<th width="20%">自定义</th>
</tr>
</thead>
<tbody>
<% if @current_week_statistic.size ==1 && @pre_week_statistic.present? %>
<tr class="">
<td>上周合计</td>
<td><%= @pre_week_statistic.map(&:pv).sum %></td>
<td><%= @pre_week_statistic.map(&:visitor).sum %></td>
<td><%= @pre_week_statistic.map(&:ip).sum %></td>
<td><%= (@pre_week_statistic.map(&:source_through).sum.to_f / 7).round(2) %>%</td>
<td><%= (@pre_week_statistic.map(&:source_link).sum.to_f / 7).round(2) %>%</td>
<td><%= (@pre_week_statistic.map(&:source_search).sum.to_f / 7).round(2) %>%</td>
<td><%= ((@pre_week_statistic.map(&:source_custom) - [nil]).sum.to_f / 7).round(2) %>%</td>
</td>
</tr>
<% end %>
<% @current_week_statistic.each_with_index do |week, index| %>
<tr class="">
<td><%= week.date %> </td>
<td><%= week.pv %></td>
<td><%= week.visitor %></td>
<td><%= week.ip %></td>
<td><%= week.source_through %>%</td>
<td><%= week.source_link %>%</td>
<td><%= week.source_search %>%</td>
<td><%= week.source_custom.to_f %>%</td>
</td>
</tr>
<% end %>
<tr class="">
<% current_week_size = @current_week_statistic.size %>
<td><span style="color: #ff8200">本周合计</span></td>
<td><span style="color: #ff8200"><%= @current_week_statistic.map(&:pv).sum %></span></td>
<td><span style="color: #ff8200"><%= @current_week_statistic.map(&:visitor).sum %></span></td>
<td><span style="color: #ff8200"><%= @current_week_statistic.map(&:ip).sum %></span></td>
<td><span style="color: #ff8200"><%= (@current_week_statistic.map(&:source_through).sum.to_f / current_week_size).round(2) %>%</span></td>
<td><span style="color: #ff8200"><%= (@current_week_statistic.map(&:source_link).sum.to_f / current_week_size).round(2) %>%</span></td>
<td><span style="color: #ff8200"><%= (@current_week_statistic.map(&:source_search).sum.to_f / current_week_size).round(2) %>%</span></td>
<td><span style="color: #ff8200"><%= ((@current_week_statistic.map(&:source_custom) - [nil]).sum.to_f / current_week_size).round(2) %>%</span></td>
</td>
</tr>
</tbody>
</table>
<% unless @access_token.present? && @overview_data.present? %>
<div>
<a href="/admins/baidu_tongji" target="_blank">1.百度统计需人工授权,点击去授权</a>
</div>
<div>
<a href="/admins/baidu_tongji_auth" onclick="this.href = '/admins/baidu_tongji_auth?code=' + document.getElementById('auth_code').value">2.获取百度统计授权码</a>
<input name="code" id="auth_code" style="width: 380px" placeholder="请输入1.百度统计返回的code后点击2.获取百度统计Token"/>
</div>
<% end %>

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