Merge remote-tracking branch 'trustie/trustie_server'

# Conflicts:
#	Gemfile
#	Gemfile.lock
#	config/configuration.yml.example
This commit is contained in:
xxq250 2023-05-10 14:56:07 +08:00
commit f8dfad28d5
322 changed files with 8847 additions and 925 deletions

View File

@ -102,6 +102,7 @@ gem 'rails-i18n', '~> 5.1'
gem 'sidekiq',"5.2.8"
gem 'sinatra'
gem "sidekiq-cron", "1.2.0"
gem 'sidekiq-failures'
# batch insert
gem 'bulk_insert'
@ -140,4 +141,4 @@ gem 'doorkeeper'
gem 'doorkeeper-jwt'
gem 'gitea-client', '~> 0.11.6'
gem 'gitea-client', '~> 1.4.2'

View File

@ -1,5 +1,5 @@
GEM
remote: https://gems.ruby-china.com/
remote: https://mirrors.cloud.tencent.com/rubygems/
specs:
aasm (5.0.6)
concurrent-ruby (~> 1.0)
@ -84,6 +84,7 @@ GEM
builder (3.2.4)
bulk_insert (1.7.0)
activerecord (>= 3.2.0)
byebug (11.1.3)
capybara (3.15.1)
addressable
mini_mime (>= 0.1.3)
@ -99,6 +100,7 @@ GEM
archive-zip (~> 0.10)
nokogiri (~> 1.8)
chunky_png (1.3.11)
coderay (1.1.3)
concurrent-ruby (1.1.6)
connection_pool (2.2.2)
crass (1.0.6)
@ -135,7 +137,7 @@ GEM
fugit (1.4.1)
et-orbi (~> 1.1, >= 1.1.8)
raabro (~> 1.4)
gitea-client (0.10.5)
gitea-client (1.4.1)
rest-client (~> 2.1.0)
globalid (0.4.2)
activesupport (>= 4.2.0)
@ -189,7 +191,7 @@ GEM
method_source (0.9.2)
mime-types (3.4.1)
mime-types-data (~> 3.2015)
mime-types-data (3.2022.0105)
mime-types-data (3.2023.0218.1)
mimemagic (0.3.10)
nokogiri (~> 1)
rake
@ -220,9 +222,21 @@ GEM
addressable (~> 2.3)
nokogiri (~> 1.5)
omniauth (~> 1.2)
omniauth-gitee (1.0.0)
omniauth (>= 1.5, < 3.0)
omniauth-oauth2 (>= 1.4.0, < 2.0)
omniauth-github (1.4.0)
omniauth (~> 1.5)
omniauth-oauth2 (>= 1.4.0, < 2.0)
omniauth-oauth2 (1.6.0)
oauth2 (~> 1.1)
omniauth (~> 1.9)
omniauth-rails_csrf_protection (0.1.2)
actionpack (>= 4.2)
omniauth (>= 1.3.1)
omniauth-wechat-oauth2 (0.2.2)
omniauth (>= 1.3.2)
omniauth-oauth2 (>= 1.1.1)
parallel (1.19.1)
parser (2.7.1.1)
ast (~> 2.4.0)
@ -232,6 +246,14 @@ GEM
popper_js (1.16.0)
powerpack (0.1.2)
prettier (0.18.2)
pry (0.12.2)
coderay (~> 1.1.0)
method_source (~> 0.9.0)
pry-rails (0.3.9)
pry (>= 0.10.4)
pry-remote (0.1.8)
pry (~> 0.9)
slop (~> 3.0)
public_suffix (4.0.3)
puma (3.12.2)
raabro (1.4.0)
@ -396,6 +418,7 @@ GEM
rack (~> 2.0)
rack-protection (= 2.0.8.1)
tilt (~> 2.0)
slop (3.6.0)
solargraph (0.38.6)
backport (~> 1.1)
benchmark
@ -467,6 +490,7 @@ DEPENDENCIES
bootsnap (>= 1.1.0)
bootstrap (~> 4.3.1)
bulk_insert
byebug
capybara (>= 2.15, < 4.0)
chartkick
chinese_pinyin
@ -478,7 +502,7 @@ DEPENDENCIES
enumerize
faraday (~> 0.15.4)
font-awesome-sass (= 4.7.0)
gitea-client (~> 0.10.2)
gitea-client (~> 1.4.1)
grape-entity (~> 0.7.1)
groupdate (~> 4.1.0)
harmonious_dictionary (~> 0.0.1)
@ -492,10 +516,16 @@ DEPENDENCIES
oauth2
omniauth (~> 1.9.0)
omniauth-cas
omniauth-gitee (~> 1.0.0)
omniauth-github
omniauth-oauth2 (~> 1.6.0)
omniauth-rails_csrf_protection
omniauth-wechat-oauth2
parallel (~> 1.19, >= 1.19.1)
pdfkit
prettier
pry-rails
pry-remote
puma (~> 3.11)
rack-cors
rack-mini-profiler
@ -516,8 +546,8 @@ DEPENDENCIES
sass-rails (~> 5.0)
searchkick
selenium-webdriver
sidekiq (= 5.2.8)
sidekiq-cron (= 1.2.0)
sidekiq
sidekiq-cron (~> 1.1)
simple_form
simple_xlsx_reader
sinatra

View File

