This commit is contained in:
chenyh 2021-11-22 13:20:23 +08:00
parent 3c3977cc18
commit ed79e106ba
197 changed files with 4324 additions and 7502 deletions

1
.gitignore vendored
View File

@ -66,6 +66,7 @@ vendor/bundle/
/Users
/files
/public/images/avatars
/public/cache_repository
/public/files
/workspace
/log

View File

@ -1,8 +1,6 @@
source 'https://gems.ruby-china.com'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.3.7'
gem 'rails', '~> 5.2.0'
gem 'mysql2', '>= 0.4.4', '< 0.6.0'
gem 'puma', '~> 3.11'
@ -19,8 +17,6 @@ gem 'kaminari', '~> 1.1', '>= 1.1.1'
gem 'bootsnap', '>= 1.1.0', require: false
gem 'gitlab', path: 'lib/gitlab-cli'
gem 'chinese_pinyin'
gem 'rack-cors'
@ -74,6 +70,7 @@ group :development do
gem 'listen', '>= 3.0.5', '< 3.2'
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
gem "annotate", "~> 2.6.0"
end
group :test do

View File

@ -1,10 +1,3 @@
PATH
remote: lib/gitlab-cli
specs:
gitlab (3.2.0)
httparty
terminal-table
GEM
remote: https://gems.ruby-china.com/
specs:
@ -61,6 +54,9 @@ GEM
public_suffix (>= 2.0.2, < 5.0)
ancestry (3.0.7)
activerecord (>= 3.2.0)
annotate (2.6.5)
activerecord (>= 2.3.0)
rake (>= 0.8.7)
archive-zip (0.12.0)
io-like (~> 0.3.0)
arel (9.0.0)
@ -138,9 +134,6 @@ GEM
harmonious_dictionary (0.0.1)
hashie (3.6.0)
htmlentities (4.3.4)
httparty (0.18.0)
mime-types (~> 3.0)
multi_xml (>= 0.5.2)
i18n (1.8.2)
concurrent-ruby (~> 1.0)
io-like (0.3.1)
@ -177,9 +170,6 @@ GEM
mimemagic (~> 0.3.2)
maruku (0.7.3)
method_source (0.9.2)
mime-types (3.3.1)
mime-types-data (~> 3.2015)
mime-types-data (3.2019.1009)
mimemagic (0.3.4)
mini_mime (1.0.2)
mini_portile2 (2.4.0)
@ -402,8 +392,6 @@ GEM
actionpack (>= 4.0)
activesupport (>= 4.0)
sprockets (>= 3.0.0)
terminal-table (1.8.0)
unicode-display_width (~> 1.1, >= 1.1.1)
thor (1.0.1)
thread_safe (0.3.6)
tilt (2.0.10)
@ -437,6 +425,7 @@ DEPENDENCIES
acts-as-taggable-on (~> 6.0)
acts_as_list
ancestry
annotate (~> 2.6.0)
awesome_print
axlsx (~> 3.0.0.pre)
axlsx_rails (~> 0.5.2)
@ -452,7 +441,6 @@ DEPENDENCIES
enumerize
faraday (~> 0.15.4)
font-awesome-sass (= 4.7.0)
gitlab!
grape-entity (~> 0.7.1)
groupdate (~> 4.1.0)
harmonious_dictionary (~> 0.0.1)
@ -502,8 +490,5 @@ DEPENDENCIES
web-console (>= 3.3.0)
wkhtmltopdf-binary
RUBY VERSION
ruby 2.3.7p456
BUNDLED WITH
2.1.4

4892
README.md

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -9,8 +9,9 @@ module ApplicationCable
private
def find_verified_user
puts "############### cookies.signed[:signed_user_id]: #{cookies.signed[:user_id]}"
puts "############### cookies.signed[:user_id]: #{cookies.signed[:user_id]}"
if current_user = User.find_by(id: cookies.signed[:user_id])
puts "############### find_verified_user success! ###############"
current_user
else
reject_unauthorized_connection

View File

@ -1,7 +1,6 @@
class MirrorProjectChannel < ApplicationCable::Channel
def subscribed
Rails.logger.info "################### channel params: #{params}"
# @project = Project.find_by_identifier params[:id]
stream_from "channel_room_#{params[:id]}"
end

View File

@ -13,24 +13,12 @@ class AccountsController < ApplicationController
password = params[:password]
platform = (params[:platform] || 'forge')&.gsub(/\s+/, "")
@user = User.new(admin: false, login: username, mail: email, type: "User")
@user.password = password
@user.platform = platform
@user.activate
ActiveRecord::Base.transaction do
interactor = Gitea::RegisterInteractor.call({username: username, email: email, password: password})
if interactor.success?
gitea_user = interactor.result
result = Gitea::User::GenerateTokenService.new(username, password).call
@user.gitea_token = result['sha1']
@user.gitea_uid = gitea_user['id']
if @user.save!
UserExtension.create!(user_id: @user.id)
render_ok({user: {id: @user.id, token: @user.gitea_token}})
end
result = autologin_register(username, email, password, platform)
if result[:message].blank?
render_ok({user: result[:user]})
else
render_error(interactor.error)
render_error(result[:message])
end
end
rescue Exception => e
@ -66,8 +54,8 @@ class AccountsController < ApplicationController
sync_params = {}
if (user_params["mail"] && user_params["mail"] != user_mail) || (user_params["login"] && user_params["login"] != params[:old_user_login])
sync_params = sync_params.merge(email: user_params["mail"], login_name: user_params["login"], full_name: user_params["login"])
if (user_params["mail"] && user_params["mail"] != user_mail)
sync_params = sync_params.merge(email: user_params["mail"])
end
if sync_params.present?
@ -122,33 +110,33 @@ class AccountsController < ApplicationController
# params[:login] 邮箱或者手机号
# params[:code] 验证码
# code_type 1注册手机验证码 8邮箱注册验证码
# 本地forge注册入口
def register
begin
# 查询验证码是否正确;type只可能是1或者8
type = phone_mail_type(params[:login].strip)
code = params[:code].strip
# code = params[:code].strip
if type == 1
uid_logger("start register by phone: type is #{type}")
pre = 'p'
email = nil
phone = params[:login]
verifi_code = VerificationCode.where(phone: phone, code: code, code_type: 1).last
# verifi_code = VerificationCode.where(phone: phone, code: code, code_type: 1).last
# TODO: 暂时限定邮箱注册
return normal_status(-1, '只支持邮箱注册')
else
uid_logger("start register by email: type is #{type}")
pre = 'm'
email = params[:login]
phone = nil
verifi_code = VerificationCode.where(email: email, code: code, code_type: 8).last
return normal_status(-1, "该邮箱已注册") if User.exists?(mail: params[:login])
return normal_status(-1, "邮箱格式错误") unless params[:login] =~ CustomRegexp::EMAIL
# verifi_code = VerificationCode.where(email: email, code: code, code_type: 8).last
end
uid_logger("start register: verifi_code is #{verifi_code}, code is #{code}, time is #{Time.now.to_i - verifi_code.try(:created_at).to_i}")
# uid_logger("start register: verifi_code is #{verifi_code}, code is #{code}, time is #{Time.now.to_i - verifi_code.try(:created_at).to_i}")
# check_code = (verifi_code.try(:code) == code.strip && (Time.now.to_i - verifi_code.created_at.to_i) <= 10*60)
# todo 上线前请删除万能验证码"513231"
unless code == "513231" && request.subdomain == "test-newweb"
return normal_status(-2, "验证码不正确") if verifi_code.try(:code) != code.strip
return normal_status(-2, "验证码已失效") if !verifi_code&.effective?
end
return normal_status(-1, "8~16位密码支持字母数字和符号") unless params[:password] =~ CustomRegexp::PASSWORD
code = generate_identifier User, 8, pre
@ -158,23 +146,20 @@ class AccountsController < ApplicationController
# 现在因为是验证码,所以在注册的时候就可以激活
@user.activate
# 必须要用save操作密码的保存是在users中
if @user.save!
# todo user_extension
UserExtension.create!(user_id: @user.id)
# 注册完成手机号或邮箱想可以奖励500金币
# RewardGradeService.call(
# @user,
# container_id: @user.id,
# container_type: pre == 'p' ? 'Phone' : 'Mail',
# score: 500
# )
# 注册时,记录是否是引流用户
ip = request.remote_ip
ua = UserAgent.find_by_ip(ip)
ua.update_column(:agent_type, UserAgent::USER_REGISTER) if ua
successful_authentication(@user)
# session[:user_id] = @user.id
normal_status("注册成功")
interactor = Gitea::RegisterInteractor.call({username: login, email: email, password: params[:password]})
if interactor.success?
gitea_user = interactor.result
result = Gitea::User::GenerateTokenService.new(login, params[:password]).call
@user.gitea_token = result['sha1']
@user.gitea_uid = gitea_user[:body]['id']
if @user.save!
UserExtension.create!(user_id: @user.id)
successful_authentication(@user)
normal_status("注册成功")
end
else
tip_exception(-1, interactor.error)
end
rescue Exception => e
uid_logger_error(e.message)
@ -258,6 +243,8 @@ class AccountsController < ApplicationController
def set_autologin_cookie(user)
token = Token.get_or_create_permanent_login_token(user, "autologin")
sync_user_token_to_trustie(user.login, token.value)
cookie_options = {
:value => token.value,
:expires => 1.month.from_now,

View File

@ -6,6 +6,12 @@ class Admins::LaboratoriesController < Admins::BaseController
@laboratories = paginate laboratories.preload(:laboratory_users)
end
def new
respond_to do |format|
format.js
end
end
def create
Admins::CreateLaboratoryService.call(create_params)
render_ok

View File

@ -1,4 +1,11 @@
class Admins::LaboratorySettingsController < Admins::BaseController
def new
respond_to do |format|
format.js
end
end
def show
@laboratory = current_laboratory
end

View File

@ -9,6 +9,7 @@ class ApplicationController < ActionController::Base
include GitHelper
include LoggerHelper
include LoginHelper
include RegisterHelper
protect_from_forgery prepend: true, unless: -> { request.format.json? }
@ -342,7 +343,8 @@ class ApplicationController < ActionController::Base
elsif params[:debug] == 'student'
User.current = User.find 8686
elsif params[:debug] == 'admin'
user = User.find 1
logger.info "@@@@@@@@@@@@@@@@@@@@@@ debug mode....."
user = User.find 36480
User.current = user
cookies.signed[:user_id] = user.id
end
@ -383,11 +385,7 @@ class ApplicationController < ActionController::Base
end
def current_user
if Rails.env.development?
User.current = User.find 1
else
User.current
end
User.current
end
## 默认输出json
@ -727,11 +725,6 @@ class ApplicationController < ActionController::Base
render_not_found("未找到’#{project}’相关的项目") unless @project
end
def find_project_with_identifier
@project = Project.find_by_identifier! params[:id]
render_not_found("未找到’#{params[:id]}’相关的项目") unless @project
end
def find_project_with_id
@project = Project.find(params[:project_id] || params[:id])
rescue Exception => e
@ -743,6 +736,32 @@ class ApplicationController < ActionController::Base
interactor.success? ? render_ok : render_error(interactor.error)
end
# projects
def load_project
namespace = params[:owner]
id = params[:repo] || params[:id]
@project, @owner = Project.find_with_namespace(namespace, id)
if @project and current_user.can_read_project?(@project)
logger.info "########### has project and can read project"
@project
elsif @project && current_user.is_a?(AnonymousUser)
logger.info "###########This is AnonymousUser"
@project = nil if !@project.is_public?
render_forbidden and return
else
logger.info "###########project not found"
@project = nil
render_not_found and return
end
@project
end
def load_repository
@repository ||= load_project&.repository
end
private
def object_not_found
uid_logger("Missing template or cant't find record, responding with 404")

View File

@ -2,7 +2,7 @@
#
# 文件上传
class AttachmentsController < ApplicationController
before_action :require_login, :check_auth, except: [:show]
before_action :require_login, :check_auth, except: [:show, :preview_attachment, :get_file]
before_action :find_file, only: %i[show destroy]
before_action :attachment_candown, only: [:show]
skip_before_action :check_sign, only: [:show, :create]
@ -28,6 +28,15 @@ class AttachmentsController < ApplicationController
update_downloads(@file)
end
def get_file
normal_status(-1, "参数缺失") if params[:download_url].blank?
url = URI.encode(params[:download_url].to_s.gsub("http:", "https:"))
response = Faraday.get(url)
filename = params[:download_url].to_s.split("/").pop()
send_data(response.body.force_encoding("UTF-8"), filename: filename, type: "application/octet-stream", disposition: 'attachment')
end
def create
# 1. 本地存储
# 2. 上传到云
@ -98,6 +107,26 @@ class AttachmentsController < ApplicationController
end
end
# 附件为视频时,点击播放
def preview_attachment
attachment = Attachment.find_by(id: params[:id])
dir_path = "#{Rails.root}/public/preview"
Dir.mkdir(dir_path) unless Dir.exist?(dir_path)
if params[:status] == "preview"
if system("cp -r #{absolute_path(local_path(attachment))} #{dir_path}/")
render json: {status: 1, url: "/preview/#{attachment.disk_filename}"}
else
normal_status(-1, "出现错误,请稍后重试")
end
else
if system("rm -rf #{dir_path}/#{attachment.disk_filename}")
normal_status(1, "操作成功")
else
normal_status(-1, "出现错误,请稍后重试")
end
end
end
private
def find_file
@file =

View File

@ -16,10 +16,6 @@ class Ci::BaseController < ApplicationController
@repos = Ci::Repo.find_all_with_namespace(namespace)
end
def load_repo_by_repo_slug(slug)
@repo_slug = Ci::Repo.load_repo_by_repo_slug(slug)
end
private
def authorize_access_project!
unless @project.manager?(current_user)
@ -67,7 +63,6 @@ class Ci::BaseController < ApplicationController
if current.ci_cloud_account.server_type == Ci::CloudAccount::SERVER_TYPE_TRUSTIE
connect_to_trustie_ci_database(options)
else
options = options.merge(db_name: current.login)
connect_to_ci_database(options)
end

View File

@ -38,7 +38,7 @@ class Ci::CloudAccountsController < Ci::BaseController
ActiveRecord::Base.transaction do
if @repo
return render_error('该项目已经激活') if @repo.repo_active?
@repo.activate!(@project)
@repo.activate!(@ci_user.user_id)
else
@repo = Ci::Repo.auto_create!(@ci_user, @project)
@user.update_column(:user_syncing, false)

View File

@ -41,8 +41,11 @@ class Ci::ProjectsController < Ci::BaseController
ActiveRecord::Base.transaction do
if @repo
return render_error('该项目已经激活') if @repo.repo_active?
@repo.activate!(@project)
return render_ok
if @project.ci_reactivate?
@project.ci_reactivate!(@repo)
return render_ok
end
@repo.activate!(@ci_user.user_id)
else
@repo = Ci::Repo.auto_create!(@ci_user, @project)
@ci_user.update_column(:user_syncing, false)
@ -63,7 +66,7 @@ class Ci::ProjectsController < Ci::BaseController
return render_error('该项目已经取消激活') if !@repo.repo_active?
@project.update_column(:open_devops, false)
@repo.deactivate_repos!
@repo.deactivate!
render_ok
end

View File

@ -6,26 +6,10 @@ class CompareController < ApplicationController
end
def show
compare
end
base_ref = Addressable::URI.unescape(params[:base])
@ref = head_ref = Addressable::URI.unescape(params[:head]&.split('.json')[0])
@compare_result = Gitea::Repository::Commits::CompareService.call(@owner.login, @project.identifier, base_ref, head_ref)
private
def compare
base, head = compare_params
# TODO: 处理fork的项目向源项目发送PR的base、head参数问题
@compare_result ||=
head.include?(":") ? gitea_compare(base, head) : gitea_compare(head, base)
end
def compare_params
base = Addressable::URI.unescape(params[:base])
head = params[:head].include?('json') ? params[:head]&.split('.json')[0] : params[:head]
[base, head]
end
def gitea_compare(base, head)
Gitea::Repository::Commits::CompareService.call(@owner.login, @project.identifier, base, head)
# render json: @compare_result
end
end

View File

@ -101,6 +101,9 @@ module Ci::CloudAccountManageable
if cloud_account.server_type == Ci::CloudAccount::SERVER_TYPE_SELF
@connection.execute("DROP DATABASE IF EXISTS #{current_user.login}_drone") # TOTO drop drone database
else
#删除drone用户
@trustie_db_connection.execute("DELETE FROM users WHERE user_login = '#{cloud_account.account}'")
end
cloud_account.destroy! unless cloud_account.blank?

View File

@ -17,8 +17,7 @@ module Ci::DbConnectable
password: db_config[:password],
port: db_config[:port]
}
db_name = options[:db_name].blank? ? current_user.login : options[:db_name]
req_params = req_params.merge(database: "#{db_name}_#{db_config[:database]}") unless master_db === true
req_params = req_params.merge(database: "#{current_user.login}_#{db_config[:database]}") unless master_db === true
db_params = Ci::Database.get_connection_params(req_params)
@connection = Ci::Database.set_connection(db_params).connection

View File

