From 1dd3fbc69a2a63c08c1a47690665ea5d7bbb2f4e Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Thu, 3 Mar 2022 14:16:57 +0800 Subject: [PATCH 01/65] =?UTF-8?q?fixed=20fork=E5=88=97=E8=A1=A8=E4=B8=AD?= =?UTF-8?q?=E5=AD=98=E5=9C=A8=E7=BB=84=E7=BB=87=E6=97=B6=E6=98=BE=E7=A4=BA?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/views/projects/fork_users.json.jbuilder | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/views/projects/fork_users.json.jbuilder b/app/views/projects/fork_users.json.jbuilder index a539797e..f5147e19 100644 --- a/app/views/projects/fork_users.json.jbuilder +++ b/app/views/projects/fork_users.json.jbuilder @@ -1,7 +1,7 @@ json.count @forks_count json.users do json.array! @fork_users.each do |f| - user = f.user + user = f.user.present? ? f.user : Organization.find_by(id: f.user_id) json.id f.fork_project.id json.identifier f.fork_project.identifier json.name "#{user.try(:show_real_name)}/#{f.fork_project.try(:name)}" From 5cb2e55f74873bc04f223808cafc789a17ff8818 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 7 Mar 2022 09:58:05 +0800 Subject: [PATCH 02/65] add: organization users insist team nickname search --- .../organizations/organization_users_controller.rb | 6 +++++- app/models/team.rb | 5 +++++ .../organizations/organization_users/_detail.json.jbuilder | 2 +- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/app/controllers/organizations/organization_users_controller.rb b/app/controllers/organizations/organization_users_controller.rb index 1cddabc9..5f358858 100644 --- a/app/controllers/organizations/organization_users_controller.rb +++ b/app/controllers/organizations/organization_users_controller.rb @@ -5,7 +5,11 @@ class Organizations::OrganizationUsersController < Organizations::BaseController def index @organization_users = @organization.organization_users.includes(:user) search = params[:search].to_s.downcase - @organization_users = @organization_users.joins(:user).merge(User.like(search)) + user_condition_users = User.like(search).to_sql + team_condition_teams = User.joins(:teams).merge(@organization.teams.like(search)).to_sql + users = User.from("( #{user_condition_users} UNION #{team_condition_teams }) AS users") + + @organization_users = @organization_users.where(user_id: users).distinct @organization_users = kaminari_paginate(@organization_users) end diff --git a/app/models/team.rb b/app/models/team.rb index c2e63338..b831cd06 100644 --- a/app/models/team.rb +++ b/app/models/team.rb @@ -29,6 +29,11 @@ class Team < ApplicationRecord has_many :team_units, dependent: :destroy has_many :team_users, dependent: :destroy + scope :like, lambda { |keywords| + sql = "teams.nickname LIKE :search OR teams.name LIKE :search" + where(sql, :search => "%#{keywords.split(" ").join('|')}%") unless keywords.blank? + } + validates :name, uniqueness: {scope: :organization_id} enum authorize: {read: 1, write: 2, admin: 3, owner: 4} diff --git a/app/views/organizations/organization_users/_detail.json.jbuilder b/app/views/organizations/organization_users/_detail.json.jbuilder index d4c21d5f..c7572971 100644 --- a/app/views/organizations/organization_users/_detail.json.jbuilder +++ b/app/views/organizations/organization_users/_detail.json.jbuilder @@ -3,5 +3,5 @@ json.user do json.partial! "organizations/user_detail", user: org_user.user end -json.team_names org_user.teams.pluck(:name) +json.team_names org_user.teams.pluck(:nickname) json.created_at org_user.created_at.strftime("%Y-%m-%d") From c4f380873ee99dbf5f867549ac523b9896e9c503 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 7 Mar 2022 10:20:51 +0800 Subject: [PATCH 03/65] fix: is public project attachment allow is not member read --- app/controllers/attachments_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/attachments_controller.rb b/app/controllers/attachments_controller.rb index de5e0a8c..3aa98257 100644 --- a/app/controllers/attachments_controller.rb +++ b/app/controllers/attachments_controller.rb @@ -217,7 +217,7 @@ class AttachmentsController < ApplicationController if @file.container && current_user.logged? if @file.container.is_a?(Issue) course = @file.container.project - candown = course.member?(current_user) + candown = course.member?(current_user) || course.is_public elsif @file.container.is_a?(Journal) course = @file.container.issue.project candown = course.member?(current_user) From e1cf2fcdeb145d9394a4ec393647aafc325454bc Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 7 Mar 2022 10:25:05 +0800 Subject: [PATCH 04/65] fix: owner project not allow repeat name --- app/controllers/projects_controller.rb | 2 +- app/forms/projects/update_form.rb | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index c31136f8..be9a93d9 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -135,7 +135,7 @@ class ProjectsController < ApplicationController validate_params = project_params.slice(:name, :description, :project_category_id, :project_language_id, :private, :identifier) - Projects::UpdateForm.new(validate_params.merge(user_id: @project.user_id, project_identifier: @project.identifier)).validate! + Projects::UpdateForm.new(validate_params.merge(user_id: @project.user_id, project_identifier: @project.identifier, project_name: @project.name)).validate! private = @project.forked_from_project.present? ? !@project.forked_from_project.is_public : params[:private] || false diff --git a/app/forms/projects/update_form.rb b/app/forms/projects/update_form.rb index 3048bc07..a351420b 100644 --- a/app/forms/projects/update_form.rb +++ b/app/forms/projects/update_form.rb @@ -1,5 +1,5 @@ class Projects::UpdateForm < BaseForm - attr_accessor :name, :description, :project_category_id, :project_language_id, :private, :identifier, :user_id, :project_identifier + attr_accessor :name, :description, :project_category_id, :project_language_id, :private, :identifier, :user_id, :project_identifier, :project_name validates :name, presence: true validates :name, length: { maximum: 50 } validates :description, length: { maximum: 200 } @@ -10,6 +10,7 @@ class Projects::UpdateForm < BaseForm check_project_language(project_language_id) check_repository_name(user_id, identifier) unless identifier.blank? || identifier == project_identifier + check_project_name(user_id, name) unless name.blank? || name == project_name end end From e120c4dac2ebca6da1141398a3615a5357b47200 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 7 Mar 2022 10:53:07 +0800 Subject: [PATCH 05/65] add: origin repository need open pr menu --- app/controllers/compare_controller.rb | 1 + app/controllers/pull_requests_controller.rb | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/controllers/compare_controller.rb b/app/controllers/compare_controller.rb index 07691d79..b71044ce 100644 --- a/app/controllers/compare_controller.rb +++ b/app/controllers/compare_controller.rb @@ -16,6 +16,7 @@ class CompareController < ApplicationController if @base.blank? || @head.blank? return -2, "请选择分支" else + return -2, "目标仓库未开启合并请求(PR)功能" unless @project.has_menu_permission("pulls") if @head.include?(":") fork_project = @project.forked_projects.joins(:owner).where(users: {login: @head.to_s.split("/")[0]}).take return -2, "请选择正确的仓库" unless fork_project.present? diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 2417e4fd..5500ed79 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -2,7 +2,7 @@ class PullRequestsController < ApplicationController before_action :require_login, except: [:index, :show, :files, :commits] before_action :require_profile_completed, only: [:create] before_action :load_repository - before_action :check_menu_authorize + before_action :check_menu_authorize, only: [:index, :show, :create, :update, :refuse_merge, :pr_merge] 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] From ef12f856872dccdbecc57201abb10060f8daddc0 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 7 Mar 2022 11:17:10 +0800 Subject: [PATCH 06/65] fix: create pull request valid merge_user_login --- app/services/pull_requests/create_service.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/app/services/pull_requests/create_service.rb b/app/services/pull_requests/create_service.rb index d15b3f9f..794220cf 100644 --- a/app/services/pull_requests/create_service.rb +++ b/app/services/pull_requests/create_service.rb @@ -157,6 +157,7 @@ class PullRequests::CreateService < ApplicationService raise "head参数不能为空" if @params[:head].blank? raise "base参数不能为空" if @params[:base].blank? raise "fork_project_id参数错误" if is_original && !@project.forked_projects.pluck(:id).include?(@params[:fork_project_id].to_i) + raise "merge_user_login参数错误" if is_original && @project.fork_users.joins(:user).where(users: {login: @params[:merge_user_login]}).blank? raise "分支内容相同,无需创建合并请求" if @params[:head] === @params[:base] && !is_original raise "合并请求已存在" if @project&.pull_requests.where(head: @params[:head], base: @params[:base], status: 0, is_original: is_original, fork_project_id: @params[:fork_project_id]).present? raise @pull_issue.errors.full_messages.join(", ") unless pull_issue.valid? From b1c03ed5e89f12c265d177911650b065e8436084 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 10 Mar 2022 09:51:46 +0800 Subject: [PATCH 07/65] fix: activity issues must only issue --- app/controllers/users/statistics_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/users/statistics_controller.rb b/app/controllers/users/statistics_controller.rb index dffd3f60..1948af9b 100644 --- a/app/controllers/users/statistics_controller.rb +++ b/app/controllers/users/statistics_controller.rb @@ -12,7 +12,7 @@ class Users::StatisticsController < Users::BaseController @commit_data = [] date_range.each do |date| @date_data << date.strftime("%Y.%m.%d") - @issue_data << observed_user.issues.where("DATE(created_on) = ?", date).size + @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) From 8d0a6d267a87aabdf3e9e93ea6b45398c2b67914 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 10 Mar 2022 10:47:06 +0800 Subject: [PATCH 08/65] fix: download escape --- app/controllers/compare_controller.rb | 2 +- app/controllers/repositories_controller.rb | 4 ++-- app/services/pull_requests/create_service.rb | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/controllers/compare_controller.rb b/app/controllers/compare_controller.rb index b71044ce..382e7506 100644 --- a/app/controllers/compare_controller.rb +++ b/app/controllers/compare_controller.rb @@ -51,6 +51,6 @@ class CompareController < ApplicationController end def gitea_compare(base, head) - Gitea::Repository::Commits::CompareService.call(@owner.login, @project.identifier, CGI.escape(base), CGI.escape(head), current_user.gitea_token) + Gitea::Repository::Commits::CompareService.call(@owner.login, @project.identifier, Addressable::URI.escape(base), Addressable::URI.escape(head), current_user.gitea_token) end end diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index c42051e0..272e121a 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -241,7 +241,7 @@ class RepositoriesController < ApplicationController def archive domain = Gitea.gitea_config[:domain] api_url = Gitea.gitea_config[:base_url] - archive_url = "/repos/#{@owner.login}/#{@repository.identifier}/archive/#{CGI.escape(params[:archive])}" + 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? @@ -255,7 +255,7 @@ class RepositoriesController < ApplicationController domain = Gitea.gitea_config[:domain] api_url = Gitea.gitea_config[:base_url] - url = "/repos/#{@owner.login}/#{@repository.identifier}/raw/#{CGI.escape(params[:filepath])}?ref=#{CGI.escape(params[:ref])}" + url = "/repos/#{@owner.login}/#{@repository.identifier}/raw/#{Addressable::URI.escape(params[:filepath])}?ref=#{Addressable::URI.escape(params[:ref])}" file_path = [domain, api_url, url].join file_path = [file_path, "access_token=#{current_user&.gitea_token}"].join("&") diff --git a/app/services/pull_requests/create_service.rb b/app/services/pull_requests/create_service.rb index 794220cf..703bb5de 100644 --- a/app/services/pull_requests/create_service.rb +++ b/app/services/pull_requests/create_service.rb @@ -132,8 +132,8 @@ class PullRequests::CreateService < ApplicationService end def merge_original_pull_params - base_pull_params[:head] = CGI.escape(base_pull_params[:head]) - base_pull_params[:base] = CGI.escape(base_pull_params[:base]) + base_pull_params[:head] = Addressable::URI.escape(base_pull_params[:head]) + base_pull_params[:base] = Addressable::URI.escape(base_pull_params[:base]) if pull_request.is_original && @params[:merge_user_login] base_pull_params.merge(head: "#{@params[:merge_user_login]}:#{base_pull_params[:head]}") else @@ -166,7 +166,7 @@ class PullRequests::CreateService < ApplicationService def compare_head_base! head = pull_request.is_original && @params[:merge_user_login] ? "#{@params[:merge_user_login]}/#{@project.identifier}:#{@params[:head]}" : @params[:head] - compare_result = Gitea::Repository::Commits::CompareService.call(@owner.login, @project.identifier, CGI.escape(@params[:base]), CGI.escape(head), @current_user.gitea_token) + compare_result = Gitea::Repository::Commits::CompareService.call(@owner.login, @project.identifier, Addressable::URI.escape(@params[:base]), Addressable::URI.escape(head), @current_user.gitea_token) raise '分支内容相同,无需创建合并请求' if compare_result["Commits"].blank? && compare_result["Diff"].blank? end From 99fbecc8345b66197650970c2f1ee568bc430ce5 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 11 Mar 2022 14:06:12 +0800 Subject: [PATCH 09/65] =?UTF-8?q?gitea=20=E8=AF=B7=E6=B1=82=E5=BB=B6?= =?UTF-8?q?=E9=95=BF=E5=88=B020=E5=88=86=E9=92=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/gitea/client_service.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/services/gitea/client_service.rb b/app/services/gitea/client_service.rb index 7cdfdd49..b0c842db 100644 --- a/app/services/gitea/client_service.rb +++ b/app/services/gitea/client_service.rb @@ -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 = 100 # open/read timeout in seconds + req.options.timeout = 1200 # open/read timeout in seconds req.options.open_timeout = 10 # connection open timeout in seconds if token.blank? req.basic_auth(username, secret) From c0e97409cbbc11c5e10e78c8e7fce15b2e5ebc90 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 11 Mar 2022 14:07:39 +0800 Subject: [PATCH 10/65] =?UTF-8?q?gitea=20=E8=AF=B7=E6=B1=82=E5=BB=B6?= =?UTF-8?q?=E9=95=BF=E5=88=B020=E5=88=86=E9=92=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/gitea/client_service.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/services/gitea/client_service.rb b/app/services/gitea/client_service.rb index 7cdfdd49..b0c842db 100644 --- a/app/services/gitea/client_service.rb +++ b/app/services/gitea/client_service.rb @@ -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 = 100 # open/read timeout in seconds + req.options.timeout = 1200 # open/read timeout in seconds req.options.open_timeout = 10 # connection open timeout in seconds if token.blank? req.basic_auth(username, secret) From ea070d4e235f9df80b402d28188c971e42e0e7c9 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 11 Mar 2022 14:10:43 +0800 Subject: [PATCH 11/65] =?UTF-8?q?gitea=20=E8=AF=B7=E6=B1=82=E5=BB=B6?= =?UTF-8?q?=E9=95=BF=E5=88=B020=E5=88=86=E9=92=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/gitea/client_service.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/services/gitea/client_service.rb b/app/services/gitea/client_service.rb index 7cdfdd49..b0c842db 100644 --- a/app/services/gitea/client_service.rb +++ b/app/services/gitea/client_service.rb @@ -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 = 100 # open/read timeout in seconds + req.options.timeout = 1200 # open/read timeout in seconds req.options.open_timeout = 10 # connection open timeout in seconds if token.blank? req.basic_auth(username, secret) From 0156e9726c822a9a42486af66cff009186400370 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 11 Mar 2022 14:11:24 +0800 Subject: [PATCH 12/65] =?UTF-8?q?gitea=20=E8=AF=B7=E6=B1=82=E5=BB=B6?= =?UTF-8?q?=E9=95=BF=E5=88=B020=E5=88=86=E9=92=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/gitea/client_service.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/services/gitea/client_service.rb b/app/services/gitea/client_service.rb index 7cdfdd49..b0c842db 100644 --- a/app/services/gitea/client_service.rb +++ b/app/services/gitea/client_service.rb @@ -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 = 100 # open/read timeout in seconds + req.options.timeout = 1200 # open/read timeout in seconds req.options.open_timeout = 10 # connection open timeout in seconds if token.blank? req.basic_auth(username, secret) From 2346b0f8481f568f3774dbc1cad94566138df1ad Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 18 Mar 2022 11:41:26 +0800 Subject: [PATCH 13/65] =?UTF-8?q?readme.md=E6=94=AF=E6=8C=81=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E7=9B=B8=E5=AF=B9=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/helpers/repositories_helper.rb | 311 +++++++++++++++-------------- 1 file changed, 163 insertions(+), 148 deletions(-) diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index c6924185..ff17679f 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -1,148 +1,163 @@ -module RepositoriesHelper - def render_permission(user, project) - return "Admin" if user&.admin? - project.get_premission(user) - end - - def render_decode64_content(str) - return nil if str.blank? - Base64.decode64(str).force_encoding("UTF-8").encode("UTF-8", invalid: :replace) - end - - def download_type(str) - default_type = %w(xlsx xls ppt pptx pdf zip 7z rar exe pdb obj idb RData rdata doc docx mpp vsdx dot otf eot ttf woff woff2 mp4 mov wmv flv mpeg avi avchd webm mkv) - default_type.include?(str&.downcase) || str.blank? - end - - def image_type?(str) - default_type = %w(png jpg gif tif psd svg bmp webp jpeg ico psd) - default_type.include?(str&.downcase) - end - - def is_readme?(type, str) - return false if type != 'file' || str.blank? - readme_types = ["readme.md", "readme", "readme_en.md", "readme_zh.md", "readme_en", "readme_zh"] - readme_types.include?(str.to_s.downcase) - end - - def render_commit_author(author_json) - return nil if author_json.blank? || (author_json["id"].blank? && author_json['name'].blank?) - if author_json["id"].present? - return find_user_by_gitea_uid author_json['id'] - end - if author_json["id"].nil? && (author_json["name"].present? && author_json["email"].present?) - return find_user_by_login_and_mail(author_json['name'], author_json["email"]) - end - end - - def render_cache_commit_author(author_json) - Rails.logger.info author_json['Email'] - if author_json["name"].present? && author_json["email"].present? - return find_user_in_redis_cache(author_json['name'], author_json['email']) - end - if author_json["Name"].present? && author_json["Email"].present? - return find_user_in_redis_cache(author_json['Name'], author_json['Email']) - end - end - - def readme_render_decode64_content(str, owner, repo, ref) - return nil if str.blank? - begin - content = Base64.decode64(str).force_encoding('UTF-8') - - c_regex = /\!\[.*?\]\((.*?)\)/ - src_regex = /src=\"(.*?)\"/ - ss = content.to_s.scan(c_regex) - ss_src = content.to_s.scan(src_regex) - total_images = ss + ss_src - if total_images.length > 0 - total_images.each do |s| - image_title = /\"(.*?)\"/ - r_content = s[0] - remove_title = r_content.to_s.scan(image_title) - if remove_title.length > 0 - r_content = r_content.gsub(/#{remove_title[0]}/, "").strip - end - # if r_content.include?("?") - # new_r_content = r_content + "&raw=true" - # else - # new_r_content = r_content + "?raw=true" - # end - new_r_content = r_content - - 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=#{r_content}&ref=#{ref}"].join - end - content = content.gsub(/#{r_content}/, new_r_content) - end - end - - return content - rescue - return str - end - end - - # unix_time values for example: 1604382982 - def render_format_time_with_unix(unix_time) - Time.at(unix_time).strftime("%Y-%m-%d %H:%M") - end - - # date for example: 2020-11-01T19:57:27+08:00 - def render_format_time_with_date(date) - date.to_time.strftime("%Y-%m-%d %H:%M") - end - - def decode64_content(entry, owner, repo, ref, path=nil) - if is_readme?(entry['type'], entry['name']) - content = Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content'] - readme_render_decode64_content(content, owner, repo, ref) - else - file_type = File.extname(entry['name'].to_s)[1..-1] - if image_type?(file_type) - return entry['content'].nil? ? Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content'] : entry['content'] - end - if download_type(file_type) - return entry['content'] - end - render_decode64_content(entry['content']) - end - end - - def base64_to_image(path, content) - # generate to https://git.trusite.net/pawm36ozq/-/raw/branch/master/entrn.png" - content = Base64.decode64(content) - File.open(path, 'wb') { |f| f.write(content) } - end - - def render_download_image_url(dir_path, file_path, content) - full_path = file_path.starts_with?("/") ? [dir_path, file_path].join("") : [dir_path, file_path].join("/") - file_name = full_path.split("/")[-1] - # 用户名/项目标识/文件路径 - dir_path = generate_dir_path(full_path.split("/"+file_name)[0]) - - file_path = [dir_path, file_name].join('/') - - puts "##### render_download_image_url file_path: #{file_path}" - base64_to_image(file_path, content) - file_path = file_path[6..-1] - File.join(base_url, file_path) - end - - def generate_dir_path(dir_path) - # tmp_dir_path - # eg: jasder/forgeplus/raw/branch/ref - dir_path = ["public", tmp_dir, dir_path].join('/') - puts "#### dir_path: #{dir_path}" - unless Dir.exists?(dir_path) - FileUtils.mkdir_p(dir_path) ##不成功这里会抛异常 - end - dir_path - end - - def tmp_dir - "repo" - end - -end +module RepositoriesHelper + def render_permission(user, project) + return "Admin" if user&.admin? + project.get_premission(user) + end + + def render_decode64_content(str) + return nil if str.blank? + Base64.decode64(str).force_encoding("UTF-8").encode("UTF-8", invalid: :replace) + end + + def download_type(str) + default_type = %w(xlsx xls ppt pptx pdf zip 7z rar exe pdb obj idb RData rdata doc docx mpp vsdx dot otf eot ttf woff woff2 mp4 mov wmv flv mpeg avi avchd webm mkv) + default_type.include?(str&.downcase) || str.blank? + end + + def image_type?(str) + default_type = %w(png jpg gif tif psd svg bmp webp jpeg ico psd) + default_type.include?(str&.downcase) + end + + def is_readme?(type, str) + return false if type != 'file' || str.blank? + readme_types = ["readme.md", "readme", "readme_en.md", "readme_zh.md", "readme_en", "readme_zh"] + readme_types.include?(str.to_s.downcase) + end + + def render_commit_author(author_json) + return nil if author_json.blank? || (author_json["id"].blank? && author_json['name'].blank?) + if author_json["id"].present? + return find_user_by_gitea_uid author_json['id'] + end + if author_json["id"].nil? && (author_json["name"].present? && author_json["email"].present?) + return find_user_by_login_and_mail(author_json['name'], author_json["email"]) + end + end + + def render_cache_commit_author(author_json) + Rails.logger.info author_json['Email'] + if author_json["name"].present? && author_json["email"].present? + return find_user_in_redis_cache(author_json['name'], author_json['email']) + end + if author_json["Name"].present? && author_json["Email"].present? + return find_user_in_redis_cache(author_json['Name'], author_json['Email']) + end + end + + def readme_render_decode64_content(str, owner, repo, ref, path) + return nil if str.blank? + begin + content = Base64.decode64(str).force_encoding('UTF-8') + + c_regex = /\!\[.*?\]\((.*?)\)/ + src_regex = /src=\"(.*?)\"/ + ss = content.to_s.scan(c_regex) + ss_src = content.to_s.gsub("'","\"").scan(src_regex) + total_images = ss + ss_src + if total_images.length > 0 + total_images.each do |s| + image_title = /\"(.*?)\"/ + r_content = s[0] + remove_title = r_content.to_s.scan(image_title) + if remove_title.length > 0 + r_content = r_content.gsub(/#{remove_title[0]}/, "").strip + end + path_last = r_content + path_current = "" + # 相对路径处理 + if r_content.start_with?("../") + relative_path_length = r_content.split("../").size - 1 + path_pre = path.split("/").size - 1 - relative_path_length + path_pre = 0 if path_pre < 0 + path_current = path.split("/")[0..path_pre].join("/") + path_last = r_content.split("../").last + elsif r_content.start_with?("/") # 根路径处理 + path_last = r_content[1..r_content.size] + else + path_current = path + end + # if r_content.include?("?") + # new_r_content = r_content + "&raw=true" + # else + # new_r_content = r_content + "?raw=true" + # end + new_r_content = r_content + + 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 + end + content = content.gsub(/src=\"#{r_content}\"/, "src=\"#{new_r_content}\"") + end + end + + return content + rescue + return str + end + end + + # unix_time values for example: 1604382982 + def render_format_time_with_unix(unix_time) + Time.at(unix_time).strftime("%Y-%m-%d %H:%M") + end + + # date for example: 2020-11-01T19:57:27+08:00 + def render_format_time_with_date(date) + date.to_time.strftime("%Y-%m-%d %H:%M") + end + + def decode64_content(entry, owner, repo, ref, path=nil) + if is_readme?(entry['type'], entry['name']) + content = Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content'] + path = URI.escape(entry['path']).to_s.downcase.gsub("/readme.md","") + readme_render_decode64_content(content, owner, repo, ref, path) + else + file_type = File.extname(entry['name'].to_s)[1..-1] + if image_type?(file_type) + return entry['content'].nil? ? Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content'] : entry['content'] + end + if download_type(file_type) + return entry['content'] + end + render_decode64_content(entry['content']) + end + end + + def base64_to_image(path, content) + # generate to https://git.trusite.net/pawm36ozq/-/raw/branch/master/entrn.png" + content = Base64.decode64(content) + File.open(path, 'wb') { |f| f.write(content) } + end + + def render_download_image_url(dir_path, file_path, content) + full_path = file_path.starts_with?("/") ? [dir_path, file_path].join("") : [dir_path, file_path].join("/") + file_name = full_path.split("/")[-1] + # 用户名/项目标识/文件路径 + dir_path = generate_dir_path(full_path.split("/"+file_name)[0]) + + file_path = [dir_path, file_name].join('/') + + puts "##### render_download_image_url file_path: #{file_path}" + base64_to_image(file_path, content) + file_path = file_path[6..-1] + File.join(base_url, file_path) + end + + def generate_dir_path(dir_path) + # tmp_dir_path + # eg: jasder/forgeplus/raw/branch/ref + dir_path = ["public", tmp_dir, dir_path].join('/') + puts "#### dir_path: #{dir_path}" + unless Dir.exists?(dir_path) + FileUtils.mkdir_p(dir_path) ##不成功这里会抛异常 + end + dir_path + end + + def tmp_dir + "repo" + end + +end From 7f1b95c7d7d73d379d0dbbfb2a7b44418aeeb19c Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 18 Mar 2022 14:03:59 +0800 Subject: [PATCH 14/65] =?UTF-8?q?readme.md=E6=94=AF=E6=8C=81=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E7=9B=B8=E5=AF=B9=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/helpers/repositories_helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index ff17679f..599a9e1c 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -86,7 +86,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?filepath=#{path_current}/#{path_last}&ref=#{ref}"].join end content = content.gsub(/src=\"#{r_content}\"/, "src=\"#{new_r_content}\"") end From fa6f0151280ba725e6c5946816f4c220fe2c40a0 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 18 Mar 2022 14:21:12 +0800 Subject: [PATCH 15/65] =?UTF-8?q?readme.md=E6=94=AF=E6=8C=81=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E7=9B=B8=E5=AF=B9=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/helpers/repositories_helper.rb | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index 599a9e1c..e0829a33 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -48,13 +48,16 @@ module RepositoriesHelper def readme_render_decode64_content(str, owner, repo, ref, path) return nil if str.blank? begin - content = Base64.decode64(str).force_encoding('UTF-8') + # content = Base64.decode64(str).force_encoding('UTF-8') + content = "# CMSIS-NN cifar10 example\n(https://github.com/ARM-software)/**[ML-examples](https://github.com/ARM-software/ML-examples)**] and can be deployed on Arm Cortex-M CPUs using [CMSIS-NN](https://github.com/ARM-software/CMSIS_5).\n\n## Requirements:\n- CMSIS-NN in Framework/knowing/cmsis_5\n- TJpgDec in Framework/knowing/image_processing\n- Enough stack size (recommend 10240) for finsh thread which can be changed in \"RT-Thread Components->Command shell->finsh shell\" by menuconfig.\n\n## To run this demo:\n- Place the photo where you want\n- Run demo by type the command\n ``` \n cmsisnn_demo /path/to/photo" c_regex = /\!\[.*?\]\((.*?)\)/ src_regex = /src=\"(.*?)\"/ + src2_regex = /src='(.*?)'/ ss = content.to_s.scan(c_regex) - ss_src = content.to_s.gsub("'","\"").scan(src_regex) - total_images = ss + ss_src + ss_src = content.scan(src_regex) + ss_src2 = content.scan(src2_regex) + total_images = ss + ss_src + ss_src2 if total_images.length > 0 total_images.each do |s| image_title = /\"(.*?)\"/ @@ -70,7 +73,7 @@ module RepositoriesHelper relative_path_length = r_content.split("../").size - 1 path_pre = path.split("/").size - 1 - relative_path_length path_pre = 0 if path_pre < 0 - path_current = path.split("/")[0..path_pre].join("/") + path_current = path_pre == 0 ? "" : path.split("/")[0..path_pre].join("/") path_last = r_content.split("../").last elsif r_content.start_with?("/") # 根路径处理 path_last = r_content[1..r_content.size] @@ -88,7 +91,7 @@ module RepositoriesHelper # 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 end - content = content.gsub(/src=\"#{r_content}\"/, "src=\"#{new_r_content}\"") + content = content.gsub(/src=\"#{r_content}\"/, "src=\"#{new_r_content}\"").gsub(/src='#{r_content}'/, "src=\"#{new_r_content}\"") end end From fe5c18c01998d150922a7780ed4b03ed1d4e7a61 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 18 Mar 2022 14:24:03 +0800 Subject: [PATCH 16/65] =?UTF-8?q?readme.md=E6=94=AF=E6=8C=81=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E7=9B=B8=E5=AF=B9=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/helpers/repositories_helper.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index e0829a33..947500fc 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -48,8 +48,7 @@ module RepositoriesHelper def readme_render_decode64_content(str, owner, repo, ref, path) return nil if str.blank? begin - # content = Base64.decode64(str).force_encoding('UTF-8') - content = "# CMSIS-NN cifar10 example\n(https://github.com/ARM-software)/**[ML-examples](https://github.com/ARM-software/ML-examples)**] and can be deployed on Arm Cortex-M CPUs using [CMSIS-NN](https://github.com/ARM-software/CMSIS_5).\n\n## Requirements:\n- CMSIS-NN in Framework/knowing/cmsis_5\n- TJpgDec in Framework/knowing/image_processing\n- Enough stack size (recommend 10240) for finsh thread which can be changed in \"RT-Thread Components->Command shell->finsh shell\" by menuconfig.\n\n## To run this demo:\n- Place the photo where you want\n- Run demo by type the command\n ``` \n cmsisnn_demo /path/to/photo" + content = Base64.decode64(str).force_encoding('UTF-8') c_regex = /\!\[.*?\]\((.*?)\)/ src_regex = /src=\"(.*?)\"/ From 23dc2d7fb6b71aaaee5a6e190105ce8235b33984 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 18 Mar 2022 14:55:42 +0800 Subject: [PATCH 17/65] =?UTF-8?q?=E7=9B=AE=E5=BD=95=E6=A0=91=E5=8A=A0?= =?UTF-8?q?=E8=BD=BD=E5=9B=BE=E7=89=87=E4=B8=8D=E9=9C=80=E8=A6=81Content?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/views/repositories/_simple_entry.json.jbuilder | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/views/repositories/_simple_entry.json.jbuilder b/app/views/repositories/_simple_entry.json.jbuilder index 9d0998c8..723f7d90 100644 --- a/app/views/repositories/_simple_entry.json.jbuilder +++ b/app/views/repositories/_simple_entry.json.jbuilder @@ -9,7 +9,7 @@ if @project.forge? json.type entry['type'] json.size entry['size'] - json.content direct_download ? nil : decode64_content(entry, @owner, @repository, @ref, @path) + json.content (direct_download || image_type) ? nil : decode64_content(entry, @owner, @repository, @ref, @path) json.target entry['target'] download_url = From d9ae4e4ba018bd84d81006d06c031c963f83fb1c Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 18 Mar 2022 16:52:23 +0800 Subject: [PATCH 18/65] =?UTF-8?q?fixed:=201.readme=E5=8A=A0=E8=BD=BD?= =?UTF-8?q?=E4=B8=8D=E6=AD=A3=E5=B8=B8,=202.=E6=96=87=E4=BB=B6=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E5=8A=A0=E8=BD=BD=E6=80=A7=E8=83=BD=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/repositories_controller.rb | 780 +++++++++--------- app/helpers/repositories_helper.rb | 9 + .../repositories/_simple_entry.json.jbuilder | 7 +- 3 files changed, 403 insertions(+), 393 deletions(-) diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index 272e121a..c46bf893 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -1,390 +1,390 @@ -class RepositoriesController < ApplicationController - include RepositoriesHelper - include ApplicationHelper - include OperateProjectAbilityAble - include Repository::LanguagesPercentagable - - before_action :require_login, only: %i[edit update create_file update_file delete_file sync_mirror] - before_action :require_profile_completed, only: [:create_file] - before_action :load_repository - before_action :authorizate!, except: [:sync_mirror, :tags, :commit, :archive] - before_action :authorizate_user_can_edit_repo!, only: %i[sync_mirror] - before_action :get_ref, only: %i[entries sub_entries top_counts file archive] - before_action :get_latest_commit, only: %i[entries sub_entries top_counts] - before_action :get_statistics, only: %i[top_counts] - - def files - result = @project.educoder? ? nil : Gitea::Repository::Files::GetService.call(@owner, @project.identifier, @ref, params[:search], @owner.gitea_token) - render json: result - end - - # 新版项目详情 - def detail - @user = current_user - @result = Repositories::DetailService.call(@owner, @repository, @user) - @project_fork_id = @project.try(:forked_from_project_id) - if @project_fork_id.present? - @fork_project = Project.find_by(id: @project_fork_id) - @fork_project_user = @fork_project.owner - end - rescue Exception => e - uid_logger_error(e.message) - tip_exception(e.message) - end - - def show - @user = current_user - @repo = @project.repository - @result = @project.forge? ? Gitea::Repository::GetService.new(@owner, @project.identifier).call : nil - @project_fork_id = @project.try(:forked_from_project_id) - if @project_fork_id.present? - @fork_project = Project.find_by(id: @project_fork_id) - @fork_project_user = @fork_project.owner - end - rescue Exception => e - uid_logger_error(e.message) - tip_exception(e.message) - end - - def entries - @project.increment!(:visits) - CacheAsyncSetJob.perform_later("project_common_service", {visits: 1}, @project.id) - if @project.educoder? - @entries = Educoder::Repository::Entries::ListService.call(@project&.project_educoder.repo_name) - else - @entries = Gitea::Repository::Entries::ListService.new(@owner, @project.identifier, ref: @ref).call - @entries = @entries.present? ? @entries.sort_by{ |hash| hash['type'] } : [] - @path = Gitea.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/" - end - end - - def top_counts - @result = @project.educoder? ? nil : Gitea::Repository::GetService.new(@project.owner, @project.identifier).call - end - - def sub_entries - file_path_uri = URI.parse(URI.encode(params[:filepath].to_s.strip)) - - if @project.educoder? - if params[:type] === 'file' - @sub_entries = Educoder::Repository::Entries::GetService.call(@project&.project_educoder&.repo_name, file_path_uri) - logger.info "######### sub_entries: #{@sub_entries}" - return render_error('该文件暂未开放,敬请期待.') if @sub_entries['status'].to_i === -1 - - tmp_entries = { - "content" => @sub_entries['data']['content'], - "type" => "blob" - } - @sub_entries = { - "trees"=>tmp_entries, - "commits" => [{}] - } - else - begin - @sub_entries = Educoder::Repository::Entries::ListService.call(@project&.project_educoder&.repo_name, {path: file_path_uri}) - if @sub_entries.blank? || @sub_entries['status'].to_i === -1 - @sub_entries = Educoder::Repository::Entries::GetService.call(@project&.project_educoder&.repo_name, file_path_uri) - return render_error('该文件暂未开放,敬请期待.') if @sub_entries['status'].to_i === -1 - tmp_entries = { - "content" => @sub_entries['data']['content'], - "type" => "blob" - } - @sub_entries = { - "trees"=>tmp_entries, - "commits" => [{}] - } - end - rescue - return render_error('该文件暂未开放,敬请期待.') - end - end - else - @path = Gitea.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/" - interactor = Repositories::EntriesInteractor.call(@owner, @project.identifier, file_path_uri, ref: @ref) - if interactor.success? - result = interactor.result - @sub_entries = result.is_a?(Array) ? result.sort_by{ |hash| hash['type'] } : result - else - render_error(interactor.error) - end - end - end - - def commits - if @project.educoder? - @commits = Educoder::Repository::Commits::ListService.call(@project&.project_educoder&.repo_name) - else - 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 - 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 - end - end - end - - def commits_slice - @hash_commit = Gitea::Repository::Commits::ListSliceService.call(@owner.login, @project.identifier, - sha: params[:sha], page: params[:page], limit: params[:limit], token: current_user&.gitea_token) - end - - def commit - @sha = params[:sha] - 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}) - end - end - - def tags - result = Gitea::Repository::Tags::ListService.call(current_user&.gitea_token, @owner.login, @project.identifier, {page: params[:page], limit: params[:limit]}) - - @tags = result.is_a?(Hash) && result.key?(:status) ? [] : result - end - - def contributors - 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 - end - rescue - @contributors = [] - end - - def edit - return render_forbidden if !@project.manager?(current_user) && !current_user.admin? - end - - def create_file - interactor = Gitea::CreateFileInteractor.call(current_user.gitea_token, @owner.login, content_params) - if interactor.success? - @file = interactor.result - # create_new_pr(params) - #如果是更新流水线文件 - if params[:pipeline_id] - update_pipeline(params[:pipeline_id]) - end - else - render_error(interactor.error) - end - end - - def update_pipeline(pipeline_id) - pipeline = Ci::Pipeline.find(pipeline_id) - if pipeline - pipeline.update!(sync: 1) - end - end - - def update_file - interactor = Gitea::UpdateFileInteractor.call(current_user.gitea_token, @owner.login, params.merge(identifier: @project.identifier)) - if interactor.success? - @file = interactor.result - # TODO: 是否创建pr - # create_new_pr(params) - render_result(1, "更新成功") - 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? - @file = interactor.result - render_result(1, "文件删除成功") - else - render_error(interactor.error) - end - end - - def repo_hook - - end - - def sync_mirror - return render_error("正在镜像中..") if @repository.mirror.waiting? - - @repository.sync_mirror! - SyncMirroredRepositoryJob.perform_later(@repository.id, current_user.id) - render_ok - end - - def readme - if params[:filepath].present? - result = Gitea::Repository::Readme::DirService.call(@owner.login, @repository.identifier, params[:filepath], params[:ref], current_user&.gitea_token) - else - result = Gitea::Repository::Readme::GetService.call(@owner.login, @repository.identifier, params[:ref], current_user&.gitea_token) - end - @path = Gitea.gitea_config[:domain]+"/#{@owner.login}/#{@repository.identifier}/raw/branch/#{params[:ref]}/" - @readme = result[:status] === :success ? result[:body] : nil - @readme['content'] = decode64_content(@readme, @owner, @repository, params[:ref], @path) - render json: @readme.slice("type", "encoding", "size", "name", "path", "content", "sha") - rescue - render json: nil - end - - def languages - if @project.educoder? - render json: {} - else - render json: languages_precentagable - end - end - - def archive - domain = Gitea.gitea_config[:domain] - api_url = Gitea.gitea_config[:base_url] - 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? - - return render_not_found if !request.format.zip? && !request.format.gzip? - - redirect_to file_path - end - - def raw - domain = Gitea.gitea_config[:domain] - api_url = Gitea.gitea_config[:base_url] - - url = "/repos/#{@owner.login}/#{@repository.identifier}/raw/#{Addressable::URI.escape(params[:filepath])}?ref=#{Addressable::URI.escape(params[:ref])}" - file_path = [domain, api_url, url].join - file_path = [file_path, "access_token=#{current_user&.gitea_token}"].join("&") - - redirect_to file_path - end - - private - - def find_project - @project = Project.find params[:id] - render_not_found("未找到相关的仓库") unless @project - end - - def find_project_with_includes - @project = Project.includes(:repository, :owner, :watchers, :praise_treads).find params[:id] - end - - def authorizate! - return if current_user && current_user.admin? - if @project.repository.hidden? && !@project.member?(current_user) - render_forbidden - end - end - - # TODO 获取最新commit信息 - def project_commits - 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 - else - Gitea::Repository::Commits::ListService.new(@project.owner.login, @project.identifier, - sha: get_ref, page: 1, limit: 1, token: current_user&.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 - end - - def get_ref - @ref = params[:ref] || @project&.default_branch - end - - def get_latest_commit - latest_commit = @project.educoder? ? nil : project_commits - @latest_commit = latest_commit.present? ? latest_commit[:body][0] : nil - @commits_count = latest_commit.present? ? latest_commit[:total_count] : 0 - end - - def content_params - { - filepath: params[:filepath], - branch: params[:branch], - new_branch: params[:new_branch], - content: params[:content], - message: params[:message], - committer: { - email: current_user.mail, - name: current_user.login - }, - identifier: @project.identifier - } - end - - def hook_params(hook_type, params) - # if hook_type == "push" - # # TODO hook返回的记录中,暂时没有文件代码数量的增减,暂时根据 commits数量来计算 - # uploadPushInfo = { - # "sha": params["commits"].present? ? params["commits"].last : "", - # "branch": params["ref"].to_s.split("/").last, - # "modification_lines": params["commits"].length - # } - # elsif hook_type == "pull_request" && params["action"].to_s == "closed" #合并请求合并后才会有上链操作 - # uploadPushInfo = { - # "branch": params["base"]["ref"].to_s.split("/").last, - # "sha": params["pull_request"]["merge_base"], - # "modification_lines": 1 #pull_request中没有commits数量 - # } - # else - # uploadPushInfo = {} - # end - - # uploadPushInfo - end - - def create_new_pr(params) - if params[:new_branch].present? && params[:new_branch] != params[:branch] - local_params = { - title: params[:message], #标题 - body: params[:content], #内容 - head: params[:new_branch], #源分支 - base: params[:branch], #目标分支 - milestone: 0 #里程碑,未与本地的里程碑关联 - - } - requests_params = local_params.merge({ - assignee: current_user.try(:login), - assignees: [], - labels: [], - due_date: Time.now - }) - - issue_params = { - author_id: current_user.id, - project_id: @project.id, - subject: params[:message], - description: params[:content], - assigned_to_id: nil, - fixed_version_id: nil, - issue_tags_value: nil, - issue_classify: "pull_request", - issue_type: "1", - tracker_id: 2, - status_id: 1, - priority_id: params[:priority_id] || "2" - } - @pull_issue = Issue.new(issue_params) - if @pull_issue.save! - local_requests = PullRequest.new(local_params.merge(user_id: current_user.try(:id), project_id: @project.id, issue_id: @pull_issue.id)) - if local_requests.save - gitea_request = Gitea::PullRequest::CreateService.new(current_user.try(:gitea_token), @owner.login, @project.try(:identifier), requests_params).call - if gitea_request[:status] == :success && local_requests.update_attributes(gpid: gitea_request["body"]["number"]) - local_requests.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create") - end - end - end - end - end - -end +class RepositoriesController < ApplicationController + include RepositoriesHelper + include ApplicationHelper + include OperateProjectAbilityAble + include Repository::LanguagesPercentagable + + before_action :require_login, only: %i[edit update create_file update_file delete_file sync_mirror] + before_action :require_profile_completed, only: [:create_file] + before_action :load_repository + before_action :authorizate!, except: [:sync_mirror, :tags, :commit, :archive] + before_action :authorizate_user_can_edit_repo!, only: %i[sync_mirror] + before_action :get_ref, only: %i[entries sub_entries top_counts file archive] + before_action :get_latest_commit, only: %i[entries sub_entries top_counts] + before_action :get_statistics, only: %i[top_counts] + + def files + result = @project.educoder? ? nil : Gitea::Repository::Files::GetService.call(@owner, @project.identifier, @ref, params[:search], @owner.gitea_token) + render json: result + end + + # 新版项目详情 + def detail + @user = current_user + @result = Repositories::DetailService.call(@owner, @repository, @user) + @project_fork_id = @project.try(:forked_from_project_id) + if @project_fork_id.present? + @fork_project = Project.find_by(id: @project_fork_id) + @fork_project_user = @fork_project.owner + end + rescue Exception => e + uid_logger_error(e.message) + tip_exception(e.message) + end + + def show + @user = current_user + @repo = @project.repository + @result = @project.forge? ? Gitea::Repository::GetService.new(@owner, @project.identifier).call : nil + @project_fork_id = @project.try(:forked_from_project_id) + if @project_fork_id.present? + @fork_project = Project.find_by(id: @project_fork_id) + @fork_project_user = @fork_project.owner + end + rescue Exception => e + uid_logger_error(e.message) + tip_exception(e.message) + end + + def entries + @project.increment!(:visits) + CacheAsyncSetJob.perform_later("project_common_service", {visits: 1}, @project.id) + if @project.educoder? + @entries = Educoder::Repository::Entries::ListService.call(@project&.project_educoder.repo_name) + else + @entries = Gitea::Repository::Entries::ListService.new(@owner, @project.identifier, ref: @ref).call + @entries = @entries.present? ? @entries.sort_by{ |hash| hash['type'] } : [] + @path = Gitea.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/" + end + end + + def top_counts + @result = @project.educoder? ? nil : Gitea::Repository::GetService.new(@project.owner, @project.identifier).call + end + + def sub_entries + file_path_uri = URI.parse(URI.encode(params[:filepath].to_s.strip)) + + if @project.educoder? + if params[:type] === 'file' + @sub_entries = Educoder::Repository::Entries::GetService.call(@project&.project_educoder&.repo_name, file_path_uri) + logger.info "######### sub_entries: #{@sub_entries}" + return render_error('该文件暂未开放,敬请期待.') if @sub_entries['status'].to_i === -1 + + tmp_entries = { + "content" => @sub_entries['data']['content'], + "type" => "blob" + } + @sub_entries = { + "trees"=>tmp_entries, + "commits" => [{}] + } + else + begin + @sub_entries = Educoder::Repository::Entries::ListService.call(@project&.project_educoder&.repo_name, {path: file_path_uri}) + if @sub_entries.blank? || @sub_entries['status'].to_i === -1 + @sub_entries = Educoder::Repository::Entries::GetService.call(@project&.project_educoder&.repo_name, file_path_uri) + return render_error('该文件暂未开放,敬请期待.') if @sub_entries['status'].to_i === -1 + tmp_entries = { + "content" => @sub_entries['data']['content'], + "type" => "blob" + } + @sub_entries = { + "trees"=>tmp_entries, + "commits" => [{}] + } + end + rescue + return render_error('该文件暂未开放,敬请期待.') + end + end + else + @path = Gitea.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{@ref}/" + interactor = Repositories::EntriesInteractor.call(@owner, @project.identifier, file_path_uri, ref: @ref) + if interactor.success? + result = interactor.result + @sub_entries = result.is_a?(Array) ? result.sort_by{ |hash| hash['type'] } : result + else + render_error(interactor.error) + end + end + end + + def commits + if @project.educoder? + @commits = Educoder::Repository::Commits::ListService.call(@project&.project_educoder&.repo_name) + else + 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 + 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 + end + end + end + + def commits_slice + @hash_commit = Gitea::Repository::Commits::ListSliceService.call(@owner.login, @project.identifier, + sha: params[:sha], page: params[:page], limit: params[:limit], token: current_user&.gitea_token) + end + + def commit + @sha = params[:sha] + 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}) + end + end + + def tags + result = Gitea::Repository::Tags::ListService.call(current_user&.gitea_token, @owner.login, @project.identifier, {page: params[:page], limit: params[:limit]}) + + @tags = result.is_a?(Hash) && result.key?(:status) ? [] : result + end + + def contributors + 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 + end + rescue + @contributors = [] + end + + def edit + return render_forbidden if !@project.manager?(current_user) && !current_user.admin? + end + + def create_file + interactor = Gitea::CreateFileInteractor.call(current_user.gitea_token, @owner.login, content_params) + if interactor.success? + @file = interactor.result + # create_new_pr(params) + #如果是更新流水线文件 + if params[:pipeline_id] + update_pipeline(params[:pipeline_id]) + end + else + render_error(interactor.error) + end + end + + def update_pipeline(pipeline_id) + pipeline = Ci::Pipeline.find(pipeline_id) + if pipeline + pipeline.update!(sync: 1) + end + end + + def update_file + interactor = Gitea::UpdateFileInteractor.call(current_user.gitea_token, @owner.login, params.merge(identifier: @project.identifier)) + if interactor.success? + @file = interactor.result + # TODO: 是否创建pr + # create_new_pr(params) + render_result(1, "更新成功") + 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? + @file = interactor.result + render_result(1, "文件删除成功") + else + render_error(interactor.error) + end + end + + def repo_hook + + end + + def sync_mirror + return render_error("正在镜像中..") if @repository.mirror.waiting? + + @repository.sync_mirror! + SyncMirroredRepositoryJob.perform_later(@repository.id, current_user.id) + render_ok + end + + def readme + if params[:filepath].present? + result = Gitea::Repository::Readme::DirService.call(@owner.login, @repository.identifier, params[:filepath], params[:ref], current_user&.gitea_token) + else + result = Gitea::Repository::Readme::GetService.call(@owner.login, @repository.identifier, params[:ref], current_user&.gitea_token) + end + @path = Gitea.gitea_config[:domain]+"/#{@owner.login}/#{@repository.identifier}/raw/branch/#{params[:ref]}/" + @readme = result[:status] === :success ? result[:body] : nil + @readme['content'] = decode64_readme_content(@readme, @owner, @repository, params[:ref], @path) + render json: @readme.slice("type", "encoding", "size", "name", "path", "content", "sha") + rescue + render json: nil + end + + def languages + if @project.educoder? + render json: {} + else + render json: languages_precentagable + end + end + + def archive + domain = Gitea.gitea_config[:domain] + api_url = Gitea.gitea_config[:base_url] + 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? + + return render_not_found if !request.format.zip? && !request.format.gzip? + + redirect_to file_path + end + + def raw + domain = Gitea.gitea_config[:domain] + api_url = Gitea.gitea_config[:base_url] + + url = "/repos/#{@owner.login}/#{@repository.identifier}/raw/#{Addressable::URI.escape(params[:filepath])}?ref=#{Addressable::URI.escape(params[:ref])}" + file_path = [domain, api_url, url].join + file_path = [file_path, "access_token=#{current_user&.gitea_token}"].join("&") + + redirect_to file_path + end + + private + + def find_project + @project = Project.find params[:id] + render_not_found("未找到相关的仓库") unless @project + end + + def find_project_with_includes + @project = Project.includes(:repository, :owner, :watchers, :praise_treads).find params[:id] + end + + def authorizate! + return if current_user && current_user.admin? + if @project.repository.hidden? && !@project.member?(current_user) + render_forbidden + end + end + + # TODO 获取最新commit信息 + def project_commits + 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 + else + Gitea::Repository::Commits::ListService.new(@project.owner.login, @project.identifier, + sha: get_ref, page: 1, limit: 1, token: current_user&.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 + end + + def get_ref + @ref = params[:ref] || @project&.default_branch + end + + def get_latest_commit + latest_commit = @project.educoder? ? nil : project_commits + @latest_commit = latest_commit.present? ? latest_commit[:body][0] : nil + @commits_count = latest_commit.present? ? latest_commit[:total_count] : 0 + end + + def content_params + { + filepath: params[:filepath], + branch: params[:branch], + new_branch: params[:new_branch], + content: params[:content], + message: params[:message], + committer: { + email: current_user.mail, + name: current_user.login + }, + identifier: @project.identifier + } + end + + def hook_params(hook_type, params) + # if hook_type == "push" + # # TODO hook返回的记录中,暂时没有文件代码数量的增减,暂时根据 commits数量来计算 + # uploadPushInfo = { + # "sha": params["commits"].present? ? params["commits"].last : "", + # "branch": params["ref"].to_s.split("/").last, + # "modification_lines": params["commits"].length + # } + # elsif hook_type == "pull_request" && params["action"].to_s == "closed" #合并请求合并后才会有上链操作 + # uploadPushInfo = { + # "branch": params["base"]["ref"].to_s.split("/").last, + # "sha": params["pull_request"]["merge_base"], + # "modification_lines": 1 #pull_request中没有commits数量 + # } + # else + # uploadPushInfo = {} + # end + + # uploadPushInfo + end + + def create_new_pr(params) + if params[:new_branch].present? && params[:new_branch] != params[:branch] + local_params = { + title: params[:message], #标题 + body: params[:content], #内容 + head: params[:new_branch], #源分支 + base: params[:branch], #目标分支 + milestone: 0 #里程碑,未与本地的里程碑关联 + + } + requests_params = local_params.merge({ + assignee: current_user.try(:login), + assignees: [], + labels: [], + due_date: Time.now + }) + + issue_params = { + author_id: current_user.id, + project_id: @project.id, + subject: params[:message], + description: params[:content], + assigned_to_id: nil, + fixed_version_id: nil, + issue_tags_value: nil, + issue_classify: "pull_request", + issue_type: "1", + tracker_id: 2, + status_id: 1, + priority_id: params[:priority_id] || "2" + } + @pull_issue = Issue.new(issue_params) + if @pull_issue.save! + local_requests = PullRequest.new(local_params.merge(user_id: current_user.try(:id), project_id: @project.id, issue_id: @pull_issue.id)) + if local_requests.save + gitea_request = Gitea::PullRequest::CreateService.new(current_user.try(:gitea_token), @owner.login, @project.try(:identifier), requests_params).call + if gitea_request[:status] == :success && local_requests.update_attributes(gpid: gitea_request["body"]["number"]) + local_requests.project_trends.create(user_id: current_user.id, project_id: @project.id, action_type: "create") + end + end + end + end + end + +end diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index 947500fc..e5d76319 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -110,6 +110,15 @@ module RepositoriesHelper date.to_time.strftime("%Y-%m-%d %H:%M") end + def decode64_readme_content(entry, owner, repo, ref, path=nil) + if is_readme?(entry['type'], entry['name']) + path = URI.escape(entry['path']).to_s.downcase.gsub("/readme.md","") + readme_render_decode64_content(entry['content'], owner, repo, ref, path) + else + render_decode64_content(entry['content']) + end + end + def decode64_content(entry, owner, repo, ref, path=nil) if is_readme?(entry['type'], entry['name']) content = Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content'] diff --git a/app/views/repositories/_simple_entry.json.jbuilder b/app/views/repositories/_simple_entry.json.jbuilder index 723f7d90..261eb4d2 100644 --- a/app/views/repositories/_simple_entry.json.jbuilder +++ b/app/views/repositories/_simple_entry.json.jbuilder @@ -1,4 +1,5 @@ if @project.forge? + is_dir = @sub_entries.is_a?(Array) file_name = entry['name'] file_type = File.extname(file_name.to_s)[1..-1] direct_download = download_type(file_type) @@ -9,16 +10,16 @@ if @project.forge? json.type entry['type'] json.size entry['size'] - json.content (direct_download || image_type) ? nil : decode64_content(entry, @owner, @repository, @ref, @path) + json.content (direct_download || image_type || is_dir) ? nil : decode64_content(entry, @owner, @repository, @ref, @path) json.target entry['target'] download_url = if image_type dir_path = [@owner.login, @repository.identifier, "raw/branch", @ref].join('/') - render_download_image_url(dir_path, entry['path'], decode64_content(entry, @owner, @repository, @ref)) + is_dir ? "" : render_download_image_url(dir_path, entry['path'], decode64_content(entry, @owner, @repository, @ref)) else # entry['download_url'] - render_download_file_url(@owner, @repository, entry['path'].to_s, @ref) + is_dir ? "" : render_download_file_url(@owner, @repository, entry['path'].to_s, @ref) end json.download_url download_url From 9912ad07794e611db30f29376cbb2f19ec082534 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 18 Mar 2022 17:09:06 +0800 Subject: [PATCH 19/65] =?UTF-8?q?fixed:=201.readme=E5=8A=A0=E8=BD=BD?= =?UTF-8?q?=E4=B8=8D=E6=AD=A3=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/helpers/repositories_helper.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index e5d76319..506263a8 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -62,9 +62,9 @@ module RepositoriesHelper image_title = /\"(.*?)\"/ r_content = s[0] remove_title = r_content.to_s.scan(image_title) - if remove_title.length > 0 - r_content = r_content.gsub(/#{remove_title[0]}/, "").strip - end + # if remove_title.length > 0 + # r_content = r_content.gsub(/#{remove_title[0]}/, "").strip + # end path_last = r_content path_current = "" # 相对路径处理 From 930805704a144ce898a8dd47e73c9b22a72ad6cc Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 18 Mar 2022 17:32:29 +0800 Subject: [PATCH 20/65] =?UTF-8?q?fixed:=20=E6=96=87=E4=BB=B6=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E5=8A=A0=E8=BD=BD=E6=80=A7=E8=83=BD=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/repositories_controller.rb | 2 +- app/helpers/repositories_helper.rb | 12 ++---------- 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb index c46bf893..9fef22fc 100644 --- a/app/controllers/repositories_controller.rb +++ b/app/controllers/repositories_controller.rb @@ -224,7 +224,7 @@ class RepositoriesController < ApplicationController end @path = Gitea.gitea_config[:domain]+"/#{@owner.login}/#{@repository.identifier}/raw/branch/#{params[:ref]}/" @readme = result[:status] === :success ? result[:body] : nil - @readme['content'] = decode64_readme_content(@readme, @owner, @repository, params[:ref], @path) + @readme['content'] = decode64_content(@readme, @owner, @repository, params[:ref], @path) render json: @readme.slice("type", "encoding", "size", "name", "path", "content", "sha") rescue render json: nil diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index 506263a8..62d27a74 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -110,18 +110,10 @@ module RepositoriesHelper date.to_time.strftime("%Y-%m-%d %H:%M") end - def decode64_readme_content(entry, owner, repo, ref, path=nil) - if is_readme?(entry['type'], entry['name']) - path = URI.escape(entry['path']).to_s.downcase.gsub("/readme.md","") - readme_render_decode64_content(entry['content'], owner, repo, ref, path) - else - render_decode64_content(entry['content']) - end - end - def decode64_content(entry, owner, repo, ref, path=nil) if is_readme?(entry['type'], entry['name']) - content = Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content'] + # content = Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content'] + content = entry['content'] path = URI.escape(entry['path']).to_s.downcase.gsub("/readme.md","") readme_render_decode64_content(content, owner, repo, ref, path) else From bc639488aa641450ab15622e0b327c3afc906fd3 Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 22 Mar 2022 10:45:14 +0800 Subject: [PATCH 21/65] fix: issues filter error --- app/controllers/issues_controller.rb | 2 +- app/controllers/pull_requests_controller.rb | 2 +- app/services/issues/list_query_service.rb | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index ad53a4b3..b546ea71 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -24,7 +24,7 @@ class IssuesController < ApplicationController @filter_issues = @all_issues @filter_issues = @filter_issues.where.not(status_id: IssueStatus::CLOSED) if params[:status_type].to_i == IssueStatus::ADD @filter_issues = @filter_issues.where(status_id: IssueStatus::CLOSED) if params[:status_type].to_i == IssueStatus::SOLVING - @filter_issues = @filter_issues.where("subject LIKE ? OR description LIKE ? ", "%#{params[:search]}%", "%#{params[:search]}%") if params[:search].present? + @filter_issues = @filter_issues.where("issues.subject LIKE ? OR issues.description LIKE ? ", "%#{params[:search]}%", "%#{params[:search]}%") if params[:search].present? @open_issues = @all_issues.where.not(status_id: IssueStatus::CLOSED) @close_issues = @all_issues.where(status_id: IssueStatus::CLOSED) scopes = Issues::ListQueryService.call(issues,params.delete_if{|k,v| v.blank?}, "Issue") diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 5500ed79..189c5c6b 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -16,7 +16,7 @@ class PullRequestsController < ApplicationController issues = issues.where(is_private: false) unless current_user.present? && (current_user.admin? || @project.member?(current_user)) @all_issues = issues.distinct @filter_issues = @all_issues - @filter_issues = @filter_issues.where("subject LIKE ? OR description LIKE ? ", "%#{params[:search]}%", "%#{params[:search]}%") if params[:search].present? + @filter_issues = @filter_issues.where("issues.subject LIKE ? OR issues.description LIKE ? ", "%#{params[:search]}%", "%#{params[:search]}%") if params[:search].present? @open_issues = @filter_issues.joins(:pull_request).where(pull_requests: {status: PullRequest::OPEN}) @close_issues = @filter_issues.joins(:pull_request).where(pull_requests: {status: PullRequest::CLOSED}) @merged_issues = @filter_issues.joins(:pull_request).where(pull_requests: {status: PullRequest::MERGED}) diff --git a/app/services/issues/list_query_service.rb b/app/services/issues/list_query_service.rb index f85e2cb9..def9644d 100644 --- a/app/services/issues/list_query_service.rb +++ b/app/services/issues/list_query_service.rb @@ -27,12 +27,12 @@ class Issues::ListQueryService < ApplicationService issues = issues.joins(:pull_request).where(pull_requests: {status: 1}) end - if search_name.present? - issues = issues.where("subject LIKE ? OR description LIKE ? ", "%#{search_name}%", "%#{search_name}%") - end + # if search_name.present? + # issues = issues.where("issues.subject LIKE ? OR issues.description LIKE ? ", "%#{search_name}%", "%#{search_name}%") + # end if start_time&.present? || end_time&.present? - issues = issues.where("start_date between ? and ?",start_time&.present? ? start_time.to_date : Time.now.to_date, end_time&.present? ? end_time.to_date : Time.now.to_date) + issues = issues.where("issues.start_date between ? and ?",start_time&.present? ? start_time.to_date : Time.now.to_date, end_time&.present? ? end_time.to_date : Time.now.to_date) end issues = issues.where(author_id: params[:author_id]) if params[:author_id].present? && params[:author_id].to_s != "all" From 183315bbd94a35c17fff29f0660574b40a29fbe8 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Thu, 24 Mar 2022 10:25:24 +0800 Subject: [PATCH 22/65] =?UTF-8?q?=E4=B8=87=E8=83=BD=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E7=A0=81=EF=BC=8C=E7=94=A8=E4=BA=8E=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/forms/base_form.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/forms/base_form.rb b/app/forms/base_form.rb index 598644fc..ca82fa4b 100644 --- a/app/forms/base_form.rb +++ b/app/forms/base_form.rb @@ -49,7 +49,7 @@ class BaseForm def check_verifi_code(verifi_code, code) code = strip(code) - # return if code == "123123" # TODO 万能验证码,用于测试 + return if code == "123123" && EduSetting.get("code_debug") # 万能验证码,用于测试 # TODO 万能验证码,用于测试 raise VerifiCodeError, "验证码已失效" if !verifi_code&.effective? raise VerifiCodeError, "验证码不正确" if verifi_code&.code != code end From d0d906d04c4e7c97ec9c602bbcbd578b92e4a157 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 28 Mar 2022 11:05:21 +0800 Subject: [PATCH 23/65] fix: readme image regex error rescued --- app/helpers/repositories_helper.rb | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index c6924185..e6e7e87f 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -57,6 +57,7 @@ module RepositoriesHelper total_images = ss + ss_src if total_images.length > 0 total_images.each do |s| + begin image_title = /\"(.*?)\"/ r_content = s[0] remove_title = r_content.to_s.scan(image_title) @@ -75,6 +76,9 @@ module RepositoriesHelper new_r_content = [base_url, "/api/#{owner&.login}/#{repo.identifier}/raw?filepath=#{r_content}&ref=#{ref}"].join end content = content.gsub(/#{r_content}/, new_r_content) + rescue + next + end end end @@ -96,7 +100,9 @@ module RepositoriesHelper def decode64_content(entry, owner, repo, ref, path=nil) if is_readme?(entry['type'], entry['name']) + Rails.logger.info("entry===#{entry["type"]} #{entry["name"]}") content = Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content'] + Rails.logger.info("content===#{content}") readme_render_decode64_content(content, owner, repo, ref) else file_type = File.extname(entry['name'].to_s)[1..-1] From a5be4a950225a6845b00609f3ed36ca74e236046 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 28 Mar 2022 11:25:13 +0800 Subject: [PATCH 24/65] fix: readme image regex error rescued --- app/helpers/repositories_helper.rb | 64 ++++++++++++++++-------------- 1 file changed, 34 insertions(+), 30 deletions(-) diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index 62d27a74..f1556376 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -59,38 +59,42 @@ module RepositoriesHelper total_images = ss + ss_src + ss_src2 if total_images.length > 0 total_images.each do |s| - image_title = /\"(.*?)\"/ - r_content = s[0] - remove_title = r_content.to_s.scan(image_title) - # if remove_title.length > 0 - # r_content = r_content.gsub(/#{remove_title[0]}/, "").strip - # end - path_last = r_content - path_current = "" - # 相对路径处理 - if r_content.start_with?("../") - relative_path_length = r_content.split("../").size - 1 - path_pre = path.split("/").size - 1 - relative_path_length - path_pre = 0 if path_pre < 0 - path_current = path_pre == 0 ? "" : path.split("/")[0..path_pre].join("/") - path_last = r_content.split("../").last - elsif r_content.start_with?("/") # 根路径处理 - path_last = r_content[1..r_content.size] - else - path_current = path - end - # if r_content.include?("?") - # new_r_content = r_content + "&raw=true" - # else - # new_r_content = r_content + "?raw=true" - # end - new_r_content = r_content + begin + image_title = /\"(.*?)\"/ + r_content = s[0] + remove_title = r_content.to_s.scan(image_title) + # if remove_title.length > 0 + # r_content = r_content.gsub(/#{remove_title[0]}/, "").strip + # end + path_last = r_content + path_current = "" + # 相对路径处理 + if r_content.start_with?("../") + relative_path_length = r_content.split("../").size - 1 + path_pre = path.split("/").size - 1 - relative_path_length + path_pre = 0 if path_pre < 0 + path_current = path_pre == 0 ? "" : path.split("/")[0..path_pre].join("/") + path_last = r_content.split("../").last + elsif r_content.start_with?("/") # 根路径处理 + path_last = r_content[1..r_content.size] + else + path_current = path + end + # if r_content.include?("?") + # new_r_content = r_content + "&raw=true" + # else + # new_r_content = r_content + "?raw=true" + # end + new_r_content = r_content - 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 + 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 + end + content = content.gsub(/src=\"#{r_content}\"/, "src=\"#{new_r_content}\"").gsub(/src='#{r_content}'/, "src=\"#{new_r_content}\"") + rescue + next end - content = content.gsub(/src=\"#{r_content}\"/, "src=\"#{new_r_content}\"").gsub(/src='#{r_content}'/, "src=\"#{new_r_content}\"") end end From 747646cd9d4bdd214dc8312e02b72d925468fffc Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 30 Mar 2022 16:19:32 +0800 Subject: [PATCH 25/65] add: trace client and api completed --- app/libs/trace.rb | 21 +++ app/services/trace/add_user_service.rb | 37 ++++++ app/services/trace/check_result_service.rb | 33 +++++ app/services/trace/check_service.rb | 36 ++++++ app/services/trace/client_service.rb | 143 +++++++++++++++++++++ app/services/trace/login_service.rb | 29 +++++ app/services/trace/pdf_report_service.rb | 26 ++++ app/services/trace/reload_check_service.rb | 25 ++++ config/configuration.yml.example | 4 + 9 files changed, 354 insertions(+) create mode 100644 app/libs/trace.rb create mode 100644 app/services/trace/add_user_service.rb create mode 100644 app/services/trace/check_result_service.rb create mode 100644 app/services/trace/check_service.rb create mode 100644 app/services/trace/client_service.rb create mode 100644 app/services/trace/login_service.rb create mode 100644 app/services/trace/pdf_report_service.rb create mode 100644 app/services/trace/reload_check_service.rb diff --git a/app/libs/trace.rb b/app/libs/trace.rb new file mode 100644 index 00000000..b1c3c476 --- /dev/null +++ b/app/libs/trace.rb @@ -0,0 +1,21 @@ +module Trace + class << self + def trace_config + trace_config = {} + + begin + config = Rails.application.config_for(:configuration).symbolize_keys! + trace_config = config[:trace].symbolize_keys! + raise 'trace config missing' if trace_config.blank? + rescue => exception + raise ex if Rails.env.production? + + puts %Q{\033[33m [warning] gitea config or configuration.yml missing, + please add it or execute 'cp config/configuration.yml.example config/configuration.yml' \033[0m} + trace_config = {} + end + + trace_config + end + end +end \ No newline at end of file diff --git a/app/services/trace/add_user_service.rb b/app/services/trace/add_user_service.rb new file mode 100644 index 00000000..9c7b12b4 --- /dev/null +++ b/app/services/trace/add_user_service.rb @@ -0,0 +1,37 @@ +# 代码溯源 添加用户 +class Trace::AddUserService < Trace::ClientService + + # 用户名 密码 单位 手机号 邮箱 昵称 + attr_accessor :username, :password, :unit, :telnumber, :email, :name + + def initialize(username, password, unit, telnumber, email, name) + @username = username + @password = password + @unit = unit + @telnumber = telnumber + @email = email + @name = name + end + + def call + result = post(url, request_params) + response = render_response(result) + end + + private + + def request_params + { + username: username, + password: password, + unit: unit, + telnumber: telnumber, + email: email, + name: name + } + end + + def url + "/user/addccfuser".freeze + end +end \ No newline at end of file diff --git a/app/services/trace/check_result_service.rb b/app/services/trace/check_result_service.rb new file mode 100644 index 00000000..f1dd61ab --- /dev/null +++ b/app/services/trace/check_result_service.rb @@ -0,0 +1,33 @@ +# 代码溯源 查询检测结果 +class Trace::CheckResultService < Trace::ClientService + + attr_accessor :token, :project_name, :file_name, :page_num, :page_size + + def initialize(token, project_name=nil, file_name=nil, page_num=1, page_size=15) + @token = token + @project_name = project_name + @file_name = file_name + @page_num = page_num + @page_size = page_size + end + + def call + result = authed_get(token, url, request_params) + reponse = render_response(result) + end + + private + def request_params + { + product_name: project_name, + file_name: file_name, + pageNum: page_num, + pageSize: page_size, + } + end + + def url + "/user/checkresult".freeze + end +end + diff --git a/app/services/trace/check_service.rb b/app/services/trace/check_service.rb new file mode 100644 index 00000000..841627b5 --- /dev/null +++ b/app/services/trace/check_service.rb @@ -0,0 +1,36 @@ +# 代码溯源 开始检测 +class Trace::CheckService < Trace::ClientService + + attr_accessor :token, :project, :if_branch, :branch_tag + + def initialize(token, project, if_branch, branch_tag) + @token = token + @project = project + @if_branch = if_branch + @branch_tag = branch_tag + end + + def call + result = authed_post(token, url, request_params) + reponse = render_response(result) + end + + private + def request_params + repo = Gitea::Repository::GetService.call(project&.owner&.login, project&.identifier) + { + product_name: project&.name, + product_type: project&.category&.name, + code_type: project&.language&.name, + product_desc: project&.description, + git_url: repo['clone_url'], + if_branch: if_branch, + branch_tag: branch_tag + } + end + + def url + "/user/check".freeze + end +end + diff --git a/app/services/trace/client_service.rb b/app/services/trace/client_service.rb new file mode 100644 index 00000000..ff6b7281 --- /dev/null +++ b/app/services/trace/client_service.rb @@ -0,0 +1,143 @@ +class Trace::ClientService < ApplicationService + + def post(url, params={}) + puts "[trace][POST] request params: #{params}" + conn.post do |req| + req.url = full_url(url) + req.body = params[:data].to_json + end + end + + def authed_post(token, url, params={}) + puts "[trace][POST] request params: #{params}" + puts "[trace][POST] request token: #{token}" + conn.post do |req| + req.url = full_url(url) + req.body = params[:data].to_json + req.headers['Authorization'] = token + end + end + + def get(url, params={}) + puts "[trace][GET] request params: #{params}" + conn.get do |req| + req.url full_url(url, 'get') + params.each_pair do |key, value| + req.params["#{key}"] = value + end + end + end + + def authed_get(token, url, params={}) + puts "[trace][GET] request params: #{params}" + puts "[trace][GET] request token: #{token}" + conn.get do |req| + req.url full_url(url, 'get') + params.each_pair do |key, value| + req.params["#{key}"] = value + end + req.headers['Authorization'] = token + end + end + + def delete(url, params={}) + puts "[trace][DELETE] request params: #{params}" + conn.delete do |req| + req.url full_url(url) + req.body = params[:data].to_json + end + end + + def authed_delete(token, url, params={}) + puts "[trace][DELETE] request params: #{params}" + puts "[trace][DELETE] request token: #{token}" + conn.delete do |req| + req.url full_url(url) + req.body = params[:data].to_json + req.headers['Authorization'] = token + end + end + + def patch(url, params={}) + puts "[trace][PATCH] request params: #{params}" + conn.patch do |req| + req.url full_url(url) + req.body = params[:data].to_json + end + end + + def authed_patch(token, url, params={}) + puts "[trace][PATCH] request params: #{params}" + puts "[trace][PATCH] request token: #{token}" + conn.patch do |req| + req.url full_url(url) + req.body = params[:data].to_json + req.headers['Authorization'] = token + end + end + + def put(url, params={}) + puts "[trace][PUT] request params: #{params}" + conn.put do |req| + req.url full_url(url) + req.body = params[:data].to_json + end + end + + def authed_put(token, url, params={}) + puts "[trace][PUT] request params: #{params}" + puts "[trace][PUT] request token: #{token}" + conn.put do |req| + req.url full_url(url) + req.body = params[:data].to_json + req.headers['Authorization'] = token + end + end + + private + def conn + @client ||= begin + Faraday.new(url: domain) do |req| + req.request :url_encoded + req.headers['Content-Type'] = 'application/json' + req.adapter Faraday.default_adapter + end + end + + @client + end + + def base_url + Trace.trace_config[:base_url] + end + + def domain + Trace.trace_config[:domain] + end + + def api_url + [domain, base_url].join('') + end + + def full_url(api_rest, action='post') + url = [api_url, api_rest].join('').freeze + url = action === 'get' ? url : URI.escape(url) + url = URI.escape(url) unless url.ascii_only? + puts "[trace] request url: #{url}" + return url + end + + def log_error(status, body) + puts "[trace] status: #{status}" + puts "[trace] body: #{body}" + end + + def render_response(response) + status = response.status + body = JSON.parse(response&.body) + + log_error(status, body) + + return [body["code"], body["Data"], body["Error"]] + end +end \ No newline at end of file diff --git a/app/services/trace/login_service.rb b/app/services/trace/login_service.rb new file mode 100644 index 00000000..b245ea73 --- /dev/null +++ b/app/services/trace/login_service.rb @@ -0,0 +1,29 @@ +# 代码溯源 用户登录 +class Trace::LoginService < Trace::ClientService + + # 用户名 密码 + attr_accessor :username, :password + + def initialize(username, password) + @username = username + @password = password + end + + def call + result = post(url, request_params) + response = render_response(result) + end + + private + + def request_params + { + username: username, + password: password, + } + end + + def url + "/user/login".freeze + end +end \ No newline at end of file diff --git a/app/services/trace/pdf_report_service.rb b/app/services/trace/pdf_report_service.rb new file mode 100644 index 00000000..e91a78b3 --- /dev/null +++ b/app/services/trace/pdf_report_service.rb @@ -0,0 +1,26 @@ +# 代码溯源 导出pdf +class Trace::PdfReportService < Trace::ClientService + + attr_accessor :token, :task_id + + def initialize(token, task_id) + @token = token + @task_id = task_id + end + + def call + result = authed_get(token, url, request_params) + response = render_response(result) + end + + private + def request_params + { + task_id: task_id + } + end + + def url + "/user/pdfreport".freeze + end +end \ No newline at end of file diff --git a/app/services/trace/reload_check_service.rb b/app/services/trace/reload_check_service.rb new file mode 100644 index 00000000..b2c4a0ff --- /dev/null +++ b/app/services/trace/reload_check_service.rb @@ -0,0 +1,25 @@ +# 代码溯源 重新检测 +class Trace::ReloadCheckService < Trace::ClientService + + attr_accessor :token, :fake_project_id + def initialize(token, fake_project_id) + @token = token + @fake_project_id = fake_project_id + end + + def call + result = authed_post(token, url, request_params) + response = render_response(result) + end + + private + def request_params + { + project_id: fake_project_id + } + end + + def url + '/user/reloadcheck'.freeze + end +end \ No newline at end of file diff --git a/config/configuration.yml.example b/config/configuration.yml.example index b5653012..61e66635 100644 --- a/config/configuration.yml.example +++ b/config/configuration.yml.example @@ -62,6 +62,10 @@ default: &default write_domain: '' read_domain: '' base_url: '' + + trace: + domain: '' + base_url: '' production: <<: *default From 4bbb843edfb6143eaad79e320446ec4e24f2e788 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 31 Mar 2022 12:54:39 +0800 Subject: [PATCH 26/65] add: trace users and get trace token --- app/models/trace_user.rb | 58 +++++++++++++++++++ app/models/user.rb | 17 ++++++ .../20220331031530_create_trace_users.rb | 17 ++++++ spec/models/trace_user_spec.rb | 5 ++ 4 files changed, 97 insertions(+) create mode 100644 app/models/trace_user.rb create mode 100644 db/migrate/20220331031530_create_trace_users.rb create mode 100644 spec/models/trace_user_spec.rb diff --git a/app/models/trace_user.rb b/app/models/trace_user.rb new file mode 100644 index 00000000..e8964156 --- /dev/null +++ b/app/models/trace_user.rb @@ -0,0 +1,58 @@ +# == Schema Information +# +# Table name: trace_users +# +# id :integer not null, primary key +# user_id :integer +# username :string(255) +# password :string(255) +# unit :string(255) +# telnumber :string(255) +# email :string(255) +# name :string(255) +# token :text(65535) +# expired_at :datetime +# created_at :datetime not null +# updated_at :datetime not null +# +# Indexes +# +# index_trace_users_on_user_id (user_id) +# + +# 代码溯源 用户 +class TraceUser < ApplicationRecord + + belongs_to :user + + + def build_self_data + return if user.nil? + + self.username = user.login + self.password = SecureRandom.hex + self.unit = user.custom_department.blank? ? 'GitLink' : user.custom_department + self.telnumber = user.phone.blank? ? '13800000000' : user.phone + self.email = user.mail + self.name = user.nickname.blank? ? user.login : user.nickname + + self + end + + + def build_token + return if username.blank? || password.blank? || unit.blank? || telnumber.blank? || email.blank? || name.blank? + + response = Trace::AddUserService.call(username, password, unit, telnumber, email, name) + self.token = response[1]['token'] + self.expired_at = Time.now + 1.hours + end + + def refresh_token + return if username.blank? || password.blank? || unit.blank? || telnumber.blank? || email.blank? || name.blank? + + response = Trace::LoginService.call(username, password) + self.token = response[1]['token'] + self.expired_at = Time.now + 1.hours + end +end diff --git a/app/models/user.rb b/app/models/user.rb index 5ca3356b..903b60c3 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -173,6 +173,7 @@ class User < Owner has_many :system_notification_histories has_many :system_notifications, through: :system_notification_histories + has_one :trace_user, dependent: :destroy # Groups and active users scope :active, lambda { where(status: STATUS_ACTIVE) } @@ -776,6 +777,22 @@ class User < Owner self.nickname.present? && self.mail.present? end + def trace_token + if trace_user.present? + if trace_user.expired_at < Time.now + trace_user.refresh_token + trace_user.save + end + else + trace_user = TraceUser.new + trace_user.build_self_data + trace_user.build_token + trace_user.save + end + + trace_user.token + end + protected def validate_password_length # 管理员的初始密码是5位 diff --git a/db/migrate/20220331031530_create_trace_users.rb b/db/migrate/20220331031530_create_trace_users.rb new file mode 100644 index 00000000..5c8b532c --- /dev/null +++ b/db/migrate/20220331031530_create_trace_users.rb @@ -0,0 +1,17 @@ +class CreateTraceUsers < ActiveRecord::Migration[5.2] + def change + create_table :trace_users do |t| + t.references :user + t.string :username + t.string :password + t.string :unit + t.string :telnumber + t.string :email + t.string :name + t.text :token + t.datetime :expired_at + + t.timestamps + end + end +end diff --git a/spec/models/trace_user_spec.rb b/spec/models/trace_user_spec.rb new file mode 100644 index 00000000..ddcc25e4 --- /dev/null +++ b/spec/models/trace_user_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe TraceUser, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end From 9ced678f910f2b56d79ae2f1ecc7e638a2083831 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 31 Mar 2022 13:03:54 +0800 Subject: [PATCH 27/65] fix: user trace token --- app/models/user.rb | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index 903b60c3..d661ab59 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -783,14 +783,16 @@ class User < Owner trace_user.refresh_token trace_user.save end + return trace_user.token else - trace_user = TraceUser.new - trace_user.build_self_data - trace_user.build_token - trace_user.save - end + tu = TraceUser.new + tu.user = self + tu.build_self_data + tu.build_token + tu.save - trace_user.token + return tu.token + end end protected From ecfc39565ca4da5c9e9b22958cc962421f4e5826 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 31 Mar 2022 13:18:38 +0800 Subject: [PATCH 28/65] fix --- app/services/trace/client_service.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/services/trace/client_service.rb b/app/services/trace/client_service.rb index ff6b7281..df9a4321 100644 --- a/app/services/trace/client_service.rb +++ b/app/services/trace/client_service.rb @@ -3,7 +3,7 @@ class Trace::ClientService < ApplicationService def post(url, params={}) puts "[trace][POST] request params: #{params}" conn.post do |req| - req.url = full_url(url) + req.url full_url(url) req.body = params[:data].to_json end end @@ -12,7 +12,7 @@ class Trace::ClientService < ApplicationService puts "[trace][POST] request params: #{params}" puts "[trace][POST] request token: #{token}" conn.post do |req| - req.url = full_url(url) + req.url full_url(url) req.body = params[:data].to_json req.headers['Authorization'] = token end From db4031b8bfcd1cfc6664b7eae35c7151e6639665 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 31 Mar 2022 14:24:47 +0800 Subject: [PATCH 29/65] fix --- app/services/trace/add_user_service.rb | 2 +- app/services/trace/check_service.rb | 2 +- app/services/trace/login_service.rb | 2 +- app/services/trace/reload_check_service.rb | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/services/trace/add_user_service.rb b/app/services/trace/add_user_service.rb index 9c7b12b4..0099f6e9 100644 --- a/app/services/trace/add_user_service.rb +++ b/app/services/trace/add_user_service.rb @@ -14,7 +14,7 @@ class Trace::AddUserService < Trace::ClientService end def call - result = post(url, request_params) + result = post(url, {data: request_params}) response = render_response(result) end diff --git a/app/services/trace/check_service.rb b/app/services/trace/check_service.rb index 841627b5..d31bbcf0 100644 --- a/app/services/trace/check_service.rb +++ b/app/services/trace/check_service.rb @@ -11,7 +11,7 @@ class Trace::CheckService < Trace::ClientService end def call - result = authed_post(token, url, request_params) + result = authed_post(token, url, {data: request_params}) reponse = render_response(result) end diff --git a/app/services/trace/login_service.rb b/app/services/trace/login_service.rb index b245ea73..9f59d8e1 100644 --- a/app/services/trace/login_service.rb +++ b/app/services/trace/login_service.rb @@ -10,7 +10,7 @@ class Trace::LoginService < Trace::ClientService end def call - result = post(url, request_params) + result = post(url, {data: request_params}) response = render_response(result) end diff --git a/app/services/trace/reload_check_service.rb b/app/services/trace/reload_check_service.rb index b2c4a0ff..62530af1 100644 --- a/app/services/trace/reload_check_service.rb +++ b/app/services/trace/reload_check_service.rb @@ -8,7 +8,7 @@ class Trace::ReloadCheckService < Trace::ClientService end def call - result = authed_post(token, url, request_params) + result = authed_post(token, url, {data: request_params}) response = render_response(result) end From 882a50cf56bd54720283bfbdbbd65b9303dc7eb2 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 31 Mar 2022 16:04:48 +0800 Subject: [PATCH 30/65] add: setting navbar varible --- app/controllers/settings_controller.rb | 12 ++++++++++++ app/views/settings/show.json.jbuilder | 4 ++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index b2dc2e90..15da47a3 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -1,6 +1,7 @@ class SettingsController < ApplicationController def show @old_projects_url = nil + get_navbar get_add_menu get_common_menu get_personal_menu @@ -8,6 +9,17 @@ class SettingsController < ApplicationController end private + def get_navbar + @navbar = [] + default_laboratory.navbar.each do |site| + hash = {} + site.each {|k, v| + hash.merge!("#{k}": get_site_url(k, v)) + } + @navbar << hash + end + end + def get_add_menu @add = [] Site.add.select(:id, :name, :url, :key).to_a.map(&:serializable_hash).each do |site| diff --git a/app/views/settings/show.json.jbuilder b/app/views/settings/show.json.jbuilder index 0e6e1606..b9319e4e 100644 --- a/app/views/settings/show.json.jbuilder +++ b/app/views/settings/show.json.jbuilder @@ -18,7 +18,7 @@ json.setting do # # end - nav_bar = default_setting.navbar + # nav_bar = default_setting.navbar # if User.current.logged? # nav_bar[2]["link"] = "https://forgeplus.trustie.net/users/#{current_user.login}/projects" @@ -39,7 +39,7 @@ json.setting do json.moop_cases_banner_url default_setting.moop_cases_banner_url&.[](1..-1) json.oj_banner_url default_setting.oj_banner_url&.[](1..-1) - json.navbar nav_bar + json.navbar @navbar json.footer default_setting.footer From 35369189382027f6960f81477f9fc39b5459219c Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 31 Mar 2022 16:18:16 +0800 Subject: [PATCH 31/65] fix --- app/controllers/settings_controller.rb | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index 15da47a3..e1a5be1d 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -10,13 +10,10 @@ class SettingsController < ApplicationController private def get_navbar - @navbar = [] - default_laboratory.navbar.each do |site| - hash = {} - site.each {|k, v| - hash.merge!("#{k}": get_site_url(k, v)) - } - @navbar << hash + @navbar = default_laboratory.navbar + if User.current.logged? + pernal_index = {"name"=>"个人主页", "link"=>get_site_url("link", "/current_user"), "hidden"=>false} + @navbar << pernal_index end end From 1f6ac05bada38e3503ad3361768bb5eabd2f568a Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Wed, 6 Apr 2022 14:33:47 +0800 Subject: [PATCH 32/65] =?UTF-8?q?=E5=85=81=E8=AE=B8=E9=9D=9E=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E6=90=9C=E7=B4=A2=E7=94=A8=E6=88=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/users_controller.rb | 648 ++++++++++++++-------------- 1 file changed, 324 insertions(+), 324 deletions(-) diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 5af634f1..9a3fab62 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -1,324 +1,324 @@ -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 :require_login, only: %i[me list sync_user_info] - before_action :connect_to_ci_db, only: [:get_user_info] - before_action :convert_image!, only: [:update, :update_image] - skip_before_action :check_sign, only: [:attachment_show] - - def connect_to_ci_db(options={}) - if !(current_user && !current_user.is_a?(AnonymousUser) && current_user.devops_certification?) - return - end - if current_user.ci_cloud_account.server_type == Ci::CloudAccount::SERVER_TYPE_TRUSTIE - connect_to_trustie_ci_database(options) - else - connect_to_ci_database(options) - end - end - - def list - scope = User.active.recent.like(params[:search]).includes(:user_extension) - @total_count = scope.size - @users = paginate(scope) - end - - def show - #待办事项,现在未做 - if User.current.admin? || User.current.login == @user.login - @waiting_applied_messages = @user.applied_messages.waiting - @common_applied_transfer_projects = AppliedTransferProject.where(owner_id: @user.id).common + AppliedTransferProject.where(owner_id: Organization.joins(team_users: :team).where(team_users: {user_id: @user.id}, teams: {authorize: %w(admin owner)} )).common - @common_applied_projects = AppliedProject.where(project_id: @user.full_admin_projects).common - #@undo_events = @waiting_applied_messages.size + @common_applied_transfer_projects.size + @common_applied_projects.size - @undo_events = @common_applied_transfer_projects.size + @common_applied_projects.size - else - @waiting_applied_messages = AppliedMessage.none - @common_applied_transfer_projects = AppliedTransferProject.none - @common_applied_projects = AppliedProject.none - @undo_events = 0 - end - #用户的组织数量 - # @user_composes_count = @user.composes.size - @user_composes_count = 0 - user_organizations = User.current.logged? ? @user.organizations.with_visibility(%w(common limited)) + @user.organizations.with_visibility("privacy").joins(:team_users).where(team_users: {user_id: current_user.id}) : @user.organizations.with_visibility("common") - @user_org_count = user_organizations.size - normal_projects = Project.members_projects(@user.id).to_sql - org_projects = Project.joins(team_projects: [team: :team_users]).where(team_users: {user_id: @user.id}).to_sql - projects = Project.from("( #{ normal_projects} UNION #{ org_projects } ) AS projects").distinct - user_projects = User.current.logged? && (User.current.admin? || User.current.login == @user.login) ? projects : projects.visible - @projects_common_count = user_projects.common.size - @projects_mirrior_count = user_projects.mirror.size - @projects_sync_mirrior_count = user_projects.sync_mirror.size - # 为了缓存活跃用户的基本信息,后续删除 - Cache::V2::OwnerCommonService.new(@user.id).read - end - - def watch_users - watchers = Watcher.watching_users(@user.id).includes(:user).order("watchers.created_at desc") - if params[:search].present? - search_user_ids = User.where(id: watchers.pluck(:watchable_id)).like(params[:search]).pluck(:id) - watchers = watchers.where(watchable_id: search_user_ids) - end - @watchers_count = watchers.size - @watchers = paginate(watchers) - end - - def fan_users - watchers = @user.watchers.includes(:user).order("watchers.created_at desc") - watchers = watchers.joins(:user).merge(User.like(params[:search])) - @watchers_count = watchers.size - @watchers = paginate(watchers) - end - - def hovercard - 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) - Util.write_file(@image, avatar_path(@user)) if user_params[:image].present? - @user.attributes = user_params.except(:image) - unless @user.save - render_error(-1, @user.errors.full_messages.join(", ")) - end - end - - 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)) - return render_ok({message: '头像修改成功'}) - rescue Exception => e - uid_logger_error(e.message) - render_error(-1, '头像修改失败!') - end - - def me - @user = current_user - end - - # 贴吧获取用户信接口 - def get_user_info - begin - @user = current_user - begin - result = Notice::Read::CountService.call(current_user.id) - @message_unread_total = result.nil? ? 0 : result[2]["unread_notification"] - rescue - @message_unread_total = 0 - end - # TODO 等消息上线再打开注释 - #@tidding_count = unviewed_tiddings(current_user) if current_user.present? - rescue Exception => e - uid_logger_error(e.message) - missing_template - end - - end - - def attachment_show - file_name = params[:file_name] - path = params[:path] || file_storage_directory - send_file "#{path}/#{file_name}", :filename => "#{file_name}", - :type => 'game', - :disposition => 'attachment' #inline can open in browser - end - - def html_show - @contents = File.read("#{params[:path]}") - respond_to do |format| - format.html {render :layout => false} - end - end - - # Redo: 消息总数缓存 - def get_navigation_info - # @old_domain = edu_setting('old_edu_host') - # @user = current_user - # # 新消息数 - # @new_message = @user.tidings.where("created_at > '#{@user.click_time}'").count > 0 || @user.private_messages.where("created_at > '#{@user.click_time}'").count > 0 - # - # @user_url = "/users/#{@user.login}" - # @career = Career.where(status: true).order("created_at asc").pluck(:id, :name) - # @auth = User.current.ec_school.present? ? "#{@old_domain}/ecs/department?school_id=#{User.current.ec_school}" : nil - end - - # 用户回复功能 - def reply_message - message = JournalsForMessage.new(reply_message_params) - message.user_id = current_user.id - message.save! - - render_ok(id: message.id) - end - - # 搜索用户具有管理员角色的项目 - def search_user_projects - projects = Project.where.not(status: 9) - - projects = projects.joins(members: :member_roles).where(member_roles: { role_id: 3 }) - projects = projects.where(members: { user_id: current_user.id }) - - search = params[:search].to_s.strip - projects = projects.where('projects.name LIKE ?', "%#{search}%") if search.present? - - @projects = projects.select(:id, :name) - end - - #TODO 个人主页信息,forge上弃用-hs, 0602 - def homepage_info - #待办事项,现在未做 - @undo_events = 10 - #用户的组织数量 - # @user_composes_count = @user.composes.size - @user_composes_count = 10 - end - - def brief_introduction - content = params[:content].to_s.strip - - current_user.user_extension.update!(brief_introduction: content) - - render_ok - end - - def attendance - attendance = Users::AttendanceService.call(current_user) - render_ok(grade: current_user.grade, next_gold: attendance.next_gold) - rescue Users::AttendanceService::Error => ex - render_error(ex.message) - end - - # 其他平台登录后,必须将token同步到forge平台,实现sso登录功能 - def sync_token - return render_error('未找相关用户!') unless @user - - token = Token.get_or_create_permanent_login_token(@user, 'autologin') - token.update_column(:value, params[:token]) - render_ok - end - - def trustie_related_projects - projects = Project.includes(:owner, :members, :project_score).where(id: params[:ids]).order("updated_on desc") - projects_json = [] - domain_url = EduSetting.get('host_name') - if projects.present? - projects.each do |p| - project_url = "/#{p.owner.login}/#{p.identifier}" - pj = { - id: p.id, - name: p.name, - is_public: p.is_public, - updated_on: p.updated_on.strftime("%Y-%m-%d"), - status: p.status, - is_member: p.member?(current_user.try(:id)), - owner: { - name: p.owner.try(:show_real_name), - login: p.owner.login - }, - members_count: p&.members.size, - issues_count: p.issues_count - p.pull_requests_count, - commits_count: p&.project_score&.changeset_num.to_i, - http_url: domain_url + project_url, - http_collaborator_url: domain_url + project_url + "/setting/collaborator", - http_issues_url: domain_url + project_url + "/issues", - http_commits_url: domain_url + project_url + "/commits", - project_score: p&.project_score.present? ? p&.project_score&.as_json(:except=>[:created_at, :updated_at]).merge!(commit_time: format_time(p&.project_score&.commit_time)) : {} - } - projects_json.push(pj) - end - end - Rails.logger.info("==========projects_json========+########{projects_json}") - render json: { projects: projects_json.present? ? projects_json : {} } - end - - def trustie_projects - user_id = User.select(:id, :login).where(login: params[:login])&.first&.id - projects = Project.visible - - projects = projects.joins(:members).where(members: { user_id: user_id }) - - search = params[:search].to_s.strip - projects = projects.where('projects.name LIKE ?', "%#{search}%") if search.present? - - projects = projects.select(:id, :name).limit(10).as_json - render json: { projects: projects } - end - - def projects - 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) - end - - # TODO 其他平台登录时同步修改gitea平台对应用户的密码 - # 该方法主要用于:别的平台初次部署对接forge平台,同步用户后,gitea平台对应的用户密码与forge平台用户密码不一致是问题 - def sync_gitea_pwd - return render_error("未找到相关的用户") if @user.blank? - - flag = sync_pwd_to_gitea!(@user, {password: params[:password].to_s}) - flag ? render_ok : render_error('同步失败!') - end - - # TODO - # 同步trusite平台用户的salt信息,只需同步一次,同步完成后,该方法可以删除 - def sync_salt - user = User.find_by_login params[:login] - return if user.blank? - user.update_column(:salt, params[:salt]) - render_ok - end - - def sync_user_info - user = User.find_by_login params[:login] - return render_forbidden unless user === current_user - - sync_params = { - email: params[:email], - password: params[:password] - } - - Users::UpdateInfoForm.new(sync_params.merge(login: params[:login])).validate! - - interactor = Gitea::User::UpdateInteractor.call(user.login, sync_params) - if interactor.success? - user.update!(password: params[:password], mail: params[:email], status: User::STATUS_ACTIVE) - render_ok - else - render_error(interactor.error) - end - end - - private - def load_user - @user = User.find_by_login(params[:id]) || User.find_by(id: params[:id]) - end - - def user_params - params.require(:user).permit(:nickname, :image, - user_extension_attributes: [ - :gender, :location, :location_city, - :occupation, :technical_title, - :school_id, :department_id, :province, :city, - :custom_department, :identity, :student_id, :description, - :show_email, :show_location, :show_department] - ) - end - - def reply_message_params - normal_status(-1, "参数不对") if params[:journals_for_message][:jour_type].nil? || params[:journals_for_message][:jour_id].nil? || - params[:journals_for_message][:notes].nil? || params[:journals_for_message][:reply_id].nil? - params.require(:journals_for_message).permit(:jour_type, :jour_id, :notes, :m_parent_id, :reply_id) - end - - def check_user_exist - return if @user.present? - render_not_found - end - -end +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 :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] + skip_before_action :check_sign, only: [:attachment_show] + + def connect_to_ci_db(options={}) + if !(current_user && !current_user.is_a?(AnonymousUser) && current_user.devops_certification?) + return + end + if current_user.ci_cloud_account.server_type == Ci::CloudAccount::SERVER_TYPE_TRUSTIE + connect_to_trustie_ci_database(options) + else + connect_to_ci_database(options) + end + end + + def list + scope = User.active.recent.like(params[:search]).includes(:user_extension) + @total_count = scope.size + @users = paginate(scope) + end + + def show + #待办事项,现在未做 + if User.current.admin? || User.current.login == @user.login + @waiting_applied_messages = @user.applied_messages.waiting + @common_applied_transfer_projects = AppliedTransferProject.where(owner_id: @user.id).common + AppliedTransferProject.where(owner_id: Organization.joins(team_users: :team).where(team_users: {user_id: @user.id}, teams: {authorize: %w(admin owner)} )).common + @common_applied_projects = AppliedProject.where(project_id: @user.full_admin_projects).common + #@undo_events = @waiting_applied_messages.size + @common_applied_transfer_projects.size + @common_applied_projects.size + @undo_events = @common_applied_transfer_projects.size + @common_applied_projects.size + else + @waiting_applied_messages = AppliedMessage.none + @common_applied_transfer_projects = AppliedTransferProject.none + @common_applied_projects = AppliedProject.none + @undo_events = 0 + end + #用户的组织数量 + # @user_composes_count = @user.composes.size + @user_composes_count = 0 + user_organizations = User.current.logged? ? @user.organizations.with_visibility(%w(common limited)) + @user.organizations.with_visibility("privacy").joins(:team_users).where(team_users: {user_id: current_user.id}) : @user.organizations.with_visibility("common") + @user_org_count = user_organizations.size + normal_projects = Project.members_projects(@user.id).to_sql + org_projects = Project.joins(team_projects: [team: :team_users]).where(team_users: {user_id: @user.id}).to_sql + projects = Project.from("( #{ normal_projects} UNION #{ org_projects } ) AS projects").distinct + user_projects = User.current.logged? && (User.current.admin? || User.current.login == @user.login) ? projects : projects.visible + @projects_common_count = user_projects.common.size + @projects_mirrior_count = user_projects.mirror.size + @projects_sync_mirrior_count = user_projects.sync_mirror.size + # 为了缓存活跃用户的基本信息,后续删除 + Cache::V2::OwnerCommonService.new(@user.id).read + end + + def watch_users + watchers = Watcher.watching_users(@user.id).includes(:user).order("watchers.created_at desc") + if params[:search].present? + search_user_ids = User.where(id: watchers.pluck(:watchable_id)).like(params[:search]).pluck(:id) + watchers = watchers.where(watchable_id: search_user_ids) + end + @watchers_count = watchers.size + @watchers = paginate(watchers) + end + + def fan_users + watchers = @user.watchers.includes(:user).order("watchers.created_at desc") + watchers = watchers.joins(:user).merge(User.like(params[:search])) + @watchers_count = watchers.size + @watchers = paginate(watchers) + end + + def hovercard + 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) + Util.write_file(@image, avatar_path(@user)) if user_params[:image].present? + @user.attributes = user_params.except(:image) + unless @user.save + render_error(-1, @user.errors.full_messages.join(", ")) + end + end + + 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)) + return render_ok({message: '头像修改成功'}) + rescue Exception => e + uid_logger_error(e.message) + render_error(-1, '头像修改失败!') + end + + def me + @user = current_user + end + + # 贴吧获取用户信接口 + def get_user_info + begin + @user = current_user + begin + result = Notice::Read::CountService.call(current_user.id) + @message_unread_total = result.nil? ? 0 : result[2]["unread_notification"] + rescue + @message_unread_total = 0 + end + # TODO 等消息上线再打开注释 + #@tidding_count = unviewed_tiddings(current_user) if current_user.present? + rescue Exception => e + uid_logger_error(e.message) + missing_template + end + + end + + def attachment_show + file_name = params[:file_name] + path = params[:path] || file_storage_directory + send_file "#{path}/#{file_name}", :filename => "#{file_name}", + :type => 'game', + :disposition => 'attachment' #inline can open in browser + end + + def html_show + @contents = File.read("#{params[:path]}") + respond_to do |format| + format.html {render :layout => false} + end + end + + # Redo: 消息总数缓存 + def get_navigation_info + # @old_domain = edu_setting('old_edu_host') + # @user = current_user + # # 新消息数 + # @new_message = @user.tidings.where("created_at > '#{@user.click_time}'").count > 0 || @user.private_messages.where("created_at > '#{@user.click_time}'").count > 0 + # + # @user_url = "/users/#{@user.login}" + # @career = Career.where(status: true).order("created_at asc").pluck(:id, :name) + # @auth = User.current.ec_school.present? ? "#{@old_domain}/ecs/department?school_id=#{User.current.ec_school}" : nil + end + + # 用户回复功能 + def reply_message + message = JournalsForMessage.new(reply_message_params) + message.user_id = current_user.id + message.save! + + render_ok(id: message.id) + end + + # 搜索用户具有管理员角色的项目 + def search_user_projects + projects = Project.where.not(status: 9) + + projects = projects.joins(members: :member_roles).where(member_roles: { role_id: 3 }) + projects = projects.where(members: { user_id: current_user.id }) + + search = params[:search].to_s.strip + projects = projects.where('projects.name LIKE ?', "%#{search}%") if search.present? + + @projects = projects.select(:id, :name) + end + + #TODO 个人主页信息,forge上弃用-hs, 0602 + def homepage_info + #待办事项,现在未做 + @undo_events = 10 + #用户的组织数量 + # @user_composes_count = @user.composes.size + @user_composes_count = 10 + end + + def brief_introduction + content = params[:content].to_s.strip + + current_user.user_extension.update!(brief_introduction: content) + + render_ok + end + + def attendance + attendance = Users::AttendanceService.call(current_user) + render_ok(grade: current_user.grade, next_gold: attendance.next_gold) + rescue Users::AttendanceService::Error => ex + render_error(ex.message) + end + + # 其他平台登录后,必须将token同步到forge平台,实现sso登录功能 + def sync_token + return render_error('未找相关用户!') unless @user + + token = Token.get_or_create_permanent_login_token(@user, 'autologin') + token.update_column(:value, params[:token]) + render_ok + end + + def trustie_related_projects + projects = Project.includes(:owner, :members, :project_score).where(id: params[:ids]).order("updated_on desc") + projects_json = [] + domain_url = EduSetting.get('host_name') + if projects.present? + projects.each do |p| + project_url = "/#{p.owner.login}/#{p.identifier}" + pj = { + id: p.id, + name: p.name, + is_public: p.is_public, + updated_on: p.updated_on.strftime("%Y-%m-%d"), + status: p.status, + is_member: p.member?(current_user.try(:id)), + owner: { + name: p.owner.try(:show_real_name), + login: p.owner.login + }, + members_count: p&.members.size, + issues_count: p.issues_count - p.pull_requests_count, + commits_count: p&.project_score&.changeset_num.to_i, + http_url: domain_url + project_url, + http_collaborator_url: domain_url + project_url + "/setting/collaborator", + http_issues_url: domain_url + project_url + "/issues", + http_commits_url: domain_url + project_url + "/commits", + project_score: p&.project_score.present? ? p&.project_score&.as_json(:except=>[:created_at, :updated_at]).merge!(commit_time: format_time(p&.project_score&.commit_time)) : {} + } + projects_json.push(pj) + end + end + Rails.logger.info("==========projects_json========+########{projects_json}") + render json: { projects: projects_json.present? ? projects_json : {} } + end + + def trustie_projects + user_id = User.select(:id, :login).where(login: params[:login])&.first&.id + projects = Project.visible + + projects = projects.joins(:members).where(members: { user_id: user_id }) + + search = params[:search].to_s.strip + projects = projects.where('projects.name LIKE ?', "%#{search}%") if search.present? + + projects = projects.select(:id, :name).limit(10).as_json + render json: { projects: projects } + end + + def projects + 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) + end + + # TODO 其他平台登录时同步修改gitea平台对应用户的密码 + # 该方法主要用于:别的平台初次部署对接forge平台,同步用户后,gitea平台对应的用户密码与forge平台用户密码不一致是问题 + def sync_gitea_pwd + return render_error("未找到相关的用户") if @user.blank? + + flag = sync_pwd_to_gitea!(@user, {password: params[:password].to_s}) + flag ? render_ok : render_error('同步失败!') + end + + # TODO + # 同步trusite平台用户的salt信息,只需同步一次,同步完成后,该方法可以删除 + def sync_salt + user = User.find_by_login params[:login] + return if user.blank? + user.update_column(:salt, params[:salt]) + render_ok + end + + def sync_user_info + user = User.find_by_login params[:login] + return render_forbidden unless user === current_user + + sync_params = { + email: params[:email], + password: params[:password] + } + + Users::UpdateInfoForm.new(sync_params.merge(login: params[:login])).validate! + + interactor = Gitea::User::UpdateInteractor.call(user.login, sync_params) + if interactor.success? + user.update!(password: params[:password], mail: params[:email], status: User::STATUS_ACTIVE) + render_ok + else + render_error(interactor.error) + end + end + + private + def load_user + @user = User.find_by_login(params[:id]) || User.find_by(id: params[:id]) + end + + def user_params + params.require(:user).permit(:nickname, :image, + user_extension_attributes: [ + :gender, :location, :location_city, + :occupation, :technical_title, + :school_id, :department_id, :province, :city, + :custom_department, :identity, :student_id, :description, + :show_email, :show_location, :show_department] + ) + end + + def reply_message_params + normal_status(-1, "参数不对") if params[:journals_for_message][:jour_type].nil? || params[:journals_for_message][:jour_id].nil? || + params[:journals_for_message][:notes].nil? || params[:journals_for_message][:reply_id].nil? + params.require(:journals_for_message).permit(:jour_type, :jour_id, :notes, :m_parent_id, :reply_id) + end + + def check_user_exist + return if @user.present? + render_not_found + end + +end From 70559744432c9a2b109b42d93e00f7a432f1ca3b Mon Sep 17 00:00:00 2001 From: yystopf Date: Wed, 6 Apr 2022 17:04:31 +0800 Subject: [PATCH 33/65] fix --- app/services/issues/list_query_service.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/services/issues/list_query_service.rb b/app/services/issues/list_query_service.rb index def9644d..73f0b438 100644 --- a/app/services/issues/list_query_service.rb +++ b/app/services/issues/list_query_service.rb @@ -27,9 +27,9 @@ class Issues::ListQueryService < ApplicationService issues = issues.joins(:pull_request).where(pull_requests: {status: 1}) end - # if search_name.present? - # issues = issues.where("issues.subject LIKE ? OR issues.description LIKE ? ", "%#{search_name}%", "%#{search_name}%") - # end + if search_name.present? + issues = issues.where("issues.subject LIKE ? OR issues.description LIKE ? ", "%#{search_name}%", "%#{search_name}%") + end if start_time&.present? || end_time&.present? issues = issues.where("issues.start_date between ? and ?",start_time&.present? ? start_time.to_date : Time.now.to_date, end_time&.present? ? end_time.to_date : Time.now.to_date) From c4f91fb05469085c3f2bff310380e5cd22c379f0 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Wed, 6 Apr 2022 20:32:02 +0800 Subject: [PATCH 34/65] =?UTF-8?q?=E6=90=9C=E7=B4=A2=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0email=E5=92=8C=E5=8D=95=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/views/users/_user_small.json.jbuilder | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/app/views/users/_user_small.json.jbuilder b/app/views/users/_user_small.json.jbuilder index b8033ba7..f5929ef6 100644 --- a/app/views/users/_user_small.json.jbuilder +++ b/app/views/users/_user_small.json.jbuilder @@ -1,9 +1,11 @@ -# 单表存储的信息可以放里面 -json.array! users do |user| - json.username user.full_name - json.login user.login - json.user_id user.id - json.image_url url_to_avatar(user) - json.profile_completed user.profile_completed -end - +# 单表存储的信息可以放里面 +json.array! users do |user| + json.username user.full_name + json.login user.login + json.user_id user.id + json.mail user.mail + json.custom_department user.custom_department + json.image_url url_to_avatar(user) + json.profile_completed user.profile_completed +end + From 8aa935ad5cbceb7ae64848dece87dfaf7e58e5d9 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 7 Apr 2022 16:13:32 +0800 Subject: [PATCH 35/65] add: glcc news management and api data --- .../admins/topic/glcc_news_controller.rb | 57 +++++++++++++++++++ app/models/topic.rb | 2 + app/models/topic/glcc_news.rb | 17 ++++++ app/views/admins/shared/_sidebar.html.erb | 6 +- .../topic/glcc_news/_form_modal.html.erb | 44 ++++++++++++++ .../admins/topic/glcc_news/_list.html.erb | 33 +++++++++++ app/views/admins/topic/glcc_news/edit.js.erb | 2 + .../admins/topic/glcc_news/index.html.erb | 18 ++++++ app/views/admins/topic/glcc_news/index.js.erb | 1 + app/views/admins/topic/glcc_news/new.js.erb | 2 + app/views/topics/_glcc_news.json.jbuilder | 4 ++ app/views/topics/index.json.jbuilder | 4 ++ config/routes.rb | 1 + 13 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 app/controllers/admins/topic/glcc_news_controller.rb create mode 100644 app/models/topic/glcc_news.rb create mode 100644 app/views/admins/topic/glcc_news/_form_modal.html.erb create mode 100644 app/views/admins/topic/glcc_news/_list.html.erb create mode 100644 app/views/admins/topic/glcc_news/edit.js.erb create mode 100644 app/views/admins/topic/glcc_news/index.html.erb create mode 100644 app/views/admins/topic/glcc_news/index.js.erb create mode 100644 app/views/admins/topic/glcc_news/new.js.erb create mode 100644 app/views/topics/_glcc_news.json.jbuilder diff --git a/app/controllers/admins/topic/glcc_news_controller.rb b/app/controllers/admins/topic/glcc_news_controller.rb new file mode 100644 index 00000000..3c1769e5 --- /dev/null +++ b/app/controllers/admins/topic/glcc_news_controller.rb @@ -0,0 +1,57 @@ +class Admins::Topic::GlccNewsController < Admins::Topic::BaseController + before_action :find_glcc, only: [:edit, :update, :destroy] + + def index + q = ::Topic::GlccNews.ransack(title_cont: params[:search]) + glcc_news = q.result(distinct: true) + @glcc_news = paginate(glcc_news) + end + + def new + @glcc = ::Topic::GlccNews.new + end + + def create + @glcc = ::Topic::GlccNews.new(glcc_params) + if @glcc.save + redirect_to admins_topic_glcc_news_index_path + flash[:success] = "新增新闻稿成功" + else + redirect_to admins_topic_glcc_news_index_path + flash[:danger] = "新增新闻稿失败" + end + end + + def edit + end + + def update + @glcc.attributes = glcc_params + if @glcc.save + redirect_to admins_topic_glcc_news_index_path + flash[:success] = "更新新闻稿成功" + else + redirect_to admins_topic_glcc_news_index_path + flash[:danger] = "更新新闻稿失败" + end + end + + def destroy + if @glcc.destroy + redirect_to admins_topic_glcc_news_index_path + flash[:success] = "删除新闻稿成功" + else + redirect_to admins_topic_glcc_news_index_path + flash[:danger] = "删除新闻稿失败" + end + end + + private + def find_glcc + @glcc = ::Topic::GlccNews.find_by_id(params[:id]) + end + + def glcc_params + params.require(:topic_glcc_news).permit(:title, :uuid, :url, :order_index) + end +end \ No newline at end of file diff --git a/app/models/topic.rb b/app/models/topic.rb index 13bf7b5b..e464859e 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -35,6 +35,8 @@ class Topic < ApplicationRecord 'Topic::ExcellentProject' when 'experience_forum' 'Topic::ExperienceForum' + when "glcc_news" + 'Topic::GlccNews' when 'pinned_forum' 'Topic::PinnedForum' end diff --git a/app/models/topic/glcc_news.rb b/app/models/topic/glcc_news.rb new file mode 100644 index 00000000..6b707bf0 --- /dev/null +++ b/app/models/topic/glcc_news.rb @@ -0,0 +1,17 @@ +# == Schema Information +# +# Table name: topics +# +# id :integer not null, primary key +# type :string(255) +# title :string(255) +# uuid :integer +# image_url :string(255) +# url :string(255) +# order_index :integer +# + +# GLCC 新闻稿 +class Topic::GlccNews < Topic + +end \ No newline at end of file diff --git a/app/views/admins/shared/_sidebar.html.erb b/app/views/admins/shared/_sidebar.html.erb index 3e659395..05598873 100644 --- a/app/views/admins/shared/_sidebar.html.erb +++ b/app/views/admins/shared/_sidebar.html.erb @@ -42,7 +42,11 @@
  • <%= sidebar_item(admins_topic_cooperators_path, '合作伙伴管理', icon: 'user', controller: 'admins-topic-cooperators') %>
  • <% end %> - +
  • + <%= sidebar_item_group('#setting-glcc', 'GLCC配置', icon: 'fire') do %> +
  • <%= sidebar_item(admins_topic_glcc_news_index_path, '新闻稿管理', icon: 'edit', controller: 'admins-topic-glcc_news') %>
  • + <% end %> +
  • <%= sidebar_item_group('#setting-submenu', '网站建设', icon: 'cogs') do %>
  • <%= sidebar_item(admins_faqs_path, 'FAQ', icon: 'question-circle', controller: 'admins-faqs') %>
  • diff --git a/app/views/admins/topic/glcc_news/_form_modal.html.erb b/app/views/admins/topic/glcc_news/_form_modal.html.erb new file mode 100644 index 00000000..15af2f27 --- /dev/null +++ b/app/views/admins/topic/glcc_news/_form_modal.html.erb @@ -0,0 +1,44 @@ + \ No newline at end of file diff --git a/app/views/admins/topic/glcc_news/_list.html.erb b/app/views/admins/topic/glcc_news/_list.html.erb new file mode 100644 index 00000000..78391033 --- /dev/null +++ b/app/views/admins/topic/glcc_news/_list.html.erb @@ -0,0 +1,33 @@ + + + + + + + + + + + + + <% if glcc_news.present? %> + <% glcc_news.each_with_index do |news, index| %> + + + + + + + + + <% end %> + <% else %> + <%= render 'admins/shared/no_data_for_table' %> + <% end %> + +
    序号标题跳转地址帖子ID排序等级操作
    <%= list_index_no((params[:page] || 1).to_i, index) %><%= news.title %><%= news.url %><%= news.uuid %><%= news.order_index %> + <%= link_to "编辑", edit_admins_topic_glcc_news_path(news), remote: true, class: "action" %> + <%= link_to "删除", admins_topic_glcc_news_path(news), method: :delete, data:{confirm: "确认删除的吗?"}, class: "action" %> +
    + +<%= render partial: 'admins/shared/paginate', locals: { objects: glcc_news } %> \ No newline at end of file diff --git a/app/views/admins/topic/glcc_news/edit.js.erb b/app/views/admins/topic/glcc_news/edit.js.erb new file mode 100644 index 00000000..64ef542e --- /dev/null +++ b/app/views/admins/topic/glcc_news/edit.js.erb @@ -0,0 +1,2 @@ +$("#glcc-news-modals").html("<%= j render(partial: 'admins/topic/glcc_news/form_modal', locals: {type: 'update'}) %>") +$(".glcc-news-change-modal").modal('show'); \ No newline at end of file diff --git a/app/views/admins/topic/glcc_news/index.html.erb b/app/views/admins/topic/glcc_news/index.html.erb new file mode 100644 index 00000000..8749fa10 --- /dev/null +++ b/app/views/admins/topic/glcc_news/index.html.erb @@ -0,0 +1,18 @@ +<% define_admin_breadcrumbs do %> + <% add_admin_breadcrumb('新闻稿管理') %> +<% end %> + +
    + <%= form_tag(admins_topic_glcc_news_index_path, method: :get, class: 'form-inline search-form flex-1', remote: true) do %> + <%= text_field_tag(:search, params[:search], class: 'form-control col-12 col-md-2 mr-3', placeholder: '标题检索') %> + <%= submit_tag('搜索', class: 'btn btn-primary ml-3', 'data-disable-with': '搜索中...') %> + + <% end %> + <%= link_to "新增", new_admins_topic_glcc_news_path, remote: true, class: "btn btn-primary pull-right", "data-disabled-with":"...新增" %> +
    + +
    + <%= render partial: 'admins/topic/glcc_news/list', locals: { glcc_news: @glcc_news } %> +
    +
    +
    diff --git a/app/views/admins/topic/glcc_news/index.js.erb b/app/views/admins/topic/glcc_news/index.js.erb new file mode 100644 index 00000000..f7db1369 --- /dev/null +++ b/app/views/admins/topic/glcc_news/index.js.erb @@ -0,0 +1 @@ +$('.glcc-news-list-container').html("<%= j( render partial: 'admins/topic/glcc_news/list', locals: { glcc_news: @glcc_news } ) %>"); \ No newline at end of file diff --git a/app/views/admins/topic/glcc_news/new.js.erb b/app/views/admins/topic/glcc_news/new.js.erb new file mode 100644 index 00000000..e03e5acd --- /dev/null +++ b/app/views/admins/topic/glcc_news/new.js.erb @@ -0,0 +1,2 @@ +$("#glcc-news-modals").html("<%= j render(partial: 'admins/topic/glcc_news/form_modal', locals: {type: 'create'}) %>") +$(".glcc-news-change-modal").modal('show'); \ No newline at end of file diff --git a/app/views/topics/_glcc_news.json.jbuilder b/app/views/topics/_glcc_news.json.jbuilder new file mode 100644 index 00000000..0147aff3 --- /dev/null +++ b/app/views/topics/_glcc_news.json.jbuilder @@ -0,0 +1,4 @@ +json.(glcc_news, :id, :title, :url, :uuid) +request_memo = Forum::Memos::GetService.call(glcc_news&.uuid) +json.visits request_memo.nil? ? 0 : request_memo["memo"]["viewed_count"] +json.created_time request_memo.nil? ? format_time(Time.now) : request_memo["memo"]["published_time"] \ No newline at end of file diff --git a/app/views/topics/index.json.jbuilder b/app/views/topics/index.json.jbuilder index 102da6b1..26a4f27d 100644 --- a/app/views/topics/index.json.jbuilder +++ b/app/views/topics/index.json.jbuilder @@ -17,6 +17,8 @@ json.topics do json.partial! "excellent_project", locals: {excellent_project: topic} when "Topic::ExperienceForum" json.partial! "experience_forum", locals: {experience_forum: topic} + when "Topic::GlccNews" + json.partial! "glcc_news", locals: {glcc_news: topic} when "Topic::PinnedForum" json.partial! "pinned_forum", locals: {pinned_forum: topic} else @@ -39,6 +41,8 @@ json.topics do json.partial! "excellent_project", locals: {excellent_project: topic} when "Topic::ExperienceForum" json.partial! "experience_forum", locals: {experience_forum: topic} + when "Topic::GlccNews" + json.partial! "glcc_news", locals: {glcc_news: topic} when "Topic::PinnedForum" json.partial! "pinned_forum", locals: {pinned_forum: topic} else diff --git a/config/routes.rb b/config/routes.rb index 21caf682..eb1c09a8 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -690,6 +690,7 @@ Rails.application.routes.draw do resources :cooperators resources :excellent_projects resources :experience_forums + resources :glcc_news resources :pinned_forums end resources :project_statistics, only: [:index] do From dec264d1693bbb70f572f7e61458570e44251901 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 7 Apr 2022 16:28:40 +0800 Subject: [PATCH 36/65] fix: sync user pwd --- app/controllers/concerns/login_helper.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/controllers/concerns/login_helper.rb b/app/controllers/concerns/login_helper.rb index d8f2445f..e608b783 100644 --- a/app/controllers/concerns/login_helper.rb +++ b/app/controllers/concerns/login_helper.rb @@ -108,7 +108,11 @@ module LoginHelper def sync_pwd_to_gitea!(user, hash={}) return true if user.is_sync_pwd? - sync_params = { email: user.mail } + sync_params = { + login_name: user.name, + source_id: 0, + email: user.mail + } interactor = Gitea::User::UpdateInteractor.call(user.login, sync_params.merge(hash)) if interactor.success? Rails.logger.info "########_ login is #{user.login} sync_pwd_to_gitea success _########" From 551f333261895546a1e7eeacf0af46bd74a5569d Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 8 Apr 2022 14:52:56 +0800 Subject: [PATCH 37/65] fix --- app/controllers/settings_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index e1a5be1d..80edd1e5 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -12,7 +12,7 @@ class SettingsController < ApplicationController def get_navbar @navbar = default_laboratory.navbar if User.current.logged? - pernal_index = {"name"=>"个人主页", "link"=>get_site_url("link", "/current_user"), "hidden"=>false} + pernal_index = {"name"=>"个人主页", "link"=>get_site_url("url", "/current_user"), "hidden"=>false} @navbar << pernal_index end end From eac7331070371acb0599745d204edbea01b506ba Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 8 Apr 2022 15:03:40 +0800 Subject: [PATCH 38/65] fix: settings need prefix --- app/controllers/settings_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index 80edd1e5..95224353 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -12,7 +12,7 @@ class SettingsController < ApplicationController def get_navbar @navbar = default_laboratory.navbar if User.current.logged? - pernal_index = {"name"=>"个人主页", "link"=>get_site_url("url", "/current_user"), "hidden"=>false} + pernal_index = {"name"=>"个人主页", "link"=>get_site_url("url", "#{Rails.application.config_for(:configuration)['platform_url']}/current_user"), "hidden"=>false} @navbar << pernal_index end end From 75a9a65b9bfce9915efd768798e7248d92a98bc8 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 8 Apr 2022 17:38:26 +0800 Subject: [PATCH 39/65] =?UTF-8?q?=E7=AB=9E=E8=B5=9B=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=AD=90=E8=B5=9B=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/views/settings/show.json.jbuilder | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/views/settings/show.json.jbuilder b/app/views/settings/show.json.jbuilder index 4c57d573..4f18eafa 100644 --- a/app/views/settings/show.json.jbuilder +++ b/app/views/settings/show.json.jbuilder @@ -66,4 +66,8 @@ json.setting do else json.system_notification nil end + + json.sub_competitions do + json.array! EduSetting.get("sub_competitions") + end end From 9d46f2743d6a5239e04683d283f3c59c92085e71 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 8 Apr 2022 17:45:15 +0800 Subject: [PATCH 40/65] =?UTF-8?q?=E7=AB=9E=E8=B5=9B=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=AD=90=E8=B5=9B=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/views/settings/show.json.jbuilder | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/app/views/settings/show.json.jbuilder b/app/views/settings/show.json.jbuilder index 4f18eafa..b5f16327 100644 --- a/app/views/settings/show.json.jbuilder +++ b/app/views/settings/show.json.jbuilder @@ -67,7 +67,5 @@ json.setting do json.system_notification nil end - json.sub_competitions do - json.array! EduSetting.get("sub_competitions") - end + json.sub_competitions EduSetting.get("sub_competitions") end From f60cd409b6b3c685707db6191e1a91e08b8d2010 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 8 Apr 2022 18:40:52 +0800 Subject: [PATCH 41/65] =?UTF-8?q?=E7=AB=9E=E8=B5=9B=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=AD=90=E8=B5=9B=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/settings_controller.rb | 10 ++++++++++ app/models/site.rb | 2 +- app/views/settings/show.json.jbuilder | 6 ++++-- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index 68a5ad54..bd44b7fd 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -4,6 +4,7 @@ class SettingsController < ApplicationController get_navbar get_add_menu get_common_menu + get_sub_competitions get_personal_menu get_third_party get_top_system_notification @@ -29,6 +30,15 @@ class SettingsController < ApplicationController end end + def get_sub_competitions + @sub_competitions = [] + Site.add.pluck(:key).each do |key| + hash = {} + hash.merge!("#{key.to_s}": Site.add.where(key: key).select(:id, :name, :url, :key).to_a.map(&:serializable_hash)) + @sub_competitions << hash + end + end + def get_common_menu @common = {} Site.common.select(:url, :key).each do |site| diff --git a/app/models/site.rb b/app/models/site.rb index 755fe386..a8b725ef 100644 --- a/app/models/site.rb +++ b/app/models/site.rb @@ -15,7 +15,7 @@ class Site < ApplicationRecord # add: 添加类链接 # personal: 个人名下类链接, # common: 普通链接 - enum site_type: { add: 0, personal: 1, common: 2 } + enum site_type: { add: 0, personal: 1, common: 2, competition: 3 } scope :by_search, -> (keyword){ where("name LIKE :keyword OR url LIKE :keyword", keyword: "%#{strip_param(keyword)}%") unless strip_param(keyword).blank? } scope :by_site_type, -> (site_type){ where(site_type: strip_param(site_type)) unless strip_param(site_type).blank? } diff --git a/app/views/settings/show.json.jbuilder b/app/views/settings/show.json.jbuilder index b5f16327..abe8207e 100644 --- a/app/views/settings/show.json.jbuilder +++ b/app/views/settings/show.json.jbuilder @@ -51,6 +51,10 @@ json.setting do json.array! @add end + json.sub_competitions do + json.array! @sub_competitions + end + json.personal do json.array! @personal end @@ -66,6 +70,4 @@ json.setting do else json.system_notification nil end - - json.sub_competitions EduSetting.get("sub_competitions") end From 3f85f88c925e58b0a4a18786dfd527b8483a003a Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 8 Apr 2022 18:46:14 +0800 Subject: [PATCH 42/65] =?UTF-8?q?=E7=AB=9E=E8=B5=9B=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=AD=90=E8=B5=9B=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/settings_controller.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index bd44b7fd..839aef2a 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -32,9 +32,9 @@ class SettingsController < ApplicationController def get_sub_competitions @sub_competitions = [] - Site.add.pluck(:key).each do |key| + Site.competition.pluck(:key).each do |key| hash = {} - hash.merge!("#{key.to_s}": Site.add.where(key: key).select(:id, :name, :url, :key).to_a.map(&:serializable_hash)) + hash.merge!("#{key.to_s}": Site.competition.where(key: key).select(:id, :name, :url, :key).to_a.map(&:serializable_hash)) @sub_competitions << hash end end From 6d280ed8f256fc9179a9d839d0c026512d4ab766 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 8 Apr 2022 18:51:01 +0800 Subject: [PATCH 43/65] =?UTF-8?q?=E7=AB=9E=E8=B5=9B=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=AD=90=E8=B5=9B=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/settings_controller.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index 839aef2a..ea75c12d 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -32,7 +32,7 @@ class SettingsController < ApplicationController def get_sub_competitions @sub_competitions = [] - Site.competition.pluck(:key).each do |key| + Site.competition.pluck(:key).uniq.each do |key| hash = {} hash.merge!("#{key.to_s}": Site.competition.where(key: key).select(:id, :name, :url, :key).to_a.map(&:serializable_hash)) @sub_competitions << hash From e97e7aa5500fccc6cf72f81182125bf8e5bb411b Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 8 Apr 2022 21:59:35 +0800 Subject: [PATCH 44/65] =?UTF-8?q?=E7=AB=9E=E8=B5=9B=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=AD=90=E8=B5=9B=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/settings_controller.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index ea75c12d..f3eedd0a 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -33,8 +33,8 @@ class SettingsController < ApplicationController def get_sub_competitions @sub_competitions = [] Site.competition.pluck(:key).uniq.each do |key| - hash = {} - hash.merge!("#{key.to_s}": Site.competition.where(key: key).select(:id, :name, :url, :key).to_a.map(&:serializable_hash)) + hash = {"identifier": "#{key.to_s}"} + hash.merge!("list": Site.competition.where(key: key).select(:id, :name, :url, :key).to_a.map(&:serializable_hash)) @sub_competitions << hash end end From 6e86f9d9f396cda2912cbe772781fe93a73d8fb4 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Fri, 8 Apr 2022 23:07:23 +0800 Subject: [PATCH 45/65] =?UTF-8?q?=E7=AB=9E=E8=B5=9B=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=AD=90=E8=B5=9B=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/settings_controller.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index ea75c12d..f3eedd0a 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -33,8 +33,8 @@ class SettingsController < ApplicationController def get_sub_competitions @sub_competitions = [] Site.competition.pluck(:key).uniq.each do |key| - hash = {} - hash.merge!("#{key.to_s}": Site.competition.where(key: key).select(:id, :name, :url, :key).to_a.map(&:serializable_hash)) + hash = {"identifier": "#{key.to_s}"} + hash.merge!("list": Site.competition.where(key: key).select(:id, :name, :url, :key).to_a.map(&:serializable_hash)) @sub_competitions << hash end end From 910ae4855688441b48414d1a635462a7043c51ec Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 11 Apr 2022 10:50:18 +0800 Subject: [PATCH 46/65] fix: exception to ex --- app/libs/notice.rb | 2 +- app/libs/trace.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/libs/notice.rb b/app/libs/notice.rb index 93d5cb42..18fdb070 100644 --- a/app/libs/notice.rb +++ b/app/libs/notice.rb @@ -7,7 +7,7 @@ module Notice config = Rails.application.config_for(:configuration).symbolize_keys! notice_config = config[:notice].symbolize_keys! raise 'notice config missing' if notice_config.blank? - rescue => exception + rescue => ex raise ex if Rails.env.production? puts %Q{\033[33m [warning] gitea config or configuration.yml missing, diff --git a/app/libs/trace.rb b/app/libs/trace.rb index b1c3c476..3ec3b56a 100644 --- a/app/libs/trace.rb +++ b/app/libs/trace.rb @@ -7,7 +7,7 @@ module Trace config = Rails.application.config_for(:configuration).symbolize_keys! trace_config = config[:trace].symbolize_keys! raise 'trace config missing' if trace_config.blank? - rescue => exception + rescue => ex raise ex if Rails.env.production? puts %Q{\033[33m [warning] gitea config or configuration.yml missing, From 0076468a150eb7e9ac9f63f31eb9b89509bdcd54 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 11 Apr 2022 15:30:28 +0800 Subject: [PATCH 47/65] fix: trace client request data --- app/services/trace/client_service.rb | 56 +++++++--------------------- 1 file changed, 13 insertions(+), 43 deletions(-) diff --git a/app/services/trace/client_service.rb b/app/services/trace/client_service.rb index df9a4321..298c2cf0 100644 --- a/app/services/trace/client_service.rb +++ b/app/services/trace/client_service.rb @@ -2,20 +2,14 @@ class Trace::ClientService < ApplicationService def post(url, params={}) puts "[trace][POST] request params: #{params}" - conn.post do |req| - req.url full_url(url) - req.body = params[:data].to_json - end + conn.post(full_url(url), params[:data]) end def authed_post(token, url, params={}) puts "[trace][POST] request params: #{params}" puts "[trace][POST] request token: #{token}" - conn.post do |req| - req.url full_url(url) - req.body = params[:data].to_json - req.headers['Authorization'] = token - end + conn.headers['Authorization'] = token + conn.post(full_url(url), params[:data]) end def get(url, params={}) @@ -42,67 +36,43 @@ class Trace::ClientService < ApplicationService def delete(url, params={}) puts "[trace][DELETE] request params: #{params}" - conn.delete do |req| - req.url full_url(url) - req.body = params[:data].to_json - end + conn.delete(full_url(url), params[:data]) end def authed_delete(token, url, params={}) puts "[trace][DELETE] request params: #{params}" puts "[trace][DELETE] request token: #{token}" - conn.delete do |req| - req.url full_url(url) - req.body = params[:data].to_json - req.headers['Authorization'] = token - end + conn.headers['Authorization'] = token + conn.delete(full_url(url), params[:data]) end def patch(url, params={}) puts "[trace][PATCH] request params: #{params}" - conn.patch do |req| - req.url full_url(url) - req.body = params[:data].to_json - end + conn.patch(full_url(url), params[:data]) end def authed_patch(token, url, params={}) puts "[trace][PATCH] request params: #{params}" puts "[trace][PATCH] request token: #{token}" - conn.patch do |req| - req.url full_url(url) - req.body = params[:data].to_json - req.headers['Authorization'] = token - end + conn.headers['Authorization'] = token + conn.patch(full_url(url), params[:data]) end def put(url, params={}) puts "[trace][PUT] request params: #{params}" - conn.put do |req| - req.url full_url(url) - req.body = params[:data].to_json - end + conn.put(full_url(url), params[:data]) end def authed_put(token, url, params={}) puts "[trace][PUT] request params: #{params}" puts "[trace][PUT] request token: #{token}" - conn.put do |req| - req.url full_url(url) - req.body = params[:data].to_json - req.headers['Authorization'] = token - end + conn.headers['Authorization'] = token + conn.put(full_url(url), params[:data]) end private def conn - @client ||= begin - Faraday.new(url: domain) do |req| - req.request :url_encoded - req.headers['Content-Type'] = 'application/json' - req.adapter Faraday.default_adapter - end - end + @client ||= Faraday.new(url: domain) @client end From 720c073f32a8f616ee35b2bf9e208a3ae00a8445 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 11 Apr 2022 15:48:47 +0800 Subject: [PATCH 48/65] fix --- app/services/trace/client_service.rb | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/app/services/trace/client_service.rb b/app/services/trace/client_service.rb index 298c2cf0..6dbe87d5 100644 --- a/app/services/trace/client_service.rb +++ b/app/services/trace/client_service.rb @@ -70,11 +70,8 @@ class Trace::ClientService < ApplicationService conn.put(full_url(url), params[:data]) end - private def conn - @client ||= Faraday.new(url: domain) - - @client + Faraday.new(url: domain) end def base_url From 2dfd69ae212ffa4e164c920073a22d2b30380ec0 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 11 Apr 2022 16:08:50 +0800 Subject: [PATCH 49/65] fix: response data result --- app/services/trace/client_service.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/services/trace/client_service.rb b/app/services/trace/client_service.rb index 6dbe87d5..72ffa8ca 100644 --- a/app/services/trace/client_service.rb +++ b/app/services/trace/client_service.rb @@ -105,6 +105,6 @@ class Trace::ClientService < ApplicationService log_error(status, body) - return [body["code"], body["Data"], body["Error"]] + return [body["code"], body["data"], body["error"]] end end \ No newline at end of file From 7aea481ccf881f4feeba2205736e90289f3b9b58 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 18 Apr 2022 10:24:54 +0800 Subject: [PATCH 50/65] add: glcc_apply_infomations admin navbar --- app/views/admins/shared/_sidebar.html.erb | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/views/admins/shared/_sidebar.html.erb b/app/views/admins/shared/_sidebar.html.erb index 05598873..4c6e6de7 100644 --- a/app/views/admins/shared/_sidebar.html.erb +++ b/app/views/admins/shared/_sidebar.html.erb @@ -45,6 +45,11 @@
  • <%= sidebar_item_group('#setting-glcc', 'GLCC配置', icon: 'fire') do %>
  • <%= sidebar_item(admins_topic_glcc_news_index_path, '新闻稿管理', icon: 'edit', controller: 'admins-topic-glcc_news') %>
  • +
  • + <% if EduSetting.get("glcc_apply_informations_admin_url")%> + <%= sidebar_item(EduSetting.get("glcc_apply_informations_admin_url"), '报名列表', icon: 'user', controller: 'root') %> + <% end %> +
  • <% end %>
  • From 8f5bb0e2d9b8c146cb42f8f84e642eb59c5344b5 Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 18 Apr 2022 10:52:48 +0800 Subject: [PATCH 51/65] fix: organization gitea_token read by associations --- app/models/organization.rb | 4 ++++ app/services/organizations/create_service.rb | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/app/models/organization.rb b/app/models/organization.rb index 40c676e0..56351a41 100644 --- a/app/models/organization.rb +++ b/app/models/organization.rb @@ -83,6 +83,10 @@ class Organization < Owner after_save :reset_cache_data + def gitea_token + team_users.joins(:team).where(teams: {authorize: "owner"}).take&.user&.gitea_token + end + def reset_cache_data Cache::V2::OwnerCommonService.new(self.id).reset end diff --git a/app/services/organizations/create_service.rb b/app/services/organizations/create_service.rb index a430ed6f..26377919 100644 --- a/app/services/organizations/create_service.rb +++ b/app/services/organizations/create_service.rb @@ -47,7 +47,7 @@ class Organizations::CreateService < ApplicationService end def create_org_and_extension - @organization = Organization.build(params[:name], params[:nickname], user.gitea_token) + @organization = Organization.build(params[:name], params[:nickname]) org_extension = OrganizationExtension.build(organization.id, description, website, location, repo_admin_change_team_access, visibility, max_repo_creation) From fc3cf01d3f6f730d9ae82b5da0a9ee66164d50ed Mon Sep 17 00:00:00 2001 From: yystopf Date: Mon, 18 Apr 2022 13:49:08 +0800 Subject: [PATCH 52/65] add: get user image action --- app/controllers/users_controller.rb | 7 +++++++ app/helpers/application_helper.rb | 9 +++++++++ app/views/users/get_user_info.json.jbuilder | 2 +- config/routes.rb | 1 + 4 files changed, 18 insertions(+), 1 deletion(-) diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 00ea926f..acc82661 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -97,6 +97,13 @@ class UsersController < ApplicationController render_error(-1, '头像修改失败!') end + def get_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) + + redirect_to Rails.application.config_for(:configuration)['platform_url'] + "/" + url_to_avatar(@user).to_s + end + def me @user = current_user end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index f2a9f93b..e7f8611e 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -147,6 +147,15 @@ module ApplicationHelper end end + def url_to_avatar_with_platform_url(source) + platform_url = Rails.application.config_for(:configuration)['platform_url'] + if platform_url + return Rails.application.config_for(:configuration)['platform_url'] + "/" + url_to_avatar(source).to_s + else + return url_to_avatar(source).to_s + end + end + # 主页banner图 def banner_img(source_type) if File.exist?(disk_filename(source_type, "banner")) diff --git a/app/views/users/get_user_info.json.jbuilder b/app/views/users/get_user_info.json.jbuilder index 2f96c696..5fa4df16 100644 --- a/app/views/users/get_user_info.json.jbuilder +++ b/app/views/users/get_user_info.json.jbuilder @@ -22,4 +22,4 @@ json.city @user.city json.custom_department @user.custom_department json.description @user.description json.(@user, :show_email, :show_department, :show_location) -json.message_unread_total @message_unread_total +json.message_unread_total @message_unread_total diff --git a/config/routes.rb b/config/routes.rb index 7e280820..da63dab6 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -214,6 +214,7 @@ Rails.application.routes.draw do get :fan_users get :hovercard put :update_image + get :get_image end collection do post :following From 088c617cc12be188a51c5840d82cfbc237e741ce Mon Sep 17 00:00:00 2001 From: yystopf Date: Tue, 26 Apr 2022 17:15:59 +0800 Subject: [PATCH 53/65] add: name query for branches --- app/controllers/projects_controller.rb | 2 +- app/controllers/pull_requests_controller.rb | 4 ++-- app/controllers/version_releases_controller.rb | 2 +- app/services/branches/list_service.rb | 7 ++++--- .../gitea/repository/branches/list_name_service.rb | 7 ++++--- app/services/gitea/repository/branches/list_service.rb | 7 ++++--- 6 files changed, 16 insertions(+), 13 deletions(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index be9a93d9..b14b105b 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -88,7 +88,7 @@ class ProjectsController < ApplicationController return @branches = [] unless @project.forge? # result = Gitea::Repository::Branches::ListService.call(@owner, @project.identifier) - result = Gitea::Repository::Branches::ListNameService.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 end diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 189c5c6b..0ac7a714 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -29,7 +29,7 @@ class PullRequestsController < ApplicationController end def new - @all_branches = Branches::ListService.call(@owner, @project) + @all_branches = Branches::ListService.call(@owner, @project, params[:branch_name]) @is_fork = @project.forked_from_project_id.present? @projects_names = [{ project_user_login: @owner.try(:login), @@ -50,7 +50,7 @@ class PullRequestsController < ApplicationController end def get_branches - branch_result = Branches::ListService.call(@owner, @project) + branch_result = Branches::ListService.call(@owner, @project, params[:name]) render json: branch_result # return json: branch_result end diff --git a/app/controllers/version_releases_controller.rb b/app/controllers/version_releases_controller.rb index 2d7546a1..dd59098f 100644 --- a/app/controllers/version_releases_controller.rb +++ b/app/controllers/version_releases_controller.rb @@ -14,7 +14,7 @@ class VersionReleasesController < ApplicationController def new #获取所有的分支 @all_branches = [] - get_all_branches = Gitea::Repository::Branches::ListService.new(@user, @repository.try(:identifier)).call + get_all_branches = Gitea::Repository::Branches::ListService.new(@user, @repository.try(:identifier), params[:branch_name]).call if get_all_branches && get_all_branches.size > 0 get_all_branches.each do |b| @all_branches.push(b["name"]) diff --git a/app/services/branches/list_service.rb b/app/services/branches/list_service.rb index a3b77a7b..7b47658e 100644 --- a/app/services/branches/list_service.rb +++ b/app/services/branches/list_service.rb @@ -1,17 +1,18 @@ class Branches::ListService < ApplicationService - attr_reader :user, :project + attr_reader :user, :project, :name - def initialize(user, project) + def initialize(user, project, name=nil) @user = user @project = project + @name = name end def call all_branches = [] user_name = user.try(:show_real_name) identifier = project.repository.try(:identifier) - get_all_branches = Gitea::Repository::Branches::ListService.new(user, identifier).call + get_all_branches = Gitea::Repository::Branches::ListService.new(user, identifier, name).call all_branches = branch_lists(user_name,user.try(:login), identifier, get_all_branches) if get_all_branches && get_all_branches.size > 0 return all_branches end diff --git a/app/services/gitea/repository/branches/list_name_service.rb b/app/services/gitea/repository/branches/list_name_service.rb index 716ee464..c005c835 100644 --- a/app/services/gitea/repository/branches/list_name_service.rb +++ b/app/services/gitea/repository/branches/list_name_service.rb @@ -1,9 +1,10 @@ class Gitea::Repository::Branches::ListNameService < Gitea::ClientService - attr_reader :user, :repo + attr_reader :user, :repo, :name - def initialize(user, repo) + def initialize(user, repo, name=nil) @user = user @repo = repo + @name = name end def call @@ -13,7 +14,7 @@ class Gitea::Repository::Branches::ListNameService < Gitea::ClientService private def params - Hash.new.merge(token: user.gitea_token) + Hash.new.merge(token: user.gitea_token, name: name) end def url diff --git a/app/services/gitea/repository/branches/list_service.rb b/app/services/gitea/repository/branches/list_service.rb index f4296509..7722ecd0 100644 --- a/app/services/gitea/repository/branches/list_service.rb +++ b/app/services/gitea/repository/branches/list_service.rb @@ -1,9 +1,10 @@ class Gitea::Repository::Branches::ListService < Gitea::ClientService - attr_reader :user, :repo + attr_reader :user, :repo, :name - def initialize(user, repo) + def initialize(user, repo, name=nil) @user = user @repo = repo + @name = name end def call @@ -13,7 +14,7 @@ class Gitea::Repository::Branches::ListService < Gitea::ClientService private def params - Hash.new.merge(token: user.gitea_token) + Hash.new.merge(token: user.gitea_token, name: name) end def url From 396ac55429d37e72d56fd505258e9900f2c4f7e7 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 28 Apr 2022 10:42:55 +0800 Subject: [PATCH 54/65] add: user super description --- app/controllers/users_controller.rb | 1 + app/models/user.rb | 2 +- app/models/user_extension.rb | 57 +++++++++---------- app/views/users/get_user_info.json.jbuilder | 3 +- app/views/users/show.json.jbuilder | 1 + ...dd_super_description_to_user_extensions.rb | 6 ++ 6 files changed, 39 insertions(+), 31 deletions(-) create mode 100644 db/migrate/20220428015313_add_super_description_to_user_extensions.rb diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index acc82661..532f29ba 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -313,6 +313,7 @@ class UsersController < ApplicationController :occupation, :technical_title, :school_id, :department_id, :province, :city, :custom_department, :identity, :student_id, :description, + :show_super_description, :super_description, :show_email, :show_location, :show_department] ) end diff --git a/app/models/user.rb b/app/models/user.rb index d661ab59..fa940c29 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -187,7 +187,7 @@ class User < Owner attr_accessor :password, :password_confirmation delegate :description, :gender, :department_id, :school_id, :location, :location_city, - :show_email, :show_location, :show_department, + :show_email, :show_location, :show_department, :super_description, :show_super_description, :technical_title, :province, :city, :custom_department, to: :user_extension, allow_nil: true before_save :update_hashed_password, :set_lastname diff --git a/app/models/user_extension.rb b/app/models/user_extension.rb index ee208af7..379243bf 100644 --- a/app/models/user_extension.rb +++ b/app/models/user_extension.rb @@ -2,35 +2,34 @@ # # Table name: user_extensions # -# id :integer not null, primary key -# user_id :integer not null -# birthday :date -# brief_introduction :string(255) -# gender :integer -# location :string(255) -# occupation :string(255) -# work_experience :integer -# zip_code :integer -# created_at :datetime not null -# updated_at :datetime not null -# technical_title :string(255) -# identity :integer -# student_id :string(255) -# teacher_realname :string(255) -# student_realname :string(255) -# location_city :string(255) -# school_id :integer -# description :string(255) default("") -# department_id :integer -# honor :text(65535) -# edu_background :integer -# edu_entry_year :integer -# province :string(255) -# city :string(255) -# custom_department :string(255) -# show_email :boolean default("0") -# show_location :boolean default("0") -# show_department :boolean default("0") +# id :integer not null, primary key +# user_id :integer not null +# birthday :date +# brief_introduction :string(255) +# gender :integer +# location :string(255) +# occupation :string(255) +# work_experience :integer +# zip_code :integer +# created_at :datetime not null +# updated_at :datetime not null +# technical_title :string(255) +# identity :integer +# student_id :string(255) +# teacher_realname :string(255) +# student_realname :string(255) +# location_city :string(255) +# school_id :integer +# description :string(255) default("") +# department_id :integer +# province :string(255) +# city :string(255) +# custom_department :string(255) +# show_email :boolean default("0") +# show_location :boolean default("0") +# show_department :boolean default("0") +# super_description :text(4294967295) +# show_super_description :boolean # # Indexes # diff --git a/app/views/users/get_user_info.json.jbuilder b/app/views/users/get_user_info.json.jbuilder index 5fa4df16..8fcadb1c 100644 --- a/app/views/users/get_user_info.json.jbuilder +++ b/app/views/users/get_user_info.json.jbuilder @@ -21,5 +21,6 @@ json.province @user.province json.city @user.city json.custom_department @user.custom_department json.description @user.description -json.(@user, :show_email, :show_department, :show_location) +json.super_description @user.super_description +json.(@user, :show_email, :show_department, :show_location, :show_super_description) json.message_unread_total @message_unread_total diff --git a/app/views/users/show.json.jbuilder b/app/views/users/show.json.jbuilder index 1c9e7793..f35705ce 100644 --- a/app/views/users/show.json.jbuilder +++ b/app/views/users/show.json.jbuilder @@ -13,4 +13,5 @@ json.email @user.show_email ? @user.mail : nil json.province @user.show_location ? @user.province : nil json.city @user.show_location ? @user.city : nil json.custom_department @user.show_department ? @user.custom_department : nil +json.super_description @user.show_super_description ? @user.super_description : nil json.description @user.description \ No newline at end of file diff --git a/db/migrate/20220428015313_add_super_description_to_user_extensions.rb b/db/migrate/20220428015313_add_super_description_to_user_extensions.rb new file mode 100644 index 00000000..07651677 --- /dev/null +++ b/db/migrate/20220428015313_add_super_description_to_user_extensions.rb @@ -0,0 +1,6 @@ +class AddSuperDescriptionToUserExtensions < ActiveRecord::Migration[5.2] + def change + add_column :user_extensions, :super_description, :text, :limit => 4294967295 + add_column :user_extensions, :show_super_description, :boolean + end +end From ec3a556a6f31fb162d47db88c88ba0e3f99f2c34 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 28 Apr 2022 11:03:42 +0800 Subject: [PATCH 55/65] fix: default value for show super description --- app/models/user_extension.rb | 2 +- .../20220428015313_add_super_description_to_user_extensions.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/models/user_extension.rb b/app/models/user_extension.rb index 379243bf..c1046ac2 100644 --- a/app/models/user_extension.rb +++ b/app/models/user_extension.rb @@ -29,7 +29,7 @@ # show_location :boolean default("0") # show_department :boolean default("0") # super_description :text(4294967295) -# show_super_description :boolean +# show_super_description :boolean default("0") # # Indexes # diff --git a/db/migrate/20220428015313_add_super_description_to_user_extensions.rb b/db/migrate/20220428015313_add_super_description_to_user_extensions.rb index 07651677..3e00416e 100644 --- a/db/migrate/20220428015313_add_super_description_to_user_extensions.rb +++ b/db/migrate/20220428015313_add_super_description_to_user_extensions.rb @@ -1,6 +1,6 @@ class AddSuperDescriptionToUserExtensions < ActiveRecord::Migration[5.2] def change add_column :user_extensions, :super_description, :text, :limit => 4294967295 - add_column :user_extensions, :show_super_description, :boolean + add_column :user_extensions, :show_super_description, :boolean, default: false end end From 3abd6037d99e16931f6ad44ece25d004ec28cf9e Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 28 Apr 2022 11:12:16 +0800 Subject: [PATCH 56/65] fix: show super description aways desplay --- app/views/users/show.json.jbuilder | 1 + 1 file changed, 1 insertion(+) diff --git a/app/views/users/show.json.jbuilder b/app/views/users/show.json.jbuilder index f35705ce..dfeb45cf 100644 --- a/app/views/users/show.json.jbuilder +++ b/app/views/users/show.json.jbuilder @@ -14,4 +14,5 @@ json.province @user.show_location ? @user.province : nil json.city @user.show_location ? @user.city : nil json.custom_department @user.show_department ? @user.custom_department : nil json.super_description @user.show_super_description ? @user.super_description : nil +json.show_super_description @user.show_super_description json.description @user.description \ No newline at end of file From f15cd44dff87a2df8072133140fa7f2c787a4c13 Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 28 Apr 2022 18:53:33 +0800 Subject: [PATCH 57/65] add: compare add paginate --- app/controllers/compare_controller.rb | 12 ++++++++++++ app/helpers/repositories_helper.rb | 1 - app/views/compare/show.json.jbuilder | 4 ++-- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/app/controllers/compare_controller.rb b/app/controllers/compare_controller.rb index 382e7506..1aab7adb 100644 --- a/app/controllers/compare_controller.rb +++ b/app/controllers/compare_controller.rb @@ -9,6 +9,10 @@ class CompareController < ApplicationController load_compare_params compare @merge_status, @merge_message = get_merge_message + @page_size = page_size <= 0 ? 1 : page_size + @page_limit = page_limit <=0 ? 15 : page_limit + @page_offset = (@page_size -1) * @page_limit + Rails.logger.info("+========#{@page_size}-#{@page_limit}-#{@page_offset}") end private @@ -53,4 +57,12 @@ class CompareController < ApplicationController def gitea_compare(base, head) Gitea::Repository::Commits::CompareService.call(@owner.login, @project.identifier, Addressable::URI.escape(base), Addressable::URI.escape(head), current_user.gitea_token) end + + def page_size + params.fetch(:page, 1).to_i + end + + def page_limit + params.fetch(:limit, 15).to_i + end end diff --git a/app/helpers/repositories_helper.rb b/app/helpers/repositories_helper.rb index e6e7e87f..b8bfc31c 100644 --- a/app/helpers/repositories_helper.rb +++ b/app/helpers/repositories_helper.rb @@ -36,7 +36,6 @@ module RepositoriesHelper end def render_cache_commit_author(author_json) - Rails.logger.info author_json['Email'] if author_json["name"].present? && author_json["email"].present? return find_user_in_redis_cache(author_json['name'], author_json['email']) end diff --git a/app/views/compare/show.json.jbuilder b/app/views/compare/show.json.jbuilder index deca4103..26a7cb76 100644 --- a/app/views/compare/show.json.jbuilder +++ b/app/views/compare/show.json.jbuilder @@ -1,7 +1,7 @@ -json.commits_count @compare_result['Commits']&.size +json.commits_count @compare_result['CommitsCount'] # json.commits @compare_result['Commits'], partial: 'pull_requests/commit', as: :commit json.commits do - json.array! @compare_result['Commits'] do |commit| + json.array! @compare_result['Commits'][@page_offset...(@page_offset + @page_limit)] do |commit| json.author do json.partial! 'repositories/commit_author', locals: { user: render_cache_commit_author(commit['Committer']), name: commit['Committer']['Name'] } end From 7c88ea3d6713065f29421d025288947a5194b11b Mon Sep 17 00:00:00 2001 From: yystopf Date: Thu, 5 May 2022 10:00:02 +0800 Subject: [PATCH 58/65] add: quit repo --- app/controllers/projects_controller.rb | 21 ++++++++++++++++++++- config/routes.rb | 1 + 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index b14b105b..c4e440af 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -13,6 +13,8 @@ class ProjectsController < ApplicationController def menu_list menu = [] + user_is_admin = current_user.admin? || @project.manager?(current_user) + menu.append(menu_hash_by_name("home")) menu.append(menu_hash_by_name("code")) if @project.has_menu_permission("code") menu.append(menu_hash_by_name("issues")) if @project.has_menu_permission("issues") @@ -22,7 +24,8 @@ class ProjectsController < ApplicationController menu.append(menu_hash_by_name("wiki")) if @project.has_menu_permission("wiki") && @project.forge? menu.append(menu_hash_by_name("resources")) if @project.has_menu_permission("resources") && @project.forge? menu.append(menu_hash_by_name("activity")) - menu.append(menu_hash_by_name("settings")) if (current_user.admin? || @project.manager?(current_user)) && @project.forge? + menu.append(menu_hash_by_name("settings")) if user_is_admin && @project.forge? + menu.append(menu_hash_by_name("quit")) if !user_is_admin && @project.member(current_user.id) && @project.forge? render json: menu end @@ -177,6 +180,22 @@ class ProjectsController < ApplicationController tip_exception(e.message) end + def quit + user_is_admin = current_user.admin? || @project.manager?(current_user) + if !user_is_admin && @project.member(current_user.id) && @project.forge? + ActiveRecord::Base.transaction do + Projects::DeleteMemberInteractor.call(@project.owner, @project, current_user) + SendTemplateMessageJob.perform_later('ProjectMemberLeft', current_user.id, current_user.id, @project.id) if Site.has_notice_menu? + render_ok + end + else + render_forbidden('你不能退出该仓库') + end + rescue Exception => e + uid_logger_error(e.message) + tip_exception(e.message) + end + def watch_users watchers = @project.watchers.includes(:user).order("watchers.created_at desc").distinct @watchers_count = watchers.size diff --git a/config/routes.rb b/config/routes.rb index da63dab6..01ff4fa3 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -436,6 +436,7 @@ Rails.application.routes.draw do get :stargazers, to: 'projects#praise_users' get :forks, to: 'projects#fork_users' match :about, :via => [:get, :put, :post] + post :quit end end From 55c74de8e46c59ec353593fe7bd92543c2688d26 Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Thu, 5 May 2022 10:41:02 +0800 Subject: [PATCH 59/65] =?UTF-8?q?fork=5Fusers=E5=8A=A0=E5=85=A5=E7=BB=84?= =?UTF-8?q?=E7=BB=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/fork_user.rb | 2 +- app/services/pull_requests/create_service.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/models/fork_user.rb b/app/models/fork_user.rb index bddf8f75..4177392e 100644 --- a/app/models/fork_user.rb +++ b/app/models/fork_user.rb @@ -17,7 +17,7 @@ class ForkUser < ApplicationRecord belongs_to :project - belongs_to :user + belongs_to :owner belongs_to :fork_project, class_name: 'Project', foreign_key: :fork_project_id after_create :incre_project_common, :incre_user_statistic, :incre_platform_statistic diff --git a/app/services/pull_requests/create_service.rb b/app/services/pull_requests/create_service.rb index 703bb5de..258d0e31 100644 --- a/app/services/pull_requests/create_service.rb +++ b/app/services/pull_requests/create_service.rb @@ -157,7 +157,7 @@ class PullRequests::CreateService < ApplicationService raise "head参数不能为空" if @params[:head].blank? raise "base参数不能为空" if @params[:base].blank? raise "fork_project_id参数错误" if is_original && !@project.forked_projects.pluck(:id).include?(@params[:fork_project_id].to_i) - raise "merge_user_login参数错误" if is_original && @project.fork_users.joins(:user).where(users: {login: @params[:merge_user_login]}).blank? + raise "merge_user_login参数错误" if is_original && @project.fork_users.joins(:owner).where(users: {login: @params[:merge_user_login]}).blank? raise "分支内容相同,无需创建合并请求" if @params[:head] === @params[:base] && !is_original raise "合并请求已存在" if @project&.pull_requests.where(head: @params[:head], base: @params[:base], status: 0, is_original: is_original, fork_project_id: @params[:fork_project_id]).present? raise @pull_issue.errors.full_messages.join(", ") unless pull_issue.valid? From 676024b6db09b7f535f07a68f795e85397ff65fb Mon Sep 17 00:00:00 2001 From: xiaoxiaoqiong Date: Thu, 5 May 2022 10:42:08 +0800 Subject: [PATCH 60/65] =?UTF-8?q?fork=5Fusers=E5=8A=A0=E5=85=A5=E7=BB=84?= =?UTF-8?q?=E7=BB=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/models/fork_user.rb | 2 +- app/services/pull_requests/create_service.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/models/fork_user.rb b/app/models/fork_user.rb index bddf8f75..4177392e 100644 --- a/app/models/fork_user.rb +++ b/app/models/fork_user.rb @@ -17,7 +17,7 @@ class ForkUser < ApplicationRecord belongs_to :project - belongs_to :user + belongs_to :owner belongs_to :fork_project, class_name: 'Project', foreign_key: :fork_project_id after_create :incre_project_common, :incre_user_statistic, :incre_platform_statistic diff --git a/app/services/pull_requests/create_service.rb b/app/services/pull_requests/create_service.rb index 703bb5de..258d0e31 100644 --- a/app/services/pull_requests/create_service.rb +++ b/app/services/pull_requests/create_service.rb @@ -157,7 +157,7 @@ class PullRequests::CreateService < ApplicationService raise "head参数不能为空" if @params[:head].blank? raise "base参数不能为空" if @params[:base].blank? raise "fork_project_id参数错误" if is_original && !@project.forked_projects.pluck(:id).include?(@params[:fork_project_id].to_i) - raise "merge_user_login参数错误" if is_original && @project.fork_users.joins(:user).where(users: {login: @params[:merge_user_login]}).blank? + raise "merge_user_login参数错误" if is_original && @project.fork_users.joins(:owner).where(users: {login: @params[:merge_user_login]}).blank? raise "分支内容相同,无需创建合并请求" if @params[:head] === @params[:base] && !is_original raise "合并请求已存在" if @project&.pull_requests.where(head: @params[:head], base: @params[:base], status: 0, is_original: is_original, fork_project_id: @params[:fork_project_id]).present? raise @pull_issue.errors.full_messages.join(", ") unless pull_issue.valid? From ae7d0d13296e595a9a3e2fa52b627d6d41d023f0 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 6 May 2022 09:56:22 +0800 Subject: [PATCH 61/65] add: issues description and journals notes validate --- app/controllers/issues_controller.rb | 4 ++-- app/controllers/journals_controller.rb | 11 +++++++++-- app/forms/issues/create_form.rb | 4 ++-- app/forms/issues/update_form.rb | 4 +++- app/forms/journals/create_form.rb | 7 +++++++ app/forms/journals/update_form.rb | 8 ++++++++ config/locales/forms/create_issuse_form.zh-CN.yml | 8 +++++++- 7 files changed, 38 insertions(+), 8 deletions(-) create mode 100644 app/forms/journals/create_form.rb create mode 100644 app/forms/journals/update_form.rb diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index b546ea71..e21c087b 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -109,7 +109,7 @@ class IssuesController < ApplicationController def create issue_params = issue_send_params(params) - Issues::CreateForm.new({subject:issue_params[:subject]}).validate! + Issues::CreateForm.new(issue_params.slice(:subject, :description)).validate! @issue = Issue.new(issue_params) if @issue.save! SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if Site.has_notice_menu? @@ -223,7 +223,7 @@ class IssuesController < ApplicationController normal_status(-1, "不允许修改为关闭状态") else issue_params = issue_send_params(params).except(:issue_classify, :author_id, :project_id) - Issues::UpdateForm.new({subject:issue_params[:subject]}).validate! + Issues::UpdateForm.new(issue_params.slice(:subject, :description)).validate! if @issue.update_attributes(issue_params) if @issue&.pull_request.present? SendTemplateMessageJob.perform_later('PullRequestChanged', current_user.id, @issue&.pull_request&.id, @issue.previous_changes.slice(:assigned_to_id, :priority_id, :fixed_version_id, :issue_tags_value)) if Site.has_notice_menu? diff --git a/app/controllers/journals_controller.rb b/app/controllers/journals_controller.rb index 8fbe4692..2dd1fef6 100644 --- a/app/controllers/journals_controller.rb +++ b/app/controllers/journals_controller.rb @@ -23,6 +23,7 @@ class JournalsController < ApplicationController normal_status(-1, "评论内容不能为空") else ActiveRecord::Base.transaction do + Journals::CreateForm.new({notes: notes.to_s.strip}).validate! journal_params = { journalized_id: @issue.id , journalized_type: "Issue", @@ -53,6 +54,9 @@ class JournalsController < ApplicationController end end end + rescue Exception => exception + puts exception.message + normal_status(-1, exception.message) end def destroy @@ -70,7 +74,8 @@ class JournalsController < ApplicationController def update content = params[:content] - if content.present? + if content.present? + Journals::UpdateForm.new({notes: notes.to_s.strip}).validate! if @journal.update_attribute(:notes, content) normal_status(0, "更新成功") else @@ -79,7 +84,9 @@ class JournalsController < ApplicationController else normal_status(-1, "评论的内容不能为空") end - + rescue Exception => exception + puts exception.message + normal_status(-1, exception.message) end def get_children_journals diff --git a/app/forms/issues/create_form.rb b/app/forms/issues/create_form.rb index 602775ff..7ab942bc 100644 --- a/app/forms/issues/create_form.rb +++ b/app/forms/issues/create_form.rb @@ -1,11 +1,11 @@ class Issues::CreateForm include ActiveModel::Model - attr_accessor :subject + attr_accessor :subject, :description validates :subject, presence: { message: "不能为空" } validates :subject, length: { maximum: 200, too_long: "不能超过200个字符" } - + validates :description, length: { maximum: 65535, too_long: "不能超过65535个字符"} end diff --git a/app/forms/issues/update_form.rb b/app/forms/issues/update_form.rb index 64acdfb5..1aa971e9 100644 --- a/app/forms/issues/update_form.rb +++ b/app/forms/issues/update_form.rb @@ -1,10 +1,12 @@ class Issues::UpdateForm include ActiveModel::Model - attr_accessor :subject + attr_accessor :subject, :description validates :subject, presence: { message: "不能为空" } validates :subject, length: { maximum: 200, too_long: "不能超过200个字符" } + validates :description, length: { maximum: 65535, too_long: "不能超过65535个字符"} + end \ No newline at end of file diff --git a/app/forms/journals/create_form.rb b/app/forms/journals/create_form.rb new file mode 100644 index 00000000..8b96bc64 --- /dev/null +++ b/app/forms/journals/create_form.rb @@ -0,0 +1,7 @@ +class Journals::CreateForm + include ActiveModel::Model + + attr_accessor :notes + + validates :notes, length: { maximum: 65535, too_long: "不能超过65535个字符"} +end diff --git a/app/forms/journals/update_form.rb b/app/forms/journals/update_form.rb new file mode 100644 index 00000000..74f8fa6f --- /dev/null +++ b/app/forms/journals/update_form.rb @@ -0,0 +1,8 @@ +class Journals::UpdateForm + include ActiveModel::Model + + attr_accessor :notes + + validates :notes, length: { maximum: 65535, too_long: "不能超过65535个字符"} + +end \ No newline at end of file diff --git a/config/locales/forms/create_issuse_form.zh-CN.yml b/config/locales/forms/create_issuse_form.zh-CN.yml index 643c6866..bebab7e2 100644 --- a/config/locales/forms/create_issuse_form.zh-CN.yml +++ b/config/locales/forms/create_issuse_form.zh-CN.yml @@ -3,5 +3,11 @@ attributes: issues/create_form: subject: 标题 + description: 描述 issues/update_form: - subject: 标题 \ No newline at end of file + subject: 标题 + description: 描述 + journals/create_form: + notes: 评论 + journals/update_form: + notes: 评论 \ No newline at end of file From 6aa3321d17e33a563a373e0c2d0bf32ff73216f1 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 6 May 2022 14:29:05 +0800 Subject: [PATCH 62/65] fix: pr title description validate --- app/controllers/pull_requests_controller.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index 0ac7a714..bb040784 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -58,6 +58,7 @@ class PullRequestsController < ApplicationController def create # return normal_status(-1, "您不是目标分支开发者,没有权限,请联系目标分支作者.") unless @project.operator?(current_user) ActiveRecord::Base.transaction do + Issues::CreateForm.new({subject: params[:title], description: params}).validate! @pull_request, @gitea_pull_request = PullRequests::CreateService.call(current_user, @owner, @project, params) if @gitea_pull_request[:status] == :success @pull_request.bind_gitea_pull_request!(@gitea_pull_request[:body]["number"], @gitea_pull_request[:body]["id"]) @@ -89,7 +90,7 @@ class PullRequestsController < ApplicationController else ActiveRecord::Base.transaction do begin - return normal_status(-1, "title不能超过255个字符") if params[:title].length > 255 + Issues::UpdateForm.new({subject: params[:title], description: params[:body]}).validate! merge_params @issue&.issue_tags_relates&.destroy_all if params[:issue_tag_ids].blank? From 000197b0d1b723932fbd47bec1fb866cf8449d66 Mon Sep 17 00:00:00 2001 From: yystopf Date: Fri, 6 May 2022 17:25:34 +0800 Subject: [PATCH 63/65] fix: issues and pull_request length calculate --- app/controllers/issues_controller.rb | 4 ++-- app/controllers/journals_controller.rb | 4 ++-- app/controllers/pull_requests_controller.rb | 4 ++-- app/models/journal.rb | 2 +- app/models/pull_request.rb | 6 +++--- ..._change_issues_description_and_journals_notes_column.rb | 7 +++++++ 6 files changed, 17 insertions(+), 10 deletions(-) create mode 100644 db/migrate/20220506083813_change_issues_description_and_journals_notes_column.rb diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index e21c087b..ee0b5eff 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -109,7 +109,7 @@ class IssuesController < ApplicationController def create issue_params = issue_send_params(params) - Issues::CreateForm.new(issue_params.slice(:subject, :description)).validate! + Issues::CreateForm.new({subject: issue_params[:subject], description: issue_params[:description].b}).validate! @issue = Issue.new(issue_params) if @issue.save! SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if Site.has_notice_menu? @@ -223,7 +223,7 @@ class IssuesController < ApplicationController normal_status(-1, "不允许修改为关闭状态") else issue_params = issue_send_params(params).except(:issue_classify, :author_id, :project_id) - Issues::UpdateForm.new(issue_params.slice(:subject, :description)).validate! + Issues::UpdateForm.new({subject: issue_params[:subject], description: issue_params[:description].b}).validate! if @issue.update_attributes(issue_params) if @issue&.pull_request.present? SendTemplateMessageJob.perform_later('PullRequestChanged', current_user.id, @issue&.pull_request&.id, @issue.previous_changes.slice(:assigned_to_id, :priority_id, :fixed_version_id, :issue_tags_value)) if Site.has_notice_menu? diff --git a/app/controllers/journals_controller.rb b/app/controllers/journals_controller.rb index 2dd1fef6..7c067659 100644 --- a/app/controllers/journals_controller.rb +++ b/app/controllers/journals_controller.rb @@ -23,7 +23,7 @@ class JournalsController < ApplicationController normal_status(-1, "评论内容不能为空") else ActiveRecord::Base.transaction do - Journals::CreateForm.new({notes: notes.to_s.strip}).validate! + Journals::CreateForm.new({notes: notes.to_s.strip.b}).validate! journal_params = { journalized_id: @issue.id , journalized_type: "Issue", @@ -75,7 +75,7 @@ class JournalsController < ApplicationController def update content = params[:content] if content.present? - Journals::UpdateForm.new({notes: notes.to_s.strip}).validate! + Journals::UpdateForm.new({notes: notes.to_s.strip.b}).validate! if @journal.update_attribute(:notes, content) normal_status(0, "更新成功") else diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index bb040784..bf5646a4 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -58,7 +58,7 @@ class PullRequestsController < ApplicationController def create # return normal_status(-1, "您不是目标分支开发者,没有权限,请联系目标分支作者.") unless @project.operator?(current_user) ActiveRecord::Base.transaction do - Issues::CreateForm.new({subject: params[:title], description: params}).validate! + Issues::CreateForm.new({subject: params[:title], description: params[:body].b}).validate! @pull_request, @gitea_pull_request = PullRequests::CreateService.call(current_user, @owner, @project, params) if @gitea_pull_request[:status] == :success @pull_request.bind_gitea_pull_request!(@gitea_pull_request[:body]["number"], @gitea_pull_request[:body]["id"]) @@ -90,7 +90,7 @@ class PullRequestsController < ApplicationController else ActiveRecord::Base.transaction do begin - Issues::UpdateForm.new({subject: params[:title], description: params[:body]}).validate! + Issues::UpdateForm.new({subject: params[:title], description: params[:body].b}).validate! merge_params @issue&.issue_tags_relates&.destroy_all if params[:issue_tag_ids].blank? diff --git a/app/models/journal.rb b/app/models/journal.rb index a1834ae2..5bf05b0d 100644 --- a/app/models/journal.rb +++ b/app/models/journal.rb @@ -6,7 +6,7 @@ # journalized_id :integer default("0"), not null # journalized_type :string(30) default(""), not null # user_id :integer default("0"), not null -# notes :text(65535) +# notes :text(4294967295) # created_on :datetime not null # private_notes :boolean default("0"), not null # parent_id :integer diff --git a/app/models/pull_request.rb b/app/models/pull_request.rb index 7338a1d7..e36af832 100644 --- a/app/models/pull_request.rb +++ b/app/models/pull_request.rb @@ -3,8 +3,8 @@ # Table name: pull_requests # # id :integer not null, primary key -# pull_request_id :integer -# gpid :integer +# gitea_id :integer +# gitea_number :integer # user_id :integer # created_at :datetime not null # updated_at :datetime not null @@ -12,7 +12,7 @@ # project_id :integer # title :string(255) # milestone :integer -# body :text(65535) +# body :text(4294967295) # head :string(255) # base :string(255) # issue_id :integer diff --git a/db/migrate/20220506083813_change_issues_description_and_journals_notes_column.rb b/db/migrate/20220506083813_change_issues_description_and_journals_notes_column.rb new file mode 100644 index 00000000..a8b934c7 --- /dev/null +++ b/db/migrate/20220506083813_change_issues_description_and_journals_notes_column.rb @@ -0,0 +1,7 @@ +class ChangeIssuesDescriptionAndJournalsNotesColumn < ActiveRecord::Migration[5.2] + def change + change_column :issues, :description, :text, :limit => 4294967295 + change_column :journals, :notes, :text, :limit => 4294967295 + change_column :pull_requests, :body, :text, :limit => 4294967295 + end +end From a6cee63d1780d353b16db4643c6c334d2942f284 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sat, 7 May 2022 11:57:58 +0800 Subject: [PATCH 64/65] fix: change owner must fix foreign_key --- app/controllers/projects_controller.rb | 2 +- app/models/fork_user.rb | 2 +- app/views/projects/fork_users.json.jbuilder | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index c4e440af..8bc2fb47 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -209,7 +209,7 @@ class ProjectsController < ApplicationController end def fork_users - fork_users = @project.fork_users.includes(:user, :project, :fork_project).order("fork_users.created_at desc").distinct + fork_users = @project.fork_users.includes(:owner, :project, :fork_project).order("fork_users.created_at desc").distinct @forks_count = fork_users.size @fork_users = paginate(fork_users) end diff --git a/app/models/fork_user.rb b/app/models/fork_user.rb index 4177392e..2d74af4a 100644 --- a/app/models/fork_user.rb +++ b/app/models/fork_user.rb @@ -17,7 +17,7 @@ class ForkUser < ApplicationRecord belongs_to :project - belongs_to :owner + belongs_to :owner, class_name: 'Owner', foreign_key: :user_id belongs_to :fork_project, class_name: 'Project', foreign_key: :fork_project_id after_create :incre_project_common, :incre_user_statistic, :incre_platform_statistic diff --git a/app/views/projects/fork_users.json.jbuilder b/app/views/projects/fork_users.json.jbuilder index f5147e19..730576c1 100644 --- a/app/views/projects/fork_users.json.jbuilder +++ b/app/views/projects/fork_users.json.jbuilder @@ -1,7 +1,7 @@ json.count @forks_count json.users do json.array! @fork_users.each do |f| - user = f.user.present? ? f.user : Organization.find_by(id: f.user_id) + user = f.owner.present? ? f.owner : Organization.find_by(id: f.user_id) json.id f.fork_project.id json.identifier f.fork_project.identifier json.name "#{user.try(:show_real_name)}/#{f.fork_project.try(:name)}" From 50dc5cce5dd0dd5e0a4588bd148c15e35af9a412 Mon Sep 17 00:00:00 2001 From: yystopf Date: Sat, 7 May 2022 14:06:48 +0800 Subject: [PATCH 65/65] fix --- app/controllers/issues_controller.rb | 4 ++-- app/controllers/journals_controller.rb | 4 ++-- app/controllers/pull_requests_controller.rb | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/controllers/issues_controller.rb b/app/controllers/issues_controller.rb index ee0b5eff..ddb0facd 100644 --- a/app/controllers/issues_controller.rb +++ b/app/controllers/issues_controller.rb @@ -109,7 +109,7 @@ class IssuesController < ApplicationController def create issue_params = issue_send_params(params) - Issues::CreateForm.new({subject: issue_params[:subject], description: issue_params[:description].b}).validate! + 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) if @issue.save! SendTemplateMessageJob.perform_later('IssueAssigned', current_user.id, @issue&.id) if Site.has_notice_menu? @@ -223,7 +223,7 @@ class IssuesController < ApplicationController normal_status(-1, "不允许修改为关闭状态") else issue_params = issue_send_params(params).except(:issue_classify, :author_id, :project_id) - Issues::UpdateForm.new({subject: issue_params[:subject], description: issue_params[:description].b}).validate! + Issues::UpdateForm.new({subject: issue_params[:subject], description: issue_params[:description].blank? ? issue_params[:description] : issue_params[:description].b}).validate! if @issue.update_attributes(issue_params) if @issue&.pull_request.present? SendTemplateMessageJob.perform_later('PullRequestChanged', current_user.id, @issue&.pull_request&.id, @issue.previous_changes.slice(:assigned_to_id, :priority_id, :fixed_version_id, :issue_tags_value)) if Site.has_notice_menu? diff --git a/app/controllers/journals_controller.rb b/app/controllers/journals_controller.rb index 7c067659..6dc1e29c 100644 --- a/app/controllers/journals_controller.rb +++ b/app/controllers/journals_controller.rb @@ -23,7 +23,7 @@ class JournalsController < ApplicationController normal_status(-1, "评论内容不能为空") else ActiveRecord::Base.transaction do - Journals::CreateForm.new({notes: notes.to_s.strip.b}).validate! + Journals::CreateForm.new({notes: notes.to_s.strip.blank? ? notes.to_s.strip : notes.to_s.strip.b}).validate! journal_params = { journalized_id: @issue.id , journalized_type: "Issue", @@ -75,7 +75,7 @@ class JournalsController < ApplicationController def update content = params[:content] if content.present? - Journals::UpdateForm.new({notes: notes.to_s.strip.b}).validate! + Journals::UpdateForm.new({notes: notes.to_s.strip.blank? ? notes.to_s.strip : notes.to_s.strip.b}).validate! if @journal.update_attribute(:notes, content) normal_status(0, "更新成功") else diff --git a/app/controllers/pull_requests_controller.rb b/app/controllers/pull_requests_controller.rb index bf5646a4..f45d1f35 100644 --- a/app/controllers/pull_requests_controller.rb +++ b/app/controllers/pull_requests_controller.rb @@ -58,7 +58,7 @@ class PullRequestsController < ApplicationController def create # return normal_status(-1, "您不是目标分支开发者,没有权限,请联系目标分支作者.") unless @project.operator?(current_user) ActiveRecord::Base.transaction do - Issues::CreateForm.new({subject: params[:title], description: params[:body].b}).validate! + Issues::CreateForm.new({subject: params[:title], description: params[:body].blank? ? params[:body] : params[:body].b}).validate! @pull_request, @gitea_pull_request = PullRequests::CreateService.call(current_user, @owner, @project, params) if @gitea_pull_request[:status] == :success @pull_request.bind_gitea_pull_request!(@gitea_pull_request[:body]["number"], @gitea_pull_request[:body]["id"]) @@ -90,7 +90,7 @@ class PullRequestsController < ApplicationController else ActiveRecord::Base.transaction do begin - Issues::UpdateForm.new({subject: params[:title], description: params[:body].b}).validate! + Issues::UpdateForm.new({subject: params[:title], description: params[:body].blank? ? params[:body] : params[:body].b}).validate! merge_params @issue&.issue_tags_relates&.destroy_all if params[:issue_tag_ids].blank?