@ -111,6 +111,7 @@ gitea:
access_key_secret: 'password'
domain: 'http://www.gitea.example.com'
base_url: '/api/v1'
hat_base_url: '/api/hat'
```
8配置/config/database.yml文件(安装redis环境:请自行搜索各平台如何安装部署redis环境)

View File

@ -0,0 +1,2 @@
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.

View File

@ -94,6 +94,20 @@ $(document).on('turbolinks:load', function(){
}
});
});
// reset user login times
$('.users-list-container').on('click', '.fresh-gitea-token-action', function(){
var $action = $(this);
var userId = $action.data('id');
$.ajax({
url: '/admins/users/' + userId + '/fresh_gitea_token',
method: 'POST',
dataType: 'json',
success: function() {
showSuccessNotify();
}
});
});
// ***************** reward grade modal *****************
var $rewardGradeModal = $('.admin-users-reward-grade-modal');

View File

@ -0,0 +1,3 @@
// Place all the styles related to the admins/organizations controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

View File

@ -205,9 +205,10 @@ class AccountsController < ApplicationController
return
end
LimitForbidControl::UserLogin.new(@user).clear
successful_authentication(@user)
sync_pwd_to_gitea!(@user, {password: params[:password].to_s}) # TODO用户密码未同步
# session[:user_id] = @user.id
end
@ -324,6 +325,8 @@ class AccountsController < ApplicationController
send_type = verify_type(login_type, type)
verification_code = code.sample(6).join
status, message = InfoRiskControlService.call(value, request.remote_ip)
tip_exception(420, message) if status == 0
sign = Digest::MD5.hexdigest("#{OPENKEY}#{value}")
tip_exception(501, "请求不合理") if sign != params[:smscode]

View File

@ -0,0 +1,27 @@
class Admins::OrganizationsController < Admins::BaseController
before_action :finder_org, except: [:index]
def index
params[:sort_by] = params[:sort_by].presence || 'created_on'
params[:sort_direction] = params[:sort_direction].presence || 'desc'
orgs = Admins::OrganizationQuery.call(params)
@orgs = paginate orgs
end
def show
end
def destroy
@org.destroy!
Admins::DeleteOrganizationService.call(@org.login)
render_delete_success
end
private
def finder_org
@org = Organization.find(params[:id])
end
end

View File

@ -57,6 +57,12 @@ class Admins::UsersController < Admins::BaseController
render_ok
end
def fresh_gitea_token
@user.fresh_gitea_token
render_ok
end
private
def finder_user
@ -64,8 +70,8 @@ class Admins::UsersController < Admins::BaseController
end
def update_params
params.require(:user).permit(%i[lastname nickname gender identity technical_title student_id is_shixun_marker
mail phone location location_city school_id department_id admin business is_test
password professional_certification authentication login])
params.require(:user).permit(%i[lastname nickname gender technical_title is_shixun_marker
mail phone location location_city school_id department_id admin
password login])
end
end

View File

@ -20,10 +20,19 @@ class Api::V1::BaseController < ApplicationController
# User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
# end
# end
def kaminary_select_paginate(relation)
limit = params[:limit] || params[:per_page]
limit = (limit.to_i.zero? || limit.to_i > 200) ? 200 : limit.to_i
page = params[:page].to_i.zero? ? 1 : params[:page].to_i
relation.page(page).per(limit)
end
def limit
params.fetch(:limit, 15)
end
def page
params.fetch(:page, 1)
end
@ -43,7 +52,6 @@ class Api::V1::BaseController < ApplicationController
# 具有仓库的操作权限或者fork仓库的操作权限
def require_operate_above_or_fork_project
@project = load_project
puts !current_user.admin? && !@project.operator?(current_user) && !(@project.fork_project.present? && @project.fork_project.operator?(current_user))
return render_forbidden if !current_user.admin? && !@project.operator?(current_user) && !(@project.fork_project.present? && @project.fork_project.operator?(current_user))
end

View File

@ -0,0 +1,12 @@
class Api::V1::Issues::AssignersController < Api::V1::BaseController
before_action :require_public_and_member_above, only: [:index]
# 负责人列表
def index
@assigners = User.joins(assigned_issues: :project).where(projects: {id: @project&.id})
@assigners = @assigners.order("users.id=#{current_user.id} desc").distinct
@assigners = @assigners.ransack(login_or_nickname_cont: params[:keyword]).result if params[:keyword].present?
@assigners = kaminary_select_paginate(@assigners)
end
end

View File

@ -0,0 +1,11 @@
class Api::V1::Issues::AuthorsController < Api::V1::BaseController
before_action :require_public_and_member_above, only: [:index]
# 发布人列表
def index
@authors = User.joins(issues: :project).where(projects: {id: @project&.id})
@authors = @authors.order("users.id=#{current_user.id} desc").distinct
@authors = @authors.ransack(login_or_nickname_cont: params[:keyword]).result if params[:keyword].present?
@authors = kaminary_select_paginate(@authors)
end
end

View File

@ -0,0 +1,10 @@
class Api::V1::Issues::IssuePrioritiesController < Api::V1::BaseController
before_action :require_public_and_member_above, only: [:index]
def index
@priorities = IssuePriority.order(position: :asc)
@priorities = @priorities.ransack(name_cont: params[:keyword]).result if params[:keyword]
@priorities = kaminary_select_paginate(@priorities)
end
end

View File

@ -0,0 +1,65 @@
class Api::V1::Issues::IssueTagsController < Api::V1::BaseController
before_action :require_login, except: [:index]
before_action :require_public_and_member_above, only: [:index]
before_action :require_operate_above, only: [:create, :update, :destroy]
def index
@issue_tags = @project.issue_tags.reorder("#{sort_by} #{sort_direction}")
@issue_tags = @issue_tags.ransack(name_cont: params[:keyword]).result if params[:keyword].present?
if params[:only_name]
@issue_tags = kaminary_select_paginate(@issue_tags.select(:id, :name, :color))
else
@issue_tags = kaminari_paginate(@issue_tags.includes(:project, :user, :issue_issues, :pull_request_issues))
end
end
def create
@issue_tag = @project.issue_tags.new(issue_tag_params)
if @issue_tag.save!
render_ok
else
render_error("创建标记失败!")
end
end
before_action :load_issue_tag, only: [:update, :destroy]
def update
@issue_tag.attributes = issue_tag_params
if @issue_tag.save!
render_ok
else
render_error("更新标记失败!")
end
end
def destroy
if @issue_tag.destroy!
render_ok
else
render_error("删除标记失败!")
end
end
private
def sort_by
sort_by = params.fetch(:sort_by, "created_at")
sort_by = IssueTag.column_names.include?(sort_by) ? sort_by : "created_at"
sort_by
end
def sort_direction
sort_direction = params.fetch(:sort_direction, "desc").downcase
sort_direction = %w(desc asc).include?(sort_direction) ? sort_direction : "desc"
sort_direction
end
def issue_tag_params
params.permit(:name, :description, :color)
end
def load_issue_tag
@issue_tag = @project.issue_tags.find_by_id(params[:id])
end
end

View File

@ -0,0 +1,64 @@
class Api::V1::Issues::JournalsController < Api::V1::BaseController
before_action :require_login, except: [:index, :children_journals]
before_action :require_public_and_member_above
before_action :load_issue
before_action :load_journal, only: [:children_journals, :update, :destroy]
before_action :check_journal_operate_permission, only: [:update, :destroy]
def index
@object_result = Api::V1::Issues::Journals::ListService.call(@issue, query_params, current_user)
@total_journals_count = @object_result[:total_journals_count]
@total_operate_journals_count = @object_result[:total_operate_journals_count]
@total_comment_journals_count = @object_result[:total_comment_journals_count]
@journals = kaminary_select_paginate(@object_result[:data])
end
def create
@object_result = Api::V1::Issues::Journals::CreateService.call(@issue, journal_params, current_user)
end
def children_journals
@object_results = Api::V1::Issues::Journals::ChildrenListService.call(@issue, @journal, query_params, current_user)
@journals = kaminari_paginate(@object_results)
end
def update
@object_result = Api::V1::Issues::Journals::UpdateService.call(@issue, @journal, journal_params, current_user)
end
def destroy
TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueComment', @issue&.id, current_user.id, @journal.id, 'deleted', JSON.parse(@journal.to_builder.target!))
if @journal.destroy!
render_ok
else
render_error("删除评论失败!")
end
end
private
def query_params
params.permit(:category, :keyword, :sort_by, :sort_direction)
end
def journal_params
params.permit(:notes, :parent_id, :reply_id, :attachment_ids => [], :receivers_login => [])
end
def load_issue
@issue = @project.issues.issue_issue.where(project_issues_index: params[:index]).where.not(id: params[:index]).take || Issue.find_by_id(params[:index])
if @issue.blank?
render_not_found("疑修不存在!")
end
end
def load_journal
@journal = Journal.find_by_id(params[:id])
return render_not_found("评论不存在!") unless @journal.present?
end
def check_journal_operate_permission
return render_forbidden("您没有操作权限!") unless @project.member?(current_user) || current_user.admin? || @issue.user == current_user || @journal.user == current_user || @journal.parent_journal&.user == current_user
end
end

View File

@ -0,0 +1,87 @@
class Api::V1::Issues::MilestonesController < Api::V1::BaseController
before_action :require_login, except: [:index, :show]
before_action :require_public_and_member_above, only: [:index, :show]
before_action :require_operate_above, only: [:create, :update, :destroy]
before_action :load_milestone, only: [:show, :update, :destroy]
# 里程碑列表
def index
@milestones = @project.versions
@milestones = @milestones.ransack(id_eq: params[:keyword]).result.or(@milestones.ransack(name_or_description_cont: params[:keyword]).result) if params[:keyword].present?
@closed_milestone_count = @milestones.closed.size
@opening_milestone_count = @milestones.opening.size
@milestones = params[:category] == "closed" ? @milestones.closed : @milestones.opening
@milestones = @milestones.reorder("versions.#{sort_by} #{sort_direction}")
if params[:only_name]
@milestones = @milestones.select(:id, :name)
@milestones = kaminary_select_paginate(@milestones)
else
@milestones = @milestones.includes(:issues, :closed_issues, :opened_issues)
@milestones = kaminari_paginate(@milestones)
end
end
def create
@milestone = @project.versions.new(milestone_params)
if @milestone.save!
render_ok
else
render_error(@milestone.errors.full_messages.join(","))
end
end
# 里程碑详情
def show
@object_result = Api::V1::Issues::Milestones::DetailIssuesService.call(@project, @milestone, query_params, current_user)
@total_issues_count = @object_result[:total_issues_count]
@opened_issues_count = @object_result[:opened_issues_count]
@closed_issues_count = @object_result[:closed_issues_count]
@issues = kaminari_paginate(@object_result[:data])
end
def update
@milestone.attributes = milestone_params
if @milestone.save!
render_ok
else
render_error(@milestone.errors.full_messages.join(","))
end
end
def destroy
if @milestone.destroy!
render_ok
else
render_error("删除里程碑失败!")
end
end
private
def milestone_params
params.permit(:name, :description, :effective_date)
end
def query_params
params.permit(:category, :author_id, :assigner_id, :sort_by, :sort_direction, :issue_tag_ids)
end
def load_milestone
@milestone = @project.versions.find_by_id(params[:id])
return render_not_found('里程碑不存在!') unless @milestone.present?
end
def sort_by
sort_by = params.fetch(:sort_by, "created_on")
sort_by = Version.column_names.include?(sort_by) ? sort_by : "created_on"
sort_by
end
def sort_direction
sort_direction = params.fetch(:sort_direction, "desc").downcase
sort_direction = %w(desc asc).include?(sort_direction) ? sort_direction : "desc"
sort_direction
end
end

View File

@ -0,0 +1,11 @@
class Api::V1::Issues::StatuesController < Api::V1::BaseController
before_action :require_public_and_member_above, only: [:index]
# 状态列表
def index
@statues = IssueStatus.order("position asc")
@statues = @statues.ransack(name_cont: params[:keyword]).result if params[:keyword].present?
@statues = kaminary_select_paginate(@statues)
end
end

View File

@ -0,0 +1,117 @@
class Api::V1::IssuesController < Api::V1::BaseController
before_action :require_login, except: [:index, :show]
before_action :require_public_and_member_above, only: [:index, :show, :create, :update, :destroy]
before_action :require_operate_above, only: [:batch_update, :batch_destroy]
def index
IssueTag.init_data(@project.id) unless $redis_cache.hget("project_init_issue_tags", @project.id)
@object_result = Api::V1::Issues::ListService.call(@project, query_params, current_user)
@total_issues_count = @object_result[:total_issues_count]
@opened_issues_count = @object_result[:opened_issues_count]
@closed_issues_count = @object_result[:closed_issues_count]
if params[:only_name].present?
@issues = kaminary_select_paginate(@object_result[:data].select(:id, :subject, :project_issues_index, :updated_on, :created_on))
else
@issues = kaminari_paginate(@object_result[:data])
end
end
def create
@object_result = Api::V1::Issues::CreateService.call(@project, issue_params, current_user)
end
before_action :load_issue, only: [:show, :update, :destroy]
before_action :check_issue_operate_permission, only: [:update, :destroy]
def show
@user_permission = current_user.present? && current_user.logged? && (@project.member?(current_user) || current_user.admin? || @issue.user == current_user)
end
def update
@object_result = Api::V1::Issues::UpdateService.call(@project, @issue, issue_params, current_user)
end
def destroy
@object_result = Api::V1::Issues::DeleteService.call(@project, @issue, current_user)
if @object_result
render_ok
else
render_error("删除疑修失败!")
end
end
before_action :load_issues, only: [:batch_update, :batch_destroy]
def batch_update
@object_result = Api::V1::Issues::BatchUpdateService.call(@project, @issues, batch_issue_params, current_user)
if @object_result
render_ok
else
render_error("批量更新疑修失败!")
end
end
def batch_destroy
@object_result = Api::V1::Issues::BatchDeleteService.call(@project, @issues, current_user)
if @object_result
render_ok
else
render_error("批量删除疑修失败!")
end
end
private
def load_issue
@issue = @project.issues.issue_issue.where(project_issues_index: params[:index]).where.not(id: params[:index]).take || Issue.find_by_id(params[:index])
if @issue.blank?
render_not_found("疑修不存在!")
end
end
def load_issues
return render_error("请输入正确的ID数组") unless params[:ids].is_a?(Array)
params[:ids].each do |id|
@issue = Issue.find_by_id(id)
if @issue.blank?
return render_not_found("ID为#{id}的疑修不存在!")
end
end
@issues = Issue.where(id: params[:ids])
end
def check_issue_operate_permission
return render_forbidden("您没有操作权限!") unless @project.member?(current_user) || current_user.admin? || @issue.user == current_user
end
def query_params
params.permit(
:only_name,
:category,
:participant_category,
:keyword, :author_id,
:milestone_id, :assigner_id,
:status_id,
:begin_date, :end_date,
:sort_by, :sort_direction,
:issue_tag_ids)
end
def issue_params
params.permit(
:status_id, :priority_id, :milestone_id,
:branch_name, :start_date, :due_date,
:subject, :description, :blockchain_token_num,
:issue_tag_ids => [],
:assigner_ids => [],
:attachment_ids => [],
:receivers_login => [])
end
def batch_issue_params
params.permit(
:status_id, :priority_id, :milestone_id,
:issue_tag_ids => [],
:assigner_ids => [])
end
end

View File

@ -0,0 +1,46 @@
class Api::V1::ProjectTopicsController < Api::V1::BaseController
def index
@project_topics = ProjectTopic
@project_topics = @project_topics.ransack(name_cont: params[:keyword]) if params[:keyword].present?
# @project_topics = @project_topics.includes(:projects)
@project_topics = kaminary_select_paginate(@project_topics)
end
def create
ActiveRecord::Base.transaction do
@project = Project.find_by_id(create_params[:project_id])
return render_not_found unless @project.present?
return render_error("请输入项目搜索标签名称.") unless create_params[:name].present?
@project_topic = ProjectTopic.find_or_create_by!(name: create_params[:name].downcase)
@project_topic_ralate = @project_topic.project_topic_ralates.find_or_create_by!(project_id: create_params[:project_id])
if @project_topic.present? && @project_topic_ralate.present?
render_ok
else
render_error("项目关联搜索标签失败.")
end
end
end
def destroy
ActiveRecord::Base.transaction do
@project = Project.find_by_id(create_params[:project_id])
return render_not_found unless @project.present?
@project_topic = ProjectTopic.find_by_id(params[:id])
@project_topic_ralate = @project_topic.project_topic_ralates.find_by(project_id: @project.id)
if @project_topic_ralate.destroy!
render_ok
else
render_error("项目取消关联搜索标签失败.")
end
end
end
private
def create_params
params.permit(:project_id, :name)
end
end

View File

@ -3,6 +3,6 @@ class Api::V1::Projects::CodeStatsController < Api::V1::BaseController
def index
@result_object = Api::V1::Projects::CodeStats::ListService.call(@project, {ref: params[:ref]}, current_user&.gitea_token)
puts @result_object
# puts @result_object
end
end

View File

@ -0,0 +1,10 @@
class Api::V1::Projects::CollaboratorsController < Api::V1::BaseController
before_action :require_public_and_member_above, only: [:index]
def index
@collaborators = @project.all_collaborators.like(params[:keyword])
@collaborators = kaminary_select_paginate(@collaborators)
end
end

View File

@ -0,0 +1,11 @@
class Api::V1::Projects::ContributorsController < Api::V1::BaseController
before_action :require_public_and_member_above, only: [:index, :stat]
# todo
def index
end
def stat
@result_object = Api::V1::Projects::Contributors::StatService.call(@project, {branch: params[:branch], pass_year: params[:pass_year], page: page, limit: limit}, current_user&.gitea_token)
end
end

View File

@ -4,6 +4,7 @@ class Api::V1::Projects::TagsController < Api::V1::BaseController
def index
@release_tags = @repository.version_releases.pluck(:tag_name)
@result_object = Api::V1::Projects::Tags::ListService.call(@project, {page: page, limit: limit}, current_user&.gitea_token)
puts @result_object
end
before_action :require_operate_above, only: [:destroy]

View File

@ -0,0 +1,24 @@
class Api::V1::Users::OpenkylinSignController < Api::V1::BaseController
before_action :load_observe_user
def competitions
@competition_ids = EduSetting.get("openkylin_sign_competitions").split(",") rescue []
render :json => {data: @competition_ids}
end
def create
@object_result = Api::V1::Users::OpenkylinSign::CreateService.call(@observe_user, create_params)
Rails.logger.info "OpenkylinSignController=====#{@object_result}"
if @object_result
return render_ok
else
return render_error('签署失败!')
end
end
private
def create_params
params.permit(:login, :email, :nickname, :phone, :address)
end
end

View File

@ -1,7 +1,17 @@
class Api::V1::UsersController < Api::V1::BaseController
before_action :load_observe_user
before_action :check_auth_for_observe_user
before_action :load_observe_user, except: [:check_user_id, :check_user_login]
before_action :check_auth_for_observe_user, except: [:check_user_id, :check_user_login]
def check_user_id
return tip_exception(-1, "用户ID不存在") unless params[:user_id].present? && User.exists?(id: params[:user_id])
render_ok
end
def check_user_login
return tip_exception(-1, "用户标识不存在") unless params[:login].present? && User.exists?(login: params[:login])
render_ok
end
def send_email_vefify_code
code = %W(0 1 2 3 4 5 6 7 8 9)
@ -9,21 +19,24 @@ class Api::V1::UsersController < Api::V1::BaseController
mail = params[:email]
code_type = params[:code_type]
status, message = InfoRiskControlService.call(mail, request.remote_ip)
tip_exception(420, message) if status == 0
sign = Digest::MD5.hexdigest("#{OPENKEY}#{mail}")
Rails.logger.info sign
tip_exception(501, "请求不合理") if sign != params[:smscode]
# 60s内不能重复发送
send_email_limit_cache_key = "send_email_60_second_limit:#{mail}"
tip_exception(-2, '请勿频繁操作') if Rails.cache.exist?(send_email_limit_cache_key)
send_email_control = LimitForbidControl::SendEmailCode.new(mail)
tip_exception(-2, '邮件发送太频繁,请稍后再试') if send_email_control.forbid?
# send_email_limit_cache_key = "send_email_60_second_limit:#{mail}"
# tip_exception(-2, '请勿频繁操作') if Rails.cache.exist?(send_email_limit_cache_key)
# send_email_control = LimitForbidControl::SendEmailCode.new(mail)
# tip_exception(-2, '邮件发送太频繁,请稍后再试') if send_email_control.forbid?
begin
UserMailer.update_email(mail, verification_code).deliver_now
Rails.cache.write(send_email_limit_cache_key, 1, expires_in: 1.minute)
send_email_control.increment!
# Rails.cache.write(send_email_limit_cache_key, 1, expires_in: 1.minute)
# send_email_control.increment!
rescue Exception => e
logger_error(e)
tip_exception(-2,"邮件发送失败,请稍后重试")

View File

@ -112,12 +112,12 @@ class ApplicationController < ActionController::Base
# 邮箱类型的发送
sigle_para = {email: value}
# 60s内不能重复发送
send_email_limit_cache_key = "send_email_60_second_limit:#{value}"
tip_exception(-1, '请勿频繁操作') if Rails.cache.exist?(send_email_limit_cache_key)
# send_email_limit_cache_key = "send_email_60_second_limit:#{value}"
# tip_exception(-1, '请勿频繁操作') if Rails.cache.exist?(send_email_limit_cache_key)
# 短时间内不能大量发送
send_email_control = LimitForbidControl::SendEmailCode.new(value)
tip_exception(-1, '邮件发送太频繁,请稍后再试') if send_email_control.forbid?
# # 短时间内不能大量发送
# send_email_control = LimitForbidControl::SendEmailCode.new(value)
# tip_exception(-1, '邮件发送太频繁,请稍后再试') if send_email_control.forbid?
begin
if send_type == 3
UserMailer.find_password(value, code).deliver_now
@ -126,8 +126,8 @@ class ApplicationController < ActionController::Base
else
UserMailer.register_email(value, code).deliver_now
end
Rails.cache.write(send_email_limit_cache_key, 1, expires_in: 1.minute)
send_email_control.increment!
# Rails.cache.write(send_email_limit_cache_key, 1, expires_in: 1.minute)
# send_email_control.increment!
# Mailer.run.email_register(code, value)
rescue Exception => e
logger_error(e)
@ -680,6 +680,14 @@ class ApplicationController < ActionController::Base
relation.page(page).per(limit)
end
def kaminari_unlimit_paginate(relation)
limit = params[:limit] || params[:per_page]
limit = (limit.to_i.zero? || limit.to_i > 9999) ? 9999 : limit.to_i
page = params[:page].to_i.zero? ? 1 : params[:page].to_i
relation.page(page).per(limit)
end
def kaminari_array_paginate(relation)
limit = params[:limit] || params[:per_page]
limit = (limit.to_i.zero? || limit.to_i > 20) ? 20 : limit.to_i
@ -832,6 +840,325 @@ class ApplicationController < ActionController::Base
HotSearchKeyword.add(keyword)
end
# author: zxh
# blockchain相关项目活动调用函数
# return true: 表示上链操作成功; return false: 表示上链操作失败
def push_activity_2_blockchain(activity_type, model)
if activity_type == "issue_create"
project_id = model['project_id']
project = Project.find(project_id)
if project['use_blockchain'] == 0 || project['use_blockchain'] == false
# 无需执行上链操作
return true
end
id = model['id']
owner_id = project['user_id']
owner = User.find(owner_id)
ownername = owner['login']
identifier = project['identifier']
author_id = project['user_id']
author = User.find(author_id)
username = author['login']
action = 'opened'
title = model['subject']
content = model['description']
created_at = model['created_on']
updated_at = model['updated_on']
# 调用区块链接口
params = {
"request-type": "upload issue info",
"issue_id": "gitlink-" + id.to_s,
"repo_id": "gitlink-" + project_id.to_s,
"issue_number": 0, # 暂时不需要改字段
"reponame": identifier,
"ownername": ownername,
"username": username,
"action": action,
"title": title,
"content": content,
"created_at": created_at,
"updated_at": updated_at
}.to_json
resp_body = Blockchain::InvokeBlockchainApi.call(params)
if resp_body['status'] == 10
raise ApplicationService::Error, resp_body['message']
elsif resp_body['status'] != 0
raise ApplicationService::Error, "区块链接口请求失败."
end
elsif activity_type == "issue_comment_create"
issue_comment_id = model['id']
issue_id = model['journalized_id']
parent_id = model['parent_id'].nil? ? "" : model['parent_id']
issue = Issue.find(issue_id)
issue_classify = issue['issue_classify'] # issue或pull_request
project_id = issue['project_id']
project = Project.find(project_id)
if project['use_blockchain'] == 0 || project['use_blockchain'] == false
# 无需执行上链操作
return
end
identifier = project['identifier']
owner_id = project['user_id']
owner = User.find(owner_id)
ownername = owner['login']
author_id = model['user_id']
author = User.find(author_id)
username = author['login']
action = 'created'
content = model['notes']
created_at = model['created_on']
if issue_classify == "issue"
params = {
"request-type": "upload issue comment info",
"issue_comment_id": "gitlink-" + issue_comment_id.to_s,
"issue_comment_number": 0, # 暂时不需要
"issue_number": 0, # 暂时不需要
"issue_id": "gitlink-" + issue_id.to_s,
"repo_id": "gitlink-" + project.id.to_s,
"parent_id": parent_id.to_s,
"reponame": identifier,
"ownername": ownername,
"username": username,
"action": action,
"content": content,
"created_at": created_at,
}.to_json
elsif issue_classify == "pull_request"
params = {
"request-type": "upload pull request comment info",
"pull_request_comment_id": "gitlink-" + issue_comment_id.to_s,
"pull_request_comment_number": 0, # 不考虑该字段
"pull_request_number": 0, # 不考虑该字段
"pull_request_id": "gitlink-" + issue_id.to_s,
"parent_id": parent_id.to_s,
"repo_id": "gitlink-" + project.id.to_s,
"reponame": identifier,
"ownername": ownername,
"username": username,
"action": action,
"content": content,
"created_at": created_at,
}.to_json
end
# 调用区块链接口
resp_body = Blockchain::InvokeBlockchainApi.call(params)
if resp_body['status'] == 10
raise ApplicationService::Error, resp_body['message']
elsif resp_body['status'] != 0
raise ApplicationService::Error, "区块链接口请求失败."
end
elsif activity_type == "pull_request_create"
# 调用区块链接口
project_id = model['project_id']
project = Project.find(project_id)
if project['use_blockchain'] == 0 || project['use_blockchain'] == false
# 无需执行上链操作
return
end
pull_request_id = model['id']
identifier = project['identifier']
owner_id = project['user_id']
owner = User.find(owner_id)
ownername = owner['login']
action = 'opened'
title = model['title']
content = model['body']
source_branch = model['head']
source_repo_id = model['fork_project_id'].nil? ? project_id : model['fork_project_id']
target_branch = model['base']
target_repo_id = project_id
author_id = model['user_id']
author = User.find(author_id)
username = author['login']
created_at = model['created_at']
updated_at = model['updated_at']
# 查询pull request对应的commit信息
commits = Gitea::PullRequest::CommitsService.call(ownername, identifier, model['gitea_number'], current_user&.gitea_token)
if commits.nil?
raise ApplicationService::Error, "区块链接口请求失败" # 获取pr中变更的commit信息失败
end
commit_shas = []
commits.each do |c|
commit_shas << c["Sha"]
end
params = {
"request-type": "upload pull request info",
"pull_request_id": "gitlink-" + pull_request_id.to_s,
"pull_request_number": 0, # trustie没有该字段
"repo_id": "gitlink-" + project_id.to_s,
"ownername": ownername,
"reponame": identifier,
"username": username,
"action": action,
"title": title,
"content": content,
"source_branch": source_branch,
"target_branch": target_branch,
"reviewers": [], # trustie没有该字段
"commit_shas": commit_shas,
"merge_user": "", # trustie没有该字段
"created_at": created_at,
"updated_at": updated_at
}.to_json
resp_body = Blockchain::InvokeBlockchainApi.call(params)
if resp_body['status'] == 9
raise ApplicationService::Error, resp_body['message']
elsif resp_body['status'] != 0
raise ApplicationService::Error, "区块链接口请求失败."
end
elsif activity_type == "pull_request_merge"
# 调用区块链接口
project_id = model['project_id']
project = Project.find(project_id)
if project['use_blockchain'] == 0 || project['use_blockchain'] == false
# 无需执行上链操作
return
end
pull_request_id = model['id']
identifier = project['identifier']
owner_id = project['user_id']
owner = User.find(owner_id)
ownername = owner['login']
action = 'merged'
created_at = model['created_at']
updated_at = model['updated_at']
# 查询pull request对应的commit信息
commits = Gitea::PullRequest::CommitsService.call(ownername, identifier, model['gitea_number'], current_user&.gitea_token)
if commits.nil?
raise ApplicationService::Error, "区块链接口请求失败" # 获取pr中变更的commit信息失败
end
commit_shas = []
commits.each do |c|
commit_shas << c["Sha"]
end
# 将pull request相关信息写入链上
params = {
"request-type": "upload pull request info",
"pull_request_id": "gitlink-" + pull_request_id.to_s,
"pull_request_number": 0, # trustie没有该字段
"repo_id": "gitlink-" + project_id.to_s,
"ownername": ownername,
"reponame": identifier,
"username": username,
"action": action,
"title": title,
"content": content,
"source_branch": source_branch,
"target_branch": target_branch,
"reviewers": [], # trustie没有该字段
"commit_shas": commit_shas,
"merge_user": "", # trustie没有该字段
"created_at": created_at,
"updated_at": updated_at
}.to_json
resp_body = Blockchain::InvokeBlockchainApi.call(params)
if resp_body['status'] == 9
raise ApplicationService::Error, resp_body['message']
elsif resp_body['status'] != 0
raise ApplicationService::Error, "区块链接口请求失败."
end
# 将commit相关信息写入链上
commit_shas.each do |commit_sha|
commit_diff = Gitea::Commit::DiffService.call(ownername, identifier, commit_sha, owner['gitea_token'])
commit = Gitea::Commit::InfoService.call(ownername, identifier, commit_sha, owner['gitea_token'])
params = {
"request-type": "upload commit info",
"commit_hash": commit_sha,
"repo_id": "gitlink-" + project_id.to_s,
"author": commit['commit']['author']['name'],
"author_email": commit['commit']['author']['email'],
"committer": commit['commit']['committer']['name'],
"committer_email": commit['commit']['committer']['email'],
"author_time": commit['commit']['author']['date'],
"committer_time": commit['commit']['committer']['date'],
"content": commit['commit']['message'],
"commit_diff": commit_diff['Files'].to_s
}.to_json
resp_body = Blockchain::InvokeBlockchainApi.call(params)
if resp_body['status'] == 7
raise ApplicationService::Error, resp_body['message']
elsif resp_body['status'] != 0
raise ApplicationService::Error, "区块链接口请求失败."
end
end
elsif activity_type == "pull_request_refuse"
# 调用区块链接口
project_id = model['project_id']
project = Project.find(project_id)
if project['use_blockchain'] == 0 || project['use_blockchain'] == false
# 无需执行上链操作
return true
end
pull_request_id = model['id']
identifier = project['identifier']
owner_id = project['user_id']
owner = User.find(owner_id)
ownername = owner['login']
action = 'refused'
# 将pull request相关信息写入链上
params = {
"request-type": "upload pull request info",
"pull_request_id": "gitlink-" + pull_request_id.to_s,
"pull_request_number": 0, # trustie没有该字段
"repo_id": "gitlink-" + project_id.to_s,
"ownername": ownername,
"reponame": identifier,
"username": username,
"action": action,
"title": title,
"content": content,
"source_branch": source_branch,
"target_branch": target_branch,
"reviewers": [], # trustie没有该字段
"commit_shas": commit_shas,
"merge_user": "", # trustie没有该字段
"created_at": created_at,
"updated_at": updated_at
}.to_json
resp_body = Blockchain::InvokeBlockchainApi.call(params)
if resp_body['status'] == 9
raise ApplicationService::Error, resp_body['message']
elsif resp_body['status'] != 0
raise ApplicationService::Error, "区块链接口请求失败."
end
end
end
def find_atme_receivers
@atme_receivers = User.where(login: params[:receivers_login])
end

View File

@ -31,14 +31,17 @@ class AttachmentsController < ApplicationController
def get_file
normal_status(-1, "参数缺失") if params[:download_url].blank?
url = base_url.starts_with?("https:") ? URI.encode(params[:download_url].to_s.gsub("http:", "https:")) : URI.encode(params[:download_url].to_s)
url = base_url.starts_with?("https:") ? params[:download_url].to_s.gsub("http:", "https:") : params[:download_url].to_s
if url.starts_with?(base_url) && !url.starts_with?("#{base_url}/repo")
domain = GiteaService.gitea_config[:domain]
api_url = GiteaService.gitea_config[:base_url]
url = ("/repos"+url.split(base_url + "/api")[1]).gsub('?filepath=', '/').gsub('&', '?')
request_url = [domain, api_url, url, "?ref=#{params[:ref]}&access_token=#{current_user&.gitea_token}"].join
url = ("/repos"+url.split(base_url + "/api")[1])
filepath, ref = url.split("/")[-1].split("?")
url.gsub!(url.split("/")[-1], '')
puts filepath
request_url = [domain, api_url, url, CGI.escape(filepath), "?ref=#{CGI.escape(ref.split('ref=')[1])}&access_token=#{User.where(admin: true).take&.gitea_token}"].join
response = Faraday.get(request_url)
filename = url.to_s.split("/").pop()
filename = filepath
else
response = Faraday.get(url)
filename = params[:download_url].to_s.split("/").pop()

View File

@ -39,6 +39,7 @@ class ClaimsController < ApplicationController
journal = Journal.new(journal_params)
if journal.save
SendTemplateMessageJob.perform_later('IssueClaim', current_user.id, @issue&.id)
render file: 'app/views/claims/list.json.jbuilder'
else
normal_status(-1,"新建声明关联评论操作失败")

View File

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

View File

@ -1,7 +1,7 @@
module Api::ProjectHelper
extend ActiveSupport::Concern
def load_project
def load_project
namespace = params[:owner]
repo = params[:repo]
@ -14,7 +14,7 @@ module Api::ProjectHelper
else
logger.info "###########project not found"
@project = nil
render_not_found and return
tip_exception(404, '您访问的页面不存在或已被删除')
end
@project
end

View File

@ -13,7 +13,7 @@ module Repository::LanguagesPercentagable
def update_project_language(language)
return if @project.project_language.present?
db_language = ProjectLanguage.find_or_create_by!(name: language.keys.first.downcase.upcase_first)
@project.update_column(:project_language_id, db_language.id)
@project.update_attribute(:project_language_id, db_language.id)
rescue
return
end

View File

@ -2,8 +2,26 @@ class InstallationsController < ApplicationController
include RegisterHelper
before_action :require_login
# app详情
def app
@bot = Bot.find_by(uid: current_user.id)
end
def index
@install_bots = BotInstall.where(:installer_id => current_user.id)
@install_bots = BotInstall.where(bot_id: get_bot_id).group(:installer_id)
end
def show
@install_bot = BotInstall.find_by(bot_id: get_bot_id, installer_id: params[:id]) || BotInstall.find_by(id: params[:id])
tip_exception "参数installer_id错误" if @install_bot.blank?
end
def repositories
# 与github差异所以取安装用户和bot对应所有的仓库
# 必须使用access_tokens获取到bot的token才能查询
tip_exception "无效Token" if current_user.platform != "bot"
bot = Bot.find_by(uid: current_user.id)
@install_bots = BotInstall.where(bot_id: bot.id).where(installer_id: params[:id])
end
def update_secret
@ -25,19 +43,45 @@ class InstallationsController < ApplicationController
render_ok
end
# 同步bot信息回调地址和名称
def update_callback_url
bot = Bot.find params[:id]
application = Doorkeeper::Application.find_by(uid: bot.client_id, secret: bot.client_secret)
application.redirect_uri = bot.oauth_callback_url
application.name = bot.name
if bot.uid.present?
bot_user = User.find_by(id: bot.uid)
bot_user.update_column(:nickname, bot.name) if bot_user.present?
end
application.save
render_ok
end
def suspended
@install_bot = BotInstall.find params[:id]
@install_bot.update_attributes!(state: 0)
render_ok
end
def unsuspended
@install_bot = BotInstall.find params[:id]
@install_bot.update_attributes!(state: 1)
render_ok
end
def auth_active
begin
@bot = Bot.find params[:id]
tip_exception("该Bot已激活") if Doorkeeper::Application.find_by(uid: @bot.client_id, secret: @bot.client_secret).present?
@bot.client_id = Doorkeeper::OAuth::Helpers::UniqueToken.generate if params[:client_id].blank?
@bot.client_id = SecureRandom.uuid.gsub("-", "") if params[:client_id].blank?
@bot.client_secret = Doorkeeper::OAuth::Helpers::UniqueToken.generate if params[:client_secret].blank?
@bot.private_key = OpenSSL::PKey::RSA::generate(2048).to_s
@bot.owner_id = current_user.id
ActiveRecord::Base.transaction do
# 注册bot对应oauth应用
Doorkeeper::Application.create!(name: @bot.name, uid: @bot.client_id, secret: @bot.client_secret, redirect_uri: "https://gitlink.org.cn")
Doorkeeper::Application.create!(name: @bot.name, uid: @bot.client_id, secret: @bot.client_secret, redirect_uri: @bot.oauth_callback_url)
# 注册bot对应用户
result = autologin_register(User.generate_user_login('b'), nil, "#{SecureRandom.hex(6)}", 'bot', nickname: @bot.name)
result = autologin_register(User.generate_user_login('b'), nil, "#{SecureRandom.hex(6)}", 'bot', nil, @bot.name)
tip_exception(-1, result[:message]) if result[:message].present?
@bot.uid = result[:user][:id]
@bot.save
@ -49,7 +93,8 @@ class InstallationsController < ApplicationController
end
def access_tokens
@install_bot = BotInstall.find params[:id]
@install_bot = BotInstall.find_by(bot_id: get_bot_id, installer_id: params[:id]) || BotInstall.find_by(id: params[:id])
tip_exception "参数installer_id错误" if @install_bot.blank?
@bot = @install_bot.bot
@application = Doorkeeper::Application.find_by(uid: @bot.client_id, secret: @bot.client_secret)
tip_exception("该Bot未激活") if @application.blank?
@ -57,11 +102,26 @@ class InstallationsController < ApplicationController
@access_token = Doorkeeper::AccessToken.create!({ :application_id => @application.id,
:resource_owner_id => @bot.uid,
:scopes => "public write",
:expires_in => "604800",
:expires_in => "2592000",
:use_refresh_token => true
})
@install_bot.update_attributes!(state: 1)
render_ok(token: @access_token.token)
end
private
def get_bot_id
header = request.authorization
pattern = /^Bearer /i
token = header.gsub(pattern, "")
decoded_token = JWT.decode token, nil, false
# 前面已验证token有效期和正确性
decoded_token[0]["iss"]
rescue JWT::DecodeError
Rails.logger.error "jwt token decode error:#{token}"
tip_exception("无效Token")
end
end

View File

@ -111,7 +111,9 @@ class IssuesController < ApplicationController
issue_params = issue_send_params(params)
Issues::CreateForm.new({subject: issue_params[:subject], description: issue_params[:description].blank? ? issue_params[:description] : issue_params[:description].b}).validate!
@issue = Issue.new(issue_params)
@issue.project_issues_index = @project.get_last_project_issues_index + 1
if @issue.save!
@project.del_project_issue_cache_delete_count
SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if Site.has_notice_menu?
SendTemplateMessageJob.perform_later('ProjectIssue', current_user.id, @issue&.id) if Site.has_notice_menu?
if params[:attachment_ids].present?
@ -149,6 +151,7 @@ class IssuesController < ApplicationController
end
@issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create")
@issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE) if params[:status_id].to_i == 5
@ -157,6 +160,17 @@ class IssuesController < ApplicationController
# 新增时向grimoirelab推送事件
IssueWebhookJob.set(wait: 5.seconds).perform_later(@issue.id)
if Site.has_blockchain? && @project.use_blockchain
# author: zxh
# 扣除发起人的token
if @issue.blockchain_token_num > 0
Blockchain::CreateIssue.call(user_id: @issue.author_id, project_id: @issue.project_id, token_num: @issue.blockchain_token_num)
end
# 调用上链API存证
push_activity_2_blockchain("issue_create", @issue)
end
render json: {status: 0, message: "创建成功", id: @issue.id}
else
normal_status(-1, "创建失败")
@ -304,6 +318,7 @@ class IssuesController < ApplicationController
login = @issue.user.try(:login)
SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, @issue&.subject, @issue.assigned_to_id, @issue.author_id) if Site.has_notice_menu?
if @issue.destroy
@project.incre_project_issue_cache_delete_count
if issue_type == "2" && status_id != 5
post_to_chain("add", token, login)
end
@ -543,7 +558,8 @@ class IssuesController < ApplicationController
branch_name: params[:branch_name].to_s,
issue_classify: "issue",
author_id: current_user.id,
project_id: @project.id
project_id: @project.id,
blockchain_token_num: params[:blockchain_token_num]
}
end

View File

@ -46,11 +46,17 @@ class JournalsController < ApplicationController
end
Rails.logger.info "[ATME] maybe to at such users: #{@atme_receivers.pluck(:login)}"
AtmeService.call(current_user, @atme_receivers, journal) if @atme_receivers.size > 0
TouchWebhookJob.set(wait: 5.seconds).perform_later('PullRequestComment', @issue&.id, current_user.id, journal.id, 'created', {})
# @issue.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "journal")
# author: zxh
# 调用上链API
push_activity_2_blockchain("issue_comment_create", journal) if Site.has_blockchain? && @project.use_blockchain
render :json => { status: 0, message: "评论成功", id: journal.id}
# normal_status(0, "评论成功")
else
normal_status(-1, "评论失败")
raise ActiveRecord::Rollback
end
end
end
@ -61,6 +67,7 @@ class JournalsController < ApplicationController
def destroy
if @journal.destroy #如果有子评论,子评论删除吗?
TouchWebhookJob.set(wait: 5.seconds).perform_later('PullRequestComment', @issue&.id, current_user.id, @journal.id, 'deleted', JSON.parse(@journal.to_builder.target!))
Journal.children_journals(@journal.id).destroy_all
normal_status(0, "评论删除成功")
else

View File

@ -49,24 +49,29 @@ class Oauth::EducoderController < Oauth::BaseController
open_user = OpenUsers::Educoder.find_by(uid: result['login'])
if open_user.present? && open_user.user.present?
successful_authentication(open_user.user)
redirect_to root_path(new_user: false)
return
else
if current_user.blank? || !current_user.logged?
new_user = true
login = User.generate_login('E')
reg_result = autologin_register(login,"#{login}@forge.com", "Ec#{login}2021#", 'educoder', true)
if reg_result[:message].blank?
open_user = OpenUsers::Educoder.create!(user_id: reg_result[:user][:id], uid: result['login'], extra: result)
autosync_register_trustie(login, "Ec#{login}2021#", "#{login}@forge.com")
successful_authentication(open_user.user)
else
render_error(reg_result[:message])
end
session[:unionid] = result['login']
# login = User.generate_login('E')
# reg_result = autologin_register(login,"#{login}@forge.com", "Ec#{login}2021#", 'educoder', true)
# if reg_result[:message].blank?
# open_user = OpenUsers::Educoder.create!(user_id: reg_result[:user][:id], uid: result['login'], extra: result)
# autosync_register_trustie(login, "Ec#{login}2021#", "#{login}@forge.com")
# successful_authentication(open_user.user)
# else
# render_error(reg_result[:message])
# end
else
OpenUsers::Educoder.create!(user: current_user, uid: result['login'], extra: result)
end
end
Rails.logger.info("[OAuth2] session[:unionid] -> #{session[:unionid]}")
redirect_to "/bindlogin/educoder"
redirect_to root_path(new_user: new_user)
# redirect_to root_path(new_user: new_user)
rescue Exception => ex
render_error(ex.message)
end

View File

@ -0,0 +1,56 @@
class Organizations::IsPinnedProjectsController < Organizations::BaseController
before_action :load_organization
def index
@is_pinned_projects = @organization.pinned_projects.order(position: :desc, created_at: :asc).includes(project: [:project_category, :project_language, :repository]).order(position: :desc)
@is_pinned_projects = kaminari_paginate(@is_pinned_projects)
end
def pin
project_ids = params[:is_pinned_project_ids] || []
@organization.is_pinned_project_ids = project_ids
render_ok
rescue ActiveRecord::RecordNotFound => e
render_not_found
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
def update
@pinned_project = PinnedProject.find_by_id(params[:id])
@pinned_project.attributes = pinned_project_params
if @pinned_project.save
render_ok
else
render_error
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
end
private
def load_organization
@organization = Organization.find_by(login: params[:organization_id]) || Organization.find_by(id: params[:organization_id])
return render_not_found("组织不存在") if @organization.nil?
return render_forbidden("没有查看组织的权限") if org_limited_condition || org_privacy_condition
end
# def is_pinned_project_ids
# if params[:is_pinned_project_ids].present?
# return params[:is_pinned_project_ids].select { |id| @organization.full_member_projects.visible.pluck(:id).include?(id.to_i) }
# end
# if params[:is_pinned_project_id].present?
# return @organization.is_pinned_project_ids unless @organization.full_member_projects.visible.pluck(:id).include?(params[:is_pinned_project_id].to_i)
# return @organization.is_pinned_project_ids.include?(params[:is_pinned_project_id].to_i) ? @organization.is_pinned_project_ids : @organization.is_pinned_project_ids.push(params[:is_pinned_project_id].to_i)
# end
# end
def pinned_project_params
params.require(:pinned_project).permit(:position)
end
end

View File

@ -1,8 +1,8 @@
class Organizations::OrganizationsController < Organizations::BaseController
before_action :require_login, except: [:index, :show, :recommend]
before_action :require_profile_completed, only: [:create]
before_action :require_login, except: [:index, :show, :recommend, :languages]
# before_action :require_profile_completed, only: [:create]
before_action :convert_image!, only: [:create, :update]
before_action :load_organization, only: [:show, :update, :destroy]
before_action :load_organization, only: [:show, :update, :destroy, :update_news, :update_memo, :update_other, :languages]
before_action :check_user_can_edit_org, only: [:update, :destroy]
def index
@ -62,6 +62,46 @@ class Organizations::OrganizationsController < Organizations::BaseController
tip_exception(e.message)
end
def update_news
@organization.organization_extension.update_attributes!(news_banner_id: params[:news_banner_id],
news_title: params[:news_title],
news_url: params[:news_url],
news_content: params[:news_content])
render_ok
end
def update_memo
@organization.organization_extension.update_attributes!(memo: params[:memo])
render_ok
end
def update_other
@organization.organization_extension.update_attributes!(news_banner_id: params[:news_banner_id],
news_content: params[:news_content],
news_title: params[:news_title],
news_url: params[:news_url],
memo: params[:memo])
render_ok
end
def languages
projects = @organization.projects
projects_count = @organization.projects.count
languages_hash = Rails.cache.fetch("query/organizations/languages/#{@organization.id}/#{projects_count}/2023", :expires_in => 1.days) do
total_languages(projects)
end
languages_hash = languages_hash.sort { |x, y| y[1] <=> x[1] }
sort_hash = Hash[*languages_hash.flatten]
total_byte_size = sort_hash.values.sum
# Rails.logger.info "languages_hash=============#{sort_hash}"
sort_hash= sort_hash.transform_values { |v|
ActionController::Base.helpers.number_to_percentage((v * 100 / total_byte_size), precision: 1)
}.select { |k, v| v != "0.0%" }
render json: sort_hash
end
def destroy
tip_exception("密码不正确") unless current_user.check_password?(password)
ActiveRecord::Base.transaction do
@ -144,5 +184,28 @@ class Organizations::OrganizationsController < Organizations::BaseController
# 更新对应所属分类下的项目数量(私有)
project.project_category.decrement!(:private_projects_count, 1) if project.project_category.present?
end
def total_languages(projects)
languages_hash ={}
projects.each do |p|
result = Gitea::Repository::Languages::ListService.call(p.owner.login,
p.identifier, current_user&.gitea_token)
next unless result[:status] === :success
total_byte_size = result[:body].values.sum
hash = result[:body].transform_values { |v|
(v * 100.0 / total_byte_size).to_f
}
hash.each do |key,value|
# Rails.logger.info "key=============#{key}:#{value}"
if languages_hash.has_key?(key)
languages_hash[key] = languages_hash[key] + value
else
languages_hash[key] = value
end
end
end
languages_hash
end
end

View File

@ -8,14 +8,17 @@ class Organizations::ProjectsController < Organizations::BaseController
.joins(team_projects: {team: :team_users})
.where(team_users: {user_id: current_user.id}).to_sql
@projects = Project.from("( #{ public_projects_sql} UNION #{ private_projects_sql } ) AS projects")
@projects = @projects.ransack(name_or_identifier_cont: params[:search]).result if params[:search].present?
# 表情处理
keywords = params[:search].to_s.each_char.select { |c| c.bytes.first < 240 }.join('')
@projects = @projects.ransack(name_or_identifier_cont: keywords).result if params[:search].present?
@projects = @projects.includes(:owner).order("projects.#{sort} #{sort_direction}")
@projects = paginate(@projects)
end
def search
tip_exception("请输入搜索关键词") if params[:search].nil?
# 表情处理
keywords = params[:search].to_s.each_char.select { |c| c.bytes.first < 240 }.join('')
public_projects_sql = @organization.projects.where(is_public: true).to_sql
private_projects_sql = @organization.projects
.where(is_public: false)
@ -23,7 +26,7 @@ class Organizations::ProjectsController < Organizations::BaseController
.where(team_users: {user_id: current_user.id}).to_sql
@projects = Project.from("( #{ public_projects_sql} UNION #{ private_projects_sql } ) AS projects")
@projects = @projects.ransack(name_or_identifier_cont: params[:search]).result
@projects = @projects.ransack(name_or_identifier_cont: keywords).result
@projects = @projects.includes(:owner).order("projects.#{sort} #{sort_direction}")
end

View File

@ -1,10 +1,13 @@
class ProjectRankController < ApplicationController
# 根据时间获取热门项目
def index
def index
limit = 9
limit = params[:limit].to_i - 1 if params[:limit].present?
limit = 99 if limit > 99
$redis_cache.zunionstore("recent-days-project-rank-#{time}", get_timeable_key_names)
deleted_data = $redis_cache.smembers("v2-project-rank-deleted")
$redis_cache.zrem("recent-days-project-rank-#{time}", deleted_data) unless deleted_data.blank?
@project_rank = $redis_cache.zrevrange("recent-days-project-rank-#{time}", 0, 9, withscores: true)
@project_rank = $redis_cache.zrevrange("recent-days-project-rank-#{time}", 0, limit, withscores: true)
rescue Exception => e
@project_rank = []
end

View File

@ -1,6 +1,6 @@
class ProjectTrendsController < ApplicationController
before_action :load_repository
before_action :check_project_public
before_action :load_repository, except: [:last]
before_action :check_project_public, except: [:last]
def index
project_trends = @project.project_trends.preload(:user, trend: :user, project: :owner)
@ -42,6 +42,14 @@ class ProjectTrendsController < ApplicationController
@project_trends = project_trends.page(@page).per(@limit)
end
def last
project_trends = ProjectTrend.preload(:user, trend: :user, project: :owner).order("id desc")
@page = params[:page] || 1
@limit = params[:limit] || 20
@project_trends_count = project_trends.count
@project_trends = project_trends.page(@page).per(@limit)
end
private
def check_project_public

View File

@ -34,18 +34,19 @@ class ProjectsController < ApplicationController
def index
scope = current_user.logged? ? Projects::ListQuery.call(params, current_user.id) : Projects::ListQuery.call(params)
@projects = kaminari_paginate(scope.includes(:project_category, :project_language, :repository, :project_educoder, :owner, :project_units))
@projects = kaminari_paginate(scope.includes(:project_category, :project_language, :repository, :project_educoder, :owner, :project_units, :project_topics))
# @projects = paginate scope.includes(:project_category, :project_language, :repository, :project_educoder, :owner, :project_units)
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?
if category_id.blank? && params[:search].blank? && params[:topic_id].blank?
# 默认查询时count性能问题处理
ProjectCategory.sum("projects_count") - Project.visible.joins("left join organization_extensions on organization_extensions.organization_id = projects.user_id").where("organization_extensions.visibility =2").count
elsif params[:search].present? || params[:topic_id].present?
@projects.total_count
else
cate = ProjectCategory.find_by(id: category_id)
cate&.projects_count || 0
cate = ProjectCategory.find_by(id: category_id)
cate&.projects_count || 0
end
end
@ -94,7 +95,7 @@ class ProjectsController < ApplicationController
# result = Gitea::Repository::Branches::ListService.call(@owner, @project.identifier)
result = Gitea::Repository::Branches::ListNameService.call(@owner, @project.identifier, params[:name])
@branches = result.is_a?(Hash) ? (result.key?(:status) ? [] : result["branch_name"]) : result
@branches = result.is_a?(Hash) ? (result.key?(:status) ? [] : result) : result
end
def branches_slice
@ -129,6 +130,13 @@ class ProjectsController < ApplicationController
# TODO:
# 临时特殊处理修改website、lesson_url操作方法
if project_params.has_key?("website")
if params[:project_topic_names].is_a?(Array)
ProjectTopicRalate.where(project: @project).destroy_all
params[:project_topic_names].each do |name|
project_topic = ProjectTopic.find_or_create_by!(name: name.downcase)
project_topic.project_topic_ralates.find_or_create_by!(project: @project)
end
end
@project.update(project_params)
elsif project_params.has_key?("default_branch")
@project.update(project_params)
@ -273,7 +281,8 @@ class ProjectsController < ApplicationController
private
def project_params
params.permit(:user_id, :name, :description, :repository_name, :website, :lesson_url, :default_branch, :identifier,
:project_category_id, :project_language_id, :license_id, :ignore_id, :private)
:project_category_id, :project_language_id, :license_id, :ignore_id, :private,
:blockchain, :blockchain_token_all, :blockchain_init_token)
end
def mirror_params

View File

@ -6,6 +6,7 @@ class PullRequestsController < ApplicationController
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]
before_action :find_atme_receivers, only: [:create, :update]
include TagChosenHelper
include ApplicationHelper
@ -73,6 +74,11 @@ class PullRequestsController < ApplicationController
SendTemplateMessageJob.perform_later('ProjectPullRequest', current_user.id, @pull_request&.id) if Site.has_notice_menu?
Rails.logger.info "[ATME] maybe to at such users: #{@atme_receivers.pluck(:login)}"
AtmeService.call(current_user, @atme_receivers, @pull_request) if @atme_receivers.size > 0
# author: zxh
# 调用上链API
push_activity_2_blockchain("pull_request_create", @pull_request) if Site.has_blockchain? && @project.use_blockchain
else
render_error("create pull request error: #{@gitea_pull_request[:status]}")
raise ActiveRecord::Rollback
@ -119,7 +125,19 @@ class PullRequestsController < ApplicationController
end
else
return normal_status(-1, "请输入正确的标记。")
end
end
end
if params[:attached_issue_ids].present?
if params[:attached_issue_ids].is_a?(Array) && params[:attached_issue_ids].size > 1
return normal_status(-1, "最多只能关联一个疑修。")
elsif params[:attached_issue_ids].is_a?(Array) && params[:attached_issue_ids].size == 1
@pull_request&.pull_attached_issues&.destroy_all
params[:attached_issue_ids].each do |issue|
PullAttachedIssue.create!(issue_id: issue, pull_request_id: @pull_request.id)
end
else
return normal_status(-1, "请输入正确的疑修。")
end
end
if params[:status_id].to_i == 5
@issue.issue_times.update_all(end_time: Time.now)
@ -149,12 +167,16 @@ class PullRequestsController < ApplicationController
ActiveRecord::Base.transaction do
begin
colsed = PullRequests::CloseService.call(@owner, @repository, @pull_request, current_user)
if colsed === true
# author: zxh
# 调用上链API
push_activity_2_blockchain("pull_request_refuse", @pull_request) if Site.has_blockchain? && @project.use_blockchain
if colsed === true
@pull_request.project_trends.create!(user: current_user, project: @project,action_type: ProjectTrend::CLOSE)
# 合并请求下issue处理为关闭
@issue&.update_attributes!({status_id:5})
SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, @pull_request.id) if Site.has_notice_menu?
normal_status(1, "已拒绝")
normal_status(1, "已拒绝")
else
normal_status(-1, '合并失败')
end
@ -173,7 +195,7 @@ class PullRequestsController < ApplicationController
@issue_user = @issue.user
@issue_assign_to = @issue.get_assign_user
@gitea_pull = Gitea::PullRequest::GetService.call(@owner.login,
@repository.identifier, @pull_request.gitea_number, current_user&.gitea_token)
@repository.identifier, @pull_request.gitea_number, @owner&.gitea_token)
@last_review = @pull_request.reviews.take
end
@ -198,6 +220,28 @@ class PullRequestsController < ApplicationController
# @pull_request.project_trend_status!
@pull_request.project_trends.create!(user: current_user, project: @project,action_type: ProjectTrend::MERGE)
@issue&.custom_journal_detail("merge", "", "该合并请求已被合并", current_user&.id)
# author: zxh
# 调用上链API
push_activity_2_blockchain("pull_request_merge", @pull_request) if Site.has_blockchain? && @project.use_blockchain
# 查看是否fix了相关issue如果fix就转账
@pull_request.attached_issues.each do |issue|
next if PullAttachedIssue.exists?(issue_id: issue.id, fixed: true)
token_num = issue.blockchain_token_num
token_num = token_num.nil? ? 0 : token_num
author_id = @pull_request.user_id
if token_num > 0
Blockchain::FixIssue.call({user_id: author_id.to_s, project_id: @project.id.to_s, token_num: token_num}) if Site.has_blockchain? && @project.use_blockchain
PullAttachedIssue.find_by(issue_id: issue.id, pull_request_id: @pull_request.id).update(fixed: true)
end
# update issue to state 5
issue.issue_participants.create!({participant_type: "edited", participant_id: current_user.id}) unless issue.issue_participants.exists?(participant_type: "edited", participant_id: current_user.id)
journal = issue.journals.create!({user_id: current_user.id})
journal.journal_details.create!({property: "attr", prop_key: "status_id", old_value: issue.status_id, value: 5})
issue.update(status_id: 5)
end
# 合并请求下issue处理为关闭
@issue&.update_attributes!({status_id:5})
SendTemplateMessageJob.perform_later('PullRequestMerged', current_user.id, @pull_request.id) if Site.has_notice_menu?
@ -237,12 +281,12 @@ class PullRequestsController < ApplicationController
def files
@files_result = Gitea::PullRequest::FilesService.call(@owner.login, @project.identifier, @pull_request.gitea_number, current_user&.gitea_token)
@files_result = Gitea::PullRequest::FilesService.call(@owner.login, @project.identifier, @pull_request.gitea_number, @owner&.gitea_token)
# render json: @files_result
end
def commits
@commits_result = Gitea::PullRequest::CommitsService.call(@owner.login, @project.identifier, @pull_request.gitea_number, current_user&.gitea_token)
@commits_result = Gitea::PullRequest::CommitsService.call(@owner.login, @project.identifier, @pull_request.gitea_number, @owner&.gitea_token)
# render json: @commits_result
end
@ -274,15 +318,10 @@ class PullRequestsController < ApplicationController
body: params[:body], #内容
head: params[:head], #源分支
base: params[:base], #目标分支
milestone: 0, #里程碑,未与本地的里程碑关联
# milestone: 0, #里程碑,未与本地的里程碑关联
}
assignee_login = User.find_by_id(params[:assigned_to_id])&.login
@requests_params = @local_params.merge({
# assignees: ["#{params[:assigned_login].to_s}"],
assignees: ["#{assignee_login.to_s}"],
labels: params[:issue_tag_ids]
# due_date: Time.now
})
@requests_params = @local_params.merge({assignees: [assignee_login.to_s].reject!(&:empty?)})
@issue_params = {
author_id: current_user.id,
project_id: @project.id,

View File

@ -22,6 +22,12 @@ class RepositoriesController < ApplicationController
def detail
@user = current_user
@result = Repositories::DetailService.call(@owner, @repository, @user)
cache_total_forks = $redis_cache.get("ProjectSpecialForks:#{@project.id}")
if cache_total_forks.present?
@project_forked_count = cache_total_forks.to_i
else
@project_forked_count = @project.forked_count.to_i
end
@project_fork_id = @project.try(:forked_from_project_id)
if @project_fork_id.present?
@fork_project = Project.find_by(id: @project_fork_id)
@ -110,7 +116,8 @@ class RepositoriesController < ApplicationController
result = interactor.result
@sub_entries = result.is_a?(Array) ? result.sort_by{ |hash| hash['type'] } : result
else
render_error(interactor.error)
status = interactor.error == "你访问的文件不存在"? -2 : -1
render_error(interactor.error,status)
end
end
end
@ -122,10 +129,10 @@ class RepositoriesController < ApplicationController
if params[:filepath].present?
file_path_uri = URI.parse(URI.encode(params[:filepath].to_s.strip))
@hash_commit = Gitea::Repository::Commits::FileListService.new(@owner.login, @project.identifier, file_path_uri,
sha: params[:sha], page: params[:page], limit: params[:limit], token: current_user&.gitea_token).call
sha: params[:sha], page: params[:page], limit: params[:limit], token: @owner&.gitea_token).call
else
@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
sha: params[:sha], page: params[:page], limit: params[:limit], token: @owner&.gitea_token).call
end
end
end
@ -140,8 +147,8 @@ class RepositoriesController < ApplicationController
if @project.educoder?
return render_error('暂未开放,敬请期待.')
else
@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})
@commit = Gitea::Repository::Commits::GetService.call(@owner.login, @repository.identifier, @sha, @owner&.gitea_token)
@commit_diff = Gitea::Repository::Commits::GetService.call(@owner.login, @repository.identifier, @sha, @owner&.gitea_token, {diff: true})
render_error(@commit[:message], @commit[:status]) if @commit.has_key?(:status) || @commit_diff.has_key?(:status)
end
end
@ -156,7 +163,7 @@ class RepositoriesController < ApplicationController
@tag_names = result.is_a?(Hash) && result.key?(:status) ? [] : name_result
result = Gitea::Repository::Tags::ListService.call(current_user&.gitea_token, @owner.login, @project.identifier, {page: params[:page], limit: params[:limit]})
result = Gitea::Repository::Tags::ListService.call(@owner&.gitea_token, @owner.login, @project.identifier, {page: params[:page], limit: params[:limit]})
@tags = result.is_a?(Hash) && result.key?(:status) ? [] : result
end
@ -166,8 +173,9 @@ class RepositoriesController < ApplicationController
if params[:filepath].present? || @project.educoder?
@contributors = []
else
result = Gitea::Repository::Contributors::GetService.call(@owner, @repository.identifier)
@contributors = result.is_a?(Hash) && result.key?(:status) ? [] : result
result = Gitea::Repository::Contributors::GetService.call(@owner, @repository.identifier, {page: params[:page], limit: params[:limit]})
@total_count = result[:total_count]
@contributors = result.is_a?(Hash) ? result[:body] : []
end
rescue
@contributors = []
@ -210,6 +218,21 @@ class RepositoriesController < ApplicationController
end
end
def replace_file
#删除
delete_interactor = Gitea::DeleteFileInteractor.call(current_user.gitea_token, @owner.login, params[:delete_file].merge(identifier: @project.identifier))
return render_error(delete_interactor.error) unless delete_interactor.success?
#新建
interactor = Gitea::CreateFileInteractor.call(current_user.gitea_token, @owner.login, content_params)
if interactor.success?
@file = interactor.result
render_result(0, "替换成功")
else
render_error(interactor.error)
end
end
def delete_file
interactor = Gitea::DeleteFileInteractor.call(current_user.gitea_token, @owner.login, params.merge(identifier: @project.identifier))
if interactor.success?
@ -234,9 +257,9 @@ class RepositoriesController < ApplicationController
def readme
if params[:filepath].present?
result = Gitea::Repository::Readme::DirService.call(@owner.login, @repository.identifier, params[:filepath], params[:ref], current_user&.gitea_token)
result = Gitea::Repository::Readme::DirService.call(@owner.login, @repository.identifier, params[:filepath], params[:ref], @owner&.gitea_token)
else
result = Gitea::Repository::Readme::GetService.call(@owner.login, @repository.identifier, params[:ref], current_user&.gitea_token)
result = Gitea::Repository::Readme::GetService.call(@owner.login, @repository.identifier, params[:ref], @owner&.gitea_token)
end
@path = GiteaService.gitea_config[:domain]+"/#{@owner.login}/#{@repository.identifier}/raw/branch/#{params[:ref]}/"
@readme = result[:status] === :success ? result[:body] : nil
@ -261,7 +284,7 @@ class RepositoriesController < ApplicationController
archive_url = "/repos/#{@owner.login}/#{@repository.identifier}/archive/#{Addressable::URI.escape(params[:archive])}"
file_path = [domain, api_url, archive_url].join
file_path = [file_path, "access_token=#{current_user&.gitea_token}"].join("?") if @repository.hidden?
file_path = [file_path, "access_token=#{@owner&.gitea_token}"].join("?")
return render_not_found if !request.format.zip? && !request.format.gzip?
@ -272,9 +295,9 @@ class RepositoriesController < ApplicationController
domain = GiteaService.gitea_config[:domain]
api_url = GiteaService.gitea_config[:base_url]
url = "/repos/#{@owner.login}/#{@repository.identifier}/raw/#{Addressable::URI.escape(params[:filepath])}?ref=#{Addressable::URI.escape(params[:ref])}"
url = "/repos/#{@owner.login}/#{@repository.identifier}/raw/#{CGI.escape(params[:filepath])}?ref=#{CGI.escape(params[:ref])}"
file_path = [domain, api_url, url].join
file_path = [file_path, "access_token=#{current_user&.gitea_token}"].join("&")
file_path = [file_path, "access_token=#{@owner&.gitea_token}"].join("&")
redirect_to file_path
end
@ -302,16 +325,16 @@ class RepositoriesController < ApplicationController
if params[:filepath].present?
file_path_uri = URI.parse(URI.encode(params[:filepath].to_s.strip))
Gitea::Repository::Commits::FileListService.new(@project.owner.login, @project.identifier, file_path_uri,
sha: get_ref, page: 1, limit: 1, token: current_user&.gitea_token).call
sha: get_ref, page: 1, limit: 1, token: @project&.owner&.gitea_token).call
else
Gitea::Repository::Commits::ListService.new(@project.owner.login, @project.identifier,
sha: get_ref, page: 1, limit: 1, token: current_user&.gitea_token).call
sha: get_ref, page: 1, limit: 1, token: @project&.owner&.gitea_token).call
end
end
def get_statistics
@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
@tags_count = @project.educoder? ? 0 : Gitea::Repository::Tags::ListService.new(@project&.owner&.gitea_token, @project.owner.login, @project.identifier).call&.size
end
def get_ref
@ -321,7 +344,12 @@ class RepositoriesController < ApplicationController
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
cache_total_commits = $redis_cache.get("ProjectSpecialCommit:#{@project.id}")
if cache_total_commits.present?
@commits_count = cache_total_commits.to_i
else
@commits_count = latest_commit.present? ? latest_commit[:total_count] : 0
end
end
def content_params

View File

@ -12,7 +12,7 @@ class Traces::ProjectsController < Traces::BaseController
return render_error("无可用检测次数") if @project.user_trace_tasks.size >= 5
return render_error("分支名不能为空!") if branch_name.blank?
@all_branches = Gitea::Repository::Branches::ListNameService.call(@project&.owner, @project.identifier)
return render_error("请输入正确的分支名!") unless @all_branches["branch_name"].include?(branch_name)
return render_error("请输入正确的分支名!") unless @all_branches.include?(branch_name)
code, data, error = Trace::CheckService.call(current_user.trace_token, @project, "1", branch_name)
if code == 200
UserTraceTask.create!(
@ -51,7 +51,7 @@ class Traces::ProjectsController < Traces::BaseController
branch_name = params[:branch_name]
return render_error("分支名不能为空!") if branch_name.blank?
@all_branches = Gitea::Repository::Branches::ListNameService.call(@project&.owner, @project.identifier)
return render_error("请输入正确的分支名!") unless @all_branches["branch_name"].include?(branch_name)
return render_error("请输入正确的分支名!") unless @all_branches.include?(branch_name)
code, data, error = Trace::ReloadCheckService.call(current_user.trace_token, params[:project_id])
if code == 200
UserTraceTask.create!(

View File

@ -1,8 +1,11 @@
class UserRankController < ApplicationController
# 根据时间获取热门开发者
def index
def index
limit = 3
limit = params[:limit].to_i - 1 if params[:limit].present?
limit = 99 if limit > 99
$redis_cache.zunionstore("recent-days-user-rank", get_timeable_key_names)
@user_rank = $redis_cache.zrevrange("recent-days-user-rank", 0, 3, withscores: true)
@user_rank = $redis_cache.zrevrange("recent-days-user-rank", 0, limit, withscores: true)
rescue Exception => e
@user_rank = []
end

View File

@ -1,7 +1,17 @@
class Users::HeadmapsController < Users::BaseController
def index
result = Gitea::User::HeadmapService.call(observed_user.login, start_stamp, end_stamp)
result = Gitea::User::HeadmapService.call(observed_user.login, start_stamp, end_stamp, observed_user&.gitea_token)
@headmaps = result[2].blank? ? [] : result[2]
headmaps_result = {}
@headmaps.each do |entry|
date = Time.at(entry["timestamp"]).strftime("%Y-%m-%d")
if headmaps_result[date].nil?
headmaps_result[date] = { "contributions" => entry["contributions"] }
else
headmaps_result[date]["contributions"] += entry["contributions"]
end
end
@headmaps = headmaps_result
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
@ -10,17 +20,17 @@ class Users::HeadmapsController < Users::BaseController
private
def start_stamp
if params[:year].present?
Date.new(params[:year], 1).to_time.to_i
Date.new(params[:year].to_i, 1).to_time.to_i
else
Date.today.to_time.to_i - 365*24*60*60
(Date.today - 1.years).to_time.to_i
end
end
def end_stamp
if params[:year].present?
Date.new(params[:year], 1).to_time.to_i + 365*24*60*60
(Date.new(params[:year].to_i, 1) + 1.years).to_time.end_of_day.to_i
else
Date.today.to_time.to_i
Date.today.to_time.end_of_day.to_i
end
end
end

View File

@ -1,6 +1,7 @@
class Users::MessagesController < Users::BaseController
before_action :private_user_resources!
before_action :find_receivers, only: [:create]
before_action :check_auth
def index
limit = params[:limit] || params[:per_page]
@ -63,6 +64,10 @@ class Users::MessagesController < Users::BaseController
end
private
def check_auth
return render_forbidden unless current_user.admin? || observed_logged_user?
end
def message_type
@message_type = begin
case params[:type]

View File

@ -4,7 +4,7 @@ class Users::StatisticsController < Users::BaseController
# 近期活动统计
def activity
date_range = (1.week.ago.to_date..Date.today).to_a
commit_request = Gitea::User::HeadmapService.call(observed_user.login, 1.week.ago.to_date.to_time.to_i, Date.today.to_time.to_i)
commit_request = Gitea::User::HeadmapService.call(observed_user.login, 1.week.ago.to_date.to_time.to_i, Date.today.end_of_day.to_time.to_i, observed_user.gitea_token)
commit_data = commit_request[2]
@date_data = []
@issue_data = []
@ -14,8 +14,11 @@ class Users::StatisticsController < Users::BaseController
@date_data << date.strftime("%Y.%m.%d")
@issue_data << observed_user.issues.issue_issue.where("DATE(created_on) = ?", date).size
@pull_request_data << observed_user.pull_requests.where("DATE(created_at) = ?", date).size
date_commit_data = commit_data.blank? ? nil : commit_data.select{|item| item["timestamp"] == date.to_time.to_i}
@commit_data << (date_commit_data.blank? ? 0 : date_commit_data[0]["contributions"].to_i)
contribution = 0
commit_data.each do |item|
contribution += item["contributions"] if Time.at(item["timestamp"]).strftime("%Y-%m-%d") == date.to_s
end
@commit_data << contribution
end
render :json => {dates: @date_data, issues_count: @issue_data, pull_requests_count: @pull_request_data, commits_count: @commit_data}
end

View File

@ -2,8 +2,8 @@ class UsersController < ApplicationController
include ApplicationHelper
include Ci::DbConnectable
before_action :load_user, only: [:show, :homepage_info, :sync_token, :sync_gitea_pwd, :projects, :watch_users, :fan_users, :hovercard]
before_action :check_user_exist, only: [:show, :homepage_info,:projects, :watch_users, :fan_users, :hovercard]
before_action :load_user, only: [:show, :homepage_info, :sync_token, :sync_gitea_pwd, :projects, :watch_users, :fan_users, :hovercard, :hovercard4proj]
before_action :check_user_exist, only: [:show, :homepage_info,:projects, :watch_users, :fan_users, :hovercard, :hovercard4proj]
before_action :require_login, only: %i[me sync_user_info]
before_action :connect_to_ci_db, only: [:get_user_info]
before_action :convert_image!, only: [:update, :update_image]
@ -81,9 +81,134 @@ class UsersController < ApplicationController
@watchers = paginate(watchers)
end
def contribution_perc
project_id = params[:project_id]
@project = Project.find(project_id)
user_id = params[:id]
@user = User.find(user_id)
def cal_perc(count_user, count_all)
(count_user * 1.0 / (count_all + 0.000000001)).round(5)
end
if @project['use_blockchain'] == true or @project['use_blockchain'] == 1
balance_user = Blockchain::BalanceQueryOneProject.call({"user_id": user_id, "project_id": project_id})
balance_all = Blockchain::RepoBasicInfo.call({"project_id": project_id})["cur_supply"]
scores = {
"final" => cal_perc(balance_user, balance_all),
"blockchain" => true
}
else
# 获取所有行为对应的项目内记录总数和个人记录数
features = {
"requirement" => {},
"development" => {},
"review" => {}
}
# 1. issue创建
issues = Issue.where(project_id: project_id, issue_classify: 'issue')
issue_all = issues.count
issue_user = issues.where(author_id: user_id).count
features["requirement"] = features["requirement"].merge({"issue" => {"all" => issue_all, "perc" => cal_perc(issue_user, issue_all)}})
# 2. 里程碑创建
milestones = Version.where(project_id: project_id)
milestone_all = milestones.count
milestone_user = milestones.where(user_id: user_id).count
features["requirement"] = features["requirement"].merge({"milestone" => {"all" => milestone_all, "perc" => cal_perc(milestone_user, milestone_all)}})
# 3. issue评论
issue_comments = Journal.joins("INNER JOIN issues on journals.journalized_id=issues.id").where("issues.project_id=#{project_id} and journalized_type='Issue' and issues.issue_classify='issue'")
issue_comment_all = issue_comments.count
issue_comment_user = issue_comments.where("journals.user_id=#{user_id}").count
features["requirement"] = features["requirement"].merge({"issue_comment" => {"all" => issue_comment_all, "perc" => cal_perc(issue_comment_user, issue_comment_all)}})
# 4. 合并请求
prs = PullRequest.where(project_id: project_id)
pr_all = prs.count
pr_user = prs.where(user_id: user_id).count
features["development"] = features["development"].merge({"pr" => {"all" => pr_all, "perc" => cal_perc(pr_user, pr_all)}})
# 5. pr评论
pr_comments = Journal.joins("INNER JOIN issues on journals.journalized_id=issues.id").where("issues.project_id=#{project_id} and journalized_type='Issue' and issues.issue_classify='pull_request'")
pr_comment_all = pr_comments.count
pr_comment_user = pr_comments.where("journals.user_id=#{user_id}").count
features["review"] = features["review"].merge({"pr_comment" => {"all" => pr_comment_all, "perc" => cal_perc(pr_comment_user, pr_comment_all)}})
# 6. 代码行评论
line_comments = Journal.joins("INNER JOIN pull_requests on journals.journalized_id=pull_requests.id").where("pull_requests.project_id=#{project_id} and journalized_type='PullRequest'")
line_comment_all = line_comments.count
line_comment_user = line_comments.where("journals.user_id=#{user_id}").count
features["review"] = features["review"].merge({"line_comment" => {"all" => line_comment_all, "perc" => cal_perc(line_comment_user, line_comment_all)}})
# 7. 代码行、commit贡献统计
code_contributions = Api::V1::Projects::CodeStats::ListService.call(@project, {ref: nil})
commit_all = code_contributions["commit_count"]
addition_all = code_contributions["additions"]
deletion_all = code_contributions["deletions"]
commit_user = 0
addition_user = 0
deletion_user = 0
code_contributions["authors"].each do |author|
if author["name"] == @user.login
commit_user = author["commits"]
addition_user = author["additions"]
deletion_user = author["deletions"]
end
end
features["development"] = features["development"].merge({"commit" => {"all" => commit_all, "perc" => cal_perc(commit_user, commit_all)}})
features["development"] = features["development"].merge({"addition" => {"all" => addition_all, "perc" => cal_perc(addition_user, addition_all)}})
features["development"] = features["development"].merge({"deletion" => {"all" => deletion_all, "perc" => cal_perc(deletion_user, deletion_all)}})
def cal_weight(features)
weights = {} # 计算每一项的权重
categories = []
features.each do |key, _|
categories << key
weights[key] = Hash.new
end
count_all = 0
counts = {}
categories.each do |category|
count_1 = 0
features[category].each do |_, value|
count_1 += value["all"]
end
count_all += count_1
counts[category] = count_1
features[category].each do |key, value|
weight = cal_perc(value["all"], count_1)
weights[category] = weights[category].merge({key => weight})
end
end
categories.each do |category|
weight = cal_perc(counts[category], count_all)
weights[category] = weights[category].merge({"category_weight" => weight})
end
return weights
end
weights_categories = cal_weight(features)
scores = {
"final" => 0.0,
"blockchain" => false
}
features.each do |category, value_1|
category_score = 0.0
value_1.each do |action, value_2|
category_score += weights_categories[category][action] * value_2["perc"]
end
scores["final"] += weights_categories[category]["category_weight"] * category_score.round(4)
scores = scores.merge({category => category_score.round(4)})
end
end
render json: { scores: scores }
end
def hovercard
end
# author: zxh, 查询贡献者的贡献度
def hovercard4proj
end
def update
return render_not_found unless @user = User.find_by(login: params[:id]) || User.find_by_id(params[:id])
return render_forbidden unless User.current.logged? && (current_user&.admin? || current_user.id == @user.id)
@ -94,11 +219,11 @@ class UsersController < ApplicationController
end
end
def update_image
return render_not_found unless @user = User.find_by(login: params[:id]) || User.find_by_id(params[:id])
def update_image
return render_not_found unless @user = User.find_by(login: params[:id]) || User.find_by_id(params[:id])
return render_forbidden unless User.current.logged? && (current_user&.admin? || current_user.id == @user.id)
Util.write_file(@image, avatar_path(@user))
Util.write_file(@image, avatar_path(@user))
return render_ok({message: '头像修改成功'})
rescue Exception => e
uid_logger_error(e.message)
@ -281,7 +406,253 @@ class UsersController < ApplicationController
is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == @user.id)
scope = Projects::ListMyQuery.call(params, @user,is_current_admin_user)
@total_count = scope.size
@projects = paginate(scope)
@projects = kaminari_unlimit_paginate(scope)
end
# query all projects with tokens by a user
def blockchain_balance
#is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i)
is_current_admin_user = true
results = Blockchain::BalanceQuery.call(params, is_current_admin_user)
if results[:status] == 0
@total_count = results[:total_count]
@projects = results[:projects]
else
@total_count = -1
@projects = []
end
# render json: { status: results[:status], projects: @projects, total_count: @total_count }
end
# query one balance
def blockchain_balance_one_project
#is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i)
is_current_admin_user = true
if is_current_admin_user
owner = User.find_by(login: params['owner_login'])
if owner.nil?
normal_status(-1, "创建者无法找到")
else
p = Project.find_by(user_id: owner.id, identifier: params['project_identifier'])
balance = Blockchain::BalanceQueryOneProject.call({"user_id": params['user_id'].to_i, "project_id": p.id.to_i})
render json: { status: 0, balance: balance}
end
else
normal_status(-1, "缺少权限")
end
end
def blockchain_transfer
#is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['payer_id'].to_i)
is_current_admin_user = true
if is_current_admin_user
Blockchain::TransferService.call(params)
render json: {status: 2} # 重新查询余额
else
normal_status(-1, "缺少权限")
end
rescue Exception => e
normal_status(-1, e.to_s)
end
# exchange money
def blockchain_exchange
#is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i)
#require 'alipay'
## setup the client to communicate with either production API or sandbox API
## https://openapi.alipay.com/gateway.do (Production)
## https://openapi.alipaydev.com/gateway.do (Sandbox)
#api_url = 'https://openapi.alipay.com/gateway.do'
#
## setup your own credentials and certificates
#app_id = '2021002140631434'
#app_private_key="-----BEGIN RSA PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCPDsgc0n0RWRnbe9OMqtUbde8gu88OyjuZm8cJXeiSING18HX56C5zV4DsHQ6K9/JmQi/NYCc7/2Prh66Bei0L4Xm5TysJTPYi90+WlbJJESFF6fqULi8sSqZXUtaoMKRcUyeR144l2GQgXbZWBbVSQeZW5DqUDlurTF0I7vQ21wGqxQqBjQK8PSVw5hF+aIsNOfAY9M1tzdD5Jzo2Y3FJdsbXIJNMyhJJCZ+7KHFqma7lpjkXdCoyh/nOISkQdGtFI29gI94sqewI2AMU84uxuBIE3h90iLT+8xrd2dQKdBS7qfhQ3PgkBPVNs5jxsVBqSFdSFT6zcqFdHJzulCUJAgMBAAECggEAWocAGz0X5+J6emnhdSKluLrol85BORrAnHP3f/XtNouOKZQBFCPZQSQecUvx5/7/ZbZ8iXpPWahDkshJpaWq29nTLXDryvboyze1JZWVPKeaZqOp7htLvrt+h8PkEoq1d7cnUyMU0N4eflzPBaCXHXaWTGYgq5Bqcfvg48ZSxGBYeHt5WWU2+GW5fpsaVBBYkdyxxGMoy/bzYzGhvfSJkexqnl0XkAAODa02mu3WsHrzRid6Mf+3syYbq/MfUodU6Vng2tbCqwnWrHCyrD4RYl6rg1TKuAv2YAfBhLzwBxHYVC4SRqzjs+8AaOQoF+lCjr4JklPhEuRThzD31YwIAQKBgQDAg4S7ciMmxvbNxR+1eimoAYLLF9jPpPU6w3VFNPb4rDu4tX77bNf082YplfJX5TYtZKjKPKyYG87K6slGunyPL4AFRW81WPB9u1uP26dihyPCBSUE01jKRPPfRrQnnru5fpm8LL3L03V3yA6J+GyQ8wltRJJi1eBSSm+IWRsZewKBgQC+PBD9J1LYOEIVeK9KvN8BpkA1ZIkk//VuJaoGfVXn+1EzM1yFB05fnsEQkHFynisvuCIr7pH63HcdyffQhe1YOnw9iDCG1zPjsi5uTe9WAM0dnb7xdsaLPr/Q2LyoDOTN9344Qovy1AAnpWtGTn6omgHst5nZpp/mHOuBlKiqSwKBgBKRXM77fjpyPEGyfpFxW+0xYB0YirfUUDa/vWLUbfGkIwp4ruuvHtEoXLUsGjiyCdys9b6zxW3SWMqnhIxG1la1HSLlBInfryphVL52UBmnsSI4fs6NV+YCaocheaTMoYyNkmRc6F1tYsoPyJ80D7yXRFR+paPUvxMQzNsYxQ1bAoGAHd2uSSBQWFPUxCwzUQd/93FTaU6EXYO103okTGqG/ymsoN4ya0wvWMHCy8fxl64PV6mP69fDoV/Vb57SwjEUhyJ/eOWVwMWuhtPliDnCFn1/tmOao6wjFZ9fW/l6/OMxVMjDTy/bat8vuwm0YtBWAEBVhwV4KPyI5AasTqa5KCsCgYB/usnqhVx2zt+MxpBt2Q9Vxc0zXcZxMDs69UUdTY86gjcJyCFGe3bbumUcyfSJzIznC2hfFX5ZyS0oMwiAzWtslRMh9LRh3kofD/6BogL3RKOlBk3iekvQ8Gn0tbwk2Qzr4WJgfA7A4GTf5r7Y+bvOfazzsUQAfSK6nUTIlOj2Ew==\n-----END RSA PRIVATE KEY-----\n"
#alipay_public_key="-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgHXLD1BshMymbqqtZVKNyo95FNfxzXzaw3P1eI0KeO6RaL+JzrWxzIBFfTjkWv/8WM9u/NcXMOFt2QO9q5KIDx6PkqjRDTd1hgP/cTgdjOHQqnVSihCrQDVCDBSOXIujC8Lk/P4pFVRhQkYeZqEb1qb8b/2tzTY8g9PKKBSCQv7SfgL2TBcpAVbb+9xdJ6VainC/wYGk8T+c+st1hXnuBJSS0m7LFxJOsYkNk0wbA0tfdZLrO3us2F7sjC9t4h/05nr+gSuDkzo+1kCEefYLqScexN+vnQiLoylp/C82wNiP6okxfhmHz3EcYfUqUyGTN/oFaFcPFPpUtFNS8jFV9QIDAQAB\n-----END PUBLIC KEY-----\n"
#
## initialize a client to communicate with the Alipay API
#@alipay_client = Alipay::Client.new(
# url: api_url,
# app_id: app_id,
# app_private_key: app_private_key,
# alipay_public_key: alipay_public_key
#)
#
#return_result = @alipay_client.page_execute_url(
# method: 'alipay.trade.page.pay',
# biz_content: JSON.generate({
# out_trade_no: '20210420104600',
# product_code: 'FAST_INSTANT_TRADE_PAY',
# total_amount: '0.01',
# subject: 'test'
# }, ascii_only: true), # ascii_only is important!
# timestamp: '2021-04-20 10:46:00'
#)
#render json: { pay_url: return_result }
#
# 替代解决方案
# 读取所有交易信息
end
# #
# # def blockchain_create_trade
# # #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i)
# # is_current_admin_user = true
# # if is_current_admin_user
# # user_id = params['user_id'].to_i
# # project_id = params['project_id'].to_i
# # money = params['money'].to_f
# # #description = params['description']
# # token_num = params['token_num'].to_i
# # # 锁仓
# # result = Blockchain::CreateTrade.call({user_id: user_id, project_id: project_id, token_num: token_num})
# # if result == false
# # normal_status(-1, "创建交易失败")
# # else
# # bt = BlockchainTrade.new(user_id: user_id, project_id: project_id, token_num: token_num, money: money, state: 0) # state=0表示创建交易; state=1表示执行中; state=2表示执行完成
# # bt.save()
# # status = 2 # 交易创建成功
# # render json: { status: status }
# # end
# # else
# # normal_status(-1, "缺少权限")
# # end
# # end
# #
# #
# # def blockchain_get_trades
# # trades = BlockchainTrade.where(state: 0).all()
# # results = []
# # trades.each do |t|
# # project_id = t.project_id
# # project = Project.find_by(id: project_id)
# # if !project.nil?
# # owner = User.find_by(id: project.user_id)
# # else
# # owner = nil
# # end
# # user_id = t.user_id
# # creator = User.find_by(id: user_id)
# # if project.nil? || owner.nil? || creator.nil?
# # else
# # results << [creator, owner, project, t]
# # end
# # end
# # render json: { results: results }
# # end
# #
# # def blockchain_trade
# # #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i)
# # is_current_admin_user = true
# # if is_current_admin_user
# # user_id2 = params['user_id2'].to_i
# # trade_id = params['trade_id'].to_i
# # BlockchainTrade.find(trade_id).update(user_id2: user_id2, state: 1) # state=1表示锁定了等待线下卖家发货
# # render json: {status: 2} # window.location.reload()
# # else
# # normal_status(-1, "缺少权限")
# # end
# # end
#
#
# def blockchain_verify_trade
# #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i)
# is_current_admin_user = true
# if is_current_admin_user
# trade_id = params['trade_id'].to_i
# BlockchainTrade.find(trade_id).update(state: 2) # state=2表示确认收货
# render json: {status: 2} # window.location.reload()
# else
# normal_status(-1, "缺少权限")
# end
# end
#
# def blockchain_get_verify_trades
# #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i)
# is_current_admin_user = true
# if is_current_admin_user
# trades = BlockchainTrade.where(state: 1).all()
# results = []
# trades.each do |t|
# project_id = t.project_id
# project = Project.find_by(id: project_id)
# if !project.nil?
# owner = User.find_by(id: project.user_id)
# else
# owner = nil
# end
# user_id = t.user_id
# creator = User.find_by(id: user_id)
# user_id2 = t.user_id2
# buyer = User.find_by(id: user_id2)
# if project.nil? || owner.nil? || creator.nil? || buyer.nil?
# else
# results << [creator, owner, project, t, buyer]
# end
# end
# render json: { results: results }
# else
# normal_status(-1, "缺少权限")
# end
# end
#
# def blockchain_get_history_trades
# #is_current_admin_user = User.current.logged? && (current_user&.admin? || current_user.id == params['user_id'].to_i)
# is_current_admin_user = true
# if is_current_admin_user
# trades = BlockchainTrade.where(state: 2).all()
# results = []
# trades.each do |t|
# project_id = t.project_id
# project = Project.find_by(id: project_id)
# if !project.nil?
# owner = User.find_by(id: project.user_id)
# else
# owner = nil
# end
# user_id = t.user_id
# creator = User.find_by(id: user_id)
# user_id2 = t.user_id2
# buyer = User.find_by(id: user_id2)
# if project.nil? || owner.nil? || creator.nil? || buyer.nil?
# else
# results << [creator, owner, project, t, buyer]
# end
# end
# render json: { results: results }
# else
# normal_status(-1, "缺少权限")
# end
# end
def blockchain_get_issue_token_num
issue_id = params["issue_id"]['orderId'].to_i
issue = Issue.find_by(id: issue_id)
project = Project.find(issue.project_id)
if project[:use_blockchain]
render json: {"blockchain_token_num": issue.blockchain_token_num}
else
render json: {"blockchain_token_num": -1} # 未使用blockchain
end
end
def blockchain_get_unclosed_issue_list
ownername = params["ownername"]
identifier = params["reponame"]
owner = User.find_by(login: ownername)
project = Project.find_by(user_id: owner.id, identifier: identifier)
unclosed_issues = Issue.where(project_id: project.id, issue_classify: "issue").where.not(status_id: 5)
results = []
unclosed_issues.each do |i|
results << [i.id, i.subject]
end
render json: {unclosed_issues: results}
end
# TODO 其他平台登录时同步修改gitea平台对应用户的密码
@ -322,7 +693,7 @@ class UsersController < ApplicationController
end
end
def email_search
def email_search
return render_error('请输入email') if params[:email].blank?
@user = User.find_by(mail: params[:email])
end

View File

@ -163,7 +163,7 @@ class VersionReleasesController < ApplicationController
end
def check_release_authorize
return render_forbidden("您没有权限进行此操作.") unless current_user.admin? || @project.manager?(current_user)
return render_forbidden("您没有权限进行此操作.") unless current_user.admin? || @project.manager?(current_user) || @project.develper?(current_user)
end
end

View File

@ -30,6 +30,14 @@ class BaseForm
raise "项目名称已被使用." if Project.where(user_id: user_id, name: project_name.strip).exists?
end
def check_blockchain_token_all(blockchain_token_all)
raise "请正确填写项目token总数." if (Float(blockchain_token_all) rescue false) == false or blockchain_token_all.to_i < 0 or Float(blockchain_token_all) != blockchain_token_all.to_i
end
def check_blockchain_init_token(blockchain_init_token)
raise "请正确填写项目创始人token占比." if (Float(blockchain_init_token) rescue false) == false or blockchain_init_token.to_i < 0 or Float(blockchain_init_token) != blockchain_init_token.to_i
end
def check_reversed_keyword(repository_name)
raise "项目标识已被占用." if ReversedKeyword.check_exists?(repository_name)
end

View File

@ -1,9 +1,10 @@
class Projects::CreateForm < BaseForm
attr_accessor :user_id, :name, :description, :repository_name, :project_category_id,
:project_language_id, :ignore_id, :license_id, :private, :owner
:project_language_id, :ignore_id, :license_id, :private, :owner,
:blockchain, :blockchain_token_all, :blockchain_init_token
validates :user_id, :name, :repository_name, presence: true
validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" }
validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "长度为2~100 只能包含数字,字母,下划线(_),中划线(-),英文句号(.),必须以数字和字母开头,不能以下划线/中划线/英文句号开头和结尾" }
validates :name, length: { maximum: 50 }
validates :repository_name, length: { maximum: 100 }
@ -15,6 +16,8 @@ class Projects::CreateForm < BaseForm
check_project_language(project_language_id)
check_project_name(user_id, name) unless name.blank?
check_repository_name(user_id, repository_name) unless repository_name.blank?
check_blockchain_token_all(blockchain_token_all) unless blockchain_token_all.blank?
check_blockchain_init_token(blockchain_init_token) unless blockchain_init_token.blank?
end
def check_license

View File

@ -3,7 +3,7 @@ class Projects::MigrateForm < BaseForm
:project_language_id, :clone_addr, :private, :is_mirror, :auth_username, :auth_password, :owner
validates :user_id, :name, :repository_name, :clone_addr, presence: true
validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" }
validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "长度为2~100 只能包含数字,字母,下划线(_),中划线(-),英文句号(.),必须以数字和字母开头,不能以下划线/中划线/英文句号开头和结尾" }
validates :clone_addr, format: { with: CustomRegexp::URL_REGEX, multiline: true, message: "地址格式不正确" }
validates :name, length: { maximum: 50 }
validates :repository_name, length: { maximum: 100 }

View File

@ -3,7 +3,7 @@ class Projects::UpdateForm < BaseForm
validates :name, presence: true
validates :name, length: { maximum: 50 }
validates :description, length: { maximum: 200 }
validates :identifier, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" }
validates :identifier, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: '长度为2~100 只能包含数字,字母,下划线(_),中划线(-),英文句号(.),必须以数字和字母开头,不能以下划线/中划线/英文句号开头和结尾' }
validate do
check_project_category(project_category_id)

View File

@ -0,0 +1,2 @@
module Admins::OrganizationsHelper
end

View File

@ -22,7 +22,7 @@ module ProjectsHelper
end
def render_download_file_url(owner, repository, filepath, ref)
[base_url, "/api/#{owner&.login}/#{repository.identifier}/raw?filepath=#{filepath}&ref=#{ref}"].join
[base_url, "/api/#{owner&.login}/#{repository.identifier}/raw/#{CGI.escape(filepath)}?ref=#{CGI.escape(ref)}"].join
end
def render_http_url(project)
@ -66,6 +66,7 @@ module ProjectsHelper
jianmu_devops: jianmu_devops_code(project, user),
jianmu_devops_url: jianmu_devops_url,
cloud_ide_saas_url: cloud_ide_saas_url(user),
open_blockchain: Site.has_blockchain? && project.use_blockchain,
ignore_id: project.ignore_id
}).compact
@ -138,6 +139,74 @@ module ProjectsHelper
"#{saas_url}/oauth/login?product_account_id=PA1001218&tenant_code=TI1001383&oauth_url=#{oauth_url}&token=#{token.value}"
end
def ai_shang_v1_url(project)
url = EduSetting.get("ai_shang_url") || "https://shang.gitlink.org.cn"
case project.identifier.to_s.downcase
when nil then ""
when 'rails' then "#{url}/v1/rails/entropy"
when 'jittor' then "#{url}/v1/jittor/entropy"
when 'paddle' then "#{url}/v1/Paddle/entropy"
when 'vue' then "#{url}/v1/vue/entropy"
when 'bootstrap' then "#{url}/v1/bootstrap/entropy"
when 'tensorflow' then "#{url}/v1/tensorflow/entropy"
when 'kernel' then "#{url}/v1/openeuler/entropy"
when 'opengauss-server' then "#{url}/v1/opengauss/entropy"
when 'mindspore' then "#{url}/v1/mindspore/entropy"
else ''
end
end
def ai_shang_v2_url(project)
url = EduSetting.get("ai_shang_url") || "https://shang.gitlink.org.cn"
case project.identifier.to_s.downcase
when nil then ""
when 'rails' then "#{url}/v2/getMediumData?repo_login=rails&repo_name=rails"
when 'jittor' then "#{url}/v2/getMediumData?repo_login=Jittor&repo_name=jittor"
when 'paddle' then "#{url}/v2/getMediumData?repo_login=PaddlePaddle&repo_name=Paddle"
when 'vue' then "#{url}/v2/getMediumData?repo_login=vuejs&repo_name=vue"
when 'bootstrap' then "#{url}/v2/getMediumData?repo_login=twbs&repo_name=bootstrap"
when 'tensorflow' then "#{url}/v2/getMediumData?repo_login=tensorflow&repo_name=tensorflow"
when 'kernel' then "#{url}/v2/getMediumData?repo_login=openeuler&repo_name=kernel"
when 'opengauss-server' then "#{url}/v2/getMediumData?repo_login=opengauss&repo_name=openGauss-server"
when 'mindspore' then "#{url}/v2/getMediumData?repo_login=mindspore&repo_name=mindspore"
else ''
end
end
def ai_shang_v4_url(project)
url = EduSetting.get("ai_shang_url") || "https://shang.gitlink.org.cn"
case project.identifier.to_s.downcase
when nil then ""
when 'rails' then "#{url}/v2/getIndexData?repo_login=rails&repo_name=rails"
when 'jittor' then "#{url}/v2/getIndexData?repo_login=Jittor&repo_name=jittor"
when 'paddle' then "#{url}/v2/getIndexData?repo_login=PaddlePaddle&repo_name=Paddle"
when 'vue' then "#{url}/v2/getIndexData?repo_login=vuejs&repo_name=vue"
when 'bootstrap' then "#{url}/v2/getIndexData?repo_login=twbs&repo_name=bootstrap"
when 'tensorflow' then "#{url}/v2/getIndexData?repo_login=tensorflow&repo_name=tensorflow"
when 'kernel' then "#{url}/v2/getIndexData?repo_login=openeuler&repo_name=kernel"
when 'opengauss-server' then "#{url}/v2/getIndexData?repo_login=opengauss&repo_name=openGauss-server"
when 'mindspore' then "#{url}/v2/getIndexData?repo_login=mindspore&repo_name=mindspore"
else ''
end
end
def ai_shang_v3_url(project)
url = EduSetting.get("ai_shang_v3_url") || "https://shang.gitlink.org.cn/v3"
case project.identifier.to_s.downcase
when nil then ""
when 'rails' then "#{url}/rails/entropy"
when 'jittor' then "#{url}/jittor/entropy"
when 'paddle' then "#{url}/paddle/entropy"
when 'vue' then "#{url}/vue/entropy"
when 'bootstrap' then "#{url}/bootstrap/entropy"
when 'tensorflow' then "#{url}/tensorflow/entropy"
when 'kernel' then "#{url}/openeuler/entropy"
when 'opengauss-server' then "#{url}/opengauss/entropy"
when 'mindspore' then "#{url}/mindspore/entropy"
else ''
end
end
def aes_encrypt(key, des_text)
# des_text='{"access_key_id":"STS.NTuC9RVmWfJqj3JkcMzPnDf7X","access_key_secret":"E8NxRZWGNxxMfwgt5nFLnBFgg6AzgXCZkSNCyqygLuHM","end_point":"oss-accelerate.aliyuncs.com","security_token":"CAIS8gF1q6Ft5B2yfSjIr5fACIPmu7J20YiaaBX7j2MYdt9Cq6Ocujz2IHhMenVhA+8Wv/02n2hR7PcYlq9IS55VWEqc/VXLaywQo22beIPkl5Gfz95t0e+IewW6Dxr8w7WhAYHQR8/cffGAck3NkjQJr5LxaTSlWS7OU/TL8+kFCO4aRQ6ldzFLKc5LLw950q8gOGDWKOymP2yB4AOSLjIx6lAt2T8vs/7hmZPFukSFtjCglL9J/baWC4O/csxhMK14V9qIx+FsfsLDqnUIs0YWpf0p3P0doGyf54vMWUM05A6dduPS7txkLAJwerjVl1/ADxc0/hqAASXhPeiktbmDjwvnSn4iKcSGQ+xoQB468eHXNdvf13dUlbbE1+JhRi0pZIB2UCtN9oTsLHcwIHt+EJaoMd3+hGwPVmvHSXzECDFHylZ8l/pzTwlE/aCtZyVmI5cZEvmWu2xBa3GRbULo7lLvyeX1cHTVmVWf4Nk6D09PzTU8qlAj","bucket":"edu-bigfiles1","region":"oss-cn-hangzhou","callback_url":"https://data.educoder.net/api/buckets/callback.json","bucket_host":"data.educoder.net"}'
# des = OpenSSL::Cipher::Cipher.new('aes-256-ctr')

View File

@ -88,7 +88,7 @@ module RepositoriesHelper
unless r_content.include?("http://") || r_content.include?("https://") || r_content.include?("mailto:")
# new_r_content = "#{path}" + new_r_content
new_r_content = [base_url, "/api/#{owner&.login}/#{repo.identifier}/raw?filepath=#{path_current}/#{path_last}&ref=#{ref}"].join
new_r_content = [base_url, "/api/#{owner&.login}/#{repo.identifier}/raw/#{path_current}/#{path_last}?ref=#{ref}"].join
end
content = content.gsub(/src=\"#{r_content}\"/, "src=\"#{new_r_content}\"").gsub(/src='#{r_content}'/, "src=\"#{new_r_content}\"")
rescue
@ -104,39 +104,71 @@ module RepositoriesHelper
end
# author hui.he
def new_readme_render_decode64_content(str, owner, repo, ref, readme_path, readme_name)
def new_readme_render_decode64_content(str, owner, repo, ref, readme_path, readme_name)
file_path = readme_path.include?('/') ? readme_path.gsub("/#{readme_name}", '') : readme_path.gsub("#{readme_name}", '')
return nil if str.blank?
content = Base64.decode64(str).force_encoding('UTF-8')
s_regex = /\[.*?\]\((.*?)\)/
# s_regex = /\s\!\[.*?\]\((.*?)\)\s/
s_regex_c = /`{1,2}[^`](.*?)`{1,2}/
s_regex = /```([\s\S]*?)```[\s]?/
s_regex_1 = /\[.*?\]\((.*?)\)/
src_regex = /src=\"(.*?)\"/
src_regex_1 = /src=\'(.*?)\'/
ss_c = content.to_s.scan(s_regex_c)
ss = content.to_s.scan(s_regex)
ss_1 = content.to_s.scan(s_regex_1)
ss_src = content.to_s.scan(src_regex)
total_sources = ss + ss_src
total_sources.uniq!
total_sources.each do |s|
begin
s_content = s[0]
# 链接直接跳过不做替换
next if s_content.starts_with?('http://') || s_content.starts_with?('https://') || s_content.starts_with?('mailto:') || s_content.blank?
ext = File.extname(s_content)[1..-1]
if (image_type?(ext) || download_type(ext)) && !ext.blank?
s_content = File.expand_path(s_content, file_path)
s_content = s_content.split("#{Rails.root}/")[1]
# content = content.gsub(s[0], "/#{s_content}")
s_content = [base_url, "/api/#{owner&.login}/#{repo.identifier}/raw?filepath=#{s_content}&ref=#{ref}"].join
content = content.gsub(s[0], s_content)
else
path = [owner&.login, repo&.identifier, 'tree', ref, file_path].join("/")
s_content = File.expand_path(s_content, path)
s_content = s_content.split("#{Rails.root}/")[1]
content = content.gsub('('+s[0]+')', '('+"/#{s_content}"+')')
ss_src_1 = content.to_s.scan(src_regex_1)
total_sources = {ss_c: ss_c,ss: ss, ss_1: ss_1, ss_src: ss_src, ss_src_1: ss_src_1}
# total_sources.uniq!
total_sources.except(:ss, :ss_c).each do |k, sources|
sources.each do |s|
begin
s_content = s[0]
# 链接直接跳过不做替换
next if s_content.starts_with?('http://') || s_content.starts_with?('https://') || s_content.starts_with?('mailto:') || s_content.blank?
ext = File.extname(s_content)[1..-1]
if (image_type?(ext) || download_type(ext)) && !ext.blank?
s_content = File.expand_path(s_content, file_path)
s_content = s_content.split("#{Rails.root}/")[1]
# content = content.gsub(s[0], "/#{s_content}")
s_content = [base_url, "/api/#{owner&.login}/#{repo.identifier}/raw/#{s_content}?ref=#{ref}"].join
case k.to_s
when 'ss_src'
content = content.gsub("src=\"#{s[0]}\"", "src=\"#{s_content}\"")
when 'ss_src_1'
content = content.gsub("src=\'#{s[0]}\'", "src=\'#{s_content}\'")
else
content = content.gsub("(#{s[0]})", "(#{s_content})")
end
else
path = [owner&.login, repo&.identifier, 'tree', ref, file_path].join("/")
s_content = File.expand_path(s_content, path)
s_content = s_content.split("#{Rails.root}/")[1]
case k.to_s
when 'ss_src'
content = content.gsub("src=\"#{s[0]}\"", "src=\"/#{s_content}\"")
when 'ss_src_1'
content = content.gsub("src=\'#{s[0]}\'", "src=\'/#{s_content}\'")
else
content = content.gsub("(#{s[0]})", "(/#{s_content})")
end
end
rescue
next
end
rescue
next
end
end
after_ss_souces = content.to_s.scan(s_regex)
after_ss_souces.each_with_index do |s, index|
content = content.gsub("#{s[0]}","#{total_sources[:ss][index][0]}")
end
after_ss_c_souces = content.to_s.scan(s_regex_c)
after_ss_c_souces.each_with_index do |s, index|
content = content.gsub("#{s[0]}","#{total_sources[:ss_c][index][0]}")
end
return content
rescue
return str

View File

@ -21,7 +21,8 @@ module TagChosenHelper
"issue_tag": render_issue_tags(project),
"issue_type": render_issue_species,
"all_issues": all_issues,
"branches": render_branches(project)
"branches": render_branches(project),
"use_blockchain": project['use_blockchain']
}
end

