diff --git a/Gemfile b/Gemfile index 41c3e139..f0effaff 100644 --- a/Gemfile +++ b/Gemfile @@ -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' \ No newline at end of file +gem 'gitea-client', '~> 1.4.2' diff --git a/Gemfile.lock b/Gemfile.lock index ee0c909a..7773ecad 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -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 diff --git a/README.md b/README.md index 2e84b704..96932e13 100644 --- a/README.md +++ b/README.md @@ -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环境) diff --git a/app/assets/javascripts/admins/organizations.js b/app/assets/javascripts/admins/organizations.js new file mode 100644 index 00000000..dee720fa --- /dev/null +++ b/app/assets/javascripts/admins/organizations.js @@ -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. diff --git a/app/assets/javascripts/admins/users/index.js b/app/assets/javascripts/admins/users/index.js index 0ef024bf..55dabed1 100644 --- a/app/assets/javascripts/admins/users/index.js +++ b/app/assets/javascripts/admins/users/index.js @@ -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'); diff --git a/app/assets/stylesheets/admins/organizations.scss b/app/assets/stylesheets/admins/organizations.scss new file mode 100644 index 00000000..a3cf9ca1 --- /dev/null +++ b/app/assets/stylesheets/admins/organizations.scss @@ -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/ diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb index 0d1660a0..889fc8b9 100644 --- a/app/controllers/accounts_controller.rb +++ b/app/controllers/accounts_controller.rb @@ -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] diff --git a/app/controllers/admins/organizations_controller.rb b/app/controllers/admins/organizations_controller.rb new file mode 100644 index 00000000..35fb4dee --- /dev/null +++ b/app/controllers/admins/organizations_controller.rb @@ -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 diff --git a/app/controllers/admins/users_controller.rb b/app/controllers/admins/users_controller.rb index 07ea8261..9137e218 100644 --- a/app/controllers/admins/users_controller.rb +++ b/app/controllers/admins/users_controller.rb @@ -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 diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rb index b937d798..bcb0c4e8 100644 --- a/app/controllers/api/v1/base_controller.rb +++ b/app/controllers/api/v1/base_controller.rb @@ -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 diff --git a/app/controllers/api/v1/issues/assigners_controller.rb b/app/controllers/api/v1/issues/assigners_controller.rb new file mode 100644 index 00000000..84476138 --- /dev/null +++ b/app/controllers/api/v1/issues/assigners_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/issues/authors_controller.rb b/app/controllers/api/v1/issues/authors_controller.rb new file mode 100644 index 00000000..d0242a51 --- /dev/null +++ b/app/controllers/api/v1/issues/authors_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/issues/issue_priorities_controller.rb b/app/controllers/api/v1/issues/issue_priorities_controller.rb new file mode 100644 index 00000000..319994a2 --- /dev/null +++ b/app/controllers/api/v1/issues/issue_priorities_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/issues/issue_tags_controller.rb b/app/controllers/api/v1/issues/issue_tags_controller.rb new file mode 100644 index 00000000..fe2eccea --- /dev/null +++ b/app/controllers/api/v1/issues/issue_tags_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/issues/journals_controller.rb b/app/controllers/api/v1/issues/journals_controller.rb new file mode 100644 index 00000000..4a88c1b0 --- /dev/null +++ b/app/controllers/api/v1/issues/journals_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/issues/milestones_controller.rb b/app/controllers/api/v1/issues/milestones_controller.rb new file mode 100644 index 00000000..003a464d --- /dev/null +++ b/app/controllers/api/v1/issues/milestones_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/issues/statues_controller.rb b/app/controllers/api/v1/issues/statues_controller.rb new file mode 100644 index 00000000..5a7fbc33 --- /dev/null +++ b/app/controllers/api/v1/issues/statues_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/issues_controller.rb b/app/controllers/api/v1/issues_controller.rb new file mode 100644 index 00000000..7238254d --- /dev/null +++ b/app/controllers/api/v1/issues_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/project_topics_controller.rb b/app/controllers/api/v1/project_topics_controller.rb new file mode 100644 index 00000000..46ae4cee --- /dev/null +++ b/app/controllers/api/v1/project_topics_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/projects/code_stats_controller.rb b/app/controllers/api/v1/projects/code_stats_controller.rb index 7ec671f3..0f2b2dd3 100644 --- a/app/controllers/api/v1/projects/code_stats_controller.rb +++ b/app/controllers/api/v1/projects/code_stats_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/projects/collaborators_controller.rb b/app/controllers/api/v1/projects/collaborators_controller.rb new file mode 100644 index 00000000..cd9002a9 --- /dev/null +++ b/app/controllers/api/v1/projects/collaborators_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/projects/contributors_controller.rb b/app/controllers/api/v1/projects/contributors_controller.rb new file mode 100644 index 00000000..abb5827c --- /dev/null +++ b/app/controllers/api/v1/projects/contributors_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/projects/tags_controller.rb b/app/controllers/api/v1/projects/tags_controller.rb index 06c3b1c8..b87d4842 100644 --- a/app/controllers/api/v1/projects/tags_controller.rb +++ b/app/controllers/api/v1/projects/tags_controller.rb @@ -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] diff --git a/app/controllers/api/v1/users/openkylin_sign_controller.rb b/app/controllers/api/v1/users/openkylin_sign_controller.rb new file mode 100644 index 00000000..6c76c5b3 --- /dev/null +++ b/app/controllers/api/v1/users/openkylin_sign_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/api/v1/users_controller.rb b/app/controllers/api/v1/users_controller.rb index 3a750b51..47087c52 100644 --- a/app/controllers/api/v1/users_controller.rb +++ b/app/controllers/api/v1/users_controller.rb @@ -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,"邮件发送失败,请稍后重试") diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 8129df8f..186ee874 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -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 diff --git a/app/controllers/attachments_controller.rb b/app/controllers/attachments_controller.rb index 63427aa4..0cdba384 100644 --- a/app/controllers/attachments_controller.rb +++ b/app/controllers/attachments_controller.rb @@ -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() diff --git a/app/controllers/claims_controller.rb b/app/controllers/claims_controller.rb index d9959baf..9132f823 100644 --- a/app/controllers/claims_controller.rb +++ b/app/controllers/claims_controller.rb @@ -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,"新建声明关联评论操作失败") diff --git a/app/controllers/commit_logs_controller.rb b/app/controllers/commit_logs_controller.rb index cc071340..c3bbf9c1 100644 --- a/app/controllers/commit_logs_controller.rb +++ b/app/controllers/commit_logs_controller.rb @@ -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 diff --git a/app/controllers/concerns/api/project_helper.rb b/app/controllers/concerns/api/project_helper.rb index 44cac08c..56f826b5 100644 --- a/app/controllers/concerns/api/project_helper.rb +++ b/app/controllers/concerns/api/project_helper.rb @@ -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 diff --git a/app/controllers/concerns/repository/languages_percentagable.rb b/app/controllers/concerns/repository/languages_percentagable.rb index 83374dad..dce5c7ff 100644 --- a/app/controllers/concerns/repository/languages_percentagable.rb +++ b/app/controllers/concerns/repository/languages_percentagable.rb @@ -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 diff --git a/app/controllers/installations_controller.rb b/app/controllers/installations_controller.rb index 20dd25e4..807554fb 100644 --- a/app/controllers/installations_controller.rb +++ b/app/controllers/installations_controller.rb @@ -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 diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index efc7d3ea..c1f2ea1f 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -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 diff --git a/app/controllers/journals_controller.rb b/app/controllers/journals_controller.rb index 6dc1e29c..8f785756 100644 --- a/app/controllers/journals_controller.rb +++ b/app/controllers/journals_controller.rb @@ -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 diff --git a/app/controllers/oauth/educoder_controller.rb b/app/controllers/oauth/educoder_controller.rb index 9ca4ae49..6d479ed0 100644 --- a/app/controllers/oauth/educoder_controller.rb +++ b/app/controllers/oauth/educoder_controller.rb @@ -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 diff --git a/app/controllers/organizations/is_pinned_projects_controller.rb b/app/controllers/organizations/is_pinned_projects_controller.rb new file mode 100644 index 00000000..bcf65951 --- /dev/null +++ b/app/controllers/organizations/is_pinned_projects_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/organizations/organizations_controller.rb b/app/controllers/organizations/organizations_controller.rb index 10aaa1ae..3c4e6478 100644 --- a/app/controllers/organizations/organizations_controller.rb +++ b/app/controllers/organizations/organizations_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/organizations/projects_controller.rb b/app/controllers/organizations/projects_controller.rb index b36a7612..ab5c9ef5 100644 --- a/app/controllers/organizations/projects_controller.rb +++ b/app/controllers/organizations/projects_controller.rb @@ -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 diff --git a/app/controllers/project_rank_controller.rb b/app/controllers/project_rank_controller.rb index 5cea074f..424f3ced 100644 --- a/app/controllers/project_rank_controller.rb +++ b/app/controllers/project_rank_controller.rb @@ -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 diff --git a/app/controllers/project_trends_controller.rb b/app/controllers/project_trends_controller.rb index f283d05f..4c0b2348 100644 --- a/app/controllers/project_trends_controller.rb +++ b/app/controllers/project_trends_controller.rb @@ -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 diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 52c77647..6e7d258a 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -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 diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 2b9bbbe6..f1039362 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -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, diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index e32b3101..6b2d2437 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -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 diff --git a/app/controllers/traces/projects_controller.rb b/app/controllers/traces/projects_controller.rb index 74e683f8..1377b452 100644 --- a/app/controllers/traces/projects_controller.rb +++ b/app/controllers/traces/projects_controller.rb @@ -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!( diff --git a/app/controllers/user_rank_controller.rb b/app/controllers/user_rank_controller.rb index dddca485..1d1a7b4f 100644 --- a/app/controllers/user_rank_controller.rb +++ b/app/controllers/user_rank_controller.rb @@ -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 diff --git a/app/controllers/users/headmaps_controller.rb b/app/controllers/users/headmaps_controller.rb index 7c88b568..15ce5676 100644 --- a/app/controllers/users/headmaps_controller.rb +++ b/app/controllers/users/headmaps_controller.rb @@ -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 \ No newline at end of file diff --git a/app/controllers/users/messages_controller.rb b/app/controllers/users/messages_controller.rb index 5116f580..4feb4a98 100644 --- a/app/controllers/users/messages_controller.rb +++ b/app/controllers/users/messages_controller.rb @@ -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] diff --git a/app/controllers/users/statistics_controller.rb b/app/controllers/users/statistics_controller.rb index 1948af9b..01319191 100644 --- a/app/controllers/users/statistics_controller.rb +++ b/app/controllers/users/statistics_controller.rb @@ -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 diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 33fd93f8..6cf505a6 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -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 diff --git a/app/controllers/version_releases_controller.rb b/app/controllers/version_releases_controller.rb index dd59098f..76a214d0 100644 --- a/app/controllers/version_releases_controller.rb +++ b/app/controllers/version_releases_controller.rb @@ -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 diff --git a/app/forms/base_form.rb b/app/forms/base_form.rb index ca82fa4b..44b5109c 100644 --- a/app/forms/base_form.rb +++ b/app/forms/base_form.rb @@ -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 diff --git a/app/forms/projects/create_form.rb b/app/forms/projects/create_form.rb index c51c2c60..c133175c 100644 --- a/app/forms/projects/create_form.rb +++ b/app/forms/projects/create_form.rb @@ -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 diff --git a/app/forms/projects/migrate_form.rb b/app/forms/projects/migrate_form.rb index ccd85447..12a4ee61 100644 --- a/app/forms/projects/migrate_form.rb +++ b/app/forms/projects/migrate_form.rb @@ -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 } diff --git a/app/forms/projects/update_form.rb b/app/forms/projects/update_form.rb index a351420b..226b2dc5 100644 --- a/app/forms/projects/update_form.rb +++ b/app/forms/projects/update_form.rb @@ -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) diff --git a/app/helpers/admins/organizations_helper.rb b/app/helpers/admins/organizations_helper.rb new file mode 100644 index 00000000..0265ab1e --- /dev/null +++ b/app/helpers/admins/organizations_helper.rb @@ -0,0 +1,2 @@ +module Admins::OrganizationsHelper +end diff --git a/app/helpers/projects_helper.rb b/app/helpers/projects_helper.rb index b4c21e04..b8622645 100644 --- a/app/helpers/projects_helper.rb +++ b/app/helpers/projects_helper.rb @@ -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') diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index c9817477..c9be515d 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -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 diff --git a/app/helpers/tag_chosen_helper.rb b/app/helpers/tag_chosen_helper.rb index 520b868f..784efcf2 100644 --- a/app/helpers/tag_chosen_helper.rb +++ b/app/helpers/tag_chosen_helper.rb @@ -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 diff --git a/app/interactors/gitea/create_file_interactor.rb b/app/interactors/gitea/create_file_interactor.rb index cf753767..70e2f6e8 100644 --- a/app/interactors/gitea/create_file_interactor.rb +++ b/app/interactors/gitea/create_file_interactor.rb @@ -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] } diff --git a/app/interactors/gitea/delete_file_interactor.rb b/app/interactors/gitea/delete_file_interactor.rb index 9a48c9e5..103df6cd 100644 --- a/app/interactors/gitea/delete_file_interactor.rb +++ b/app/interactors/gitea/delete_file_interactor.rb @@ -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 diff --git a/app/interactors/gitea/update_file_interactor.rb b/app/interactors/gitea/update_file_interactor.rb index 7dc0c017..38cfd98a 100644 --- a/app/interactors/gitea/update_file_interactor.rb +++ b/app/interactors/gitea/update_file_interactor.rb @@ -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 diff --git a/app/jobs/open_project_dev_ops_job.rb b/app/jobs/open_project_dev_ops_job.rb index 64115f25..b3fe99e6 100644 --- a/app/jobs/open_project_dev_ops_job.rb +++ b/app/jobs/open_project_dev_ops_job.rb @@ -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)}") diff --git a/app/jobs/send_template_message_job.rb b/app/jobs/send_template_message_job.rb index 763708c3..05572d45 100644 --- a/app/jobs/send_template_message_job.rb +++ b/app/jobs/send_template_message_job.rb @@ -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| diff --git a/app/jobs/touch_webhook_job.rb b/app/jobs/touch_webhook_job.rb new file mode 100644 index 00000000..0a8c03e9 --- /dev/null +++ b/app/jobs/touch_webhook_job.rb @@ -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 \ No newline at end of file diff --git a/app/libs/blockchain.rb b/app/libs/blockchain.rb new file mode 100644 index 00000000..e2c7804a --- /dev/null +++ b/app/libs/blockchain.rb @@ -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 \ No newline at end of file diff --git a/app/libs/custom_regexp.rb b/app/libs/custom_regexp.rb index 889da4df..b735a631 100644 --- a/app/libs/custom_regexp.rb +++ b/app/libs/custom_regexp.rb @@ -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 diff --git a/app/models/attachment.rb b/app/models/attachment.rb index 3451246a..0cbf6fb0 100644 --- a/app/models/attachment.rb +++ b/app/models/attachment.rb @@ -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 diff --git a/app/models/bot.rb b/app/models/bot.rb index 2098ac1e..13ac70a7 100644 --- a/app/models/bot.rb +++ b/app/models/bot.rb @@ -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) diff --git a/app/models/claim.rb b/app/models/claim.rb index 963b5f55..25f333e3 100644 --- a/app/models/claim.rb +++ b/app/models/claim.rb @@ -17,5 +17,6 @@ class Claim < ApplicationRecord belongs_to :user, foreign_key: :user_id + belongs_to :issue scope :claim_includes, ->{includes(:user)} end diff --git a/app/models/commit_log.rb b/app/models/commit_log.rb index 9b51b063..def2846f 100644 --- a/app/models/commit_log.rb +++ b/app/models/commit_log.rb @@ -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 diff --git a/app/models/concerns/matchable.rb b/app/models/concerns/matchable.rb index 5c013f95..0640e7c7 100644 --- a/app/models/concerns/matchable.rb +++ b/app/models/concerns/matchable.rb @@ -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 diff --git a/app/models/concerns/project_operable.rb b/app/models/concerns/project_operable.rb index 10b03cf7..4fee9ea3 100644 --- a/app/models/concerns/project_operable.rb +++ b/app/models/concerns/project_operable.rb @@ -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 diff --git a/app/models/concerns/watchable.rb b/app/models/concerns/watchable.rb index 008d382f..6d3d94e6 100644 --- a/app/models/concerns/watchable.rb +++ b/app/models/concerns/watchable.rb @@ -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 diff --git a/app/models/fork_user.rb b/app/models/fork_user.rb index 2d74af4a..92040ad1 100644 --- a/app/models/fork_user.rb +++ b/app/models/fork_user.rb @@ -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 diff --git a/app/models/gitea/webhook_task.rb b/app/models/gitea/webhook_task.rb index 325352c6..7e9bc68a 100644 --- a/app/models/gitea/webhook_task.rb +++ b/app/models/gitea/webhook_task.rb @@ -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 \ No newline at end of file diff --git a/app/models/import_repo.rb b/app/models/import_repo.rb new file mode 100644 index 00000000..8b53a776 --- /dev/null +++ b/app/models/import_repo.rb @@ -0,0 +1,6 @@ + + +# for oauth2 application +class ImportRepo < ApplicationRecord + self.table_name = "open_shixuns" +end diff --git a/app/models/issue.rb b/app/models/issue.rb index a691f9e1..e12f667d 100644 --- a/app/models/issue.rb +++ b/app/models/issue.rb @@ -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 diff --git a/app/models/issue_assigner.rb b/app/models/issue_assigner.rb new file mode 100644 index 00000000..a0836f21 --- /dev/null +++ b/app/models/issue_assigner.rb @@ -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 diff --git a/app/models/issue_participant.rb b/app/models/issue_participant.rb new file mode 100644 index 00000000..fa7be698 --- /dev/null +++ b/app/models/issue_participant.rb @@ -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 diff --git a/app/models/issue_priority.rb b/app/models/issue_priority.rb index 27865a70..5bf70da0 100644 --- a/app/models/issue_priority.rb +++ b/app/models/issue_priority.rb @@ -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 diff --git a/app/models/issue_status.rb b/app/models/issue_status.rb index a58346ea..fde87118 100644 --- a/app/models/issue_status.rb +++ b/app/models/issue_status.rb @@ -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 diff --git a/app/models/issue_tag.rb b/app/models/issue_tag.rb index bf236865..b4ee673f 100644 --- a/app/models/issue_tag.rb +++ b/app/models/issue_tag.rb @@ -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 diff --git a/app/models/issue_tags_relate.rb b/app/models/issue_tags_relate.rb index df9fd81a..fc753e95 100644 --- a/app/models/issue_tags_relate.rb +++ b/app/models/issue_tags_relate.rb @@ -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 diff --git a/app/models/journal.rb b/app/models/journal.rb index 20297dd9..ce69c1f3 100644 --- a/app/models/journal.rb +++ b/app/models/journal.rb @@ -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 "创建了疑修" + 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 += "添加了#{new_value}附件" + else + new_value = "无" if new_value.blank? + content += "将附件由#{old_value}更改为#{new_value}" + 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 += "添加了#{new_value}标记" + else + new_value = "无" if new_value.blank? + content += "将标记由#{old_value}更改为#{new_value}" + 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 += "添加负责人#{new_value}" + else + new_value = "无" if new_value.blank? + content += "将负责人由#{old_value}更改为#{new_value}" + end + when 'attr' + content = "将" + case detail.prop_key + when 'subject' + return "修改了标题" + when 'description' + return "修改了描述" + 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 += "设置为#{new_value}" + else + new_value = "无" if new_value.blank? + content += "由#{old_value}更改为#{new_value}" + 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 diff --git a/app/models/message_template.rb b/app/models/message_template.rb index 200c2f67..7ab7fdad 100644 --- a/app/models/message_template.rb +++ b/app/models/message_template.rb @@ -24,6 +24,7 @@ class MessageTemplate < ApplicationRecord self.create(type: 'MessageTemplate::IssueAtme', sys_notice: '{nickname} 在疑修 {title} 中@我', 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: '在项目 {nickname2}/{repository} 的疑修 {title} 中:{ifassigner}{nickname1}将负责人从 {assigner1} 修改为 {assigner2} {endassigner}{ifstatus}{nickname1}将状态从 {status1} 修改为 {status2} {endstatus}{iftracker}{nickname1}将类型从 {tracker1} 修改为 {tracker2} {endtracker}{ifpriority}{nickname1}将优先级从 {priority1} 修改为 {priority2} {endpriority}{ifmilestone}{nickname1}将里程碑从 {milestone1} 修改为 {milestone2} {endmilestone}{iftag}{nickname1}将标记从 {tag1} 修改为 {tag2} {endtag}{ifdoneratio}{nickname1}将完成度从 {doneratio1} 修改为 {doneratio2} {enddoneratio}{ifbranch}{nickname1}将指定分支从 {branch1} 修改为 {branch2} {endbranch}{ifstartdate}{nickname1}将开始日期从 {startdate1} 修改为 {startdate2} {endstartdate}{ifduedate}{nickname1}将结束日期从 {duedate1} 修改为 {duedate2} {endduedate}', email: email_html, email_title: "#{PLATFORM}: 疑修 {title} 有状态变更", notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}') + self.create(type: 'MessageTemplate::IssueClaim', sys_notice: '在 {nickname2}/{repository} 的疑修 {title} 中, {nickname1} 新建了一条声明', 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: '疑修 {title} 已临近截止日期,请尽快处理', notification_url: '{baseurl}/{owner}/{identifier}/issues/{id}', email: email_html, email_title: "#{PLATFORM}: 疑修截止日期到达最后一天") email_html = File.read("#{email_template_html_dir}/issue_deleted.html") diff --git a/app/models/message_template/issue_assigned.rb b/app/models/message_template/issue_assigned.rb index 7f8494f6..7973ed47 100644 --- a/app/models/message_template/issue_assigned.rb +++ b/app/models/message_template/issue_assigned.rb @@ -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 diff --git a/app/models/message_template/issue_assigner_expire.rb b/app/models/message_template/issue_assigner_expire.rb index 610c5117..8f9417a4 100644 --- a/app/models/message_template/issue_assigner_expire.rb +++ b/app/models/message_template/issue_assigner_expire.rb @@ -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}") diff --git a/app/models/message_template/issue_atme.rb b/app/models/message_template/issue_atme.rb index 04eb132e..7709ed05 100644 --- a/app/models/message_template/issue_atme.rb +++ b/app/models/message_template/issue_atme.rb @@ -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}") diff --git a/app/models/message_template/issue_changed.rb b/app/models/message_template/issue_changed.rb index e8a5e5cd..43e2cee7 100644 --- a/app/models/message_template/issue_changed.rb +++ b/app/models/message_template/issue_changed.rb @@ -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}', '
') 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}', '
') 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 diff --git a/app/models/message_template/issue_claim.rb b/app/models/message_template/issue_claim.rb new file mode 100644 index 00000000..0a7b6e4e --- /dev/null +++ b/app/models/message_template/issue_claim.rb @@ -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 diff --git a/app/models/message_template/issue_expire.rb b/app/models/message_template/issue_expire.rb index d77965f1..eedd5350 100644 --- a/app/models/message_template/issue_expire.rb +++ b/app/models/message_template/issue_expire.rb @@ -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 diff --git a/app/models/message_template/project_issue.rb b/app/models/message_template/project_issue.rb index e0483083..e262cd58 100644 --- a/app/models/message_template/project_issue.rb +++ b/app/models/message_template/project_issue.rb @@ -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) diff --git a/app/models/openkylin_sign_detail.rb b/app/models/openkylin_sign_detail.rb new file mode 100644 index 00000000..7f9000cf --- /dev/null +++ b/app/models/openkylin_sign_detail.rb @@ -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 diff --git a/app/models/organization.rb b/app/models/organization.rb index adf43a2c..75a2db97 100644 --- a/app/models/organization.rb +++ b/app/models/organization.rb @@ -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 diff --git a/app/models/organization_extension.rb b/app/models/organization_extension.rb index 4b093520..cb216aca 100644 --- a/app/models/organization_extension.rb +++ b/app/models/organization_extension.rb @@ -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 # diff --git a/app/models/owner.rb b/app/models/owner.rb index 2763dc80..d325d3bd 100644 --- a/app/models/owner.rb +++ b/app/models/owner.rb @@ -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? } diff --git a/app/models/pinned_project.rb b/app/models/pinned_project.rb index 8e47c9ea..c87944fa 100644 --- a/app/models/pinned_project.rb +++ b/app/models/pinned_project.rb @@ -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 diff --git a/app/models/praise_tread.rb b/app/models/praise_tread.rb index 5d4ae0d8..0250f012 100644 --- a/app/models/praise_tread.rb +++ b/app/models/praise_tread.rb @@ -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 diff --git a/app/models/project.rb b/app/models/project.rb index e1670bf5..a63a8dd4 100644 --- a/app/models/project.rb +++ b/app/models/project.rb @@ -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 diff --git a/app/models/project_topic.rb b/app/models/project_topic.rb new file mode 100644 index 00000000..94c9df9c --- /dev/null +++ b/app/models/project_topic.rb @@ -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 diff --git a/app/models/project_topic_ralate.rb b/app/models/project_topic_ralate.rb new file mode 100644 index 00000000..d8638699 --- /dev/null +++ b/app/models/project_topic_ralate.rb @@ -0,0 +1,22 @@ +# == Schema Information +# +# Table name: project_topic_ralates +# +# id :integer not null, primary key +# project_topic_id :integer +# project_id :integer +# created_at :datetime not null +# updated_at :datetime not null +# +# Indexes +# +# index_project_topic_ralates_on_project_id (project_id) +# index_project_topic_ralates_on_project_topic_id (project_topic_id) +# + +class ProjectTopicRalate < ApplicationRecord + + belongs_to :project_topic, counter_cache: :projects_count + belongs_to :project + +end diff --git a/app/models/pull_attached_issue.rb b/app/models/pull_attached_issue.rb new file mode 100644 index 00000000..abc6c344 --- /dev/null +++ b/app/models/pull_attached_issue.rb @@ -0,0 +1,23 @@ +# == Schema Information +# +# Table name: pull_attached_issues +# +# id :integer not null, primary key +# pull_request_id :integer +# issue_id :integer +# created_at :datetime not null +# updated_at :datetime not null +# fixed :boolean default("0") +# +# Indexes +# +# index_pull_attached_issues_on_issue_id (issue_id) +# index_pull_attached_issues_on_pull_request_id (pull_request_id) +# + +class PullAttachedIssue < ApplicationRecord + + belongs_to :pull_request + belongs_to :issue + +end diff --git a/app/models/pull_request.rb b/app/models/pull_request.rb index 270e7dc7..e4677795 100644 --- a/app/models/pull_request.rb +++ b/app/models/pull_request.rb @@ -44,6 +44,8 @@ class PullRequest < ApplicationRecord has_many :pull_requests_reviewers, dependent: :destroy has_many :reviewers, through: :pull_requests_reviewers has_many :mark_files, dependent: :destroy + has_many :pull_attached_issues, dependent: :destroy + has_many :attached_issues, through: :pull_attached_issues, source: :issue scope :merged_and_closed, ->{where.not(status: 0)} scope :opening, -> {where(status: 0)} @@ -117,4 +119,37 @@ class PullRequest < ApplicationRecord JSON.parse file_names end + + def to_builder + Jbuilder.new do |pull| + pull.(self, :id, :gitea_number, :title, :body, :base, :head, :is_original, :comments_count) + pull.user self.user.to_builder + if self.fork_project.present? + pull.fork_project self.fork_project.to_builder + else + pull.fork_project nil + end + pull.created_at self.created_at.strftime("%Y-%m-%d %H:%M") + pull.updated_at self.updated_at.strftime("%Y-%m-%d %H:%M") + pull.status self.pr_status + pull.url self.pr_url + end + end + + def pr_url + return nil if self.project.nil? + "#{Rails.application.config_for(:configuration)['platform_url']}/#{self.project.owner.login}/#{self.project.name}/pulls/#{self.id}" + end + + def pr_status + case status + when 0 + "OPEN" + when 1 + "MERGED" + when 2 + "CLOSED" + end + end + end diff --git a/app/models/site.rb b/app/models/site.rb index a8b725ef..097306fb 100644 --- a/app/models/site.rb +++ b/app/models/site.rb @@ -30,6 +30,10 @@ class Site < ApplicationRecord self.common.where(key: 'notice').present? end + def self.has_blockchain? + self.common.where(key: 'blockchain').present? + end + private def self.set_add_menu! adds= [ diff --git a/app/models/user.rb b/app/models/user.rb index b43e289e..ba8afffa 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -178,9 +178,16 @@ class User < Owner has_many :user_trace_tasks, dependent: :destroy has_many :feedbacks, dependent: :destroy + has_many :issue_assigners, foreign_key: :assigner_id + has_many :assigned_issues, through: :issue_assigners, source: :issue + has_many :issue_participants, foreign_key: :participant_id + has_many :participant_issues, through: :issue_participants, source: :issue + has_many :project_topics # Groups and active users scope :active, lambda { where(status: [STATUS_ACTIVE, STATUS_EDIT_INFO]) } scope :like, lambda { |keywords| + # 表情处理 + keywords = keywords.to_s.each_char.select { |c| c.bytes.first < 240 }.join('') sql = "CONCAT(lastname, firstname) LIKE :search OR nickname LIKE :search OR login LIKE :search OR mail LIKE :search OR nickname LIKE :search" where(sql, :search => "%#{keywords.strip}%") unless keywords.blank? } @@ -443,6 +450,19 @@ class User < Owner self.status = STATUS_EDIT_INFO end + def fresh_gitea_token + result = $gitea_client.get_users_tokens_by_username(self.login, {query: {sudo: self.login}}) + if result[:data].present? + result[:data].map{ |e| + $gitea_client.delete_users_tokens_by_username_token(self.login, e["name"], {query: {sudo: self.login} }) + } + end + new_result = $gitea_client.post_users_tokens_by_username(self.login, { query: {sudo: self.login}, body:{ name: self.login} }) + if new_result["sha1"].present? + update(gitea_token: new_result["sha1"]) + end + end + def activate! update_attribute(:status, STATUS_ACTIVE) prohibit_gitea_user_login!(false) @@ -839,6 +859,49 @@ class User < Owner end end + # 重写gitea_token,当用户为bot类型时,替换成管理员token + def gitea_token + if self.platform == "bot" + GiteaService.gitea_config[:admin_token] + else + self['gitea_token'] + end + end + + def to_builder + Jbuilder.new do |user| + user.(self, :id, :login) + user.name self.real_name + user.email self.mail + user.image_url self.get_letter_avatar_url + end + end + + def self.develop_score(commit_count, code_line, user_id=User.current.id) + user_date_statistic_key = "v2-user-statistic:#{user_id}" + follow_count = $redis_cache.hget(user_date_statistic_key, "follow-count") || 0 + pullrequest_count = $redis_cache.hget(user_date_statistic_key, "pullrequest-count").to_i || 0 + issues_count = $redis_cache.hget(user_date_statistic_key, "issue-count").to_i || 0 + project_count = $redis_cache.hget(user_date_statistic_key, "project-count") || 0 + fork_count = $redis_cache.hget(user_date_statistic_key, "fork-count") || 0 + project_watchers_count = $redis_cache.hget(user_date_statistic_key, "project-watcher-count") || 0 + project_praises_count = $redis_cache.hget(user_date_statistic_key, "project-praise-count") || 0 + project_language = $redis_cache.hget(user_date_statistic_key, "project-language") + project_languages_count = project_language.nil? || project_language == "{}" ? 0 : JSON.parse(project_language).length + pullrequest_count += commit_count + issues_count += code_line + influence = (60.0 + follow_count.to_i / (follow_count.to_i + 20.0) * 40.0).to_i + contribution = (60.0 + pullrequest_count.to_i / (pullrequest_count.to_i + 20.0) * 40.0).to_i + activity = (60.0 + issues_count.to_i / (issues_count.to_i + 80.0) * 40.0).to_i + experience = 10 * project_count.to_i + 5 * fork_count.to_i + project_watchers_count.to_i + project_praises_count.to_i + experience = (60.0 + experience / (experience + 100.0) * 40.0).to_i + language = (60.0 + project_languages_count.to_i / (project_languages_count.to_i + 5.0) * 40.0).to_i + score = influence+ contribution + activity + experience + language + + score + end + + protected def validate_password_length # 管理员的初始密码是5位 diff --git a/app/models/version.rb b/app/models/version.rb index 41256833..82474f55 100644 --- a/app/models/version.rb +++ b/app/models/version.rb @@ -28,6 +28,9 @@ class Version < ApplicationRecord has_many :issues, class_name: "Issue", foreign_key: "fixed_version_id" belongs_to :user, optional: true + has_many :opened_issues, -> {where(issue_classify: "issue").where.not(status_id: 5)}, class_name: "Issue", foreign_key: :fixed_version_id + has_many :closed_issues, -> {where(issue_classify: "issue", status_id: 5)}, class_name: "Issue", foreign_key: :fixed_version_id + scope :version_includes, ->{includes(:issues, :user)} scope :closed, ->{where(status: 'closed')} scope :opening, ->{where(status: 'open')} @@ -43,16 +46,27 @@ class Version < ApplicationRecord after_create :send_create_message_to_notice_system after_save :send_update_message_to_notice_system + def issue_percent + issues_total_count = opened_issues.size + closed_issues.size + issues_total_count.zero? ? 0.0 : closed_issues.size.to_f / issues_total_count + end + def version_user User.select(:login, :lastname,:firstname, :nickname)&.find_by_id(self.user_id) end + def to_builder + Jbuilder.new do |version| + version.(self, :id, :name, :description, :effective_date) + end + end + private def send_create_message_to_notice_system SendTemplateMessageJob.perform_later('ProjectMilestone', self.id, self.user_id) if Site.has_notice_menu? end def send_update_message_to_notice_system - SendTemplateMessageJob.perform_later('ProjectMilestoneCompleted', self.id) if Site.has_notice_menu? && self.percent == 1.0 + SendTemplateMessageJob.perform_later('ProjectMilestoneCompleted', self.id) if Site.has_notice_menu? && self.issue_percent == 1.0 end end diff --git a/app/models/watcher.rb b/app/models/watcher.rb index 5a2cd96f..f9d646ca 100644 --- a/app/models/watcher.rb +++ b/app/models/watcher.rb @@ -28,10 +28,12 @@ class Watcher < ApplicationRecord def incre_project_common CacheAsyncSetJob.perform_later("project_common_service", {watchers: 1}, self.watchable_id) if self.watchable_type == "Project" + self.watchable.update_column(:updated_on, Time.now) if self.watchable_type == "Project" end def decre_project_common CacheAsyncSetJob.perform_later("project_common_service", {watchers: -1}, self.watchable_id) if self.watchable_type == "Project" + self.watchable.update_column(:updated_on, Time.now) if self.watchable_type == "Project" end def incre_user_statistic diff --git a/app/queries/admins/organization_query.rb b/app/queries/admins/organization_query.rb new file mode 100644 index 00000000..09dbab9e --- /dev/null +++ b/app/queries/admins/organization_query.rb @@ -0,0 +1,21 @@ +class Admins::OrganizationQuery < ApplicationQuery + include CustomSortable + attr_reader :params + sort_columns :created_on, :last_login_on, :experience, :grade, default_by: :created_on, default_direction: :desc + + def initialize(params) + @params = params + end + + def call + orgs = Organization.all + # 关键字检索 + keyword = params[:keyword].to_s.strip.presence + if keyword + sql = 'nickname LIKE :keyword OR login LIKE :keyword' + orgs = orgs.where(sql, keyword: "%#{keyword}%") + end + + custom_sort(orgs, params[:sort_by], params[:sort_direction]) + end +end \ No newline at end of file diff --git a/app/queries/application_query.rb b/app/queries/application_query.rb index c66af94c..e2d7c446 100644 --- a/app/queries/application_query.rb +++ b/app/queries/application_query.rb @@ -6,4 +6,55 @@ class ApplicationQuery def strip_param(key) params[key].to_s.strip.presence end + + # find all the repos that a user has tokens + def find_repo_with_token(user_id, page=1, limit=10) + params = { + "request-type": "query user balance of all repos by page", + "username": user_id.to_s, + "page": page.to_i, + "page_num": limit.to_i + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] != 0 + raise "区块链接口请求失败." + else + token_list = resp_body['UserBalanceList'].nil? ? [] : resp_body['UserBalanceList'] + return token_list, resp_body['total_count'] + end + end + + + # find one repo that a user has tokens + def find_one_balance(user_id, project_id) + # return 3 statuses: UnknownErr/ResUserNotExisted/Success + params = { + "request-type": "query user balance of single repo", + "username": user_id.to_s, + "token_name": project_id.to_s + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 0 + return resp_body['balance'] + elsif resp_body['status'] == 100 + return 0 # 找不到用户返回0 + else + raise "区块链接口请求失败." + end + end + + # query the basic info of a repository + def find_blockchain_repo_info(project_id) + params = { + "request-type": "query repo basic info", + "token_name": project_id.to_s + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 0 + return resp_body + else + raise "区块链接口请求失败." + end + end + end \ No newline at end of file diff --git a/app/queries/blockchain/balance_query.rb b/app/queries/blockchain/balance_query.rb new file mode 100644 index 00000000..f2c39c00 --- /dev/null +++ b/app/queries/blockchain/balance_query.rb @@ -0,0 +1,32 @@ +class Blockchain::BalanceQuery < ApplicationQuery + + attr_reader :params, :is_current_admin_user + + def initialize(params,is_current_admin_user) + @params = params + @is_current_admin_user = is_current_admin_user + end + + def call + if is_current_admin_user + token_list, total_count = find_repo_with_token(params["user_id"], (params["page"] || 1), (params["limit"] || 10)) + result_list = [] + token_list.each do |t| + project = Project.find_by(id: t['token_name'].to_i) + if project.nil? + result_list << {project: nil, balance: t['balance']} + next + end + owner = User.find_by(id: project.user_id) + if owner.nil? || project.nil? + else + balance = t['balance'] + result_list << {project: project, balance: balance} + end + end + results = {"status": 0, "projects": result_list, "total_count": total_count} + else + results = {"status": 1} # query failed + end + end +end diff --git a/app/queries/blockchain/balance_query_one_project.rb b/app/queries/blockchain/balance_query_one_project.rb new file mode 100644 index 00000000..c4ec19e2 --- /dev/null +++ b/app/queries/blockchain/balance_query_one_project.rb @@ -0,0 +1,12 @@ +class Blockchain::BalanceQueryOneProject < ApplicationQuery + + attr_reader :params, :is_current_admin_user + + def initialize(params) + @params = params + end + + def call + find_one_balance(params[:user_id].to_s, params[:project_id].to_s) + end +end diff --git a/app/queries/blockchain/repo_basic_info.rb b/app/queries/blockchain/repo_basic_info.rb new file mode 100644 index 00000000..df17b7a0 --- /dev/null +++ b/app/queries/blockchain/repo_basic_info.rb @@ -0,0 +1,13 @@ +class Blockchain::RepoBasicInfo < ApplicationQuery + + attr_reader :params, :is_current_admin_user + + def initialize(params) + @params = params + end + + def call + info = find_blockchain_repo_info(params[:project_id].to_s) + return info + end +end diff --git a/app/queries/projects/list_my_query.rb b/app/queries/projects/list_my_query.rb index 6c7f38d9..27415543 100644 --- a/app/queries/projects/list_my_query.rb +++ b/app/queries/projects/list_my_query.rb @@ -34,10 +34,20 @@ class Projects::ListMyQuery < ApplicationQuery elsif params[:category].to_s == "forked" #我fork的 fork_ids = user.fork_users.select(:id, :fork_project_id).pluck(:fork_project_id) projects = projects.where(id: fork_ids) + elsif params[:category].to_s == "admin" + normal_projects = projects.joins(members: :roles).where(members: {user_id: user.id}, roles: {name: %w(Manager)}).to_sql + org_projects = projects.joins(team_projects: [team: :team_users]).where(teams: {authorize: %w(owner admin)},team_users: {user_id: user.id}).to_sql + projects = Project.from("( #{ normal_projects} UNION #{ org_projects } ) AS projects").distinct # elsif params[:category].to_s == "public" # projects = projects.visible.joins(:members).where(members: { user_id: user.id }) # elsif params[:category].to_s == "private" # projects = projects.is_private.joins(:members).where(members: { user_id: user.id }) + elsif params[:category].to_s == "blockchain_token" # 所有钱包中有token的项目有哪些 + token_list, total_count = find_repo_with_token(user.id) + project_names = token_list.map { |x| x['token_name'] } + projects = projects.where(name: project_names) + tokens = token_list.map { |x| x['balance'] } + puts "pause" end if params[:is_public].present? @@ -52,10 +62,12 @@ class Projects::ListMyQuery < ApplicationQuery elsif params[:project_type].to_s === "sync_mirror" projects = projects.sync_mirror end - - q = projects.ransack(name_or_identifier_cont: params[:search]) - scope = q.result.includes(:project_category, :project_language,:owner, :repository, :has_pinned_users) + # 表情处理 + keywords = params[:search].to_s.each_char.select { |c| c.bytes.first < 240 }.join('') + q = projects.ransack(name_or_identifier_cont: keywords) + + scope = q.result.includes(:project_category, :project_language,:owner, :repository, :has_pinned_users, :project_topics) sort = Project.column_names.include?(params[:sort_by]) ? params[:sort_by] : "updated_on" sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : "desc" diff --git a/app/queries/projects/list_query.rb b/app/queries/projects/list_query.rb index 6b084354..72776f7a 100644 --- a/app/queries/projects/list_query.rb +++ b/app/queries/projects/list_query.rb @@ -3,7 +3,7 @@ class Projects::ListQuery < ApplicationQuery attr_reader :params, :current_user_id - sort_columns :updated_on, :created_on, :forked_count, :praises_count, default_by: :updated_on, default_direction: :desc + sort_columns :updated_on, :created_on, :forked_count, :praises_count, default_by: :updated_on, default_direction: :desc, default_table: 'projects' def initialize(params, current_user_id=nil) @params = params @@ -32,6 +32,7 @@ class Projects::ListQuery < ApplicationQuery collection = by_project_type(collection) collection = by_project_category(collection) collection = by_project_language(collection) + collection = by_project_topic(collection) collection end @@ -51,7 +52,9 @@ class Projects::ListQuery < ApplicationQuery # items = items.where(id: @ids).by_name_or_identifier(params[:search]) items = items.where(id: @ids) else - items = items.by_name_or_identifier(params[:search]).or(main_collection.where(user_id: Owner.like(params[:search]).pluck(:id))) + # 表情处理 + keywords = params[:search].to_s.each_char.select { |c| c.bytes.first < 240 }.join('') + items = items.by_name_or_identifier(keywords).or(main_collection.where(user_id: Owner.like(keywords).pluck(:id))) end items end @@ -72,6 +75,10 @@ class Projects::ListQuery < ApplicationQuery (params[:pinned].present? && params[:category_id].present?) ? items.pinned : items end + def by_project_topic(items) + items.with_project_topic(params[:topic_id]) + end + # 优化排序 def optimize_sorting(relations, sort_by) if sort_by == "updated_on" diff --git a/app/services/admins/delete_organization_service.rb b/app/services/admins/delete_organization_service.rb new file mode 100644 index 00000000..d5c9bd2c --- /dev/null +++ b/app/services/admins/delete_organization_service.rb @@ -0,0 +1,23 @@ +class Admins::DeleteOrganizationService < Gitea::ClientService + attr_reader :token, :name + + def initialize(name) + @name = name + end + + def call + response = delete(url, params) + render_status(response) + + Gitea::Organization::DeleteService.call(token,name) + end + + + private + def token + { + username: GiteaService.gitea_config[:access_key_id], + password: GiteaService.gitea_config[:access_key_secret] + } + end +end diff --git a/app/services/api/v1/issues/batch_delete_service.rb b/app/services/api/v1/issues/batch_delete_service.rb new file mode 100644 index 00000000..45821b37 --- /dev/null +++ b/app/services/api/v1/issues/batch_delete_service.rb @@ -0,0 +1,38 @@ +class Api::V1::Issues::BatchDeleteService < ApplicationService + include ActiveModel::Model + + attr_reader :project, :issues, :current_user + + validates :project, :issues, :current_user, presence: true + + def initialize(project, issues, current_user = nil) + @project = project + @issues = issues.includes(:assigners) + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + try_lock("Api::V1::Issues::DeleteService:#{project.id}") # 开始写数据,加锁 + + delete_issues + + project.incre_project_issue_cache_delete_count(@issues.size) + + if Site.has_notice_menu? + @issues.each do |issue| + SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, @issue&.subject, @issue.assigners.pluck(:id), @issue.author_id) + end + end + + unlock("Api::V1::Issues::DeleteService:#{project.id}") + + return true + end + + private + + def delete_issues + raise Error, "批量删除疑修失败!" unless @issues.destroy_all + end +end \ No newline at end of file diff --git a/app/services/api/v1/issues/batch_update_service.rb b/app/services/api/v1/issues/batch_update_service.rb new file mode 100644 index 00000000..ccf783dc --- /dev/null +++ b/app/services/api/v1/issues/batch_update_service.rb @@ -0,0 +1,33 @@ +class Api::V1::Issues::BatchUpdateService < ApplicationService + include ActiveModel::Model + include Api::V1::Issues::Concerns::Checkable + include Api::V1::Issues::Concerns::Loadable + + attr_reader :project, :issues, :params, :current_user + attr_reader :status_id, :priority_id, :milestone_id + attr_reader :issue_tag_ids, :assigner_ids + + validates :project, :issues, :current_user, presence: true + + def initialize(project, issues, params, current_user = nil) + @project = project + @issues = issues + @params = params + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + ActiveRecord::Base.transaction do + @issues.each do |issue| + if issue.issue_classify == "issue" + Api::V1::Issues::UpdateService.call(project, issue, params, current_user) + end + end + + return true + end + end + + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/concerns/checkable.rb b/app/services/api/v1/issues/concerns/checkable.rb new file mode 100644 index 00000000..b19c245e --- /dev/null +++ b/app/services/api/v1/issues/concerns/checkable.rb @@ -0,0 +1,53 @@ +module Api::V1::Issues::Concerns::Checkable + + def check_issue_status(status_id) + raise ApplicationService::Error, "IssueStatus不存在!" unless IssueStatus.find_by_id(status_id).present? + end + + def check_issue_priority(priority_id) + raise ApplicationService::Error, "IssuePriority不存在!" unless IssuePriority.find_by_id(priority_id).present? + end + + def check_milestone(milestone_id) + raise ApplicationService::Error, "Milestone不存在!" unless Version.find_by_id(milestone_id).present? + end + + def check_issue_tags(issue_tag_ids) + raise ApplicationService::Error, "请输入正确的标记ID数组!" unless issue_tag_ids.is_a?(Array) + raise ApplicationService::Error, "最多可选择3个标记" if issue_tag_ids.size > 3 + issue_tag_ids.each do |tid| + raise ApplicationService::Error, "请输入正确的标记ID!" unless IssueTag.exists?(id: tid) + end + end + + def check_assigners(assigner_ids) + raise ApplicationService::Error, "请输入正确的负责人ID数组!" unless assigner_ids.is_a?(Array) + raise ApplicationService::Error, "最多可选择5个负责人" if assigner_ids.size > 5 + assigner_ids.each do |aid| + raise ApplicationService::Error, "请输入正确的负责人ID!" unless User.exists?(id: aid) + end + end + + def check_attachments (attachment_ids) + raise ApplicationService::Error, "请输入正确的附件ID数组!" unless attachment_ids.is_a?(Array) + attachment_ids.each do |aid| + raise ApplicationService::Error, "请输入正确的附件ID!" unless Attachment.exists?(id: aid) + end + end + + def check_atme_receivers(receivers_login) + raise ApplicationService::Error, "请输入正确的用户标识数组!" unless receivers_login.is_a?(Array) + receivers_login.each do |rlogin| + raise ApplicationService::Error, "请输入正确的用户标识!" unless User.exists?(login: rlogin) + end + end + + def check_parent_journal(parent_id) + raise ApplicationService::Error, "ParentJournal不存在!" unless Journal.find_by_id(parent_id).present? + end + + def check_blockchain_token_num(user_id, project_id, blockchain_token_num, now_blockchain_token_num=0) + left_blockchain_token_num = Blockchain::BalanceQueryOneProject.call({"user_id": user_id, "project_id": project_id}) rescue 0 + raise ApplicationService::Error, "用户Token不足。" if blockchain_token_num.to_i > (left_blockchain_token_num+now_blockchain_token_num).to_i + end +end diff --git a/app/services/api/v1/issues/concerns/loadable.rb b/app/services/api/v1/issues/concerns/loadable.rb new file mode 100644 index 00000000..df30042e --- /dev/null +++ b/app/services/api/v1/issues/concerns/loadable.rb @@ -0,0 +1,19 @@ +module Api::V1::Issues::Concerns::Loadable + + def load_assigners(assigner_ids) + @assigners = User.where(id: assigner_ids) + end + + def load_issue_tags(issue_tag_ids) + @issue_tags = IssueTag.where(id: issue_tag_ids) + end + + def load_attachments(attachment_ids) + @attachments = Attachment.where(id: attachment_ids) + end + + def load_atme_receivers(receivers_login) + @atme_receivers = User.where(login: receivers_login) + end + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/create_service.rb b/app/services/api/v1/issues/create_service.rb new file mode 100644 index 00000000..c155b69d --- /dev/null +++ b/app/services/api/v1/issues/create_service.rb @@ -0,0 +1,146 @@ +class Api::V1::Issues::CreateService < ApplicationService + include ActiveModel::Model + include Api::V1::Issues::Concerns::Checkable + include Api::V1::Issues::Concerns::Loadable + + attr_reader :project, :current_user + attr_reader :status_id, :priority_id, :milestone_id, :branch_name, :start_date, :due_date, :subject, :description, :blockchain_token_num + attr_reader :issue_tag_ids, :assigner_ids, :attachment_ids, :receivers_login + attr_accessor :created_issue + + validates :subject, presence: true + validates :status_id, :priority_id, presence: true + validates :project, :current_user, presence: true + validates :blockchain_token_num, numericality: {greater_than: 0}, allow_blank: true + + def initialize(project, params, current_user = nil) + @project = project + @current_user = current_user + @status_id = params[:status_id] + @priority_id = params[:priority_id] + @milestone_id = params[:milestone_id] + @branch_name = params[:branch_name] + @start_date = params[:start_date] + @due_date = params[:due_date] + @subject = params[:subject] + @description = params[:description] + @blockchain_token_num = params[:blockchain_token_num] + @issue_tag_ids = params[:issue_tag_ids] + @assigner_ids = params[:assigner_ids] + @attachment_ids = params[:attachment_ids] + @receivers_login = params[:receivers_login] + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + ActiveRecord::Base.transaction do + check_issue_status(status_id) + check_issue_priority(priority_id) + check_milestone(milestone_id) if milestone_id.present? + check_issue_tags(issue_tag_ids) unless issue_tag_ids.blank? + check_assigners(assigner_ids) unless assigner_ids.blank? + check_attachments(attachment_ids) unless attachment_ids.blank? + check_atme_receivers(receivers_login) unless receivers_login.blank? + check_blockchain_token_num(current_user.id, project.id, blockchain_token_num) if blockchain_token_num.present? + load_assigners(assigner_ids) unless assigner_ids.blank? + load_attachments(attachment_ids) unless attachment_ids.blank? + load_issue_tags(issue_tag_ids) unless issue_tag_ids.blank? + load_atme_receivers(receivers_login) unless receivers_login.blank? + + try_lock("Api::V1::Issues::CreateService:#{project.id}") # 开始写数据,加锁 + @created_issue = Issue.new(issue_attributes) + build_author_participants + build_assigner_participants unless assigner_ids.blank? + build_atme_participants if @atme_receivers.present? + build_issue_journal_details + build_issue_project_trends + @created_issue.assigners = @assigners unless assigner_ids.blank? + @created_issue.attachments = @attachments unless attachment_ids.blank? + @created_issue.issue_tags = @issue_tags unless issue_tag_ids.blank? + + @created_issue.issue_tags_value = @issue_tags.order("id asc").pluck(:id).join(",") unless issue_tag_ids.blank? + @created_issue.save! + + if Site.has_blockchain? && @project.use_blockchain + if @created_issue.blockchain_token_num.present? && @created_issue.blockchain_token_num > 0 + Blockchain::CreateIssue.call({user_id: current_user.id, project_id: @created_issue.project_id, token_num: @created_issue.blockchain_token_num}) + end + + push_activity_2_blockchain("issue_create", @created_issue) + end + + project.del_project_issue_cache_delete_count # 把缓存里存储项目删除issue的个数清除掉 + + # 新增时向grimoirelab推送事件 + IssueWebhookJob.set(wait: 5.seconds).perform_later(@created_issue.id) + + # @信息发送 + AtmeService.call(current_user, @atme_receivers, @created_issue) unless receivers_login.blank? + + # 发消息 + if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @created_issue&.id, assigner_ids) unless assigner_ids.blank? + SendTemplateMessageJob.perform_later('ProjectIssue', current_user.id, @created_issue&.id) + end + + # 触发webhook + TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueCreate', @created_issue&.id, current_user.id) + TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueLabel', @created_issue&.id, current_user.id, {issue_tag_ids: [[], issue_tag_ids]}) unless issue_tag_ids.blank? + TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueAssign', @created_issue&.id, current_user.id, {assigner_ids: [[], assigner_ids]}) unless assigner_ids.blank? + unlock("Api::V1::Issues::CreateService:#{project.id}") # 结束写数据,解锁 + end + + return @created_issue + end + + private + + def issue_attributes + issue_attributes = { + subject: subject, + project_id: project.id, + author_id: current_user.id, + tracker_id: Tracker.first.id, + status_id: status_id, + priority_id: priority_id, + project_issues_index: (project.get_last_project_issues_index + 1), + issue_type: "1", + issue_classify: "issue" + } + + issue_attributes.merge!({description: description}) if description.present? + issue_attributes.merge!({fixed_version_id: milestone_id}) if milestone_id.present? + issue_attributes.merge!({start_date: start_date}) if start_date.present? + issue_attributes.merge!({due_date: due_date}) if due_date.present? + issue_attributes.merge!({branch_name: branch_name}) if branch_name.present? + issue_attributes.merge!({blockchain_token_num: blockchain_token_num}) if blockchain_token_num.present? + + issue_attributes + end + + def build_author_participants + @created_issue.issue_participants.new({participant_type: "authored", participant_id: current_user.id}) + end + + def build_assigner_participants + assigner_ids.each do |aid| + @created_issue.issue_participants.new({participant_type: "assigned", participant_id: aid}) + end + end + + def build_atme_participants + @atme_receivers.each do |receiver| + @created_issue.issue_participants.new({participant_type: "atme", participant_id: receiver.id}) + end + end + + def build_issue_project_trends + @created_issue.project_trends.new({user_id: current_user.id, project_id: @project.id, action_type: "create"}) + @created_issue.project_trends.new({user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE}) if status_id.to_i == 5 + end + + def build_issue_journal_details + journal = @created_issue.journals.new({user_id: current_user.id}) + journal.journal_details.new({property: "issue", prop_key: 1, old_value: '', value: ''}) + end +end \ No newline at end of file diff --git a/app/services/api/v1/issues/delete_service.rb b/app/services/api/v1/issues/delete_service.rb new file mode 100644 index 00000000..b6273318 --- /dev/null +++ b/app/services/api/v1/issues/delete_service.rb @@ -0,0 +1,41 @@ +class Api::V1::Issues::DeleteService < ApplicationService + include ActiveModel::Model + + attr_reader :project, :issue, :current_user + + validates :project, :issue, :current_user, presence: true + + def initialize(project, issue, current_user = nil) + @project = project + @issue = issue + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + try_lock("Api::V1::Issues::DeleteService:#{project.id}") # 开始写数据,加锁 + + delete_issue + + project.incre_project_issue_cache_delete_count + + if Site.has_blockchain? && @project.use_blockchain + unlock_balance_on_blockchain(@issue.author_id.to_s, @project.id.to_s, @issue.blockchain_token_num.to_i) if @issue.blockchain_token_num.present? + end + + if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('IssueDeleted', current_user.id, @issue&.subject, @issue.assigners.pluck(:id), @issue.author_id) + end + + unlock("Api::V1::Issues::DeleteService:#{project.id}") + + return true + end + + private + + def delete_issue + raise Error, "删除疑修失败!" unless issue.destroy! + end + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/journals/children_list_service.rb b/app/services/api/v1/issues/journals/children_list_service.rb new file mode 100644 index 00000000..d46f9fbb --- /dev/null +++ b/app/services/api/v1/issues/journals/children_list_service.rb @@ -0,0 +1,42 @@ +class Api::V1::Issues::Journals::ChildrenListService < ApplicationService + + include ActiveModel::Model + + attr_reader :issue, :journal, :keyword, :sort_by, :sort_direction + attr_accessor :queried_journals + + validates :sort_by, inclusion: {in: Journal.column_names, message: '请输入正确的SortBy'}, allow_blank: true + validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}, allow_blank: true + + + def initialize(issue, journal, params, current_user=nil) + @issue = issue + @journal = journal + @keyword = params[:keyword] + @sort_by = params[:sort_by].present? ? params[:sort_by] : 'created_on' + @sort_direction = (params[:sort_direction].present? ? params[:sort_direction] : 'asc').downcase + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + begin + journal_query_data + + return @queried_journals + rescue + raise Error, "服务器错误,请联系系统管理员!" + + end + end + + private + def journal_query_data + @queried_journals = journal.children_journals + + @queried_journals = @queried_journals.ransack(notes_cont: keyword).result if keyword.present? + @queried_journals = @queried_journals.includes(:user, :attachments, :reply_journal) + @queried_journals = @queried_journals.reorder("journals.#{sort_by} #{sort_direction}").distinct + + @queried_journals + end +end \ No newline at end of file diff --git a/app/services/api/v1/issues/journals/create_service.rb b/app/services/api/v1/issues/journals/create_service.rb new file mode 100644 index 00000000..5f57c4f0 --- /dev/null +++ b/app/services/api/v1/issues/journals/create_service.rb @@ -0,0 +1,77 @@ +class Api::V1::Issues::Journals::CreateService < ApplicationService + include ActiveModel::Model + include Api::V1::Issues::Concerns::Checkable + include Api::V1::Issues::Concerns::Loadable + + attr_reader :issue, :current_user, :notes, :parent_id, :reply_id, :attachment_ids, :receivers_login + attr_accessor :created_journal, :atme_receivers + + validates :notes, :issue, :current_user, presence: true + + def initialize(issue, params, current_user=nil) + @issue = issue + @notes = params[:notes] + @parent_id = params[:parent_id] + @reply_id = params[:reply_id] + @attachment_ids = params[:attachment_ids] + @receivers_login = params[:receivers_login] + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + raise Error, "请输入回复的评论ID" if parent_id.present? && !reply_id.present? + ActiveRecord::Base.transaction do + check_parent_journal(parent_id) if parent_id.present? + check_parent_journal(reply_id) if reply_id.present? + check_attachments(attachment_ids) unless attachment_ids.nil? + check_atme_receivers(receivers_login) unless receivers_login.nil? + load_attachments(attachment_ids) unless attachment_ids.nil? + load_atme_receivers(receivers_login) unless receivers_login.nil? + + try_lock("Api::V1::Issues::Journals::CreateService:#{@issue.id}") + @created_journal = @issue.journals.new(journal_attributes) + + build_comment_participants + build_atme_participants if @atme_receivers.present? + @created_journal.attachments = @attachments unless attachment_ids.blank? + + @created_journal.save! + @issue.save! + + push_activity_2_blockchain("issue_comment_create", @created_journal) if Site.has_blockchain? && @issue.project&.use_blockchain + + # @信息发送 + AtmeService.call(current_user, @atme_receivers, @created_journal) unless receivers_login.blank? + TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueComment', @issue&.id, @current_user.id, @created_journal.id, 'created', {}) + unlock("Api::V1::Issues::Journals::CreateService:#{@issue.id}") + + @created_journal + end + end + + private + + def journal_attributes + journal_attributes = { + notes: notes, + user_id: current_user.id + } + + journal_attributes.merge!({parent_id: parent_id}) if parent_id.present? + journal_attributes.merge!({reply_id: reply_id}) if reply_id.present? + + journal_attributes + end + + def build_comment_participants + @issue.issue_participants.new({participant_type: "commented", participant_id: current_user.id}) unless @issue.issue_participants.exists?(participant_type: "commented", participant_id: current_user.id) + end + + def build_atme_participants + @atme_receivers.each do |receiver| + next if @issue.issue_participants.exists?(participant_type: "atme", participant_id: receiver.id) + @issue.issue_participants.new({participant_type: "atme", participant_id: receiver.id}) + end + end +end \ No newline at end of file diff --git a/app/services/api/v1/issues/journals/list_service.rb b/app/services/api/v1/issues/journals/list_service.rb new file mode 100644 index 00000000..486fa5d3 --- /dev/null +++ b/app/services/api/v1/issues/journals/list_service.rb @@ -0,0 +1,56 @@ +class Api::V1::Issues::Journals::ListService < ApplicationService + + include ActiveModel::Model + + attr_reader :issue, :category, :keyword, :sort_by, :sort_direction + attr_accessor :queried_journals, :total_journals_count, :total_operate_journals_count, :total_comment_journals_count + + validates :category, inclusion: {in: %w(all comment operate), message: "请输入正确的Category"} + validates :sort_by, inclusion: {in: Journal.column_names, message: '请输入正确的SortBy'}, allow_blank: true + validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}, allow_blank: true + + def initialize(issue, params, current_user=nil) + @issue = issue + @keyword = params[:keyword] + @category = params[:category] || 'all' + @sort_by = params[:sort_by].present? ? params[:sort_by] : 'created_on' + @sort_direction = (params[:sort_direction].present? ? params[:sort_direction] : 'asc').downcase + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + begin + journal_query_data + + {data: @queried_journals, total_journals_count: @total_journals_count, total_operate_journals_count: total_operate_journals_count, total_comment_journals_count: total_comment_journals_count} + rescue + raise Error, "服务器错误,请联系系统管理员!" + end + end + + private + def journal_query_data + + @queried_journals = issue.journals + + @queried_journals = @queried_journals.parent_journals + + @queried_journals = @queried_journals.ransack(notes_cont: keyword).result if keyword.present? + + @total_journals_count = queried_journals.distinct.size + @total_operate_journals_count = @queried_journals.where(notes: nil).distinct.size + @total_comment_journals_count = @queried_journals.where.not(notes: nil).distinct.size + + case category + when 'comment' + @queried_journals = @queried_journals.where.not(notes: nil) + when 'operate' + @queried_journals = @queried_journals.where(notes: nil) + end + + @queried_journals = @queried_journals.includes(:journal_details, :user, :attachments, first_ten_children_journals: [:parent_journal, :reply_journal]) + @queried_journals = @queried_journals.reorder("journals.#{sort_by} #{sort_direction}").distinct + + @queried_journals + end +end \ No newline at end of file diff --git a/app/services/api/v1/issues/journals/update_service.rb b/app/services/api/v1/issues/journals/update_service.rb new file mode 100644 index 00000000..c771d5c1 --- /dev/null +++ b/app/services/api/v1/issues/journals/update_service.rb @@ -0,0 +1,58 @@ +class Api::V1::Issues::Journals::UpdateService < ApplicationService + include ActiveModel::Model + include Api::V1::Issues::Concerns::Checkable + include Api::V1::Issues::Concerns::Loadable + + attr_reader :issue, :journal, :current_user, :notes, :attachment_ids, :receivers_login + attr_accessor :updated_journal, :atme_receivers + + validates :notes, :issue, :journal, :current_user, presence: true + + def initialize(issue, journal, params, current_user=nil) + @issue = issue + @journal = journal + @notes = params[:notes] + @attachment_ids = params[:attachment_ids] + @receivers_login = params[:receivers_login] + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + ActiveRecord::Base.transaction do + check_attachments(attachment_ids) unless attachment_ids.nil? + check_atme_receivers(receivers_login) unless receivers_login.nil? + load_attachments(attachment_ids) unless attachment_ids.nil? + load_atme_receivers(receivers_login) unless receivers_login.nil? + + try_lock("Api::V1::Issues::Journals::UpdateService:#{@issue.id}:#{@journal.id}") + @updated_journal = @journal + @updated_journal.notes = notes + + build_atme_participants if @atme_receivers.present? + + @updated_journal.attachments = @attachments unless attachment_ids.nil? + + @updated_journal.save! + @issue.save! + + # @信息发送 + AtmeService.call(current_user, @atme_receivers, @created_journal) unless receivers_login.blank? + TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueComment', @issue&.id, @current_user.id, @updated_journal.id, 'edited', @updated_journal.previous_changes.slice(:notes).stringify_keys) + + unlock("Api::V1::Issues::Journals::UpdateService:#{@issue.id}:#{@journal.id}") + + @updated_journal + end + end + + private + + def build_atme_participants + @atme_receivers.each do |receiver| + next if @issue.issue_participants.exists?(participant_type: "atme", participant_id: receiver.id) + @issue.issue_participants.new({participant_type: "atme", participant_id: receiver.id}) + end + end + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/list_service.rb b/app/services/api/v1/issues/list_service.rb new file mode 100644 index 00000000..5a3f97e9 --- /dev/null +++ b/app/services/api/v1/issues/list_service.rb @@ -0,0 +1,103 @@ +class Api::V1::Issues::ListService < ApplicationService + include ActiveModel::Model + + attr_reader :project, :only_name, :category, :participant_category, :keyword, :author_id, :issue_tag_ids + attr_reader :begin_date, :end_date + attr_reader :milestone_id, :assigner_id, :status_id, :sort_by, :sort_direction, :current_user + attr_accessor :queried_issues, :total_issues_count, :closed_issues_count, :opened_issues_count + + validates :category, inclusion: {in: %w(all opened closed), message: "请输入正确的Category"} + validates :participant_category, inclusion: {in: %w(all aboutme authoredme assignedme atme), message: "请输入正确的ParticipantCategory"} + validates :sort_by, inclusion: {in: ['issues.created_on', 'issues.updated_on', 'issues.blockchain_token_num', 'issue_priorities.position'], message: '请输入正确的SortBy'}, allow_blank: true + validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}, allow_blank: true + validates :current_user, presence: true + + def initialize(project, params, current_user=nil) + @project = project + @only_name = params[:only_name] + @category = params[:category] || 'all' + @participant_category = params[:participant_category] || 'all' + @keyword = params[:keyword] + @author_id = params[:author_id] + @issue_tag_ids = params[:issue_tag_ids].present? ? params[:issue_tag_ids].split(",") : [] + @milestone_id = params[:milestone_id] + @assigner_id = params[:assigner_id] + @status_id = params[:status_id] + @begin_date = params[:begin_date] + @end_date = params[:end_date] + @sort_by = params[:sort_by].present? ? params[:sort_by] : 'issues.updated_on' + @sort_direction = (params[:sort_direction].present? ? params[:sort_direction] : 'desc').downcase + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + # begin + issue_query_data + + return {data: queried_issues, total_issues_count: @total_issues_count, closed_issues_count: @closed_issues_count, opened_issues_count: @opened_issues_count} + # rescue + # raise Error, "服务器错误,请联系系统管理员!" + # end + end + + private + def issue_query_data + issues = @project.issues.issue_issue + + case participant_category + when 'aboutme' # 关于我的 + issues = issues.joins(:issue_participants).where(issue_participants: {participant_type: %w(authored assigned atme), participant_id: current_user&.id}) + when 'authoredme' # 我创建的 + issues = issues.joins(:issue_participants).where(issue_participants: {participant_type: 'authored', participant_id: current_user&.id}) + when 'assignedme' # 我负责的 + issues = issues.joins(:issue_participants).where(issue_participants: {participant_type: 'assigned', participant_id: current_user&.id}) + when 'atme' # @我的 + issues = issues.joins(:issue_participants).where(issue_participants: {participant_type: 'atme', participant_id: current_user&.id}) + end + + # author_id + issues = issues.where(author_id: author_id) if author_id.present? + + # issue_tag_ids + issues = issues.ransack(issue_tags_value_cont: issue_tag_ids.sort!.join(",")).result unless issue_tag_ids.blank? + + # milestone_id + issues = issues.where(fixed_version_id: milestone_id) if milestone_id.present? + + # assigner_id + issues = issues.joins(:assigners).where(users: {id: assigner_id}) if assigner_id.present? + + # status_id + issues = issues.where(status_id: status_id) if status_id.present? && category != 'closed' + + if begin_date&.present? || end_date&.present? + issues = issues.where("issues.created_on between ? and ?", begin_date&.present? ? begin_date.to_time : Time.now.beginning_of_day, end_date&.present? ? end_date.to_time.end_of_day : Time.now.end_of_day) + end + + # keyword + issues = issues.ransack(id_eq: keyword).result.or(issues.ransack(subject_or_description_cont: keyword).result) if keyword.present? + + @total_issues_count = issues.distinct.size + @closed_issues_count = issues.closed.distinct.size + @opened_issues_count = issues.opened.distinct.size + + case category + when 'closed' + issues = issues.closed + when 'opened' + issues = issues.opened + end + + if only_name.present? + scope = issues.select(:id, :subject, :project_issues_index, :updated_on, :created_on) + scope = scope.reorder("#{sort_by} #{sort_direction}").distinct + else + scope = issues.includes(:priority, :issue_status, :user, :show_assigners, :show_issue_tags, :version, :comment_journals) + scope = scope.reorder("#{sort_by} #{sort_direction}").distinct + end + + @queried_issues = scope + end + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/milestones/detail_issues_service.rb b/app/services/api/v1/issues/milestones/detail_issues_service.rb new file mode 100644 index 00000000..8b6f69ae --- /dev/null +++ b/app/services/api/v1/issues/milestones/detail_issues_service.rb @@ -0,0 +1,65 @@ +class Api::V1::Issues::Milestones::DetailIssuesService < ApplicationService + include ActiveModel::Model + + attr_reader :project, :category, :author_id, :assigner_id, :issue_tag_ids, :sort_by, :sort_direction, :current_user + attr_accessor :queried_issues, :total_issues_count, :closed_issues_count, :opened_issues_count + + validates :category, inclusion: {in: %w(all opened closed), message: "请输入正确的Category"} + validates :sort_by, inclusion: {in: ['issues.created_on', 'issues.updated_on', 'issue_priorities.position'], message: '请输入正确的SortBy'}, allow_blank: true + validates :sort_direction, inclusion: {in: %w(asc desc), message: '请输入正确的SortDirection'}, allow_blank: true + validates :current_user, presence: true + + def initialize(project, milestone, params, current_user=nil) + @project = project + @milestone = milestone + @category = params[:category] || 'all' + @author_id = params[:author_id] + @assigner_id = params[:assigner_id] + @issue_tag_ids = params[:issue_tag_ids].present? ? params[:issue_tag_ids].split(",") : [] + @sort_by = params[:sort_by].present? ? params[:sort_by] : 'issues.updated_on' + @sort_direction = (params[:sort_direction].present? ? params[:sort_direction] : 'desc').downcase + @current_user = current_user + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + begin + issue_query_data + + return {data: queried_issues, total_issues_count: @total_issues_count, closed_issues_count: @closed_issues_count, opened_issues_count: @opened_issues_count} + rescue + raise Error, "服务器错误,请联系系统管理员!" + end + end + + private + def issue_query_data + issues = @milestone.issues.issue_issue + + # author_id + issues = issues.where(author_id: author_id) if author_id.present? + + # assigner_id + issues = issues.joins(:assigners).where(users: {id: assigner_id}).or(issues.joins(:assigners).where(assigned_to_id: assigner_id)) if assigner_id.present? + + issues = issues.ransack(issue_tags_value_cont: issue_tag_ids.sort!.join(",")).result unless issue_tag_ids.blank? + + @total_issues_count = issues.distinct.size + @closed_issues_count = issues.closed.distinct.size + @opened_issues_count = issues.opened.distinct.size + + case category + when 'closed' + issues = issues.closed + when 'opened' + issues = issues.opened + end + + scope = issues.includes(:priority, :issue_status, :user, :show_assigners, :version, :show_issue_tags, :comment_journals).references(:assigners) + + scope = scope.reorder("#{sort_by} #{sort_direction}").distinct + + @queried_issues = scope + end + +end \ No newline at end of file diff --git a/app/services/api/v1/issues/update_service.rb b/app/services/api/v1/issues/update_service.rb new file mode 100644 index 00000000..d55c0f58 --- /dev/null +++ b/app/services/api/v1/issues/update_service.rb @@ -0,0 +1,264 @@ +class Api::V1::Issues::UpdateService < ApplicationService + include ActiveModel::Model + include Api::V1::Issues::Concerns::Checkable + include Api::V1::Issues::Concerns::Loadable + + attr_reader :project, :issue, :current_user + attr_reader :status_id, :priority_id, :milestone_id, :branch_name, :start_date, :due_date, :subject, :description, :blockchain_token_num + attr_reader :issue_tag_ids, :assigner_ids, :attachment_ids, :receivers_login, :before_issue_tag_ids, :before_assigner_ids + attr_accessor :add_assigner_ids, :previous_issue_changes, :updated_issue, :atme_receivers + + validates :project, :issue, :current_user, presence: true + validates :blockchain_token_num, numericality: {greater_than: 0}, allow_blank: true + + def initialize(project, issue, params, current_user = nil) + @project = project + @issue = issue + @current_user = current_user + @status_id = params[:status_id] + @priority_id = params[:priority_id] + @milestone_id = params[:milestone_id] + @branch_name = params[:branch_name] + @start_date = params[:start_date] + @due_date = params[:due_date] + @subject = params[:subject] + @description = params[:description] + @blockchain_token_num = params[:blockchain_token_num] + @issue_tag_ids = params[:issue_tag_ids] + @assigner_ids = params[:assigner_ids] + @before_issue_tag_ids = issue.issue_tags.pluck(:id) + @before_assigner_ids = issue.assigners.pluck(:id) + @attachment_ids = params[:attachment_ids] + @receivers_login = params[:receivers_login] + @add_assigner_ids = [] + @previous_issue_changes = {} + end + + def call + raise Error, errors.full_messages.join(", ") unless valid? + ActiveRecord::Base.transaction do + check_issue_status(status_id) if status_id.present? + check_issue_priority(priority_id) if priority_id.present? + check_milestone(milestone_id) if milestone_id.present? + check_issue_tags(issue_tag_ids) unless issue_tag_ids.nil? + check_assigners(assigner_ids) unless assigner_ids.nil? + check_attachments(attachment_ids) unless attachment_ids.nil? + check_atme_receivers(receivers_login) unless receivers_login.nil? + check_blockchain_token_num(issue.author_id, project.id, blockchain_token_num, (@issue.blockchain_token_num || 0)) if blockchain_token_num.present? && current_user.id == @issue.author_id && !PullAttachedIssue.exists?(issue_id: @issue, fixed: true) + load_assigners(assigner_ids) + load_attachments(attachment_ids) + load_issue_tags(issue_tag_ids) + load_atme_receivers(receivers_login) unless receivers_login.nil? + + try_lock("Api::V1::Issues::UpdateService:#{project.id}:#{issue.id}") + @updated_issue = @issue + issue_load_attributes + build_assigner_issue_journal_details unless assigner_ids.nil?# 操作记录 + build_attachment_issue_journal_details unless attachment_ids.nil? + build_issue_tag_issue_journal_details unless issue_tag_ids.nil? + build_issue_project_trends if status_id.present? # 开关时间记录 + build_assigner_participants unless assigner_ids.nil? # 负责人 + build_edit_participants + build_atme_participants if @atme_receivers.present? + unless assigner_ids.nil? + @previous_issue_changes.merge!(assigned_to_id: [@updated_issue.assigners.pluck(:id), @assigners.pluck(:id)]) + @updated_issue.assigners = @assigners || User.none + end + @updated_issue.attachments = @attachments || Attachment.none unless attachment_ids.nil? + @updated_issue.issue_tags_relates.destroy_all & @updated_issue.issue_tags = @issue_tags || IssueTag.none unless issue_tag_ids.nil? + @updated_issue.issue_tags_value = @issue_tags.order("id asc").pluck(:id).join(",") unless issue_tag_ids.nil? + + @updated_issue.updated_on = Time.now + @updated_issue.save! + + build_after_issue_journal_details if @updated_issue.previous_changes.present? # 操作记录 + build_previous_issue_changes + build_cirle_blockchain_token if blockchain_token_num.present? + + # @信息发送 + AtmeService.call(current_user, @atme_receivers, @issue) unless receivers_login.blank? + # 消息发送 + if Site.has_notice_menu? + SendTemplateMessageJob.perform_later('IssueChanged', current_user.id, @issue&.id, previous_issue_changes) unless previous_issue_changes.blank? + SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id, add_assigner_ids) unless add_assigner_ids.blank? + end + + unlock("Api::V1::Issues::UpdateService:#{project.id}:#{issue.id}") + # 触发webhook + Rails.logger.info "################### 触发webhook" + TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueUpdate', @updated_issue&.id, current_user.id, previous_issue_changes.except(:issue_tags_value, :assigned_to_id)) + TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueLabel', @issue&.id, current_user.id, {issue_tag_ids: [before_issue_tag_ids, issue_tag_ids]}) unless issue_tag_ids.nil? + TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueAssign', @issue&.id, current_user.id, {assigner_ids: [before_assigner_ids, assigner_ids]}) unless assigner_ids.nil? + + return @updated_issue + end + end + + private + + def issue_load_attributes + if current_user.id == @updated_issue.author_id && !PullAttachedIssue.exists?(issue_id: @updated_issue, fixed: true) + @updated_issue.blockchain_token_num = blockchain_token_num unless blockchain_token_num.nil? + end + @updated_issue.status_id = status_id if status_id.present? + @updated_issue.priority_id = priority_id if priority_id.present? + @updated_issue.fixed_version_id = milestone_id unless milestone_id.nil? + @updated_issue.branch_name = branch_name unless branch_name.nil? + @updated_issue.start_date = start_date unless start_date.nil? + @updated_issue.due_date = due_date unless due_date.nil? + @updated_issue.subject = subject if subject.present? + @updated_issue.description = description unless description.nil? + end + + def build_assigner_participants + if assigner_ids.blank? + @updated_issue.issue_participants.where(participant_type: "assigned").each(&:destroy!) + else + @updated_issue.issue_participants.where(participant_type: "assigned").where.not(participant_id: assigner_ids).each(&:destroy!) + assigner_ids.each do |aid| + next if @updated_issue.issue_participants.exists?(participant_type: "assigned", participant_id: aid) + @updated_issue.issue_participants.new({participant_type: "assigned", participant_id: aid}) + @add_assigner_ids << aid + end + end + end + + def build_edit_participants + @updated_issue.issue_participants.new({participant_type: "edited", participant_id: current_user.id}) unless @updated_issue.issue_participants.exists?(participant_type: "edited", participant_id: current_user.id) + end + + def build_atme_participants + @atme_receivers.each do |receiver| + next if @updated_issue.issue_participants.exists?(participant_type: "atme", participant_id: receiver.id) + @updated_issue.issue_participants.new({participant_type: "atme", participant_id: receiver.id}) + end + end + + def build_previous_issue_changes + @previous_issue_changes.merge!(@updated_issue.previous_changes.slice("status_id", "priority_id", "fixed_version_id", "issue_tags_value", "branch_name", "subject", "description").symbolize_keys) + if @updated_issue.previous_changes[:start_date].present? + @previous_issue_changes.merge!(start_date: [@updated_issue.previous_changes[:start_date][0].to_s, @updated_issue.previous_changes[:start_date][1].to_s]) + end + if @updated_issue.previous_changes[:due_date].present? + @previous_issue_changes.merge!(due_date: [@updated_issue.previous_changes[:due_date][0].to_s, @updated_issue.previous_changes[:due_date][1].to_s]) + end + end + + def build_cirle_blockchain_token + if @updated_issue.previous_changes["blockchain_token_num"].present? + unlock_balance_on_blockchain(@updated_issue&.author_id.to_s, @updated_issue.project_id.to_s, @updated_issue.previous_changes["blockchain_token_num"][0].to_i) if @updated_issue.previous_changes["blockchain_token_num"][0].present? + lock_balance_on_blockchain(@updated_issue&.author_id.to_s, @updated_issue.project_id.to_s, @updated_issue.previous_changes["blockchain_token_num"][1].to_i) if @updated_issue.previous_changes["blockchain_token_num"][1].present? + end + end + + def build_issue_project_trends + if @updated_issue.previous_changes["status_id"].present? && @updated_issue.previous_changes["status_id"][1] == 5 + @updated_issue.project_trends.new({user_id: current_user.id, project_id: @project.id, action_type: ProjectTrend::CLOSE}) + end + if @updated_issue.previous_changes["status_id"].present? && @updated_issue.previous_changes["status_id"][0] == 5 + @updated_issue.project_trends.where(action_type: ProjectTrend::CLOSE).each(&:destroy!) + end + end + + def build_after_issue_journal_details + begin + # 更改标题 + if @updated_issue.previous_changes["subject"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "subject", old_value: @updated_issue.previous_changes["subject"][0], value: @updated_issue.previous_changes["subject"][1]}) + end + + # 更改描述 + if @updated_issue.previous_changes["description"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "description", old_value: @updated_issue.previous_changes["description"][0], value: @updated_issue.previous_changes["description"][1]}) + end + + # 修改状态 + if @updated_issue.previous_changes["status_id"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "status_id", old_value: @updated_issue.previous_changes["status_id"][0], value: @updated_issue.previous_changes["status_id"][1]}) + end + + # 修改优先级 + if @updated_issue.previous_changes["priority_id"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "priority_id", old_value: @updated_issue.previous_changes["priority_id"][0], value: @updated_issue.previous_changes["priority_id"][1]}) + end + + # 修改里程碑 + if @updated_issue.previous_changes["fixed_version_id"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "fixed_version_id", old_value: @updated_issue.previous_changes["fixed_version_id"][0], value: @updated_issue.previous_changes["fixed_version_id"][1]}) + end + + # 更改分支 + if @updated_issue.previous_changes["branch_name"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "branch_name", old_value: @updated_issue.previous_changes["branch_name"][0], value: @updated_issue.previous_changes["branch_name"][1]}) + end + + # 更改开始时间 + if @updated_issue.previous_changes["start_date"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "start_date", old_value: @updated_issue.previous_changes["start_date"][0], value: @updated_issue.previous_changes["start_date"][1]}) + end + + # 更改结束时间 + if @updated_issue.previous_changes["due_date"].present? + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attr", prop_key: "due_date", old_value: @updated_issue.previous_changes["due_date"][0], value: @updated_issue.previous_changes["due_date"][1]}) + end + rescue + raise Error, "创建操作记录失败!" + end + end + + def build_assigner_issue_journal_details + begin + # 更改负责人 + new_assigner_ids = @assigner_ids + new_assigner_ids = [] if @assigner_ids.nil? + now_assigner_ids = @updated_issue.assigners.pluck(:id) + if !(now_assigner_ids & assigner_ids).empty? || !(now_assigner_ids.empty? && new_assigner_ids.empty?) + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "assigner", prop_key: "#{new_assigner_ids.size}", old_value: now_assigner_ids.join(","), value: new_assigner_ids.join(",")}) + end + + rescue + raise Error, "创建操作记录失败!" + end + end + + def build_issue_tag_issue_journal_details + begin + # 更改标记 + new_issue_tag_ids = @issue_tag_ids + new_issue_tag_ids = [] if @issue_tag_ids.nil? + now_issue_tag_ids = @updated_issue.issue_tags.pluck(:id) + if !(now_issue_tag_ids & new_issue_tag_ids).empty? || !(now_issue_tag_ids.empty? && new_issue_tag_ids.empty?) + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "issue_tag", prop_key: "#{new_issue_tag_ids.size}", old_value: now_issue_tag_ids.join(","), value: new_issue_tag_ids.join(",")}) + end + rescue + raise Error, "创建操作记录失败!" + end + end + + + def build_attachment_issue_journal_details + begin + # 更改附件 + new_attachment_ids = @attachment_ids + new_attachment_ids = [] if @attachment_ids.nil? + now_attachment_ids = @updated_issue.attachments.pluck(:id) + if !(now_attachment_ids & new_attachment_ids).empty? || !(now_attachment_ids.empty? && new_attachment_ids.empty?) + journal = @updated_issue.journals.create!({user_id: current_user.id}) + journal.journal_details.create!({property: "attachment", prop_key: "#{new_attachment_ids.size}", old_value: now_attachment_ids.join(","), value: new_attachment_ids.join(",")}) + end + rescue + raise Error, "创建操作记录失败!" + end + end + +end \ No newline at end of file diff --git a/app/services/api/v1/projects/blame_service.rb b/app/services/api/v1/projects/blame_service.rb index d419fec1..cdd5739b 100644 --- a/app/services/api/v1/projects/blame_service.rb +++ b/app/services/api/v1/projects/blame_service.rb @@ -32,7 +32,7 @@ class Api::V1::Projects::BlameService < ApplicationService end def load_gitea_data - @gitea_data = $gitea_client.get_repos_blame_by_owner_repo(owner, repo, {query: request_params}) + @gitea_data = $gitea_hat_client.get_repos_blame_by_owner_repo(owner, repo, {query: request_params}) raise Error, '获取项目blame失败!' unless @gitea_data.is_a?(Hash) end end \ No newline at end of file diff --git a/app/services/api/v1/projects/branches/all_list_service.rb b/app/services/api/v1/projects/branches/all_list_service.rb index 182495cd..9ca4ae7d 100644 --- a/app/services/api/v1/projects/branches/all_list_service.rb +++ b/app/services/api/v1/projects/branches/all_list_service.rb @@ -24,7 +24,7 @@ class Api::V1::Projects::Branches::AllListService < ApplicationService end def load_gitea_data - @gitea_data = $gitea_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil - raise Error, '获取所有分支失败!' unless @gitea_data.is_a?(Hash) + @gitea_data = $gitea_hat_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil + raise Error, '获取所有分支失败!' unless @gitea_data.is_a?(Array) end end \ No newline at end of file diff --git a/app/services/api/v1/projects/branches/create_service.rb b/app/services/api/v1/projects/branches/create_service.rb index eae3779f..39964e40 100644 --- a/app/services/api/v1/projects/branches/create_service.rb +++ b/app/services/api/v1/projects/branches/create_service.rb @@ -44,9 +44,9 @@ class Api::V1::Projects::Branches::CreateService < ApplicationService end def check_branch_exist - result = $gitea_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil - raise Error, '查询分支名称失败!' unless result.is_a?(Hash) - raise Error, '旧分支不存在!' if !result['branch_name'].include?(@old_branch_name) - raise Error, '新分支已存在!' if result['branch_name'].include?(@new_branch_name) + result = $gitea_hat_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil + raise Error, '查询分支名称失败!' unless result.is_a?(Array) + raise Error, '旧分支不存在!' if !result.include?(@old_branch_name) + raise Error, '新分支已存在!' if result.include?(@new_branch_name) end end \ No newline at end of file diff --git a/app/services/api/v1/projects/branches/delete_service.rb b/app/services/api/v1/projects/branches/delete_service.rb index 79a6ba0d..28836c79 100644 --- a/app/services/api/v1/projects/branches/delete_service.rb +++ b/app/services/api/v1/projects/branches/delete_service.rb @@ -40,8 +40,8 @@ class Api::V1::Projects::Branches::DeleteService < ApplicationService end def check_branch_exist - result = $gitea_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil - raise Error, '查询分支名称失败!' unless result.is_a?(Hash) - raise Error, '分支不存在!' if !result['branch_name'].include?(@branch_name) + result = $gitea_hat_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil + raise Error, '查询分支名称失败!' unless result.is_a?(Array) + raise Error, '分支不存在!' if !result.include?(@branch_name) end end \ No newline at end of file diff --git a/app/services/api/v1/projects/branches/list_service.rb b/app/services/api/v1/projects/branches/list_service.rb index e5c6fe44..590c4884 100644 --- a/app/services/api/v1/projects/branches/list_service.rb +++ b/app/services/api/v1/projects/branches/list_service.rb @@ -1,7 +1,7 @@ class Api::V1::Projects::Branches::ListService < ApplicationService attr_accessor :project, :token, :owner, :repo, :name, :page, :limit - attr_accessor :gitea_data + attr_accessor :gitea_data, :gitea_repo_data def initialize(project, params, token=nil) @project = project @@ -15,8 +15,11 @@ class Api::V1::Projects::Branches::ListService < ApplicationService def call load_gitea_data - - gitea_data + load_default_branch + + @gitea_data[:default_branch] = @gitea_repo_data["default_branch"] + + @gitea_data end private @@ -32,9 +35,12 @@ class Api::V1::Projects::Branches::ListService < ApplicationService end def load_gitea_data - puts request_params - @gitea_data = $gitea_client.get_repos_branches_by_owner_repo(owner, repo, {query: request_params}) rescue nil - puts @gitea_data + @gitea_data = $gitea_hat_client.get_repos_branches_by_owner_repo(owner, repo, {query: request_params}) rescue nil raise Error, '获取分支列表失败!' unless @gitea_data.is_a?(Hash) end + + def load_default_branch + @gitea_repo_data = $gitea_client.get_repos_by_owner_repo(owner, repo) rescue nil + raise Error, '获取仓库信息失败!' unless @gitea_data.is_a?(Hash) + end end \ No newline at end of file diff --git a/app/services/api/v1/projects/branches/update_default_branch_service.rb b/app/services/api/v1/projects/branches/update_default_branch_service.rb index 5c220aa5..c79c33bd 100644 --- a/app/services/api/v1/projects/branches/update_default_branch_service.rb +++ b/app/services/api/v1/projects/branches/update_default_branch_service.rb @@ -48,8 +48,8 @@ class Api::V1::Projects::Branches::UpdateDefaultBranchService < ApplicationServi end def check_branch_exist - result = $gitea_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil - raise Error, '查询分支名称失败!' unless result.is_a?(Hash) - raise Error, '新默认分支不存在!' if !result['branch_name'].include?(@new_default_branch) + result = $gitea_hat_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil + raise Error, '查询分支名称失败!' unless result.is_a?(Array) + raise Error, '新默认分支不存在!' if !result.include?(@new_default_branch) end end \ No newline at end of file diff --git a/app/services/api/v1/projects/code_stats/list_service.rb b/app/services/api/v1/projects/code_stats/list_service.rb index a5e330e2..0831bc72 100644 --- a/app/services/api/v1/projects/code_stats/list_service.rb +++ b/app/services/api/v1/projects/code_stats/list_service.rb @@ -28,7 +28,7 @@ class Api::V1::Projects::CodeStats::ListService < ApplicationService end def load_gitea_data - @gitea_data = $gitea_client.get_repos_code_stats_by_owner_repo(owner, repo, {query: request_params}) rescue nil + @gitea_data = $gitea_hat_client.get_repos_code_stats_by_owner_repo(owner, repo, {query: request_params}) rescue nil raise Error, '获取贡献者贡献度失败!' unless @gitea_data.is_a?(Hash) end end \ No newline at end of file diff --git a/app/services/api/v1/projects/commits/diff_service.rb b/app/services/api/v1/projects/commits/diff_service.rb index 71dd155a..3de96fba 100644 --- a/app/services/api/v1/projects/commits/diff_service.rb +++ b/app/services/api/v1/projects/commits/diff_service.rb @@ -29,7 +29,7 @@ class Api::V1::Projects::Commits::DiffService < ApplicationService end def load_gitea_data - @gitea_data = $gitea_client.get_repos_commits_diff_by_owner_repo_sha(owner, repo, sha, {query: request_params}) rescue nil + @gitea_data = $gitea_hat_client.get_repos_commits_diff_by_owner_repo_sha(owner, repo, sha, {query: request_params}) rescue nil raise Error, '获取提交对比失败!' unless @gitea_data.is_a?(Hash) end diff --git a/app/services/api/v1/projects/contents/batch_create_service.rb b/app/services/api/v1/projects/contents/batch_create_service.rb index 92bd30a9..6503fd88 100644 --- a/app/services/api/v1/projects/contents/batch_create_service.rb +++ b/app/services/api/v1/projects/contents/batch_create_service.rb @@ -78,15 +78,15 @@ class Api::V1::Projects::Contents::BatchCreateService < ApplicationService def excute_data_to_gitea puts request_body.to_json - @gitea_data = $gitea_client.post_repos_contents_batch_by_owner_repo(owner, repo, {body: request_body.to_json, query: request_params}) rescue nil + @gitea_data = $gitea_hat_client.post_repos_contents_batch_by_owner_repo(owner, repo, {body: request_body.to_json, query: request_params}) rescue nil raise Error, '提交文件失败!' unless @gitea_data.is_a?(Hash) end def check_branch_exist - result = $gitea_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params} ) rescue nil - raise Error, '查询分支名称失败!' unless result.is_a?(Hash) - raise Error, '分支不存在!' unless result['branch_name'].include?(branch) - raise Error, '分支已存在!' if result['branch_name'].include?(new_branch) && !new_branch.nil? + result = $gitea_hat_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params} ) rescue nil + raise Error, '查询分支名称失败!' unless result.is_a?(Array) + raise Error, '分支不存在!' unless result.include?(branch) + raise Error, '分支已存在!' if result.include?(new_branch) && !new_branch.nil? end end \ No newline at end of file diff --git a/app/services/api/v1/projects/contributors/stat_service.rb b/app/services/api/v1/projects/contributors/stat_service.rb new file mode 100644 index 00000000..d264a109 --- /dev/null +++ b/app/services/api/v1/projects/contributors/stat_service.rb @@ -0,0 +1,38 @@ +class Api::V1::Projects::Contributors::StatService < ApplicationService + + attr_reader :project, :branch, :pass_year, :owner, :repo, :token, :page, :limit + attr_accessor :gitea_data + + def initialize(project, params, token=nil) + @project = project + @branch = params[:branch] + @pass_year = params[:pass_year] + @page = params[:page] || 1 + @limit = params[:limit] || 15 + @owner = project&.owner.login + @repo = project&.identifier + @token = token + end + + def call + load_gitea_data + + gitea_data + end + + private + def request_params + param = { + access_token: token + } + param.merge!(branch: branch) if branch.present? + param.merge!(pass_year: pass_year) if pass_year.present? + + param + end + + def load_gitea_data + @gitea_data = $gitea_hat_client.get_repos_contributors_stat_by_owner_repo(owner, repo, {query: request_params}) rescue nil + raise Error, '获取贡献者(代码行)失败!' unless @gitea_data.is_a?(Hash) + end +end \ No newline at end of file diff --git a/app/services/api/v1/projects/get_service.rb b/app/services/api/v1/projects/get_service.rb index ebb0d1cf..480744bf 100644 --- a/app/services/api/v1/projects/get_service.rb +++ b/app/services/api/v1/projects/get_service.rb @@ -45,6 +45,6 @@ class Api::V1::Projects::GetService < ApplicationService end def load_gitea_branch_tag_count - @gitea_branch_tag_count = $gitea_client.get_repos_branch_tag_count_by_owner_repo(owner, repo, {query: request_params}) rescue nil + @gitea_branch_tag_count = $gitea_hat_client.get_repos_branch_tag_count_by_owner_repo(owner, repo, {query: request_params}) rescue nil end end \ No newline at end of file diff --git a/app/services/api/v1/projects/pulls/get_service.rb b/app/services/api/v1/projects/pulls/get_service.rb index 3c1bba99..f28881ae 100644 --- a/app/services/api/v1/projects/pulls/get_service.rb +++ b/app/services/api/v1/projects/pulls/get_service.rb @@ -26,7 +26,7 @@ class Api::V1::Projects::Pulls::GetService < ApplicationService end def load_gitea_data - @gitea_data = $gitea_client.get_repos_pulls_by_owner_repo_index(owner, repo, index, {query: request_params}) + @gitea_data = $gitea_hat_client.get_repos_pulls_by_owner_repo_index(owner, repo, index, {query: request_params}) # raise Error, '获取合并请求失败!' unless @gitea_data.is_a?(Hash) end end \ No newline at end of file diff --git a/app/services/api/v1/projects/pulls/journals/create_service.rb b/app/services/api/v1/projects/pulls/journals/create_service.rb index df207771..051c6777 100644 --- a/app/services/api/v1/projects/pulls/journals/create_service.rb +++ b/app/services/api/v1/projects/pulls/journals/create_service.rb @@ -30,6 +30,8 @@ class Api::V1::Projects::Pulls::Journals::CreateService < ApplicationService create_comment_journal end + push_activity_2_blockchain("issue_comment_create", @journal) if Site.has_blockchain? && @project.use_blockchain + journal end diff --git a/app/services/api/v1/projects/pulls/versions/get_diff_service.rb b/app/services/api/v1/projects/pulls/versions/get_diff_service.rb index 979bc33f..1f882fd3 100644 --- a/app/services/api/v1/projects/pulls/versions/get_diff_service.rb +++ b/app/services/api/v1/projects/pulls/versions/get_diff_service.rb @@ -30,7 +30,7 @@ class Api::V1::Projects::Pulls::Versions::GetDiffService < ApplicationService end def load_gitea_data - @gitea_data = $gitea_client.get_repos_pulls_versions_diff_by_owner_repo_index_version_id(owner, repo, index, version_id, {query: request_params}) + @gitea_data = $gitea_hat_client.get_repos_pulls_versions_diff_by_owner_repo_index_id(owner, repo, index, version_id, {query: request_params}) raise Error, '获取合并请求版本diff失败!' unless @gitea_data.is_a?(Hash) end end \ No newline at end of file diff --git a/app/services/api/v1/projects/pulls/versions/list_service.rb b/app/services/api/v1/projects/pulls/versions/list_service.rb index ca88ff1f..e9ae69c3 100644 --- a/app/services/api/v1/projects/pulls/versions/list_service.rb +++ b/app/services/api/v1/projects/pulls/versions/list_service.rb @@ -30,7 +30,7 @@ class Api::V1::Projects::Pulls::Versions::ListService < ApplicationService end def load_gitea_data - @gitea_data = $gitea_client.get_repos_pulls_versions_by_owner_repo_index(owner, repo, index, {query: request_params}) + @gitea_data = $gitea_hat_client.get_repos_pulls_versions_by_owner_repo_index(owner, repo, index, {query: request_params}) raise Error, '获取合并请求版本失败!' unless @gitea_data.is_a?(Hash) end end \ No newline at end of file diff --git a/app/services/api/v1/projects/tags/delete_service.rb b/app/services/api/v1/projects/tags/delete_service.rb index 492898b5..d0d317aa 100644 --- a/app/services/api/v1/projects/tags/delete_service.rb +++ b/app/services/api/v1/projects/tags/delete_service.rb @@ -40,7 +40,7 @@ class Api::V1::Projects::Tags::DeleteService < ApplicationService end def check_tag_exist - result = $gitea_client.get_repos_tag_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil + result = $gitea_hat_client.get_repos_tag_name_set_by_owner_repo(owner, repo, {query: request_params}) rescue nil raise Error, '查询标签名称失败!' unless result.is_a?(Array) raise Error, '标签不存在!' if !result.include?(@tag_name) end diff --git a/app/services/api/v1/projects/tags/list_service.rb b/app/services/api/v1/projects/tags/list_service.rb index a7743fe0..9bf4701f 100644 --- a/app/services/api/v1/projects/tags/list_service.rb +++ b/app/services/api/v1/projects/tags/list_service.rb @@ -30,7 +30,7 @@ class Api::V1::Projects::Tags::ListService < ApplicationService end def load_gitea_data - @gitea_data = $gitea_client.get_repos_tags_by_owner_repo(owner, repo, {query: request_params}) rescue nil + @gitea_data = $gitea_hat_client.get_repos_tags_by_owner_repo(owner, repo, {query: request_params}) rescue nil raise Error, '获取标签列表失败!' unless @gitea_data.is_a?(Hash) end end \ No newline at end of file diff --git a/app/services/api/v1/projects/webhooks/create_service.rb b/app/services/api/v1/projects/webhooks/create_service.rb index edc8b226..303f3b39 100644 --- a/app/services/api/v1/projects/webhooks/create_service.rb +++ b/app/services/api/v1/projects/webhooks/create_service.rb @@ -8,7 +8,7 @@ class Api::V1::Projects::Webhooks::CreateService < ApplicationService validates :active, inclusion: {in: [true, false]} validates :http_method, inclusion: { in: %w(POST GET), message: "请输入正确的请求方式"} validates :content_type, inclusion: { in: %w(json form), message: "请输入正确的Content Type"} - validates :type, inclusion: {in: %w(gitea slack discord dingtalk telegram msteams feishu matrix jianmu), message: "请输入正确的Webhook Type"} + validates :type, inclusion: {in: %w(gitea slack discord dingtalk telegram msteams feishu matrix jianmu softbot), message: "请输入正确的Webhook Type"} def initialize(project, params, token=nil) @project = project @owner = project&.owner.login @@ -58,6 +58,6 @@ class Api::V1::Projects::Webhooks::CreateService < ApplicationService end def excute_data_to_gitea - @gitea_data = $gitea_client.post_repos_hooks_by_owner_repo(owner, repo, {body: request_body.to_json, query: request_params}) rescue nil + @gitea_data = $gitea_hat_client.post_repos_hooks_by_owner_repo(owner, repo, {body: request_body.to_json, query: request_params}) rescue nil end end \ No newline at end of file diff --git a/app/services/api/v1/projects/webhooks/hooktasks_service.rb b/app/services/api/v1/projects/webhooks/hooktasks_service.rb index 6be9c67c..17ada908 100644 --- a/app/services/api/v1/projects/webhooks/hooktasks_service.rb +++ b/app/services/api/v1/projects/webhooks/hooktasks_service.rb @@ -30,6 +30,6 @@ class Api::V1::Projects::Webhooks::ListService < ApplicationService end def load_gitea_data - @gitea_data = $gitea_client.get_repos_hooks_hooktasks_by_owner_repo(owner, repo, id, {query: request_params}) rescue nil + @gitea_data = $gitea_hat_client.get_repos_hooks_hooktasks_by_owner_repo(owner, repo, id, {query: request_params}) rescue nil end end \ No newline at end of file diff --git a/app/services/api/v1/projects/webhooks/update_service.rb b/app/services/api/v1/projects/webhooks/update_service.rb index a632d6f2..c98a24ad 100644 --- a/app/services/api/v1/projects/webhooks/update_service.rb +++ b/app/services/api/v1/projects/webhooks/update_service.rb @@ -58,6 +58,6 @@ class Api::V1::Projects::Webhooks::UpdateService < ApplicationService end def excute_data_to_gitea - @gitea_data = $gitea_client.patch_repos_hooks_by_owner_repo_id(owner, repo, id, {body: request_body.to_json, query: request_params}) rescue nil + @gitea_data = $gitea_hat_client.patch_repos_hooks_by_owner_repo_id(owner, repo, id, {body: request_body.to_json, query: request_params}) rescue nil end end \ No newline at end of file diff --git a/app/services/api/v1/users/openkylin_sign/create_service.rb b/app/services/api/v1/users/openkylin_sign/create_service.rb new file mode 100644 index 00000000..e9703d9d --- /dev/null +++ b/app/services/api/v1/users/openkylin_sign/create_service.rb @@ -0,0 +1,45 @@ +class Api::V1::Users::OpenkylinSign::CreateService < ApplicationService + include ActiveModel::Model + + attr_reader :observe_user, :login, :email, :nickname, :phone, :address + + # validates :login, format: {with: CustomRegexp::LOGIN} + validates :email, format: {with: CustomRegexp::EMAIL} + validates :nickname, length: { maximum: 32 } + validates :phone, format: {with: CustomRegexp::PHONE} + validates :address, length: { maximum: 100 } + + def initialize(observe_user, params={}) + @observe_user = observe_user + @login = observe_user.login + @email = params[:email] + @nickname = params[:nickname] + @phone = params[:phone] + @address = params[:address] + end + + def call + raise Error, errors.full_messages.join(",") unless valid? + raise Error, '用户已经签署CLA协议!' if @observe_user.sign_cla + begin + ActiveRecord::Base.transaction do + create_openkylin_sign_detail + update_user_sign_cla + end + + return true + rescue + raise Error, "服务器错误,请联系系统管理员!" + end + end + + private + def create_openkylin_sign_detail + OpenkylinSignDetail.create!(user_id: @observe_user.id, login: @login, email: @email, nickname: @nickname, phone: @phone, address: @address) + end + + def update_user_sign_cla + @observe_user.update_attributes!(sign_cla: true) + end + +end \ No newline at end of file diff --git a/app/services/api/v1/users/projects/list_service.rb b/app/services/api/v1/users/projects/list_service.rb index 8b3bffef..47457c58 100644 --- a/app/services/api/v1/users/projects/list_service.rb +++ b/app/services/api/v1/users/projects/list_service.rb @@ -73,8 +73,10 @@ class Api::V1::Users::Projects::ListService < ApplicationService end - projects = projects.with_project_type(project_type) + projects = projects.with_project_type(project_type) + # 表情处理 + search = search.to_s.each_char.select { |c| c.bytes.first < 240 }.join('') q = projects.ransack(name_or_identifier_cont: search) scope = q.result.includes(:project_category, :project_language,:owner, :repository, :has_pinned_users) diff --git a/app/services/api/v1/users/update_email_service.rb b/app/services/api/v1/users/update_email_service.rb index 9418cac6..7ed5a0fb 100644 --- a/app/services/api/v1/users/update_email_service.rb +++ b/app/services/api/v1/users/update_email_service.rb @@ -31,7 +31,7 @@ class Api::V1::Users::UpdateEmailService < ApplicationService ActiveRecord::Base.transaction do change_user_email excute_data_to_gitea - excute_change_email_from_gitea + excute_change_email_from_gitea remove_old_cache_for_user end @@ -62,13 +62,17 @@ class Api::V1::Users::UpdateEmailService < ApplicationService end def excute_data_to_gitea - Rails.logger.info request_body @gitea_data = $gitea_client.patch_admin_users_by_username(@user.login, {body: request_body.to_json}) end def excute_change_email_from_gitea - $gitea_client.delete_user_emails({body: {emails: [@old_mail]}.to_json, query: request_params}) - $gitea_client.post_user_emails({body: {emails: [@mail]}.to_json, query: request_params}) + emails = $gitea_client.get_user_emails({query: request_params}) + puts "emails=#{emails}" + emails.each do |email| + email = email.stringify_keys + next if email["email"] == @mail + $gitea_client.delete_user_emails({body: {emails: [email["email"]]}.to_json, query: request_params}) + end end def remove_old_cache_for_user diff --git a/app/services/application_service.rb b/app/services/application_service.rb index 81ecf5f7..de9842f9 100644 --- a/app/services/application_service.rb +++ b/app/services/application_service.rb @@ -1,26 +1,427 @@ -class ApplicationService - include Callable - - Error = Class.new(StandardError) - - def regix_emoji content - " " if content.blank? - regex = /[^a-zA-Z0-9\u4E00-\u9FFF]/ - content.gsub(regex, '') - end - - private - - def strip(str) - str.to_s.strip.presence - end - - def str_to_boolean str - ActiveModel::Type::Boolean.new.cast str - end - - def phone_mail_type value - value =~ /^1\d{10}$/ ? 1 : 0 - end - -end +class ApplicationService + include Callable + + Error = Class.new(StandardError) + + def regix_emoji content + " " if content.blank? + regex = /[^a-zA-Z0-9\u4E00-\u9FFF]/ + content.gsub(regex, '') + end + + protected + def try_lock(key) + raise Error, "请稍后再试!" unless $redis_cache.set(key, 1, nx: true, ex: 60.seconds) + end + + def unlock(key) + $redis_cache.del(key) + end + + private + + def strip(str) + str.to_s.strip.presence + end + + def str_to_boolean str + ActiveModel::Type::Boolean.new.cast str + end + + # params: params from index.js page + def create_repo_on_blockchain(params, project) + username = params['user_id'].to_s + token_name = project.id.to_s + total_supply = params['blockchain_token_all'].to_i + token_balance = [[username, params['blockchain_init_token'].to_i]] + + params = { + "request-type": "create repo", + "username": username, + "token_name": token_name, + "total_supply": total_supply, + "token_balance": token_balance + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] != 0 + raise "区块链接口请求失败." + end + end + + + def transfer_balance_on_blockchain(payer, payee, token_name, amount) + + params = { + "request-type": "transfer amount", + "payer": payer, + "payee": payee, + "token_name": token_name, + "amount": amount + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 5 or resp_body['status'] == 106 or resp_body['status'] == 105 + raise resp_body['message'] + elsif resp_body['status'] != 0 + raise "区块链接口请求失败." + else + end + end + + + def lock_balance_on_blockchain(username, tokenname, amount) + + params = { + "request-type": "lock user balance", + "username": username, + "token_name": tokenname, + "amount": amount + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 5 or resp_body['status'] == 106 or resp_body['status'] == 103 + raise resp_body['message'] + elsif resp_body['status'] != 0 + raise "区块链接口请求失败." + else + end + end + + + def unlock_balance_on_blockchain(username, tokenname, amount) + + params = { + "request-type": "unlock user balance", + "username": username, + "token_name": tokenname, + "amount": amount + }.to_json + resp_body = Blockchain::InvokeBlockchainApi.call(params) + if resp_body['status'] == 5 or resp_body['status'] == 106 or resp_body['status'] == 104 + raise resp_body['message'] + elsif resp_body['status'] != 0 + raise "区块链接口请求失败." + else + end + end + + 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 Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise 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 Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise 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']) + if commits.nil? + raise 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 Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise 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']) + if commits.nil? + raise 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 Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise 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 Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise 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 Error, resp_body['message'] + elsif resp_body['status'] != 0 + raise Error, "区块链接口请求失败." + end + end + end + + def phone_mail_type value + value =~ /^1\d{10}$/ ? 1 : 0 + end + +end diff --git a/app/services/blockchain/create_issue.rb b/app/services/blockchain/create_issue.rb new file mode 100644 index 00000000..c3ab5ad4 --- /dev/null +++ b/app/services/blockchain/create_issue.rb @@ -0,0 +1,28 @@ +class Blockchain::CreateIssue < ApplicationService + + attr_reader :params + + def initialize(params) + @params = params + end + + def call + ActiveRecord::Base.transaction do + username = @params[:user_id].to_s + token_name = @params[:project_id].to_s + amount = @params[:token_num].to_i + + # 调用token锁仓函数 + lock_balance_on_blockchain(username, token_name, amount) + end + rescue => e + puts "转账失败: #{e.message}" + raise Error, e.message + end + + private + + def no_use + puts "this function does not have any usage" + end +end \ No newline at end of file diff --git a/app/services/blockchain/create_trade.rb b/app/services/blockchain/create_trade.rb new file mode 100644 index 00000000..a4de9878 --- /dev/null +++ b/app/services/blockchain/create_trade.rb @@ -0,0 +1,29 @@ +class Blockchain::CreateTrade < ApplicationService + + attr_reader :params + + def initialize(params) + @params = params + end + + def call + ActiveRecord::Base.transaction do + username = @params[:user_id].to_s + token_name = @params[:project_id].to_s + amount = @params[:token_num].to_i + + # 调用token锁仓函数 + results = lock_balance_on_blockchain(username, token_name, amount) + return results + end + rescue => e + puts "转账失败: #{e.message}" + raise Error, e.message + end + + private + + def no_use + puts "this function does not have any usage" + end +end \ No newline at end of file diff --git a/app/services/blockchain/fix_issue.rb b/app/services/blockchain/fix_issue.rb new file mode 100644 index 00000000..33220279 --- /dev/null +++ b/app/services/blockchain/fix_issue.rb @@ -0,0 +1,28 @@ +class Blockchain::FixIssue < ApplicationService + + attr_reader :params + + def initialize(params) + @params = params + end + + def call + ActiveRecord::Base.transaction do + username = @params[:user_id].to_s + token_name = @params[:project_id].to_s + amount = @params[:token_num].to_i + + # 调用token锁仓函数 + unlock_balance_on_blockchain(username, token_name, amount) + end + rescue => e + puts "关联issue失败: #{e.message}" + raise Error, e.message + end + + private + + def no_use + puts "this function does not have any usage" + end +end \ No newline at end of file diff --git a/app/services/blockchain/invoke_blockchain_api.rb b/app/services/blockchain/invoke_blockchain_api.rb new file mode 100644 index 00000000..d485e171 --- /dev/null +++ b/app/services/blockchain/invoke_blockchain_api.rb @@ -0,0 +1,34 @@ +class Blockchain::InvokeBlockchainApi < ApplicationService + # 调用blockchain + + attr_reader :params + + def initialize(params) + @params = params + end + + def call + begin + uri = Blockchain.blockchain_config[:api_url] + uri = URI.parse(URI.encode(uri.strip)) + res = Net::HTTP.start(uri.host, uri.port) do |http| + req = Net::HTTP::Post.new(uri) + req['Content-Type'] = 'application/json' + req.body = @params + http.request(req) + end + if res.code.to_i != 200 + raise "区块链接口请求失败." + else + res_body = JSON.parse(res.body) + if res_body.has_key?("status") + else + raise "区块链接口请求失败." + end + end + return res_body + rescue Exception => e + raise "区块链接口请求失败." + end + end +end \ No newline at end of file diff --git a/app/services/blockchain/transfer_service.rb b/app/services/blockchain/transfer_service.rb new file mode 100644 index 00000000..4f7425e5 --- /dev/null +++ b/app/services/blockchain/transfer_service.rb @@ -0,0 +1,36 @@ +class Blockchain::TransferService < ApplicationService + + attr_reader :params + + def initialize(params) + @params = params + end + + def call + ActiveRecord::Base.transaction do + transfer_amount = params['transfer_amount'] + if (Float(transfer_amount) rescue false) == false or transfer_amount.to_i < 0 or Float(transfer_amount) != transfer_amount.to_i + raise Error, "请输入正确的转账金额" + end + transfer_amount = params['transfer_amount'].to_i + transfer_login = params['transfer_login'] + payer = params['payer_id'].to_s + payee = User.find_by(login: transfer_login) + if payee.nil? + raise Error, "未找到接收转账的用户" + else + payee = payee.id.to_s + token_name = params['project_id'].to_s + # 调用token转移函数 + transfer_balance_on_blockchain(payer, payee, token_name, transfer_amount) + end + end + end + + private + + def no_use + puts "this function does not have any usage" + end + +end \ No newline at end of file diff --git a/app/services/gitea/client_service.rb b/app/services/gitea/client_service.rb index e2bd9d49..62e040d8 100644 --- a/app/services/gitea/client_service.rb +++ b/app/services/gitea/client_service.rb @@ -18,19 +18,19 @@ class Gitea::ClientService < ApplicationService # token: {}, # data: {} # } - def post(url, params={}) + def post(url, params={}, is_hat=false) puts "[gitea] request params: #{params}" auth_token = authen_params(params[:token]) conn(auth_token).post do |req| - req.url full_url(url) + req.url full_url(url, "post", is_hat) req.body = params[:data].to_json end end - def get(url, params={}) + def get(url, params={}, is_hat = false) auth_token = authen_params(params[:token]) conn(auth_token).get do |req| - req.url full_url(url, 'get') + req.url full_url(url, 'get', is_hat) params.except(:token).each_pair do |key, value| req.params["#{key}"] = value end @@ -41,27 +41,27 @@ class Gitea::ClientService < ApplicationService # end #=> 响应头 end - def delete(url, params={}) + def delete(url, params={}, is_hat = false) auth_token = authen_params(params[:token]) conn(auth_token).delete do |req| - req.url full_url(url) + req.url full_url(url, "delete", is_hat) req.body = params[:data].to_json end end - def patch(url, params={}) + def patch(url, params={}, is_hat=false) puts "[gitea] request params: #{params}" auth_token = authen_params(params[:token]) conn(auth_token).patch do |req| - req.url full_url(url) + req.url full_url(url, 'patch', is_hat) req.body = params[:data].to_json end end - def put(url, params={}) + def put(url, params={}, is_hat=false) puts "[gitea] put request params: #{params}" conn(authen_params(params[:token])).put do |req| - req.url full_url(url) + req.url full_url(url, "put", is_hat) req.body = params[:data].to_json end end @@ -82,7 +82,7 @@ class Gitea::ClientService < ApplicationService req.headers['Content-Type'] = 'application/json' req.response :logger # 显示日志 req.adapter Faraday.default_adapter - req.options.timeout = 1200 # open/read timeout in seconds + req.options.timeout =7200 # open/read timeout in seconds req.options.open_timeout = 10 # connection open timeout in seconds if token.blank? req.basic_auth(username, secret) @@ -99,16 +99,20 @@ class Gitea::ClientService < ApplicationService GiteaService.gitea_config[:base_url] end + def hat_base_url + GiteaService.gitea_config[:hat_base_url] + end + def domain GiteaService.gitea_config[:domain] end - def api_url - [domain, base_url].join('') + def api_url(is_hat=false) + is_hat ? [domain, hat_base_url].join('') : [domain, base_url].join('') end - def full_url(api_rest, action='post') - url = [api_url, api_rest].join('').freeze + def full_url(api_rest, action='post', is_hat=false) + url = [api_url(is_hat), api_rest].join('').freeze url = action === 'get' ? url : URI.escape(url) url = URI.escape(url) unless url.ascii_only? puts "[gitea] request url: #{url}" @@ -217,6 +221,8 @@ class Gitea::ClientService < ApplicationService end [body, message] + rescue + return [{}, ""] end def json_parse!(body) diff --git a/app/services/gitea/commit/diff_service.rb b/app/services/gitea/commit/diff_service.rb new file mode 100644 index 00000000..71230250 --- /dev/null +++ b/app/services/gitea/commit/diff_service.rb @@ -0,0 +1,40 @@ +# get the diff info for the commit +class Gitea::Commit::DiffService < Gitea::ClientService + attr_reader :owner, :repo, :sha, :token + + # GET /repos/{owner}/{repo}/commits/{sha}/diff + # owner: 用户 + # repo: 仓库名称/标识 + # sha: commit唯一标识 + # eg: + # Gitea::Commit::DiffService.call('jasder', 'repo_identifier', 'sha value') + def initialize(owner, repo, sha, token=nil) + @owner = owner + @repo = repo + @sha = sha + @token = token + end + + def call + response = get(url, params) + render_result(response) + end + + private + def params + Hash.new.merge(token: token) + end + + def url + "/repos/#{owner}/#{repo}/commits/#{sha}/diff".freeze + end + + def render_result(response) + case response.status + when 200 + JSON.parse(response.body) + else + nil + end + end +end diff --git a/app/services/gitea/commit/info_service.rb b/app/services/gitea/commit/info_service.rb new file mode 100644 index 00000000..d337071e --- /dev/null +++ b/app/services/gitea/commit/info_service.rb @@ -0,0 +1,39 @@ +class Gitea::Commit::InfoService < Gitea::ClientService + attr_reader :owner, :repo, :sha, :token + + # GET /repos/{owner}/{repo}/commits/{sha}/diff + # owner: 用户 + # repo: 仓库名称/标识 + # sha: commit唯一标识 + # eg: + # Gitea::Commit::InfoService.call('jasder', 'repo_identifier', 'sha value', token='gitea token') + def initialize(owner, repo, sha, token=nil) + @owner = owner + @repo = repo + @sha = sha + @token = token + end + + def call + response = get(url, params) + render_result(response) + end + + private + def params + Hash.new.merge(token: token) + end + + def url + "/repos/#{owner}/#{repo}/git/commits/#{sha}".freeze + end + + def render_result(response) + case response.status + when 200 + JSON.parse(response.body) + else + nil + end + end +end \ No newline at end of file diff --git a/app/services/gitea/hooks/create_service.rb b/app/services/gitea/hooks/create_service.rb index 6b65a686..8b8d7f2c 100644 --- a/app/services/gitea/hooks/create_service.rb +++ b/app/services/gitea/hooks/create_service.rb @@ -24,7 +24,7 @@ class Gitea::Hooks::CreateService < Gitea::ClientService end def call - response = post(url, params) + response = post(url, params, true) render_201_response(response) end diff --git a/app/services/gitea/organization/create_service.rb b/app/services/gitea/organization/create_service.rb index 4da1720c..6f4c3d4f 100644 --- a/app/services/gitea/organization/create_service.rb +++ b/app/services/gitea/organization/create_service.rb @@ -7,7 +7,7 @@ class Gitea::Organization::CreateService < Gitea::ClientService end def call - response = post(url, request_params) + response = post(url, request_params, true) render_status(response) end diff --git a/app/services/gitea/organization/update_service.rb b/app/services/gitea/organization/update_service.rb index 963099ad..7a0fd1ee 100644 --- a/app/services/gitea/organization/update_service.rb +++ b/app/services/gitea/organization/update_service.rb @@ -8,7 +8,7 @@ class Gitea::Organization::UpdateService < Gitea::ClientService end def call - response = patch(url, request_params) + response = patch(url, request_params, true) render_status(response) end diff --git a/app/services/gitea/pull_request/commits_service.rb b/app/services/gitea/pull_request/commits_service.rb index dc2877eb..f85edd29 100644 --- a/app/services/gitea/pull_request/commits_service.rb +++ b/app/services/gitea/pull_request/commits_service.rb @@ -16,7 +16,7 @@ class Gitea::PullRequest::CommitsService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_result(response) end diff --git a/app/services/gitea/pull_request/files_service.rb b/app/services/gitea/pull_request/files_service.rb index f7a2bd75..a5c2cf0d 100644 --- a/app/services/gitea/pull_request/files_service.rb +++ b/app/services/gitea/pull_request/files_service.rb @@ -17,7 +17,7 @@ class Gitea::PullRequest::FilesService < Gitea::ClientService end def call - response = get(url, params.merge(token: token)) + response = get(url, params.merge(token: token), true) render_result(response) end diff --git a/app/services/gitea/pull_request/get_service.rb b/app/services/gitea/pull_request/get_service.rb index f9a35fdc..bd1fd895 100644 --- a/app/services/gitea/pull_request/get_service.rb +++ b/app/services/gitea/pull_request/get_service.rb @@ -12,7 +12,7 @@ class Gitea::PullRequest::GetService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_result(response) end diff --git a/app/services/gitea/pull_request/update_service.rb b/app/services/gitea/pull_request/update_service.rb index a68981f2..339caa6c 100644 --- a/app/services/gitea/pull_request/update_service.rb +++ b/app/services/gitea/pull_request/update_service.rb @@ -27,7 +27,7 @@ class Gitea::PullRequest::UpdateService < Gitea::ClientService end def call - response = patch(url, request_params) + response = patch(url, request_params, true) status, message, body = render_response(response) json_format(status, message, body) diff --git a/app/services/gitea/repository/branches/list_name_service.rb b/app/services/gitea/repository/branches/list_name_service.rb index c005c835..84f6d3a4 100644 --- a/app/services/gitea/repository/branches/list_name_service.rb +++ b/app/services/gitea/repository/branches/list_name_service.rb @@ -8,7 +8,7 @@ class Gitea::Repository::Branches::ListNameService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_200_response(response) end diff --git a/app/services/gitea/repository/branches/list_slice_service.rb b/app/services/gitea/repository/branches/list_slice_service.rb index 6b643831..e04a4b6e 100644 --- a/app/services/gitea/repository/branches/list_slice_service.rb +++ b/app/services/gitea/repository/branches/list_slice_service.rb @@ -7,7 +7,7 @@ class Gitea::Repository::Branches::ListSliceService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_200_response(response) end diff --git a/app/services/gitea/repository/commits/compare_service.rb b/app/services/gitea/repository/commits/compare_service.rb index 502f6ce9..bdfd4ca3 100644 --- a/app/services/gitea/repository/commits/compare_service.rb +++ b/app/services/gitea/repository/commits/compare_service.rb @@ -14,7 +14,7 @@ class Gitea::Repository::Commits::CompareService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_status(response) end diff --git a/app/services/gitea/repository/commits/file_list_service.rb b/app/services/gitea/repository/commits/file_list_service.rb index b1606a0f..14c873fd 100644 --- a/app/services/gitea/repository/commits/file_list_service.rb +++ b/app/services/gitea/repository/commits/file_list_service.rb @@ -14,13 +14,13 @@ class Gitea::Repository::Commits::FileListService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_result(response) end private def params - {sha: args[:sha] || 'master', page: args[:page] || PAGINATE_DEFAULT_PAGE, limit: args[:limit] || PAGINATE_DEFAULT_LIMIT, token: args[:token] || "" } + {sha: args[:sha] || 'master', page: args[:page] || PAGINATE_DEFAULT_PAGE, limit: args[:limit] || PAGINATE_DEFAULT_LIMIT, token: args[:token] || "", stat: args[:page].to_i != 1 } end def url diff --git a/app/services/gitea/repository/commits/get_service.rb b/app/services/gitea/repository/commits/get_service.rb index d497f1e4..a8fc6723 100644 --- a/app/services/gitea/repository/commits/get_service.rb +++ b/app/services/gitea/repository/commits/get_service.rb @@ -14,7 +14,7 @@ class Gitea::Repository::Commits::GetService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_status(response) end diff --git a/app/services/gitea/repository/commits/list_slice_service.rb b/app/services/gitea/repository/commits/list_slice_service.rb index 04f45f55..d31cf2bc 100644 --- a/app/services/gitea/repository/commits/list_slice_service.rb +++ b/app/services/gitea/repository/commits/list_slice_service.rb @@ -13,7 +13,7 @@ class Gitea::Repository::Commits::ListSliceService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_result(response) end diff --git a/app/services/gitea/repository/contributors/get_service.rb b/app/services/gitea/repository/contributors/get_service.rb index 1ee1c395..fe9ed246 100644 --- a/app/services/gitea/repository/contributors/get_service.rb +++ b/app/services/gitea/repository/contributors/get_service.rb @@ -1,22 +1,38 @@ class Gitea::Repository::Contributors::GetService < Gitea::ClientService - attr_reader :owner, :repo_name + attr_reader :owner, :repo_name, :page, :limit - def initialize(owner, repo_name) + def initialize(owner, repo_name, params={}) @owner = owner @repo_name = repo_name + @page = params[:page] || 1 + @limit = params[:limit] || 20 end def call - response = get(url, params) - render_status(response) + response = get(url, params, true) + render_result(response) end private def params - Hash.new.merge(token: owner.gitea_token) + Hash.new.merge(token: owner.gitea_token, page: page, limit: limit) end def url "/repos/#{owner.login}/#{repo_name}/contributors" end + + def render_result(response) + case response.status + when 200 + result = {} + headers = response.headers.to_hash + body = JSON.parse(response.body) + total_count = headers["x-total"] + result.merge(total_count: total_count.to_i, body: body) + else + nil + # {status: -1, message: "#{body['message']}"} + end + end end \ No newline at end of file diff --git a/app/services/gitea/repository/entries/get_service.rb b/app/services/gitea/repository/entries/get_service.rb index f8ac2754..f8e7b945 100644 --- a/app/services/gitea/repository/entries/get_service.rb +++ b/app/services/gitea/repository/entries/get_service.rb @@ -13,7 +13,7 @@ class Gitea::Repository::Entries::GetService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_result(response) end diff --git a/app/services/gitea/repository/entries/list_service.rb b/app/services/gitea/repository/entries/list_service.rb index dd62a114..df9fdb1e 100644 --- a/app/services/gitea/repository/entries/list_service.rb +++ b/app/services/gitea/repository/entries/list_service.rb @@ -10,7 +10,7 @@ class Gitea::Repository::Entries::ListService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_result(response) end diff --git a/app/services/gitea/repository/files/get_service.rb b/app/services/gitea/repository/files/get_service.rb index e5b96e7b..2a158982 100644 --- a/app/services/gitea/repository/files/get_service.rb +++ b/app/services/gitea/repository/files/get_service.rb @@ -10,7 +10,7 @@ class Gitea::Repository::Files::GetService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_status(response) end diff --git a/app/services/gitea/repository/get_branch_and_tag_total_num_service.rb b/app/services/gitea/repository/get_branch_and_tag_total_num_service.rb index 0b8a5246..f0fd2557 100644 --- a/app/services/gitea/repository/get_branch_and_tag_total_num_service.rb +++ b/app/services/gitea/repository/get_branch_and_tag_total_num_service.rb @@ -11,7 +11,7 @@ module Gitea end def call - response = get(url, params) + response = get(url, params, true) render_result(response) end diff --git a/app/services/gitea/repository/readme/dir_service.rb b/app/services/gitea/repository/readme/dir_service.rb index 587fb5d5..830cceaa 100644 --- a/app/services/gitea/repository/readme/dir_service.rb +++ b/app/services/gitea/repository/readme/dir_service.rb @@ -10,7 +10,7 @@ class Gitea::Repository::Readme::DirService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) status, message, body = render_response(response) json_format(status, message, body) end diff --git a/app/services/gitea/repository/readme/get_service.rb b/app/services/gitea/repository/readme/get_service.rb index 48e2d447..5af86b5a 100644 --- a/app/services/gitea/repository/readme/get_service.rb +++ b/app/services/gitea/repository/readme/get_service.rb @@ -15,7 +15,7 @@ class Gitea::Repository::Readme::GetService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) status, message, body = render_response(response) json_format(status, message, body) end diff --git a/app/services/gitea/repository/tags/list_name_service.rb b/app/services/gitea/repository/tags/list_name_service.rb index 0857ca11..ac81c9d7 100644 --- a/app/services/gitea/repository/tags/list_name_service.rb +++ b/app/services/gitea/repository/tags/list_name_service.rb @@ -8,7 +8,7 @@ class Gitea::Repository::Tags::ListNameService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_200_response(response) end diff --git a/app/services/gitea/repository/tags/list_service.rb b/app/services/gitea/repository/tags/list_service.rb index 0f8158b3..95828717 100644 --- a/app/services/gitea/repository/tags/list_service.rb +++ b/app/services/gitea/repository/tags/list_service.rb @@ -11,7 +11,7 @@ class Gitea::Repository::Tags::ListService < Gitea::ClientService end def call - response = get(url, request_params) + response = get(url, request_params, true) render_result(response) end diff --git a/app/services/gitea/repository/transfer_service.rb b/app/services/gitea/repository/transfer_service.rb index 358ac942..40cf5d1b 100644 --- a/app/services/gitea/repository/transfer_service.rb +++ b/app/services/gitea/repository/transfer_service.rb @@ -9,7 +9,7 @@ class Gitea::Repository::TransferService < Gitea::ClientService end def call - response = post(url, request_params) + response = post(url, request_params, true) render_status(response) end diff --git a/app/services/gitea/repository/webhooks/create_service.rb b/app/services/gitea/repository/webhooks/create_service.rb index 33c9a9b0..9105b39c 100644 --- a/app/services/gitea/repository/webhooks/create_service.rb +++ b/app/services/gitea/repository/webhooks/create_service.rb @@ -8,7 +8,7 @@ class Gitea::Repository::Webhooks::CreateService < Gitea::ClientService end def call - response = post(url, request_params) + response = post(url, request_params, true) render_response(response) end diff --git a/app/services/gitea/repository/webhooks/tasks_service.rb b/app/services/gitea/repository/webhooks/tasks_service.rb index e4c62edb..be5a5929 100644 --- a/app/services/gitea/repository/webhooks/tasks_service.rb +++ b/app/services/gitea/repository/webhooks/tasks_service.rb @@ -11,7 +11,7 @@ class Gitea::Repository::Webhooks::TasksService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_response(response) end diff --git a/app/services/gitea/repository/webhooks/update_service.rb b/app/services/gitea/repository/webhooks/update_service.rb index 6094c6c5..25456a80 100644 --- a/app/services/gitea/repository/webhooks/update_service.rb +++ b/app/services/gitea/repository/webhooks/update_service.rb @@ -9,7 +9,7 @@ class Gitea::Repository::Webhooks::UpdateService < Gitea::ClientService end def call - response = patch(url, data_params) + response = patch(url, data_params, true) render_response(response) end diff --git a/app/services/gitea/user/headmap_service.rb b/app/services/gitea/user/headmap_service.rb index 611a8b9d..eef8e21a 100644 --- a/app/services/gitea/user/headmap_service.rb +++ b/app/services/gitea/user/headmap_service.rb @@ -1,20 +1,21 @@ class Gitea::User::HeadmapService < Gitea::ClientService - attr_reader :start_time, :end_time, :username + attr_reader :start_time, :end_time, :username, :token - def initialize(username, start_time, end_time) + def initialize(username, start_time, end_time, token=nil) @username = username @start_time = start_time @end_time = end_time + @token = token end def call - response = get(url, params) + response = get(url, params, true) render_response(response) end private def params - Hash.new.merge(start: start_time, end: end_time) + Hash.new.merge(start: start_time, end: end_time, token: token) end def url diff --git a/app/services/gitea/user/update_service.rb b/app/services/gitea/user/update_service.rb index 9826c7ed..24660158 100644 --- a/app/services/gitea/user/update_service.rb +++ b/app/services/gitea/user/update_service.rb @@ -24,7 +24,7 @@ class Gitea::User::UpdateService < Gitea::ClientService end def call - patch(url, data_params) + patch(url, data_params, true) end private diff --git a/app/services/gitea/versions/create_service.rb b/app/services/gitea/versions/create_service.rb index 04fed00f..4424fc27 100644 --- a/app/services/gitea/versions/create_service.rb +++ b/app/services/gitea/versions/create_service.rb @@ -18,7 +18,7 @@ class Gitea::Versions::CreateService < Gitea::ClientService end def call - response = post(url, request_params) + response = post(url, request_params, true) render_status(response) end diff --git a/app/services/gitea/versions/get_service.rb b/app/services/gitea/versions/get_service.rb index b3c6cf9c..2af78ab2 100644 --- a/app/services/gitea/versions/get_service.rb +++ b/app/services/gitea/versions/get_service.rb @@ -12,7 +12,7 @@ class Gitea::Versions::GetService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_result(response) end diff --git a/app/services/gitea/versions/list_service.rb b/app/services/gitea/versions/list_service.rb index 5d160fc3..3505fa25 100644 --- a/app/services/gitea/versions/list_service.rb +++ b/app/services/gitea/versions/list_service.rb @@ -11,7 +11,7 @@ class Gitea::Versions::ListService < Gitea::ClientService end def call - response = get(url, params) + response = get(url, params, true) render_result(response) end diff --git a/app/services/gitea/versions/update_service.rb b/app/services/gitea/versions/update_service.rb index a4c9acfc..c07620bc 100644 --- a/app/services/gitea/versions/update_service.rb +++ b/app/services/gitea/versions/update_service.rb @@ -19,7 +19,7 @@ class Gitea::Versions::UpdateService < Gitea::ClientService end def call - patch(url, request_params) + patch(url, request_params, true) end private diff --git a/app/services/info_risk_control_service.rb b/app/services/info_risk_control_service.rb new file mode 100644 index 00000000..f8bd993b --- /dev/null +++ b/app/services/info_risk_control_service.rb @@ -0,0 +1,77 @@ +class InfoRiskControlService < ApplicationService + + attr_reader :receiver, :remote_ip + attr_accessor :status, :message + + + def initialize(receiver="", remote_ip="0.0.0.0") + @receiver = receiver + @remote_ip = remote_ip + @status = 1 + @message = "" + end + + def call + if receiver == "" + remote_ip_minute_risk_control + remote_ip_risk_control if @status == 1 + else + remote_ip_minute_risk_control + remote_ip_risk_control if @status == 1 + minute_risk_control + day_risk_control if @status == 1 + end + + return @status, @message + end + + private + def remote_ip_minute_risk_control + result = Rails.cache.read("InfoRiskControlService-RemoteIp-Minute-#{remote_ip}") + if result.present? + @status = 0 + @message = "您的请求过于频繁,请稍后再试" + else + Rails.cache.write("InfoRiskControlService-RemoteIp-Minute-#{remote_ip}", 1, expires_in: 1.minute) + end + end + + def remote_ip_risk_control + result = Rails.cache.read("InfoRiskControlService-RemoteIp-#{remote_ip}") + if result.present? + if result.to_i > 20 + @status = 0 + @message = "暂时无法请求,请稍后再试" + else + Rails.cache.write("InfoRiskControlService-RemoteIp-#{remote_ip}", result.to_i + 1) + end + else + Rails.cache.write("InfoRiskControlService-RemoteIp-#{remote_ip}", 1, expires_in: 1.day) + end + end + + def minute_risk_control + result = Rails.cache.read("InfoRiskControlService-Minute-#{receiver}") + if result.present? + @status = 0 + @message = "您的请求过于频繁,请稍后再试" + else + Rails.cache.write("InfoRiskControlService-Minute-#{receiver}", 1, expires_in: 1.minute) + end + end + + def day_risk_control + result = Rails.cache.read("InfoRiskControlService-Day-#{receiver}") + if result.present? + if result.to_i > 10 + @status = 0 + @message = "您的请求过于频繁,请稍后再试" + else + Rails.cache.write("InfoRiskControlService-Day-#{receiver}", result.to_i + 1) + end + else + Rails.cache.write("InfoRiskControlService-Day-#{receiver}", 1, expires_in: 1.days) + end + end + +end \ No newline at end of file diff --git a/app/services/projects/create_service.rb b/app/services/projects/create_service.rb index 2b4523bf..c4f892f7 100644 --- a/app/services/projects/create_service.rb +++ b/app/services/projects/create_service.rb @@ -14,9 +14,13 @@ class Projects::CreateService < ApplicationService ActiveRecord::Base.transaction do if @project.save! Project.update_common_projects_count! + IssueTag.init_data(@project.id) ProjectUnit.init_types(@project.id) Repositories::CreateService.new(user, @project, repository_params).call upgrade_project_category_private_projects_count + if repo_use_blockchain + create_repo_on_blockchain(params, @project) + end else Rails.logger.info("#############___________create_project_erros______###########{@project.errors.messages}") end @@ -29,7 +33,7 @@ class Projects::CreateService < ApplicationService private - def upgrade_project_category_private_projects_count + def upgrade_project_category_private_projects_count # 如果为空或者项目为公有项目直接返回 return unless params[:project_category_id].present? return if repo_is_public @@ -37,7 +41,7 @@ class Projects::CreateService < ApplicationService project_category.increment!(:private_projects_count, 1) end - def authroize_user_id_success + def authroize_user_id_success (user.id == params[:user_id].to_i) || (user.organizations.find_by_id(params[:user_id]).present?) end @@ -52,7 +56,8 @@ class Projects::CreateService < ApplicationService ignore_id: params[:ignore_id], license_id: params[:license_id], website: params[:website], - identifier: params[:repository_name] + identifier: params[:repository_name], + use_blockchain: repo_use_blockchain # 新增,zxh } end @@ -71,4 +76,8 @@ class Projects::CreateService < ApplicationService def repo_is_public params[:private].blank? ? true : !(ActiveModel::Type::Boolean.new.cast(params[:private]).nil? ? false : ActiveModel::Type::Boolean.new.cast(params[:private])) end + + def repo_use_blockchain + params[:blockchain].blank? ? false : params[:blockchain] + end end diff --git a/app/services/projects/transfer_service.rb b/app/services/projects/transfer_service.rb index 8ed58f8a..07eab898 100644 --- a/app/services/projects/transfer_service.rb +++ b/app/services/projects/transfer_service.rb @@ -51,7 +51,7 @@ class Projects::TransferService < ApplicationService def gitea_update_owner begin - @gitea_repo = $gitea_client.post_repos_transfer_by_owner_repo(owner&.login, project.identifier, {body: {new_owner: new_owner&.login}.to_json}) + @gitea_repo = $gitea_hat_client.post_repos_transfer_by_owner_repo(owner&.login, project.identifier, {body: {new_owner: new_owner&.login}.to_json}) # @gitea_repo = Gitea::Repository::TransferService.call(owner&.gitea_token, owner&.login, project.identifier, new_owner&.login) rescue Exception => e Rails.logger.info("##### Project transfer_service, gitea transfer error #{e}") diff --git a/app/services/pull_requests/create_service.rb b/app/services/pull_requests/create_service.rb index 258d0e31..2b4767f3 100644 --- a/app/services/pull_requests/create_service.rb +++ b/app/services/pull_requests/create_service.rb @@ -20,6 +20,7 @@ class PullRequests::CreateService < ApplicationService save_tiding! save_project_trend! save_custom_journal_detail! + save_pull_attached_issues! end [pull_request, gitea_pull_request] @@ -111,6 +112,20 @@ class PullRequests::CreateService < ApplicationService end end + def save_pull_attached_issues! + if attached_issue_ids.size > 1 + raise "最多只能关联一个疑修。" + else + attached_issue_ids.each do |issue| + PullAttachedIssue.create!(issue_id: issue, pull_request_id: pull_request&.id) + end + end + end + + def attached_issue_ids + Array(@params[:attached_issue_ids]) + end + def gitea_pull_request @gitea_pull_request ||= create_gitea_pull_request! end diff --git a/app/services/webhook/client.rb b/app/services/webhook/client.rb new file mode 100644 index 00000000..cb1cac61 --- /dev/null +++ b/app/services/webhook/client.rb @@ -0,0 +1,120 @@ +module Webhook::Client + + # uuid SecureRandom.uuid + # hmac = OpenSSL::HMAC.new(secret, OpenSSL::Digest::SHA1.new) + # message = Gitea::WebhookTask.last.read_attribute_before_type_cast("payload_content") + # hmac.update(message) + # sha1 = hmac.digest.unpack('H*').first + + attr_reader :uuid, :event, :http_method, :content_type, :url, :secret, :payload_content, :webhook + attr_accessor :request_content, :response_content, :webhook_task + + def initialize(opts) + @uuid = opts[:uuid] + @event = opts[:event] + @webhook = opts[:webhook] + @http_method = @webhook.http_method + @content_type = @webhook.content_type + @url = @webhook.url + @secret = @webhook.secret + @payload_content = opts[:payload_content] + @request_content = {} + @response_content = {} + @webhook_task = Gitea::WebhookTask.create( + hook_id: @webhook.id, + uuid: @uuid, + payload_content: @payload_content, + event_type: @event, + is_delivered: true + ) + end + + def do_request + headers = {} + headers['Content-Type'] = trans_content_type + headers["X-Gitea-Delivery"] = @uuid + headers["X-Gitea-Event"] = @event + headers["X-Gitea-Event-Type"] = @event + headers["X-Gitea-Signature"] = signatureSHA256 + headers["X-Gogs-Delivery"] = @uuid + headers["X-Gogs-Event"] = @event + headers["X-Gogs-Event-Type"] = @event + headers["X-Gogs-Signature"] = signatureSHA256 + headers["X-Hub-Signature"] = "sha1=" + signatureSHA1 + headers["X-Hub-Signature-256"] = "sha256=" + signatureSHA256 + headers["X-GitHub-Delivery"] = @uuid + headers["X-GitHub-Event"] = @event + headers["X-GitHub-Event-Type"] = @event + @request_content["url"] = @url + @request_content["http_method"] = @http_method + @request_content["headers"] = headers + + begin + + response = RestClient::Request.execute(method: trans_http_method, url: @url, headers: headers, payload: @webhook_task.read_attribute_before_type_cast("payload_content")) {|response, request, result| response } + + @response_content["status"] = response.code + @response_content["headers"] = response.headers + @response_content["body"] = response.body + + rescue => e + @response_content["status"] = 500 + @response_content["headers"] = {} + @response_content["body"] = e.message + end + + @webhook_task.update_attributes({ + delivered: Time.now.to_i * 1000000000, + is_succeed: @response_content["status"] < 300, + request_content: @request_content, + response_content: @response_content + }) + + + return @request_content, @response_content, @webhook_task + end + + def request_content + @request_content + end + + def response_content + @response_content + end + + def webhook_task + @webhook_task + end + + private + def signatureSHA1 + hmac = OpenSSL::HMAC.new(@secret, OpenSSL::Digest::SHA1.new) + message = @payload_content + + hmac.digest.unpack('H*').first + end + + def signatureSHA256 + hmac = OpenSSL::HMAC.new(@secret, OpenSSL::Digest::SHA256.new) + message = @payload_content + + hmac.digest.unpack('H*').first + end + + def trans_content_type + if @content_type == "form" + return "application/x-www-form-urlencoded" + else + return "application/json" + end + end + + def trans_http_method + if @http_method == "GET" + return :get + else + return :post + end + end + +end \ No newline at end of file diff --git a/app/services/webhook/issue_client.rb b/app/services/webhook/issue_client.rb new file mode 100644 index 00000000..53533089 --- /dev/null +++ b/app/services/webhook/issue_client.rb @@ -0,0 +1,117 @@ +class Webhook::IssueClient + + include Webhook::Client + + attr_accessor :webhook, :issue, :sender, :event, :changes + attr_accessor :webhook_task + + def initialize(webhook, issue, sender, event, changes={}) + @webhook = webhook + @issue = issue.reload + @sender = sender.reload + @event = event + @changes = changes + + # 构建client参数 + super({ + uuid: SecureRandom.uuid, + event: @event, + webhook: @webhook, + payload_content: payload_content + }) + end + + def payload_content + case @event + when "issues" + issue_payload_content + when "issue_assign" + issue_assign_payload_content + when "issue_label" + issue_label_payload_content + end + end + + def issue_payload_content + if @changes.blank? + { + "action": "opened", + "number": @issue.project_issues_index, + "issue": JSON.parse(@issue.to_builder.target!), + "project": JSON.parse(@issue.project.to_builder.target!), + "sender": JSON.parse(@sender.to_builder.target!) + } + else + if @changes.has_key?("status_id") + before_status = IssueStatus.find_by_id(@changes["status_id"][0]) + after_status = IssueStatus.find_by_id(@changes["status_id"][1]) + @changes["status"] = [] + @changes["status"].append(before_status.present? ? JSON.parse(before_status.to_builder.target!) : {}) + @changes["status"].append(after_status.present? ? JSON.parse(after_status.to_builder.target!) : {}) + @changes.delete("status_id") + end + if @changes.has_key?("fixed_version_id") + before_milestone = Version.find_by_id(@changes["fixed_version_id"][0]) + after_milestone = Version.find_by_id(@changes["fixed_version_id"][1]) + @changes["milestone"] = [] + @changes["milestone"].append(before_milestone.present? ? JSON.parse(before_milestone.to_builder.target!) : {}) + @changes["milestone"].append(after_milestone.present? ? JSON.parse(after_milestone.to_builder.target!) : {}) + @changes.delete("fixed_version_id") + end + if @changes.has_key?("priority_id") + before_priority = IssuePriority.find_by_id(@changes["priority_id"][0]) + after_priority = IssuePriority.find_by_id(@changes["priority_id"][1]) + @changes["priority"] = [] + @changes["priority"].append(before_priority.present? ? JSON.parse(before_priority.to_builder.target!) : {}) + @changes["priority"].append(after_priority.present? ? JSON.parse(after_priority.to_builder.target!) : {}) + @changes.delete("priority_id") + end + { + "action": "edited", + "number": @issue.project_issues_index, + "changes": @changes, + "issue": JSON.parse(@issue.to_builder.target!), + "project": JSON.parse(@issue.project.to_builder.target!), + "sender": JSON.parse(@sender.to_builder.target!) + } + end + end + + def issue_assign_payload_content + if @changes.has_key?("assigner_ids") + before_assigners = User.where(id: @changes["assigner_ids"][0]) + after_assigners = User.where(id: @changes["assigner_ids"][1]) + @changes["assigners"] = [] + @changes["assigners"].append(before_assigners.blank? ? [] : before_assigners.map{|a|JSON.parse(a.to_builder.target!)}) + @changes["assigners"].append(after_assigners.blank? ? [] : after_assigners.map{|a|JSON.parse(a.to_builder.target!)}) + @changes.delete("assigner_ids") + end + { + "action": @changes["assigners"].blank? ? "unassigned" : "assigned", + "number": @issue.project_issues_index, + "changes": @changes, + "issue": JSON.parse(@issue.to_builder.target!), + "project": JSON.parse(@issue.project.to_builder.target!), + "sender": JSON.parse(@sender.to_builder.target!) + } + end + + def issue_label_payload_content + if @changes.has_key?("issue_tag_ids") + before_issue_tags = IssueTag.where(id: @changes["issue_tag_ids"][0]) + after_issue_tags = IssueTag.where(id: @changes["issue_tag_ids"][1]) + @changes["issue_tags"] = [] + @changes["issue_tags"].append(before_issue_tags.blank? ? [] : before_issue_tags.map{|t|JSON.parse(t.to_builder.target!)}) + @changes["issue_tags"].append(after_issue_tags.blank? ? [] : after_issue_tags.map{|t|JSON.parse(t.to_builder.target!)}) + @changes.delete("issue_tag_ids") + end + { + "action": @changes["issue_tags"].blank? ? "label_cleared" : "label_updated", + "changes": @changes, + "number": @issue.project_issues_index, + "issue": JSON.parse(@issue.to_builder.target!), + "project": JSON.parse(@issue.project.to_builder.target!), + "sender": JSON.parse(@sender.to_builder.target!) + } + end +end \ No newline at end of file diff --git a/app/services/webhook/issue_comment_client.rb b/app/services/webhook/issue_comment_client.rb new file mode 100644 index 00000000..32204149 --- /dev/null +++ b/app/services/webhook/issue_comment_client.rb @@ -0,0 +1,45 @@ +class Webhook::IssueCommentClient + + include Webhook::Client + + attr_accessor :webhook, :issue, :journal, :sender, :event, :action_type, :comment_json + + def initialize(webhook, issue, journal, sender, event, action_type, comment_json={}) + @webhook = webhook + @issue = issue.reload + @journal = journal.present? ? journal.reload : nil + @sender = sender.reload + @event = event + @action_type = action_type + @comment_json = comment_json + + # 构建client参数 + super({ + uuid: SecureRandom.uuid, + event: @event, + webhook: @webhook, + payload_content: payload_content + }) + end + + + + private + + def payload_content + payload_content = { + "action": @action_type, + "issue": JSON.parse(@issue.to_builder.target!), + "journal": @journal.present? ? JSON.parse(@journal.to_builder.target!) : @comment_json, + "project": JSON.parse(@issue.project.to_builder.target!), + "sender": JSON.parse(@sender.to_builder.target!), + "is_pull": false + } + + payload_content.merge!({ + "changes": @comment_json, + }) if @action_type == "edited" + + payload_content + end +end \ No newline at end of file diff --git a/app/services/webhook/pull_comment_client.rb b/app/services/webhook/pull_comment_client.rb new file mode 100644 index 00000000..a4d6cab4 --- /dev/null +++ b/app/services/webhook/pull_comment_client.rb @@ -0,0 +1,43 @@ +class Webhook::PullCommentClient + include Webhook::Client + + attr_accessor :webhook, :pull, :journal, :sender, :event, :action_type, :comment_json + + def initialize(webhook, pull, journal, sender, event, action_type='created', comment_json={}) + @webhook = webhook + @pull = pull.reload + @journal = journal.present? ? journal.reload : nil + @sender = sender.reload + @event = event + @action_type = action_type + @comment_json = comment_json + # 构建client参数 + super({ + uuid: SecureRandom.uuid, + event: @event, + webhook: @webhook, + payload_content: payload_content + }) + end + + private + + def payload_content + payload_content = { + "action": @action_type, + "number": @pull.gitea_number, + "pull_request": JSON.parse(@pull.to_builder.target!), + "comment": @journal.present? ? JSON.parse(@journal.to_builder.target!) : @comment_json, + "project": JSON.parse(@pull.project.to_builder.target!), + "sender": JSON.parse(@sender.to_builder.target!), + "is_pull": true + } + + payload_content.merge!({ + "changes": @comment_json + }) if @action_type == "edited" + + payload_content + end + +end \ No newline at end of file diff --git a/app/views/admins/organizations/edit.html.erb b/app/views/admins/organizations/edit.html.erb new file mode 100644 index 00000000..0cc9909f --- /dev/null +++ b/app/views/admins/organizations/edit.html.erb @@ -0,0 +1,41 @@ +<% + define_admin_breadcrumbs do + add_admin_breadcrumb('组织管理', admins_organizations_path) + add_admin_breadcrumb('组织详情') + end +%> + +
+
+ <%= link_to "/#{@org.login}", class: 'user-info-avatar col-md-1', target: '_blank', data: { toggle: 'tooltip', title: '个人中心' } do %> + + <% end %> + +
+ + <%= simple_form_for(@org, url: admins_organization_path(@org)) do |f| %> + +
基本信息
+
+
+ <%= f.input :login, label: '登录名', wrapper_html: { class: 'col-md-3' }, input_html: { readonly: true, class: 'col-md-11', value: @org.login } %> +
+ +
+ <%= f.input :lastname, label: '姓名', wrapper_html: { class: 'col-md-3' }, input_html: { class: 'col-md-11', value: @org.real_name } %> +
+ + +
+ +
+ <%= f.button :submit, value: '保存', class: 'btn-primary mr-3 px-4' %> + <%= link_to '取消', admins_organizations_path, class: 'btn btn-secondary px-4' %> +
+ <% end %> +
diff --git a/app/views/admins/organizations/index.html.erb b/app/views/admins/organizations/index.html.erb new file mode 100644 index 00000000..7cd2ba8f --- /dev/null +++ b/app/views/admins/organizations/index.html.erb @@ -0,0 +1,17 @@ +<% define_admin_breadcrumbs do %> + <% add_admin_breadcrumb('组织管理', admins_organizations_path) %> +<% end %> +
+ <%= form_tag(admins_organizations_path, method: :get, class: 'form-inline search-form flex-1', remote: true) do %> + + <%= text_field_tag(:keyword, params[:keyword], class: 'form-control col-sm-2 ml-3', placeholder: 'login/昵称') %> + + <%= submit_tag('搜索', class: 'btn btn-primary ml-3', 'data-disable-with': '搜索中...') %> + <% end %> + +
+ +
+ <%= render partial: 'admins/organizations/shared/org_list', locals: { organizations: @orgs } %> +
+ diff --git a/app/views/admins/organizations/index.js.erb b/app/views/admins/organizations/index.js.erb new file mode 100644 index 00000000..c2778115 --- /dev/null +++ b/app/views/admins/organizations/index.js.erb @@ -0,0 +1 @@ +$('.organizations-list-container').html("<%= j( render partial: 'admins/organizations/shared/org_list', locals: { organizations: @orgs } ) %>"); diff --git a/app/views/admins/organizations/index.json.jbuilder b/app/views/admins/organizations/index.json.jbuilder new file mode 100644 index 00000000..1278c3c1 --- /dev/null +++ b/app/views/admins/organizations/index.json.jbuilder @@ -0,0 +1,6 @@ +json.count @orgs.total_count +json.orgs do + json.array! @orgs.each do |org| + json.extract! org, :id, :login, :nickname + end +end \ No newline at end of file diff --git a/app/views/admins/organizations/shared/_org_list.html.erb b/app/views/admins/organizations/shared/_org_list.html.erb new file mode 100644 index 00000000..25878b29 --- /dev/null +++ b/app/views/admins/organizations/shared/_org_list.html.erb @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + <% if organizations.present? %> + <% organizations.each_with_index do |org, index| %> + + + + + + + + + + + <% end %> + <% else %> + <%= render 'admins/shared/no_data_for_table' %> + <% end %> + +
序号login昵称<%= sort_tag('创建于', name: 'created_on', path: admins_organizations_path) %>团队成员项目数操作
<%= list_index_no((params[:page] || 1).to_i, index) %> + <%= link_to "/#{org.login}", target: '_blank' do %> + <%= overflow_hidden_span org.login, width: 100 %> + <% end %> + <%= org.nickname %> <%= display_text(org.created_on&.strftime('%Y-%m-%d %H:%M')) %><%= link_to org.teams_count, "/#{org.login}", target: "_blank" %><%= link_to org.organization_users_count, "/#{org.login}", target: "_blank" %><%= link_to org.projects_count, "/#{org.login}", target: "_blank" %> + <%= link_to '查看', admins_organization_path(org), class: 'action' %> +
+ <%= javascript_void_link('更多', class: 'action dropdown-toggle', 'data-toggle': 'dropdown', 'aria-haspopup': true, 'aria-expanded': false) %> + +
+
+ +<%= render partial: 'admins/shared/paginate', locals: { objects: organizations } %> diff --git a/app/views/admins/organizations/shared/_project_list.html.erb b/app/views/admins/organizations/shared/_project_list.html.erb new file mode 100644 index 00000000..e828938f --- /dev/null +++ b/app/views/admins/organizations/shared/_project_list.html.erb @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + <% if projects.present? %> + <% projects.each_with_index do |project, index| %> + + + + + + + + + + + + + + + + <% end %> + <% else %> + <%= render 'admins/shared/no_data_for_table' %> + <% end %> + +
序号ID项目名称公开推荐Issues资源Pulls里程碑成员管理员<%= sort_tag('创建时间', name: 'created_on', path: admins_projects_path) %>操作
<%= list_index_no((params[:page] || 1).to_i, index) %><%= project.id %> + <%= link_to(project.name, "/#{project&.owner&.login}/#{project.identifier}", target: '_blank') %> + <%= project.is_public ? '√' : '' %><%= project.recommend ? '√' : '' %><%= project.issues.size %><%= project.attachments.size %><%= project&.pull_requests_count %><%= project.versions.size %><%= project.members.size %> + <%= link_to_project(project) %> + <%= project.created_on&.strftime('%Y-%m-%d %H:%M') %> + <% if project.is_public %> + <%= javascript_void_link '推荐', class: 'action recommend-action', data: { id: project.id }, style: project.recommend ? 'display: none;' : '' %> + <%= javascript_void_link '取消推荐', class: 'action unrecommend-action', data: { id: project.id }, style: project.recommend ? '' : 'display: none;' %> + <%= link_to "设置推荐等级", edit_admins_project_path(project.id), remote: true, class: "action edit-recommend-action", style: project.recommend ? '' : 'display: none;' %> + <% end %> + <%= link_to "删除", admins_project_path(project.id), method: :delete, data:{confirm: "确认删除的吗?"}, class: "delete-project-action" %> +
\ No newline at end of file diff --git a/app/views/admins/organizations/show.html.erb b/app/views/admins/organizations/show.html.erb new file mode 100644 index 00000000..b40f1c25 --- /dev/null +++ b/app/views/admins/organizations/show.html.erb @@ -0,0 +1,38 @@ +<% + define_admin_breadcrumbs do + add_admin_breadcrumb('组织管理', admins_organizations_path) + add_admin_breadcrumb('组织详情') + end +%> + +
+
+ <%= link_to "/#{@org.login}", class: 'user-info-avatar col-md-1', target: '_blank', data: { toggle: 'tooltip', title: '个人中心' } do %> + + <% end %> + +
+ + <%= simple_form_for(@org, url: admins_organization_path(@org)) do |f| %> + +
基本信息
+
+
+ <%= f.input :login, label: '登录名', wrapper_html: { class: 'col-md-3' }, input_html: { readonly: true, class: 'col-md-11', value: @org.login } %> +
+ +
+ <%= f.input :lastname, label: '姓名', wrapper_html: { class: 'col-md-3' }, input_html: { readonly: true, class: 'col-md-11', value: @org.real_name } %> +
+ + +
+ <% end %> +