@ -11,19 +11,24 @@ module LoginHelper
def set_autologin_cookie(user)
token = Token.get_or_create_permanent_login_token(user, "autologin")
sync_user_token_to_trustie(user.login, token.value)
Rails.logger.info "###### def set_autologin_cookie and get_or_create_permanent_login_token result: #{token&.value}"
cookie_options = {
:value => token.value,
:expires => 1.month.from_now,
:path => '/',
:secure => false,
:httponly => false
:httponly => true
}
if edu_setting('cookie_domain').present?
cookie_options = cookie_options.merge(domain: edu_setting('cookie_domain'))
end
unless cookies[autologin_cookie_name].present?
cookies[autologin_cookie_name] = cookie_options
end
# unless cookies[autologin_cookie_name].present?
# cookies[autologin_cookie_name] = cookie_options
# end
cookies[autologin_cookie_name] = cookie_options
# for action cable
cookies.signed[:user_id] ||= user.id
@ -48,11 +53,16 @@ module LoginHelper
Rails.logger.info("####################__User.current_id______######{current_user.try(:id)}###___#{current_user&.logged?}")
if User.current.logged?
if autologin = cookies.delete(autologin_cookie_name)
user = User.current
autologin =
if edu_setting('cookie_domain').present?
cookies.delete(autologin_cookie_name, domain: edu_setting('cookie_domain'))
else
cookies.delete(autologin_cookie_name)
end
User.current.delete_autologin_token(autologin)
end
User.current.delete_session_token(session[:tk])
user.delete_autologin_token(autologin)
user.delete_session_token(session[:tk])
self.logged_user = nil
end
@ -65,7 +75,7 @@ module LoginHelper
# Sets the logged in user
def logged_user=(user)
# reset_session
reset_session
if user && user.is_a?(User)
Rails.logger.info("########________logged_user___________###########{user.id}")
@ -108,4 +118,34 @@ module LoginHelper
false
end
end
# TODO 同步token到trustie平台保持同步登录状态
def sync_user_token_to_trustie(login, token_value)
config = Rails.application.config_for(:configuration).symbolize_keys!
token = config[:sync_token]
api_host = config[:sync_url]
return if api_host.blank?
url = "#{api_host}/api/v1/users/sync_user_token"
sync_json = {
"token": token,
"login": login,
"user_token": token_value
}
uri = URI.parse(url)
if api_host
http = Net::HTTP.new(uri.hostname, uri.port)
if api_host.include?("https://")
http.use_ssl = true
end
http.send_request('POST', uri.path, sync_json.to_json, {'Content-Type' => 'application/json'})
end
end
end

View File

@ -10,7 +10,7 @@ module OperateProjectAbilityAble
end
def authorizate_user_can_edit_repo!
return if @repo.project.manager?(current_user) || current_user.admin?
return if @repository.project.manager?(current_user) || current_user.admin?
render_forbidden('你没有权限操作.')
end

View File

@ -8,8 +8,6 @@ module RegisterHelper
user.password = password
user.platform = platform
user.activate
return unless user.valid?
interactor = Gitea::RegisterInteractor.call({username: username, email: email, password: password})
if interactor.success?

View File

@ -1,5 +1,6 @@
class ForksController < ApplicationController
before_action :require_login, :find_project_with_id
before_action :require_login
before_action :load_project
before_action :authenticate_project!, :authenticate_user!
def create

View File

@ -4,18 +4,18 @@ class HooksController < ApplicationController
before_action :check_user
before_action :set_repository
def index
hooks_response = Gitea::Hooks::ListService.new(@user, @repository.try(:identifier)).call
if hooks_response.status == 200
def index
hooks_response = Gitea::Hooks::ListService.new(@user.gitea_token, @user.login, @repository.try(:identifier)).call
if hooks_response.status == 200
lists = JSON.parse(hooks_response.body)
@hooks_size = lists.size
@hooks = paginate(lists)
else
else
normal_status(-1, "出现错误")
end
end
def create
def create
#根据gitea的api
# hook_params = {
# active: true,
@ -36,17 +36,17 @@ class HooksController < ApplicationController
# content_type: params[:content_type].to_i,
# secret: params[:secret],
# events: {
# push_only: params[:push_only] || false, # 是否为推送事件
# send_everything: params[:send_everything] || false, #是否为所有事件
# push_only: params[:push_only] || false, # 是否为推送事件
# send_everything: params[:send_everything] || false, #是否为所有事件
# choose_events: params[:choose_events] || false, #是否为自定义事件
# branch_filter: params[:branch_filter] || "*",
# events: {
# create: params[:create] || false, #创建分支/标签
# delete: params[:delete] || false, #删除分支/标签
# fork: params[:fork] || false, #仓库被派生
# delete: params[:delete] || false, #删除分支/标签
# fork: params[:fork] || false, #仓库被派生
# issues: params[:issues] || false, #工单
# issue_comment: params[:issue_comment] || false, #评论
# push: params[:push] || false # 推送
# issue_comment: params[:issue_comment] || false, #评论
# push: params[:push] || false # 推送
# pull_request: params[:pull_request] || false #合并请求
# repository: params[:repository] || false #仓库
# release: params[:release] || false #版本发布
@ -58,28 +58,28 @@ class HooksController < ApplicationController
Gitea::Hooks::CreateService.new(@user, @repository.try(:identifier), hook_params).call #创建gitea的hook功能
Gitea::Hooks::CreateService.new(user, p.try(:identifier), hook_params).call #创建gitea的hook功能
end
end
def update
def update
hook_params = params[:hook_params]
response = Gitea::Hooks::UpdateService.new(@user, @repository.try(:identifier), hook_params, params[:id]).call
if response.status == 200
if response.status == 200
normal_status(1, "更新成功")
else
else
normal_status(-1, "更新失败")
end
end
end
def destroy
def destroy
response = Gitea::Hooks::DestroyService.new(@user, @repository.try(:identifier), params[:id]).call
if response.status == 204
normal_status(1, "删除成功")
else
else
normal_status(-1, "删除失败")
end
end
end
private
private
def set_repository
@repository = @project.repository
@ -88,9 +88,9 @@ class HooksController < ApplicationController
normal_status(-1, "用户不存在") unless @user.present?
end
def check_user
unless @project.user_id == current_user.id
tip_exception(403, "您没有权限进入")
def check_user
unless @project.user_id == current_user.id
tip_exception(403, "您没有权限进入")
end
end
end

View File

@ -1,7 +1,7 @@
class IssueTagsController < ApplicationController
before_action :require_login, except: [:index]
before_action :find_project_with_id
before_action :set_project
before_action :load_repository
before_action :set_user
before_action :check_issue_permission, except: :index
before_action :set_issue_tag, only: [:edit, :update, :destroy]
@ -38,12 +38,12 @@ class IssueTagsController < ApplicationController
begin
issue_tag = IssueTag.new(tag_params.merge(project_id: @project.id, user_id: current_user.id))
if issue_tag.save
gitea_tag = Gitea::Labels::CreateService.new(current_user, @repository.try(:identifier), tag_params).call
if gitea_tag && issue_tag.update_attributes(gid: gitea_tag["id"], gitea_url: gitea_tag["url"])
normal_status(0, "标签创建成功")
else
normal_status(-1, "标签创建失败")
end
# gitea_tag = Gitea::Labels::CreateService.new(current_user, @repository.try(:identifier), tag_params).call
# if gitea_tag && issue_tag.update_attributes(gid: gitea_tag["id"], gitea_url: gitea_tag["url"])
# normal_status(0, "标签创建成功")
# else
# normal_status(-1, "标签创建失败")
# end
else
normal_status(-1, "标签创建失败")
end
@ -79,12 +79,12 @@ class IssueTagsController < ApplicationController
ActiveRecord::Base.transaction do
begin
if @issue_tag.update_attributes(tag_params)
gitea_tag = Gitea::Labels::UpdateService.new(current_user, @repository.try(:identifier),@issue_tag.try(:gid), tag_params).call
if gitea_tag
normal_status(0, "标签更新成功")
else
normal_status(-1, "标签更新失败")
end
# gitea_tag = Gitea::Labels::UpdateService.new(current_user, @repository.try(:identifier),@issue_tag.try(:gid), tag_params).call
# if gitea_tag
# normal_status(0, "标签更新成功")
# else
# normal_status(-1, "标签更新失败")
# end
else
normal_status(-1, "标签更新失败")
end
@ -103,12 +103,12 @@ class IssueTagsController < ApplicationController
ActiveRecord::Base.transaction do
begin
if @issue_tag.destroy
issue_tag = Gitea::Labels::DeleteService.new(@user, @repository.try(:identifier), @issue_tag.try(:gid)).call
if issue_tag
normal_status(0, "标签删除成功")
else
normal_status(-1, "标签删除失败")
end
# issue_tag = Gitea::Labels::DeleteService.new(@user, @repository.try(:identifier), @issue_tag.try(:gid)).call
# if issue_tag
# normal_status(0, "标签删除成功")
# else
# normal_status(-1, "标签删除失败")
# end
else
normal_status(-1, "标签删除失败")
end
@ -121,13 +121,8 @@ class IssueTagsController < ApplicationController
private
def set_project
# @project = Project.find_by_identifier! params[:project_id]
@repository = @project.repository
def set_user
@user = @project.owner
normal_status(-1, "项目不存在") unless @project.present?
normal_status(-1, "仓库不存在") unless @repository.present?
normal_status(-1, "用户不存在") unless @user.present?
end
def check_issue_permission
@ -143,4 +138,4 @@ class IssueTagsController < ApplicationController
end
end
end
end

View File

@ -1,12 +1,11 @@
class IssuesController < ApplicationController
before_action :require_login, except: [:index, :show, :index_chosen]
before_action :find_project_with_id
before_action :set_project_and_user
before_action :load_project
before_action :set_user
before_action :check_issue_permission
before_action :check_project_public, only: [:index ,:show, :copy, :index_chosen, :close_issue]
before_action :set_issue, only: [:edit, :update, :destroy, :show, :copy, :close_issue, :lock_issue]
before_action :get_branches, only: [:new, :edit]
before_action :check_token_enough, only: [:create, :update]
include ApplicationHelper
@ -16,7 +15,7 @@ class IssuesController < ApplicationController
@user_admin_or_member = current_user.present? && current_user.logged? && (current_user.admin || @project.member?(current_user))
issues = @project.issues.issue_issue.issue_index_includes
issues = issues.where(is_private: false) unless @user_admin_or_member
@all_issues_size = issues.size
@open_issues_size = issues.where.not(status_id: 5).size
@close_issues_size = issues.where(status_id: 5).size
@ -97,8 +96,7 @@ class IssuesController < ApplicationController
end
def new
@all_branches = get_branches
@issue_chosen = issue_left_chosen(@project, nil)
@issue_chosen = get_associated_data(@project)
end
def create
@ -110,46 +108,39 @@ class IssuesController < ApplicationController
issue_params = issue_send_params(params)
@issue = Issue.new(issue_params)
begin
if @issue.save!
if params[:attachment_ids].present?
params[:attachment_ids].each do |id|
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?
attachment.container = @issue
attachment.author_id = current_user.id
attachment.description = ""
attachment.save
end
if @issue.save!
if params[:attachment_ids].present?
params[:attachment_ids].each do |id|
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?
attachment.container = @issue
attachment.author_id = current_user.id
attachment.description = ""
attachment.save
end
end
if params[:issue_tag_ids].present?
params[:issue_tag_ids].each do |tag|
IssueTagsRelate.create!(issue_id: @issue.id, issue_tag_id: tag)
end
end
if params[:assigned_to_id].present?
Tiding.create!(user_id: params[:assigned_to_id], trigger_user_id: current_user.id,
container_id: @issue.id, container_type: 'Issue',
parent_container_id: @project.id, parent_container_type: "Project",
tiding_type: 'issue', status: 0)
end
#为悬赏任务时, 扣除当前用户的积分
if params[:issue_type].to_s == "2"
post_to_chain("minus", params[:token].to_i, current_user.try(:login))
end
@issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create")
normal_status(0, "创建成功")
else
normal_status(-1, "创建失败")
end
rescue => e
Rails.looger.info("##################________exception_________________######################{e.message}")
normal_status(-1, e.message)
if params[:issue_tag_ids].present?
params[:issue_tag_ids].each do |tag|
IssueTagsRelate.create!(issue_id: @issue.id, issue_tag_id: tag)
end
end
if params[:assigned_to_id].present?
Tiding.create!(user_id: params[:assigned_to_id], trigger_user_id: current_user.id,
container_id: @issue.id, container_type: 'Issue',
parent_container_id: @project.id, parent_container_type: "Project",
tiding_type: 'issue', status: 0)
end
#为悬赏任务时, 扣除当前用户的积分
if params[:issue_type].to_s == "2"
post_to_chain("minus", params[:token].to_i, current_user.try(:login))
end
@issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create")
render json: {status: 0, message: "创建成", id: @issue.id}
else
normal_status(-1, "创建失败")
end
end
@ -157,7 +148,6 @@ class IssuesController < ApplicationController
end
def edit
# @all_branches = get_branches
# @issue_chosen = issue_left_chosen(@project, @issue.id)
@cannot_edit_tags = @issue.issue_type=="2" && @issue.status_id == 5 #悬赏任务已解决且关闭的状态下,不能修改
@issue_attachments = @issue.attachments
@ -190,17 +180,21 @@ class IssuesController < ApplicationController
end
end
if @issue.issue_type.to_s == "2" && @issue.status_id == 5 #已关闭的情况下,只能更新标题和内容,附件
new_issue_params = {
subject: params[:subject],
description: params[:description],
}
if @issue.update_attributes(new_issue_params)
normal_status(0, "更新成功")
else
normal_status(-1, "更新失败")
end
elsif @issue.issue_type.to_s == "2" && params[:status_id].to_i == 5 && @issue.author_id != current_user.try(:id)
# if params[:issue_tag_ids].present?
# issue_current_tags = @issue&.issue_tags&.select(:id)&.pluck(:id)
# new_tag_ids = params[:issue_tag_ids] - issue_current_tags
# old_tag_ids = issue_current_tags - params[:issue_tag_ids]
# if old_tag_ids.size > 0
# @issue.issue_tags_relates.where(issue_tag_id: old_tag_ids).delete_all
# end
# if new_tag_ids.size > 0
# new_tag_ids.each do |tag|
# IssueTagsRelate.create(issue_id: @issue.id, issue_tag_id: tag)
# end
# end
# end
if @issue.issue_type.to_s == "2" && params[:status_id].to_i == 5 && @issue.author_id != current_user.try(:id)
normal_status(-1, "不允许修改为关闭状态")
else
issue_params = issue_send_params(params).except(:issue_classify, :author_id, :project_id)
@ -212,12 +206,12 @@ class IssuesController < ApplicationController
if @issue.issue_type.to_s == "2" && last_status_id != 5
if @issue.assigned_to_id.present? && last_status_id == 3 #只有当用户完成100%时才给token
post_to_chain("add", @issue.token, @issue.get_assign_user.try(:login))
else
else
post_to_chain("add", @issue.token, @issue.user.try(:login))
end
end
end
if @issue.issue_type.to_s == "2" && @issue.status_id != 5 && @issue.saved_change_to_attribute("token")
#表示修改token值
change_token = last_token - @issue.token
@ -288,7 +282,19 @@ class IssuesController < ApplicationController
update_hash = {}
update_hash.merge!(assigned_to_id: params[:assigned_to_id]) if params[:assigned_to_id].present?
update_hash.merge!(fixed_version_id: params[:fixed_version_id]) if params[:fixed_version_id].present?
update_hash.merge!(status_id: params[:status_id]) if params[:status_id].present?
# update_hash.merge!(status_id: params[:status_id]) if params[:status_id].present?
if params[:status_id].present?
status_id = params[:status_id].to_i
update_hash.merge!(status_id: status_id)
done_ratio = nil
case status_id
when 1
done_ratio = 0
when 3
done_ratio = 100
end
update_hash.merge!(done_ratio: done_ratio) if done_ratio
end
# update_hash = params[:issue]
issue_ids = params[:ids]
if issue_ids.present?
@ -378,11 +384,8 @@ class IssuesController < ApplicationController
end
private
def set_project_and_user
# @project = Project.find_by_identifier(params[:project_id]) || (Project.find params[:project_id]) || (Project.find params[:id])
def set_user
@user = @project&.owner
# normal_status(-1, "项目不存在") unless @project.present?
normal_status(-1, "用户不存在") unless @user.present?
end
def check_project_public
@ -433,17 +436,6 @@ class IssuesController < ApplicationController
tracker_array
end
def get_branches
all_branches = []
get_all_branches = Gitea::Repository::Branches::ListService.new(@user, @project&.repository.try(:identifier)).call
if get_all_branches && get_all_branches.size > 0
get_all_branches.each do |b|
all_branches.push(b["name"])
end
end
all_branches
end
def issue_send_params(params)
{
subject: params[:subject],
@ -481,7 +473,7 @@ class IssuesController < ApplicationController
PostChainJob.perform_later(change_params)
end
def check_token_enough
def check_token_enough
if params[:issue_type].to_s == "2" && (@issue.blank? || (@issue.present? && @issue.author_id == current_user.try(:id)))
return normal_status(-1, "悬赏的奖金必须大于0") if params[:token].to_i == 0
query_params = {
@ -492,7 +484,7 @@ class IssuesController < ApplicationController
}
}
response = Gitea::Chain::ChainGetService.new(query_params).call
return normal_status(-1, "获取token失败请稍后重试") if response.status != 200
return normal_status(-1, "获取token失败请稍后重试") if response.status != 200
return normal_status(-1, "您的token值不足") if JSON.parse(response.body)["balance"].to_i < params[:token].to_i
end
end