View File

@ -25,7 +25,7 @@ module Gitea
def run
Contents::CreateForm.new(valid_params).validate!
result = Gitea::Repository::Entries::CreateService.call(token,
owner, @params[:identifier], @params[:filepath], file_params)
owner, @params[:identifier], file_path, file_params)
if result[:status] == :success
@result = result[:body]
@ -50,9 +50,17 @@ module Gitea
@result = response
end
def file_path
if @params[:base64_filepath].present?
Base64.decode64(params[:base64_filepath])
else
@params[:filepath]
end
end
def valid_params
{
filepath: @params[:filepath],
filepath: file_path,
branch: @params[:branch],
new_branch: @params[:new_branch]
}

View File

@ -24,7 +24,7 @@ module Gitea
def run
Contents::DeleteForm.new(valid_params).validate!
response = Gitea::Repository::Entries::DeleteService.new(token, owner, @params[:identifier], @params[:filepath], file_params).call
response = Gitea::Repository::Entries::DeleteService.new(token, owner, @params[:identifier], file_path, file_params).call
render_result(response)
rescue Exception => exception
fail!(exception.message)
@ -45,9 +45,17 @@ module Gitea
end
end
def file_path
if @params[:base64_filepath].present?
Base64.decode64(params[:base64_filepath])
else
@params[:filepath]
end
end
def valid_params
{
filepath: @params[:filepath],
filepath: file_path,
sha: @params[:sha]
}
end