组织项目

+ <%= render partial: 'admins/organizations/shared/project_list', locals: { projects: @org.projects } %> + +
diff --git a/app/views/admins/projects_rank/index.html.erb b/app/views/admins/projects_rank/index.html.erb index 056e0a0d..d3a7926b 100644 --- a/app/views/admins/projects_rank/index.html.erb +++ b/app/views/admins/projects_rank/index.html.erb @@ -19,15 +19,15 @@ 排名 - 项目 - 得分 - 访问数 - 关注数 - 点赞数 - fork数 - 疑修数 - 合并请求数 - 提交数 + 项目 + 得分 + 访问数 + 关注数 + 点赞数 + fork数 + 疑修数 + 合并请求数 + 提交数 @@ -38,7 +38,7 @@ <% owner_common = $redis_cache.hgetall("v2-owner-common:#{project_common["owner_id"]}")%> /<%= project_common["identifier"]%>"> - <%= project_common["name"] %> + <%= "#{owner_common["name"]}/#{project_common["name"]}" %> diff --git a/app/views/admins/shared/_sidebar.html.erb b/app/views/admins/shared/_sidebar.html.erb index fb96f088..fc2fe606 100644 --- a/app/views/admins/shared/_sidebar.html.erb +++ b/app/views/admins/shared/_sidebar.html.erb @@ -15,14 +15,15 @@