View File

@ -2,7 +2,7 @@ class MainController < ApplicationController
protect_from_forgery except: :index
skip_before_action :check_sign
skip_before_action :user_setup
# skip_before_action :setup_laboratory
skip_before_action :setup_laboratory
def first_stamp
render :json => { status: 0, message: Time.now.to_i }

View File

@ -1,6 +1,6 @@
class MembersController < ApplicationController
before_action :require_login
before_action :find_project_with_id
before_action :load_project
before_action :find_user_with_id, only: %i[create remove change_role]
before_action :operate!, except: %i[index]
before_action :check_member_exists!, only: %i[create]

View File

@ -1,4 +1,6 @@
class OauthController < ApplicationController
layout "oauth_register", only: [:register]
DEFAULT_PASSWORD = "a12345678"
TOKEN_CALL_BACK = "/oauth/get_token_callback"
USER_INFO = "/oauth/userinfo"
@ -51,4 +53,35 @@ class OauthController < ApplicationController
def get_token_callback
end
def register
end
def auto_register
login = params[:login]
email = params[:mail]
password = params[:password]
callback_url = params[:callback_url]
platform = params[:plathform] || 'educoder'
if User.where(mail: email).exists?
render json: { email_exist: '该邮箱已使用过' }
else
result = autologin_register(login, email, password, platform)
logger.info "[Oauth educoer] =====#{result}"
if result[:message].blank?
logger.info "[Oauth educoer] ====auto_register success"
user = User.find result[:user][:id]
successful_authentication(user)
OpenUsers::Educoder.create!(user: user, uid: user.login)
render json: { callback_url: callback_url }
# redirect_to callback_url
else
logger.info "[Oauth educoer] ====auto_register failed."
render :action => "auto_register"
end
end
end
end

View File

@ -40,8 +40,5 @@ class PraiseTreadController < ApplicationController
end
private
def render_result
end
end

View File

@ -6,12 +6,8 @@ class ProjectCategoriesController < ApplicationController
end
def group_list
# if current_user&.logged?
# projects = Project.list_user_projects(current_user.id)
# else
# projects = Project.visible
# end
projects = Project.no_anomory_projects.visible
@category_group_list = projects.joins(:project_category).group("project_categories.id", "project_categories.name").size
@project_categories = ProjectCategory.where('projects_count > 0').order(projects_count: :desc)
# projects = Project.no_anomory_projects.visible
# @category_group_list = projects.joins(:project_category).group("project_categories.id", "project_categories.name").size
end
end

View File

@ -1,5 +1,5 @@
class ProjectTrendsController < ApplicationController
before_action :find_project_with_id
before_action :load_repository
before_action :check_project_public
def index
@ -44,4 +44,4 @@ class ProjectTrendsController < ApplicationController
normal_status(-1, "您没有权限")
end
end
end
end

View File

@ -1,5 +1,7 @@
class Projects::BaseController < ApplicationController
include PaginateHelper
before_action :require_login, :check_auth
before_action :load_project
before_action :load_repository
end

View File