View File

@ -24,7 +24,7 @@ module Gitea
def run
Contents::UpdateForm.new(valid_params).validate!
response = Gitea::Repository::Entries::UpdateService.new(token, owner, @params[:identifier], @params[:filepath], file_params).call
response = Gitea::Repository::Entries::UpdateService.new(token, owner, @params[:identifier], file_path, file_params).call
render_result(response)
rescue Exception => exception
fail!(exception.message)
@ -45,9 +45,25 @@ module Gitea
end
end
def file_path
if @params[:base64_filepath].present?
Base64.decode64(params[:base64_filepath])
else
@params[:filepath]
end
end
def from_file_path
if @params[:base64_from_path].present?
Base64.decode64(params[:base64_from_path])
else
@params[:from_path]
end
end
def valid_params
{
filepath: @params[:filepath],
filepath: file_path,
branch: @params[:branch],
new_branch: @params[:new_branch],
sha: @params[:sha]
@ -59,7 +75,7 @@ module Gitea
branch: @params[:branch],
sha: @params[:sha],
new_branch: @params[:new_branch],
from_path: @params[:from_path],
from_path: from_file_path,
message: @params[:message],
content: Base64.encode64(@params[:content])
).compact

View File

@ -5,6 +5,7 @@ class OpenProjectDevOpsJob < ApplicationJob
def perform(project_id, user_id)
project = Project.find_by(id: project_id)
return if project.blank?
user = User.find_by(id: user_id)
code = jianmu_devops_code(project, user)
uri = URI.parse("#{jianmu_devops_url}/activate?code=#{URI.encode_www_form_component(code)}")

View File

@ -34,8 +34,8 @@ class SendTemplateMessageJob < ApplicationJob
operator_id, issue_id = args[0], args[1]
operator = User.find_by_id(operator_id)
issue = Issue.find_by_id(issue_id)
return unless operator.present? && issue.present?
receivers = User.where(id: issue&.assigned_to_id).where.not(id: operator&.id)
return unless operator.present? && issue.present?
receivers = issue&.assigners.where.not(id: operator&.id)
receivers_string, content, notification_url = MessageTemplate::IssueAssigned.get_message_content(receivers, operator, issue)
Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id})
receivers.find_each do |receiver|
@ -56,18 +56,26 @@ class SendTemplateMessageJob < ApplicationJob
operator = User.find_by_id(operator_id)
issue = Issue.find_by_id(issue_id)
return unless operator.present? && issue.present?
receivers = User.where(id: [issue&.assigned_to_id, issue&.author_id]).where.not(id: operator&.id)
receivers = User.where(id: (issue.assigners.pluck(:id).append(issue&.author_id) + issue.claim_users.pluck(:id)).uniq).where.not(id: operator&.id)
receivers_string, content, notification_url = MessageTemplate::IssueChanged.get_message_content(receivers, operator, issue, change_params.symbolize_keys)
Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id, change_params: change_params.symbolize_keys})
receivers.find_each do |receiver|
receivers_email_string, email_title, email_content = MessageTemplate::IssueChanged.get_email_message_content(receiver, operator, issue, change_params)
Notice::Write::EmailCreateService.call(receivers_email_string, email_title, email_content)
end
when 'IssueClaim'
operator_id, issue_id = args[0], args[1]
operator = User.find_by_id(operator_id)
issue = Issue.find_by_id(issue_id)
return unless operator.present? && issue.present?
receivers = User.where(id: issue.claim_users.pluck(:id).append(issue.author_id)).where.not(id: operator&.id)
receivers_string, content, notification_url = MessageTemplate::IssueClaim.get_message_content(receivers, operator, issue)
Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_id: issue.id})
when 'IssueExpire'
issue_id = args[0]
issue = Issue.find_by_id(issue_id)
return unless issue.present?
receivers = User.where(id: [issue&.assigned_to_id, issue&.author_id])
receivers = User.where(id: issue.assigners.pluck(:id).append(issue&.author_id))
receivers_string, content, notification_url = MessageTemplate::IssueExpire.get_message_content(receivers, issue)
Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {issue_id: issue.id})
receivers.find_each do |receiver|
@ -78,7 +86,11 @@ class SendTemplateMessageJob < ApplicationJob
operator_id, issue_title, issue_assigned_to_id, issue_author_id = args[0], args[1], args[2], args[3]
operator = User.find_by_id(operator_id)
return unless operator.present?
receivers = User.where(id: [issue_assigned_to_id, issue_author_id]).where.not(id: operator&.id)
if issue_assigned_to_id.is_a?(Array)
receivers = User.where(id: issue_assigned_to_id.append(issue_author_id)).where.not(id: operator&.id)
else
receivers = User.where(id: [issue_assigned_to_id, issue_author_id]).where.not(id: operator&.id)
end
receivers_string, content, notification_url = MessageTemplate::IssueDeleted.get_message_content(receivers, operator, issue_title)
Notice::Write::CreateService.call(receivers_string, content, notification_url, source, {operator_id: operator.id, issue_title: issue_title})
receivers.find_each do |receiver|