@ -2,16 +2,26 @@ class ProjectsController < ApplicationController
include ApplicationHelper
include OperateProjectAbilityAble
include ProjectsHelper
before_action :require_login, except: %i[index branches group_type_list simple]
before_action :find_project_with_id, only: %i[show branches update destroy fork_users praise_users watch_users]
before_action :require_login, except: %i[index branches group_type_list simple show fork_users praise_users watch_users recommend about]
before_action :load_project, except: %i[index group_type_list migrate create recommend]
before_action :authorizate_user_can_edit_project!, only: %i[update]
before_action :project_public?, only: %i[fork_users praise_users watch_user]
before_action :project_public?, only: %i[fork_users praise_users watch_users]
def index
scope = Projects::ListQuery.call(params)
@projects = kaminari_paginate(scope)
@total_count = @projects.total_count
# @projects = kaminari_paginate(scope)
@projects = paginate scope.includes(:project_category, :project_language, :repository, :project_educoder, owner: :user_extension)
category_id = params[:category_id]
@total_count =
if category_id.blank?
ps = ProjectStatistic.first
ps.common_projects_count + ps.mirror_projects_count unless ps.blank?
else
cate = ProjectCategory.find_by(id: category_id)
cate&.projects_count || 0
end
end
def create
@ -34,26 +44,40 @@ class ProjectsController < ApplicationController
end
def branches
@branches = Gitea::Repository::Branches::ListService.new(@project.owner, @project.identifier).call
@branches = @project.forge? ? Gitea::Repository::Branches::ListService.new(@owner, @project.identifier).call : []
end
def group_type_list
# if current_user&.logged?
# projects = Project.list_user_projects(current_user.id)
# else
# projects = Project.visible
# end
projects = Project.no_anomory_projects.visible
@project_group_list = projects.group(:project_type).size
project_statics = ProjectStatistic.first
@project_statics_list = [
{
project_type: 'common',
name: '开源托管项目',
projects_count: project_statics&.common_projects_count || 0
},
{
project_type: 'mirror',
name: '开源镜像项目',
projects_count: project_statics&.mirror_projects_count || 0
}
]
# projects = Project.no_anomory_projects.visible
# @project_group_list = projects.group(:project_type).size
end
def update
ActiveRecord::Base.transaction do
# Projects::CreateForm.new(project_params).validate!
private = params[:private]
gitea_params = {
private: private,
default_branch: params[:default_branch]
}
if [true, false].include? private
new_project_params = project_params.merge(is_public: !private)
Gitea::Repository::UpdateService.new(@project.owner, @project.repository.identifier, {private: private}).call
Gitea::Repository::UpdateService.call(@owner, @project.identifier, gitea_params)
@project.repository.update_column(:hidden, private)
end
@project.update_attributes!(new_project_params)
@ -94,16 +118,48 @@ class ProjectsController < ApplicationController
end
def fork_users
fork_users = @project.fork_users.includes(:user, :project).order("fork_users.created_at desc").distinct
fork_users = @project.fork_users.includes(:user, :project, :fork_project).order("fork_users.created_at desc").distinct
@forks_count = fork_users.size
@fork_users = paginate(fork_users)
end
def simple
project = Project.includes(:owner, :repository).select(:id, :name, :identifier, :user_id, :project_type).find params[:id]
json_response(project)
json_response(@project, current_user)
end
def recommend
@projects = Project.recommend.includes(:repository, :project_category, owner: :user_extension).limit(5)
end
def about
@project_detail = @project.project_detail
@attachments = Array(@project_detail&.attachments) if request.get?
ActiveRecord::Base.transaction do
if request.post?
require_login
authorizate_user_can_edit_project!
unless @project_detail.present?
@project_detail = ProjectDetail.new(
content: params[:content],
project_id: @project.id)
else
@project_detail.content = params[:content]
end
if @project_detail.save!
attachment_ids = Array(params[:attachment_ids])
logger.info "=============> #{Array(params[:attachment_ids])}"
@attachments = Attachment.where(id: attachment_ids)
@attachments.update_all(
container_id: @project_detail.id,
container_type: @project_detail.model_name.name,
author_id: current_user.id,
description: "")
end
end
end
end
private
def project_params
params.permit(:user_id, :name, :description, :repository_name,
@ -116,8 +172,13 @@ class ProjectsController < ApplicationController
end
def project_public?
unless @project.is_public || current_user&admin?
tip_exception(403, "..")
return if @project.is_public?
if current_user
return if current_user.admin? || @project.member?(current_user.id)
render_forbidden('你没有权限访问.')
else
render_unauthorized('你还未登录.')
end
end
end

View File

@ -1,9 +1,8 @@
class PullRequestsController < ApplicationController
before_action :require_login, except: [:index, :show]
before_action :find_project_with_id
before_action :set_repository
before_action :find_pull_request, except: [:index, :new, :create, :check_can_merge,:get_branches,:create_merge_infos]
# before_action :get_relatived, only: [:edit]
before_action :require_login, except: [:index, :show, :files, :commits]
before_action :load_repository
before_action :find_pull_request, except: [:index, :new, :create, :check_can_merge,:get_branches,:create_merge_infos, :files, :commits]
before_action :load_pull_request, only: [:files, :commits]
include TagChosenHelper
include ApplicationHelper
@ -24,12 +23,13 @@ class PullRequestsController < ApplicationController
end
def new
@all_branches = PullRequests::BranchesService.new(@user, @project).call
@all_branches = Branches::ListService.call(@owner, @project)
@is_fork = @project.forked_from_project_id.present?
@projects_names = [{
project_user_login: @user.try(:login),
project_name: "#{@user.try(:show_real_name)}/#{@repository.try(:identifier)}",
project_id: @project.id
project_user_login: @owner.try(:login),
project_name: "#{@owner.try(:show_real_name)}/#{@repository.try(:identifier)}",
project_id: @project.identifier,
id: @project.id
}]
@merge_projects = @projects_names
fork_project = @project.fork_project if @is_fork
@ -37,69 +37,27 @@ class PullRequestsController < ApplicationController
@merge_projects.push({
project_user_login: fork_project.owner.try(:login),
project_name: "#{fork_project.owner.try(:show_real_name)}/#{fork_project.repository.try(:identifier)}",
project_id: fork_project.id
project_id: fork_project.identifier,
id: fork_project.id
})
end
end
def get_branches
branch_result = PullRequests::BranchesService.new(@user, @project).call
branch_result = Branches::ListService.call(@owner, @project)
render json: branch_result
# return json: branch_result
end
def create
if params[:title].nil?
normal_status(-1, "名称不能为空")
elsif params[:issue_tag_ids].nil?
normal_status(-1, "标签不能为空")
else
ActiveRecord::Base.transaction do
begin
merge_params
pull_issue = Issue.new(@issue_params)
if pull_issue.save!
pr_params = {
user_id: current_user.try(:id),
project_id: @project.id,
issue_id: pull_issue.id,
fork_project_id: params[:fork_project_id],
is_original: params[:is_original]
}
local_requests = PullRequest.new(@local_params.merge(pr_params))
if local_requests.save
remote_pr_params = @local_params
remote_pr_params = remote_pr_params.merge(head: "#{params[:merge_user_login]}:#{params[:head]}").compact if local_requests.is_original && params[:merge_user_login]
gitea_request = Gitea::PullRequest::CreateService.call(current_user.try(:gitea_token), @project.owner, @repository.try(:identifier), remote_pr_params.except(:milestone))
if gitea_request && local_requests.update_attributes(gpid: gitea_request["number"])
if params[:issue_tag_ids].present?
params[:issue_tag_ids].each do |tag|
IssueTagsRelate.create!(issue_id: pull_issue.id, issue_tag_id: tag)
end
end
if params[:assigned_to_id].present?
Tiding.create!(user_id: params[:assigned_to_id], trigger_user_id: current_user.id,
container_id: local_requests.id, container_type: 'PullRequest',
parent_container_id: @project.id, parent_container_type: "Project",
tiding_type: 'pull_request', status: 0)
end
local_requests.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create")
if params[:title].to_s.include?("WIP:")
pull_issue.custom_journal_detail("WIP", "", "这个合并请求被标记为尚未完成的工作。完成后请从标题中移除WIP:前缀。", current_user&.id)
end
normal_status(0, "PullRequest创建成功")
else
normal_status(-1, "PullRequest创建失败")
end
else
normal_status(-1, "PullRequest创建失败")
end
end
rescue => e
normal_status(-1, e.message)
raise ActiveRecord::Rollback
end
ActiveRecord::Base.transaction do
@pull_request, @gitea_pull_request = PullRequests::CreateService.call(current_user, @owner, @project, params)
if @gitea_pull_request[:status] == :success
@pull_request.bind_gitea_pull_request!(@gitea_pull_request[:body]["number"])
render_ok
else
render_error("create pull request error: #{@gitea_pull_request[:status]}")
raise ActiveRecord::Rollback
end
end
end
@ -219,11 +177,11 @@ class PullRequestsController < ApplicationController
elsif target_head === target_base && !is_original
normal_status(-2, "分支内容相同,无需创建合并请求")
else
can_merge = @project&.pull_requests.where(user_id: current_user&.id, head: target_head, base: target_base, status: 0, is_original: is_original, fork_project_id: params[:fork_project_id])
can_merge = @project&.pull_requests.where(head: target_head, base: target_base, status: 0, is_original: is_original, fork_project_id: params[:fork_project_id])
if can_merge.present?
render json: {
status: -2,
message: "在这些分支之间的合并请求已存在:<a href='/projects/#{@project.id}/merge/#{can_merge.first.id}/Messagecount''>#{can_merge.first.try(:title)}</a>",
message: "在这些分支之间的合并请求已存在:<a href='/projects/#{@owner.login}/#{@project.identifier}/pulls/#{can_merge.first.id}/Messagecount''>#{can_merge.first.try(:title)}</a>",
}
else
normal_status(0, "可以合并")
@ -232,13 +190,19 @@ class PullRequestsController < ApplicationController
end
private
def files
@files_result = Gitea::PullRequest::FilesService.call(@owner.login, @project.identifier, @pull_request.gpid, @owner.gitea_token)
# render json: @files_result
end
def set_repository
@repository = @project.repository
@user = @project.owner
normal_status(-1, "仓库不存在") unless @repository.present?
normal_status(-1, "用户不存在") unless @user.present?
def commits
@commits_result = Gitea::PullRequest::CommitsService.call(@owner.login, @project.identifier, @pull_request.gpid, @owner.gitea_token)
# render json: @commits_result
end
private
def load_pull_request
@pull_request = PullRequest.find params[:id]
end
def find_pull_request

View File

@ -1,11 +1,10 @@
class RepositoriesController < ApplicationController
include ApplicationHelper
include OperateProjectAbilityAble
before_action :require_login, only: %i[edit update create_file update_file delete_file sync_mirror]
before_action :find_project_with_includes, only: :show
before_action :find_project, except: [:tags, :commit, :sync_mirror, :show]
before_action :load_repository
before_action :authorizate!, except: [:sync_mirror, :tags, :commit]
before_action :find_repository_by_id, only: %i[commit sync_mirror tags]
before_action :authorizate_user_can_edit_repo!, only: %i[sync_mirror]
before_action :get_ref, only: %i[entries sub_entries top_counts]
before_action :get_latest_commit, only: %i[entries sub_entries top_counts]
@ -14,7 +13,7 @@ class RepositoriesController < ApplicationController
def show
@user = current_user
@repo = @project.repository
@result = Gitea::Repository::GetService.new(@project.owner, @project.identifier).call
@result = @project.forge? ? Gitea::Repository::GetService.new(@owner, @project.identifier).call : nil
@project_fork_id = @project.try(:forked_from_project_id)
if @project_fork_id.present?
@fork_project = Project.find_by(id: @project_fork_id)
@ -27,60 +26,85 @@ class RepositoriesController < ApplicationController
def entries
@project.increment!(:visits)
@project_owner = @project.owner
@entries = Gitea::Repository::Entries::ListService.new(@project_owner, @project.identifier, ref: @ref).call
@entries = @entries.present? ? @entries.sort_by{ |hash| hash['type'] } : []
@path = Gitea.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/"
if @project.educoder?
@entries = Educoder::Repository::Entries::ListService.call(@project&.project_educoder.repo_name)
else
@entries = Gitea::Repository::Entries::ListService.new(@owner, @project.identifier, ref: @ref).call
@entries = @entries.present? ? @entries.sort_by{ |hash| hash['type'] } : []
@path = Gitea.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/"
end
end
def top_counts
@result = Gitea::Repository::GetService.new(@project.owner, @project.identifier).call
@result = @project.educoder? ? nil : Gitea::Repository::GetService.new(@project.owner, @project.identifier).call
end
def sub_entries
file_path_uri = URI.parse(URI.encode(params[:filepath].to_s.strip))
interactor = Repositories::EntriesInteractor.call(@project.owner, @project.identifier, file_path_uri, ref: @ref)
if interactor.success?
@sub_entries = interactor.result
@sub_entries = [] << @sub_entries unless @sub_entries.is_a? Array
@sub_entries = @sub_entries.sort_by{ |hash| hash['type'] }
if @project.educoder?
if params[:type] === 'file'
@sub_entries = Educoder::Repository::Entries::GetService.call(@project&.project_educoder&.repo_name, file_path_uri)
logger.info "######### sub_entries: #{@sub_entries}"
return render_error('该文件暂未开放,敬请期待.') if @sub_entries['status'].to_i === -1
tmp_entries = [{
"content" => @sub_entries['data']['content'],
"type" => "blob"
}]
@sub_entries = {
"trees"=>tmp_entries,
"commits" => [{}]
}
else
@sub_entries = Educoder::Repository::Entries::ListService.call(@project&.project_educoder&.repo_name, {path: file_path_uri})
end
else
render_error(interactor.error)
interactor = Repositories::EntriesInteractor.call(@owner, @project.identifier, file_path_uri, ref: @ref)
if interactor.success?
result = interactor.result
@sub_entries = result.is_a?(Array) ? result.sort_by{ |hash| hash['type'] } : result
else
render_error(interactor.error)
end
end
end
def commits
@project_owner = @project.owner
@hash_commit = Gitea::Repository::Commits::ListService.new(@project_owner.login, @project.identifier,
@hash_commit = Gitea::Repository::Commits::ListService.new(@owner.login, @project.identifier,
sha: params[:sha], page: params[:page], limit: params[:limit], token: current_user&.gitea_token).call
end
def commit
@commit = Gitea::Repository::Commits::GetService.new(@repo.user.login, @repo.identifier, params[:sha], current_user.gitea_token).call
@sha = params[:sha]
@commit = Gitea::Repository::Commits::GetService.call(@owner.login, @repository.identifier, @sha, current_user&.gitea_token)
@commit_diff = Gitea::Repository::Commits::GetService.call(@owner.login, @repository.identifier, @sha, current_user&.gitea_token, {diff: true})
end
def tags
@tags = Gitea::Repository::Tags::ListService.new(current_user&.gitea_token, @repo.user.login, @repo.identifier, {page: params[:page], limit: params[:limit]}).call
@tags = Gitea::Repository::Tags::ListService.call(current_user&.gitea_token, @owner.login, @project.identifier, {page: params[:page], limit: params[:limit]})
end
def edit
end
def create_file
interactor = Gitea::CreateFileInteractor.call(current_user, content_params)
interactor = Gitea::CreateFileInteractor.call(current_user.gitea_token, @owner.login, content_params)
if interactor.success?
@file = interactor.result
create_new_pr(params)
# create_new_pr(params)
else
render_error(interactor.error)
end
end
def update_file
interactor = Gitea::UpdateFileInteractor.call(current_user, params.merge(identifier: @project.identifier))
interactor = Gitea::UpdateFileInteractor.call(current_user.gitea_token, @owner.login, params.merge(identifier: @project.identifier))
if interactor.success?
@file = interactor.result
create_new_pr(params)
# TODO: 是否创建pr
# create_new_pr(params)
render_result(1, "更新成功")
else
render_error(interactor.error)
@ -88,7 +112,7 @@ class RepositoriesController < ApplicationController
end
def delete_file
interactor = Gitea::DeleteFileInteractor.call(current_user, params.merge(identifier: @project.identifier))
interactor = Gitea::DeleteFileInteractor.call(current_user.gitea_token, @owner.login, params.merge(identifier: @project.identifier))
if interactor.success?
@file = interactor.result
render_result(1, "文件删除成功")
@ -102,10 +126,10 @@ class RepositoriesController < ApplicationController
end
def sync_mirror
return render_error("正在镜像中..") if @repo.mirror.waiting?
return render_error("正在镜像中..") if @repository.mirror.waiting?
@repo.sync_mirror!
SyncMirroredRepositoryJob.perform_later(@repo.id, current_user.id)
@repository.sync_mirror!
SyncMirroredRepositoryJob.perform_later(@repository.id, current_user.id)
render_ok
end
@ -121,6 +145,7 @@ class RepositoriesController < ApplicationController
end
def authorizate!
return if current_user && current_user.admin?
if @project.repository.hidden? && !@project.member?(current_user)
render_forbidden
end
@ -133,18 +158,18 @@ class RepositoriesController < ApplicationController
end
def get_statistics
@branches_count = Gitea::Repository::Branches::ListService.new(@project.owner, @project.identifier).call&.size
@tags_count = Gitea::Repository::Tags::ListService.new(current_user&.gitea_token, @project.owner.login, @project.identifier).call&.size
@branches_count = @project.educoder? ? 0 : Gitea::Repository::Branches::ListService.new(@project.owner, @project.identifier).call&.size
@tags_count = @project.educoder? ? 0 : Gitea::Repository::Tags::ListService.new(current_user&.gitea_token, @project.owner.login, @project.identifier).call&.size
end
def get_ref
@ref = params[:ref] || "master"
end
def get_latest_commit
latest_commit = project_commits
@latest_commit = latest_commit[:body][0] if latest_commit.present?
@commits_count = latest_commit[:total_count] if latest_commit.present?
def get_latest_commit
latest_commit = @project.educoder? ? nil : project_commits
@latest_commit = latest_commit.present? ? latest_commit[:body][0] : nil
@commits_count = latest_commit.present? ? latest_commit[:total_count] : 0
end
def content_params
@ -154,6 +179,10 @@ class RepositoriesController < ApplicationController
new_branch: params[:new_branch],
content: params[:content],
message: params[:message],
committer: {
email: current_user.mail,
name: current_user.login
},
identifier: @project.identifier
}
end
@ -214,8 +243,8 @@ class RepositoriesController < ApplicationController
if @pull_issue.save!
local_requests = PullRequest.new(local_params.merge(user_id: current_user.try(:id), project_id: @project.id, issue_id: @pull_issue.id))
if local_requests.save
gitea_request = Gitea::PullRequest::CreateService.new(current_user.try(:gitea_token), @project.owner, @project.try(:identifier), requests_params).call
if gitea_request && local_requests.update_attributes(gpid: gitea_request["number"])
gitea_request = Gitea::PullRequest::CreateService.new(current_user.try(:gitea_token), @owner.login, @project.try(:identifier), requests_params).call
if gitea_request[:status] == :success && local_requests.update_attributes(gpid: gitea_request["body"]["number"])
local_requests.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create")
end
end

View File

@ -1,307 +1,334 @@
class SyncForgeController < ApplicationController
# before_action :check_token
def create
ActiveRecord::Base.transaction do
params.permit!
sync_params = params[:sync_params]
project_user = User.where(login: sync_params[:owner_login])&.first
#以前已同步的项目,那么肯定存在仓库
user_projects = Project.where(user_id: project_user.id)
if user_projects.where(id: sync_params[:id], identifier: sync_params[:identifier]).present?
has_project = true
project = user_projects.where(id: sync_params[:id], identifier: sync_params[:identifier])&.first
elsif user_projects.where(id: sync_params[:id]).present?
has_project = true
project = user_projects.where(id: sync_params[:id])&.first
elsif user_projects.where(identifier: sync_params[:identifier]).present?
has_project = true
project = user_projects.where(identifier: sync_params[:identifier])&.first
else
has_project = false
end
if has_project
SyncLog.sync_log("=================begin_to_update_project========")
# project = user_projects.where(id: sync_params[:id]), identifier: sync_params[:identifier])&.first ||
check_sync_project(project, sync_params)
else #新建项目
SyncLog.sync_log("=================begin_to_create_new_project========")
project_params = {
repository_name: sync_params[:identifier],
user_id: project_user.id,
private: !sync_params[:is_public],
name: sync_params[:name]
}
project = Projects::CreateService.new(project_user, project_params).call
if project.present?
if sync_params[:project_score].present?
sync_params.permit!
score_params = sync_params[:project_score].merge(project_id: project.id)
new_project_score = ProjectScore.create(score_params)
SyncLog.sync_log("=================new_project_score:#{new_project_score.try(:id)}========")
end
SyncRepositoryJob.perform_later(sync_params[:owner_login], sync_params[:identifier], sync_params[:repository], get_sudomain) if sync_params[:repository].present?
check_new_project(project, sync_params)
else
SyncLog.sync_project_log("=============new_project_create_failed, trustie_project_id==:#{params[:sync_params][:id]}")
end
end
end
rescue Exception => e
SyncLog.sync_project_log("=============sync_has_errors:==#{e.message}, project_id==:#{params[:sync_params][:id]}")
end
def sync_users
params.permit!
sync_params = params[:sync_params]
users_params = sync_params[:users]
users_params.each do |u|
if User.exists?(login: u[:user_params][:login])
SyncLog.sync_log("=================sync_to_user_been_exists====#{u[:user_params][:login]}")
else
# new_user = User.new(u[:user_params])
if u[:user_params][:mail].blank?
u_mail = "#{u[:user_params][:login]}@example.com"
else
u_mail = u[:user_params][:mail]
end
new_user = User.new(u[:user_params].merge(mail: u_mail))
username = new_user.login
password = "12345678"
if new_user.save!
SyncLog.sync_log("=================sync_to_user_success==#{new_user.login}")
else
SyncLog.sync_log("=================sync_to_user_failed,user_login==#{new_user.login}")
end
# ActiveRecord::Base.transaction do
# interactor = Gitea::RegisterInteractor.call({username: username, email: new_user.mail, password: password})
# if interactor.success?
# gitea_user = interactor.result
# result = Gitea::User::GenerateTokenService.new(username, password).call
# new_user.gitea_token = result['sha1']
# new_user.gitea_uid = gitea_user['id']
# if new_user.save!
# UserExtension.create!(u[:user_extensions][:user_extensions].merge(user_id: new_user.id)) if u[:user_extensions].present? && u[:user_extensions][:user_extensions].present?
# else
# SyncLog.sync_log("=================sync_to_user_failed,user_login==#{new_user.login}")
# end
# else
# SyncLog.sync_project_log("=============sync_to_user_failed,user_login====#{new_user.login}")
# SyncLog.sync_log("=================sync_to_user_failed,user_login====#{new_user.login}")
# end
# end
end
end
# normal_status(1, "completed_sync")
rescue Exception => e
SyncLog.sync_log("=================sync_user_failed====#{e}")
end
private
def check_sync_project(project,sync_params)
begin
gitea_main = "https://www.trustie.net/"
if request.subdomain === 'testforgeplus'
gitea_main = "https://ucloudtest.trustie.net/"
end
SyncLog.sync_log("----begin_to_check_sync_project----project_id:#{project.id}---------------")
change_project_score(project, sync_params[:project_score], sync_params[:repository]) if sync_params[:repository].present? #更新project_score
change_project_issues(project, sync_params[:issues],project.id, gitea_main)
change_project_members(project, sync_params[:members],gitea_main)
change_project_versions(project, sync_params[:project_versions],gitea_main)
change_project_watchers(project, sync_params[:project_watchers],gitea_main)
change_project_praises(project, sync_params[:praise_trends],gitea_main)
rescue => e
SyncLog.sync_log("=========check_sync_project_errors:#{e}===================")
end
end
def check_new_project(project,sync_params)
SyncLog.sync_log("***8. begin_to_sync_new_project---------------")
sync_projects_params = {
type: "Project",
ids: sync_params[:id],
token: get_token,
sync_params: sync_params,
new_project_id: project.id
}
gitea_main = "https://www.trustie.net/"
if request.subdomain === 'testforgeplus'
gitea_main = "https://ucloudtest.trustie.net/"
end
SyncProjectsJob.perform_later(sync_projects_params, gitea_main)
SyncLog.sync_log("***8. end_to_sync_new_project---------------")
end
def change_project_praises(project, praises,gitea_main)
SyncLog.sync_log("***6. begin_to_sync_parises---------------")
forge_praises_ids = project&.praise_treads&.select(:id)&.pluck(:id)
diff_target_ids = praises[:ids] - forge_praises_ids
if diff_target_ids.size > 0
sync_projects_params = {
type: "PraiseTread",
ids: diff_target_ids,
token: get_token,
parent_id: project.id
}
SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
SyncLog.sync_log("***6. end_to_sync_parises---------------")
def sync_range_projects
sync_counts = params[:sync_count] || 10
projects = Project.includes(:project_score, :repository)
.where(is_public: true)
.where.not(identifier: ["educoder","trustieforge", "gitlab", "rGDBbQmOK", "socialforge"])
.joins(:project_score).order("project_scores.changeset_num desc").limit(sync_counts.to_i)
projects.each do | project |
SyncProjectMilitaryJob.perform_later(project, project.repository, project.project_score)
end
end
#检查repository和project_score
def change_project_score(project, project_scores, repository_params)
SyncLog.sync_log("***1. begin_to_sync_project_score---------------")
begin
pre_project_score = project.project_score
if pre_project_score.present?
change_num = 0
project_scores.each do |k,v|
unless pre_project_score.send("#{k}") == v
change_num += 1
pre_project_score[:"#{k}"] = v
end
if k == "changeset_num" && v.to_i > pre_project_score.changeset_num.to_i && repository_params[:url].present?
SyncRepositoryJob.perform_later(project.owner.try(:login), project.identifier, repository_params, get_sudomain)
end
end
pre_project_score.save! if change_num > 0 #如果 project_score有变化则更新
else
ProjectScore.create!(project_scores.merge(project_id: project.id))
end
SyncLog.sync_log("***1. end_to_sync_project_score---------------")
rescue Exception => e
SyncLog.sync_log("=========change_project_score_errors:#{e}===================")
end
end
# def create
# ActiveRecord::Base.transaction do
# params.permit!
# sync_params = params[:sync_params]
# project_user = User.where(login: sync_params[:owner_login])&.first
# #以前已同步的项目,那么肯定存在仓库
# SyncLog.sync_log("=================begin_to_sync_forge: project_identifier: #{sync_params[:identifier]}========")
# user_projects = Project.where(user_id: project_user.id)
# if user_projects.where(id: sync_params[:id], identifier: sync_params[:identifier]).present?
# has_project = true
# project = user_projects.where(id: sync_params[:id], identifier: sync_params[:identifier])&.first
# elsif user_projects.where(id: sync_params[:id]).present?
# has_project = true
# project = user_projects.where(id: sync_params[:id])&.first
# elsif user_projects.where(identifier: sync_params[:identifier]).present?
# has_project = true
# project = user_projects.where(identifier: sync_params[:identifier])&.first
# else
# has_project = false
# end
def change_project_issues(project, old_issues_params,project_id, gitea_main)
SyncLog.sync_log("***2. begin_to_syncissues---------------")
begin
forge_issue_ids = project&.issues&.select(:id)&.pluck(:id)
sync_projects_params = {}
unless forge_issue_ids.size.to_i <= old_issues_params[:count].to_i
diff_issue_ids = old_issues_params[:ids] - forge_issue_ids
if diff_issue_ids.size == 0 #issue数量一样判断评论是否有增减
forge_journal_ids = Journal.select([:id, :journalized_id, :journalized_type]).where(journalized_id: forge_issue_ids).pluck(:id)
diff_journal_ids = old_issues_params[:journals][:ids] - forge_journal_ids
unless diff_journal_ids.size == 0
sync_projects_params = {
type: "Journal",
ids: diff_journal_ids,
token: get_token,
parent_id: project_id
}
end
else
sync_projects_params = {
type: "Issue",
ids: diff_issue_ids,
token: get_token,
parent_id: project_id
}
end
end
SyncProjectsJob.perform_later(sync_projects_params, gitea_main) if sync_projects_params.present?
SyncLog.sync_log("***2. end_to_syncissues---------------")
rescue Exception => e
SyncLog.sync_log("=========change_project_issues_errors:#{e}===================")
end
end
# if has_project
# SyncLog.sync_log("=================begin_to_update_project========")
# check_sync_project(project, sync_params)
# else #新建项目
# SyncLog.sync_log("=================begin_to_create_new_project========")
def change_project_watchers(project, watchers,gitea_main)
SyncLog.sync_log("***5. begin_to_sync_watchers---------------")
forge_watchers_ids = project&.watchers&.select(:id)&.pluck(:id)
unless forge_watchers_ids.size.to_i <= watchers[:count].to_i
diff_target_ids = watchers[:ids] - forge_watchers_ids
if diff_target_ids.size > 0
sync_projects_params = {
type: "Watcher",
ids: diff_target_ids,
token: get_token,
parent_id: project.id
}
SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
end
end
SyncLog.sync_log("***5. begin_to_sync_watchers---------------")
end
# project_params = {
# repository_name: sync_params[:identifier],
# user_id: project_user.id,
# private: !sync_params[:is_public],
# name: sync_params[:name]
# }
# project = Projects::CreateService.new(project_user, project_params).call
# if project.present?
# if sync_params[:project_score].present?
# sync_params.permit!
# score_params = sync_params[:project_score].merge(project_id: project.id)
# new_project_score = ProjectScore.create(score_params)
# SyncLog.sync_log("=================new_project_score:#{new_project_score.try(:id)}========")
# end
def change_project_versions(project, versions,gitea_main)
SyncLog.sync_log("***4. begin_to_sync_versions---------------")
forge_version_ids = project&.versions&.select(:id)&.pluck(:id)
unless forge_version_ids.size <= versions[:count].to_i
diff_version_ids = versions[:ids] - forge_version_ids
if diff_version_ids.size > 0
sync_projects_params = {
type: "Version",
ids: diff_version_ids,
token: get_token,
parent_id: project.id
}
SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
end
SyncLog.sync_log("***4. end_to_sync_versions---------------")
end
end
# SyncRepositoryJob.perform_later(sync_params[:owner_login], sync_params[:identifier], sync_params[:repository], get_sudomain) if sync_params[:repository].present?
# check_new_project(project, sync_params)
# else
# SyncLog.sync_project_log("=============new_project_create_failed, trustie_project_id==:#{params[:sync_params][:id]}")
# end
# end
# end
# rescue Exception => e
# SyncLog.sync_project_log("=============sync_has_errors:==#{e.message}, project_id==:#{params[:sync_params][:id]}")
# end
def change_project_members(project, members,gitea_main)
SyncLog.sync_log("***3. begin_to_sync_members---------------")
forge_member_ids = project&.members&.select(:id)&.pluck(:id)
unless forge_member_ids.size <= members[:count]
diff_member_ids = members[:ids] - forge_member_ids
if diff_member_ids.size > 0
sync_projects_params = {
type: "Member",
ids: diff_member_ids,
token: get_token,
parent_id: project.id
}
SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
end
SyncLog.sync_log("***3. end_to_sync_members---------------")
end
end
# def sync_users
# params.permit!
# sync_params = params[:sync_params]
# users_params = sync_params[:users]
# def check_token
# users_params.each do |u|
# if User.exists?(login: u[:user_params][:login])
# SyncLog.sync_log("=================sync_to_user_been_exists====#{u[:user_params][:login]}")
# else
# # new_user = User.new(u[:user_params])
# if u[:user_params][:mail].blank?
# u_mail = "#{u[:user_params][:login]}@example.com"
# else
# u_mail = u[:user_params][:mail]
# end
# new_user = User.new(u[:user_params].merge(mail: u_mail))
# username = new_user.login
# password = "12345678"
# # if new_user.save!
# # SyncLog.sync_log("=================sync_to_user_success==#{new_user.login}")
# # else
# # SyncLog.sync_log("=================sync_to_user_failed,user_login==#{new_user.login}")
# # end
# ActiveRecord::Base.transaction do
# interactor = Gitea::RegisterInteractor.call({username: username, email: new_user.mail, password: password})
# if interactor.success?
# gitea_user = interactor.result
# result = Gitea::User::GenerateTokenService.new(username, password).call
# new_user.gitea_token = result['sha1']
# new_user.gitea_uid = gitea_user['id']
# if new_user.save!
# UserExtension.create!(u[:user_extensions][:user_extensions].merge(user_id: new_user.id)) if u[:user_extensions].present? && u[:user_extensions][:user_extensions].present?
# else
# SyncLog.sync_log("=================sync_to_user_failed,user_login==#{new_user.login}")
# end
# else
# SyncLog.sync_log("=============sync_to_user_failed,user_login====#{new_user.login}")
# SyncLog.sync_log("=================sync_to_user_failed,user_login====#{new_user.login}")
# end
# end
# end
# end
# # normal_status(1, "completed_sync")
# rescue Exception => e
# SyncLog.sync_log("=================sync_user_failed====#{e}")
# end
# private
# def check_sync_project(project,sync_params)
# begin
# gitea_main = "https://www.trustie.net/"
# # if request.subdomain === 'testforgeplus'
# # gitea_main = "https://ucloudtest.trustie.net/"
# # end
# SyncLog.sync_log("----begin_to_check_sync_project----project_id:#{project.id}---------------")
# change_project_score(project, sync_params[:project_score], sync_params[:repository]) if sync_params[:repository].present? #更新project_score
# change_project_issues(project, sync_params[:issues],project.id, gitea_main)
# change_project_members(project, sync_params[:members],gitea_main)
# change_project_versions(project, sync_params[:project_versions],gitea_main)
# change_project_watchers(project, sync_params[:project_watchers],gitea_main)
# change_project_praises(project, sync_params[:praise_trends],gitea_main)
# rescue => e
# SyncLog.sync_log("=========check_sync_project_errors:#{e}===================")
# end
# end
# def check_new_project(project,sync_params)
# SyncLog.sync_log("***8. begin_to_sync_new_project---------------")
# sync_projects_params = {
# type: "Project",
# ids: sync_params[:id],
# token: get_token,
# sync_params: sync_params,
# new_project_id: project.id
# }
# gitea_main = "https://www.trustie.net/"
# # if request.subdomain === 'testforgeplus'
# # gitea_main = "https://ucloudtest.trustie.net/"
# # end
# SyncProjectsJob.perform_later(sync_projects_params, gitea_main)
# SyncLog.sync_log("***8. end_to_sync_new_project---------------")
# end
# def change_project_praises(project, praises,gitea_main)
# SyncLog.sync_log("***6. begin_to_sync_parises---------------")
# forge_praises_ids = project&.praise_treads&.select(:id)&.pluck(:id)
# diff_target_ids = praises[:ids] - forge_praises_ids
# if diff_target_ids.size > 0
# sync_projects_params = {
# type: "PraiseTread",
# ids: diff_target_ids,
# token: get_token,
# parent_id: project.id
# }
# SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
# SyncLog.sync_log("***6. end_to_sync_parises---------------")
# end
# end
# #检查repository和project_score
# def change_project_score(project, project_scores, repository_params)
# SyncLog.sync_log("***1. begin_to_sync_project_score---------------")
# begin
# pre_project_score = project.project_score
# if pre_project_score.present?
# change_num = 0
# project_scores.each do |k,v|
# unless pre_project_score.send("#{k}") == v
# change_num += 1
# pre_project_score[:"#{k}"] = v
# end
# if k == "changeset_num" && v.to_i > pre_project_score.changeset_num.to_i && repository_params[:url].present?
# SyncRepositoryJob.perform_later(project.owner.try(:login), project.identifier, repository_params, get_sudomain)
# end
# end
# pre_project_score.save! if change_num > 0 #如果 project_score有变化则更新
# else
# ProjectScore.create!(project_scores.merge(project_id: project.id))
# end
# SyncLog.sync_log("***1. end_to_sync_project_score---------------")
# rescue Exception => e
# SyncLog.sync_log("=========change_project_score_errors:#{e}===================")
# end
# end
# def change_project_issues(project, old_issues_params,project_id, gitea_main)
# SyncLog.sync_log("***2. begin_to_syncissues---------------")
# begin
# forge_issue_ids = project&.issues&.select(:id)&.pluck(:id)
# sync_projects_params = {}
# SyncLog.sync_log("***2--01. forge_issue_ids-#{forge_issue_ids.size.to_i}--------------")
# if forge_issue_ids.size.to_i <= old_issues_params[:count].to_i
# diff_issue_ids = old_issues_params[:ids] - forge_issue_ids
# if diff_issue_ids.size == 0 #issue数量一样判断评论是否有增减
# forge_journal_ids = Journal.select([:id, :journalized_id, :journalized_type]).where(journalized_id: forge_issue_ids).pluck(:id)
# diff_journal_ids = old_issues_params[:journals][:ids] - forge_journal_ids
# unless diff_journal_ids.size == 0
# sync_projects_params = {
# type: "Journal",
# ids: diff_journal_ids,
# token: get_token,
# parent_id: project_id
# }
# SyncLog.sync_log("***2--02. sync_projects_params-#{sync_projects_params}--------------")
# SyncProjectsJob.perform_later(sync_projects_params, gitea_main)
# end
# else
# new_diff_ids = diff_issue_ids.in_groups_of(200).map{|k| k.reject(&:blank?)}
# diff_len = new_diff_ids.length
# (1..diff_len).each do |len|
# sync_projects_params = {
# type: "Issue",
# ids: new_diff_ids[len-1],
# token: get_token,
# parent_id: project_id
# }
# SyncLog.sync_log("***2--030#{len}. sync_projects_params_groups-#{sync_projects_params}--------------")
# SyncProjectsJob.perform_later(sync_projects_params, gitea_main)
# end
# # sync_projects_params = {
# # type: "Issue",
# # ids: diff_issue_ids,
# # token: get_token,
# # parent_id: project_id
# # }
# # SyncLog.sync_log("***2--03. sync_projects_params_groups-#{sync_projects_params}--------------")
# # SyncProjectsJob.perform_later(sync_projects_params, gitea_main)
# end
# end
# # SyncProjectsJob.perform_later(sync_projects_params, gitea_main) if sync_projects_params.present?
# SyncLog.sync_log("***2. end_to_syncissues---------------")
# rescue Exception => e
# SyncLog.sync_log("=========change_project_issues_errors:#{e}===================")
# end
# end
# def change_project_watchers(project, watchers,gitea_main)
# SyncLog.sync_log("***5. begin_to_sync_watchers---------------")
# forge_watchers_ids = project&.watchers&.select(:id)&.pluck(:id)
# if forge_watchers_ids.size.to_i <= watchers[:count].to_i
# diff_target_ids = watchers[:ids] - forge_watchers_ids
# if diff_target_ids.size > 0
# sync_projects_params = {
# type: "Watcher",
# ids: diff_target_ids,
# token: get_token,
# parent_id: project.id
# }
# SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
# end
# end
# SyncLog.sync_log("***5. begin_to_sync_watchers---------------")
# end
# def change_project_versions(project, versions,gitea_main)
# SyncLog.sync_log("***4. begin_to_sync_versions---------------")
# forge_version_ids = project&.versions&.select(:id)&.pluck(:id)
# if forge_version_ids.size <= versions[:count].to_i
# diff_version_ids = versions[:ids] - forge_version_ids
# if diff_version_ids.size > 0
# sync_projects_params = {
# type: "Version",
# ids: diff_version_ids,
# token: get_token,
# parent_id: project.id
# }
# SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
# end
# SyncLog.sync_log("***4. end_to_sync_versions---------------")
# end
# end
# def change_project_members(project, members,gitea_main)
# SyncLog.sync_log("***3. begin_to_sync_members---------------")
# forge_member_ids = project&.members&.select(:id)&.pluck(:id)
# if forge_member_ids.size <= members[:count]
# diff_member_ids = members[:ids] - forge_member_ids
# if diff_member_ids.size > 0
# sync_projects_params = {
# type: "Member",
# ids: diff_member_ids,
# token: get_token,
# parent_id: project.id
# }
# SyncProjectsJob.perform_later(sync_projects_params,gitea_main)
# end
# SyncLog.sync_log("***3. end_to_sync_members---------------")
# end
# end
# def check_token
# sync_params = params[:sync_params]
# unless sync_params[:token] && sync_params[:token] == get_token
# render json: {message: "token_errors"}
# end
# end
def get_token
"34c82f51e0b699d9d16d70fd6497c9b1e4821d6ea3e872558a6537a091076b8e"
end
# def get_token
# "34c82f51e0b699d9d16d70fd6497c9b1e4821d6ea3e872558a6537a091076b8e"
# end
def get_sudomain
SyncLog.sync_log("=================request.subdomain:#{request.subdomain}========")
gitea_main = "gitea.trustie.net"
if request.subdomain === 'testforgeplus'
gitea_main = "testgitea2.trustie.net"
# elsif request.subdomain === 'forgeplus'
# gitea_main = "gitea.trustie.net"
end
return gitea_main
end
# def get_sudomain
# SyncLog.sync_log("=================request.subdomain:#{request.subdomain}========")
# gitea_main = "gitea.trustie.net"
# if request.subdomain === 'testforgeplus'
# gitea_main = "testgitea2.trustie.net"
# # elsif request.subdomain === 'forgeplus'
# # gitea_main = "gitea.trustie.net"
# end
# return gitea_main
# end
end
end

View File

@ -1,10 +1,23 @@
class UsersController < ApplicationController
include Ci::DbConnectable
before_action :load_user, only: [:show, :homepage_info, :sync_token, :sync_gitea_pwd, :projects, :watch_users, :fan_users]
before_action :check_user_exist, only: [:show, :homepage_info,:projects, :watch_users, :fan_users]
before_action :require_login, only: %i[me list]
before_action :connect_to_ci_db, only: [:get_user_info]
skip_before_action :check_sign, only: [:attachment_show]
def connect_to_ci_db(options={})
if !(current_user && !current_user.is_a?(AnonymousUser) && current_user.devops_certification?)
return
end
if current_user.ci_cloud_account.server_type == Ci::CloudAccount::SERVER_TYPE_TRUSTIE
connect_to_trustie_ci_database(options)
else
connect_to_ci_database(options)
end
end
def list
scope = User.active.recent.like(params[:search]).includes(:user_extension)
@total_count = scope.size
@ -149,32 +162,41 @@ class UsersController < ApplicationController
def trustie_related_projects
projects = Project.includes(:owner, :members, :project_score).where(id: params[:ids]).order("updated_on desc")
projects_json = []
domain_url = EduSetting.get('host_name') + '/projects'
if projects.present?
projects.each do |p|
project_url = "/#{p.owner.login}/#{p.identifier}"
pj = {
id: p.id,
name: p.name,
is_public: p.is_public,
updated_on: p.updated_on.strftime("%Y-%m-%d"),
status: p.status,
is_member: p.member?(current_user.try(:id)),
owner: {
name: p.owner.try(:show_real_name),
login: p.owner.login
},
members_count: p&.members.size,
issues_count: p.issues_count - p.pull_requests_count,
commits_count: p&.project_score&.changeset_num.to_i
commits_count: p&.project_score&.changeset_num.to_i,
http_url: domain_url + project_url,
http_collaborator_url: domain_url + project_url + "/setting/collaborator",
http_issues_url: domain_url + project_url + "/issues",
http_commits_url: domain_url + project_url + "/commits",
project_score: p&.project_score.present? ? p&.project_score&.as_json(:except=>[:created_at, :updated_at]).merge!(commit_time: format_time(p&.project_score&.commit_time)) : {}
}
projects_json.push(pj)
end
end
Rails.logger.info("==========projects_json========+########{projects_json}")
render json: { projects: projects_json }
render json: { projects: projects_json.present? ? projects_json : {} }
end
def trustie_projects
user_id = User.select(:id, :login).where(login: params[:login])&.first&.id
projects = Project.visible
projects = projects.joins(:members).where(members: { user_id: user_id })
search = params[:search].to_s.strip

View File

@ -1,6 +1,6 @@
class VersionReleasesController < ApplicationController
before_action :find_project_with_id
before_action :set_user_and_project
before_action :load_repository
before_action :set_user
before_action :require_login, except: [:index]
before_action :find_version , only: [:edit, :update, :destroy]
@ -78,14 +78,14 @@ class VersionReleasesController < ApplicationController
ActiveRecord::Base.transaction do
begin
version_params = releases_params
if @version.update_attributes!(version_params)
create_attachments(params[:attachment_ids], @version) if params[:attachment_ids].present?
git_version_release = Gitea::Versions::UpdateService.new(@user.gitea_token, @user.try(:login), @repository.try(:identifier), version_params, @version.try(:version_gid)).call
unless git_version_release
raise Error, "更新失败"
end
normal_status(0, "更新成功")
else
normal_status(-1, "更新失败")
@ -123,14 +123,8 @@ class VersionReleasesController < ApplicationController
private
def set_user_and_project
# @project = Project.find_by_id(params[:project_id])
@repository = @project.repository #项目的仓库
@user = @project.owner
unless @user.present? && @project.present? && @repository.present?
normal_status(-1, "仓库不存在")
end
def set_user
@user = @repository.user
end
def find_version
@ -140,18 +134,18 @@ class VersionReleasesController < ApplicationController
end
end
def releases_params
def releases_params
{
body: params[:body],
draft: params[:draft] || false,
name: params[:name],
prerelease: params[:prerelease],
prerelease: params[:prerelease] || false,
tag_name: params[:tag_name],
target_commitish: params[:target_commitish] || "master" #分支
}
end
def create_attachments(attachment_ids, target)
def create_attachments(attachment_ids, target)
attachment_ids.each do |id|
attachment = Attachment.select(:id, :container_id, :container_type)&.find_by_id(id)
unless attachment.blank?

View File

@ -1,6 +1,6 @@
class VersionsController < ApplicationController
before_action :require_login, except: [:index, :show]
before_action :find_project_with_id
before_action :load_repository
before_action :check_issue_permission, except: [:show, :index]
before_action :set_version, only: [:edit, :update, :destroy, :show,:update_status]
@ -166,4 +166,4 @@ class VersionsController < ApplicationController
end
end
end
end

View File

@ -436,4 +436,9 @@ module ApplicationHelper
def find_user_by_login(login)
User.find_by_login login
end
def render_base64_decoded(str)
return nil if str.blank?
Base64.decode64 str
end
end

View File

@ -28,8 +28,10 @@ module ProjectsHelper
(User.find_by_login identifier) || (User.find_by_mail identifier)
end
def json_response(project)
repo = project.repository
def json_response(project, user)
# repo = project.repository
repo = Repository.includes(:mirror).select(:id, :mirror_url).find_by(project: project)
tmp_json = {}
unless project.common?
tmp_json = tmp_json.merge({
@ -41,16 +43,48 @@ module ProjectsHelper
end
tmp_json = tmp_json.merge({
identifier: project.identifier,
identifier: render_identifier(project),
name: project.name,
platform: project.platform,
id: project.id,
repo_id: repo.id,
open_devops: (user.blank? || user.is_a?(AnonymousUser)) ? false : project.open_devops?,
type: project.numerical_for_project_type,
author: {
login: project.owner.login,
name: project.owner.real_name,
image_url: url_to_avatar(project.owner)
}
author: render_owner(project)
}).compact
render json: tmp_json
end
def render_owner(project)
if project.educoder?
{
login: project.project_educoder.owner,
name: project.project_educoder.owner,
image_url: project.project_educoder.image_url
}
else
{
login: @owner.login,
name: @owner.real_name,
image_url: url_to_avatar(@owner)
}
end
end
def render_identifier(project)
project.educoder? ? project.project_educoder&.repo_name&.split('/')[1] : project.identifier
end
def render_author(project)
project.educoder? ? project.project_educoder&.repo_name&.split('/')[0] : project.owner.login
end
def render_educoder_avatar_url(project_educoder)
[Rails.application.config_for(:configuration)['educoder']['cdn_url'], project_educoder&.image_url].join('/')
end
def render_avatar_url(owner)
['images', url_to_avatar(owner)].join('/')
end
end

View File

@ -1,11 +1,17 @@
module RepositoriesHelper
def render_permission(user, project)
return "Admin" if user&.admin?
return "Owner" if user === project.owner
project.get_premission(user)
end
def render_decode64_content(str)
return nil if str.blank?
Base64.decode64(str).force_encoding('UTF-8')
Base64.decode64(str).force_encoding("UTF-8")
end
def download_type(str)
default_type = %w(xlsx xls ppt pptx pdf zip 7z rar exe pdb obj idb png jpg gif tif psd svg RData rdata)
default_type = %w(xlsx xls ppt pptx pdf zip 7z rar exe pdb obj idb png jpg gif tif psd svg RData rdata doc docx mpp vsdx)
default_type.include?(str&.downcase)
end
@ -44,7 +50,7 @@ module RepositoriesHelper
end
if r_content.include?("?")
new_r_content = r_content + "&raw=true"
else
else
new_r_content = r_content + "?raw=true"
end
unless r_content.include?("http://") || r_content.include?("https://") || r_content.include?("mailto:")
@ -56,4 +62,14 @@ module RepositoriesHelper
return content
end
# unix_time values for example: 1604382982
def render_format_time_with_unix(unix_time)
Time.at(unix_time).strftime("%Y-%m-%d %H:%M")
end
# date for example: 2020-11-01T19:57:27+08:00
def render_format_time_with_date(date)
date.to_time.strftime("%Y-%m-%d %H:%M")
end
end

View File

@ -1,4 +1,143 @@
module TagChosenHelper
def get_associated_data(project)
issue_comment_users_array = []
cost_time_array = []
all_issues = []
{
"assign_user": render_cache_collaborators(project),
"tracker": render_cache_trackers,
"issue_status": render_cache_issue_statuses,
"priority": render_cache_issue_priorities,
"issue_version": render_cache_milestones(project),
"start_date": "",
"due_date": "",
"joins_users": issue_comment_users_array,
"cost_time_users": cost_time_array,
# "total_cost_time": Time.at(all_cost_time).utc.strftime('%H h %M min %S s'),
# "be_depended_issues": be_depended_issues_array,
# "depended_issues":depended_issues_array,
# "estimated_hours": issue_info[7],
"done_ratio": render_complete_percentage,
"issue_tag": render_issue_tags(project),
"issue_type": render_issue_species,
"all_issues": all_issues
}
end
def render_cache_trackers
cache_key = "all_trackers/#{Tracker.maximum('id')}"
Rails.cache.fetch(cache_key) do
Tracker.select(:id, :name, :position).collect do |event|
{
id: event.id,
name: event.name,
position: event.position,
is_chosen: '0'
}
end
end
end
def render_cache_issue_statuses
cache_key = "all_issue_statuses/#{IssueStatus.maximum('id')}"
Rails.cache.fetch(cache_key) do
IssueStatus.select(:id, :name, :position).collect do |event|
{
id: event.id,
name: event.name,
position: event.position,
is_chosen: '0'
}
end
end
end
def render_cache_issue_priorities
cache_key = "all_issue_priorities/#{IssuePriority.maximum('id')}"
Rails.cache.fetch(cache_key) do
IssuePriority.select(:id, :name, :position).collect do |event|
{
id: event.id,
name: event.name,
position: event.position,
is_chosen: '0'
}
end
end
end
def render_complete_percentage
completion_nums = %w(0 10 20 30 40 50 60 70 80 90 100)
completion_nums.collect do |event|
{
id: event.to_i,
name: event + "%",
is_chosen: '0'
}
end
end
def render_issue_species
species = %W(普通 悬赏)
species.collect do |event|
{
id: event.to_i + 1,
token: nil,
is_chosen: '0'
}
end
end
def render_issue_tags(project)
# project.issue_tags.last&.cache_key
cache_key = "all_issue_tags/#{project.issue_tags.maximum('updated_at')}"
Rails.cache.fetch(cache_key) do
project.issue_tags.select(:id, :name, :color).collect do |event|
{
id: event.id,
name: event.name,
color: event.color,
is_chosen: '0'
}
end
end
end
def render_cache_milestones(project)
cache_key = "all_milestones/#{project.versions.maximum('updated_on')}"
Rails.cache.fetch(cache_key) do
project.versions.select(:id, :name, :status).collect do |event|
{
id: event.id,
name: event.name,
status: event.status,
is_chosen: '0'
}
end
end
end
def render_cache_collaborators(project)
cache_key = "all_collaborators/#{project.members.maximum('created_on')}"
Rails.cache.fetch(cache_key) do
project.members.includes(:user).collect do |event|
{
id: event.user&.id,
name: event.user&.show_real_name,
avatar_url: url_to_avatar(event.user),
is_chosen: '0'
}
end
end
end
def issue_left_chosen(project,issue_id)
issue_info = Array.new(11)
@ -205,4 +344,4 @@ module TagChosenHelper
# be_depended_issues_array
# end
end
end

View File

@ -1,15 +1,16 @@
module Gitea
class CreateFileInteractor
def self.call(user, params={})
interactor = new(user, params)
def self.call(token, owner, params={})
interactor = new(token, owner, params)
interactor.run
interactor
end
attr_reader :error, :result
def initialize(user, params)
@user = user
def initialize(token, owner, params)
@token = token
@owner = owner
@params = params
end
@ -23,7 +24,7 @@ module Gitea
def run
Contents::CreateForm.new(valid_params).validate!
response = Gitea::Repository::Entries::CreateService.new(user, @params[:identifier], @params[:filepath], file_params).call
response = Gitea::Repository::Entries::CreateService.new(token, owner, @params[:identifier], @params[:filepath], file_params).call
render_result(response)
rescue Exception => exception
Rails.logger.info "Exception ===========> #{exception.message}"
@ -33,7 +34,7 @@ module Gitea
private
attr_reader :params, :user
attr_reader :params, :owner, :token
def fail!(error)
@error = error
@ -57,6 +58,7 @@ module Gitea
file_params = file_params.merge(new_branch: @params[:new_branch]) unless @params[:new_branch].blank?
file_params = file_params.merge(content: Base64.encode64(@params[:content]))
file_params = file_params.merge(message: @params[:message]) unless @params[:message].blank?
file_params = file_params.merge(committer: @params[:committer])
file_params
end
end

View File

@ -1,15 +1,16 @@
module Gitea
class DeleteFileInteractor
def self.call(user, params={})
interactor = new(user, params)
def self.call(token, owner, params={})
interactor = new(token, owner, params)
interactor.run
interactor
end
attr_reader :error, :result
def initialize(user, params)
@user = user
def initialize(token, owner, params)
@token = token
@owner = owner
@params = params
end
@ -23,7 +24,7 @@ module Gitea
def run
Contents::DeleteForm.new(valid_params).validate!
response = Gitea::Repository::Entries::DeleteService.new(user, @params[:identifier], @params[:filepath], file_params).call
response = Gitea::Repository::Entries::DeleteService.new(token, owner, @params[:identifier], @params[:filepath], file_params).call
render_result(response)
rescue Exception => exception
fail!(exception.message)
@ -31,7 +32,7 @@ module Gitea
private
attr_reader :params, :user
attr_reader :params, :owner, :token
def fail!(error)
puts "[exception]: error"

View File

@ -22,7 +22,7 @@ module Gitea
def run
Gitea::UserForm.new(params).validate!
response = Gitea::User::RegisterService.new(params).call
response = Gitea::User::RegisterService.call(params.merge(token: token))
render_result(response)
rescue Exception => exception
Rails.logger.info "Exception ===========> #{exception.message}"
@ -41,5 +41,12 @@ module Gitea
def render_result(response)
@result = response
end
def token
{
username: Gitea.gitea_config[:access_key_id],
password: Gitea.gitea_config[:access_key_secret]
}
end
end
end

View File

@ -1,15 +1,16 @@
module Gitea
class UpdateFileInteractor
def self.call(user, params={})
interactor = new(user, params)
def self.call(token, owner, params={})
interactor = new(token, owner, params)
interactor.run
interactor
end
attr_reader :error, :result
def initialize(user, params)
@user = user
def initialize(token, owner, params)
@owner = owner
@token = token
@params = params
end
@ -23,7 +24,7 @@ module Gitea
def run
Contents::UpdateForm.new(valid_params).validate!
response = Gitea::Repository::Entries::UpdateService.new(user, @params[:identifier], @params[:filepath], file_params).call
response = Gitea::Repository::Entries::UpdateService.new(token, owner, @params[:identifier], @params[:filepath], file_params).call
render_result(response)
rescue Exception => exception
fail!(exception.message)
@ -31,7 +32,7 @@ module Gitea
private
attr_reader :params, :user
attr_reader :params, :owner, :token
def fail!(error)
puts "[exception]: error"

View File

@ -10,24 +10,8 @@ class MigrateRemoteRepositoryJob < ApplicationJob
gitea_repository = Gitea::Repository::MigrateService.new(token, params).call
if gitea_repository
repo&.project&.update_columns(gpid: gitea_repository["id"])
repo&.mirror&.update_columns(status: Mirror.statuses[:succeeded])
project = repo.project
json_data = {
mirror_status: repo.mirror_status,
mirror_num: repo.mirror_num,
mirror_url: repo.mirror_url,
first_sync: repo.first_sync?,
identifier: repo.identifier,
name: project.name,
id: project.id,
type: project.numerical_for_project_type
}
puts "############ broadcast start.......... ############"
cable_result = ActionCable.server.broadcast "channel_room_#{repo.identifier}", project: json_data
puts "############ room_channel_#{repo.identifier} result : #{cable_result}"
repo&.mirror&.succeeded!
puts "############ mirror status: #{repo.mirror.status} ############"
end
end
end

View File

@ -8,28 +8,28 @@ class SyncProjectsJob < ApplicationJob
SyncLog.sync_log("==========begin to sync #{sync_params[:type]} to forge============")
SyncLog.sync_log("==========sync_params:#{sync_params}============")
begin
begin
url = "#{gitea_main}/sync_forges" #trustie上的相关路由
uri = URI.parse(url)
http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = true
response = http.send_request('GET', uri.path, sync_params.to_json, {'Content-Type' => 'application/json'})
SyncLog.sync_log("==========response_status::#{response.code}============")
SyncLog.sync_log("=======#{sync_params[:parent_id].present? ? sync_params[:parent_id] : sync_params[:new_project_id]}===response_status::#{response.code}============")
if response.code == '200'
target_jsons = eval(response.body)
if sync_params[:type] == "Project"
SyncLog.sync_project_log("==========target_jsons: #{target_jsons}============")
# SyncLog.sync_log("==========target_jsons: #{target_jsons}============")
update_new_project(target_jsons[:targets_params][0], sync_params[:new_project_id])
else
SyncLog.sync_project_log("========== #{sync_params[:type]}============")
SyncLog.sync_log("========== #{sync_params[:type]}============")
create_target(target_jsons[:targets_params], sync_params[:type].to_s)
end
else
SyncLog.sync_project_log("==========sync_project_to_forge_failed #{sync_params[:type]}============")
SyncLog.sync_log("==========sync_project_to_forge_failed #{sync_params[:type]}============")
end
rescue => e
SyncLog.sync_project_log("==========sync_project_to_forge_failed #{sync_params[:type]}============errors:#{e}")
SyncLog.sync_log("==========sync_project_to_forge_failed #{sync_params[:type]}============errors:#{e}")
end
end
@ -39,19 +39,19 @@ class SyncProjectsJob < ApplicationJob
SyncLog.sync_log("=========begin_to_update_project=project_id: #{project_id}============")
project = Project.find_by(id: project_id)
project.update(re[:target_params]) if re[:target_params].present?
create_target(re[:issues_params], "Issue") if re[:issues_params].present?
create_target(re[:member_params], "Member") if re[:member_params].present?
create_target(re[:watcher_params], "Watcher") if re[:watcher_params].present?
create_target(re[:praise_treads], "PraiseTread") if re[:praise_treads].present?
create_versions(project, re[:versions_params]) if re[:versions_params].present?
create_target(re[:issues_params], "Issue") if re[:issues_params].present?
end
def create_target(target_jsons, target_type)
begin
SyncLog.sync_project_log("***【#{target_type}】. begin_to_create_target---------------")
return SyncLog.sync_log("*** no target_jsons") if target_jsons.blank?
target_jsons.each_with_index do |re,index|
SyncLog.sync_project_log("***user_login:#{re[:user_login]}----target_type:#{target_type}-----#{index+1}")
SyncLog.sync_log("***【#{target_type}】. begin_to_create_target---------------")
return SyncLog.sync_log("*** no target_jsons") if target_jsons.blank?
target_jsons.each_with_index do |re,index|
begin
SyncLog.sync_log("***user_login:#{re[:user_login]}----target_type:#{target_type}-----#{index+1}")
if re[:target_params].present?
SyncLog.sync_log("***user_login:#{re[:user_login]}----target_type:#{target_type}")
u_id = User.select(:id, :login).where(login: re[:user_login]).pluck(:id).first
@ -59,9 +59,12 @@ class SyncProjectsJob < ApplicationJob
if target_type == "Issue"
is_exists = Issue.exists?(author_id: u_id, project_id: re[:target_params][:project_id], subject: re[:target_params][:subject])
unless is_exists
version_name = re[:re_version]
version_id = Version.where(project_id: re[:target_params][:project_id], name: version_name)&.first&.id if version_name.present?
assing_u_id = User.select(:id, :login).where(login: re[:assign_login]).pluck(:id).first
new_target = target_type.constantize.new(re[:target_params].merge(author_id: u_id))
new_target.assigned_to_id = assing_u_id
new_target.fixed_version_id = version_id if version_id.present?
end
else
case target_type
@ -84,7 +87,7 @@ class SyncProjectsJob < ApplicationJob
end
if !is_exists && new_target.save!
SyncLog.sync_project_log("***【#{target_type}】. create_success---------------")
SyncLog.sync_log("***【#{target_type}】. create_success---------------")
if re[:journals].present?
create_journals(re[:journals], "Journal", new_target.id)
end
@ -101,43 +104,51 @@ class SyncProjectsJob < ApplicationJob
end
end
else
SyncLog.sync_project_log("***【#{target_type}】. create_failed---or has_exists---------------")
SyncLog.sync_log("***【#{target_type}】. create_failed---or has_exists---------------")
end
end
SyncLog.sync_log("***111222. end_to_create_target---------------")
rescue => e
SyncLog.sync_log("=========***【#{target_type}】creat_had_erros:#{e}===================")
next
end
SyncLog.sync_project_log("***111222. end_to_create_target---------------")
rescue => e
SyncLog.sync_project_log("=========***【#{target_type}】creat_had_erros:#{e}===================")
end
end
def create_journals(target_jsons, target_type,issue_id)
SyncLog.sync_log("***【#{target_type}】. begin_to_create_target---------------")
return SyncLog.sync_log("*** no target_jsons") if target_jsons.blank?
target_jsons.each_with_index do |re,index|
SyncLog.sync_log("***user_login:#{re[:user_login]}----target_type:#{target_type}-----#{index+1}")
if re[:target_params].present?
u_id = User.select(:id, :login).where(login: re[:user_login]).pluck(:id).first
is_exists = Journal.exists?(user_id: u_id, journalized_id: re[:target_params][:journalized_id], created_on: re[:target_params][:created_on].to_s.to_time)
begin
SyncLog.sync_log("***user_login:#{re[:user_login]}----target_type:#{target_type}-----#{index+1}")
if re[:target_params].present?
u_id = User.select(:id, :login).where(login: re[:user_login]).pluck(:id).first
is_exists = Journal.exists?(user_id: u_id, journalized_id: re[:target_params][:journalized_id], created_on: re[:target_params][:created_on].to_s.to_time)
if is_exists
SyncLog.sync_project_log("***00000. Journal:#{re[:target_params][:id]}-is exists--------------")
else
re[:target_params].delete(:id)
new_target = Journal.new(re[:target_params].merge(user_id: u_id))
new_target.journalized_id = issue_id
if new_target.save!
if re[:journal_details].present?
re[:journal_details].each do |j|
JournalDetail.create!(j.merge(journal_id: new_target.id))
end
end
if is_exists
SyncLog.sync_log("***00000. Journal:#{re[:target_params][:id]}-is exists--------------")
else
SyncLog.sync_project_log("***111222. journal_create failed---------------")
re[:target_params].delete(:id)
new_target = Journal.new(re[:target_params].merge(user_id: u_id))
new_target.journalized_id = issue_id
if new_target.save!
if re[:journal_details].present?
re[:journal_details].each do |j|
JournalDetail.create!(j.merge(journal_id: new_target.id))
end
end
else
SyncLog.sync_log("***111222. journal_create failed---------------")
end
end
end
rescue => e
SyncLog.sync_log("***111222. journal_create failed---#{e}------------")
next
end
end
SyncLog.sync_log("***111222. end_to_create_journal---------------")
end
@ -151,15 +162,16 @@ class SyncProjectsJob < ApplicationJob
u_id = User.select(:id, :login).where(login: re[:user_login]).pluck(:id).first
is_exists = Version.exists?(user_id: u_id, project_id: re[:target_params][:project_id], created_on: re[:target_params][:created_on].to_s.to_time)
if is_exists
SyncLog.sync_project_log("***00000. Version:#{re[:target_params][:id]}-is exists--------------")
SyncLog.sync_log("***00000. Version:#{re[:target_params][:id]}-is exists--------------")
else
re[:target_params].delete(:id)
new_target = Version.new(re[:target_params].merge(user_id: u_id))
if new_target.save!
all_issues = project.issues.select(:id, :project_id, :fixed_version_id)
all_issues&.where(fixed_version_id: old_id)&.update_all(fixed_version_id: new_target.id)
SyncLog.sync_log("***111222. Version_create success-#{new_target.id}--------------")
# all_issues = project.issues.select(:id, :project_id, :fixed_version_id)
# all_issues&.where(fixed_version_id: old_id)&.update_all(fixed_version_id: new_target.id)
else
SyncLog.sync_project_log("***111222. Version_create failed---------------")
SyncLog.sync_log("***111222. Version_create failed-#{old_id}--------------")
end
end
end
@ -167,4 +179,4 @@ class SyncProjectsJob < ApplicationJob
SyncLog.sync_log("***111222. end_to_create_target---------------")
end
end
end

View File

@ -25,13 +25,14 @@ class SyncRepositoryJob < ApplicationJob
gitlab_branches.each do |branch|
shell5 = system("cd #{path}/#{image_repo_name} && git checkout #{branch} && git push --force --set-upstream origin #{branch}")
if !shell5
SyncLog.sync_project_log("=============force_push_erros==#{path}/#{image_repo_name}++branch:#{branch}")
SyncLog.sync_log("=============force_push_erros==#{path}/#{image_repo_name}++branch:#{branch}")
else
SyncLog.sync_project_log("=============force_push_success==#{path}/#{image_repo_name}++branch+++#{branch}")
SyncLog.sync_log("=============force_push_success==#{path}/#{image_repo_name}++branch+++#{branch}")
system("rm -rf #{path}/#{image_repo_name}")
end
end
else
SyncLog.sync_project_log("=============check_clone_erros==#{path}/#{image_repo_name}")
SyncLog.sync_log("=============check_clone_erros==#{path}/#{image_repo_name}")
SyncLog.sync_log("++++++++++++++++++check_clone_erros++++++++++++++++++#{image_repo_name}")
end
SyncLog.sync_log("=================end to sync repository=====================#{image_repo_name}")

View File

@ -85,24 +85,4 @@ class Ci::Drone::API < Ci::Drone::Request
post(endpoint, "/api/users", {login: options[:login], email: options[:email], avatar_url:options[:avatar_url],active:true, drone_token: options[:token]})
end
# Creates a secret.
def create_secret
post(endpoint, "/api/repos/#{owner}/#{repo}/secrets", {name: options[:name], data: options[:data], pull_request:true, drone_token: drone_token})
end
# Update a secret.
def update_secret
patch(endpoint, "/api/repos/#{owner}/#{repo}/secrets/#{options[:name]}", { data: options[:data], pull_request:true, drone_token: drone_token})
end
# list of secrets.
def secrets
get(endpoint, "/api/repos/#{owner}/#{repo}/secrets", drone_token: drone_token)
end
# delete secret.
def delete_secret
delete(endpoint, "/api/repos/#{owner}/#{repo}/secrets/#{options[:name]}", drone_token: drone_token)
end
end

View File

@ -5,4 +5,5 @@ module CustomRegexp
NICKNAME = /\A[\u4e00-\u9fa5_a-zA-Z0-9]+\z/
PASSWORD = /\A[a-z_A-Z0-9\-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'_<>~\·`\?:;|]{8,16}\z/
URL = /\Ahttps?:\/\/[-A-Za-z0-9+&@#\/%?=~_|!:,.;]+[-A-Za-z0-9+&@#\/%=~_|]\z/
end
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])$/
end

View File

@ -1,5 +1,23 @@
# == Schema Information
#
# Table name: applied_messages
#
# id :integer not null, primary key
# user_id :integer
# applied_id :integer
# applied_type :string(255)
# viewed :integer default("0")
# status :integer default("0")
# created_at :datetime not null
# updated_at :datetime not null
# name :string(255)
# applied_user_id :integer
# role :integer
# project_id :integer
#
class AppliedMessage < ApplicationRecord
belongs_to :user
belongs_to :applied, polymorphic: true
end
end

View File

@ -1,3 +1,14 @@
# == Schema Information
#
# Table name: applied_projects
#
# id :integer not null, primary key
# project_id :integer not null
# user_id :integer not null
# role :integer default("0")
# status :integer default("0")
#
class AppliedProject < ApplicationRecord
belongs_to :user
belongs_to :project

View File

@ -1,3 +1,26 @@
# == Schema Information
#
# Table name: apply_actions
#
# id :integer not null, primary key
# user_id :integer
# reason :string(255)
# container_id :integer
# container_type :string(255)
# dealer_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# status :integer default("0")
# apply_reason :text(65535)
# noticed :boolean default("0")
# ip_addr :string(255)
# reject_description :string(255)
#
# Indexes
#
# index_apply_actions_on_user_id (user_id)
#
# 申请消息
class ApplyAction < ApplicationRecord
belongs_to :user
@ -27,4 +50,4 @@ class ApplyAction < ApplicationRecord
belong_container_id: container_id, belong_container_type: belong_container_type)
end
end
end
end

View File

@ -1,3 +1,23 @@
# == Schema Information
#
# Table name: apply_user_authentications
#
# id :integer not null, primary key
# user_id :integer
# status :integer
# auth_type :integer
# remarks :string(255)
# dealer :integer
# deal_time :datetime
# created_at :datetime not null
# updated_at :datetime not null
# is_delete :boolean default("0")
#
# Indexes
#
# index_apply_user_authentications_on_user_id (user_id)
#
# status0 审核中 1 同意 2 拒绝 3 撤销
# auth_type1 实名认证, 2 职业认证
class ApplyUserAuthentication < ApplicationRecord

View File

@ -1,3 +1,42 @@
# == Schema Information
#
# Table name: attachments
#
# id :integer not null, primary key
# container_id :integer
# container_type :string(30)
# filename :string(255) default(""), not null
# disk_filename :string(255) default(""), not null
# filesize :integer default("0"), not null
# content_type :string(255) default("")
# digest :string(60) default(""), not null
# downloads :integer default("0"), not null
# author_id :integer default("0"), not null
# created_on :datetime
# description :text(65535)
# disk_directory :string(255)
# attachtype :integer default("1")
# is_public :integer default("1")
# copy_from :integer
# quotes :integer default("0")
# is_publish :integer default("1")
# publish_time :datetime
# resource_bank_id :integer
# unified_setting :boolean default("1")
# cloud_url :string(255) default("")
# course_second_category_id :integer default("0")
# delay_publish :boolean default("0")
#
# Indexes
#
# index_attachments_on_author_id (author_id)
# index_attachments_on_container_id_and_container_type (container_id,container_type)
# index_attachments_on_course_second_category_id (course_second_category_id)
# index_attachments_on_created_on (created_on)
# index_attachments_on_is_public (is_public)
# index_attachments_on_quotes (quotes)
#
class Attachment < ApplicationRecord
include BaseModel
include Publicable

View File

@ -1,3 +1,22 @@
# == Schema Information
#
# Table name: attachment_group_settings
#
# id :integer not null, primary key
# attachment_id :integer
# course_group_id :integer
# course_id :integer
# publish_time :datetime
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_attachment_group_settings_on_attachment_id (attachment_id)
# index_attachment_group_settings_on_course_group_id (course_group_id)
# index_attachment_group_settings_on_course_id (course_id)
#
class AttachmentGroupSetting < ActiveRecord::Base
belongs_to :attachment
# belongs_to :course_group

View File

@ -1,3 +1,31 @@
# == Schema Information
#
# Table name: attachment_histories
#
# id :integer not null, primary key
# container_id :integer
# container_type :string(255)
# filename :string(255) default("")
# disk_filename :string(255) default("")
# filesize :integer default("0")
# content_type :string(255) default("")
# digest :string(60) default("")
# downloads :integer default("0")
# author_id :integer
# created_on :datetime
# description :text(65535)
# disk_directory :string(255)
# attachtype :integer
# is_public :integer
# copy_from :integer
# quotes :integer
# version :integer
# attachment_id :integer
# is_publish :integer default("1")
# publish_time :date
# cloud_url :string(255) default("")
#
class AttachmentHistory < ApplicationRecord
include Publishable
include Publicable

View File

@ -1,3 +1,20 @@
# == Schema Information
#
# Table name: bidding_users
#
# id :integer not null, primary key
# project_package_id :integer
# user_id :integer
# status :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_bidding_users_on_project_package_id (project_package_id)
# index_bidding_users_on_user_id (user_id)
#
class BiddingUser < ApplicationRecord
include AASM
@ -21,4 +38,4 @@ class BiddingUser < ApplicationRecord
def status_text
I18n.t("bidding_user.status.#{status}")
end
end
end

View File

@ -11,6 +11,4 @@ class Ci::Build < Ci::RemoteBase
scope :pending, -> { by_status('pending') }
scope :killed, -> { by_status('killed') }
scope :by_status, ->(status) { where(build_status: status) }
scope :by_branch, ->(branch) { where(build_target: branch) }
end

View File

@ -4,10 +4,10 @@ class Ci::Perm < Ci::RemoteBase
belongs_to :user, class_name: 'Ci::User', foreign_key: :perm_user_id
belongs_to :repo, class_name: 'Ci::Repo', foreign_key: :perm_repo_uid
def self.auto_create!(user_id, repo_id)
def self.auto_create!(user, repo)
perm = new(
perm_user_id: user_id,
perm_repo_uid: repo_id,
perm_user_id: user.user_id,
perm_repo_uid: repo.repo_id,
perm_read: true,
perm_write: true,
perm_admin: true,

View File

@ -20,53 +20,37 @@ class Ci::Repo < Ci::RemoteBase
return repos
end
def self.load_repo_by_repo_slug(repo_slug)
logger.info "########repo_slug: #{repo_slug}"
repo = Ci::Repo.where(repo_slug: repo_slug).first
return repo
end
def find_by_repo_name(repo_name)
logger.info "########repo_name: #{repo_name}"
repos = Ci::Repo.where(repo_name: repo_name)
return repos
def activate!(ci_user_id)
update(repo_active: 1,
repo_signer: generate_code,
repo_secret: generate_code,
repo_user_id: ci_user_id,
repo_timeout: 60,
repo_config: '.trustie-pipeline.yml',
repo_updated: Time.now.to_i)
end
def self.auto_create!(user, project)
create_params = {
repo = new(
repo_user_id: user.user_id,
repo_namespace: project.owner.login,
repo_name: project.identifier,
repo_slug: "#{project.owner.login}/#{project.identifier}",
repo_clone_url: project.repository.url,
repo_branch: 'master',
repo_config: '.trustie-pipeline.yml'
}
repo = create_repo(create_params)
repo
end
def self.create_repo(create_params)
repo = new(
repo_user_id: create_params[:repo_user_id],
repo_namespace: create_params[:repo_namespace],
repo_name: create_params[:repo_name],
repo_slug: create_params[:repo_slug],
repo_scm: "git",
repo_ssh_url: "",
repo_html_url: "",
repo_clone_url: create_params[:repo_clone_url],
repo_clone_url: project.repository.url,
repo_active: 1,
repo_private: true,
repo_visibility: 'private',
repo_branch: create_params[:repo_branch],
repo_branch: 'master',
repo_counter: 0,
repo_trusted: false,
repo_protected: false,
repo_synced: 0,
repo_version: 1,
repo_timeout: 60,
repo_config: create_params[:repo_config],
repo_config: '.trustie-pipeline.yml',
repo_created: Time.now.to_i,
repo_updated: Time.now.to_i
)
@ -74,34 +58,13 @@ class Ci::Repo < Ci::RemoteBase
repo.repo_signer = repo.generate_code
repo.repo_secret = repo.generate_code
if repo.save!
Ci::Perm.auto_create!(create_params[:repo_user_id], repo.id)
Ci::Perm.auto_create!(user, repo)
repo.update_column(:repo_uid, repo.id)
repo
end
end
# 取消激活同一个项目多个repo
def deactivate_repos!
repos = find_by_repo_name(self.repo_name)
repos.each do |repo|
repo.update_column(:repo_active, 0)
end
end
def activate!(project)
repos = find_by_repo_name(self.repo_name)
project.update_column(:open_devops, true)
project.increment!(:open_devops_count)
repos.each do |repo|
repo.update_column(:repo_active, 1)
end
end
def deactivate!
update_column(:repo_active, 0)
end
def destroy!
self.destroy
end
end

View File

@ -1,3 +1,23 @@
# == Schema Information
#
# Table name: composes
#
# id :integer not null, primary key
# user_id :integer
# title :string(255)
# description :text(65535)
# show_mode :integer default("0")
# compose_mode :boolean default("0")
# compose_users_count :integer default("0")
# compose_projects_count :integer default("0")
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_composes_on_user_id_and_show_mode_and_compose_mode (user_id,show_mode,compose_mode)
#
class Compose < ApplicationRecord
#组织
belongs_to :user

View File

@ -1,3 +1,20 @@
# == Schema Information
#
# Table name: compose_projects
#
# id :integer not null, primary key
# user_id :integer
# project_id :integer
# compose_id :integer
# position :integer default("0")
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_compose_projects_on_user_id_and_project_id_and_compose_id (user_id,project_id,compose_id)
#
class ComposeProject < ApplicationRecord
#组织的项目记录表
belongs_to :compose

View File

@ -1,3 +1,19 @@
# == Schema Information
#
# Table name: compose_users
#
# id :integer not null, primary key
# user_id :integer
# compose_id :integer
# is_manager :integer default("0")
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_compose_users_on_user_id_and_compose_id (user_id,compose_id)
#
class ComposeUser < ApplicationRecord
belongs_to :compose
belongs_to :user

View File

@ -5,6 +5,7 @@ module Matchable
scope :with_project_category, ->(category_id) { where(project_category_id: category_id) unless category_id.blank? }
scope :with_project_language, ->(language_id) { where(project_language_id: language_id) unless language_id.blank? }
scope :with_project_type, ->(project_type) { where(project_type: project_type) if Project.project_types.include?(project_type) }
scope :by_name_or_identifier, ->(search) { where("name like :search or identifier LIKE :search", :search => "#{search.split(" ").join('|')}%") unless search.blank? }
end
end

View File

@ -7,6 +7,7 @@ module ProjectOperable
has_many :managers, -> { joins(:roles).where(roles: { name: 'Manager' }) }, class_name: 'Member'
has_many :developers, -> { joins(:roles).where(roles: { name: 'Developer' }) }, class_name: 'Member'
has_many :reporters, -> { joins(:roles).where(roles: { name: 'Reporter' }) }, class_name: 'Member'
has_many :writable_members, -> { joins(:roles).where.not(roles: {name: 'Reporter'}) }, class_name: 'Member'
end
def add_member!(user_id, role_name='Developer')

View File

@ -1,5 +1,18 @@
# == Schema Information
#
# Table name: coo_imgs
#
# id :integer not null, primary key
# src_states :string(255)
# url_states :string(255)
# img_type :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# position :integer
#
class CooImg < ApplicationRecord
extend Enumerize
enumerize :img_type, in: %i[com_coop edu_coop alliance_coop]
end
end

View File

@ -1,3 +1,21 @@
# == Schema Information
#
# Table name: diff_records
#
# id :integer not null, primary key
# user_id :integer
# container_type :string(255)
# container_id :integer
# column_name :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_diff_records_on_container_type_and_container_id (container_type,container_id)
# index_diff_records_on_user_id (user_id)
#
class DiffRecord < ApplicationRecord
belongs_to :user
belongs_to :container, polymorphic: true
@ -5,4 +23,4 @@ class DiffRecord < ApplicationRecord
has_one :diff_record_content, dependent: :destroy
delegate :content, to: :diff_record_content
end
end

View File

@ -1,3 +1,16 @@
# == Schema Information
#
# Table name: diff_record_contents
#
# id :integer not null, primary key
# diff_record_id :integer
# content :text(65535)
#
# Indexes
#
# index_diff_record_contents_on_diff_record_id (diff_record_id)
#
class DiffRecordContent < ApplicationRecord
belongs_to :diff_record
end
end

View File

@ -1,3 +1,19 @@
# == Schema Information
#
# Table name: edu_settings
#
# id :integer not null, primary key
# name :string(255)
# value :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# description :string(255)
#
# Indexes
#
# index_edu_settings_on_name (name) UNIQUE
#
class EduSetting < ApplicationRecord
after_commit :expire_value_cache

View File

@ -1,4 +1,23 @@
# == Schema Information
#
# Table name: fork_users
#
# id :integer not null, primary key
# project_id :integer
# fork_project_id :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_fork_users_on_project_id (project_id)
# index_fork_users_on_user_id (user_id)
#
class ForkUser < ApplicationRecord
belongs_to :project
belongs_to :project
belongs_to :user
belongs_to :fork_project, class_name: 'Project', foreign_key: :fork_project_id
end

View File

@ -1,3 +1,14 @@
# == Schema Information
#
# Table name: ignores
#
# id :integer not null, primary key
# name :string(255)
# content :text(65535)
# created_at :datetime not null
# updated_at :datetime not null
#
class Ignore < ApplicationRecord
include Projectable
end

View File

@ -1,3 +1,53 @@
# == Schema Information
#
# Table name: issues
#
# id :integer not null, primary key
# tracker_id :integer not null
# project_id :integer not null
# subject :string(255) default(""), not null
# description :text(4294967295)
# due_date :date
# category_id :integer
# status_id :integer not null
# assigned_to_id :integer
# priority_id :integer not null
# fixed_version_id :integer
# author_id :integer not null
# created_on :datetime
# updated_on :datetime
# start_date :date
# done_ratio :integer default("0"), not null
# estimated_hours :float(24)
# parent_id :integer
# root_id :integer
# lft :integer
# rgt :integer
# is_private :boolean default("0"), not null
# closed_on :datetime
# project_issues_index :integer
# issue_type :string(255)
# token :integer default("0")
# issue_tags_value :string(255)
# is_lock :boolean default("0")
# issue_classify :string(255)
# ref_name :string(255)
# branch_name :string(255)
#
# 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_created_on (created_on)
# index_issues_on_fixed_version_id (fixed_version_id)
# index_issues_on_priority_id (priority_id)
# index_issues_on_root_id_and_lft_and_rgt (root_id,lft,rgt)
# index_issues_on_status_id (status_id)
# index_issues_on_tracker_id (tracker_id)
# issues_project_id (project_id)
#
class Issue < ApplicationRecord
#issue_type 1为普通2为悬赏
belongs_to :project, :counter_cache => true

View File

@ -1,3 +1,19 @@
# == Schema Information
#
# Table name: issue_depends
#
# id :integer not null, primary key
# user_id :integer
# issue_id :integer
# depend_issue_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_issue_depends_on_user_id_and_issue_id_and_depend_issue_id (user_id,issue_id,depend_issue_id)
#
class IssueDepend < ApplicationRecord
belongs_to :issue
end

View File

@ -1,3 +1,18 @@
# == Schema Information
#
# Table name: issue_priorities
#
# id :integer not null, primary key
# name :string(255)
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_issue_priorities_on_name (name)
#
class IssuePriority < ApplicationRecord
has_many :issues
end
end

View File

@ -1,4 +1,22 @@
# == Schema Information
#
# Table name: issue_statuses
#
# id :integer not null, primary key
# name :string(30) default(""), not null
# is_closed :boolean default("0"), not null
# is_default :boolean default("0"), not null
# position :integer default("1")
# default_done_ratio :integer
#
# Indexes
#
# index_issue_statuses_on_is_closed (is_closed)
# index_issue_statuses_on_is_default (is_default)
# index_issue_statuses_on_position (position)
#
class IssueStatus < ApplicationRecord
has_many :issues
belongs_to :project, optional: true
end
end

View File

@ -1,3 +1,24 @@
# == Schema Information
#
# Table name: issue_tags
#
# id :integer not null, primary key
# name :string(255)
# description :string(255)
# color :string(255)
# user_id :integer
# project_id :integer
# issues_count :integer default("0")
# created_at :datetime not null
# updated_at :datetime not null
# gid :integer
# gitea_url :string(255)
#
# Indexes
#
# index_issue_tags_on_user_id_and_name_and_project_id (user_id,name,project_id)
#
class IssueTag < ApplicationRecord
has_many :issue_tags_relates, dependent: :destroy

View File

@ -1,3 +1,18 @@
# == Schema Information
#
# Table name: issue_tags_relates
#
# id :integer not null, primary key
# issue_id :integer
# issue_tag_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_issue_tags_relates_on_issue_id_and_issue_tag_id (issue_id,issue_tag_id)
#
class IssueTagsRelate < ApplicationRecord
belongs_to :issue
belongs_to :issue_tag, counter_cache: :issues_count

View File

@ -1,3 +1,21 @@
# == Schema Information
#
# Table name: issue_times
#
# id :integer not null, primary key
# issue_id :integer
# user_id :integer
# start_time :datetime
# end_time :datetime
# cost_time :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_issue_times_on_issue_id_and_user_id (issue_id,user_id)
#
class IssueTime < ApplicationRecord
belongs_to :issue
belongs_to :user

View File

@ -1,3 +1,26 @@
# == Schema Information
#
# Table name: journals
#
# id :integer not null, primary key
# journalized_id :integer default("0"), not null
# journalized_type :string(30) default(""), not null
# user_id :integer default("0"), not null
# notes :text(65535)
# created_on :datetime not null
# private_notes :boolean default("0"), not null
# parent_id :integer
# comments_count :integer default("0")
# reply_id :integer
#
# Indexes
#
# index_journals_on_created_on (created_on)
# index_journals_on_journalized_id (journalized_id)
# index_journals_on_user_id (user_id)
# journals_journalized_id (journalized_id,journalized_type)
#
class Journal < ApplicationRecord
belongs_to :user
belongs_to :issue, foreign_key: :journalized_id, :touch => true
@ -150,4 +173,4 @@ class Journal < ApplicationRecord
end
end
end

View File

@ -1,3 +1,19 @@
# == Schema Information
#
# Table name: journal_details
#
# id :integer not null, primary key
# journal_id :integer default("0"), not null
# property :string(30) default(""), not null
# prop_key :string(30) default(""), not null
# old_value :text(65535)
# value :text(65535)
#
# Indexes
#
# journal_details_journal_id (journal_id)
#
class JournalDetail < ApplicationRecord
belongs_to :journal
end
end

View File

@ -1,3 +1,32 @@
# == Schema Information
#
# Table name: journals_for_messages
#
# id :integer not null, primary key
# jour_id :integer
# jour_type :string(255)
# user_id :integer
# notes :text(65535)
# status :integer
# reply_id :integer
# created_on :datetime not null
# updated_on :datetime not null
# m_parent_id :string(255)
# is_readed :boolean
# m_reply_count :integer
# m_reply_id :integer
# is_comprehensive_evaluation :integer
# private :integer default("0")
# root_id :integer
# hidden :boolean default("0")
# praises_count :integer default("0")
#
# Indexes
#
# index_journals_for_messages_on_jour_id (jour_id)
# index_journals_for_messages_on_root_id (root_id)
#
class JournalsForMessage < ApplicationRecord
belongs_to :jour, :polymorphic => true
belongs_to :user

View File

@ -1,3 +1,17 @@
# == Schema Information
#
# Table name: laboratories
#
# id :integer not null, primary key
# school_id :integer
# identifier :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# sync_course :boolean default("0")
# sync_subject :boolean default("0")
# sync_shixun :boolean default("0")
#
class Laboratory < ApplicationRecord
belongs_to :school, optional: true

View File

@ -1,3 +1,12 @@
# == Schema Information
#
# Table name: laboratory_settings
#
# id :integer not null, primary key
# laboratory_id :integer
# config :text(65535)
#
class LaboratorySetting < ApplicationRecord
belongs_to :laboratory
@ -63,12 +72,13 @@ class LaboratorySetting < ApplicationRecord
navbar: [
{ 'name' => '首页', 'link' => '/projects', 'hidden' => false },
{ 'name' => '课程', 'link' => '/courses', 'hidden' => false },
{ 'name' => '项目', 'link' => '/projects', 'hidden' => false },
{ 'name' => '项目', 'link' => '', 'hidden' => true },
{ 'name' => '数据', 'link' => '/datas', 'hidden' => false },
{ 'name' => '竞赛', 'link' => '/competitions', 'hidden' => false },
{ 'name' => '问吧', 'link' => '/forums', 'hidden' => false },
{ 'name' => '开源社区', 'link' => '/projects', 'hidden' => false },
],
footer: nil
}
end
end
end

View File

@ -1,4 +1,18 @@
# == Schema Information
#
# Table name: laboratory_users
#
# id :integer not null, primary key
# laboratory_id :integer
# user_id :integer
#
# Indexes
#
# index_laboratory_users_on_laboratory_id (laboratory_id)
# index_laboratory_users_on_user_id (user_id)
#
class LaboratoryUser < ApplicationRecord
belongs_to :laboratory
belongs_to :user
end
end

View File

@ -1,3 +1,15 @@
# == Schema Information
#
# Table name: licenses
#
# id :integer not null, primary key
# name :string(255)
# content :text(65535)
# created_at :datetime not null
# updated_at :datetime not null
# is_secret :boolean default("0")
#
class License < ApplicationRecord
include Projectable
end

View File

@ -1,3 +1,26 @@
# == Schema Information
#
# Table name: members
#
# id :integer not null, primary key
# user_id :integer default("0"), not null
# project_id :integer default("0")
# created_on :datetime
# mail_notification :boolean default("0"), not null
# course_id :integer default("-1")
# course_group_id :integer default("0")
# is_collect :integer default("1")
# graduation_group_id :integer default("0")
# is_apply_signature :boolean default("0")
#
# Indexes
#
# index_members_on_course_id (course_id)
# index_members_on_project_id (project_id)
# index_members_on_user_id (user_id)
# index_members_on_user_id_and_project_id (user_id,project_id,course_id) UNIQUE
#
class Member < ApplicationRecord
belongs_to :user
# belongs_to :course, optional: true

View File

@ -1,3 +1,19 @@
# == Schema Information
#
# Table name: member_roles
#
# id :integer not null, primary key
# member_id :integer not null
# role_id :integer not null
# inherited_from :integer
# is_current :integer default("1")
#
# Indexes
#
# index_member_roles_on_member_id (member_id)
# index_member_roles_on_role_id (role_id)
#
class MemberRole < ApplicationRecord
belongs_to :role
belongs_to :member

View File

@ -1,11 +1,26 @@
# == Schema Information
#
# Table name: mirrors
#
# id :integer not null, primary key
# repo_id :integer
# status :integer default("0"), not null
# interval :integer
# next_update_time :datetime
# created_at :datetime not null
# updated_at :datetime not null
# sync_num :integer default("1")
#
class Mirror < ApplicationRecord
# 0 - succeeded, 1 - waiting, 2 - failed
# 0: 同步镜像成功1: 正在同步镜像2: 同步失败; 默认值为0
enum status: { succeeded: 0, waiting: 1, failed: 2 }
belongs_to :repository, foreign_key: :repo_id
after_update :websocket_boardcast, if: :saved_change_to_status?
belongs_to :repository, foreign_key: :repo_id
def set_status!(status=Mirror.statuses[:succeeded])
update_column(:status, status)
@ -14,4 +29,9 @@ class Mirror < ApplicationRecord
def numerical_for_status
self.class.name.constantize.statuses["#{self.status}"]
end
private
def websocket_boardcast
BroadcastMirrorRepoMsgJob.perform_later(self.repository.id)
end
end

View File

@ -1,3 +1,18 @@
# == Schema Information
#
# Table name: onclick_times
#
# id :integer not null, primary key
# user_id :integer
# onclick_time :datetime
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_onclick_times_on_user_id (user_id)
#
class OnclickTime < ApplicationRecord
belongs_to :user

View File

@ -1,3 +1,21 @@
# == 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 OpenUser < ApplicationRecord
belongs_to :user
@ -8,4 +26,4 @@ class OpenUser < ApplicationRecord
def can_bind_cache_key
"open_user:#{type}:#{uid}:can_bind"
end
end
end

View File

@ -1,3 +1,21 @@
# == 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::Cas < OpenUser
def nickname
extra&.[]('nickname')
@ -6,4 +24,4 @@ class OpenUsers::Cas < OpenUser
def en_type
'cas'
end
end
end

View File

@ -1,3 +1,21 @@
# == 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::QQ < OpenUser
def nickname
extra&.[]('nickname')
@ -6,4 +24,4 @@ class OpenUsers::QQ < OpenUser
def en_type
'qq'
end
end
end

View File

@ -1,3 +1,21 @@
# == 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::Wechat < OpenUser
def nickname
extra&.[]('nickname')
@ -6,4 +24,4 @@ class OpenUsers::Wechat < OpenUser
def en_type
'wechat'
end
end
end

View File

@ -1,3 +1,20 @@
# == Schema Information
#
# Table name: praise_treads
#
# id :integer not null, primary key
# user_id :integer not null
# praise_tread_object_id :integer
# praise_tread_object_type :string(255)
# praise_or_tread :integer default("1")
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# praise_tread (praise_tread_object_id,praise_tread_object_type)
#
class PraiseTread < ApplicationRecord
belongs_to :user
belongs_to :praise_tread_object, polymorphic: true, counter_cache: :praises_count

View File

@ -1,2 +1,15 @@
# == Schema Information
#
# Table name: praise_tread_caches
#
# id :integer not null, primary key
# object_id :integer not null
# object_type :string(255)
# praise_num :integer
# tread_num :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class PraiseTreadCache < ApplicationRecord
end

View File

@ -1,3 +1,23 @@
# == Schema Information
#
# Table name: private_messages
#
# id :integer not null, primary key
# user_id :integer
# target_id :integer
# sender_id :integer
# receiver_id :integer
# content :text(65535)
# send_time :datetime
# status :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_private_messages_on_user_id (user_id)
#
class PrivateMessage < ApplicationRecord
belongs_to :user
belongs_to :target, class_name: "User"

View File

@ -1,3 +1,73 @@
# == Schema Information
#
# Table name: projects
#
# id :integer not null, primary key
# name :string(255) default(""), not null
# description :text(4294967295)
# homepage :string(255) default("")
# is_public :boolean default("1"), not null
# parent_id :integer
# created_on :datetime
# updated_on :datetime
# identifier :string(255)
# status :integer default("1"), not null
# lft :integer
# rgt :integer
# inherit_members :boolean default("0"), not null
# project_type :integer default("0")
# hidden_repo :boolean default("0"), not null
# attachmenttype :integer default("1")
# user_id :integer
# dts_test :integer default("0")
# enterprise_name :string(255)
# organization_id :integer
# project_new_type :integer
# gpid :integer
# forked_from_project_id :integer
# forked_count :integer default("0")
# publish_resource :integer default("0")
# visits :integer default("0")
# hot :integer default("0")
# invite_code :string(255)
# qrcode :string(255)
# qrcode_expiretime :integer default("0")
# script :text(65535)
# training_status :integer default("0")
# rep_identifier :string(255)
# project_category_id :integer
# project_language_id :integer
# license_id :integer
# ignore_id :integer
# praises_count :integer default("0")
# watchers_count :integer default("0")
# issues_count :integer default("0")
# pull_requests_count :integer default("0")
# language :string(255)
# versions_count :integer default("0")
# issue_tags_count :integer default("0")
# closed_issues_count :integer default("0")
# open_devops :boolean default("0")
# gitea_webhook_id :integer
# open_devops_count :integer default("0")
# recommend :boolean default("0")
# platform :integer default("0")
#
# Indexes
#
# index_projects_on_forked_from_project_id (forked_from_project_id)
# index_projects_on_identifier (identifier)
# index_projects_on_is_public (is_public)
# index_projects_on_lft (lft)
# index_projects_on_name (name)
# index_projects_on_platform (platform)
# index_projects_on_project_type (project_type)
# index_projects_on_recommend (recommend)
# index_projects_on_rgt (rgt)
# index_projects_on_status (status)
# index_projects_on_updated_on (updated_on)
#
class Project < ApplicationRecord
include Matchable
include Publicable
@ -10,15 +80,19 @@ class Project < ApplicationRecord
#
enum project_type: { sync_mirror: 2, mirror: 1, common: 0 }
# forge: trustie平台项目 educoder: educoder平台项目 默认为forge平台
enum platform: { forge: 0, educoder: 1 }
belongs_to :ignore, optional: true
belongs_to :license, optional: true
belongs_to :owner, class_name: 'User', foreign_key: :user_id
belongs_to :owner, class_name: 'User', foreign_key: :user_id, optional: true
belongs_to :project_category, optional: true , :counter_cache => true
belongs_to :project_language, optional: true , :counter_cache => true
has_many :project_trends, dependent: :destroy
has_many :watchers, as: :watchable, dependent: :destroy
has_many :fork_users, dependent: :destroy
# has_many :commits, dependent: :destroy
has_many :forked_users, class_name: 'ForkUser', foreign_key: :fork_project_id, dependent: :destroy
has_one :project_educoder, dependent: :destroy
has_one :project_score, dependent: :destroy
has_one :repository, dependent: :destroy
@ -31,10 +105,13 @@ class Project < ApplicationRecord
has_many :versions, -> { order("versions.created_on DESC, versions.name DESC") }, dependent: :destroy
has_many :praise_treads, as: :praise_tread_object, dependent: :destroy
has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
has_one :project_detail, dependent: :destroy
after_save :check_project_members
scope :project_statics_select, -> {select(:id,:name, :is_public, :identifier, :status, :project_type, :user_id, :forked_count, :visits, :project_category_id, :project_language_id, :license_id, :ignore_id, :watchers_count, :created_on)}
scope :no_anomory_projects, -> {where("projects.user_id is not null and projects.user_id != ?", 2)}
scope :recommend, -> { visible.project_statics_select.where(recommend: true) }
def self.search_project(search)
@ -160,7 +237,7 @@ class Project < ApplicationRecord
member&.roles&.last&.name || permission
end
def fork_project
def fork_project
Project.find_by(id: self.forked_from_project_id)
end
@ -168,4 +245,38 @@ class Project < ApplicationRecord
joins(:members).where(members: { user_id: member_user_id})
end
def self.find_with_namespace(namespace_path, identifier)
logger.info "########namespace_path: #{namespace_path} ########identifier: #{identifier} "
user = User.find_by_login namespace_path
project = user&.projects&.find_by(identifier: identifier) || Project.find_by(identifier: "#{namespace_path}/#{identifier}")
return nil if project.blank?
[project, user]
end
def ci_reactivate?
open_devops_count > 0
end
def ci_reactivate!(ci_repo)
ci_repo.update_column(:repo_active, 1)
update_column(:open_devops, true)
increment!(:open_devops_count)
end
def self.sync_educoder_shixun(url, private_token, page, per_page)
SyncEducoderShixunJob.perform_later(url, private_token, page, per_page)
end
def self.update_common_projects_count!
ps = ProjectStatistic.first
ps.increment!(:common_projects_count) unless ps.blank?
end
def self.update_mirror_projects_count!
ps = ProjectStatistic.first
ps.increment!(:mirror_projects_count) unless ps.blank?
end
end

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