View File

@ -0,0 +1,79 @@
class TouchWebhookJob < ApplicationJob
queue_as :webhook
def perform(source, *args)
case source
when 'IssueCreate'
issue_id, sender_id = args[0], args[1]
issue = Issue.find_by_id issue_id
sender = User.find_by_id sender_id
return if issue.nil? || sender.nil?
issue.project.webhooks.each do |webhook|
next unless webhook.events["events"]["issues"]
_, _, @webhook_task = Webhook::IssueClient.new(webhook, issue, sender,"issues").do_request
Rails.logger.info "Touch Webhook Response result: #{@webhook_task.response_content}"
end
when 'IssueUpdate'
issue_id, sender_id, changes = args[0], args[1], args[2]
issue = Issue.find_by_id issue_id
sender = User.find_by_id sender_id
return if issue.nil? || sender.nil? || !changes.is_a?(Hash) || changes.blank?
issue.project.webhooks.each do |webhook|
next unless webhook.events["events"]["issues"]
_, _, @webhook_task = Webhook::IssueClient.new(webhook, issue, sender, "issues", changes.stringify_keys).do_request
Rails.logger.info "Touch Webhook Response result: #{@webhook_task.response_content}"
end
when 'IssueAssign'
issue_id, sender_id, changes = args[0], args[1], args[2]
issue = Issue.find_by_id issue_id
sender = User.find_by_id sender_id
return if issue.nil? || sender.nil?
issue.project.webhooks.each do |webhook|
next unless webhook.events["events"]["issue_assign"]
_, _, @webhook_task = Webhook::IssueClient.new(webhook, issue, sender, "issue_assign", changes.stringify_keys).do_request
Rails.logger.info "Touch Webhook Response result: #{@webhook_task.response_content}"
end
when 'IssueLabel'
issue_id, sender_id, changes = args[0], args[1], args[2]
issue = Issue.find_by_id issue_id
sender = User.find_by_id sender_id
return if issue.nil? || sender.nil?
issue.project.webhooks.each do |webhook|
next unless webhook.events["events"]["issue_label"]
_, _, @webhook_task = Webhook::IssueClient.new(webhook, issue, sender, "issue_label", changes.stringify_keys).do_request
Rails.logger.info "Touch Webhook Response result: #{@webhook_task.response_content}"
end
when 'IssueComment'
issue_id, sender_id, comment_id, action_type, comment_json = args[0], args[1], args[2], args[3], args[4]
issue = Issue.find_by_id issue_id
comment = issue.comment_journals.find_by_id comment_id
sender = User.find_by_id sender_id
return if issue.nil? || sender.nil?
return if action_type == 'edited' && comment_json.blank?
issue.project.webhooks.each do |webhook|
next unless webhook.events["events"]["issue_comment"]
_, _, @webhook_task = Webhook::IssueCommentClient.new(webhook, issue, comment, sender, "issue_comment", action_type, comment_json).do_request
Rails.logger.info "Touch Webhook Response result: #{@webhook_task.response_content}"
end
when 'PullRequestComment'
issue_id, sender_id, comment_id, action_type, comment_json = args[0], args[1], args[2], args[3], args[4]
issue = Issue.find_by_id(issue_id)
comment = issue.comment_journals.find_by_id comment_id
sender = User.find_by_id sender_id
pull = issue.try(:pull_request)
return if pull.nil? || sender.nil?
return if action_type == 'edited' && comment_json.blank?
pull.project.webhooks.each do |webhook|
next unless webhook.events["events"]["pull_request_comment"]
_, _, @webhook_task = Webhook::PullCommentClient.new(webhook, pull, comment, sender, "pull_request_comment", action_type, comment_json).do_request
Rails.logger.info "Touch Webhook Response result: #{@webhook_task.response_content}"
end
end
end
end

20
app/libs/blockchain.rb Normal file
View File

@ -0,0 +1,20 @@
class Blockchain
class << self
def blockchain_config
blockchain_config = {}
begin
config = Rails.application.config_for(:configuration).symbolize_keys!
blockchain_config = config[:blockchain].symbolize_keys!
raise 'blockchain config missing' if blockchain_config.blank?
rescue => ex
raise ex if Rails.env.production?
puts %Q{\033[33m [warning] blockchain config or configuration.yml missing,
please add it or execute 'cp config/configuration.yml.example config/configuration.yml' \033[0m}
blockchain_config = {}
end
blockchain_config
end
end
end

View File

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

View File

@ -1,42 +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 :string(255)
# 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")
# link :string(255)
# clone_id :integer
#
# Indexes
#
# index_attachments_on_author_id (author_id)
# index_attachments_on_clone_id (clone_id)
# index_attachments_on_container_id_and_container_type (container_id,container_type)
# index_attachments_on_created_on (created_on)
#
# == 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 :string(255)
# 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")
# link :string(255)
# clone_id :integer
#
# Indexes
#
# index_attachments_on_author_id (author_id)
# index_attachments_on_clone_id (clone_id)
# index_attachments_on_container_id_and_container_type (container_id,container_type)
# index_attachments_on_created_on (created_on)
#
class Attachment < ApplicationRecord
@ -184,4 +184,14 @@ class Attachment < ApplicationRecord
is_pdf
end
def to_builder
Jbuilder.new do |attachment|
attachment.id self.id
attachment.title self.title
attachment.filesize self.filesize
attachment.is_pdf self.is_pdf?
attachment.created_on self.created_on.strftime("%Y-%m-%d %H:%M")
attachment.content_type self.content_type
end
end
end

View File

@ -36,7 +36,7 @@ class Bot < ApplicationRecord
def self.decode_jwt_token(token)
decoded_token = JWT.decode token, nil, false
return [nil, "Token已过期"] if Time.now.to_i - 60 - decoded_token[0]["exp"].to_i > 0
return [nil, "Token已过期"] if Time.now.to_i - 10*60 - decoded_token[0]["exp"].to_i > 0
bot = Bot.find_by(id: decoded_token[0]["iss"])
return [nil, "Token不存在"] if bot.blank?
rsa_private = OpenSSL::PKey::RSA.new(bot.private_key)

View File

@ -17,5 +17,6 @@
class Claim < ApplicationRecord
belongs_to :user, foreign_key: :user_id
belongs_to :issue
scope :claim_includes, ->{includes(:user)}
end

View File

@ -3,4 +3,10 @@ class CommitLog < ApplicationRecord
belongs_to :project
belongs_to :repository
has_many :project_trends, as: :trend, dependent: :destroy
def title
self.message
end
end

View File

@ -6,6 +6,7 @@ module Matchable
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? }
scope :with_project_topic, ->(topic_id) {joins(:project_topics).where(project_topics: {id: topic_id}) unless topic_id.blank?}
end
end

View File

@ -93,9 +93,14 @@ module ProjectOperable
team_user.destroy! if team_user
end
# 安装bot后的权限
def is_install_bot?(user)
user.platform == "bot" && BotInstall.joins(:bot).where(bot: { uid: user.id }).where(store_id: self.id).exists?
end
def member?(user_id)
if owner.is_a?(User)
members.exists?(user_id: user_id)
members.exists?(user_id: user_id) || is_install_bot?(User.find_by(id: user_id))
elsif owner.is_a?(Organization)
members.exists?(user_id: user_id) || team_projects.joins(team: :team_users).where(team_users: {user_id: user_id}).present?
else
@ -190,22 +195,24 @@ module ProjectOperable
end
# 项目管理员(包含项目拥有者),权限:仓库设置、仓库可读可写
# 增加bot用户权限已安装bot当前bot用户即拥有权限权限粒度待完善
def manager?(user)
if owner.is_a?(User)
managers.exists?(user_id: user.id)
managers.exists?(user_id: user.id) || (user.platform == "bot" && BotInstall.joins(:bot).where(bot: { uid: user.id }).where(store_id: self.id).exists?)
elsif owner.is_a?(Organization)
managers.exists?(user_id: user.id) || owner.is_owner?(user.id) || owner.is_only_admin?(user.id)
managers.exists?(user_id: user.id) || owner.is_owner?(user.id) || (owner.is_only_admin?(user.id) && (teams.pluck(:id) & user.teams.pluck(:id)).size > 0) || (user.platform == "bot" && BotInstall.joins(:bot).where(bot: { uid: user.id }).where(store_id: self.id).exists?)
else
false
end
end
# 项目开发者,可读可写权限
# 增加bot用户权限已安装当前bot用户对应的bot即拥有权限权限粒度待完善
def develper?(user)
if owner.is_a?(User)
developers.exists?(user_id: user.id)
developers.exists?(user_id: user.id) || (user.platform == "bot" && BotInstall.joins(:bot).where(bot: { uid: user.id }).where(store_id: self.id).exists?)
elsif owner.is_a?(Organization)
developers.exists?(user_id: user.id) || owner.is_only_write?(user.id)
developers.exists?(user_id: user.id) || (owner.is_only_write?(user.id) && (teams.pluck(:id) & user.teams.pluck(:id)).size > 0) || (user.platform == "bot" && BotInstall.joins(:bot).where(bot: { uid: user.id }).where(store_id: self.id).exists?)
else
false
end

View File

@ -1,45 +1,178 @@
module Watchable
extend ActiveSupport::Concern
included do
has_many :watchers, as: :watchable, dependent: :destroy
has_many :watcher_users, through: :watchers, source: :user, validate: false
scope :watched_by, -> (user_id) { includes(:watchers).where(watchers: { user_id: user_id }) }
scope :following, -> (user_id) { watched_by(user_id) }
end
def watched?(watchable)
watchable.watchers.exists?(user: self)
end
def watch!(watchable)
watchable.watchers.create!(user: self, created_at: Time.current)
end
def unwatch!(watchable)
obj = watchable.watchers.find_by(user: self)
obj.destroy! if obj.present?
end
# 我正在关注的、我追随的
def following
User.following(self.id)
end
def following_count
following.size
end
# 关注我的、我的粉丝、我的追随者
def followers
watcher_users
end
def followers_count
followers.size
end
module ClassMethods
end
end
module Watchable
extend ActiveSupport::Concern
included do
has_many :watchers, as: :watchable, dependent: :destroy
has_many :watcher_users, through: :watchers, source: :user, validate: false
scope :watched_by, -> (user_id) { includes(:watchers).where(watchers: { user_id: user_id }) }
scope :following, -> (user_id) { watched_by(user_id) }
end
def watched?(watchable)
watchable.watchers.exists?(user: self)
end
def watch!(watchable)
watchable.watchers.create!(user: self, created_at: Time.current)
end
def unwatch!(watchable)
obj = watchable.watchers.find_by(user: self)
obj.destroy! if obj.present?
end
# 我正在关注的、我追随的
def following
User.following(self.id)
end
def following_count
following.size
end
def simple_contribution_perc(project, perc=nil)
@project = project
@user = self
def cal_perc(count_user, count_all)
(count_user * 1.0 / (count_all + 0.000000001)).round(5)
end
if Site.has_blockchain? && (@project['use_blockchain'] == true or @project['use_blockchain'] == 1) && @user.id.present?
balance_user = Blockchain::BalanceQueryOneProject.call({"user_id": @user.id, "project_id": @project.id})
balance_all = Blockchain::RepoBasicInfo.call({"project_id": @project.id})["cur_supply"]
score = cal_perc(balance_user, balance_all)
score = (score * 100).round(1).to_s + "%"
else
score = perc
end
score
end
def contribution_perc(project)
@project = project
@user = self
def cal_perc(count_user, count_all)
(count_user * 1.0 / (count_all + 0.000000001)).round(5)
end
if @project['use_blockchain'] == true or @project['use_blockchain'] == 1
balance_user = Blockchain::BalanceQueryOneProject.call({"user_id": @user.id, "project_id": @project.id})
balance_all = Blockchain::RepoBasicInfo.call({"project_id": @project.id})["cur_supply"]
score = cal_perc(balance_user, balance_all)
else
# 获取所有行为对应的项目内记录总数和个人记录数
features = {
"requirement" => {},
"development" => {},
"review" => {}
}
# 1. issue创建
issues = Issue.where(project_id: @project.id, issue_classify: 'issue')
issue_all = issues.count
issue_user = issues.where(author_id: @user.id).count
features["requirement"] = features["requirement"].merge({"issue" => {"all" => issue_all, "perc" => cal_perc(issue_user, issue_all)}})
# 2. 里程碑创建
milestones = Version.where(project_id: @project.id)
milestone_all = milestones.count
milestone_user = milestones.where(user_id: @user.id).count
features["requirement"] = features["requirement"].merge({"milestone" => {"all" => milestone_all, "perc" => cal_perc(milestone_user, milestone_all)}})
# 3. issue评论
issue_comments = Journal.joins("INNER JOIN issues on journals.journalized_id=issues.id").where("issues.project_id=#{@project.id} and journalized_type='Issue' and issues.issue_classify='issue'")
issue_comment_all = issue_comments.count
issue_comment_user = issue_comments.where("journals.user_id=#{@user.id}").count
features["requirement"] = features["requirement"].merge({"issue_comment" => {"all" => issue_comment_all, "perc" => cal_perc(issue_comment_user, issue_comment_all)}})
# 4. 合并请求
prs = PullRequest.where(project_id: @project.id)
pr_all = prs.count
pr_user = prs.where(user_id: @user.id).count
features["development"] = features["development"].merge({"pr" => {"all" => pr_all, "perc" => cal_perc(pr_user, pr_all)}})
# 5. pr评论
pr_comments = Journal.joins("INNER JOIN issues on journals.journalized_id=issues.id").where("issues.project_id=#{@project.id} and journalized_type='Issue' and issues.issue_classify='pull_request'")
pr_comment_all = pr_comments.count
pr_comment_user = pr_comments.where("journals.user_id=#{@user.id}").count
features["review"] = features["review"].merge({"pr_comment" => {"all" => pr_comment_all, "perc" => cal_perc(pr_comment_user, pr_comment_all)}})
# 6. 代码行评论
line_comments = Journal.joins("INNER JOIN pull_requests on journals.journalized_id=pull_requests.id").where("pull_requests.project_id=#{@project.id} and journalized_type='PullRequest'")
line_comment_all = line_comments.count
line_comment_user = line_comments.where("journals.user_id=#{@user.id}").count
features["review"] = features["review"].merge({"line_comment" => {"all" => line_comment_all, "perc" => cal_perc(line_comment_user, line_comment_all)}})
# 7. 代码行、commit贡献统计
code_contributions = Api::V1::Projects::CodeStats::ListService.call(@project, {ref: nil})
commit_all = code_contributions["commit_count"]
addition_all = code_contributions["additions"]
deletion_all = code_contributions["deletions"]
commit_user = 0
addition_user = 0
deletion_user = 0
code_contributions["authors"].each do |author|
if author["name"] == @user.login
commit_user = author["commits"]
addition_user = author["additions"]
deletion_user = author["deletions"]
end
end
features["development"] = features["development"].merge({"commit" => {"all" => commit_all, "perc" => cal_perc(commit_user, commit_all)}})
features["development"] = features["development"].merge({"addition" => {"all" => addition_all, "perc" => cal_perc(addition_user, addition_all)}})
features["development"] = features["development"].merge({"deletion" => {"all" => deletion_all, "perc" => cal_perc(deletion_user, deletion_all)}})
def cal_weight(features)
weights = {} # 计算每一项的权重
categories = []
features.each do |key, _|
categories << key
weights[key] = Hash.new
end
count_all = 0
counts = {}
categories.each do |category|
count_1 = 0
features[category].each do |_, value|
count_1 += value["all"]
end
count_all += count_1
counts[category] = count_1
features[category].each do |key, value|
weight = cal_perc(value["all"], count_1)
weights[category] = weights[category].merge({key => weight})
end
end
categories.each do |category|
weight = cal_perc(counts[category], count_all)
weights[category] = weights[category].merge({"category_weight" => weight})
end
return weights
end
weights_categories = cal_weight(features)
score = 0.0
features.each do |category, value_1|
category_score = 0.0
value_1.each do |action, value_2|
category_score += weights_categories[category][action] * value_2["perc"]
end
score += weights_categories[category]["category_weight"] * category_score.round(4)
end
end
score
(score * 100).round(1).to_s + "%"
end
# 关注我的、我的粉丝、我的追随者
def followers
watcher_users
end
def followers_count
followers.size
end
module ClassMethods
end
end

View File

@ -25,10 +25,12 @@ class ForkUser < ApplicationRecord
def incre_project_common
CacheAsyncSetJob.perform_later("project_common_service", {forks: 1}, self.project_id)
self.project.update_column(:updated_on, Time.now)
end
def decre_project_common
CacheAsyncSetJob.perform_later("project_common_service", {forks: -1}, self.project_id)
self.project.update_column(:updated_on, Time.now)
end
def incre_user_statistic

View File

@ -1,6 +1,7 @@
class Gitea::WebhookTask < Gitea::Base
serialize :payload_content, JSON
serialize :request_content, JSON
serialize :response_content, JSON
self.inheritance_column = nil
@ -10,9 +11,4 @@ class Gitea::WebhookTask < Gitea::Base
enum type: {gogs: 1, slack: 2, gitea: 3, discord: 4, dingtalk: 5, telegram: 6, msteams: 7, feishu: 8, matrix: 9}
def response_content_json
JSON.parse(response_content)
rescue
{}
end
end

View File

@ -0,0 +1,6 @@
# for oauth2 application
class ImportRepo < ApplicationRecord
self.table_name = "open_shixuns"
end

View File

@ -65,16 +65,31 @@ class Issue < ApplicationRecord
has_many :journals, :as => :journalized, :dependent => :destroy
has_many :journal_details, through: :journals
has_many :claims, :dependent => :destroy
has_many :claim_users, through: :claims, source: :user
has_many :issue_tags_relates, dependent: :destroy
has_many :issue_tags, through: :issue_tags_relates
has_many :issue_times, dependent: :destroy
has_many :issue_depends, dependent: :destroy
has_many :issue_assigners, dependent: :destroy
has_many :assigners, through: :issue_assigners
has_many :issue_participants, dependent: :destroy
has_many :participants, through: :issue_participants
has_many :show_participants, -> {joins(:issue_participants).where.not(issue_participants: {participant_type: "atme"}).distinct}, through: :issue_participants, source: :participant
has_many :show_assigners, -> {joins(:issue_assigners).distinct}, through: :issue_assigners, source: :assigner
has_many :show_issue_tags, -> {joins(:issue_tags_relates).distinct}, through: :issue_tags_relates, source: :issue_tag
has_many :comment_journals, -> {where.not(notes: nil)}, class_name: "Journal", :as => :journalized
has_many :operate_journals, -> {where(notes: nil)}, class_name: "Journal", :as => :journalized
has_many :pull_attached_issues, dependent: :destroy
has_many :attach_pull_requests, through: :pull_attached_issues, source: :pull_request
scope :issue_includes, ->{includes(:user)}
scope :issue_many_includes, ->{includes(journals: :user)}
scope :issue_issue, ->{where(issue_classify: [nil,"issue"])}
scope :issue_pull_request, ->{where(issue_classify: "pull_request")}
scope :issue_index_includes, ->{includes(:tracker, :priority, :version, :issue_status, :journals,:issue_tags,user: :user_extension)}
scope :closed, ->{where(status_id: 5)}
scope :opened, ->{where.not(status_id: 5)}
after_create :incre_project_common, :incre_user_statistic, :incre_platform_statistic
after_save :change_versions_count, :send_update_message_to_notice_system
after_destroy :update_closed_issues_count_in_project!, :decre_project_common, :decre_user_statistic, :decre_platform_statistic
@ -204,4 +219,30 @@ class Issue < ApplicationRecord
SendTemplateMessageJob.perform_later('IssueExpire', self.id) if Site.has_notice_menu? && self.due_date == Date.today + 1.days
end
def to_builder
Jbuilder.new do |issue|
issue.(self, :id, :project_issues_index, :subject, :description, :branch_name, :start_date, :due_date)
issue.created_at self.created_on.strftime("%Y-%m-%d %H:%M")
issue.updated_at self.updated_on.strftime("%Y-%m-%d %H:%M")
issue.tags self.show_issue_tags.map{|t| JSON.parse(t.to_builder.target!)}
issue.status self.issue_status.to_builder
if self.priority.present?
issue.priority self.priority.to_builder
else
issue.priority nil
end
if self.version.present?
issue.milestone self.version.to_builder
else
issue.milestone nil
end
issue.author self.user.to_builder
issue.assigners self.show_assigners.map{|t| JSON.parse(t.to_builder.target!)}
issue.participants self.participants.distinct.map{|t| JSON.parse(t.to_builder.target!)}
issue.comment_journals_count self.comment_journals.size
issue.operate_journals_count self.operate_journals.size
issue.attachments self.attachments.map{|t| JSON.parse(t.to_builder.target!)}
end
end
end

View File

@ -0,0 +1,20 @@
# == Schema Information
#
# Table name: issue_assigners
#
# id :integer not null, primary key
# issue_id :integer
# assigner_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_issue_assigners_on_assigner_id (assigner_id)
# index_issue_assigners_on_issue_id (issue_id)
#
class IssueAssigner < ApplicationRecord
belongs_to :issue
belongs_to :assigner, class_name: "User"
end

View File

@ -0,0 +1,9 @@
class IssueParticipant < ApplicationRecord
belongs_to :issue
belongs_to :participant, class_name: "User"
enum participant_type: {"authored": 0, "assigned": 1, "commented": 2, "edited": 3, "atme": 4}
end

View File

@ -15,4 +15,27 @@
class IssuePriority < ApplicationRecord
has_many :issues
def self.init_data
map = {
"1" => "",
"2" => "正常",
"3" => "",
"4" => "紧急"
}
IssuePriority.order(id: :asc).each do |prty|
if map["#{prty.id}"] == prty.name
IssuePriority.find_or_create_by(id: prty.id, name: prty.name)
else
Issue.where(priority_id: prty.id).each{|i| i.update_column(:priority_id, 2)}
prty.destroy!
end
end
end
def to_builder
Jbuilder.new do |priority|
priority.(self, :id, :name)
end
end
end

View File

@ -20,10 +20,34 @@ class IssueStatus < ApplicationRecord
ADD = 1
SOLVING = 2
SOLVED = 3
FEEDBACK = 4
# FEEDBACK = 4
CLOSED = 5
REJECTED = 6
has_many :issues
belongs_to :project, optional: true
def self.init_data
map = {
"1" => "新增",
"2" => "正在解决",
"3" => "已解决",
"5" => "关闭",
"6" => "拒绝"
}
IssueStatus.order(id: :asc).each do |stat|
if map["#{stat.id}"] == stat.name
IssueStatus.find_or_create_by(id: stat.id, name: stat.name)
else
Issue.where(status_id: stat.id).each{|i| i.update_column(:status_id, 1)}
stat.destroy!
end
end
end
def to_builder
Jbuilder.new do |status|
status.(self, :id, :name)
end
end
end

View File

@ -23,6 +23,43 @@ class IssueTag < ApplicationRecord
has_many :issue_tags_relates, dependent: :destroy
has_many :issues, through: :issue_tags_relates
has_many :issue_issues, -> {where(issue_classify: [nil,"issue"])}, source: :issue, through: :issue_tags_relates
has_many :pull_request_issues, -> {where(issue_classify: "pull_request")}, source: :issue, through: :issue_tags_relates
belongs_to :project, optional: true, counter_cache: true
belongs_to :user, optional: true
validates :name, uniqueness: {scope: :project_id, message: "已存在" }
def self.init_data(project_id)
data = [
["缺陷", "表示存在意外问题或错误", "#d92d4c"],
["功能", "表示新功能申请", "#ee955a"],
["疑问", "表示存在疑惑", "#2d6ddc"],
["支持", "表示特定功能或特定需求", "#019549"],
["任务", "表示需要分配的任务", "#c1a30d"],
["协助", "表示需要社区用户协助", "#2a0dc1"],
["搁置", "表示此问题暂时不会继续处理", "#892794"],
["文档", "表示文档材料补充", "#9ed600"],
["测试", "表示需要测试的需求", "#2897b9"],
["重复", "表示已存在类似的疑修", "#bb5332"]
]
data.each do |item|
next if IssueTag.exists?(project_id: project_id, name: item[0])
IssueTag.create!(project_id: project_id, name: item[0], description: item[1], color: item[2])
end
$redis_cache.hset("project_init_issue_tags", project_id, 1)
end
def reset_counter_field
self.update_column(:issues_count, issue_issues.size)
self.update_column(:pull_requests_count, pull_request_issues.size)
end
def to_builder
Jbuilder.new do |tag|
tag.(self, :id, :name, :description)
end
end
end

View File

@ -15,5 +15,29 @@
class IssueTagsRelate < ApplicationRecord
belongs_to :issue
belongs_to :issue_tag, counter_cache: :issues_count
belongs_to :issue_tag
after_create :increment_issue_tags_counter_cache
after_destroy :decrement_issue_tags_counter_cache
def increment_issue_tags_counter_cache
Rails.logger.info "11111"
Rails.logger.info self.issue.issue_classify
if self.issue.issue_classify == "issue"
IssueTag.increment_counter :issues_count, issue_tag_id
else
IssueTag.increment_counter :pull_requests_count, issue_tag_id
end
end
def decrement_issue_tags_counter_cache
Rails.logger.info "2222222"
Rails.logger.info self.issue.issue_classify
if self.issue.issue_classify == "issue"
IssueTag.decrement_counter :issues_count, issue_tag_id
else
IssueTag.decrement_counter :pull_requests_count, issue_tag_id
end
end
end

View File

@ -40,9 +40,12 @@ class Journal < ApplicationRecord
belongs_to :journalized, polymorphic: true
belongs_to :review, optional: true
belongs_to :resolveer, class_name: 'User', foreign_key: :resolveer_id, optional: true
belongs_to :parent_journal, class_name: 'Journal', foreign_key: :parent_id, optional: true, counter_cache: :comments_count
belongs_to :reply_journal, class_name: 'Journal', foreign_key: :reply_id, optional: true
has_many :journal_details, :dependent => :delete_all
has_many :attachments, as: :container, dependent: :destroy
has_many :children_journals, class_name: 'Journal', foreign_key: :parent_id
has_many :first_ten_children_journals, -> { order(created_on: :asc).limit(10)}, class_name: 'Journal', foreign_key: :parent_id
has_many :children_journals, class_name: 'Journal', foreign_key: :parent_id, dependent: :destroy
scope :journal_includes, ->{includes(:user, :journal_details, :attachments)}
scope :parent_journals, ->{where(parent_id: nil)}
@ -54,6 +57,85 @@ class Journal < ApplicationRecord
self.notes.blank? && self.journal_details.present?
end
def operate_content
content = ""
detail = self.journal_details.take
case detail.property
when 'issue'
return "创建了<b>疑修</b>"
when 'attachment'
old_value = Attachment.where(id: detail.old_value.split(",")).pluck(:filename).join("")
new_value = Attachment.where(id: detail.value.split(",")).pluck(:filename).join("")
if old_value.nil? || old_value.blank?
content += "添加了<b>#{new_value}</b>附件"
else
new_value = "" if new_value.blank?
content += "将附件由<b>#{old_value}</b>更改为<b>#{new_value}</b>"
end
when 'issue_tag'
old_value = IssueTag.where(id: detail.old_value.split(",")).pluck(:name).join("")
new_value = IssueTag.where(id: detail.value.split(",")).pluck(:name).join("")
if old_value.nil? || old_value.blank?
content += "添加了<b>#{new_value}</b>标记"
else
new_value = "" if new_value.blank?
content += "将标记由<b>#{old_value}</b>更改为<b>#{new_value}</b>"
end
when 'assigner'
old_value = User.where(id: detail.old_value.split(",")).map{|u| u.real_name}.join("")
new_value = User.where(id: detail.value.split(",")).map{|u| u.real_name}.join("")
if old_value.nil? || old_value.blank?
content += "添加负责人<b>#{new_value}</b>"
else
new_value = "" if new_value.blank?
content += "将负责人由<b>#{old_value}</b>更改为<b>#{new_value}</b>"
end
when 'attr'
content = ""
case detail.prop_key
when 'subject'
return "修改了<b>标题</b>"
when 'description'
return "修改了<b>描述</b>"
when 'status_id'
old_value = IssueStatus.find_by_id(detail.old_value)&.name
new_value = IssueStatus.find_by_id(detail.value)&.name
content += "状态"
when 'priority_id'
old_value = IssuePriority.find_by_id(detail.old_value)&.name
new_value = IssuePriority.find_by_id(detail.value)&.name
content += "优先级"
when 'fixed_version_id'
old_value = Version.find_by_id(detail.old_value)&.name
new_value = Version.find_by_id(detail.value)&.name
content += "里程碑"
when 'branch_name'
old_value = detail.old_value
new_value = detail.value
content += "关联分支"
when 'start_date'
old_value = detail.old_value
new_value = detail.value
content += "开始日期"
when 'due_date'
old_value = detail.old_value
new_value = detail.value
content += "结束日期"
when 'assigned_to_id'
old_value = User.find_by_id(detail.old_value)&.real_name
new_value = User.find_by_id(detail.value)&.real_name
content += "负责人"
end
if old_value.nil? || old_value.blank?
content += "设置为<b>#{new_value}</b>"
else
new_value = "" if new_value.blank?
content += "由<b>#{old_value}</b>更改为<b>#{new_value}</b>"
end
end
end
def journal_content
send_details = []
if self.is_journal_detail?
@ -190,5 +272,15 @@ class Journal < ApplicationRecord
send_details
end
def to_builder
Jbuilder.new do |journal|
journal.(self, :id, :notes, :comments_count)
if self.parent_journal.present?
journal.parent_journal self.parent_journal.to_builder
end
if self.reply_journal.present?
journal.reply_journal self.reply_journal.to_builder
end
end
end
end

View File

@ -24,6 +24,7 @@ class MessageTemplate < ApplicationRecord
self.create(type: 'MessageTemplate::IssueAtme', sys_notice: '<b>{nickname}</b> 在疑修 <b>{title}</b> 中@我', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}')
email_html = File.read("#{email_template_html_dir}/issue_changed.html")
self.create(type: 'MessageTemplate::IssueChanged', sys_notice: '在项目 <b>{nickname2}/{repository}</b> 的疑修 <b>{title}</b> 中:{ifassigner}{nickname1}将负责人从 <b>{assigner1}</b> 修改为 <b>{assigner2}</b> {endassigner}{ifstatus}{nickname1}将状态从 <b>{status1}</b> 修改为 <b>{status2}</b> {endstatus}{iftracker}{nickname1}将类型从 <b>{tracker1}</b> 修改为 <b>{tracker2}</b> {endtracker}{ifpriority}{nickname1}将优先级从 <b>{priority1}</b> 修改为 <b>{priority2}</b> {endpriority}{ifmilestone}{nickname1}将里程碑从 <b>{milestone1}</b> 修改为 <b>{milestone2}</b> {endmilestone}{iftag}{nickname1}将标记从 <b>{tag1}</b> 修改为 <b>{tag2}</b> {endtag}{ifdoneratio}{nickname1}将完成度从 <b>{doneratio1}</b> 修改为 <b>{doneratio2}</b> {enddoneratio}{ifbranch}{nickname1}将指定分支从 <b>{branch1}</b> 修改为 <b>{branch2}</b> {endbranch}{ifstartdate}{nickname1}将开始日期从 <b>{startdate1}</b> 修改为 <b>{startdate2}</b> {endstartdate}{ifduedate}{nickname1}将结束日期从 <b>{duedate1}</b> 修改为 <b>{duedate2}</b> {endduedate}', email: email_html, email_title: "#{PLATFORM}: 疑修 {title} 有状态变更", notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}')
self.create(type: 'MessageTemplate::IssueClaim', sys_notice: '在 <b>{nickname2}/{repository}</b> 的疑修 <b>{title}</b> 中, <b>{nickname1}</b> 新建了一条声明', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}')
email_html = File.read("#{email_template_html_dir}/issue_expire.html")
self.create(type: 'MessageTemplate::IssueExpire', sys_notice: '疑修 <b>{title}</b> 已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}', email: email_html, email_title: "#{PLATFORM}: 疑修截止日期到达最后一天")
email_html = File.read("#{email_template_html_dir}/issue_deleted.html")

View File

@ -26,7 +26,7 @@ class MessageTemplate::IssueAssigned < MessageTemplate
project = issue&.project
owner = project&.owner
content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s)
return receivers_string(receivers), content, url
rescue => e
Rails.logger.info("MessageTemplate::IssueAssigned.get_message_content [ERROR] #{e}")
@ -52,7 +52,7 @@ class MessageTemplate::IssueAssigned < MessageTemplate
content.gsub!('{repository}', project&.name)
content.gsub!('{baseurl}', base_url)
content.gsub!('{title}', issue&.subject)
content.gsub!('{id}', issue&.id.to_s)
content.gsub!('{id}', issue&.project_issues_index.to_s)
content.gsub!('{platform}', PLATFORM)
return receiver&.mail, title, content

View File

@ -20,7 +20,7 @@ class MessageTemplate::IssueAssignerExpire < MessageTemplate
project = issue&.project
owner = project&.owner
content = sys_notice.gsub('{title}', issue&.subject)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s)
return receivers_string(receivers), content, url
rescue => e
Rails.logger.info("MessageTemplate::IssueAssignerExpire.get_message_content [ERROR] #{e}")

View File

@ -20,7 +20,7 @@ class MessageTemplate::IssueAtme < MessageTemplate
project = issue&.project
owner = project&.owner
content = sys_notice.gsub('{nickname}', operator&.real_name).gsub('{title}', issue&.subject)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s)
return receivers_string(receivers), content, url
rescue => e
Rails.logger.info("MessageTemplate::IssueAtme.get_message_content [ERROR] #{e}")

View File

@ -27,20 +27,20 @@ class MessageTemplate::IssueChanged < MessageTemplate
project = issue&.project
owner = project&.owner
content = MessageTemplate::IssueChanged.sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s)
change_count = change_params.keys.size
# 疑修负责人修改
if change_params[:assigned_to_id].present?
assigner1 = User.find_by_id(change_params[:assigned_to_id][0])
assigner2 = User.find_by_id(change_params[:assigned_to_id][1])
assigner1 = User.where(id: change_params[:assigned_to_id][0])
assigner2 = User.where(id: change_params[:assigned_to_id][1])
if change_count > 1
content.sub!('{ifassigner}', '<br/>')
else
content.sub!('{ifassigner}', '')
end
content.sub!('{endassigner}', '')
content.gsub!('{assigner1}', assigner1.present? ? assigner1&.real_name : '未指派成员')
content.gsub!('{assigner2}', assigner2.present? ? assigner2&.real_name : '未指派成员')
content.gsub!('{assigner1}', assigner1.present? ? assigner1.map{|a| a&.real_name}.join("") : '未指派成员')
content.gsub!('{assigner2}', assigner2.present? ? assigner2.map{|a| a&.real_name}.join("") : '未指派成员')
else
content.gsub!(/({ifassigner})(.*)({endassigner})/, '')
end
@ -205,20 +205,20 @@ class MessageTemplate::IssueChanged < MessageTemplate
content.gsub!('{identifier}', project&.identifier)
content.gsub!('{repository}', project&.name)
content.gsub!('{title}', issue&.subject)
content.gsub!('{id}', issue&.id.to_s)
content.gsub!('{id}', issue&.project_issues_index.to_s)
change_count = change_params.keys.size
# 疑修负责人修改
if change_params[:assigned_to_id].present?
assigner1 = User.find_by_id(change_params[:assigned_to_id][0])
assigner2 = User.find_by_id(change_params[:assigned_to_id][1])
assigner1 = User.where(id: change_params[:assigned_to_id][0])
assigner2 = User.where(id: change_params[:assigned_to_id][1])
if change_count > 1
content.sub!('{ifassigner}', '<br/>')
else
content.sub!('{ifassigner}', '')
end
content.sub!('{endassigner}', '')
content.gsub!('{assigner1}', assigner1.present? ? assigner1&.real_name : '未指派成员')
content.gsub!('{assigner2}', assigner2.present? ? assigner2&.real_name : '未指派成员')
content.gsub!('{assigner1}', assigner1.present? ? assigner1.map{|a| a&.real_name}.join("") : '未指派成员')
content.gsub!('{assigner2}', assigner2.present? ? assigner2.map{|a| a&.real_name}.join("") : '未指派成员')
else
content.gsub!(/({ifassigner})(.*)({endassigner})/, '')
end

View File

@ -0,0 +1,31 @@
# == Schema Information
#
# Table name: message_templates
#
# id :integer not null, primary key
# type :string(255)
# sys_notice :text(65535)
# email :text(65535)
# created_at :datetime not null
# updated_at :datetime not null
# notification_url :string(255)
# email_title :string(255)
#
# 在疑修中创建声明
class MessageTemplate::IssueClaim < MessageTemplate
# MessageTemplate::IssueAtme.get_message_content(User.where(login: 'yystopf'), User.last, Issue.last)
def self.get_message_content(receivers, operator, issue)
return '', '', '' if receivers.blank?
project = issue&.project
owner = project&.owner
content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s)
return receivers_string(receivers), content, url
rescue => e
Rails.logger.info("MessageTemplate::IssueClaim.get_message_content [ERROR] #{e}")
return 0, '', ''
end
end

View File

@ -28,7 +28,7 @@ class MessageTemplate::IssueExpire < MessageTemplate
project = issue&.project
owner = project&.owner
content = sys_notice.gsub('{title}', issue&.subject)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s)
return receivers_string(receivers), content, url
rescue => e
@ -53,7 +53,7 @@ class MessageTemplate::IssueExpire < MessageTemplate
content.gsub!('{repository}', project&.name)
content.gsub!('{baseurl}', base_url)
content.gsub!('{title}', issue&.subject)
content.gsub!('{id}', issue&.id.to_s)
content.gsub!('{id}', issue&.project_issues_index.to_s)
content.gsub!('{platform}', PLATFORM)
return receiver&.mail, title, content

View File

@ -27,7 +27,7 @@ class MessageTemplate::ProjectIssue < MessageTemplate
receivers = managers + followers
return '', '', '' if receivers.blank?
content = sys_notice.gsub('{nickname1}', operator&.real_name).gsub('{nickname2}', owner&.real_name).gsub('{repository}', project&.name).gsub('{title}', issue&.subject)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.id.to_s)
url = notification_url.gsub('{owner}', owner&.login).gsub('{identifier}', project&.identifier).gsub('{id}', issue&.project_issues_index.to_s)
return receivers_string(receivers), content, url
rescue => e
@ -54,7 +54,7 @@ class MessageTemplate::ProjectIssue < MessageTemplate
content.gsub!('{repository}', project&.name)
content.gsub!('{login2}', owner&.login)
content.gsub!('{identifier}', project&.identifier)
content.gsub!('{id}', issue&.id.to_s)
content.gsub!('{id}', issue&.project_issues_index.to_s)
content.gsub!('{title}', issue&.subject)
content.gsub!('{platform}', PLATFORM)

View File

@ -0,0 +1,24 @@
# == Schema Information
#
# Table name: openkylin_sign_details
#
# id :integer not null, primary key
# user_id :integer
# login :string(255)
# email :string(255)
# nickname :string(255)
# phone :string(255)
# address :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_openkylin_sign_details_on_user_id (user_id)
#
class OpenkylinSignDetail < ApplicationRecord
belongs_to :user
end

View File

@ -39,15 +39,18 @@
# business :boolean default("0")
# profile_completed :boolean default("0")
# laboratory_id :integer
# is_shixun_marker :boolean default("0")
# admin_visitable :boolean default("0")
# collaborator :boolean default("0")
# platform :string(255) default("0")
# gitea_token :string(255)
# gitea_uid :integer
# is_shixun_marker :boolean default("0")
# is_sync_pwd :boolean default("1")
# watchers_count :integer default("0")
# devops_step :integer default("0")
# gitea_token :string(255)
# platform :string(255)
# sponsor_certification :integer default("0")
# sponsor_num :integer default("0")
# sponsored_num :integer default("0")
# sponsor_description :text(65535)
# award_time :datetime
#
# Indexes
#
@ -55,9 +58,8 @@
# index_users_on_homepage_engineer (homepage_engineer)
# index_users_on_homepage_teacher (homepage_teacher)
# index_users_on_laboratory_id (laboratory_id)
# index_users_on_login (login) UNIQUE
# index_users_on_mail (mail) UNIQUE
# index_users_on_phone (phone) UNIQUE
# index_users_on_login (login)
# index_users_on_mail (mail)
# index_users_on_type (type)
#
@ -71,13 +73,16 @@ class Organization < Owner
has_many :teams, dependent: :destroy
has_many :organization_users, dependent: :destroy
has_many :team_users, dependent: :destroy
has_many :pinned_projects, class_name: 'PinnedProject', foreign_key: :user_id, dependent: :destroy
has_many :is_pinned_projects, through: :pinned_projects, source: :project, validate: false
validates :login, presence: true
validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, case_sensitive: false
validates :login, format: { with: NAME_REGEX, multiline: true, message: "只能含有数字、字母、下划线且不能以下划线开头和结尾" }
delegate :description, :website, :location, :repo_admin_change_team_access, :recommend,
:visibility, :max_repo_creation, :num_projects, :num_users, :num_teams, to: :organization_extension, allow_nil: true
:visibility, :max_repo_creation, :num_projects, :num_users, :num_teams,
:news_banner_id, :news_content, :memo, :news_title, :news_url, to: :organization_extension, allow_nil: true
scope :with_visibility, ->(visibility) { joins(:organization_extension).where(organization_extensions: {visibility: visibility}) if visibility.present? }
@ -144,6 +149,26 @@ class Organization < Owner
end
end
def projects_count
Project.where( user_id: self.id).count
end
def teams_count
teams.count
end
def organization_users_count
organization_users.count
end
def teams_count
teams.count
end
def organization_users_count
organization_users.count
end
def real_name
name = lastname + firstname
name = name.blank? ? (nickname.blank? ? login : nickname) : name

View File

@ -16,6 +16,9 @@
# num_users :integer default("0")
# num_teams :integer default("0")
# recommend :boolean default("0")
# news_banner_id :integer
# news_content :text(65535)
# memo :text(65535)
#
# Indexes
#

View File

@ -67,8 +67,11 @@ class Owner < ApplicationRecord
has_many :projects, foreign_key: :user_id, dependent: :destroy
has_many :repositories, foreign_key: :user_id, dependent: :destroy
has_many :applied_transfer_projects, dependent: :destroy
has_many :pinned_projects, foreign_key: :user_id, dependent: :destroy
scope :like, lambda { |keywords|
# 表情处理
keywords = keywords.to_s.each_char.select { |c| c.bytes.first < 240 }.join('')
sql = "CONCAT(lastname, firstname) LIKE :search OR nickname LIKE :search OR login LIKE :search "
where(sql, :search => "%#{keywords.strip}%") unless keywords.blank?
}

View File

@ -17,6 +17,7 @@
class PinnedProject < ApplicationRecord
belongs_to :user
# belongs_to :user
belongs_to :owner, class_name: 'Owner', foreign_key: :user_id, optional: true
belongs_to :project
end

View File

@ -26,10 +26,12 @@ class PraiseTread < ApplicationRecord
def incre_project_common
CacheAsyncSetJob.perform_later("project_common_service", {praises: 1}, self.praise_tread_object_id) if self.praise_tread_object_type == "Project"
self.praise_tread_object.update_column(:updated_on, Time.now) if self.praise_tread_object_type == "Project"
end
def decre_project_common
CacheAsyncSetJob.perform_later("project_common_service", {praises: -1}, self.praise_tread_object_id) if self.praise_tread_object_type == "Project"
self.praise_tread_object.update_column(:updated_on, Time.now) if self.praise_tread_object_type == "Project"
end
def incre_user_statistic

View File

@ -3,7 +3,7 @@
# Table name: projects
#
# id :integer not null, primary key
# name :string(255) default(""), not null
# name :string(255)
# description :text(4294967295)
# homepage :string(255) default("")
# is_public :boolean default("1"), not null
@ -122,10 +122,13 @@ class Project < ApplicationRecord
has_many :project_units, dependent: :destroy
has_one :applied_transfer_project,-> { order created_at: :desc }, dependent: :destroy
has_many :pinned_projects, dependent: :destroy
has_many :has_pinned_users, through: :pinned_projects, source: :user
has_many :has_pinned_users, through: :pinned_projects, source: :owner
has_many :webhooks, class_name: "Gitea::Webhook", primary_key: :gpid, foreign_key: :repo_id
has_many :user_trace_tasks, dependent: :destroy
has_many :project_invite_links, dependent: :destroy
has_many :project_topic_ralates, dependent: :destroy
has_many :project_topics, through: :project_topic_ralates
has_many :commit_logs, dependent: :destroy
after_create :incre_user_statistic, :incre_platform_statistic
after_save :check_project_members
before_save :set_invite_code, :reset_unmember_followed, :set_recommend_and_is_pinned, :reset_cache_data
@ -240,6 +243,8 @@ class Project < ApplicationRecord
end
def self.search_project(search)
# 表情处理
search = search.to_s.each_char.select { |c| c.bytes.first < 240 }.join('')
ransack(name_or_identifier_cont: search)
end
# 创建者
@ -378,7 +383,13 @@ class Project < ApplicationRecord
user = Owner.find_by_login namespace_path
user = User.new(login: namespace_path) if user.nil?
project = user&.projects&.find_by(identifier: identifier) || Project.find_by(identifier: "#{namespace_path}/#{identifier}")
if identifier.end_with?('.json')
project = user&.projects&.find_by(identifier: identifier) || Project.find_by(identifier: "#{namespace_path}/#{identifier}")
identifier = identifier.sub(/.*\K.json/, '')
project = user&.projects&.find_by(identifier: identifier) || Project.find_by(identifier: "#{namespace_path}/#{identifier}")
else
project = user&.projects&.find_by(identifier: identifier) || Project.find_by(identifier: "#{namespace_path}/#{identifier}")
end
return nil if project.blank?
[project, user]
@ -421,4 +432,104 @@ class Project < ApplicationRecord
raise("项目名称包含敏感词汇,请重新输入") if name && !HarmoniousDictionary.clean?(name)
raise("项目描述包含敏感词汇,请重新输入") if description && !HarmoniousDictionary.clean?(description)
end
def get_last_project_issues_index
last_issue = self.issues.issue_issue.last
deleted_issue_count = ($redis_cache.hget("issue_cache_delete_count", self.id) || 0).to_i
last_issue&.project_issues_index.present? ? last_issue.project_issues_index + deleted_issue_count : 0
end
def incre_project_issue_cache_delete_count(count=1)
$redis_cache.hincrby("issue_cache_delete_count", self.id, count)
end
def del_project_issue_cache_delete_count
$redis_cache.hdel("issue_cache_delete_count", self.id)
end
def self.mindspore_contributors
cache_result = $redis_cache.get("ProjectMindsporeContributors")
if cache_result.nil?
contributors = []
file = File.open('public/mindspore_authors', 'r')
file.each_line do |l|
itemArray = l.gsub("\r\n", "").split("|:|")
email = itemArray[0]
username = itemArray[1]
commits = itemArray[2].to_i
user = User.find_by(login: username, mail: email)
user = User.find_by(login: username) if user.nil?
user = User.find_by(mail: email) if user.nil?
# next if user.nil?
search_contributor = contributors.select{|con| con["id"]==user.id}[0]
if search_contributor.present?
search_contributor["contributions"] += commits
else
contributors << {contributions: commits, name: username, login: username, email: email, id: user&.id}.stringify_keys
end
end
file.close
$redis_cache.set("ProjectMindsporeContributors", contributors.to_json)
return contributors
else
return JSON.parse(cache_result)
end
end
def to_builder
Jbuilder.new do |project|
project.id self.id
project.identifier self.identifier
project.name self.name
project.description Nokogiri::HTML(self.description).text
project.visits self.visits
project.praises_count self.praises_count.to_i
project.watchers_count self.watchers_count.to_i
project.issues_count self.issues_count.to_i
project.pull_requests_count self.pull_requests_count.to_i
project.forked_count self.forked_count.to_i
project.is_public self.is_public
project.mirror_url self.repository&.mirror_url
project.type self&.project_type
project.created_at self.created_on.strftime("%Y-%m-%d %H:%M")
project.updated_at self.updated_on.strftime("%Y-%m-%d %H:%M")
project.forked_from_project_id self.forked_from_project_id
project.platform self.platform
project.author do
if self.educoder?
project_educoder = self.project_educoder
project.name project_educoder&.owner
project.type 'Educoder'
project.login project_educoder&.repo_name.split('/')[0]
project.image_url render_educoder_avatar_url(self.project_educoder)
else
user = self.owner
project.name user.try(:show_real_name)
project.type user&.type
project.login user.login
project.image_url user.get_letter_avatar_url
end
end
project.category do
if self.project_category.blank?
project.nil!
else
project.id self.project_category.id
project.name self.project_category.name
end
end
project.language do
if self.project_language.blank?
project.nil!
else
project.id self.project_language.id
project.name self.project_language.name
end
end
end
end
end

View File

@ -0,0 +1,25 @@
# == Schema Information
#
# Table name: project_topics
#
# id :integer not null, primary key
# user_id :integer
# name :string(255)
# position :integer default("0")
# projects_count :integer default("0")
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_project_topics_on_user_id (user_id)
#
class ProjectTopic < ApplicationRecord
belongs_to :user, optional: true
has_many :project_topic_ralates, dependent: :destroy
has_many :projects, through: :project_topic_ralates
validates :name, uniqueness: { case_sensitive: false }
end

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